Box2D Java

Nice to see updates still coming strong. 😀

*downloads latest snapshot*
Has anyone seen this Java port http://www.cokeandcode.com/phys2d/? It might have some features that aren't even in the current source.
It's kinda shame that java never really took off as a compiled language as well (it is a lot more of a modern language than C++...) although most modern VM's are really efficient I'd love to see some benchmarks of a java app compiled natively (I know its fairly easy to do in *nix but god knows for windows)

My hunch is that a compiled java app ought to be rather close in speed to a C++ app... (I could be wrong it could be faster 😀 )

I'm assuming that the java version is a source port and not just a wrapper to a c++ library?

I saw a javascript version of box2d somewhere oh boy was that a disappointment....
@SarcasmMonster - Phys2d is based on Box2d Lite, Erin's earlier Box2d engine, so the feature set is for the most part a subset of Box2d's. Some stuff was added to Phys2d on top of Box2d Lite, so there might be some stuff in there that differs from the current Box2d.

@chris_c - I've run some Java vs. C++ benchmarks, and for instance with Box2d there is between a 20% to 50% difference depending which code the tests exercise (some of the Java stuff has not been fully optimized yet to minimize the Java penalty by reducing garbage creation, etc.).

You're probably aware that current JVMs actually compile often used Java methods to machine code - most of JBox2d ends up compiled, not interpreted, after a minute or two of simulation. I've been looking lately at the actual assembly created by this compilation, and for the most part it's fairly good. The main losses in speed are garbage collection, null pointer checks and array bounds checks; there's another issue that someone recently informed me of where very long methods are not very well optimized because the optimizer cuts off early to save compilation time. Some of the heavy lifting in JBox2d happens in big methods, so I'm going to experiment with breaking them up to see if it helps matters.

There are ways to natively compile Java, too (though this does break cross-platform compatibility, in which case some might argue that you might as well just write C++) - Excelsior's JET (http://www.excelsior-usa.com/jet.html) comes to mind, and it's supposed to be extremely good (it performs a whole lot of global optimizations that would probably help JBox2d a lot). Unfortunately it's expensive, over $1000 per seat for the cheapest commercial version (academic/non-profit licenses are much cheaper). I haven't tried it myself yet, though at some point I might, because I'm curious to see how JET compiled Java compares to similarly written C++.
Here's a minor idea.

Maybe the JointDef class should be defined as

Code:
public class JointDef<T extends Joint>


Where T is the Joint that it's defining. ie.
Code:
MouseJointDef extends JointDef<MouseJoint>


That way the when creating joints, we won't need to cast everytime we create new joints
Code:
public static <T extends Joint> T create(JointDef<T> description) {


So whatever JointDef goes in the parameter, the returned type matches. I don't know if you want to introduce generics into the code but it's only a couple of line changes. The advantage is that the developer using the engine doesn't have to cast every time they create a joint.

Code:
LAnkle = (RevoluteJoint) w.createJoint(def.LAnkleDef);

becomes
Code:
LAnkle = w.createJoint(def.LAnkleDef);
Hi,
just wanted to thank you guys for your work on JBox2D, and of course Erin for Box2D! I got basic platformer character up and running very quickly in JBox2D, having never touched (J)Box2D before. 😀 I've tried integrating a few 3d physics engines for 2d platformer usage some time ago, and they were pain compared to Box2D. So, keep up the excellent work, and hopefully you can keep the Java port alive and up-to-date. 😎

I'm planning to make a platformer later using LWJGL and JBox2D, but first I'll have to finish <shameless plug>this.. </shameless plug> 😛
Hey,

first of all thank you so much for the port. 🙂
I had used Phys2D (mentioned above) before, but I found Box2D to be superior.

Running my game for about 10 hours altogether, there have occurred two exceptions from inside JBox2D. I'm not sure about what the first one was, but I looked at it in detail for the second one:
In BroadPhase.java, line 778, there was a ArrayOuttOfBoundsException. The index was -1. The code around there looks like this:
Code:
        if (lowerQuery > 0) {
            int i = lowerQuery - 1;
            int s = bounds[i].stabbingCount;
            // Find the s overlaps.
            while (s != 0) {
                assert (i >= 0) : ("i = " + i + "; s = " + s);
                if (bounds[i].isLower()) {    <-- here the exception occurred

So, i is the one which took the inappropriate value. Quite strange considering the lines above, as it seems impossible for i to be smaller than 0...
I'm pretty sure I didn't do anything unusual, and the code does not call JBox2D methods in parallel which could cause concurrent modification of variable values. (Oh, and also I just realised that i is a local variable, so it cannot even be concurrently modified.)

My code looks as follows:
Code:
Shape[] shape = world.query(aabb, 1);

so nothing special.

If you need any further details let me know, but I'm afraid I've already told all I know about it.

Sascha
@ElkMonster: Ok, thanks for the report, I'll look into it. FWIW, the entire block there reads:

Code:
        if (lowerQuery > 0) {
            int i = lowerQuery - 1;
            int s = bounds[i].stabbingCount;
            // Find the s overlaps.
            while (s != 0) {
                assert (i >= 0) : ("i = " + i + "; s = " + s);
                if (bounds[i].isLower()) {
                    Proxy proxy = m_proxyPool[bounds[i].proxyId];
                    if (lowerQuery <= proxy.upperBounds[axis]) {
                        incrementOverlapCount(bounds[i].proxyId);
                        --s;
                    }
                }
                --i;
            }
        }

Notice that i is being decremented and is relying on s to hit zero before i goes below, so it's definitely possible for i to hit -1, maybe something is going wrong a little further up, I'll look into it.

A couple questions:

Is this consistently reproducible, or is it just something that happens once in a long while? I'm curious, any chance you can try running your program with assertions enabled? (add -ea to the VM arguments) Unfortunately, Java disables assertions by default, which means a lot of the fail-fast checking gets skipped over...

Also, have you altered Settings.java at all? Changed the maxProxies or anything like that?

@SarcasmMonster: That's actually a pretty good idea. I'll think about adding that to a future version; I'd like to remain backwards compatible, but I'll see if there's a good way to do it. I also need to check if we lose type safety that way - you're probably aware of the crappy Java implementation of generics using type-erasure, so I need to make sure everything blows up correctly if the user makes an error. We'll see - depending on the size of my todo list, I'll consider adding this a version or two down the line.
ewjordan wrote:
Notice that i is being decremented and is relying on s to hit zero before i goes below, so it's definitely possible for i to hit -1

Oh, I missed that --i at the end.

Quote:
Is this consistently reproducible, or is it just something that happens once in a long while?

Like I said, it happened twice in two days during which the programme has run for many hours. It's a kind of Pong that is played on a multi-touch table. Instead of a paddle, there are a number of small boxes that are used to hit the ball. Therefore, it is a very repetitive game. Each time a player touches the table, the game calls query to check if a box is touched. So, I'd rather call it the opposite of "reproducible". 😉

Quote:
I'm curious, any chance you can try running your program with assertions enabled? (add -ea to the VM arguments) Unfortunately, Java disables assertions by default, which means a lot of the fail-fast checking gets skipped over...

Well... there's a conflict then. The game will be running a few more times as it is part of a study for my bachelor thesis. I have to recruit a lot of people and ask them to play for the study, so I don't want the game to break anytime during the matches. So, enabling assertions isn't a good option for me (and I'll also have to prevent the OutOfBoundsException from breaking the game). However, I could just change the code to some simple if-statements and then log any bad values.

Quote:
Also, have you altered Settings.java at all? Changed the maxProxies or anything like that?

Nothing like it. The most "special" thing I do is to create and destroy a lot of joints (mouse and revolute joints) nearly every frame, and the mouse joints have an unusual high value for frequencyHz.
Hmm, that's all quite disturbing...a couple exceptions over many hours of play means that this will be extremely tough to track down, and it sounds like it probably depends on user input.

I'll have to take a look through that code in detail and try to figure out what possible edge case might break it - I'll also check whether there is possibly anything that's happening that's different from the C++, the broadphase code was a bit tricky to port so it's very possible.

For now, you might just wrap each of your query calls in a try/catch, you should be able to safely ignore any exceptions there without causing much trouble (the side effects of those calls should not do anything important to the simulation), at least until I track this down.

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