JBox2D Threaded RayCasts?

Hello All,
This is my first post, so forgive me if this isn't the proper place for questions. I have far too much code to post it all so I will be mostly giving pseudo-code of the relevant parts, but this is mainly a theoretical/how do I question so code may not be needed at all.

I'm working on a game with cameras that are scanning for the player, I've implemented the field of view of the camera as a sensor attached to a Kinematic body. When the Sensor is colliding with the player I'm using a World.raycast() from the camera to the player to determine if there is Line of sight. This happens every frame that the player is in the FoV of the camera. When the player is in the FoV of a camera there is a slight drop in frame rate, which gets worse the more cameras the player is within view of.

My question is if it's safe to spawn a new thread to do the cast on the world, or add a requested cast to a thread safe queue to allow worker-threads to cast?

The JBox2D documentation doesn't specify any thread safety, so my assumption is that it is not safe to do.
What would be the best way to:
1) reduce the number of ray casts per frame (simply skipping some frames would probably be fine, but I don't want the player to be able to get through the FoV of the camera before a ray cast occurs)
2) speed up the ray casts or
3) offload the ray casts so they won't lower my frame rate.

Using JBox2D 2.3.0.

If you need code I can post some later, right now my game loop looks something like this (pseudo-code):

Code: Select all

class GameWorld extends JPanel implements Runnable, (various listeners) {
    World phys; //physics world
    boolean running;
    BufferedImage backBuf;
    ///lots of other stuff
    public GameWorld(){
        //init everything
    }
    public void start(){running=true; new Thread(this).start();}
    public void stop(){running=false;}
    @Override
    public void run(){
        while(running){
            step();
            draw();
        }
    }
    private void step(){
        world.step(1/60f);
        ///update all game entities
       
        ///camera entities perform the ray casts when they are stepped


        //remove dead entities
    }
    private void draw(){
         Graphics g = backBuff.getGraphics();
         //draw everything
         g.dispose();
         Graphics g2 = getGraphics();
         g2.drawImage(backBuf,0,0);
    }

     /////////Listener methods and probably others.


    public static void main(String[] args){
        GameWorld world=new GameWorld();
        JFrame frame  = new JFrame();
        frame.add(world);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        world.start();

    }
}
Strange that the raycasting should cause a slowdown.

... looking at the source code just now, it seems like maybe the raycast function is doing more work than it needs to. Comparing the C++ and Java versions of the DynamicTree class (simplified for brevity):

C++:

Code: Select all

b2GrowableStack<int32, 256> stack;
stack.Push(m_root);
while (stack.GetCount() > 0) {
    int32 nodeId = stack.Pop();
    if ( node->IsLeaf() )
        ... check if node hits, return if callback says to quit here ...
    else {
        stack.Push(node->child1);
        stack.Push(node->child2);
    }
}


Java:

Code: Select all

intStack.push(m_root);
while (intStack.getCount() > 0) {
    int nodeId = intStack.pop();
    if (node.isLeaf()) {
        ... check if node hits, return if callback says to quit here ...
    } else {
        intStack.push(node.child1);
        intStack.push(node.child2);
    }
}

Both versions are essentially the same, except that in the Java version the 'intStack' variable is a class member, while 'stack' in C++ is a local variable. If I understand this correctly, when the raycast callback specifies that the function should return without checking every node in the stack (as would be the case when checking a line-of-sight, you can return as soon as any obstruction is found), then the stack is left with some nodes in it. After a while these could pile up in the stack and cause a lot of unnecessary processing. The stack class has a reset() function which I think should be called before pushing the root node into 'intStack'.
Yes, this was a slip-up by me 😳
It shouldn't be TOO big of a performance hit, as the AABB check is right away. But it should be changed anyways. I'll make another 2.1.2 release soon
I'll also run an optimization pass on that code, it could use some inlining. Are you using the 2.1.2 version, or trunk?

edit: also, what kind of shapes are you using mostly?
edit2: also, to answer your question, the library is not thread safe
Thanks for the info, I'm using a version of the trunk, but the last time I checked out and compiled was several months ago, about August revision 521 I believe (I'm bad about updating things). I suppose I should update it.

When I first checked it out some things wouldn't compile, a GearJoint and WheelJoint were broken and I don't remember why, and several others were using the org.slf4j.Logger and I swapped it for java.util.logging.Logger. The slf4j wasn't something I wanted, and I had trouble getting the engine to compile with it, Is that still a dependency?

Google showed other had the problem because something wasn't right with the pom.xml file, but swapping it to java.util.logging worked with only minor adjustments and compiled just fine. (Just trying to find out how much trouble updating will cause).

EDIT: forgot the other question:

I'm using mainly circle and box shapes, character and bullets are circles, walls, and cameras are boxes with arbitrary angles and dimensions.
The logging dependencies were removed, and everything should compile just fine from trunk. You might want to try with a clean checkout, to avoid merging.

You should see speed improvements, a decent amount of optimization has happened since then 🙂
Have you seen improvements? Let me know how things are going, I also just made the broadphase quite a bit faster.

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