Custom Fluid simulation with Box2D rigid bodies

Hi,

I've not been around much to hassle people for the last few months because I've been working on other (non Box2D-specific) parts of my game, but you'll be pleased/annoyed to know that I'm back, and I could use some help getting fluids interacting with rigid bodies. There was a long thread about fluid physics (viewtopic.php?t=574) which resulted in me writing custom non-Box2D physics for fluids (the short version of the story is that Box2D is set up to deal with rigid bodies and as such just isn't sufficienty optimised to do lots of fluids - this is no criticism of Box2D, you use different tools for different jobs). However, I am still using Box2D to represent all of the static and dynamic rigid bodies in the world, so I need to find a way to get them to interact with the fluid nicely (things floating, getting swept away in floods, displacing fluid, etc). I've got a description of an algorithm from the paper I've been referring to to implement the fluids, but I'm not sure how to get it working in Box2D, which is where you nice people come in.

This is the paper: http://www.iro.umontreal.ca/labs/infogr ... S/pvfs.pdf

It's well worth a read, for those interested. What I'm trying to get working is section 6.1 of the paper - there's a diagram, a list of the equations, and an outline of the algorithm there which explains the method, and is what I'm trying to get working. There are a few parts where I'm not clear on how I should go about the implementation, and as a result of not knowing what I'm doing, the fluid either has no discernible effect on rigid bodies, or it causes them to spin around like crazy and go completely out of control. I'm also not sure how buoyancy is supposed to work, since the equations for the fluid particles do away with any concept of mass.

1 - The paper says that the particle velocity is calculated "using the difference between the current and previous particle positions". So, by subtracting the particle's position this frame from its position last frame. I'm not sure if it's quite that simple, though - my particles use Verlet integration, so velocity is calculated from the difference in positions between timesteps (rather than Euler, where newPos = oldPos + (velocity * dt)). I don't know whether to use this calculated velocity or just a simple subtraction, or if dt needs to play a part in that.

2 - The paper then says "We then compute the particle relative velocity v = vi - vp, where vp is the body velocity at the contact point". I'm using pBody->GetLinearVelocityFromWorldPoint() for that, but it's not clear to me whether the "contact point" means the world position of an intersecting particle, or the position on an edge of the body where the particle would have first collided with it, if the particles were using continuous physics. Again, I don't know if dt needs to be included in this relative velocity calculation.

3 - The paper then talks about seperating the relative velocity into normal and tangential components in order to compute an "impulse" and adding this "impulse" into force and torque buffers, which will be used to compute changes to the linear and angular velocity of the rigid body. This confuses the hell out of me. I struggle with understanding the difference between impulses and forces, but if we take the paper at face value as meaning an impulse, pBody->ApplyImpulse() doesn't touch the torque of an object, it directly affects the angular velocity (and results in uncontrollably spinning objects). So should I be ignoring the paper's terminology and calling pBody->ApplyForce() instead, because that updates the torque rather than the angular velocity directly? ApplyForce() seems to have very little impact on the bodies at all.

Sorry if this isn't entirely Box2D-specific. I just wanted to get an idea about how people might use Box2D in conjunction with an algorithm like this.
Apologies for the double-post. I've got another question. I'm still hoping someone could shed some light on the questions above, but in the absence of any better knowledge or guesses, I've decided that:

1 - Particle velocity should be calculated "on the fly" rather than taken from what was calculated in the Verlet integration from the previous step (because the particle will have already moved this frame since the velocty calculation at the end of the previous frame), but the calculation should involve terms for acceleration and dt rather than just be a simple subtraction.

2 - I'm assuming that the "contact point" is the point on the edge of the box where the particle would have first touched the box if there had been swept collision, rather than it's (non-swept) position inside the box.

3 - I'm assuming the paper is correct, and I should apply an impulse rather than a force, although to produce a result with anything like the right magnitude the impulse needs to be scaled by dt (so I suppose that's functionally the same as applying an unscaled force).

Again, please feel free to correct me if I seem wrong about any of this. Anyway, I've been looking more at the wider algorithm. My code goes something like this:

1 - Step the rigid bodies using Box2D
2 - Apply the fluid constraints to come up with potential new positions for the fluid particles
3 - Apply impulses from the fluid particles to the box
4 - Move the particles so they don't intersect with the box, and then integrate to these "final" positions

But the paper seems to be advocating something like this:
1 - Apply the fluid constraints to come up with potential new positions for the fluid particles (it's not actually stated when this happens in relation to the rigid body movement, but I presume it gets done first)
2 - Keep a copy of the rigid bodies' current positions, and do a "fake" step to find out where the new position would be without the fluid's involvement
3 - Calculate what impulses would be applied to this body in its "fake" position
4 - Step the body from its "actual" current position, having applied the impulses calculated in step 3
5 - Do another pass on the fluid to extract the particles from the body, and then integrate.

Can anyone tell me, in practical terms, if they would expect the outcome of the second approach to be noticeably different from the first (and if so, why)? I'm having trouble wrapping my head around it. If there is a difference, is Box2D able to handle such a simulation? Is it possible to "rewind" the physics back to a stored state from the start of a frame and "redo" it with the new forces? Or to provide some kind of functionality that could show what state a body would be in "if" it stepped given its current state without actually performing the step?
I cannot answer all your questions. You must work out some for yourself, or experiment for best results.

Verlet integration only works easily with fixed timesteps. Impulses and forces are basically equivalent then, they just differ by a constant scaling factor. Even without that, it doesn't seem unreasonable to me to talk about adding them - just assuming an implicit conversion. They seem to be using verlet to define the velocities, too, so I don't see any contradiction.

I'm not really sure, but it sounds like step-undo-step is a weaker solver than Box2D, which can be used directly instead. I think that scheme somehow creates position correction for verlet integration, but Box2D has a different method of position correction. Unless you've missed some step, I'd guess you can just read 2-4 as "solve rigid bodies".

IIRC Box2D's solver keeps track of total accumulated impulse, so it is completely possible to undo the changes made by the solver. (position, less so, but the position solver is independent). It takes advantage of this for a few things. But it would be best if you could interleave solving for fluids with solving bodies, much like joints are interleaved at the moment.
For what it's worth, I'm running at a fixed timestep at the moment anyway (1/60th of a second), which means that if the framerate drops, the physics runs slower - this is clearly a Bad Thing(tm) for a finished game, but it's helpful to me right now to eliminate problems like the one you mentioned.

My question about the different between the two solutions wasn't so much about whether the Box2D solver is sufficiently strong, more about whether both approaches would result in the same outcome overall. To perform a "fake" step, work out forces/impulses bases on the results of that fake step, and then to take those into consideration when performing the "real" step seems like it might be different to just performing the real step and having the forces be applied on the next frame rather than on this one. My intuition tells me that my current approach would effectively end up applying the forces/impulses from the fluid particles one frame later than the approach described in the paper (if I understand the differences correctly), and my question is about whether people feel like that one frame "lag" is likely to be significant (and, if it is, how to avoid it).
Hello again,

So, I haven't got very far with the whole step-compute force-revert-restep thing, so I've gone back to the drawing board to ascertain the exact cause of the problem with the spinning bodies, and added a whole bunch of debug rendering. It was quite difficult to capture a representative example of the problem, so bear with me if it looks a bit arcane to begin with. Any thoughts on this would be most useful.

Image

So, here's a crate in my fluid. The red circles are fluid particles in their positions after all the physics has been completed for the frame, although all of the forces shown here won't be applied to the crate until the physics step in the next frame. The green circles are particle contact points on the edges of the crate at the time the rigid body interaction was computed - it's not easy to see in the picture, but each green circle is connected by a yellow line to a red circle which represents where the particle has moved to after collision response and integration for the frame.

Blue lines are the linear velocity of the crate at the contact point. Cyan lines with circles on the end are the collision normals between particles and the crate, magenta lines represent the "normal" component of the impulse between a particle and a crate, white lines are the "tangential" component, and green lines are the resulting impulse forces and magnitudes to be applied to the crate. Some of the debug lines have been scaled by varying amounts to be able to see them properly, so don't read too much into the relative lengths of different-coloured lines.

With me so far? 😉 So, once you start looking at the image, it becomes clear that one of these things is not like the others. The particle on the far left has calculated an impulse which points "outwards", and would pull the bottom left corner down, causing the crate to spin anticlockwise, which is exactly what's happening. This seems to be the cause of my problem - particles at the corners of the box exterting forces in the wrong direction. It only happens intermittently, and generally only for a frame or two at a time, but it's enough to add energy to the box to make it continue rotating with increasing velocity (whereas if it pointed "inwards" it would counteract the velocity somewhat, which is what we want).

So, why is that impulse pointing the wrong way? Well, the impact normal seems okay, pointing out to the left, but the "normal" component of the relative velocity between the particle and the box is wrong, it's pointing outward whilst you can see that all the others point in. That normal component is calculated from the normal and from the relative velocity between the particle and the corresponding point on the box, and the relative velocity comes from GetLinearVelocityFromWorldPoint(). I noticed that the blue line for that goes down and to the right, cutting across the corner of the box, but I have no idea if that's to be expected for a box spinning anticlockwise or not. I don't know what the expected behaviour is when calling this function on the edge of a body. So I figure that the root cause of the problem is either:

a) GetLinearVelocityFromWorldPoint() doing something unexpected, or
b) my calculations for getting the normal component of the relative velocity

What do people think? For reference, here's the code that calculates all of these forces:

Code:
// At this point, pShape is the shape we're looking at, and particleIdx
// is the index into an array of particle structures which we think might
// be in contact with the shape
float dt2 = mDeltaT * mDeltaT;   // Delta time, squared. Used in calculating the particle's current velocity
b2Vec2 particlePos = mParticles[particleIdx].mPosition;

b2Vec2 nearestPos(0,0);
b2Vec2 normal(0,0);

// Returns true if there's an intersection, and also sets the nearest position
// the particle can be moved to to be outside the body, and sets up the normal
// at that point.
bool inside = ParticleSolidCollision(pShape, particleIdx, nearestPos, normal);

if (inside)
{
   // Use Verlet code to calculate the velocity right now, rather
   // than using last frame's value, or just performing a simple subtraction
   b2Vec2 acc = (mParticles[particleIdx].mForce + PhysicsMgr().GetPhysicsWorld()->GetGravity());
   acc.x *= dt2;
   acc.y *= dt2;
   b2Vec2 particleVelocity = particlePos - mParticles[particleIdx].mOldPosition + acc;

   // Dampen velocity
   particleVelocity.x *= 0.995f;
   particleVelocity.y *= 0.995f;

   b2Vec2 impulsePos = nearestPos;

   b2Vec2 pointVelocity = pShape->GetBody()->GetLinearVelocityFromWorldPoint(impulsePos);

   b2Vec2 relativeVelocity = particleVelocity - pointVelocity;

   b2Vec2 pointVelNormal = normal;
   pointVelNormal *= b2Dot(relativeVelocity, normal);

   b2Vec2 pointVelTangent = relativeVelocity - pointVelNormal;

   // Should be a value between 0.0f and 1.0f
   const float slipFriction = 0.5f;

   pointVelTangent *= slipFriction;
   b2Vec2 impulse = pointVelNormal - pointVelTangent;

   // Not sure if this should be here
   impulse *= mDeltaT;

   // Don't know if this should be a force or an impulse...
   pShape->GetBody()->ApplyImpulse(impulse, impulsePos);

   // move the particles away from the body
   SeparateParticleFromBody(particleIdx, nearestPos, normal, 1.0f);
}
Hi,

I will first answer your first post, your aksed a lot of questions, I will try to answer most of the first ones as I've been implementing exactly this research paper in XNA (using Farseer Physics) and also have a working Box2D version.

ElectroDruid wrote:
1 - The paper says that the particle velocity is calculated "using the difference between the current and previous particle positions". So, by subtracting the particle's position this frame from its position last frame. I'm not sure if it's quite that simple, though - my particles use Verlet integration, so velocity is calculated from the difference in positions between timesteps (rather than Euler, where newPos = oldPos + (velocity * dt)). I don't know whether to use this calculated velocity or just a simple subtraction, or if dt needs to play a part in that.

Verlet works just fine with PVFS. I tried the integration proposed in the paper and it didn't work that well. Just do a substraction as suggested and it works : position - previousPosition and use that for the particle velocity.

ElectroDruid wrote:
2 - The paper then says "We then compute the particle relative velocity v = vi - vp, where vp is the body velocity at the contact point". I'm using pBody->GetLinearVelocityFromWorldPoint() for that, but it's not clear to me whether the "contact point" means the world position of an intersecting particle, or the position on an edge of the body where the particle would have first collided with it, if the particles were using continuous physics. Again, I don't know if dt needs to be included in this relative velocity calculation.

pBody->GetLinearVelocityFromWorldPoint() works very well too, you just have to multiply its value by the timestep so you obtain velocities in the same unit and scale (ie. positions differences). The point you need to give to the function is the particle world position.

ElectroDruid wrote:
3 - The paper then talks about seperating the relative velocity into normal and tangential components in order to compute an "impulse" and adding this "impulse" into force and torque buffers, which will be used to compute changes to the linear and angular velocity of the rigid body. This confuses the hell out of me. I struggle with understanding the difference between impulses and forces, but if we take the paper at face value as meaning an impulse, pBody->ApplyImpulse() doesn't touch the torque of an object, it directly affects the angular velocity (and results in uncontrollably spinning objects). So should I be ignoring the paper's terminology and calling pBody->ApplyForce() instead, because that updates the torque rather than the angular velocity directly? ApplyForce() seems to have very little impact on the bodies at all.

What I have is 2 buffers, one is a 2D vector, for force, and another is a float, for torque. I use merely the same code as ApplyLinearImpulse to compute separate linear and angular impulses. Then, I apply these accumulated (you have to accumulate for all particles in collision with the bodies) buffers using ApplyLinearImpulse and ApplyAngularImpulse.


Also, to apply impulses in Verlet you just have to move the position or previousPosition of the particle, all the impulses described in the paper can be done like that.


Maybe, you already figured all that out by experimenting but if you have any remaining questions, feel free to ask.

PS : you can check out our XNA game (with Farseer Physics) at http://puddle-game.com, I didn't have the time to implement the whole paper for IGF but I did it recently and it works really well for floating objects, pushing things etc.

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