Loading Box2D b2World from .Dump() file - c++

I am trying to save and load the state of b2World in order to resume a simulation at a later time, but with the states of the Collision Manager, etc being exactly maintained. What is the best way to do this (without getting into library internals, and having to use boost serialize while monitoring public/private members of every class)? Is there a way to repurpose the log file from b2World.dump function to construct the object again?

I think parsing Dump as-is is a dead end.
First, the output of Dump seems to be executable C++ code:
b2ChainShape chainShape;
b2Vec2 vertices[] = {b2Vec2(-5,0), b2Vec2(5,0), b2Vec2(5,5), b2Vec2(4,1), b2Vec2(-4,1), b2Vec2(-5,5)};
chainShape.CreateLoop(vertices, 6);
b2FixtureDef groundFixtureDef;
groundFixtureDef.density = 0;
groundFixtureDef.shape = &chainShape;
Secondly, there is the problem of dumping floating point values with enough precision to recreate the original object.
Finally, some objects don't seem to support Dumping at all.
Some alternatives:
Hack box2d and add your own state-preserving dumping mechanism
Keep all box2d objects in a specific memory area and use memory snapshotting and/or checkpointing techniques to restore that memory again on load. One such library I know of is Ken, but I'm sure there are other implementations.

Related

How to exchange custom data between Ops in Nuke?

This questions is addressed to developers using C++ and the NDK of Nuke.
Context: Assume a custom Op which implements the interfaces of DD::Image::NoIop and
DD::Image::Executable. The node iterates of a range of frames extracting information at
each frame, which is stored in a custom data structure. An custom knob, which is a member
variable of the above Op (but invisible in the UI), handles the loading and saving
(serialization) of the data structure.
Now I want to exchange that data structure between Ops.
So far I have come up with the following ideas:
Expression linking
Knobs can share information (matrices, etc.) using expression linking.
Can this feature be exploited for custom data as well?
Serialization to image data
The custom data would be serialized and written into a (new) channel. A
node further down the processing tree could grab that and de-serialize
again. Of course, the channel must not be altered between serialization
and de-serialization or else ... this is a hack, I know, but, hey, any port
in a storm!
GeoOp + renderer
In cases where the custom data is purely point-based (which, unfortunately,
it isn't in my case), I could turn the above node into a 3D node and pass
point data to other 3D nodes. At some point a render node would be required
to come back to 2D.
I am going into the correct direction with this? If not, what is a sensible
approach to make this data structure available to other nodes, which rely on the
information contained in it?
This question has been answered on the Nuke-dev mailing list:
If you know the actual class of your Op's input, it's possible to cast the
input to that class type and access it directly. A simple example could be
this snippet below:
//! #file DownstreamOp.cpp
#include "UpstreamOp.h" // The Op that contains your custom data.
// ...
UpstreamOp * upstreamOp = dynamic_cast< UpstreamOp * >( input( 0 ) );
if ( upstreamOp )
{
YourCustomData * data = yourOp->getData();
// ...
}
// ...
UPDATE
Update with reference to a question that I received via email:
I am trying to do this exact same thing, pass custom data from one Iop
plugin to another.
But these two plugins are defined in different dso/dll files.
How did you get this to work ?
Short answer:
Compile your Ops into a single shared object.
Long answer:
Say
UpstreamOp.cpp
DownstreamOp.cpp
define the depending Ops.
In a first attempt I compiled the first plugin using only UpstreamOp.cpp,
as usual. For the second plugin I compiled both DownstreamOp.cpp and
UpstreamOp.cpp into that plugin.
Strangely enough that worked (on Linux; didn't test Windows).
However, by overriding
bool Op::test_input( int input, Op * op ) const;
things will break. Creating and saving a Comp using the above plugins still
works. But loading that same Comp again breaks the connection in the node graph
between UpstreamOp and DownstreamOp and it is no longer possible to connect
them again.
My hypothesis is this: since both plugins contain symbols for UpstreamOp it
depends on the load order of the plugins if a node uses instances of UpstreamOp
from the first or from the second plugin. So, if UpstreamOp from the first plugin
is used then any dynamic_cast in Op::test_input() will fail and the two Op cannot
be connected anymore.
It is still surprising that Nuke would even bother to start at all with the above
configuration, since it can be rather picky about symbols from plugins, e.g if they
are missing.
Anyway, to get around this problem I did the following:
compile both Ops into a single shared object, e.g. myplugins.so, and
add TCL script or Python script (init.py/menu.py)which instructs Nuke how to load
the Ops correctly.
An example for a TCL scripts can be found in the dev guide and the instructions
for your menu.py could be something like this
menu = nuke.menu( 'Nodes' ).addMenu( 'my-plugins' )
menu.addCommand('UpstreamOp', lambda: nuke.createNode('UpstreamOp'))
menu.addCommand('DownstreamOp', lambda: nuke.createNode('DownstreamOp'))
nuke.load('myplugins')
So far, this works reliably for us (on Linux & Windows, haven't tested Mac).

How do you control a player character in Bullet Physics?

I am not sure how you are supposed to control a player character in Bullet. The methods that I read were to use the provided btKinematicCharacterController. I also saw methods that use btDynamicCharacterController from the demos. However, in the manual it is stated that kinematic controller has several outstanding issues. Is this still the preferred path? If so, are there any tutorials or documentations for this? All I found are snippets of code from the demo, and the usage of controllers with Ogre, which I do not use.
If this is not the path that should be tread, then someone point me to the correct solution. I am new to bullet and would like a straightforward, easy solution. What I currently have is hacked together bits of a btKinematicCharacterController.
This is the code I used to set up the controller:
playerShape = new btCapsuleShape(0.25, 1);
ghostObject= new btPairCachingGhostObject();
ghostObject->setWorldTransform(btTransform(btQuaternion(0,0,0,1),btVector3(0,20,0)));
physics.getWorld()->getPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());
ghostObject->setCollisionShape(playerShape);
ghostObject->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT);
controller = new btKinematicCharacterController(ghostObject,playerShape,0.5);
physics.getWorld()->addCollisionObject(ghostObject,btBroadphaseProxy::CharacterFilter, btBroadphaseProxy::StaticFilter|btBroadphaseProxy::DefaultFilter);
physics.getWorld()->addAction(controller);
This is the code I use to access the controller's position:
trans = controller->getGhostObject()->getWorldTransform();
camPosition.z = trans.getOrigin().z();
camPosition.y = trans.getOrigin().y()+0.5;
camPosition.x = trans.getOrigin().x();
The way I control it is through setWalkDirection() and jump() (if canJump() is true).
The issue right now is that the character spazzes out a little, then drops through the static floor. Clearly this is not intended. Is this due to the lack of a rigid body? How does one integrate that?
Actually, now it just falls as it should, but then slowly sinks through the floor.
I have moved this line to be right after the dynamic world is created
physics.getWorld()->getPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());
It is now this:
broadphase->getOverlappingPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());
I am also using a .bullet file imported from blender, if that is relevant.
The issue was with the bullet file, which has since been fixed(the collision boxes weren't working). However, I still experience jitteryness, unable to step up occasionally, instant step down from to high a height, and other issues.
My answer to this question here tells you what worked well for me and apparently also for the person who asked.
Avoid ground collision with Bullet
The character controller implementations in bullet are very "basic" unfortunately.
To get good character controller, you'll need to invest this much.

Retain cycle with CCAction and CCCallFunc/CCCallBlock

I'm in the final stages of releasing my first game, and after running Instruments:Leaks & Allocations, I see that I have a leak in my code caused by a retain cycle. I am using Cocos2d 2.0, and compiling my app with ARC, and I should mention that I started the project pre-ARC, and used the Xcode refactoring tool to convert it. My game has several animated objects per screen, each of which has a small number (1-7) of animated "variants" of that object (i.e. the barn opens to show a horse once and a zebra another time). I have a class that represents each animation, and another class for each variant. The variant creates a CCAnimation from a sequence of frames, and then creates an action which will be run whenever a touch event is received in the correct region. This action is what is causing my retain cycle. My declaration for the action ivar looks like this:
#interface AnimationVariant : NSObject
{
#private
CCAction* _action;
...
}
#property (readonly, nonatomic) CCAction* action;
...
-(void) setupActionWithMask:(int)mask
cycles:(int)cycles
hasScale:(bool)hasScale
scale:(float)scale
masterScale:(float)master_scale
animationFrames:(NSArray*) frames
duration:(float)duration
andBlock:(VoidBlock)block;
#end
In the implementation of the setupActionWithMask method, I build up an NSMutableArray of CCActions, actionList. The sequence of CCActions varies depending on args, but usually it looks something like this:
[actionList addObject:[CCScaleTo actionWithDuration:0.0f scale:scale]];
[actionList addObject: [CCAnimate actionWithAnimation:animation] ];
[actionList addObject:[CCScaleTo actionWithDuration:0.0f scale:master_scale]];
[actionList addObject: [CCCallBlock actionWithBlock:block]];
And I create the action like this:
_action = [CCSequence actionMutableArray:actionList];
The consuming class creates an AnimationVariant instance, sets its properties, calls setupActionWithMask, and passes in a block it wants executed when the action completes. When the consuming class wants to play the animation variant, it does so like this:
[self runAction: variant.action];
I tried declaring _action as:
CCAction* __unsafe_unretained _action;
which of course broke the retain cycle, but the action is destroyed, and is no longer around when it's needed (which is what you would expect, since __unsafe_unretained does not retain). I know __weak is the recommended solution, but as I am targeting iOS 4 and up, I don't think it's available to me.
I had another retain cycle in my code, exactly like this one, also caused by retaining (automatically with ARC of course) a CCSequence containing a CCCallFunc/CCCallBlock. I solved that one by just re-creating it whenever I needed it, which I could also do in this case, but these animations are triggered maybe a couple hundred times in the whole game, so I was hoping to follow the recommended Cocos2d Best Practices and retain the actions.
Thanks!
Retaining actions is not best practice. It's not even good practice. Though it comes heavily recommended by many, quite unfortunately.
Retaining actions works in many cases, but fails in others causing objects to leak. I'm guessing your case may be one of those.
Since you're targeting iOS 4 you can't use weak references. But you should probably reconsider unless you have to target the remaining few 1st and 2nd generation devices. Otherwise, google for iOS 5 adoption rate. The handful of devices that haven't been updated yet are well below a reasonable threshold, in particular if you consider that those users probably don't buy (many) apps (anymore) anyway.
Since you meantioned CCCallFunc, make sure you don't use them and replace with CCCallBlock. CCCallFunc are not safe to use with ARC, in particular whenever you have to __bridge_transfer cast a data object to void* (also bad practice).
There's always the chance that the necessary bridge cast back to the original object never occurs, and then ARC doesn't get the chance to clean up that object. With CCCallFunc this can happen when you run a call func action but the action is stopped before the callback selector is called, for example by changing scenes or stopping the action/sequence.
Cocos2D is also prone to retain cycles if you don't follow this rule:
any node should only retain another node that is one of its children or grandchildren
In all other cases (ie node retains (grand)parent or sibling node) you must make sure to nil those references in the -(void) cleanup method. Doing so in -(void) dealloc is too late because the object will never get to dealloc when there's a retain cycle.

How to dynamically build a new protobuf from a set of already defined descriptors?

At my server, we receive Self Described Messages (as defined here... which btw wasn't all that easy as there aren't any 'good' examples of this in c++).
At this point I am having no issue creating messages from these self-described ones. I can take the FileDescriptorSet, go through each FileDescriptorProto, adding each to a DescriptorPool (using BuildFile, which also gives me every defined FileDescriptor).
From here I can create any of the messages which were defined in the FileDescriptorSet with a DynamicMessageFactory instanced with the DP and calling GetPrototype (which is very easy to do as our SelfDescribedMessage required the messages full_name() and thus we can call the FindMessageTypeByName method of the DP, giving us the properly encoded Message Prototype).
The question is how can I take each already defined Descriptor or message and dynamically BUILD a 'master' message that contains all of the defined messages as nested messages. This would primarily be used for saving the current state of the messages. Currently we're handling this by just instancing a type of each message in the server(to keep a central state across different programs). But when we want to 'save off' the current state, we're forced to stream them to disk as defined here. They're streamed one message at a time (with a size prefix). We'd like to have ONE message (one to rule them all) instead of the steady stream of separate messages. This can be used for other things once it is worked out (network based shared state with optimized and easy serialization)
Since we already have the cross-linked and defined Descriptors, one would think there would be an easy way to build 'new' messages from those already defined ones. So far the solution has alluded us. We've tried creating our own DescriptorProto and adding new fields of the type from our already defined Descriptors but got lost (haven't deep dived into this one yet). We've also looked at possibly adding them as extensions (unknown at this time how to do so). Do we need to create our own DescriptorDatabase (also unknown at this time how to do so)?
Any insights?
Linked example source on BitBucket.
Hopefully this explanation will help.
I am attempting to dynamically build a Message from a set of already defined Messages. The set of already defined messages are created by using the "self-described" method explained(briefly) in the official c++ protobuf tutorial (i.e. these messages not available in compiled form). This newly defined message will need to be created at runtime.
Have tried using the straight Descriptors for each message and attempted to build a FileDescriptorProto. Have tried looking at the DatabaseDescriptor methods. Both with no luck. Currently attempting to add these defined messages as an extension to another message (even tho at compile time those defined messages, and their 'descriptor-set' were not classified as extending anything) which is where the example code starts.
you need a protobuf::DynamicMessageFactory:
{
using namespace google;
protobuf::DynamicMessageFactory dmf;
protobuf::Message* actual_msg = dmf.GetPrototype(some_desc)->New();
const protobuf::Reflection* refl = actual_msg->GetReflection();
const protobuf::FieldDescriptor* fd = trip_desc->FindFieldByName("someField");
refl->SetString(actual_msg, fd, "whee");
...
cout << actual_msg->DebugString() << endl;
}
I was able to solve this problem by dynamically creating a .proto file and loading it with an Importer.
The only requirement is for each client to either send across its proto file (only needed at init... not during full execution). The server then saves each proto file to a temp directory. An alternative if possible is to just point the server to a central location that holds all of the needed proto files.
This was done by first using a DiskSourceTree to map actual path locations to in program virtual ones. Then building the .proto file to import every proto file that was sent across AND define an optional field in a 'master message'.
After the master.proto has been saved to disk, i Import it with the Importer. Now using the Importers DescriptorPool and a DynamicMessageFactory, I'm able to reliably generate the whole message under one message. I will be putting an example of what I am describing up later on tonight or tomorrow.
If anyone has any suggestions on how to make this process better or how to do it different, please say so.
I will be leaving this question unanswered up until the bounty is about to expire just in case someone else has a better solution.
What about serializing all the messages into strings, and making the master message a sequence of (byte) strings, a la
message MessageSet
{
required FileDescriptorSet proto_files = 1;
repeated bytes serialized_sub_message = 2;
}

Does IASetInputLayout check to see if you pass an already set input layout?

I am designing a game engine in DirectX 11 and I had a question about the ID3D11DeviceContext::IASetInputLayout function. From what i can find in the documentation there is no mention of what the function will do if you set an input layout to the device that has been previously set. In context, if i were to do the following:
//this assumes dc is a valid ID3D11DeviceContex interface and that
//ia is a valid ID3D11InputLayout interface.
dc->IASetInputLayout(&ia);
//other program lines: drawing, setting vertex shaders/pixel shaders, etc.
dc->IASetInputLayout(&ia);
//continue execution
would this incur a performance penalty through device state switching, or would the runtime recognize the input layout as being equivalent to the one already set and return?
While I also can not find anything related to if the InputLayout is already set, you could get a pointer to the input layout already bound by calling ID3D11DeviceContext::IAGetInputLayout or by doing an internal check by keeping your own reference, that way you do not have a call to your ID3D11DeviceContext object.
As far as I know, it should detect that there are no changes and so the call is to be ignored. But it can be easily tested - just call this method 10000 times each render and see how bad FPS drop is :)