serializing world state

I've seen a few threads about this topic already, but no one seems to have really nailed serialization yet. I'm trying to serialize my scenes for demo playback in my game. I really just want a sort of arcade "attract mode" playing back gameplay on the main menu so total fidelity isn't really necessary.

First off, I just record the initial state of the world, and then the user input each frame. To get the state of the world, I save the velocity and position (linear and angular) for all of my bodies. I also save whatever unique properties each entity instance has, health, etc. When I want to reload that state, I spawn each type of entity like normal, then write the velocities and positions directly back to the newly spawned bodies that comprise these newly spawned entities.

Also, some of these entities have 2 bodies connected by a revolute joint. If I set these bodies up the same with every spawning, and then when I serialize them, I save GetJointSpeed and m_referenceAngle (then setting SetMotorSpeed() and m_referenceAngle back when reloading) along with all the body positions and velocities, then shouldn't I have the same entity state when I reload them? Is there something I'm missing here?

Furthermore, when I start to record, I first save the current state, then immediately reload it. The state load destroys all active entity bodies before loading a new state. I would assume this would mean that upon the start of the recording of the demo and the start of any future playback of this demo, I should have the same initial state. I've also turned off warm starting.

This works to a degree, but something is still different between state loads, as whenever I try to play back the demo player input will eventually get out of sync with what's going on in the world. Is there something else about the world that I'm not maintaining between state loads?
Honestly, sounds like you are going to a huge amount of trouble for what amounts to an animation... Why aren't you just saving the transform matrix for each object at x frame intervals, and then interpolating between those values?
You'd get a completely deterministic approach and be guaranteed it would work across all achitectures. The other way you won't be at all... for one thing floating point numbers are an approximation and are not guaranteed to be the same across different architectures.
Sure, but that way I'd no longer be using the collision in box2d, which is the thing that is controlling basically ever entity interaction (bullet, ship-to-ship collision) and all the accompanying effects (sparks, explosions) in the game. I would then have to record all game events like entity spawn/removal, sound playback, particle effects, etc. which is doable I suppose, but it seems like a lot of work to me. Not to mention space. As it is now after the initial state, each successive frame costs 1 uint and 2 floats of player input to fully describe, so demos of 1-2min usually take about 20kb at 30fps. Which is important because I intend to include several in the game, showing off different levels. Would but if it worked right:P. Still, its so close it just seems like I'm missing something small.

I am aware of the floating point rounding differences across architectures but I really don't think it will affect 15-20 sec gameplay demos considerably. Again, it's just main-menu eyecandy, but I do want it to resemble actual gameplay.
I'm having a similar problem as you. I thought it would be too much work to save the coordinates in very frame or so, especially considering I want to have explosions, and I would like to be able to create the exploded bodies dynamically.
I noticed that if I set the angle in SetXForm() to, say, .93..., and when I read back the angle using GetAngle(), I would get 0.95..., which was more than a degree off. If I changed the angle I passed to SetXForm() to something less than .93..., I would get closer to the desired angle. I wrote a function for this here. I may be doing something that may not end up working at the end, but I am getting closer and closer to the original simulation.

When you say that this may not work across different CPUs, does this mean it may not work across different Intel CPUs?
What I don't understand is that I can't even reload everything just before recording, as I would do during playback, and expect things to be the same. What I did was when I tried to record a demo, I first stopped everything and saved the state of the world (just bodies' positions and orientations*), destroyed the world and recreated it from the saved state (in the exact same matter and in the same order as I would later do before playback), and then simply recorded input from then on. I would have thought the simulation would run the same later. After all each time I started from the same world state (theoretically) and just fed in the same set of input. But for whatever reason it still didn't play back deterministically. I understand there is an issue with contacts having a certain order, but again I completely destroyed and recreated the world before recording in the same fashion, and in the same order, as I would just before playback so I would think whatever resulting contact negotiations would be the same using the same input, realtime or played back.

I'd all but given up on this really. And now you're saying SetXForm isn't even accurate most of the time? I'm kind of surprised that in the few instances serialization is talked about on the forums there still really isn't any practical solution. Keyframing animation is not only wasteful but it defeats the purpose of building the core application on a physics engine. Most of the object creation in my game is based on contacts found by box2D. Why record all of that interaction instead of simply storing the player's input each frame.

AFAIK, the software itself is deterministic in design so the problem really comes down to somehow recording a reliable initial game state. Why is this so difficult? I certainly appreciate the blackbox nature of having a robust physics engine underlying my game, but in this one particular instance it's kind of a bummer we can't peek inside and make a simple photocopy of the innards.

* I know its said to store the body defs explicitly for any later object recreation, but if I just store the information that is unique to my entity and upon playback recreate said entity through the same function with the same parameters as I did when originally spawning the entity during recording then I would think I'd get the same bodies in the simulation.
Oh and as for your question of different Intel architectures I'm sure there are others who could say better than I but as I understand it, if Intel's different CPUs handle floating point operations with varying degrees of precision, you'll get differences in simulation results.
I don't understand the SetXForm thing - it should be perfectly accurate.

Box2D is deterministic. That means if you start from the same point, you will frequently (depending on platform), get the same results. But starting from the same point is not the same as saving and loading from a point midway through the simulation. Warmstarting and order of contact creation can easily foil you.
Boris, it isn't. If use SetXForm() to set the position/angle of a body, and then read it back, it is different from what you set. My "continuous adjustment" approach isn't deterministic, either: sometimes the simulation is close, sometimes it's way off. I've come to conclusion that you have to save the positions and angles of your sprites each frame for playback.
Well I'll be damned. I was about to reply with how I completely destroy and recreate the physics world, and how I didn't understand how doing so wouldn't leave me with exactly the same initial state every time. But then I realized that I wasn't physically destroying the world, just removing bodies and then recreating those bodies. As I said I had all but given up on this over a month ago, but this little discussion got me interested in it again.

Anyway I did just that and it seems to work now. Let me explain my method. As I said the way I go about this is when I want to record I first grab the initial state of the world. All the things that are unique to the current game session (score, time, entities on-screen). I have a list of on-screen enemies that I go through and serialize unique parameters about like current health and firing rate, etc. As far as physics is concerned I just save the position/orientation and velocity/angular velocity of each body comprising the entity. When I recreate these entities later, my entity spawn routine will build their shape and other properties based on their signature, so I don't need to store that, but I suppose you could generalize it and just store body-defs.

The part that makes it work now is that after I've saved the initial world state, I recreate the physics world from scratch so now I know its completely empty aside from whatever initial conditions I have when I create the world in the first place. Then I reload all the content from the save state and from that point on I just record player input. Now whenever I play a demo back I do the same and destroy and recreate the world from scratch before loading the initial state. I also turn off warmstarting before any recording or playback.

It seems to me it should be unnecessary to recreate the physics world just for replays, but this is the only way I've gotten it to work reliably. And yes I'm just using SetXForm, SetLinearVelocity, and SetAngularVelocity on my bodies and it all seems accurate enough for a minute or two of fairly intense gameplay. Check it out: http://files.getdropbox.com/u/1099362/Blast.swf

Be warned, the above is still very early and frightfully unoptimized and will probably bring your browser to its knees until some of the enemies are destroyed and the bullets clear. For some reason its defaulting to full-window, so you might want to bump the quality down to low. But it's enough to see a demo I recorded of the game in action that plays in a loop like old arcade attract modes. This was all I really wanted the ability for anyway so I think even if this isn't totally accurate it's good enough, though I've watched it go several times and it sure seems to be doing the same thing each time.

If you're adventurous, you can start a game (arrows/WASD move, mouse shoots) and begin recording a demo with 'R,' stop with 'T' and play back your replay with 'Y.' You can even save your demo with 'U,' but why on earth would you want to do that at this stage? 😛 And of course, don't distribute this anywhere, its just a proof of concept that I'll leave up for a few days.
This is an old thread, but I thought I'd respond anyway - the issue with setting the transform and then re-reading it is that the rotation is stored internally in Box2D as sin and cos components. When you do the operation to convert the angle in radians into sin and cos components, then do the conversion back, you don't always get the exact same thing (due to floating point errors). You'd have to hack Box2D to let you set the components directly (look at b2Rot in b2Math.cpp).

That said, I can't get my stuff totally synchronized. It works great with simple objects, but with ragdolls I'm having issues and I can't figure out what's not getting synced...something to do with contacts or joints maybe. I haven't tried destroying the whole world yet, but that's a lot of work in my simulation.

Original thread: https://box2d.org/forum/viewtopic.php?t=3131