We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexDiscussionExhibition › jbox2d with custom rendering method
Page Index Toggle Pages: 1
jbox2d with custom rendering method (Read 6666 times)
jbox2d with custom rendering method
Dec 29th, 2008, 12:01am
 
since I couldn't find so much examples of how to implement a custom rendering method with JBox2d, I've decided to share this code.

here is a link to a simple video where real-time boxes are drawn onto the screen using JBox2d and a custom rendering method :
http://www.vimeo.com/2654808

here is the code. you'll need BoxWrap2D library:
http://jbox2d.org/processing/

Quote:
import org.jbox2d.p5.*;
import org.jbox2d.dynamics.*;
import org.jbox2d.common.*;
import org.jbox2d.collision.*;

Physics physics;
float x1, y1, x2, y2;
boolean sizeSet; int count = 0; // to work around threading problems with size

void setup() {
 size(600, 300, P3D);
 frameRate(60);
 sizeSet = false;
}

void draw() {
 
 // hack to make sure that the sketch size is fully initialized
 ++count;
 if ( (!sizeSet && count > 10) ) {
   initScene();
 }
 
}

void mouseDragged() {
 if (mouseButton == LEFT) {
   x2 = mouseX;
   y2 = mouseY;
 }
}

void mouseReleased() {
 if (mouseButton == LEFT) {
   Body randomBod = physics.createRect(x1, y1, x2, y2);
   x2 = 0; y2 = 0;
 }
}

void mousePressed() {
 if (mouseButton == LEFT) {
   x1 = mouseX;
   y1 = mouseY;
   x2 = x1;
   y2 = y1;
 }
}

void initScene() {
 physics = new Physics(this, width, height);
 physics.setDensity(1.0f);
 physics.setCustomRenderingMethod(this, "sketchBlocks");
 sizeSet = true;
}

void sketchBlocks(World w) {
 if (frameCount%10 != 0) return;
 background(255);
 noFill(); stroke(0);
 for (Body body = physics.getWorld().getBodyList(); body != null; body = body.getNext()) {
   org.jbox2d.collision.Shape shape;
   for (shape = body.getShapeList(); shape != null; shape = shape.getNext()) {
     beginShape();
     if (shape.getType() == ShapeType.POLYGON_SHAPE) {
       PolygonShape poly = (PolygonShape)shape;
       int count = poly.getVertexCount();
       Vec2[] verts = poly.getVertices();
       for(int i = 0; i < count; i++) {
         Vec2 vert = physics.worldToScreen(body.getWorldPoint(verts[i]));
         vertex(vert.x, vert.y);
       }
       Vec2 firstVert = physics.worldToScreen(body.getWorldPoint(verts[0]));
       vertex(firstVert.x, firstVert.y);
       for(int i = 0; i < count; i++) {
         Vec2 vert = physics.worldToScreen(body.getWorldPoint(verts[i]));
         vertex(vert.x-2+int(random(4)), vert.y-2+int(random(4)));
       }
       firstVert = physics.worldToScreen(body.getWorldPoint(verts[0]));
       vertex(firstVert.x, firstVert.y);
     }
     endShape();
   }
 }
 if (mousePressed && mouseButton == LEFT) {
   rect(x1, y1, x2-x1, y2-y1);
 }
}
Re: jbox2d with custom rendering method
Reply #1 - Dec 30th, 2008, 6:09pm
 
Heres a more simplified version for beginners, broken down step by step and split into different functions. The best way to test this draw method out is to copy it to the bottom of the boxwrap2D example "SwingingDemo":

Quote:
void blackWhite(World w) {

  background(255);
  smooth();

  //go through each of our body lists in the physics world
  for (Body body = physics.getWorld().getBodyList(); body != null; body = body.getNext()) {

    //Define the shape as a jbox2D shape variable
    org.jbox2d.collision.Shape shape;

    //go through each of our shapes contained in the current body
    for (shape = body.getShapeList(); shape != null; shape = shape.getNext()) {

      //draw the shapes based on type
      if (shape.getType() == ShapeType.POLYGON_SHAPE) {

        //Polygon Appearance Parameters
        fill(0);
        stroke(255);
        strokeWeight(2);

        //Draw the polygon
        polyDraw(body, shape);

      } 
      else if (shape.getType() == ShapeType.CIRCLE_SHAPE) {

        //Circle Appearance Parameters
        fill(255);
        stroke(0);
        strokeWeight(5);

        //Draw the circle
        circleDraw(body, shape);
      }
    } 
  }
}

void polyDraw(Body body, org.jbox2d.collision.Shape shape) {

  beginShape();

  PolygonShape poly = (PolygonShape) shape;

  //get the number of vertex points that make up the shape
  int count = poly.getVertexCount();

  //convert the polygon into points
  Vec2[] verts = poly.getVertices();

  //make a vertex for each point of the polygon and convert for pixel coordinates
  for(int i = 0; i < count; i++) {

    //get the position of the vertex of the shape within the body in the world (whew!!)
    Vec2 vert = physics.worldToScreen(body.getWorldPoint(verts[i]));
    vertex(vert.x, vert.y);
  }

  //connect the last point with the first point and stop
  Vec2 firstVert = physics.worldToScreen(body.getWorldPoint(verts[0])); 
  vertex(firstVert.x, firstVert.y);
  endShape();
}

void circleDraw(Body body, org.jbox2d.collision.Shape shape) {

  //convert the shape to a circleshape
  CircleShape circle = (CircleShape) shape;

  //get position of circle within body
  Vec2 center = circle.getLocalPosition();

  //get position of body within world and convert to pixel coordinates
  Vec2 wpoint = physics.worldToScreen(body.getWorldPoint(center));

  //get the radius of the circleshape in pixel format
  float radius = physics.worldToScreen(circle.getRadius());

  //draw the circle with radius converted to diameter
  ellipse(wpoint.x,wpoint.y,radius*2,radius*2);
}


Re: jbox2d with custom rendering method
Reply #2 - Feb 10th, 2009, 8:31am
 
while playing with jbox2d i came across this post. And hope you can maybe help me with some question.

I played arround with the SwingingDemo
http://www.jbox2d.org/processing/examples/index.html

I was asking myself where the shapes are actually drawn... How do i change the look of the shapes and replace them with my own ellipse or whatever? Would be great if you could show me a way how to do this. And if its working, it shouldnt be a problem to export the actual screen to a pdf onclick, right?

Thanks for your help!
Re: jbox2d with custom rendering method
Reply #3 - Feb 10th, 2009, 11:03am
 
Cool stuff, guys, I threw that hook in even though I wasn't sure if anyone would do anything with it, and since it was sort of an advanced feature I haven't yet gotten around to documenting it outside the Javadocs (actually, there's a lot relating to this library that I haven't gotten around to lately!  I'm finishing a major part of my current consulting gig as we speak, so I'll have more time soon, I swear!), but I'm glad to see someone was poking around!

Let me know if you notice any problems, I'll admit this functionality was not very thoroughly tested, esp. from within the PDE, so there may be some issues to work out.

Also let me know if there's a simpler way you can think of to do this stuff, I'm not sure I'm entirely satisfied with the complexity yet...
Re: jbox2d with custom rendering method
Reply #4 - Feb 10th, 2009, 6:28pm
 
thanks to ewjordan who allready solved my problem...
Re: jbox2d with custom rendering method
Reply #5 - Feb 20th, 2009, 5:42pm
 
Thx for the n00bie code Cheesy
Re: jbox2d with custom rendering method
Reply #6 - Sep 18th, 2009, 3:18am
 
Hi everyone,
I'm trying to build some stuff with boxwrap2d,
and I'm wondering exactly the same question as Cedric…
You seems to get the answer from ewjordan? Is there a way to apply custom *.png to a body, without editing the CustomRenderingMethod (i'm a newbie, and this is not really friendly…).
Thanks for all this amzing work…

Gui-aum


Re: jbox2d with custom rendering method
Reply #7 - Sep 18th, 2009, 3:28am
 
I planned to explain that in my on-going BoxWrap2D tutorial but due to lack of interest from people and multiple interests from myself, the series is a bit on hold currently (but should resume someday).

You don't edit the library, you use setCustomRenderingMethod with your own method, as shown above. Then you query the currently rendered objects, and display them, say with image(), using the proper translate() and rotate() depending on object position and angle.
Re: jbox2d with custom rendering method
Reply #8 - Sep 18th, 2009, 3:41am
 
Hey, PhiLho,
your tutorial is printed, on my desk, and this is a very powerful way to get in boxwrap… many many thanks…

About the rendering method, that's what I thougt… I just wondered if there was a faster "mapping" method (circle = image).

So…a coffee, the tuto, and go on.
Thanks
Re: jbox2d with custom rendering method
Reply #9 - Sep 18th, 2009, 5:34am
 
Nice to learn some people are interested. Even if I mostly started the tutorial for myself (pushing me through the arcanes of JBox2D), it is encouraging. Smiley

More hint: you have a loop to "Walk the body list in the physics world".
For each body, supposing it is made of only one simple shape, you can draw it with an image instead of using ellipse or a list of vertices.
You have its angle with body.getAngle(), its position with body.getPosition() (to transform to sketch coordinates), you can check if it is stable (.isSleeping()) if you want to draw it differently in this case. And you can know what body it is by using .getUserData() (eg. using a String as object, .setUserData("name") at creation, but can be more complex objects, eg. holding a state, counters, etc.).

After that, that's usual Processing business, pushMatrix, translate, rotate, translate again if needed, draw image, popMatrix.

I hope this pushes you forward.
Re: jbox2d with custom rendering method
Reply #10 - Sep 18th, 2009, 7:24am
 
Your tutorial is really perfect to begin with jbox2d (in a few hours, I had my first sketch perfectly running).

Your explanations are exactly what I need, in one post, all my questions are answered.
.setUserData / .getUserData would be very useful.

I'll came back in a few weeks to post my results…

Thanks again, (and sorry for my english  Embarrassed )
Re: jbox2d with custom rendering method
Reply #11 - Sep 23rd, 2009, 4:49pm
 
Hi!
Yes, it's me again... with another question………
The last thing missing in my project is the contact detection.
I've understood how it works (I think), with some tutorials about the contactListener in box2D in flash, but I can't understand how I can declare a listener, or overriding the "add" function into it, as a lot of people do in AS3. I looked at a lot of Java sources on the net, without finding the solution… Any idea?
Thx a lot

Gui-aum
Re: jbox2d with custom rendering method
Reply #12 - Sep 25th, 2009, 1:01am
 
I've just started a new topic about this, maybe it would be more visible…
[url]http://processing.org/discourse/yabb2/num_1253865618.html#0[/url]
Page Index Toggle Pages: 1