Source code for pymunk.batch

"""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.


"""

__docformat__ = "reStructuredText"

__all__ = [
    "ArbiterFields",
    "BodyFields",
    "Buffer",
    "Layout",
    "get_arbiter_layout",
    "get_body_layout",
    "get_space_arbiters",
    "get_space_bodies",
    "set_space_bodies",
]

from enum import Flag
from operator import index
from typing import Any, Union

from ._chipmunk_cffi import ffi, lib
from .space import Space


[docs] class BodyFields(Flag): """Flag fields to specify body properties to get.""" BODY_ID = lib.BODY_ID """:py:attr:`pymunk.Body.id`. Value stored in int_buf.""" ANGLE = lib.ANGLE """:py:attr:`pymunk.Body.angle`. Value stored in float_buf.""" POSITION = lib.POSITION """:py:attr:`pymunk.Body.position`. X and Y stored in float_buf.""" VELOCITY = lib.VELOCITY """:py:attr:`pymunk.Body.velocity`. X and Y stored in float_buf.""" ANGULAR_VELOCITY = lib.ANGULAR_VELOCITY """:py:attr:`pymunk.Body.angular_velocity`. Value stored in float_buf""" FORCE = lib.FORCE """:py:attr:`pymunk.Body.force`. X and Y stored in float_buf.""" TORQUE = lib.TORQUE """:py:attr:`pymunk.Body.torque`. Value stored in float_buf""" ALL = 0xFFFF """All the fields"""
[docs] class ArbiterFields(Flag): """Flag fields to specify arbiter properties to get.""" BODY_A_ID = lib.BODY_A_ID """:py:attr:`pymunk.Body.id` of body A. Value stored in int_buf.""" BODY_B_ID = lib.BODY_B_ID """:py:attr:`pymunk.Body.id` of body B. Value stored in int_buf.""" TOTAL_IMPULSE = lib.TOTAL_IMPULSE """:py:attr:`pymunk.Arbiter.total_impulse`. X and Y stored in float_buf.""" TOTAL_KE = lib.TOTAL_KE """:py:attr:`pymunk.Arbiter.total_ke`. Value stored in float_buf.""" IS_FIRST_CONTACT = lib.IS_FIRST_CONTACT """:py:attr:`pymunk.Arbiter.is_first_contact`. Value (0 or 1) stored in int_buf.""" NORMAL = lib.NORMAL """:py:attr:`pymunk.Arbiter.normal`. X and Y stored in float_buf.""" CONTACT_COUNT = lib.CONTACT_COUNT """Number of contacts (1 or 2)`. Value stored in int_buf.""" POINT_A_1 = lib.POINT_A_1 """:py:attr:`pymunk.ContactPoint.point_a` of contact 1. X and Y stored in float_buf.""" POINT_B_1 = lib.POINT_B_1 """:py:attr:`pymunk.ContactPoint.point_b` of contact 1. X and Y stored in float_buf.""" DISTANCE_1 = lib.DISTANCE_1 """:py:attr:`pymunk.ContactPoint.distance` of contact 1. Value stored in float_buf.""" POINT_A_2 = lib.POINT_A_2 """:py:attr:`pymunk.ContactPoint.point_a` of contact 2. X and Y stored in float_buf.""" POINT_B_2 = lib.POINT_B_2 """:py:attr:`pymunk.ContactPoint.point_b` of contact 2. X and Y stored in float_buf.""" DISTANCE_2 = lib.DISTANCE_2 """:py:attr:`pymunk.ContactPoint.distance` of contact 2. Value stored in float_buf.""" ALL = 0xFFFF """All the fields"""
# Explicit packing order, independent of numeric flag values. Keep these # tables in sync with the native iterators in pymunk_cffi/extensions.c. _BODY_LAYOUT = ( (BodyFields.BODY_ID, "int", 1), (BodyFields.ANGLE, "float", 1), (BodyFields.POSITION, "float", 2), (BodyFields.VELOCITY, "float", 2), (BodyFields.ANGULAR_VELOCITY, "float", 1), (BodyFields.FORCE, "float", 2), (BodyFields.TORQUE, "float", 1), ) _ARBITER_LAYOUT = ( (ArbiterFields.BODY_A_ID, "int", 1), (ArbiterFields.BODY_B_ID, "int", 1), (ArbiterFields.TOTAL_IMPULSE, "float", 2), (ArbiterFields.TOTAL_KE, "float", 1), (ArbiterFields.IS_FIRST_CONTACT, "int", 1), (ArbiterFields.NORMAL, "float", 2), (ArbiterFields.CONTACT_COUNT, "int", 1), (ArbiterFields.POINT_A_1, "float", 2), (ArbiterFields.POINT_B_1, "float", 2), (ArbiterFields.DISTANCE_1, "float", 1), (ArbiterFields.POINT_A_2, "float", 2), (ArbiterFields.POINT_B_2, "float", 2), (ArbiterFields.DISTANCE_2, "float", 1), )
[docs] class Layout: """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(). """ def __init__( self, fields: dict[Union[BodyFields, ArbiterFields], tuple[int, int]], int_fields: frozenset[Union[BodyFields, ArbiterFields]], ) -> None: self.fields = fields self._int_fields = int_fields def __getitem__(self, field: Union[BodyFields, ArbiterFields]) -> tuple[int, int]: """Return the field's (element offset, field size in elements).""" return self.fields[field] @property def float_stride(self) -> int: """Number of float elements per record.""" return sum( size for field, (offset, size) in self.fields.items() if field not in self._int_fields ) @property def int_stride(self) -> int: """Number of integer elements per record.""" return sum( size for field, (offset, size) in self.fields.items() if field in self._int_fields )
[docs] def component( self, arr: Any, field: Union[BodyFields, ArbiterFields], component: int = 0 ) -> Any: """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. """ offset, size = self.fields[field] component = index(component) if not 0 <= component < size: raise IndexError("component index out of range") stride = self.int_stride if field in self._int_fields else self.float_stride return arr[offset + component :: stride]
def _make_layout( fields: Union[BodyFields, ArbiterFields], spec: tuple[tuple[Any, str, int], ...], ) -> Layout: offsets = {"float": 0, "int": 0} layout = {} for field, buffer, size in spec: if field in fields: layout[field] = (offsets[buffer], size) offsets[buffer] += size return Layout( layout, frozenset(field for field, buffer, size in spec if buffer == "int") )
[docs] def get_body_layout(fields: BodyFields) -> Layout: """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. """ return _make_layout(fields, _BODY_LAYOUT)
[docs] def get_arbiter_layout(fields: ArbiterFields) -> Layout: """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. """ return _make_layout(fields, _ARBITER_LAYOUT)
[docs] class Buffer: _int_arr: ffi.CData = None _float_arr: ffi.CData = None def __init__(self) -> None: """Create a empty BatchData object.""" self._float_arr = lib.pmFloatArrayNew(0) self._int_arr = lib.pmIntArrayNew(0) self._int_buf = None self._float_buf = None
[docs] def clear(self) -> None: """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. """ self._float_arr.num = 0 self._int_arr.num = 0
[docs] def float_buf(self) -> ffi.buffer: """Return a CFFI buffer object of the floating point data in the internal array. """ arr = self._float_buf if arr is None: arr = self._float_arr.arr return ffi.buffer(arr, ffi.sizeof("cpFloat") * self._float_arr.num)
[docs] def set_float_buf(self, buffer: Any) -> None: """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) """ arr = ffi.from_buffer("cpFloat[]", buffer) self._float_buf = arr self._float_arr.arr = arr self._float_arr.max = len(arr) self._float_arr.num = len(arr)
[docs] def int_buf(self) -> ffi.buffer: """Return a CFFI buffer object of the integer data in the internal array. """ arr = self._int_buf if arr is None: arr = self._int_arr.arr return ffi.buffer(arr, ffi.sizeof("uintptr_t") * self._int_arr.num)
[docs] def set_int_buf(self, buffer: Any) -> None: """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) """ arr = ffi.from_buffer("uintptr_t[]", buffer) self._int_buf = arr self._int_arr.arr = arr self._int_arr.max = len(arr) self._int_arr.num = len(arr)
[docs] def get_space_bodies(space: Space, fields: BodyFields, buffers: Buffer) -> None: """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 :func:`get_body_layout` for packing order. """ _data = ffi.new("pmBatchedData *") _data.fields = fields.value _data.floatArray = buffers._float_arr _data.intArray = buffers._int_arr lib.cpSpaceEachBody( space._space, ffi.addressof(lib, "pmSpaceBodyGetIteratorFuncBatched"), _data, )
[docs] def set_space_bodies(space: Space, fields: BodyFields, buffers: Buffer) -> None: """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 :func:`get_body_layout`. BODY_ID and the integer buffer are ignored; records are applied in native body iteration order. """ _data = ffi.new("pmBatchedData *") _data.fields = fields.value _data.floatArray = buffers._float_arr _data.intArray = buffers._int_arr # To iterate from the beginning of the array, num should start at 0 orig_float_num = buffers._float_arr.num buffers._float_arr.num = 0 lib.cpSpaceEachBody( space._space, ffi.addressof(lib, "pmSpaceBodySetIteratorFuncBatched"), _data, ) buffers._float_arr.num = orig_float_num
[docs] def get_space_arbiters(space: Space, fields: ArbiterFields, buffers: Buffer) -> None: """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 :func:`get_arbiter_layout` for packing order. """ _data = ffi.new("pmBatchedData *") _data.fields = fields.value _data.floatArray = buffers._float_arr _data.intArray = buffers._int_arr lib.cpSpaceEachCachedArbiter( space._space, ffi.addressof(lib, "pmSpaceArbiterIteratorFuncBatched"), _data, )