pymunk.batch Module

The batch module contain functions to efficiently get and set space data in

a batch instead of one by one.

Note

This module is highly experimental and will likely change in future Pymunk verisons including major, minor and patch versions!

To get data out

First create space and two bodies.

>>> import pymunk, pymunk.batch
>>> s = pymunk.Space()
>>> b1 = pymunk.Body(1, 1)
>>> b1.position = 1,2
>>> s.add(b1, pymunk.Circle(b1, 4))
>>> b2 = pymunk.Body(1,1)
>>> b2.position = 3,4
>>> s.add(b2, pymunk.Circle(b2, 4))

To get data out first create a Buffer holder object, which is used to reuse the underlying arrays between calls. Then call the batch method. Note that the fields on the body to extract need to be specified explicitly.

>>> data = pymunk.batch.Buffer()
>>> pymunk.batch.get_space_bodies(
...     s,
...     pymunk.batch.BodyFields.BODY_ID | pymunk.batch.BodyFields.POSITION,
...     data,
... )

The data is available in the Buffer object as cffi buffers. One that contains any int data, and one that contains floating point data. You can either use it directly like here, but also pass it in to 3rd parties that implements the buffer protocol like numpy arrays.

>>> list(memoryview(data.int_buf()).cast("P")) == [b1.id, b2.id]
True
>>> list(memoryview(data.float_buf()).cast("d"))
[1.0, 2.0, 3.0, 4.0]

Its also possible to get the arbiters with collision data. Note that we need to call step to run the simulation, and clear the data data buffers first so they can be reused:

>>> s.step(1)
>>> data.clear()
>>> pymunk.batch.get_space_arbiters(
...     s,
...     pymunk.batch.ArbiterFields.BODY_A_ID | pymunk.batch.ArbiterFields.BODY_B_ID,
...     data,
... )
>>> list(memoryview(data.int_buf()).cast("P")) == [b2.id, b1.id]
True
>>> list(memoryview(data.float_buf()).cast("d"))
[]

Layouts and setting data

Query the layout instead of hardcoding column indices. Offsets and strides are in elements, separately for each buffer:

>>> flags = BodyFields.POSITION | BodyFields.ANGLE
>>> layout = get_body_layout(flags)
>>> layout[BodyFields.ANGLE]
(0, 1)
>>> layout[BodyFields.POSITION]
(1, 2)
>>> stride = layout.float_stride
>>> stride
3

For this selection, each float record is [angle, x, y]. Unselected fields occupy no space. Packing order is independent of numeric flag values.

For example, build records using the queried offsets:

>>> import array
>>> records = array.array("d", [0.0] * (2 * stride))
>>> for row, (angle, x, y) in enumerate(((0.5, 5, 6), (1.0, 7, 8))):
...     base = row * stride
...     records[base + layout[BodyFields.ANGLE][0]] = angle
...     p = base + layout[BodyFields.POSITION][0]
...     records[p:p + 2] = array.array("d", [x, y])
>>> updates = Buffer()
>>> updates.set_float_buf(records)
>>> set_space_bodies(s, flags, updates)
>>> b1.angle, tuple(b1.position), b2.angle, tuple(b2.position)
(0.5, (5.0, 6.0), 1.0, (7.0, 8.0))

Use float_stride and int_stride for the respective buffers, or extract individual components without calculating slices:

>>> values = memoryview(records)
>>> list(layout.component(values, BodyFields.POSITION, 0))
[5.0, 7.0]
>>> list(layout.component(values, BodyFields.POSITION, 1))
[6.0, 8.0]

Component indices are zero-based. These memoryview slices (and NumPy array slices) are views, not copies. Record indices follow native iteration order, adding/removing bodies can change that order.

See also the NumPy example in planet.py.

class pymunk.batch.ArbiterFields(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Flag

Flag fields to specify arbiter properties to get.

ALL = 65535

All the fields

BODY_A_ID

pymunk.Body.id of body A. Value stored in int_buf.

BODY_B_ID

pymunk.Body.id of body B. Value stored in int_buf.

CONTACT_COUNT

Number of contacts (1 or 2)`. Value stored in int_buf.

DISTANCE_1

pymunk.ContactPoint.distance of contact 1. Value stored in float_buf.

DISTANCE_2

pymunk.ContactPoint.distance of contact 2. Value stored in float_buf.

IS_FIRST_CONTACT

pymunk.Arbiter.is_first_contact. Value (0 or 1) stored in int_buf.

NORMAL

pymunk.Arbiter.normal. X and Y stored in float_buf.

POINT_A_1

pymunk.ContactPoint.point_a of contact 1. X and Y stored in float_buf.

POINT_A_2

pymunk.ContactPoint.point_a of contact 2. X and Y stored in float_buf.

POINT_B_1

pymunk.ContactPoint.point_b of contact 1. X and Y stored in float_buf.

POINT_B_2

pymunk.ContactPoint.point_b of contact 2. X and Y stored in float_buf.

TOTAL_IMPULSE

pymunk.Arbiter.total_impulse. X and Y stored in float_buf.

TOTAL_KE

pymunk.Arbiter.total_ke. Value stored in float_buf.

class pymunk.batch.BodyFields(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Flag

Flag fields to specify body properties to get.

ALL = 65535

All the fields

ANGLE

pymunk.Body.angle. Value stored in float_buf.

ANGULAR_VELOCITY

pymunk.Body.angular_velocity. Value stored in float_buf

BODY_ID

pymunk.Body.id. Value stored in int_buf.

FORCE

pymunk.Body.force. X and Y stored in float_buf.

POSITION

pymunk.Body.position. X and Y stored in float_buf.

TORQUE

pymunk.Body.torque. Value stored in float_buf

VELOCITY

pymunk.Body.velocity. X and Y stored in float_buf.

class pymunk.batch.Buffer[source]

Bases: object

clear() → None[source]

Mark the internal arrays empty (for reuse).

It is more efficient to reuse the BatchedData object and its internal arrays by calling clear, than to create a new object each step.

float_buf() → pymunk._chipmunk.ffi.buffer[source]

Return a CFFI buffer object of the floating point data in the internal array.

int_buf() → pymunk._chipmunk.ffi.buffer[source]

Return a CFFI buffer object of the integer data in the internal array.

set_float_buf(buffer: Any) → None[source]

Set the floating point internal data to the supplied buffer.

buffer should be an array of floats, implmenting the buffer/memoryview interface like a numpy array or array.array.

The storage stays exported while this Buffer or a returned view uses it. Its elements can be changed, but it must not be resized. On CPython, resizing is blocked until those exports are released.

(From Python 3.12 the buffer argument will be typed as collections.abc.Buffer)

set_int_buf(buffer: Any) → None[source]

Set the integer internal data to the supplied buffer.

buffer should be an array of ints, implmenting the buffer/memoryview interface like a numpy array or array.array.

The storage stays exported while this Buffer or a returned view uses it. Its elements can be changed, but it must not be resized. On CPython, resizing is blocked until those exports are released.

(From Python 3.12 the buffer argument will be typed as collections.abc.Buffer)

class pymunk.batch.Layout(fields: dict[BodyFields | ArbiterFields, tuple[int, int]], int_fields: frozenset[BodyFields | ArbiterFields])[source]

Bases: object

Batch field locations and helpers for the two separate buffers.

fields maps selected flags to (offset, size) tuples. Both values count scalar elements, i.e. POSITION has size 2 while ANGLE has size 1. Offsets start at zero separately within each buffer’s record. Dictionary order is native packing order. layout[field] looks up the specific field.

Query this class through get_body_layout() or get_arbiter_layout().

component(arr: Any, field: BodyFields | ArbiterFields, component: int = 0) → Any[source]

Slice one component from every record, using a zero-based index.

The buffer object cannot be used directly as arr. Instead pass a one-dimensional scalar array made from the field’s buffer. For example, a float buffer could be converted with with np.frombuffer() or memoryview(…).cast(“d”).

NumPy arrays and memoryviews return views; Python lists return copies. Mutating a writable view also changes its source array. A missing field raises KeyError; an out-of-range component raises IndexError.

property float_stride: int

Number of float elements per record.

property int_stride: int

Number of integer elements per record.

pymunk.batch.get_arbiter_layout(fields: ArbiterFields) → Layout[source]

Return a Layout for the selected fields.

The fields dict follows ArbiterFields declaration order. BODY_A_ID, BODY_B_ID, IS_FIRST_CONTACT and CONTACT_COUNT use the integer buffer; all others use the float buffer. Vectors store X then Y. Use float_stride and int_stride for elements per record, or component() to extract one scalar component across records.

ALL selects all supported fields; zero flags give empty fields and zero strides. Each call returns an independent layout. Missing contacts retain their selected slots filled with zeros; use CONTACT_COUNT to distinguish them.

pymunk.batch.get_body_layout(fields: BodyFields) → Layout[source]

Return a Layout for the selected fields.

The fields dict’s insertion order is packing order: BODY_ID, ANGLE, POSITION, VELOCITY, ANGULAR_VELOCITY, FORCE, TORQUE. BODY_ID uses the integer buffer; all other fields use the float buffer. Vectors store X then Y. Use float_stride and int_stride for elements per record, or component() to extract one scalar component across records.

Unselected fields take no space. ALL selects all supported fields; zero flags give empty fields and zero strides. Each call returns an independent layout. Changing its fields does not change native packing.

The setter uses the same float layout but ignores BODY_ID and the integer buffer. Bodies are updated in native iteration order, not by ID.

pymunk.batch.get_space_arbiters(space: Space, fields: ArbiterFields, buffers: Buffer) → None[source]

Get data for all active arbiters in the space.

Filter out the fields you are interested in with the fields property.

The data is appended to the buffers. Call Buffer.clear() before reuse unless appending is intended. See get_arbiter_layout() for packing order.

pymunk.batch.get_space_bodies(space: Space, fields: BodyFields, buffers: Buffer) → None[source]

Get data for all bodies in the space.

Filter out the fields you are interested in with the fields property.

The data is appended to the buffers. Call Buffer.clear() before reuse unless appending is intended. See get_body_layout() for packing order.

pymunk.batch.set_space_bodies(space: Space, fields: BodyFields, buffers: Buffer) → None[source]

Set data for all bodies in the space.

Filter out the fields you want to set with the fields property.

The data to update is passed in the batched_data buffers.

The float buffer follows get_body_layout(). BODY_ID and the integer buffer are ignored; records are applied in native body iteration order.