Chipmunk Physics 5.3.5

First of all, Chipmunk is a 2D rigid body physics library distributed under the MIT license. It is intended to be fast, portable, numerically stable, and easy to use. For this reason it’s been used in hundreds of games on every system you can name. This includes top quality titles such as Night Sky for the Wii and many #1 sellers on the iPhone App Store! I’ve put thousands of hours of work over many years to make Chipmunk what it is today. If you find Chipmunk has saved you a lot of time, please consider donating. You’ll make an indie game developer very happy!

First of all, I would like to give a Erin Catto a big thank you, as Chipmunk’s impulse solver was directly inspired by his Box2D example code way back in 2006. (Now a full fledged physics engine all it’s own: His contact persistence idea allows for stable stacks of objects with very few iterations of the solver. My previous solver produced mushy piles of objects or required a large amount of CPU to operate stably.

Why a C Library?

A lot of people ask me why I wrote Chipmunk in C instead of pick your favorite language here. I tend to get really excited about different programming languages. Depending on the month, take your pick of Scheme, OCaml, Ruby, Objective-C, OOC, Lua, Io… the list goes on. The one common factor between most any language is that they are usually dead simple to make bindings to C code. I wanted Chipmunk to be fast, portable, and easy to optimize. With Chipmunk weiging in at less than 7,500 lines of C code, headers and comments, I don’t feel that using C has made Chipmunk difficult to develop. In fact, at times I feel it has made it easier to optimize and debug.

That said, I’ve never developed a whole game in C and I probably never will. There are much more interesting languages to do that in than C with all sorts of nice features like garbage collection, closures and object oriented runtimes. Check out the Bindings and Ports page to see if you can use Chipmunk from your language of choice. Because Chipmunk is written in a subset of C99 it compiles cleanly as C, C++, Objective-C and Objective-C++ code, making it easy to integrate into projects in those languages.

If you are writing iPhone games using Chipmunk, you should check out the Objective-Chipmunk wrapper that we’ve developed for Chipmunk. It integrates with the Objective-C memory model and provides a number of high level APIs that make writing physics based games for the iPhone even easier. While we do charge for Objective-Chipmunk, it will almost certainly save you more time than the small cost to license it. As a bonus, you’ll be helping to ensure that we can afford to continue to work on Chipmunk improvements.

Limitations of a C API:

There are two problems with C APIs. The first is that they lack operator overloading. Chipmunk defines vector operators as functions instead of allowing you to use inline operators such as *, , and -. In practice, it’s usually not a major problem for readability, but a little annoying. Chipmunk does provide overloaded operators if you are using C+. Another problem is that there is no way to mark struct field or functions as “private” in C. To get around this, I created the CP_PRIVATE() macro, if you see a struct field or function defined using CP_PRIVATE it means that you shouldn’t be using it as it’s name or meaning might change in future versions without warning. In Chipmunk 6, it will be a hard error to access these fields or functions unless you import the _chipmunk_private.h_ header.


The best way to get support is to visit the Chipmunk Forums. There are plenty of people around using Chipmunk on the just about every platform I’ve ever heard of. If you are working on a commercial project, Howling Moon Software (my company) is available for contracting. We can help with implementing custom Chipmunk behaviors, as well as priority bug fixes and performance tuning.


If you find any bugs in Chipmunk or this document, or have a question or comment about Chipmunk you can contact me at slembcke(at)gmail(dot)com.


Chipmunk is licensed under the MIT license.

Copyright (c) 2007 Scott Lembcke

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.


This means that you do not have to buy a license or pay to use Chipmunk in commercial projects. (Though we really appreciate donations)


Chipmunk Basics:


There are 4 basic objects you will use in Chipmunk.

There is often confusion between rigid bodies and their collision shapes in Chipmunk and how they relate to sprites. A sprite would be a visual representation of an object, while a collision shape is an invisible property that defines how objects should collide. Both the sprite’s and the collision shape’s position and rotation are controlled by a rigid body.


Before you do anything else, you must initialize Chipmunk. Otherwise you will crash as soon as the first collision is detected.

cpInitChipmunk(); // That is all

If Chipmunk was not compiled with the NDEBUG flag set, it will also print out the debug mode message and the current version number to stdout.

Memory Management the Chipmunk way:

For many of the structures you will use, Chipmunk uses a more or less standard set of memory management functions. Take the cpSpace struct for example:

While you will probably use the new/free versions exclusively if you are using C/C++, but the alloc/init/destroy functions can be helpful when writing language extensions so that you can more easily work with a garbage collector.

In general, you are responsible for freeing any structs that you allocate. Chipmunk does not have any fancy reference counting or garbage collection built in.

Basic Types:

chipmunk_types.h defines a number of basic types that Chipmunk uses. These can be changed at compile time to better suit your needs:

Note: On the iPhone, cpFloat is defined as float and cpVect is an alias for CGPoint for performance and compatibility reasons.

Math the Chipmunk way:

First of all, Chipmunk uses double precision floating point numbers throughout it’s calculations by default. This is likely to be faster on most modern desktop processors, and means you have to worry less about floating point round off errors. You can change the floating point type used by Chipmunk when compiling the library. Look in chipmunk_types.h.

Chipmunk defines a number of aliases for common math functions so that you can choose to use floats or doubles for Chipmunk’s floating point type. In your own code, there probably isn’t a strong reason to use these aliases unless you expect you might want to change Chipmunk’s floating point type later and a 2% performance hit from using the wrong float/double version of math functions will matter.

That said, there are a few functions you will probably find very useful:

cpFloat cpfclamp(cpFloat f, cpFloat min, cpFloat max)

Clamp f to be between min and max.

cpFloat cpflerp(cpFloat f1, cpFloat f2, cpFloat t)

Linearly interpolate between f1 and f2.

cpFloat cpflerpconst(cpFloat f1, cpFloat f2, cpFloat d)

Linearly interpolate from f1 towards f2 by no more than d.

Floating point infinity is defined for you as INFINITY if your standard math library (cough MSVC cough) doesn’t define it for you.

To represent vectors, Chipmunk defines the cpVect type and a set of inline functions for working with them (cpv, cpvadd, cpvmult, etc). See the API reference for more information..

Chipmunk C API:

Main API:

Chipmunk Vectors: cpVect

Struct Definition, Constants and Constructors:

typedef struct cpVect{
	cpFloat x, y;
} cpVect

Simply a 2D vector packed into a struct.

#define cpvzero ((cpVect){0.0f, 0.0f})

Constant for the zero vector.

cpVect cpv(const cpFloat x, const cpFloat y)

Convenience constructor for creating new cpVect structs.


cpBool cpveql(const cpVect v1, const cpVect v2)

Check if two vectors are equal. (Be careful when comparing floating point numbers!)

cpVect cpvadd(const cpVect v1, const cpVect v2)
cpVect cpvsub(const cpVect v1, const cpVect v2)

Add or subtract two vectors.

cpVect cpvneg(const cpVect v)

Negate a vector.

cpVect cpvmult(const cpVect v, const cpFloat s)

Scalar multiplication.

cpFloat cpvdot(const cpVect v1, const cpVect v2)

Vector dot product.

cpFloat cpvcross(const cpVect v1, const cpVect v2)

2D vector cross product analog. The cross product of 2D vectors results in a 3D vector with only a z component. This function returns the magnitude of the z value.

cpVect cpvperp(const cpVect v)

Returns a perpendicular vector. (90 degree rotation)

cpVect cpvrperp(const cpVect v)

Returns a perpendicular vector. (-90 degree rotation)

cpVect cpvproject(const cpVect v1, const cpVect v2)

Returns the vector projection of v1 onto v2.

cpVect cpvrotate(const cpVect v1, const cpVect v2)

Uses complex multiplication to rotate v1 by v2. Scaling will occur if v1 is not a unit vector.

cpVect cpvunrotate(const cpVect v1, const cpVect v2)

Inverse of cpvrotate().

cpFloat cpvlength(const cpVect v)

Returns the length of v.

cpFloat cpvlengthsq(const cpVect v)

Returns the squared length of v. Faster than cpvlength() when you only need to compare lengths.

cpVect cpvlerp(const cpVect v1, const cpVect v2, const cpFloat t)

Linearly interpolate between v1 and v2.

cpVect cpvlerpconst(const cpVect v1, const cpVect v2, const cpFloat d)

Linearly interpolate between v1 towards v2 by distance d.

cpVect cpvslerp(const cpVect v1, const cpVect v2, const cpFloat t)

Spherical linearly interpolate between v1 and v2.

cpVect cpvslerpconst(const cpVect v1, const cpVect v2, const cpFloat a)

Spherical linearly interpolate between v1 towards v2 by no more than angle @a@’ in radians.

cpVect cpvnormalize(const cpVect v)

Returns a normalized copy of v.

cpVect cpvnormalize_safe(const cpVect v)

Returns a normalized copy of v or cpvzero if v was already cpvzero. Protects against divide by zero errors.

cpVect cpvclamp(const cpVect v, const cpFloat len)

Clamp v to length len.

cpFloat cpvdist(const cpVect v1, const cpVect v2)

Returns the distance between v1 and v2.

cpFloat cpvdistsq(const cpVect v1, const cpVect v2)

Returns the squared distance between v1 and v2. Faster than cpvdist() when you only need to compare distances.

int cpvnear(const cpVect v1, const cpVect v2, const cpFloat dist)

Returns true if the distance between v1 and v2 is less than dist.

cpVect cpvforangle(const cpFloat a)

Returns the unit length vector for the given angle (in radians).

cpFloat cpvtoangle(const cpVect v)

Returns the angular direction v is pointing in (in radians).

char *cpvstr(const cpVect v)

Returns a string representation of v. Intended mostly for debugging purposes and not production use.

NOTE: The string points to a static local and is reset every time the function is called. If you want to print more than one vector you will have to split up your printing onto separate lines.

Chipmunk Bounding Boxes: cpBB

Struct Definition and Constructors:

typedef struct cpBB{
	cpFloat l, b, r ,t;
} cpBB

Simple bounding box struct. Stored as left, bottom, right, top values.

cpBB cpBBNew(const cpFloat l, const cpFloat b, const cpFloat r, const cpFloat t)

Convenience constructor for cpBB structs. Like cpv() this function returns a copy and not a malloced pointer.


int cpBBintersects(const cpBB a, const cpBB b)

Returns true if the bounding boxes intersect.

int cpBBcontainsBB(const cpBB bb, const cpBB other)

Returns true if bb completely contains other.

int cpBBcontainsVect(const cpBB bb, const cpVect v)

Returns true if bb contains v.

int cpBBmerge(const cpBB a,  const cpBB b)

Return the minimal bounding box that contains both a and b.

int cpBBexpand(const cpBB bb,  const cpVect v)

Return the minimal bounding box that contains both bb and v.

cpVect cpBBClampVect(const cpBB bb, const cpVect v)

Returns a copy of v clamped to the bounding box.

cpVect cpBBWrapVect(const cpBB bb, const cpVect v)

Returns a copy of v wrapped to the bounding box.

Chipmunk Rigid Bodies: cpBody

Function Types for Integration Callbacks:

typedef void (*cpBodyVelocityFunc)(struct cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt);
typedef void (*cpBodyPositionFunc)(struct cpBody *body, cpFloat dt);

Integration function types. You can write your own integration functions to create your own body behaviors that go beyond applying simply gravity. It’s unlikely that you’ll need to override the position integration function, and if you do you should carefully study how the default function (cpBodyUpdatePosition()) works. See the planet demo for an example of how to create planetary gravity.


Using the standard single letter names used in physics equations for these values probably wasn’t the best idea in the long run. For me at least, it made things easier as the equations in the code looked more like the written equations I was used to. The getter/setter functions listed below may help save your sanity however.

When changing any of a body’s properties, you should also call cpBodyActivate() to make sure that it is not stuck sleeping when you’ve changed a property that should make it move again. The cpBodySet*() functions do this for you automatically.

Note: m, i, and a must be set using setter functions. The body holds on to cached values based on them.

Memory Management Functions:

cpBody *cpBodyAlloc(void)
cpBody *cpBodyInit(cpBody *body, cpFloat m, cpFloat i)
cpBody *cpBodyNew(cpFloat m, cpFloat i)

void cpBodyDestroy(cpBody *body)
void cpBodyFree(cpBody *body)

Standard set of Chipmunk memory management functions. m and i are the mass and moment of inertia for the body. Guessing the mass for a body is usually fine, but guessing a moment of inertia can lead to a very poor simulation.

Creating Additional Static Bodies:

While every cpSpace:#cpSpace has a built in static body that you can use, it can be convenient to make your own as well. One potential use is in a level editor. By attaching chunks of your level to static bodies, you can still move and rotate the chunks independently of each other. Then all you have to do is call cpSpaceRehashStatic() to rebuild the static collision detection data when you are done.

For more information on rogue and static bodies, see Chipmunk Spaces.

cpBody *cpBodyAlloc(void);
cpBody *cpBodyInitStatic(cpBody *body)
cpBody *cpBodyNewStatic()

Create additional static bodies with infinite mass and moment of inertia.

Moment of Inertia Helper Functions:

Use the following functions to approximate the moment of inertia for your body, adding the results together if you want to use more than one.

cpFloat cpMomentForCircle(cpFloat m, cpFloat r1, cpFloat r2, cpVect offset)

Calculate the moment of inertia for a hollow circle, r1 and r2 are the inner and outer diameters in no particular order. (A solid circle has an inner diameter of 0)

cpFloat cpMomentForSegment(cpFloat m, cpVect a, cpVect b)

Calculate the moment of inertia for a line segment. The endpoints a and b are relative to the body.

cpFloat cpMomentForPoly(cpFloat m, int numVerts, cpVect *verts, cpVect offset)

Calculate the moment of inertia for a solid polygon shape assuming it’s center of gravity is at it’s centroid. The offset is added to each vertex.

cpFloat cpMomentForBox(cpFloat m, cpFloat width, cpFloat height)

Calculate the moment of inertia for a solid box centered on the body.

Area Helper Functions:

Use the following functions to get the area for common Chipmunk shapes if you want to approximate masses.

cpFloat cpAreaForCircle(cpFloat r1, cpFloat r2)

Area of a hollow circle.

cpFloat cpAreaForSegment(cpVect a, cpVect b, cpFloat r)

Area of a beveled segment. (Will always be zero if radius is zero)

cpFloat cpAreaForPoly(const int numVerts, const cpVect *verts)

Signed area of a polygon shape. Returns a negative number for polygons with a backwards winding.

Setters for Linked Values:

Because several rigid body values are linked (m/m_inv, i/i_inv, a/rot), don’t set them explicitly. Use the following setter functions instead.

void cpBodySetMass(cpBody *body, cpFloat m);
void cpBodySetMoment(cpBody *body, cpFloat i);
void cpBodySetAngle(cpBody *body, cpFloat a);

Getters and Setters:

While you MUST use the setters in the previous section. You are encouraged to use setters/getters for all properties.

Getters and setters will all be of the form:

cpFloat cpBodyGetMass(cpBody *body)
void cpBodySetMass(cpBody *body, cpFloat mass)

And the full list:

Name Type Read Only?
Mass cpFloat no
Moment cpFloat no
Pos cpVect no
Vel cpVect no
Force cpVect no
Angle cpFloat no
AngVel cpFloat no
Torque cpFloat no
Rot cpVect yes

Integration Functions:

void cpBodySlew(cpBody *body, cpVect pos, cpFloat dt)

Modify the velocity of the body so that it will move to the specified absolute coordinates in the next timestep. Intended for objects that are moved manually with a custom velocity integration function.

void cpBodyUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)

Default rigid body velocity integration function. Updates the velocity of the body using Euler integration.

void cpBodyUpdatePosition(cpBody *body, cpFloat dt)

Default rigid body position integration function. Updates the position of the body using Euler integration. Unlike the velocity function, it’s unlikely you’ll want to override this function. If you do, make sure you understand it’s source code as it’s an important part of the collision/joint correction process.

Coordinate Conversion Functions:

cpVect cpBodyLocal2World(cpBody *body, cpVect v)

Convert from body local coordinates to world space coordinates.

cpVect cpBodyWorld2Local(cpBody *body, cpVect v)

Convert from world space coordinates to body local coordinates.

Applying Forces and Torques:

void cpBodyApplyImpulse(cpBody *body, cpVect j, cpVect r)

Apply the impulse j to body at a relative offset r from the center of gravity. Both r and j are in world coordinates. r is relative to the position of the body, but not the rotation. Many people get tripped up by this.

void cpBodyResetForces(cpBody *body)

Zero both the forces and torques accumulated on body.

void cpBodyApplyForce(cpBody *body, cpVect f, cpVect r)

Apply (accumulate) the force f on body at a relative offset (important!) r from the center of gravity. Both r and f are in world coordinates.

Sleeping Functions:

See Chipmunk Spaces":#cpSpace for more information on Chipmunk’s sleeping feature.

cpBool cpBodyIsSleeping(const cpBody *body)

Returns true if body is sleeping.

void cpBodySleepWithGroup(cpBody *body, cpBody *group)

When objects in Chipmunk sleep, they sleep as a group of all objects that are touching or jointed together. When an object is woken up, all of the objects in it’s group are woken up. Calling cpBodySleepWithGroup() forces a body to fall asleep immediately. If group is NULL, a new group will be created. If group is another sleeping body, it will be added to that body’s group. It is an error to specify a non-sleeping body for group. Make sure everything is set up before calling this method. Calling a setter function or adding/removing a shape or constraint will cause the body to be woken up again. Also, this function must not be called from a collision handler or query callback. Use a post-step callback instead.

An example of how this could be used is to set up a piles of boxes that a player can knock over. Creating the piles and letting them fall asleep normally would work, but it means that all of the boxes would need to be simulated until they fell asleep. This could be slow if you had a lot of piles. Instead you can force them to sleep and start the game with the boxes already sleeping.

Another example would be collapsing platforms. You could create a sleeping object that is suspended in the air. As soon as the player comes along to jump on it, it wakes up and starts falling. In this case, it would be impossible to have the platform fall asleep naturally.

void cpBodySleep(cpBody *body)

Equivalent to calling cpBodySleepWithGroup(body, NULL). It forces body to fall asleep and creates a new group for it.

void cpBodyActivate(cpBody *body)

Wake body up so that it starts actively simulating again if it’s sleeping, or reset the idle timer if it’s active. In Chipmunk 5.3.4 and up, you can call this function from a collision or query callback. In previous versions this was an error.

Misc Functions:

cpBool cpBodyIsStatic(const cpBody *body)

Returns true if body is a static body. (cpSpace.staticBody or a static rogue body)

cpBool cpBodyIsRogue(const cpBody *body)

Returns true if body has never been added to a space. Though shapes attached to this body may still be added to a space. For more information on rogue and static bodies, see Chipmunk Spaces.

cpBool cpBodyIsSleeping(const cpBody *body)

Returns true if body is sleeping.


Chipmunk Collision Shapes: cpShape

There are currently 3 collision shape types:

You can add multiple shapes to a body. This should give you the flexibility to make any shape you want as well providing different areas of the same object with different friction, elasticity or callback values.


When creating different types of shapes, you will always be given a cpShape* pointer back. This is because Chipmunk shapes are meant to be opaque types. Think of the specific collision types such as cpCircleShape, cpSegmentShape and cpPolyShape as private subclasses of cpShape. You can still read some properties from them using the getter functions, but you are not intended to cast cpShape pointers to their specific types.

Filtering Collisions:

Chipmunk has two primary means of ignoring collisions: groups and layers.

Groups are meant to ignore collisions between parts on a complex object. A ragdoll is a good example. When jointing an arm onto the torso, you’ll want them to allow them to overlap. Groups allow you to do exactly that. Shapes that have the same group don’t generate collisions. So by placing all of the shapes in a ragdoll in the same group, you’ll prevent it from colliding against other parts of itself.

Layers allow you to separate collision shapes into mutually exclusive planes. Shapes can be in more than one layer, and shapes only collide with other shapes that are in at least one of the same layers. As a simple example, say shape A is in layer 1, shape B is in layer 2, and shape C is in layer 1 and 2. Shape A and B won’t collide with each other, but shape C will collide with both A and B.

Layers can also be used to set up rule based collisions. Say you have four types of shapes in your game. The player, the enemies, player bullets and enemy bullets. The are that the player should collide with enemies, and bullets shouldn’t collide with the type (player or enemy) that fired them. Making a chart would look like this:

Player Enemy Player Bullet Enemy Bullet
Player (1) (2)
Enemy (3)
Player Bullet
Enemy Bullet

The ‘-’s are for redundant spots in the chart, and the numbers are spots where types should collide. You can use a layer for rule that you want to define. Then add the layers to each type: The player should be in layers 1 and 2, the enemy should be in layers 1 and 3, the player bullets should be in layer 3, and the enemy bullets should be in layer 2. Treating layers as rules this way, you can define up to 32 rules. The default cpLayers type is unsigned int which has a resolution of 32 bits on most systems. Redefine it if you need more to work with.

There is one last way of filtering collisions using collision handlers. See the section on callbacks for more information. While collision handlers can be more flexible, they are also the slowest method. So you try to use groups or layers first.

Memory Management Functions:

void cpShapeDestroy(cpShape *shape)
void cpShapeFree(cpShape *shape)

Destroy and Free functions are shared by all shape types. Allocation and initialization functions are specific to each shape type. See below.

Shape Operations:

cpBB cpShapeCacheBB(cpShape *shape)

Updates and returns the bounding box of shape.

void cpResetShapeIdCounter(void)

Chipmunk keeps a counter so that every new shape is given a unique hash value to be used in the spatial hash. Because this affects the order in which the collisions are found and handled, you can reset the shape counter every time you populate a space with new shapes. If you don’t, there might be (very) slight differences in the simulation.

Working With Circle Shapes:

cpCircleShape *cpCircleShapeAlloc(void)
cpCircleShape *cpCircleShapeInit(cpCircleShape *circle, cpBody *body, cpFloat radius, cpVect offset)
cpShape *cpCircleShapeNew(cpBody *body, cpFloat radius, cpVect offset)

body is the body to attach the circle to, offset is the offset from the body’s center of gravity in body local coordinates.

cpVect cpCircleShapeGetOffset(cpShape *circleShape)
cpFloat cpCircleShapeGetRadius(cpShape *circleShape)

Getters for circle shape properties. Passing as non-circle shape will throw an assertion.

Working With Segment Shapes:

cpSegmentShape* cpSegmentShapeAlloc(void)
cpSegmentShape* cpSegmentShapeInit(cpSegmentShape *seg, cpBody *body, cpVect a, cpVect b, cpFloat radius)
cpShape* cpSegmentShapeNew(cpBody *body, cpVect a, cpVect b, cpFloat radius)

body is the body to attach the segment to, a and b are the endpoints, and radius is the thickness of the segment.

cpVect cpSegmentShapeGetA(cpShape *shape)
cpVect cpSegmentShapeGetA(cpShape *shape)
cpVect cpSegmentShapeGetNormal(cpShape *shape)
cpFloat cpSegmentShapeGetRadius(cpShape *shape)

Getters for segment shape properties. Passing a non-segment shape will throw an assertion.

Working With Polygon Shapes:

cpPolyShape *cpPolyShapeAlloc(void)
cpPolyShape *cpPolyShapeInit(cpPolyShape *poly, cpBody *body, int numVerts, cpVect *verts, cpVect offset)
cpShape *cpPolyShapeNew(cpBody *body, int numVerts, cpVect *verts, cpVect offset)

body is the body to attach the poly to, verts is an array of cpVect structs defining a convex hull with a clockwise winding, offset is the offset from the body’s center of gravity in body local coordinates. An assertion will be thrown the vertexes are not convex or do not have a clockwise winding.

int cpPolyShapeGetNumVerts(cpShape *shape)
cpVect cpPolyShapeGetVert(cpShape *shape, int index)

Getters for poly shape properties. Passing a non-poly shape or an index that does not exist will throw an assertion.

Poly Shape Helper Functions:

cpVect cpCentroidForPoly(const int numVerts, const cpVect *verts)

Calculate the centroid for a polygon.

void cpRecenterPoly(const int numVerts, cpVect *verts)

Center a polygon to (0,0). Subtracts the centroid from each vertex.

Modifying cpShapes:

The short answer is that you can’t because the changes would be only picked up as a change to the position of the shape’s surface, but not it’s velocity. The long answer is that you can using the “unsafe” API as long as you realize that doing so will not result in realistic physical behavior. These extra functions are define in a separate header chipmunk_unsafe.h.


Chipmunk Spaces: cpSpace

Spaces in Chipmunk are the basic unit of simulation. You add rigid bodies, shapes and constraints to it and then step them forward through time.

What Are Iterations, and Why Should I care?

Chipmunk uses an iterative solver to figure out the forces between objects in the space. What this means is that it builds a big list of all of the collisions, joints, and other constraints between the bodies and makes several passes over the list considering each one individually. The number of passes it makes is the iteration count, and each iteration makes the solution more accurate. If you use too many iterations, the physics should look nice and solid, but may use up too much CPU time. If you use too few iterations, the simulation may seem mushy or bouncy when the objects should be solid. Setting the number of iterations lets you balance between CPU usage and the accuracy of the physics. Chipmunk’s default of 10 iterations is sufficient for most simple games.

Rogue and Static Bodies:

Rogue bodies are bodies that have not been added to the space, but are referenced from shapes or joints. Rogue bodies are a common way of controlling moving elements in Chipmunk such as platforms. As long as the body’s velocity matches the changes to it’s position, there is no problem with doing this. Most games will not need rogue bodies however.

In previous versions, Chipmunk used infinite mass rogue bodies to attach static shapes to. Creating and maintaining your own body for this is no longer necessary as each space has it’s own body for attaching static shapes to. This body is marked as being a static body. A static body allows other objects resting on or jointed to it to fall asleep even though it does not fall asleep itself. Additional static bodies can be created using cpBodyNewStatic() or cpBodyInitStatic(). Objects resting on or jointed to rogue bodies can never fall asleep. This is because the purpose of rogue bodies are to allow the programmer to move or modify them at any time. Without knowing when they will move, Chipmunk has to assume that objects cannot fall asleep when touching them.

Static Shapes:

Chipmunk optimizes collision detection against shapes that do not move. There are two ways that Chipmunk knows a shape is static.

The first is automatic. When adding or removing shapes attached to static bodies, Chipmunk knows to handle them specially and you just use the same functions as adding regular dynamic shapes, cpSpaceAddShape() and cpSpaceRemoveShape().

The second way is to explicitly tag shapes as static using cpSpaceAddStaticShape(). This is rarely needed, but say for instance that you have a rogue body that seldomly moves. In this case, adding a shape attached to it as a static shape and updating it only when the body moves can increase performance. Shapes added this way must be removed by calling cpSpaceRemoveStaticShape().

Because static shapes aren’t updated automatically, you must let Chipmunk know that it needs to update the static shapes. You can update all of the static shapes at once using cpSpaceRehashStatic() or individual shapes using cpSpaceRehashShape(). If you find yourself rehashing static bodies often, you should be adding them normally using cpSpaceAddShape() instead.


New in Chipmunk 5.3 is the ability of spaces to disable entire groups of objects that have stopped moving to save CPU time as well as battery life. In order to use this feature you must do 2 things. The first is that you must attach all your static geometry to static bodies. Objects cannot fall asleep if they are touching a non-static rogue body even if it’s shapes were added as static shapes. The second is that you must enable sleeping explicitly by choosing a time threshold value for cpSpace.sleepTimeThreshold. If you do not set cpSpace.idleSpeedThreshold explicitly, a value will be chosen automatically based on the current amount of gravity.


Memory Management Functions:

cpSpace* cpSpaceAlloc(void)
cpSpace* cpSpaceInit(cpSpace *space)
cpSpace* cpSpaceNew()

void cpSpaceDestroy(cpSpace *space)
void cpSpaceFree(cpSpace *space)

More standard Chipmunk memory functions.

void cpSpaceFreeChildren(cpSpace *space)

This function will free all of the shapes, bodies and joints that have been added to space. Does not free space. You will still need to call cpSpaceFree() on your own. You will probably never use this in a real game, as your gamestate or game controller should manage removing and freeing objects from the space.


void cpSpaceAddShape(cpSpace *space, cpShape *shape)
void cpSpaceAddStaticShape(cpSpace *space, cpShape *shape)
void cpSpaceAddBody(cpSpace *space, cpBody *body)
void cpSpaceAddConstraint(cpSpace *space, cpConstraint *constraint)

void cpSpaceRemoveShape(cpSpace *space, cpShape *shape)
void cpSpaceRemoveStaticShape(cpSpace *space, cpShape *shape)
void cpSpaceRemoveBody(cpSpace *space, cpBody *body)
void cpSpaceRemoveConstraint(cpSpace *space, cpConstraint *constraint)

These functions add and remove shapes, bodies and constraints from space. See the section on Static Shapes above for an explanation of what a static shape is and how it differs from a normal shape. Also, you cannot call the any of these functions from within a callback other than a post-step callback (which is different than a post-solve callback!). Attempting to add or remove objects from the space while cpSpaceStep() is still executing will throw an assertion. See the callbacks section for more information.


void cpSpaceActivateShapesTouchingShape(cpSpace *space, cpShape *shape)

Perform a query for all shapes touching shape and call cpBodyActivate() on them. This is useful when you need to move a shape explicitly. Waking shapes touching the moved shape prevents objects from sleeping when the floor is moved or something similar. You only need to do this when changing the shape of an existing shape or moving a static shape. Most other methods of moving a shape automatically would wake up other touching objects.

Spatial Hash Management Functions:

Chipmunk uses a spatial hash to accelerate it’s collision detection. While it’s not necessary to interact with the hash directly. The current API does expose some of this at the space level to allow you to tune it’s performance.

void cpSpaceResizeStaticHash(cpSpace *space, cpFloat dim, int count)
void cpSpaceResizeActiveHash(cpSpace *space, cpFloat dim, int count)

The spatial hash data structures used by Chipmunk’s collision detection are fairly size sensitive. dim is the size of the hash cells. Setting dim to the average collision shape size is likely to give the best performance. Setting dim too small will cause the shape to be inserted into many cells, setting it too low will cause too many objects into the same hash slot.

count is the suggested minimum number of cells in the hash table. If there are too few cells, the spatial hash will return many false positives. Too many cells will be hard on the cache and waste memory. the Setting count to ~10x the number of objects in the space is probably a good starting point. Tune from there if necessary. By default, dim is 100.0, and count is 1000. The new demo program has a visualizer for the static hash. You can use this to get a feel for how to size things up against the spatial hash.

Using the spatial has visualization in the demo program you can see what I mean. The grey squares represent cells in the spatial hash. The darker the cell, the more objects have been mapped into that cell. A good dim size is when your objects fit nicely into the grid:

Notice the light grey meaning that each cell doesn’t have too many objects mapped onto it.

When you use too small a size, Chipmunk has to insert each object into a lot of cells. This can get expensive.

Notice that the grey cells are very small compared to the collision shapes.

When you use too big of a size, a lot of shapes will fit into each cell. Each shape has to be checked against every other shape in the cell, so this makes for a lot of unnecessary collision checks.

Notice the dark grey cells meaning that many objects are mapped onto them.

void cpSpaceRehashStatic(cpSpace *space)

Rehashes the shapes in the static spatial hash. You must call this if you move any static shapes or Chipmunk won’t update their collision detection data.

void cpSpaceRehashShape(cpSpace *space, cpShape *shape)

Update an individual static shape that has moved.

Simulating the Space:

void cpSpaceStep(cpSpace *space, cpFloat dt)

Update the space for the given time step. Using a fixed time step is highly recommended. Doing so will increase the efficiency of the contact persistence, requiring an order of magnitude fewer iterations and CPU usage.


Chipmunk Constraints: cpConstraint

A constraint is something that describes how two bodies interact with each other. (how they constrain each other) Constraints can be simple joints that allow bodies to pivot around each other like the bones in your body, or they can be more abstract like the gear joint or motors.

What constraints are and what they are not:

Constraints in Chipmunk are all velocity based constraints. This means that they act primarily by synchronizing the velocity of two bodies. A pivot joint holds two anchor points on two separate bodies together by defining equations that say that the velocity of the anchor points must be the same and calculating impulses to apply to the bodies to try and keep it that way. A constraint takes a velocity as it’s primary input and produces a velocity change as it’s output. Some constraints, (joints in particular) apply velocity changes to correct differences in positions. More about this in the next section.

A spring connected between two bodies is not a constraint. It’s very constraint-like as it creates forces that affect the velocities of the two bodies, but a spring takes distances as input and produces forces as it’s output. If a spring is not a constraint, then why do I have two varieties of spring constraints you ask? The reason is because they are damped springs. The damping associated with the spring is a true constraint that creates velocity changes based on the relative velocities of the two bodies it links. As it is convenient to put a damper and a spring together most of the time, I figured I might as well just apply the spring force as part of the constraint instead of having a damper constraint and having the user calculate and apply their own spring forces separately.


To access properties of specific joint types, use the getter and setter functions provided (ex: cpPinJointGetAnchr1()). See the lists of properties for more information.

Error correction by Feedback:

Joints in Chipmunk are not perfect. A pin joint can’t maintain the exact correct distance between it’s anchor points, nor can a pivot joint hold it’s anchor points completely together. Instead, they are designed to deal with this by correcting themselves over time. In Chipmunk 5, you have a fair amount of extra control over how joints correct themselves and can even use this ability to create physical effects that allow you to use joints in unique ways:

There are three public fields of cpConstraint structs that control the error correction, maxForce, maxBias, and biasCoef. maxForce is pretty self explanatory, a joint or constraint will not be able to use more than this amount of force in order to function. If it needs more force to be able to hold itself together, it will fall apart. maxBias is the maximum speed at which error correction can be applied. If you change a property on a joint so that the joint will have to correct itself, it normally does so very quickly. By setting a maxSpeed you can make the joint work like a servo, correcting itself at a constant rate over a longer period of time. Lastly, biasCoef is the percentage of error corrected every step before clamping to a maximum speed. You can use this to make joints correct themselves smoothly instead of at a constant speed, but is probably the least useful of the three properties by far.

Constraints and Collision Shapes:

Neither constraints or collision shapes have any knowledge of the other. When connecting joints to a body the anchor points don’t need to be inside of any shapes attached to the body and it often makes sense that they shouldn’t. Also, adding a constraint between two bodies doesn’t prevent their collision shapes from colliding. In fact, this is the primary reason that the collision group property exists.

Video Tour of Current Joint Types. (Requires connection to YouTube)

Shared Memory Management Functions:

void cpConstraintDestroy(cpConstraint *constraint)
void cpConstraintFree(cpConstraint *constraint)

Destroy and Free functions are shared by all joint types. Allocation and initialization functions are specific to each joint type.

Misc Functions:

cpFloat cpConstraintGetImpulse(cpConstraint *constraint)

Get the most recent impulse that constraint applied. To convert this to a force, divide by the timestep passed to cpSpaceStep().

Constraint Types:

Pin Joints:

cpPinJoint *cpPinJointAlloc(void)
cpPinJoint *cpPinJointInit(cpPinJoint *joint, cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2)
cpConstraint *cpPinJointNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2)

a and b are the two bodies to connect, and anchr1 and anchr2 are the anchor points on those bodies. The distance between the two anchor points is measured when the joint is created. If you want to set a specific distance, use the setter function to override it.

Properties List:

Name Type
Anchr1 cpVect
Anchr2 cpVect
Dist cpFloat

Slide Joints:

cpSlideJoint *cpSlideJointAlloc(void)

cpSlideJoint *cpSlideJointInit(
	cpSlideJoint *joint, cpBody *a, cpBody *b,
	cpVect anchr1, cpVect anchr2, cpFloat min, cpFloat max

cpConstraint *cpSlideJointNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat min, cpFloat max)

a and b are the two bodies to connect, anchr1 and anchr2 are the anchor points on those bodies, and min and max define the allowed distances of the anchor points.

Properties List:

Name Type
Anchr1 cpVect
Anchr2 cpVect
Min cpFloat
Max cpFloat

Pivot Joints:

cpPivotJoint *cpPivotJointAlloc(void)
cpPivotJoint *cpPivotJointInit(cpPivotJoint *joint, cpBody *a, cpBody *b, cpVect pivot)
cpConstraint *cpPivotJointNew(cpBody *a, cpBody *b, cpVect pivot)
cpConstraint *cpPivotJointNew2(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2)

a and b are the two bodies to connect, and pivot is the point in world coordinates of the pivot. Because the pivot location is given in world coordinates, you must have the bodies moved into the correct positions already. Alternatively you can specify the joint based on a pair of anchor points, but make sure you have the bodies in the right place as the joint will fix itself as soon as you start simulating the space.

Properties List:

Name Type
Anchr1 cpVect
Anchr2 cpVect

Groove Joint:

cpGrooveJoint *cpGrooveJointAlloc(void)

cpGrooveJoint *cpGrooveJointInit(
	cpGrooveJoint *joint, cpBody *a, cpBody *b,
	cpVect groove_a, cpVect groove_b, cpVect anchr2

cpConstraint *cpGrooveJointNew(cpBody *a, cpBody *b, cpVect groove_a, cpVect groove_b, cpVect anchr2)

The groove goes from groov_a to groove_b on body a, and the pivot is attached to anchr2 on body b. All coordinates are body local.

Properties List:

Name Type
Anchr2 cpVect
GrooveA cpVect
GrooveB cpVect

Damped Spring:

cpDampedSpring *cpDampedSpringAlloc(void)

cpDampedSpring *cpDampedSpringInit(
	cpDampedSpring *joint, cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2,
	cpFloat restLength, cpFloat stiffness, cpFloat damping

cpConstraint *cpDampedSpringNew(
	cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2,
	cpFloat restLength, cpFloat stiffness, cpFloat damping

Defined much like a slide joint. restLength is the distance the spring wants to be, stiffness is the spring constant (Young’s modulus), and damping is how soft to make the damping of the spring.

Properties List:

Name Type
Anchr1 cpVect
Anchr2 cpVect
RestLength cpFloat
Stiffness cpFloat
Damping cpFloat

Damped Rotary Spring:

cpDampedRotarySpring *cpDampedRotarySpringAlloc(void)

cpDampedRotarySpring *cpDampedRotarySpringInit(
	cpDampedRotarySpring *joint, cpBody *a, cpBody *b,
	cpFloat restAngle, cpFloat stiffness, cpFloat damping

cpConstraint *cpDampedRotarySpringNew(cpBody *a, cpBody *b, cpFloat restAngle, cpFloat stiffness, cpFloat damping)

Like a damped spring, but works in an angular fashion. restAngle is the relative angle in radians that the bodies want to have, stiffness and damping work basically the same as on a damped spring.

Properties List:

Name Type
RestAngle cpFloat
Stiffness cpFloat
Damping cpFloat

Rotary Limit Joint:

cpRotaryLimitJoint *cpRotaryLimitJointAlloc(void)
cpRotaryLimitJoint *cpRotaryLimitJointInit(cpRotaryLimitJoint *joint, cpBody *a, cpBody *b, cpFloat min, cpFloat max)
cpConstraint *cpRotaryLimitJointNew(cpBody *a, cpBody *b, cpFloat min, cpFloat max)

Constrains the relative rotations of two bodies. min and max are the angular limits in radians. It is implemented so that it’s possible to for the range to be greater than a full revolution.

Properties List:

Name Type
Min cpFloat
Max cpFloat

Ratchet Joint:

cpRatchetJoint *cpRatchetJointAlloc(void);
cpRatchetJoint *cpRatchetJointInit(cpRatchetJoint *joint, cpBody *a, cpBody *b, cpFloat phase, cpFloat ratchet);
cpConstraint *cpRatchetJointNew(cpBody *a, cpBody *b, cpFloat phase, cpFloat ratchet);

Works like a socket wrench. ratchet is the distance between “clicks”, phase is the initial offset to use when deciding where the ratchet angles are.

Properties List:

Name Type
Angle cpFloat
Phase cpFloat
Ratchet cpFloat

Gear Joint:

cpGearJoint *cpGearJointAlloc(void);
cpGearJoint *cpGearJointInit(cpGearJoint *joint, cpBody *a, cpBody *b, cpFloat phase, cpFloat ratio);
cpConstraint *cpGearJointNew(cpBody *a, cpBody *b, cpFloat phase, cpFloat ratio);

Keeps the angular velocity ratio of a pair of bodies constant. ratio is always measured in absolute terms. It is currently not possible to set the ratio in relation to a third body’s angular velocity. phase is the initial angular offset of the two bodies.

Properties List:

Name Type
Phase cpFloat
Ratio cpFloat

Simple Motor:

cpSimpleMotor *cpSimpleMotorAlloc(void);
cpSimpleMotor *cpSimpleMotorInit(cpSimpleMotor *joint, cpBody *a, cpBody *b, cpFloat rate);
cpConstraint *cpSimpleMotorNew(cpBody *a, cpBody *b, cpFloat rate);

Keeps the relative angular velocity of a pair of bodies constant. rate is the desired relative angular velocity. You will usually want to set an force (torque) maximum for motors as otherwise they will be able to apply a nearly infinite torque to keep the bodies moving.

Properties List:

Name Type
Rate cpFloat


Overview of Collision Detection in Chipmunk:

In order to make collision detection in Chipmunk as fast as possible, the process is broken down into several stages. While I’ve tried to keep it conceptually simple, the implementation can be a bit daunting. Fortunately as a user of the library, you don’t need to understand everything about how it works. If you are trying to squeeze every ounce of performance out of Chipmunk, understanding this section is crucial.

Magic Collision Detection Globals:

Chipmunk contains a few global variables that control how collisions are solved. They can’t be set on a per space basis, but most games wont need to change them at all.

extern cpFloat cp_bias_coef

Because Chipmunk does not perform swept collisions, shapes may overlap. Each time you call cpSpaceStep() Chipmunk fixes a percentage of the overlap to push the shapes apart. By default, this value is set to 0.1. With this setting, after 15 steps the overlap will be reduced to 20%, after 30 it will be reduced to 4%. This is usually satisfactory for most games. Setting cp_bias_coef to 1.0 is not recommended as it will reduce the stability of stacked objects.

extern cpFloat cp_collision_slop

Chipmunk’s impulse solver works by caching the last solution as it is likely to be very similar to the current one. In order to help keep objects touching, Chipmunk allows objects to overlap a small amount. By default this value is 0.1. If you are using pixel coordinates you won’t even notice. If using a different scale, adjust the value to be as high as possible without creating any unwanted visual overlap.

extern cpTimestamp cp_contact_persistence

This is how many steps the space should remember old contact solutions. The default value is 3 and it’s unlikely that you’ll need to change it.

Spatial Hashing:

Chipmunk uses a spatial hash for its broad phase culling. Spatial hashes are very efficient for a scene made up of consistently sized objects. It basically works by taking the axis aligned bounding boxes for all the objects in the scene, mapping them onto an infinite sized grid, then mapping those grid cells onto a finite sized hash table. This way, you only have to check collisions between objects in the same hash table cells, and mapping the objects onto the grid can be done fairly quickly. Objects in the same hash table cells tend to be very close together, and therefore more likely to be colliding. The downside is that in order to get the best performance out of a spatial hash, you have to tune the size of the grid cells and the size of the hash table so you don’t get too many false positives. For more information about tuning the hash see the cpSpace section.

Things to keep in mind:

For more information on spatial hashing in general, Optimized Spatial Hashing for Collision Detection of Deformable Objects is a good paper that covers all the basics.

Collision Filtering:

After the spatial hash figures out pairs of shapes that are likely to be near each other, it passes them back to the space to perform some additional filtering on the pairs. If the pairs pass all the filters, then Chipmunk will test if the shapes are actually overlapping. If the shape to shape collision check passes, then the collision handler callbacks are called. These tests are much faster to try than the shape to shape collision checks, so use these if you can to reject collisions early instead of rejecting them from callbacks if you can.

Primitive Shape to Shape Collision Detection:

The most expensive test that you can do to see if shapes should collide is to actually check based on their geometry. Circle to circle and circle to line collisions are pretty quick. Poly to poly collisions get more expensive as the number of vertexes increases. Simpler shapes make for faster collisions (and more importantly fewer collision points for the solver to run).

Collision Handler Filtering:

After checking if two shapes overlap Chipmunk will look to see if you have defined a collision handler for the collision types of the shapes. This gives you a large amount of flexibility to process collisions events, but also gives you a very flexible way to filter out collisions. The return value of the begin and preSolve callback determines whether or not the colliding pair of shapes is discarded or not. Returning true will keep the pair, false will discard it. If you don’t define a handler for the given collision_types, Chipmunk will call the space’s default handler, which by default is defined to simply accept all collisions.

While using callbacks to filter collisions is the most flexible way, keep in mind that by the time your callback is called all of the most expensive collision detection has already been done. For simulations with a lot of colliding objects each frame, the time spent finding collisions is small compared to the time spent solving the physics for them so it may not be a big deal. Still, use layers or groups first if you can.


A physics library without any events or feedback would not be very useful for games. How would you know when the player bumped into an enemy so that you could take some health points away? How would you know how hard the car hit something so you don’t play a loud crash noise when a pebble hits it? What if you need to decide if a collision should be ignored based on specific conditions, like implementing one way platforms? Chipmunk has a number of powerful callback systems that you can plug into to accomplish all of that.

Collision Handlers:

A collision handler is a set of 4 function callbacks for the different collision events that Chipmunk recognizes. The event types are:

Collision callbacks are closely associated with cpArbiter structs. You should familiarize yourself with those as well.

Note: Shapes tagged as sensors (cpShape.sensor == true) never generate collisions that get processed so collisions between sensors shapes and other shapes will never call the post-solve callback. They still generate begin, and separate callbacks, and the pre solve callback is also called every frame even though there is no real collision.

Collision Handler API:

typedef int (*cpCollisionBeginFunc)(cpArbiter *arb, struct cpSpace *space, void *data)
typedef int (*cpCollisionPreSolveFunc)(cpArbiter *arb, cpSpace *space, void *data)
typedef void (*cpCollisionPostSolveFunc)(cpArbiter *arb, cpSpace *space, void *data)
typedef void (*cpCollisionSeparateFunc)(cpArbiter *arb, cpSpace *space, void *data)

Collision handler function types. While all of them take an arbiter, space, and a user data pointer, only the begin and pre-solve callbacks return a value. See above for more information.

void cpSpaceAddCollisionHandler(
	cpSpace *space,
	cpCollisionType a, cpCollisionType b,
	cpCollisionBeginFunc begin,
	cpCollisionPreSolveFunc preSolve,
	cpCollisionPostSolveFunc postSolve,
	cpCollisionSeparateFunc separate,
	void *data

Add a collision handler for given collision type pair. Whenever a shapes with collision type (cpShape.collision_type) a and collision type b collide, these callbacks will be used to process the collision. data is a user definable context pointer that is passed to each of the callbacks. NULL can be provided for callbacks you do not wish to implement, however Chipmunk will call it’s own default versions for these and not the default ones you’ve set up for the space. If you need to fall back on the space’s default callbacks, you’ll have to provide them individually to each handler definition.

void cpSpaceRemoveCollisionHandler(cpSpace *space, cpCollisionType a, cpCollisionType b)

Remove a collision handler for a given collision type pair.

void cpSpaceSetDefaultCollisionHandler(
	cpSpace *space,
	cpCollisionType a, cpCollisionType b,
	cpCollisionBeginFunc begin,
	cpCollisionPreSolveFunc preSolve,
	cpCollisionPostSolveFunc postSolve,
	cpCollisionSeparateFunc separate,
	void *data

Register a default collision handler to be used when no specific collision handler is found. The space is given a default handler when created that returns true for all collisions in begin() and preSolve() and does nothing in the postSolve() and separate() callbacks.

Post-Step Callbacks:

Post-step callbacks are the one place where you can break the rules about adding or removing objects from within a callback. In fact, their primary function is to help you safely remove objects from the space that you wanted to disable or destroy in a collision callback.

Post step callbacks are registered as a function and a pointer that is used as a key. You can only register one post step callback per key. This prevents you from accidentally removing an object more than once. For instance, say that you get a collision callback between a bullet and object A. You want to destroy both the bullet and object A, so you register a post-step callback to safely remove them from your game. Then you get a second collision callback between the bullet and object B. You register a post-step callback to remove object B, and a second post-step callback to remove the bullet. Because you can only register one callback per key, the post-step callback for the bullet will only be called once and you can’t accidentally register to have it removed twice.

Note: Additional callbacks registered to the same key are ignored even if they use a different callback function or data pointer.

typedef void (*cpPostStepFunc)(cpSpace *space, void *key, void *data)

Function type used for post step callbacks. space is the space the callback was registered on, obj is the pointer value you supplied as the key, and data is a user definable pointer you can use to pass in as a context value.

void cpSpaceAddPostStepCallback(cpSpace *space, cpPostStepFunc func, void *key, void *data)

Add func to be called before cpSpaceStep() returns. obj and data will be passed to your function. Only the last callback registered for any unique value of obj will be recorded. You can add post-step callbacks from outside of other callback functions, but they won’t be called until cpSpaceStep() is called again.


See the callback examples for more information.

Chipmunk Collision Pairs: cpArbiter

First of all, why are they called arbiters? The short answer is that Box2D called them that way back in 2006 when I was looking at the source for it’s solver. An arbiter is like a judge, a person that has authority to settle disputes between two people. It was a fun, fitting name and was shorter to type than CollisionPair which I had been using. :p

Originally arbiters were going to be an internal data type that Chipmunk used that wouldn’t ever be sent to outside code. In Chipmunk 4.x and earlier, only a single callback hook was provided for handling collision events. It was triggered every step that to shapes were touching. This made it non-trivial to track when objects started and stopped touching as the user would have to record and process this themselves. Many people, including myself, wanted to get collision begin/separate events and eventually I realized that information was already being stored in the arbiter cache that the Chipmunk maintains. With some changes to the collision callback API, that information is now exposed to the user. Internally, arbiters are used primarily for solving collision impulses. To external users, you can simply think of them as a weird type used in collision callbacks.

Memory Management:

You should never need to create an arbiter, nor will you ever need to free one as they are handled by the space. More importantly, because they are managed by the space you should never store a reference to an arbiter as you don’t know when they will be destroyed. Use them within the callback where they are given to you and then forget about them or copy out the information you need.

Helper Functions:

void cpArbiterGetShapes(cpArbiter *arb, cpShape **a, cpShape **b)
#define CP_ARBITER_GET_SHAPES(arb, a, b) cpShape *a, *b; cpArbiterGetShapes(arb, &a, &b);

Get the shapes in the order that they were defined in the collision handler associated with this arbiter. If you defined the handler as cpSpaceAddCollisionHandler(space, 1, 2, ...), you you will find that a->collision_type == 1 and b->collision_type == 2. The convenience macro defines and initializes the two shape variables for you. example

int cpArbiterIsFirstContact(cpArbiter *arb)

Returns true if this is the first step that the shapes touched. You can use this from preSolve() and postSolve() callbacks to know if a collision between two shapes is new without needing to flag a boolean in your begin callback.

typedef struct cpContactPointSet {
	int count;
	struct {
		cpVect point, normal;
		cpFloat dist;
} cpContactPointSet;

static inline cpContactPointSet
cpArbiterGetContactPointSet(const cpArbiter *arb)

Returns a cpContactPointSet structure. This is the new and preferred API for working with contact points instead of the cpArbiterGet*() functions as it is faster and slightly simpler.

cpContactPointSet set = cpArbiterGetContactPointSet(arbiter);
for(int i=0; i<set.count; i++){
	// get and work with the collision point normal and penetration distance:
cpVect cpArbiterGetCount(cpArbiter *arb)

Returns the number of contact points in this arbiter.

cpVect cpArbiterGetNormal(cpArbiter *arb, int i)

Returns the collision normal for the i’th contact point, flipping it if necessary. Note: Currently due to how Chipmunk’s collision detection is implemented, the collision normals will be the same for all collision points. You can simply do cpArbiterGetNormal(arb, 0) and not have to check each contact point. Note: calling this function from the separate() callback is undefined.

cpVect cpArbiterGetPoint(cpArbiter *arb, int i)

Returns the position of the i’th collision point. Note: calling this function from the separate() callback is undefined.

cpVect cpArbiterGetDepth(cpArbiter *arb, int i)

Returns the penetration depth of the i’th collision point.

cpVect cpArbiterTotalImpulse(cpArbiter *arb);
cpVect cpArbiterTotalImpulseWithFriction(cpArbiter *arb);

Returns the impulse that was applied this step to resolve the collision. These functions should only be called from a postStep() or postSolve() callback, otherwise the result is undefined. Note: If you are using the deprecated elastic iterations setting on your space, it will cause you to get incorrect results. Elastic iterations should no longer be needed, and you should be able to safely turn them off.


It’s unlikely that you’ll need to interact with a cpArbiter struct directly as the collision helper functions should provide most functionality that people will need. One exception is the e, and u fields. By default, Chipmunk multiplies the friction and elasticity values of to shapes together to determine what values to use when solving the collision. This mostly works, but in many cases is simply not flexible enough. If you are running into problems with that, you can change the values calculated for e and u in a preSolve callback. This is likely to change in the next major version of Chipmunk.


Chipmunk spaces currently support three kinds of spatial queries, point, segment and bounding box. Any type can be done efficiently against an entire space, or against individual shapes. All types of queries take a collision group and layer that are used to filter matches out using the same rules used for filtering collisions between shapes. See cpShape for more information. If you don’t want to filter out any matches, use CP_ALL_LAYERS for the layers and CP_NO_GROUP as the group.

Point Queries:

Point queries are useful for things like mouse picking and simple sensors.

cpBool cpShapePointQuery(cpShape *shape, cpVect p)

Check if the given point lies within the shape.

typedef void (*cpSpacePointQueryFunc)(cpShape *shape, void *data);

void cpSpacePointQuery(
	cpSpace *space, cpVect point,
	cpLayers layers, cpGroup group,
	cpSpacePointQueryFunc func, void *data

Query space at point filtering out matches with the given layers and group. func is called for each shape found along with the data argument passed to cpSpacePointQuery(). Sensor shapes are included.

cpShape *cpSpacePointQueryFirst(cpSpace *space, cpVect point, cpLayers layers, cpGroup group)

Query space at point and return the first shape found matching the given layers and group. Returns NULL if no shape was found. Sensor shapes are ignored.

Segment Queries:

Segment queries are like ray casting, but because Chipmunk uses a spatial hash to process collisions, it cannot process infinitely long queries like a ray. In practice this is still very fast and you don’t need to worry too much about the performance as long as you aren’t using extremely long segments for your queries.

typedef struct cpSegmentQueryInfo{
	struct cpShape *shape; // shape that was hit, NULL if no collision
	cpFloat t; // Distance along query segment, will always be in the range "1":0,.
	cpVect n; // normal of hit surface
} cpSegmentQueryInfo;

Segment queries return more information than just a simple yes or no, they also return where a shape was hit and it’s surface normal at the hit point. t is the percentage between the query start and end points. If you need the hit point in world space or the absolute distance from start, see the segment query helper functions farther down.

cpBool cpShapeSegmentQuery(cpShape *shape, cpVect a, cpVect b, cpSegmentQueryInfo *info)

Check if the line segment from a to b intersects the shape. info must be a valid pointer to a cpSegmentQueryInfo structure which will be initialized with the raycast info.

typedef void (*cpSpaceSegmentQueryFunc)(cpShape *shape, cpFloat t, cpVect n, void *data)

void cpSpaceSegmentQuery(
	cpSpace *space, cpVect start, cpVect end,
	cpLayers layers, cpGroup group,
	cpSpaceSegmentQueryFunc func, void *data

Query space along the line segment from start to end filtering out matches with the given layers and group. func is called with the normalized distance along the line and surface normal for each shape found along with the data argument passed to cpSpacePointQuery(). Sensor shapes are included.

cpShape *cpSpaceSegmentQueryFirst(
	cpSpace *space, cpVect start, cpVect end,
	cpLayers layers, cpGroup group,
	cpSegmentQueryInfo *info

Query space along the line segment from start to end filtering out matches with the given layers and group. Only the first shape encountered is returned and the search is short circuited. Returns NULL if no shape was found. The info struct pointed to by info will be initialized with the raycast info unless info is NULL. Sensor shapes are ignored.

Segment Query Helper Functions:

cpVect cpSegmentQueryHitPoint(cpVect start, cpVect end, cpSegmentQueryInfo info)

Return the hit point in world coordinates where the segment first intersected with the shape.

cpFloat cpSegmentQueryHitDist(cpVect start, cpVect end, cpSegmentQueryInfo info)

Return the absolute distance where the segment first hit the shape.


See the query examples for more information.