OpenGL Liquid Simulation

Well, I have decided to try put over old Phys2D and start out with JBox2D. So therefore, I decided to actually try port the liquid simulation feature to OpenGL as the testbed uses Java2D for drawing. For simple shape rendering and such, OpenGL works out perfectly with this:

Code:
for (Entity e : entities) {
            final Vec2[] vertices = ((PolygonShape) e.getBody().getFixtureList().getShape()).getVertices();
            float[] points = new float[vertices.length * 2];
            for (int i = 0; i < vertices.length; i++) {
                points[i * 2] = vertices[i].x;
                points[i * 2 + 1] = vertices[i].y;
            }
            Polygon p = new Polygon(points);
            p.setCenterX(e.getX());
            p.setCenterY(e.getY());
            g.draw(p);
            e.render();
        }


However, after I decided to test this rendering method on liquid, it caused immense lag and "manipulated" all the other shape's physics in a bad way. Also, the liquid particles are not actually shown, all you can see from the screen is a single dot that represents the liquid.

Also, here is my class for Liquid (basically just a reorganized version of LiquidTest in the testbed):

Code:
import java.util.ArrayList;
import java.util.Arrays;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.collision.shapes.MassData;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Settings;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;
import org.sactualize.entity.Entity;

/**
 *
 * @author JBox2D
 */
public class LiquidEntity extends Entity {

    public static Integer LIQUID_INT = new Integer(1234598372);
    private int nParticles = 500;
    private float totalMass = 10.0f;
    private float boxWidth = 2.0f;
    private float boxHeight = 20.0f;
    private float fluidMinX = -11.0f;
    private float fluidMaxX = 5.0f;
    private float fluidMinY = -10.0f;
    private float fluidMaxY = 10.0f;
    private Body[] liquid;
    private float rad = 0.6f;
    private float visc = 0.004f;//0.005f;
    private ArrayList<Integer>[][] hash;
    private int hashWidth, hashHeight;

    public LiquidEntity(World w, float x, float y) {
        super(w, x, y, false, null);
        initPhysics(w, x, y);
        hash = new ArrayList[40][40];
        for (int i = 0; i < 40; ++i) {
            for (int j = 0; j < 40; ++j) {
                hash[i][j] = new ArrayList<Integer>();
            }
        }
        hashWidth = 40;
        hashHeight = 40;
    }

    private void initPhysics(World w, float x, float y) {
        liquid = new Body[nParticles];
        float massPerParticle = totalMass / nParticles;
        CircleShape pd = new CircleShape();
        FixtureDef fd = new FixtureDef();
        fd.shape = pd;
        fd.density = 1f;
        fd.filter.groupIndex = -10;
        pd.m_radius = .05f;
        fd.restitution = 0.4f;
        fd.friction = 0.0f;
        float cx = 400.0f;
        float cy = 25.0f;
        for (int i = 0; i < nParticles; ++i) {
            BodyDef bd = new BodyDef();
            bd.position = new Vec2(MathUtils.randomFloat(cx - boxWidth * .5f, cx + boxWidth * .5f),
                    MathUtils.randomFloat(cy - boxHeight * .5f, cy + boxHeight * .5f));
            bd.fixedRotation = true;
            bd.type = BodyType.DYNAMIC;
            Body b = w.createBody(bd);

            b.createFixture(fd).setUserData(LIQUID_INT);

            MassData md = new MassData();
            md.mass = massPerParticle;
            md.I = 1.0f;
            b.setMassData(md);
            b.setSleepingAllowed(false);
            liquid[i] = b;
        }

        PolygonShape polyDef = new PolygonShape();
        polyDef.setAsBox(MathUtils.randomFloat(0.3f, 0.7f), MathUtils.randomFloat(0.3f, 0.7f));
        BodyDef bodyDef = new BodyDef();
        bodyDef.position = new Vec2(400f, 25.0f);
        bodyDef.type = BodyType.DYNAMIC;
        setBody(w.createBody(bodyDef));
        getBody().createFixture(polyDef, 1f);
    }

    private int hashX(float x) {
        float f = MathUtils.map(x, fluidMinX, fluidMaxX, 0, hashWidth - .001f);
        return (int) f;
    }

    private int hashY(float y) {
        float f = MathUtils.map(y, fluidMinY, fluidMaxY, 0, hashHeight - .001f);
        return (int) f;
    }

    private void hashLocations() {
        for (int a = 0; a < hashWidth; a++) {
            for (int b = 0; b < hashHeight; b++) {
                hash[a][b].clear();
            }
        }

        for (int a = 0; a < liquid.length; a++) {
            int hcell = hashX(liquid[a].m_sweep.c.x);
            int vcell = hashY(liquid[a].m_sweep.c.y);
            if (hcell > -1 && hcell < hashWidth && vcell > -1 && vcell < hashHeight) {
                hash[hcell][vcell].add(new Integer(a));
            }
        }
    }

    private void applyLiquidConstraint(float deltaT) {
        final float idealRad = 50.0f;
        float multiplier = idealRad / rad;

        float[] xchange = new float[liquid.length];
        float[] ychange = new float[liquid.length];
        Arrays.fill(xchange, 0.0f);
        Arrays.fill(ychange, 0.0f);

        float[] xs = new float[liquid.length];
        float[] ys = new float[liquid.length];
        float[] vxs = new float[liquid.length];
        float[] vys = new float[liquid.length];
        for (int i = 0; i < liquid.length; ++i) {
            xs[i] = multiplier * liquid[i].m_sweep.c.x;
            ys[i] = multiplier * liquid[i].m_sweep.c.y;
            vxs[i] = multiplier * liquid[i].m_linearVelocity.x;
            vys[i] = multiplier * liquid[i].m_linearVelocity.y;
        }

        for (int i = 0; i < liquid.length; i++) {
            ArrayList<Integer> neighbors = new ArrayList<Integer>();
            int hcell = hashX(liquid[i].m_sweep.c.x);
            int vcell = hashY(liquid[i].m_sweep.c.y);
            for (int nx = -1; nx < 2; nx++) {
                for (int ny = -1; ny < 2; ny++) {
                    int xc = hcell + nx;
                    int yc = vcell + ny;
                    if (xc > -1 && xc < hashWidth && yc > -1 && yc < hashHeight && hash[xc][yc].size() > 0) {
                        for (int a = 0; a < hash[xc][yc].size(); a++) {
                            Integer ne = (Integer) hash[xc][yc].get(a);
                            if (ne != null && ne.intValue() != i) {
                                neighbors.add(ne);
                            }
                        }
                    }
                }
            }
            float[] vlen = new float[neighbors.size()];
            float p = 0.0f;
            float pnear = 0.0f;
            for (int a = 0; a < neighbors.size(); a++) {
                Integer n = (Integer) neighbors.get(a);
                int j = n.intValue();
                float vx = xs[j] - xs[i];
                float vy = ys[j] - ys[i];
                if (vx > -idealRad && vx < idealRad && vy > -idealRad && vy < idealRad) {
                    float vlensqr = (vx * vx + vy * vy);
                    //within idealRad check
                    if (vlensqr < idealRad * idealRad) {
                        vlen[a] = (float) Math.sqrt(vlensqr);
                        if (vlen[a] < Settings.EPSILON) {
                            vlen[a] = idealRad - .01f;
                        }
                        float oneminusq = 1.0f - (vlen[a] / idealRad);
                        p = (p + oneminusq * oneminusq);
                        pnear = (pnear + oneminusq * oneminusq * oneminusq);
                    } else {
                        vlen[a] = Float.MAX_VALUE;
                    }
                }
            }
            float pressure = (p - 5F) / 2.0F;
            float presnear = pnear / 2.0F;
            float changex = 0.0F;
            float changey = 0.0F;
            for (int a = 0; a < neighbors.size(); a++) {
                Integer n = (Integer) neighbors.get(a);
                int j = n.intValue();
                float vx = xs[j] - xs[i];
                float vy = ys[j] - ys[i];
                if (vx > -idealRad && vx < idealRad && vy > -idealRad && vy < idealRad) {
                    if (vlen[a] < idealRad) {
                        float q = vlen[a] / idealRad;
                        float oneminusq = 1.0f - q;
                        float factor = oneminusq * (pressure + presnear * oneminusq) / (2.0F * vlen[a]);
                        float dx = vx * factor;
                        float dy = vy * factor;
                        float relvx = vxs[j] - vxs[i];
                        float relvy = vys[j] - vys[i];
                        factor = visc * oneminusq * deltaT;
                        dx -= relvx * factor;
                        dy -= relvy * factor;
                        xchange[j] += dx;
                        ychange[j] += dy;
                        changex -= dx;
                        changey -= dy;
                    }
                }
            }
            xchange[i] += changex;
            ychange[i] += changey;
        }
        for (int i = 0; i < liquid.length; ++i) {
            liquid[i].m_xf.position.x += xchange[i] / multiplier;
            liquid[i].m_xf.position.y += ychange[i] / multiplier;
            liquid[i].m_linearVelocity.x += xchange[i] / (multiplier * deltaT);
            liquid[i].m_linearVelocity.y += ychange[i] / (multiplier * deltaT);
        }
    }

    @Override
    public void render() {
    }

    @Override
    public void update(int delta) {
        float dt = 1.0f / 60f;

        int n = 1;
        for (int i = 0; i < n; ++i) {
            hashLocations();
            applyLiquidConstraint(dt * n);
        }
        this.dampenLiquid();
        this.checkBounds();
    }

    private void checkBounds() {
        for (int i = 0; i < liquid.length; ++i) {
            if (liquid[i].getWorldCenter().y < -10.0f) {
                getWorld().destroyBody(liquid[i]);
                float massPerParticle = totalMass / nParticles;

                CircleShape pd = new CircleShape();
                FixtureDef fd = new FixtureDef();
                fd.shape = pd;
                fd.density = 1.0f;
                fd.filter.groupIndex = -10;
                pd.m_radius = .05f;
                fd.restitution = 0.4f;
                fd.friction = 0.0f;
                float cx = 0.0f + MathUtils.randomFloat(-0.6f, 0.6f);
                float cy = 15.0f + MathUtils.randomFloat(-2.3f, 2.0f);
                BodyDef bd = new BodyDef();
                bd.position = new Vec2(cx, cy);
                bd.fixedRotation = true;
                bd.type = BodyType.DYNAMIC;
                Body b = getWorld().createBody(bd);
                b.createFixture(fd).setUserData(LIQUID_INT);
                MassData md = new MassData();
                md.mass = massPerParticle;
                md.I = 1.0f;
                b.setMassData(md);
                b.setSleepingAllowed(false);
                liquid[i] = b;
            }
        }

        if (getBody().getWorldCenter().y < -15.0f) {
            getWorld().destroyBody(getBody());
            PolygonShape polyDef = new PolygonShape();
            polyDef.setAsBox(MathUtils.randomFloat(0.3f, 0.7f), MathUtils.randomFloat(0.3f, 0.7f));
            BodyDef bodyDef = new BodyDef();
            bodyDef.position = new Vec2(400f, 25f);
            bodyDef.type = BodyType.DYNAMIC;
            setBody(getWorld().createBody(bodyDef));
            getBody().createFixture(polyDef, 1f);
        }
    }

    private void dampenLiquid() {
        for (int i = 0; i < liquid.length; ++i) {
            Body b = liquid[i];
            b.setLinearVelocity(b.getLinearVelocity().mul(0.995f));
        }
    }
}


If you see anything wrong on how the rendering works, or on how the liquid class works, please comment below on any possible ways to fix it.
I would suggest just writing your own testbed panel as a GLCanvas and make your own DebugDraw. That way you don't have to change anything in the tests. This is something I was gonna do soon. Let me know if you finish, I might patch it in if that's cool 🙂
Hm, I would rather not since it is more recommended to not use DebugDraw when you start to use it for an actual game.
tommo1 wrote:
Hm, I would rather not since it is more recommended to not use DebugDraw when you start to use it for an actual game.


Oh right, I see. I would store an array of all liquid fixtures (you can grab them from the createFixture method), and then render them however you like.

The liquid physics doesn't seem to be as stable as in 2.0.1, this might be because of the dynamic tree. I'm currently trying to debug this.

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