Thursday, 29 December 2011

JBox2D With JavaFX : Write your first JBox2D with JavaFX 2 program

So far we have learned about JBox2D world, Bodies and world Simulation. With this we are ready to try our hands on JBox2D.

Today we will write one simple JBox2D application. In this application we will create one bouncy ball and release it into the JBox2D world. We will use JavaFX 2 for UI.

Our first step is to create JavaFX project. We will use NetBeans 7.1 for this. If you have not installed JavaFX SDK and NetBeans then you can download and install it form here. Once installed, open NetBeans IDE and follow the following steps

Click on File>New Project… menu. This will open “New Project” dialog box.
Select “JavaFX” under categories and then select JavaFX Application under projects
Click on “Next“ button.

In next window, type project name as “BouncyBallApp”.
Select project location.
Select “Create Application class” checkbox.
Select “Set as main project”
Click on finish.


This will create a project with main class “BouncyBallApp.java”

We will create two more class in this project – Utility.java and BouncyBall.java

Utility.Java – We will add all required constants and utility methods to this class.

We will add following constants to the Utility.java class
//Create a JBox2D world. 
    public static final World world = new World(new Vec2(0.0f, -10.0f), true);
    
    //Screen width and height
    public static final int WIDTH = 600;
    public static final int HEIGHT = 600;
    
    //Ball radius in pixel
    public static final int BALL_RADIUS = 8;


We will add method “addGround” to Utility class. This method will help us to add ground/platform for our JBox2D world. Ground is an essential component of our application. This is where our bouncy ball will land and bounce back. If we do not add ground ball will move infinitely downwards.

//This method adds a ground to the screen. 
public static void addGround(float width, float height){
    PolygonShape ps = new PolygonShape();
    ps.setAsBox(width,height);
        
    FixtureDef fd = new FixtureDef();
    fd.shape = ps;

    BodyDef bd = new BodyDef();
    bd.position= new Vec2(0.0f,-10f);

    world.createBody(bd).createFixture(fd);
}

As you can see we are using polygon shape for creating the ground. I will cover JBox2D shapes in detail in future post.

Next we will add method “addWall” to utility class. This method will allow us to add walls to our JBox2D world. Walls are required because we don’t want our bouncy ball to go outside the application viewable area.
//This method creates a walls. 
public static void addWall(float posX, float posY, float width, float height){
    PolygonShape ps = new PolygonShape();
    ps.setAsBox(width,height);
        
    FixtureDef fd = new FixtureDef();
    fd.shape = ps;
    fd.density = 1.0f;
    fd.friction = 0.3f;    

    BodyDef bd = new BodyDef();
    bd.position.set(posX, posY);
        
    Utils.world.createBody(bd).createFixture(fd);
}

Next we will add few utility methods which will allow us to convert JBox2D world coordinates to pixel coordinates and vise versa.
//Convert a JBox2D x coordinate to a JavaFX pixel x coordinate
public static float toPixelPosX(float posX) {
    float x = WIDTH*posX / 100.0f;
    return x;
}

//Convert a JavaFX pixel x coordinate to a JBox2D x coordinate
public static float toPosX(float posX) {
    float x =   (posX*100.0f*1.0f)/WIDTH;
    return x;
}

//Convert a JBox2D y coordinate to a JavaFX pixel y coordinate
public static float toPixelPosY(float posY) {
    float y = HEIGHT - (1.0f*HEIGHT) * posY / 100.0f;
    return y;
}

//Convert a JavaFX pixel y coordinate to a JBox2D y coordinate
public static float toPosY(float posY) {
    float y = 100.0f - ((posY * 100*1.0f) /HEIGHT) ;
    return y;
}

//Convert a JBox2D width to pixel width
public static float toPixelWidth(float width) {
    return WIDTH*width / 100.0f;
}

//Convert a JBox2D height to pixel height
public static float toPixelHeight(float height) {
    return HEIGHT*height/100.0f;
}


BouncyBall.java – Now we will create main actor of our application i.e. bouncy ball. First we will add class called as BouncyBall.java. We will add following attributes to this class.
//JavaFX UI for ball
    public Node node;
    
    //X and Y position of the ball in JBox2D world
    private float posX;
    private float posY;
    
    //Ball radius in pixels
    private int radius;

Then we will add method “private Node create()” to this class. The return type of method is set to javafx.scene.Node. We will use this method to create a ball. To create ball we will have to:

Create graphical representation of the ball and set its x,y position
//Create an UI for ball - JavaFX code
        Circle ball = new Circle();
        ball.setRadius(radius);
        ball.setFill(color); //set look and feel

        /**
         * Set ball position on JavaFX scene. We need to convert JBox2D coordinates 
         * to JavaFX coordinates which are in pixels.
         */
        ball.setLayoutX(Utils.toPixelPosX(posX)); 
        ball.setLayoutY(Utils.toPixelPosY(posY));

Create body definition of the ball i.e. ball body type (Dynamic in this case) & body position
//Create an JBox2D body defination for ball.
        BodyDef bd = new BodyDef();
        bd.type = BodyType.DYNAMIC;
        bd.position.set(posX, posY);

Create ball shape
CircleShape cs = new CircleShape();
        cs.m_radius = radius * 0.1f;  //We need to convert radius to JBox2D equivalent

Create fixture for ball
// Create a fixture for ball
        FixtureDef fd = new FixtureDef();
        fd.shape = cs;
        fd.density = 0.6f;
        fd.friction = 0.3f;        
        fd.restitution = 0.8f;
And finally we will create body, associate it with its graphical representation and return it.
/**
        * Virtual invisible JBox2D body of ball. Bodies have velocity and position. 
        * Forces, torques, and impulses can be applied to these bodies.
        */
        Body body = Utils.world.createBody(bd);
        body.createFixture(fd);
        ball.setUserData(body);
        return ball;

We will call this method from class constructor.
public BouncyBall(float posX, float posY, int radius, Color color){
        this.posX = posX;
        this.posY = posY;
        this.radius = radius;
        this.color = color;
        node = create();
    }

Finally BouncyBall.java should look like this:

package bouncyballapp;

import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;

/**
 *
 * @author dilip
 */
public class BouncyBall{

    //JavaFX UI for ball
    public Node node;
    
    //X and Y position of the ball in JBox2D world
    private float posX;
    private float posY;
    
    //Ball radius in pixels
    private int radius;
    
   
    private Color color;
    public BouncyBall(float posX, float posY, int radius, Color color){
        this.posX = posX;
        this.posY = posY;
        this.radius = radius;
        this.color = color;
        node = create();
    }
    
    /**
     * This method creates a ball by using Circle object from JavaFX and CircleShape from JBox2D
     */
    private Node create(){
        //Create an UI for ball - JavaFX code
        Circle ball = new Circle();
        ball.setRadius(radius);
        ball.setFill(color); //set look and feel 
        
        /**
         * Set ball position on JavaFX scene. We need to convert JBox2D coordinates 
         * to JavaFX coordinates which are in pixels.
         */
        ball.setLayoutX(Utils.toPixelPosX(posX)); 
        ball.setLayoutY(Utils.toPixelPosY(posY));
       
        //Create an JBox2D body defination for ball.
        BodyDef bd = new BodyDef();
        bd.type = BodyType.DYNAMIC;
        bd.position.set(posX, posY);
        
        CircleShape cs = new CircleShape();
        cs.m_radius = radius * 0.1f;  //We need to convert radius to JBox2D equivalent
        
        // Create a fixture for ball
        FixtureDef fd = new FixtureDef();
        fd.shape = cs;
        fd.density = 0.6f;
        fd.friction = 0.3f;        
        fd.restitution = 0.8f;

        /**
        * Virtual invisible JBox2D body of ball. Bodies have velocity and position. 
        * Forces, torques, and impulses can be applied to these bodies.
        */
        Body body = Utils.world.createBody(bd);
        body.createFixture(fd);
        ball.setUserData(body);
        return ball;
    }
    
}


Our final step is to modify main class i.e. BouncyBallApp.java class.

We will have to do following changes to “start()” method.

Set application title and application window size. Also set full screen and resizable properties to false so user will not be able to resize application window.
primaryStage.setTitle("Bouncy Ball");
        primaryStage.setFullScreen(false);
        primaryStage.setResizable(false);
        Group root = new Group(); //Create a group for holding all objects on the screen
        Scene scene = new Scene(root, Utils.WIDTH, Utils.HEIGHT);

Add ball, ground and walls
//create ball   
        final BouncyBall ball = new BouncyBall(45, 90, Utils.BALL_RADIUS, Color.RED);
         
        //Add ground to the application, this is where balls will land
        Utils.addGround(100, 10);
        
        //Add left and right walls so balls will not move outside the viewing area.
        Utils.addWall(0,100,1,100); //Left wall
        Utils.addWall(99,100,1,100); //Right wall

Add code for simulating the world.
final Timeline timeline = new Timeline();
        timeline.setCycleCount(Timeline.INDEFINITE);

        Duration duration = Duration.seconds(1.0/60.0); // Set duration for frame.
        
        //Create an ActionEvent, on trigger it executes a world time step and moves the balls to new position 
        EventHandler<actionevent> ae = new EventHandler<actionevent>() {
            public void handle(ActionEvent t) {
                        //Create time step. Set Iteration count 8 for velocity and 3 for positions
                        Utils.world.step(1.0f/60.f, 8, 3); 
                       
                        //Move balls to the new position computed by JBox2D
                        Body body = (Body)ball.node.getUserData();
                        float xpos = Utils.toPixelPosX(body.getPosition().x);
                        float ypos = Utils.toPixelPosY(body.getPosition().y);
                        ball.node.setLayoutX(xpos);
                        ball.node.setLayoutY(ypos);
           }
        };

                
         /**
         * Set ActionEvent and duration to the KeyFrame. 
         * The ActionEvent is trigged when KeyFrame execution is over. 
         */
        KeyFrame frame = new KeyFrame(duration, ae, null,null);

        timeline.getKeyFrames().add(frame);

Add code to start simulating the world on click of the button
//Create button to start simulation.
        final Button btn = new Button();
        btn.setLayoutX((Utils.WIDTH/2) -15);
        btn.setLayoutY((Utils.HEIGHT-30));
        btn.setText("Start");
        btn.setOnAction(new EventHandler<actionevent>() {
            public void handle(ActionEvent event) {
                        timeline.playFromStart(); 
                        btn.setVisible(false);
            }
        });

Finally add button and ball to the root group
root.getChildren().add(btn);
        root.getChildren().add(ball.node);
        primaryStage.setScene(scene);
        primaryStage.show();


Finally hit the “F6” to run the application.

<<Simulating JBox2D world                         Applying Force and Impulse on body>>

Wednesday, 21 December 2011

JBox2D Tutorial : Simulating JBox2D world

In previous post we have learned how to create JBox2D world. We also learned how to create bodies and add them to the world. Now next step is to simulate the JBox2D world.

To simulate the world, we need to call step method of the world.

float timeStep = 1.0f / 60.f;
int velocityIterations = 6;
int positionIterations = 2;

for (int i = 0; i < 60; ++i) {
world.step(timeStep, velocityIterations, positionIterations);
      Vec2 position = body.getPosition();
      float angle = body.getAngle();
      System.out.printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);
}
As you can see in above snippet, we are passing three arguments to the world.step

timeStep - This defines how much simulation should advance in one second. In above example simulation will advance by 1/60th second on every call to the step method.

velocityIterations – This define how accurately velocity will be simulated. Higher iteration value increases the accuracy of velocity simulation but decreases the performance. The recommended velocity iteration value is 6.

 positionIterations – This is similar to velocity iteration, higher value means more accurate position simulation but lesser performance. The recommended position iteration value is 3.

In above sample code snippet on every simulation step we are getting body’s new position and angle details and printing them to the console. So far we have learned about world, bodies and world simulation. In next post we will write our first JBox2D program with JavaFX 2.0

<<Creating Body                                      Writing first JBox2D program>>

Monday, 19 December 2011

JBox2D Tutorial : Creating an object body

In last post we have learned how to create the JBox2D WorldNow our next step will be to create an object body and add it to the world. 

To create bodies in JBox2D world we need to first create:

  • Body definition
  • Body shape and
  • Body fixtures.


Body Definition

Body definition is created as below.

BodyDef bd = new BodyDef();
bd.position.set(50, 50);  
bd.type = BodyType.DYNAMIC;

Main properties of the body definition are

  • Position - position of the body in JBox2d world i.e. x and y coordinates.
  • Body type – type of the 
Body can be static, dynamic or kinematic.


Static Body

  • Static bodies have zero velocity.
  • Static bodies do not move under simulations.
  • Static bodies can be moved manually by user.
  • Static bodies have infinite mass.
  • Static bodies do not collide with other static and kinematic bodies.
  • Examples - Ground, Walls.


Dynamic Body –

  • Dynamic bodies move under simulation.
  • Dynamic bodies respond to the forces and they move accordingly.
  • Dynamic bodies can be moved manually.
  • Dynamic bodies always have non-zero mass. If mass is set to zero then it acquires 1Kg mass.
  • Dynamic bodies collide with dynamic, kinematic and static body types.
  • Examples – Ball, Box,


Kinematic Body –

  • Under simulation, kinematic bodies move according to its velocity.
  • Kinematic bodies do not move according to forces.
  • Kinematic bodies can be moved manually by user.
  • Kinematic bodies have infinite mass.
  • Kinematic bodies do not collide with static or kinematic bodies.
  • Kinematic body’s movement does not get affected by gravity.
  • Kinematic body’s movement does not get affected when dynamic bodies are collided with it.
  • Example – moving platforms in games.


Body Shape

Next we need to define the body shape. JBox2D support Circle shape, Polygon Shape, Edge Shape and Chain Shape. We will discuss each shape in details in future tutorials.

Following code snippet shows how to create a circle shape.

CircleShape cs = new CircleShape();
cs.m_radius = 0.5f;  

Fixtures

Fixture defines the material properties of the body. Fixtures are also used for attaching shape to the body. These material properties describe how two bodies should react when they collide with each other.

FixtureDef fd = new FixtureDef();
fd.shape = cs;
fd.density = 0.5f;
fd.friction = 0.3f;        
fd.restitution = 0.5f;

Density – This defines the heaviness of the body with respect to its area.

Friction - This defines how bodies slide when they come in contact with each other. Friction value can be set between 0 and 1. Lower value means more slippery bodies.

Restitution – This define how bouncy is the body. Restitution values can be set between 0 and 1. Here higher value means more bouncy body.

There are some more properties of fixture, will cover them in future post.

Creating body

Now final step is to create a body and add fixture to it. The bodies are created using World class.

Body body =  world.createBody(bd);
body.createFixture(fd);

The complete code snippet would look like:
//body definition
BodyDef bd = new BodyDef();
bd.position.set(50, 50);  
bd.type = BodyType.DYNAMIC;

//define shape of the body.
CircleShape cs = new CircleShape();
cs.m_radius = 0.5f;  

//define fixture of the body.
FixtureDef fd = new FixtureDef();
fd.shape = cs;
fd.density = 0.5f;
fd.friction = 0.3f;        
fd.restitution = 0.5f;

//create the body and add fixture to it
Body body =  world.createBody(bd);
body.createFixture(fd);
In next post we will learn how to simulate the JBox2D World.

<<JBox2D World                                                Simulating the JBox2D world>>

Tuesday, 13 December 2011

JBox2D Tutorial : JBox2D World


From today I am starting JBox2D tutorial series. In each post I will explain few features of the JBox2D.  I will try to keep each post small and simple.

In today’s post I will explain how to create the JBox2D world.

What is a JBox2D?

JBox2D is a java based physics engine API for game development. This is a java port for a very popular C++ library called Box2d.  This can be used in games to move objects in a natural way. JBox2D works well with moving objects between 0.1 to 1 meters size.  Jbox2D doesn’t have its own UI. It creates an invisible object. We need to attach UI components to these invisible objects. 
             
Creating the JBox2D World

To write any JBox2D program, the first thing we need to do is to create a JBox2d world. World is a collection of bodies, fixtures and constraints. Memory, objects and simulations are managed by the World.

Following is a code snippet for creating a JBox2D World

Vec2 gravity = new Vec2(0.0f, -10.0f);
boolean doSleep = true;
World world = new World(gravity, doSleep);

As you can see in above code snippet, two parameters (Gravity and the doSleep) are passed to the World objects constructor. 

Gravity – gravity is an attraction of the mass for bodies present in the World. As you can see in above snippet, Vec2 object is used for defining the gravity. The first parameter defines the horizontal gravity and second parameter defines the vertical gravity.  In most cases first parameter is set to zero as requirement for horizontal gravity is very rare. If negative value is set for the second parameter then bodies are attracted downwards. And if positive value is set for the second parameter then bodies are attracted upwards.  In most cases negative value is set to the second parameter

doSleep – If doSleep is set to true, JBox2d world will allow bodies to sleep when they come to rest. The sleeping bodies are not part of simulations; it means better performance as body simulations are expensive. In most cases this parameter should be set to true.

I have created small application to understand gravity behavior.  This is the sample video.


Soon I will provide launch URL for this application.  


                                                                              Creating an object body>>


Wednesday, 30 November 2011

Hello World JBox2D with JavaFX 2.0

<<JBox2D Tutorial


This is a simple application to get your hands wet with JBox2D and JavaFX 2. I have chosen JavaFX 2.0 for GUI due to its power and simplicity. In this application user can draw different shapes, these shapes works as a hurdles. When user clicks on the  “Start” button, balls starts falling, bouncing and reacting to the hurdles in a very natural way.

You can click here to launch this applications! If JavaFX 2 runtime is not installed on your  PC then it will prompt you for installation. Launch this application and try drawing different hurdles and see how balls reacts to them. You can also click here to download the source code. Please note this is my first program in JBox2D and JavaFX so it might not be following all coding standards. So, your suggestions and feedback will help me to improve on this, so please leave your comments and rating at the end of this post.

If you are not able to launch the application from above link for any reason then this is a sample video of Hello World JBox2D with JavaFX 2.0application.





These are few sample snapshots of Hello World JBox2D with JavaFX 2.0 application.






JBox2D world, Ground, walls and balls are the main component of this application.

JBox2D World is the main component of any JBox2D application. Memory, objects and simulations are managed by the JBox2D World object. Gravity and the doSleep are two parameters of World object. If doSleep is set to true JBox2D world will allow bodies to sleep when they come to rest.

Ground is a bottom most part of application screen. If ground is not created then balls will travel downwards infinitely. Also left and right walls are created so balls will not move out of the viewable screen area. 

These are the code snippets for Hello World JBox2D with JavaFX 2.0.  Please let me know if you have any queries on some part of code. I will be happy to answer. 

Ball.java


package jfxwithjbox2d;

import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.paint.LinearGradient;
import javafx.scene.shape.Circle;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;

/**
 *
 * @author dilip
 */
public class Ball{

    //JavaFX UI for ball
    public Node node;
    
    //X and Y position of the ball in JBox2D world
    private float posX;
    private float posY;
    
    //Ball radius in pixels
    private int radius;
    
    /**
     * There are three types bodies in JBox2D – Static, Kinematic and dynamic 
     * In this application static bodies (BodyType.STATIC – non movable bodies) 
     * are used for drawing hurdles and dynamic bodies (BodyType.DYNAMIC–movable bodies) 
     * are used for falling balls
     */
    private BodyType bodyType;

    //Gradient effects for balls
    private LinearGradient gradient;
    
    public Ball(float posX, float posY){
        this(posX, posY, Utils.BALL_SIZE, BodyType.DYNAMIC,Color.RED);
        this.posX = posX;
        this.posY = posY;
    }

    public Ball(float posX, float posY, int radius, BodyType bodyType, Color color){
        this.posX = posX;
        this.posY = posY;
        this.radius = radius;
        this.bodyType = bodyType;
        this.gradient = Utils.getBallGradient(color);
        node = create();
    }
    
    /**
     * This method creates a ball by using Circle object from JavaFX and CircleShape from JBox2D
     */
    private Node create(){
        //Create an UI for ball - JavaFX code
        Circle ball = new Circle();
        ball.setRadius(radius);
        ball.setFill(gradient); //set look and feel 
        
        /**
         * Set ball position on JavaFX scene. We need to convert JBox2D coordinates 
         * to JavaFX coordinates which are in pixels.
         */
        ball.setLayoutX(Utils.toPixelPosX(posX)); 
        ball.setLayoutY(Utils.toPixelPosY(posY));
       
        ball.setCache(true); //Cache this object for better performance
        
        //Create an JBox2D body defination for ball.
        BodyDef bd = new BodyDef();
        bd.type = bodyType;
        bd.position.set(posX, posY);
        
        CircleShape cs = new CircleShape();
        cs.m_radius = radius * 0.1f;  //We need to convert radius to JBox2D equivalent
        
        // Create a fixture for ball
        FixtureDef fd = new FixtureDef();
        fd.shape = cs;
        fd.density = 0.9f;
        fd.friction = 0.3f;        
        fd.restitution = 0.6f;

        /**
        * Virtual invisible JBox2D body of ball. Bodies have velocity and position. 
        * Forces, torques, and impulses can be applied to these bodies.
        */
        Body body = Utils.world.createBody(bd);
        body.createFixture(fd);
        ball.setUserData(body);
        return ball;
    }
}


JFXwithJBox2d.java


package jfxwithjbox2d;

import java.util.Random;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyType;

/**
 *
 * @author dilip
 */
public class JFXwithJBox2d extends Application {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Application.launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        
        primaryStage.setTitle("Hello JBox2d World!");
        primaryStage.setFullScreen(false);
        primaryStage.setResizable(false);
        
        final Group root = new Group(); //Create a group for holding all objects on the screen
        final Scene scene = new Scene(root, Utils.WIDTH, Utils.HEIGHT,Color.BLACK);
        
        //Ball array for hold the  balls
        final Ball[] ball = new Ball[Utils.NO_OF_BALLS];
                
        Random r = new Random(System.currentTimeMillis());
        
        /**
         * Generate balls and position them on random locations.  
         * Random locations between 5 to 95 on x axis and between 100 to 500 on y axis 
         */
        for(int i=0;i<Utils.NO_OF_BALLS;i++) {
            ball[i]=new Ball(r.nextInt(90)+5,r.nextInt(400)+100);
        }
     
        //Add ground to the application, this is where balls will land
        Utils.addGround(100, 10);
        
        //Add left and right walls so balls will not move outside the viewing area.
        Utils.addWall(0,100,1,100); //Left wall
        Utils.addWall(99,100,1,100); //Right wall
        
        
        final Timeline timeline = new Timeline();
        timeline.setCycleCount(Timeline.INDEFINITE);

        Duration duration = Duration.seconds(1.0/60.0); // Set duration for frame.
        
        //Create an ActionEvent, on trigger it executes a world time step and moves the balls to new position 
        EventHandler<ActionEvent> ae = new EventHandler<ActionEvent>() {
            public void handle(ActionEvent t) {
                        //Create time step. Set Iteration count 8 for velocity and 3 for positions
                       Utils.world.step(1.0f/60.f, 8, 3); 
                       
                       //Move balls to the new position computed by JBox2D
                       for(int i=0;i<Utils.NO_OF_BALLS;i++) {
                            Body body = (Body)ball[i].node.getUserData();
                            float xpos = Utils.toPixelPosX(body.getPosition().x);
                            float ypos = Utils.toPixelPosY(body.getPosition().y);
                            ball[i].node.setLayoutX(xpos);
                            ball[i].node.setLayoutY(ypos);
                       }
           }
        };

        
        /**
         * Set ActionEvent and duration to the KeyFrame. 
         * The ActionEvent is trigged when KeyFrame execution is over. 
         */
        KeyFrame frame = new KeyFrame(duration, ae, null,null);

        timeline.getKeyFrames().add(frame);

        //Create button to start simulation.
        final Button btn = new Button();
        btn.setLayoutX((Utils.WIDTH/2));
        btn.setLayoutY((Utils.HEIGHT-30));
        btn.setText("Start");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent event) {
                        timeline.playFromStart(); 
                        btn.setVisible(false);
            }
        });

        //Add button to the root group
        root.getChildren().add(btn);

        //Add all balls to the root group
        for(int i=0;i<Utils.NO_OF_BALLS;i++) {
            root.getChildren().add(ball[i].node);
        }
        
        //Draw hurdles on mouse event.
        EventHandler<MouseEvent> addHurdle = new EventHandler<MouseEvent>(){
            public void handle(MouseEvent me) {
                    //Get mouse's x and y coordinates on the scene
                    float dragX = (float)me.getSceneX();
                    float dragY = (float)me.getSceneY();
                    
                    //Draw ball on this location. Set balls body type to static.
                    Ball hurdle = new Ball(Utils.toPosX(dragX), Utils.toPosY(dragY),2,BodyType.STATIC,Color.BLUE);
                    //Add ball to the root group
                    root.getChildren().add(hurdle.node);
            }
        };
        
        scene.setOnMouseDragged(addHurdle);
        
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}



Utils.java


import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;

/**
 *
 * @author dilip
 */
public class Utils {
    //Create a JBox2D world. 
    public static final World world = new World(new Vec2(0.0f, -10.0f), true);
    
    //Screen width and height
    public static final int WIDTH = 800;
    public static final int HEIGHT = 600;
    
    //Ball radius in pixel
    public static final int BALL_SIZE = 8;
    
    //Total number of balls
    public final static int NO_OF_BALLS = 400; 
    
    //Ball gradient
    private final static LinearGradient BALL_GRADIENT = new LinearGradient(0.0, 0.0, 1.0, 0.0, true, CycleMethod.NO_CYCLE, new Stop[] { new Stop(0, Color.WHITE), new Stop(1, Color.RED)});
    
    //This method adds a ground to the screen. 
    public static void addGround(float width, float height){
        PolygonShape ps = new PolygonShape();
        ps.setAsBox(width,height);
        
        FixtureDef fd = new FixtureDef();
        fd.shape = ps;

        BodyDef bd = new BodyDef();
        bd.position= new Vec2(0.0f,-10f);

        world.createBody(bd).createFixture(fd);
    }
    
    //This method creates a walls. 
    public static void addWall(float posX, float posY, float width, float height){
        PolygonShape ps = new PolygonShape();
        ps.setAsBox(width,height);
        
        FixtureDef fd = new FixtureDef();
        fd.shape = ps;
        fd.density = 1.0f;
        fd.friction = 0.3f;    

        BodyDef bd = new BodyDef();
        bd.position.set(posX, posY);
        
        Utils.world.createBody(bd).createFixture(fd);
    }
    
    //This gives a look and feel to balls
    public static LinearGradient getBallGradient(Color color){
        if(color.equals(Color.RED))
            return BALL_GRADIENT;
        else
            return new LinearGradient(0.0, 0.0, 1.0, 0.0, true, CycleMethod.NO_CYCLE, new Stop[] { new Stop(0, Color.WHITE), new Stop(1, color)});
    }
   
    //Convert a JBox2D x coordinate to a JavaFX pixel x coordinate
    public static float toPixelPosX(float posX) {
        float x = WIDTH*posX / 100.0f;
        return x;
    }

    //Convert a JavaFX pixel x coordinate to a JBox2D x coordinate
    public static float toPosX(float posX) {
        float x =   (posX*100.0f*1.0f)/WIDTH;
        return x;
    }
    
    //Convert a JBox2D y coordinate to a JavaFX pixel y coordinate
    public static float toPixelPosY(float posY) {
        float y = HEIGHT - (1.0f*HEIGHT) * posY / 100.0f;
        return y;
    }
    
    //Convert a JavaFX pixel y coordinate to a JBox2D y coordinate
    public static float toPosY(float posY) {
        float y = 100.0f - ((posY * 100*1.0f) /HEIGHT) ;
        return y;
    }
    
    //Convert a JBox2D width to pixel width
    public static float toPixelWidth(float width) {
        return WIDTH*width / 100.0f;
    }
    
    //Convert a JBox2D height to pixel height
    public static float toPixelHeight(float height) {
        return HEIGHT*height/100.0f;
    }
 
}

Please try this application and let me know your feedback/queries. Let me know if you find it difficult to build and run this application, I will be happy to help you.

JavaFX 2 books



Tuesday, 22 November 2011

Web Performance With Flash And HTML5

Web Performance With Flash And HTML5

By Kevin Darwin


So, Flash is a vibrant platform that offers a high degree of rich functionality, some of it best-of-breed. Sites and applications developed with Flash are available to virtually every non-mobile Web user, and likely to be available for most mobile users before long, except for those using Apple products.
HTML5 is an exciting, evolving Web coding language with extensive support from all of the Internet's heavy hitters - Google, Apple, Microsoft (albeit slowly), Mozilla, Opera, and yes, even Adobe. It promises to simplify and speed-up both the Web development and Web browsing experience, has native capability to handle multimedia and rich Internet functionality without external plugins, and has ambitions to be the technology that finally bridges all devices, mobile included.
A number of leading Internet voices argue that it's not an either-or scenario. Flash is the best platform for some applications, and HTML5 for others. But how is a developer to decide what the best technology is for the project that's in front of them? Assuming A) that the technology can perform the desired function and B) that the end product is available on user devices, it gets down to a matter of performance.
See HTML5 run

Because it's an open technology (with the possible exception of video), HTML5 promises to lend itself to the robust performance monitoring, measurement, and diagnosis that's been available for other open Web technologies. And it is expected that the advances found in HTML5 will, if used judiciously, be a boon to overall page performance.
Aside from any inherent speed gains, another big advantage of HTML5 vis-�-vis Flash is that, because it is an open technology, real browsers can be deployed in the field to measure and record virtually all of its activity and performance. As has been the case with HTML in all its flavors, and JavaScript, AJAX, etc., performance issues are transparent, and problem sources are more readily visible. There are far fewer black holes that require deep diagnosis.
One of the most anticipated features of HTML5 - and one of the most debated - is the ability to handle audio and video natively in the browser. A few simple lines of code is all it takes to embed A/V files, and, once browsers are updated to handle HTML5, the user would need no special plug-ins to run the files.
As mentioned above, Flash is by far the dominant force in online video. But HTML5 is already making inroads. Vimeo has introduced HTML5 video capability in a new universal player, enabling its videos to be viewed on mobile devices, including those from Apple. And Google has introduced a new, HTML5 mobile version of its site, m.youtube.com, which is promoted as delivering better video with a better interface than Apple's own YouTube app.
Keynote Systems - Web performance
mobile website testing, web load testing and measurement of your web sites online performance from inside and outside the firewall all the way to the actual end-user.

Article Source: http://EzineArticles.com/?expert=Kevin_Darwin


http://EzineArticles.com/?Web-Performance-With-Flash-And-HTML5&id=6696284








Sunday, 20 November 2011

Snapshot: The Wacky History Behind 3D Television Technology


Snapshot: The Wacky History Behind 3D Television Technology



Snapshot: The Wacky History Behind 3D Television Technology

By Justin Hanus



How did our path to 3D TV get started? Was it because of some fluke? Or was this the plan all along?

Below I'll outline the history of 3D TV technology in this article.

Prior to 1900

The road to 3D TV technology all got started way back in 1844 when David Brewster invented the stereoscope, which allowed photographed objects to be seen in 3D.

Fast forward 11 years and the Kinematascope was born in 1855 allowing a camera to capture 3D images in motion.

Right before the turn of the century, renowned British film maker William Friese-Greene took things a step further by securing a patent for the process of 3D movie production. His patent made it possible for a person to see a 3D image from two films positioned perpendicularly to each other.

1900 to 1935

Around 1915, film makers produced the world's first 3D movie, which could be viewed via 3D glasses with two colored lenses.

This in turn became a prelude to Robert Elder and Harry Fairall's mainstream film masterpiece 'The Power of Love', which is known as the first 3D film ever produced.

This was followed by the first color movie utilizing 3D technology in 1935.

1935 to 1960

Due to World War II there wasn't much in terms of the advancement of 3D technology until John Baird showcased the first ever 3D TV to the world in 1958. His research which eventually led to his creation of the 3D TV was heavily influenced by the success of 3D movies (Bwana Devil, House of Wax, and Dial M for Murder) that were released in the early 1950s.

1960 to 1970

With the evolution of 3D technology known as Space Vision, which takes two images and puts them one on top of another on a strip, a single projector could be used instead of two cameras making the production of 3D movies all the easier. As a side note, the first movie created with Space Vision was 'The Bubble' although it was not received well by critics.

1970 to 1990

In 1970, Stereovision was developed by Chris Condon and Allan Silliphant using 35mm film strip to create 3D imagery.

The 1980s saw such titles as Jaws and Friday the 13th part III released as 3D versions.

IMAX was born allowing viewers to watch 3D movies with the absence of eye fatigue.

1990 to 2010

IMAX continued on with its popularity to audiences worldwide by releasing two highly acclaimed movies 'Into the Deep' and 'Wings of Courage'.

Hollywood finally got into the act once 2000 rolled around by releasing Ghosts of the Abyss, Spy Kids 3D: Game Over and The Polar Express.

By 2009, 3D technology finally made it into our homes from the theaters with various broadcasters jumping on the bandwagon.

2010 to???

The sky is the limit as we move forward to a 3D technology experience that will be like none other.

For more relevant information about 3D TVs, click here: 3D TV.


Article Source: http://EzineArticles.com/?expert=Justin_Hanus


http://EzineArticles.com/?Snapshot:-The-Wacky-History-Behind-3D-Television-Technology&id=6693974







Friday, 18 November 2011

Build Your Own Robots at Home


Build Your Own Robots at Home



Build Your Own Robots at Home

By James Cott



The Time Is Right

The field of hobby robotics is more exciting today than ever before. The day when you will have a humanoid, walking, talking robot in your home that will do your cooking and cleaning looms ever closer. Short of having a real robotic maid or butler, there are many other options that can be built today on just about any budget. If you really want to enjoy a fun, reasonably priced hobby, you should try to build your own robots.

There are many reasons why it makes sense create a robot from scratch rather than buying pre-made ones.

Affordable

The technology that exists today staggers the mind in not only how advanced it has become, but also in how cheap it is to purchase. There are microcontrollers today that literally replace a room-sized computer of the previous century. The cost for such controllers can be well under $100 for a more-than-capable unit. Some can be purchased as kits to assemble and learn about computer architecture and electronics, others are pre-built units and some even come as single boards that are ready to "plug and play."

Sensors for hobby robots have increased in functionality while they have also reduced in price. It has gotten to the point where advanced sensors like ultrasonic range detectors and infrared distance sensors even come with robotic toys like the Lego Mindstorms kits. The accuracy of these sensors is astonishing and affords the robotic hobbyist with very high-precision instruments capable of providing ample functionality on even an entry-level robot.

To program or Not

It was formerly the case that many of these microcontrollers required a high-level understanding of computers, binary math and assembler language programming to operate. This restricted the field to schooled adults or older children with a great deal of mathematics background.

Today, many of these robotic products come with a computer interface that allows "building block" style components to be visually ordered on-screen in a graphical editor which allows even younger children the ability to understand logic programming and control-flow logic structures in an easy to understand format. These same programs usually also allow code-level programming to be performed as the student gains an understanding of the high-level logic. This allows them to get "closer to the metal" of the processor's native language and architecture while providing skill-building opportunities.

Even more interesting for some, is that many of the common hobby robots have their loyal fan following, usually very technical people, who like to push the limits of the platforms. Often you can find compilers or interpreters written to support programming in other languages. This allows the clever and curious inventors to use their robotic for other purposes while learning ever more technical skills. You can often find more than one website devoted to groups like these.

Attack of the Toys

If you are not as interested in learning programming software, you can also take existing toys and use them as a springboard to more advanced uses. Toys like the Furby of yesteryear gained a following by inspired experimenters who took them apart, rewired them, and put them back together in their own vision, to perform functions not intended by the original manufacturers.

Radio controlled toys are also an excellent springboard for robot development as they take care of a common problem with robots, locomotion. One of the persistent problems creating a robot from scratch is how to propel your robot accurately around the room. Motors require careful selection, knowledge of velocity, gearing and other complex formulas in order to operate accurately. Robots like the iRobot Roomba have solved these problems and thus it makes sense to reuse the work they have done rather than re-inventing the wheel. Pun intended!

Also, battery power can be tricky to learn and many of these platforms take the guesswork out of creating rechargable platforms that won't run out of juice after a five minute stroll around your home.

Reusing these technologies allows the experiment to concentrate on higher-level functions like navigation, vision and other robotic applications that may be more appealing to the robotics enthusiast.

Finally

If you have been sitting on the sidelines waiting for the opportunity to dive into hobby robotics; I hope you don't wait any longer, but decide to build your own robot this year. There has never been a better time to get started.

Find more valuable resources, tutorials and information for anyone interested in getting started with the hobby of robotics at James' Blog http://www.Robotics-Toys.com (http://www.robotics-toys.com). You can learn more about the technologies and even submit your robot for inclusion into our online gallery of robots. Please join us for news, reviews. We try to make learning fun!


Article Source: http://EzineArticles.com/?expert=James_Cott


http://EzineArticles.com/?Build-Your-Own-Robots-at-Home&id=3363430







Best Selling Robot Kits

Best Selling Robot Kits

By Lance D Jepsen


Robotic toys are a lot of fun and entertainment and they can be fantastic educational toys also. Robotic toys have been developed and refined quite a bit since Leonardo da Vinci's model, and the first robot toy was manufactured in 1939 when Westinghouse created Elektro, a human-like robot, and his robot dog companion Sparky. A smaller version, the Omnibot 2000, was a toy robot developed during the 1980's.
A company called WowWee created the most advanced human-like robotic toy hailed the Robosapien in 2004. Priced at under $99 (US), the first cost-effective, mass-produced humanoid sold four million units and gave life to the consumer robot industry.
The robot market has continued to grow at a very rapid pace. In the present day there is an increasing desire of buying and using robots whether it's a toy for our children, a security system or a lawn mower, adults and kids equally share in using them.
Popular Robotic Toys

The Gaming Roboni-i




Robotic toys are fun to own, but they don't actually boast the same multi player functionality that video games presently have. That might all change with the The Gaming Roboni-i, Earth's first-ever programmable gaming robot.
It's simple to customize and is packed with games; play by yourself or against friends with like robots. You can even create your own games, or download games others have made. To set up a multi player game, the robots must link to each other in a group so that they can identify each other. When this occurs, you're able to intermingle with other The Gaming Roboni-i units and play games with them.

Robosapien



Robosapien is a highly developed mixture of personality with technology. Loaded with attitude and brains, Robosapien is the first robot based on the technology of applied biomorphic robotics. The Robosapien is capable of make out objects and even skin tones and recognize when its owner walks into the room. In addition, Robosapien also has internal incline sensors that can end most functions when he is located in unusual positions, such as lying on its back. The nice thing about this humanoid is the ability for him to stand up in instances where he tips over. Robosapien is a programmable, rapid moving robot. The Robosapien has real multi-speed rapid dynamic running, turning, and walking.
Robosapien has four programming modes: right sensor, left sensor, sonic and master program. The right and left sensors are triggered when sensors on their matching sides are triggered, the sonic sensor is activated when the robot hears a sharp noise (and is in the Listen mode), and the master program is triggered from the remote control.

Lego Mindstorms



Lego Mindstorms allows you to make and program robots that can do just about anything. Lego Mindstorms give you the ability to put together your own robots and program them to carry out all kinds of actions. Version 1.0 RCX bricks feature a power adapter jack that allows nonstop operation rather than the narrow operation time when using batteries. In version 2.0 (as well as later 1.0s included in the RIS 1.5), the power adapter jack was taken off. Version 2.0 of the robotics invention kit includes a programming environment that puts a lot of professional programming products to shame. It is easy to understand why a lot of schools are standardizing on the mindstorms kits to teach classes in the field of robotics.

Wrex the Dog

Wrex the Dog's nose functions like a stop button when he is moving and a random activities selection button when he is not. Wrex the Dog is able to scoot about, play and follow commands and run like a real dog. He can turn his head, twitch his ears, pant and even wag his tail.

The First Robotic Arthropod Known As Roboquad



The First Robotic Arthropod Known As Roboquad is a four-legged, spider-like robot with unparalleled mobility and consciousness. The The First Robotic Arthropod Known As Roboquad is built with advanced sensory awareness, helping it respond immediately to the surrounding environment and follow a moving object in any direction, including forward, backwards, and sideways. The First Robotic Arthropod Known As Roboquad, by WowWee Robotics, claims the honor of being the first true robotic arthropod. It is fundamentally an animated robot that has multi-directional movement capabilities and highly developed sensory perception.
The First Robotic Arthropod Known As Roboquad even has an extended battery life for extended missions. Capable of spotting movement from up to 6 feet away with a IRscanner, he can also hunt for and navigate doorways, and distinguish table edges. When the lights go out, The First Robotic Arthropod Known As Roboquad can continue operating, turning on his head-mounted LEDs which lets it move in the dark. The First Robotic Arthropod Known As Roboquad becomes crabby, happy, attentive, standoffish and jumpy as he walks about on any type of floor. The First Robotic Arthropod Known As Roboquad can even dance.

Tread Based Roborover



Tread Based Roborover appears to be WowWee's 2009 successor to their massively popular Tri-Bot robot which appeared first in 2008. The primary difference is that Tread Based Roborover has treads rather than wheels.
Tread Based Roborover is enabled with object recognition. He has forward and rear sensors that prevent him from bumping in to walls. Tread Based Roborover's tread wheels let it maneuver over objects up to a 15-degree gradient, or about an inch high. Tread Based Roborover is an lively tread based friend with a timid but inquisitive nature, his personality grows and becomes more self-confident as you play with him. He is always eager to be on the move or play games with you. Tread Based Roborover has several distinct modes: explore, lookout, standby and sleep. Explore mode does just what you would expect; Tread Based Roborover navigates around the room autonomously while it avoids running into objects. Sensor-based LED headlights will automatically turn on if it's dark. The Tread Based Roborover features a mixture of vocal content and driving-based games.

The Roving Rovio Security Robot



The Roving Rovio Security Robot, allows you to be in two places at one time! WowWee The Roving Rovio Security Robot includes a WiFi connection which allows you drive it from anywhere in the world given that you have a web capable mobile phone or a PC with internet connection. The Roving Rovio Security Robot's built-in LED headlight will help you steer it even in faintly lit locations, so you will always know what is going on at home or at the office. Its skull-mounted, movable camera and wide range of vision allow you to see and hear precisely what The Roving Rovio Security Robot sees and hears, on your computer screen, anyplace in the world!
No need to be concerned about The Roving Rovio Security Robot running low on power while you're gone - the self-docking feature allows you to send The Roving Rovio Security Robot back to the charging dock to recharge, with the tap of a button in your internet browser. Once it's done charging, The Roving Rovio Security Robot is ready to continue watching your home or office.
Find out more about the fascinating world of robotics as well as popular robots that sell for less than $30 by going to buy robot toy [http://www.buyrobotslave.com/buy-robot-toy/robot-guide-least-costly-robots].

Article Source: http://EzineArticles.com/?expert=Lance_D_Jepsen


http://EzineArticles.com/?Best-Selling-Robot-Kits&id=3758692








Thursday, 17 November 2011

Getting started with HTML5 – Input Types


I had my first hands on experience with HTML5 and I am quite impressed with it.  HTML5 will definitely change the way we build web sites and the way we access them. Most popular browsers and mobile devices have already started supporting some HTML5 features.

To start with, I will cover few basic but interesting features of HTML5.

Please note, I have used Google Chrome browser to test these features.

HTML5 doctype 

To use HTML5, you need to place <!DOCTYPE html> code snippet on the first line of your HTML file.

For example:

<!DOCTYPE html>
<html>
<body>
<form  method="get">
     Name : <input type="text"  />
</form>
</body>
</html>

HTML5 Input Types

Many new input types are introduced in HTML5. Some of the most interesting input types are as below.

Number -   The number input types is a field which should contain numeric value.  The number input type supports a following validation attributes.
            min – minimum value allowed
            max – maximum value allowed
            step -  Allowed number series between min and max. it means if min=0, max=10 and step=2 then allowed field values will be 0,2,4,6….10.

Example:

Even Numbers: <input type=”number” name=”Even” min=”0” max=”10” step=”2”/>

In above example value less than 0 or greater than 10 or odd values like 3,5,7 are considered as invalid values.


Range – The range input type is very similar to number input type. However, it is displayed as slider bar. The range input type supports a following validation attributes.
            min – minimum value allowed
            max – maximum value allowed
            step -  This defines a jump for slider bar. It means if step=5 then slider slides a 5 points at a time.

Example:

Zoom : 0 <input type="range" name="zoom" min="0" max="100" step="5"/> 100

In browser, this is represented as below.


Email – The email input type is a field which should contain email address as value. On form submit, value of email field is automatically validated.

Example:

Personal Email: <input type="email" name="personalEmail"/>

<input type="submit"/>

If user enters an incomplete/invalid email address then following warning message is displayed.


URL – The url input type is a field which should contain URL address as a value. On form submit, value of url field is automatically validated.

Example:

URL: <input type="url" name="myUrl"/>

<input type="submit"/>

If user enters an incomplete/invalid URL address then following warning message is displayed.


Date – The date input type field should contain date as a value. On form submit this field is validated automatically.

Example:

Date: <input type="date" name="date"/>

In browser, this is represented as below.


Month – The month input type filed is used for selecting year and month.  On form submit this field is validated automatically.

Example:

Month: <input type="month" name="month"/>

In browser, this is represented as below.


Week – The week input type filed is used for selecting year and week.  On form submit this field is validated automatically.

Example:

Week: <input type="week" name="week"/>

In browser, this is represented as below.


Time - The time input type filed is used for selecting hours and minutes.  On form submit this field is validated automatically.

Example:

Time: <input type="time" name="time"/>

In browser, this is represented as below.


Datetime - The datetime input type filed is used for selecting year, month, day, hours and minutes (UTC time).  On form submit this field is validated automatically.

Example:

Date Time: <input type="datetime" name="d_time"/>

In browser, this is represented as below.


Datetime-local  - The datetime-local input type filed is used for selecting year, month, day, hours and minutes (local time).  On form submit this field is validated automatically.

Example:

Date Time Local: <input type="datetime-local" name="d_time_local"/>

In browser, this is represented as below.


……………………………………………………………………………………………..

So, today I have covered few important HTML5 input types. This is only a tip of iceberg. I will cover few more  HTML5 features in my next post. Meanwhile I would recommend you to read Head First HTML5 Programming: Building Web Apps with JavaScript.

Please feel free to post your queries.