How to get the Object3D from convenience functions (extrusion, tube, sphere) in ThreeBox - threebox

The documentation says: "Threebox offers convenience functions to construct meshes of various Three.js meshes, as well as 3D models. Under the hood, they invoke a subclass of THREE.Object3D". Ex: extrusion, tube, sphere
Once those threeboxObjects have been created is possible to get the resulting THREE.Object3D ?
The code below returns false, so the returned extrusion doesn't seem to inherit from Object3D
obj = tb.extrusion(options);
if (!(obj instanceof THREE.Object3D)) return false;
I actually would like to get the Object3D Geometry to call the function EdgesGeometry after calling 'tb.extrusion'.
Any help much appreciated.

Related

how to convert std::vector<float> to a tensor without copy in tensorflow in c++?

In c++, a multidimensional matrix is stored in std::vector<float>. I need to use it in tensorflow, which uses tensors. The conversion from a std::vector to a tensor seems not obvious. There is a c_api which convert a vector to a TF_Tensor instead of Tensor. std::copy also works, but I want to perform a conversion without copy.
Tensorflow now has a way to do this in the C++ API by providing your own tensorflow::TensorBuffer and using the following constructor:
#include <tensorflow/core/framework/tensor.h>
#include <tensorflow/core/framework/types.pb.h>
...
tensorflow::Tensor(tensorflow::DataType type, const TensorShape & shape, TensorBuffer *buf)
Since tensorflow::TensorBuffer is an abstract class, you'll need to subclass it and implement a few methods yourself (that said, it's fairly easy to do). One thing to note: notice how we have OwnsMemory() returning false. If you want to use manual memory management (malloc/free or new/delete), you can set this to true and then override the destructor yourself. That said, since you're using a vector I'd just set it to false and take care to not have the buffer go out of scope. When it does, vector will free its own internal memory anyways.
eg;
class MyBuffer: public tensorflow::TensorBuffer {
std::size_t len_;
public:
MyBuffer(void* data, std::size_t len): len_(len), tensorflow::TensorBuffer(data){}
//returns how many bytes we have in our buffer
std::size_t size() const override {return len_;};
//needed so TF knows this isn't a child of some other buffer
TensorBuffer* root_buffer() override { return this; }
// Not actually sure why we need this, but it lets TF know where the memory for this tensor came from
void FillAllocationDescription(tensorflow::AllocationDescription* proto) const override{};
// A value of false indicates this TensorBuffer does not own the underlying data
bool OwnsMemory() const override { return false; }
}
Then, you just need to provide the correct tensorflow::DataType (eg; tensorflow::DT_FLOAT32) and a tensorflow::TensorShape (you can just instantiate it and add each dimension using <TensorShape>.addDim(<the dimension>). You could modify the above by storing the std::vector inside and then exposing the contents by using .data() and a void* cast to make a constructor for MyBuffer that takes in a vector. Or you could just do that yourself outside of MyBuffer.

Passing pointer/reference to object

I'm writting a simple game where I've Player object and Enemy object. I want Enemy to pursue Player but I've no idea what is the right way of passing current Player's position to Enemy.
Natively I'm a C++ dev so I was naturally thinking of passing Player (probably as an interface) to Enemy but I cannot find any clue about such approach in QML.
How should I do it then?
Well, the best way would be using property bindings like hyde has already pointed out.
// Enemy.qml
Item {
property int targetX
property int targetY
// more code
}
// Player.qml
Item {
property int currentPosX
property int currentPosY
}
// Main.qml
Enemy {
id: enemy
targetX: player.currentPosX
targetY: player.currentPosY
}
Player {
id: player
// Some calculation for the current x and y position
}
Another approach would be to pass the Player component to the Enemy component. But than you have a little bit coupling. This is maybe the C++ thinking you have pointed out.
// Enemy.qml
Item {
id: enemy
property Item myPlayer
Component.onCompleted: {
console.log(enemy.myPlayer.currentPosX +
" | " +
enemy.myPlayer.currentPosY)
}
}
// Player.qml
Item {
property int currentPosX
property int currentPosY
}
// Main.qml
Enemy {
id: enemy
myPlayer: player
}
Player {
id: player
// Some calculation for the current x and y position
}
Ad mentioned here:
JavaScript expressions allow QML code to contain application logic.
Moreover:
QML offers a highly readable, declarative, JSON-like syntax with support for imperative JavaScript expressions combined with dynamic property bindings.
Because of that, you have not the notion of pointer in the QML environment, unless you push your logic under the hood, writing it in C++.
Anyway, almost everything in JavaScript is passed by reference (that's an acceptable simplification valid for your case, there are also some exceptions like primitive values and immutable objects).
Because of that, you can simply let your instance of A refers to an instance of B, either by passing it in the constructor or setting it by means of a setter or whatever (there is a plenty of alternative solutions indeed).
Keep in mind that there is no explicit support for interfaces neither in JavaScript nor in QML, so you cannot rely on them, even if you can simulate them (it isn't worth it from my point if view).
How to solve your specific problem?
Well, it depends on your actual code and software architecture, so I cannot say that, I'm sorry. I hope one of the hints above is of any help for you.

Chain up to 'Gtk.Box.new' not supported

I'm new to Vala and so far I think it's pretty cool but I'm having trouble understanding inheritance. I read here that I should use base() to call the parents constructor. Alright, cool, seems understandable but It din't work for me. I kept getting the error on the title. Here is my snippet to show:
public class MyBox : Gtk.Box {
public MyBox(Gtk.Orientation orientation, int spacing) {
// I have to this
this.set_orientation(orientation);
this.set_spacing(spacing);
// I want to do this:
base(orientation, spacing);
//workaround is this:
Object(orientation: orientation, spacing: spacing);
}
}
Please help me understand why Object(....) works but not base(...)
Shouldn't it be the same thing?
This is due to implementation of the C code. When Vala generates a constructor, it generates two C functions a _new function that allocates memory and calls the _construct and a _construct function that initialises the object. When you case the base constructor using base(), it needs a matching _construct function to call. Not all the classes written in C have this; in the VAPI file, you will find has_construct_function = false for some constructors. If this is the case, no chain-up can be done. The base GObject can set properties from arguments, so this becomes the only way to set defaults in the base class.

mimicking MVC DisplayExtensions methods (fun and confusion with lambdas)

I'm trying to develop my own editable data grid for MVC in a fluent interface usable in a View. My question is really about using lambdas, not about data grids, but the context might help for understanding my question. Anyway, I have some code that looks like this:
#model IEnumerable<AdamOneilSoftware.Models.Something>
#{
var firstItem = Model.FirstOrDefault();
}
#(Html.DataGrid(Model)
.CssClass("data")
.TextBox(model => firstItem.Text)
.TextBox(model => firstItem.Position)
.Render())
This much compiles okay. You can see that I want to use lambdas to setting up columns of my data grid. The thing I don't understand is how to do anything with those lambdas in my data grid class. I have surmised that I need to compile/invoke the expression, but I'm stuck on the Invoke part. Here's what I have:
public DataGridBuilder<TModel> TextBox<TValue>(Expression<Func<TModel, TValue>> expression)
{
var del = expression.Compile();
// invoke the delegate?
var result = del.Invoke(); // but this expects a TModel argument
return this;
}
The Invoke call expects a TModel argument (according to the Func declaration -- I understand that). But this doesn't work--and rightly so:
var result = del.Invoke(TModel);
How do I form the TModel argument in the Invoke call? Or am I heading the wrong direction completely? The goal is to do something like what the DisplayFor and EditorFor methods do--render some HTML with some awareness of the target property's metadata (DataFormatString, Display label, and so on).
You need to get the view's Model instance to pass as the parameter.
You can find that in Html.ViewData.Model.

Reducing the number of arguments to a constructor

I am reading "Clean Code" and having trouble figuring out how to keep some of my functions (usually constructors) to their MAXIMUM of 3 parameters.
Often my objects need an awful lot of information to work - am I supposed to make a small constructor and then use mutator functions to give them all of the information? This doesn't seem any better than just using a big constructor.
As an example, I have a "MovablePatch" class. It lets the user drag a square around in a window. It needs a several parameters, including Radius, Color, Renderer, InitialPosition, and Visibility. Currently I collect all of these from my GUI and then call:
MovablePatch(int radius, Renderer* renderer, Color color, Position initial, bool visibility)
These are only some of the things that I need in this class. Can anyone suggest how else I might package this information to pass to the constructor? I don't see any obvious "break it into smaller classes" appearing here.
You could have
MovablePatch(Renderer* renderer, CircleAppearance circleAppearance)
where CircleAppearance gathers the other info.
However, clean code and other books that generalize about what good code should look like, are aiming for 80 percent of the code out there. Your code seems to be "closer to the metal" than the typical LoB (Line of Business) variety. As such, you may run into places where certain coding ideals are not applicable.
The most important part is that you're thinking about it and trying to keep things nice and tidy! :)
Do not take maxims like "thou shalt not have more than 3 parameters in thy constructors" at face value. If you have the slightest chance of making an object immutable, make it; and if it being immutable means that it is going to have a constructor with 50 parameters, so be it; go for it; don't even think about it twice.
Even if the object is going to be mutable, still, you should pass its constructor as many parameters as necessary so that immediately upon construction it will be in a valid and meaningful state. In my book, it is absolutely impermissible to have to know which are the magic mutator methods that have to be called (sometimes even in the right order) before any other methods can be invoked, under penalty of segfault.
That having been said, if you would really like to reduce the number of parameters to a constructor, or to any function, simply pass this method an interface that it can invoke to get from it the stuff it needs in order to work.
Some of the things you are passing in could be abstracted into a larger construct. For example, visibility, color, and radius, could make sense to be placed into an object that you define. Then, an instance of this class, call it ColoredCircle, could be passed into the constructor of MovablePatch. A ColoredCircle doesn't care where it is or what renderer it is using, but a MovablePatch does.
My main point, is that from an OO perspective, radius isn't really an integer, it's a radius. You want to avoid these long constructor lists because it is daunting to understand the context of these things. If you collect them into a larger class, kind of like how you already have with Color and Position, you can have fewer parameters passed in and make it easier to understand.
The Named Parameter Idiom is useful here. In your case, you might have
class PatchBuilder
{
public:
PatchBuilder() { }
PatchBuilder& radius(int r) { _radius = r; return *this; }
PatchBuilder& renderer(Renderer* r) { _renderer = r; return *this; }
PatchBuilder& color(const Color& c) { _color = c; return *this; }
PatchBuilder& initial(const Position& p) { _position = p; return *this; }
PatchBuilder& visibility(bool v) { _visibility = v; return *this; }
private:
friend class MovablePatch;
int _radius;
Renderer* _renderer;
Color _color;
Position _position;
bool _visibility;
};
class MovablePatch
{
public:
MovablePatch( const PatchBuilder& b ) :
_radius( b._radius );
_renderer( b._renderer );
_color( b._color );
_position( b._position );
_visibility( b._visibility );
{
}
private:
int _radius;
Renderer* _renderer;
Color _color;
Position _position;
bool _visibility;
};
then you use it like so
int
main()
{
MovablePatch foo = PatchBuilder().
radius( 1.3 ).
renderer( asdf ).
color( asdf ).
position( asdf ).
visibility( true )
;
}
overly simplified, but I think it gets the point across. If certain parameters are required they can be included in the PatchBuilder constructor:
class PatchBuilder
{
public:
PatchBuilder(const Foo& required) : _foo(required) { }
...
};
Obviously this pattern degenerates into the original problem if all arguments are required, in which case the named parameter idiom isn't applicable. The point being, this isn't a one size fits all solution, and as Adam describes in the comment below there are additional costs and some overhead with doing so.
One good option is to use a Builder pattern, where each "setter" method returns the own instance, and you can chain the methods as you need.
In your case, you will get a new MovablePatchBuilder class.
The approach is very useful and you can find it in many different frameworks and languages.
Refer here to see some examples.