Class World
- Author:
- Daniel Murphy
-
Field Summary
FieldsModifier and TypeFieldDescriptionintstatic final intprotected ContactManagerintprotected intstatic final intstatic final intstatic final intstatic final int -
Constructor Summary
ConstructorsConstructorDescriptionConstruct a world object.Construct a world object.World(Vec2 gravity, WorldPool pool, BroadPhase broadPhase) Construct a world object.World(Vec2 gravity, WorldPool pool, BroadPhaseStrategy strategy) Construct a world object. -
Method Summary
Modifier and TypeMethodDescriptionvoidCall this after you are done with time steps to clear the forces.floatCompute the kinetic energy that can be lost by damping forcecreateBody(BodyDef def) create a rigid body given a definition.createJoint(JointDef def) create a joint to constrain bodies together.intCreate a particle whose properties have been defined.Create a particle group whose properties have been defined.voiddestroyBody(Body body) Destroy a rigid body given a definition.voiddestroy a joint.voiddestroyParticle(int index) Destroy a particle.voiddestroyParticle(int index, boolean callDestructionListener) Destroy a particle.voidDestroy particles in a group without enabling the destruction callback for destroyed particles.voiddestroyParticlesInGroup(ParticleGroup group, boolean callDestructionListener) Destroy particles in a group.intdestroyParticlesInShape(Shape shape, Transform xf) Destroy particles inside a shape without enabling the destruction callback for destroyed particles.intdestroyParticlesInShape(Shape shape, Transform xf, boolean callDestructionListener) Destroy particles inside a shape.voidCall this to draw shapes and other debug draw data.booleanGet the flag that controls automatic clearing of forces after each time step.intGet the number of bodies.Get the world body list.intGet the number of contacts (each may have 0 or more contact points).Get the world contact list.Get the contact manager for testing purposesGet the global gravity vector.intGet the number of joints.Get the world joint list.intGet contacts between particles and bodiesintGet contacts between particlesintGet the number of particles.floatGet damping for particlesfloatGet the particle density.int[]Get the particle data.floatGet the particle gravity scale.intGet the number of particle groups.Get the world particle group list.intGet the maximum number of particles.Vec2[]floatGet the particle radius.Object[]Vec2[]getPool()intGet the number of broad-phase proxies.intGet the balance of the dynamic tree.intGet the height of the dynamic tree.floatGet the quality of the dynamic tree.booleanbooleanbooleanisLocked()Is the world locked (in the middle of a time step).booleanbooleanbooleanvoidjoinParticleGroups(ParticleGroup groupA, ParticleGroup groupB) Join two particle groups.popContact(Fixture fixtureA, int indexA, Fixture fixtureB, int indexB) voidpushContact(Contact contact) voidqueryAABB(ParticleQueryCallback particleCallback, AABB aabb) Query the world for all particles that potentially overlap the provided AABB.voidqueryAABB(QueryCallback callback, ParticleQueryCallback particleCallback, AABB aabb) Query the world for all fixtures and particles that potentially overlap the provided AABB.voidqueryAABB(QueryCallback callback, AABB aabb) Query the world for all fixtures that potentially overlap the provided AABB.voidraycast(ParticleRaycastCallback particleCallback, Vec2 point1, Vec2 point2) Ray-cast the world for all particles in the path of the ray.voidraycast(RayCastCallback callback, ParticleRaycastCallback particleCallback, Vec2 point1, Vec2 point2) Ray-cast the world for all fixtures and particles in the path of the ray.voidraycast(RayCastCallback callback, Vec2 point1, Vec2 point2) Ray-cast the world for all fixtures in the path of the ray.voidsetAllowSleep(boolean flag) voidsetAutoClearForces(boolean flag) Set flag to control automatic clearing of forces after each time step.voidsetContactFilter(ContactFilter filter) Register a contact filter to provide specific control over collision.voidsetContactListener(ContactListener listener) Register a contact event listener.voidsetContinuousPhysics(boolean flag) Enable/disable continuous physics.voidsetDebugDraw(DebugDraw debugDraw) Register a routine for debug drawing.voidsetDestructionListener(DestructionListener listener) Register a destruction listener.voidsetGravity(Vec2 gravity) Change the global gravity vector.voidsetParticleColorBuffer(ParticleColor[] buffer, int capacity) voidsetParticleDamping(float damping) Damping is used to reduce the velocity of particles.voidsetParticleDensity(float density) Change the particle density.voidvoidsetParticleFlagsBuffer(int[] buffer, int capacity) Set a buffer for particle data.voidsetParticleGravityScale(float gravityScale) Change the particle gravity scale.voidsetParticleMaxCount(int count) Set the maximum number of particles.voidsetParticlePositionBuffer(Vec2[] buffer, int capacity) voidsetParticleRadius(float radius) Change the particle radius.voidsetParticleUserDataBuffer(Object[] buffer, int capacity) voidsetParticleVelocityBuffer(Vec2[] buffer, int capacity) voidsetSleepingAllowed(boolean sleepingAllowed) voidsetSubStepping(boolean subStepping) voidsetWarmStarting(boolean flag) Enable/disable warm starting.voidstep(float timeStep, int velocityIterations, int positionIterations) Take a time step.
-
Field Details
-
WORLD_POOL_SIZE
public static final int WORLD_POOL_SIZE- See Also:
-
WORLD_POOL_CONTAINER_SIZE
public static final int WORLD_POOL_CONTAINER_SIZE- See Also:
-
NEW_FIXTURE
public static final int NEW_FIXTURE- See Also:
-
LOCKED
public static final int LOCKED- See Also:
-
CLEAR_FORCES
public static final int CLEAR_FORCES- See Also:
-
activeContacts
public int activeContacts -
contactPoolCount
public int contactPoolCount -
flags
protected int flags -
contactManager
-
-
Constructor Details
-
World
Construct a world object.- Parameters:
gravity- The world gravity vector.
-
World
Construct a world object.- Parameters:
gravity- The world gravity vector.pool- The world pool that provides pooling for all objects used in the engine.
-
World
Construct a world object.- Parameters:
gravity- The world gravity vector.pool- The world pool that provides pooling for all objects used in the engine.strategy- The broad phase strategy.
-
World
Construct a world object.- Parameters:
gravity- The world gravity vector.
-
-
Method Details
-
setAllowSleep
public void setAllowSleep(boolean flag) -
setSubStepping
public void setSubStepping(boolean subStepping) -
isSubStepping
public boolean isSubStepping() -
isAllowSleep
public boolean isAllowSleep() -
getDestructionListener
-
getParticleDestructionListener
-
setParticleDestructionListener
-
popContact
-
pushContact
-
getPool
-
setDestructionListener
Register a destruction listener. The listener is owned by you and must remain in scope. -
setContactFilter
Register a contact filter to provide specific control over collision. Otherwise, the default filter is used (_defaultFilter). The listener is owned by you and must remain in scope. -
setContactListener
Register a contact event listener. The listener is owned by you and must remain in scope. -
setDebugDraw
Register a routine for debug drawing. The debug draw functions are called inside with World.DrawDebugData method. The debug draw object is owned by you and must remain in scope. -
createBody
create a rigid body given a definition. No reference to the definition is retained.- Warning:
- This function is locked during callbacks.
-
destroyBody
Destroy a rigid body given a definition. No reference to the definition is retained. This function is locked during callbacks.- Warning:
- This automatically deletes all associated shapes and joints., This function is locked during callbacks.
-
createJoint
create a joint to constrain bodies together. No reference to the definition is retained. This may cause the connected bodies to cease colliding.- Warning:
- This function is locked during callbacks.
-
destroyJoint
destroy a joint. This may cause the connected bodies to begin colliding.- Warning:
- This function is locked during callbacks.
-
step
public void step(float timeStep, int velocityIterations, int positionIterations) Take a time step. This performs collision detection, integration, and constraint solution.Box2D uses a computational algorithm called an integrator. Integrators simulate the physics equations at discrete points of time. This goes along with the traditional game loop where we essentially have a flip book of movement on the screen. So we need to pick a time step for Box2D. Generally physics engines for games like a time step at least as fast as 60Hz or 1/60 seconds. You can get away with larger time steps, but you will have to be more careful about setting up the definitions for your world. We also don't like the time step to change much. A variable time step produces variable results, which makes it difficult to debug.
In addition to the integrator, Box2D also uses a larger bit of code called a constraint solver. The constraint solver solves all the constraints in the simulation, one at a time. A single constraint can be solved perfectly. However, when we solve one constraint, we slightly disrupt other constraints. To get a good solution, we need to iterate over all constraints a number of times.
There are two phases in the constraint solver: a velocity phase and a position phase. In the velocity phase the solver computes the impulses necessary for the bodies to move correctly. In the position phase the solver adjusts the positions of the bodies to reduce overlap and joint detachment. Each phase has its own iteration count. In addition, the position phase may exit iterations early if the errors are small.
The suggested iteration count for Box2D is 8 for velocity and 3 for position. You can tune this number to your liking, just keep in mind that this has a trade-off between performance and accuracy. Using fewer iterations increases performance but accuracy suffers. Likewise, using more iterations decreases performance but improves the quality of your simulation.
Note that the time step and the iteration count are completely unrelated. An iteration is not a sub-step. One solver iteration is a single pass over all the constraints within a time step. You can have multiple passes over the constraints within a single time step.
Source: Box2D 2.4.1 Hello Box2D
To make a realistic looking simulation, you will generally set the timeStep value to match the number of times per second you will be calling the world's Step() function in your game.
The velocity iterations and position iterations settings affect the way bodies will react when they collide. Typically in Box2D when a collision between two objects is detected, those objects are overlapping (stuck into other) and some calculation needs to be done to figure out how each body should move or rotate so that they are not overlapping any more. Making these values higher will give you a more correct simulation, at the cost of some performance.
Firstly, these values are only relevant to collision resolution, so if nothing is colliding then they are not used at all. When two things collide, to resolve the collision (push both bodies so they don't overlap any more) they need to have their position and velocity changed. The need for changing the position should be obvious - this is to correct the overlap. The velocity also needs to be changed, for example to make sure that a ball bounces off a wall correctly, or to make something rotate if it is hit off-center.
The exact details of which body should move where, what their new velocities should be, whether their angular velocity should also be affected etc, is handled by an iterative solver. This means that the calculation does not give you a perfect result the first time, but each time you do it the result gets more accurate.
- Parameters:
timeStep- The amount of time to simulate, this should not vary.velocityIterations- The number of iterations in the velocity phase of the constraint solver.positionIterations- The number of iterations in the position phase of the constraint solver.
-
clearForces
public void clearForces()Call this after you are done with time steps to clear the forces. You normally call this after each call to Step, unless you are performing sub-steps. By default, forces will be automatically cleared, so you don't need to call this function. -
drawDebugData
public void drawDebugData()Call this to draw shapes and other debug draw data. -
queryAABB
Query the world for all fixtures that potentially overlap the provided AABB.- Parameters:
callback- A user implemented callback class.aabb- The query box. The axis-aligned bounding box.
-
queryAABB
Query the world for all fixtures and particles that potentially overlap the provided AABB.- Parameters:
callback- A user implemented callback class.particleCallback- A callback for particles.aabb- The query box. The axis-aligned bounding box.
-
queryAABB
Query the world for all particles that potentially overlap the provided AABB.- Parameters:
particleCallback- The callback for particles.aabb- The query box. The axis-aligned bounding box.
-
raycast
Ray-cast the world for all fixtures in the path of the ray. Your callback controls whether you get the closest point, any point, or n-points. The ray-cast ignores shapes that contain the starting point.- Parameters:
callback- A user implemented callback class.point1- The ray starting point.point2- The ray ending point.
-
raycast
public void raycast(RayCastCallback callback, ParticleRaycastCallback particleCallback, Vec2 point1, Vec2 point2) Ray-cast the world for all fixtures and particles in the path of the ray. Your callback controls whether you get the closest point, any point, or n-points. The ray-cast ignores shapes that contain the starting point.- Parameters:
callback- A user implemented callback class.particleCallback- The particle callback class.point1- The ray starting pointpoint2- The ray ending point
-
raycast
Ray-cast the world for all particles in the path of the ray. Your callback controls whether you get the closest point, any point, or n-points.- Parameters:
particleCallback- The particle callback class.point1- The ray starting pointpoint2- The ray ending point
-
getBodyList
Get the world body list. With the returned body, use Body.getNext to get the next body in the world list. A null body indicates the end of the list.- Returns:
- The head of the world body list.
-
getJointList
Get the world joint list. With the returned joint, use Joint.getNext to get the next joint in the world list. A null joint indicates the end of the list.- Returns:
- The head of the world joint list.
-
getContactList
Get the world contact list. With the returned contact, use Contact.getNext to get the next contact in the world list. A null contact indicates the end of the list.- Returns:
- The head of the world contact list.
- Warning:
- contacts are created and destroyed in the middle of a time step. Use ContactListener to avoid missing contacts.
-
isSleepingAllowed
public boolean isSleepingAllowed() -
setSleepingAllowed
public void setSleepingAllowed(boolean sleepingAllowed) -
setWarmStarting
public void setWarmStarting(boolean flag) Enable/disable warm starting. For testing. -
isWarmStarting
public boolean isWarmStarting() -
setContinuousPhysics
public void setContinuousPhysics(boolean flag) Enable/disable continuous physics. For testing. -
isContinuousPhysics
public boolean isContinuousPhysics() -
getProxyCount
public int getProxyCount()Get the number of broad-phase proxies. -
getBodyCount
public int getBodyCount()Get the number of bodies. -
getJointCount
public int getJointCount()Get the number of joints. -
getContactCount
public int getContactCount()Get the number of contacts (each may have 0 or more contact points). -
getTreeHeight
public int getTreeHeight()Get the height of the dynamic tree. -
getTreeBalance
public int getTreeBalance()Get the balance of the dynamic tree. -
getTreeQuality
public float getTreeQuality()Get the quality of the dynamic tree. -
setGravity
Change the global gravity vector. -
getGravity
Get the global gravity vector. -
isLocked
public boolean isLocked()Is the world locked (in the middle of a time step). -
setAutoClearForces
public void setAutoClearForces(boolean flag) Set flag to control automatic clearing of forces after each time step. -
getAutoClearForces
public boolean getAutoClearForces()Get the flag that controls automatic clearing of forces after each time step. -
getContactManager
Get the contact manager for testing purposes -
getProfile
-
createParticle
Create a particle whose properties have been defined. No reference to the definition is retained. A simulation step must occur before it's possible to interact with a newly created particle. For example, DestroyParticleInShape() will not destroy a particle until Step() has been called.- Returns:
- The index of the particle.
- Warning:
- This function is locked during callbacks.
-
destroyParticle
public void destroyParticle(int index) Destroy a particle. The particle is removed after the next step. -
destroyParticle
public void destroyParticle(int index, boolean callDestructionListener) Destroy a particle. The particle is removed after the next step.- Parameters:
index- Index of the particle to destroy.callDestructionListener- Whether to call the destruction listener just before the particle is destroyed.
-
destroyParticlesInShape
Destroy particles inside a shape without enabling the destruction callback for destroyed particles. This function is locked during callbacks. For more information seeDestroyParticleInShape(Shape&, Transform&,bool).- Parameters:
shape- Shape which encloses particles that should be destroyed.xf- Transform applied to the shape.- Returns:
- Number of particles destroyed.
- Warning:
- This function is locked during callbacks.
-
destroyParticlesInShape
Destroy particles inside a shape. This function is locked during callbacks. In addition, this function immediately destroys particles in the shape in contrast to DestroyParticle() which defers the destruction until the next simulation step.- Parameters:
shape- Shape which encloses particles that should be destroyed.xf- Transform applied to the shape.callDestructionListener- Whether to call the world b2DestructionListener for each particle destroyed.- Returns:
- Number of particles destroyed.
- Warning:
- This function is locked during callbacks.
-
createParticleGroup
Create a particle group whose properties have been defined. No reference to the definition is retained.- Warning:
- This function is locked during callbacks.
-
joinParticleGroups
Join two particle groups.- Parameters:
groupA- The first group. Expands to encompass the second group.groupB- The second group. It is destroyed.- Warning:
- This function is locked during callbacks.
-
destroyParticlesInGroup
Destroy particles in a group. This function is locked during callbacks.- Parameters:
group- The particle group to destroy.callDestructionListener- Whether to call the world b2DestructionListener for each particle is destroyed.- Warning:
- This function is locked during callbacks.
-
destroyParticlesInGroup
Destroy particles in a group without enabling the destruction callback for destroyed particles. This function is locked during callbacks.- Parameters:
group- The particle group to destroy.- Warning:
- This function is locked during callbacks.
-
getParticleGroupList
Get the world particle group list. With the returned group, use ParticleGroup::GetNext to get the next group in the world list. A NULL group indicates the end of the list.- Returns:
- The head of the world particle group list.
-
getParticleGroupCount
public int getParticleGroupCount()Get the number of particle groups. -
getParticleCount
public int getParticleCount()Get the number of particles. -
getParticleMaxCount
public int getParticleMaxCount()Get the maximum number of particles. -
setParticleMaxCount
public void setParticleMaxCount(int count) Set the maximum number of particles. -
setParticleDensity
public void setParticleDensity(float density) Change the particle density. -
getParticleDensity
public float getParticleDensity()Get the particle density. -
setParticleGravityScale
public void setParticleGravityScale(float gravityScale) Change the particle gravity scale. Adjusts the effect of the global gravity vector on particles. Default value is 1.0f. -
getParticleGravityScale
public float getParticleGravityScale()Get the particle gravity scale. -
setParticleDamping
public void setParticleDamping(float damping) Damping is used to reduce the velocity of particles. The damping parameter can be larger than 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is large. -
getParticleDamping
public float getParticleDamping()Get damping for particles -
setParticleRadius
public void setParticleRadius(float radius) Change the particle radius. You should set this only once, on world start. If you change the radius during execution, existing particles may explode, shrink, or behave unexpectedly. -
getParticleRadius
public float getParticleRadius()Get the particle radius. -
getParticleFlagsBuffer
public int[] getParticleFlagsBuffer()Get the particle data.- Returns:
- The pointer to the head of the particle data.
-
getParticlePositionBuffer
-
getParticleVelocityBuffer
-
getParticleColorBuffer
-
getParticleGroupBuffer
-
getParticleUserDataBuffer
-
setParticleFlagsBuffer
public void setParticleFlagsBuffer(int[] buffer, int capacity) Set a buffer for particle data.- Parameters:
buffer- Is a pointer to a block of memory.capacity- Is the number of values in the block.
-
setParticlePositionBuffer
-
setParticleVelocityBuffer
-
setParticleColorBuffer
-
setParticleUserDataBuffer
-
getParticleContacts
Get contacts between particles -
getParticleContactCount
public int getParticleContactCount() -
Get contacts between particles and bodies
-
getParticleBodyContactCount
public int getParticleBodyContactCount() -
computeParticleCollisionEnergy
public float computeParticleCollisionEnergy()Compute the kinetic energy that can be lost by damping force
-