Understanding Matter.Engine.clear in Matter.js
Matter.Engine.clear is a core utility method in
Matter.js designed to reset an engine's internal simulation state
without requiring developers to instantiate a new Engine
object. This article examines the exact mechanics behind how this method
flushes active collision pairs, purges broadphase and narrowphase
structures, clears the composite world tree, and severs dangling object
references to prevent memory leaks during scene transitions or
simulation restarts.
Clearing the World Composite
The clearance process begins at the root container of the simulation:
engine.world. Under the hood,
Matter.Engine.clear invokes
Matter.Composite.clear(engine.world, false).
This operation recursively traverses the composite hierarchy:
- Bodies Array: All physical bodies inside
engine.world.bodiesare removed, detaching their geometry, motion vectors, and force accumulators. - Constraints Array: All joint linkages, springs, and
pin constraints in
engine.world.constraintsare emptied. - Nested Composites: Any sub-composites grouped within the root world are cleared recursively down to leaf nodes.
By passing false as the second argument, the root
composite itself is preserved while its contents are completely
evacuated.
Flushing Collision Pairs
During execution, Matter.js tracks persistent contact points across
frames using a dedicated collision pair manager located at
engine.pairs. This cache stores active collision pairs
(Pair objects), separation vectors, friction data, and
penetration depths to solve impulses efficiently over time.
Matter.Engine.clear calls
Matter.Pairs.clear(engine.pairs). This operation:
- Empties the
pairs.tablehash map, which indexes collisions using unique body pair keys (e.g.,idA_idB). - Clears the
pairs.listarray, which holds active contact manifolds scheduled for resolution. - Resets internal collision metrics, including active collision counts
and collision lifecycle states (
collisionStart,collisionActive,collisionEnd).
Purging the pairs table ensures that newly spawned bodies in subsequent frames do not inherit outdated impulse values or phantom collision responses from previous objects.
Resetting Broadphase Spatial Structures
Before calculating detailed vertex-level intersections, Matter.js uses a broadphase collision detector (such as a spatial grid or bounding box tree) to filter out distant bodies.
Matter.Engine.clear resets this system by:
- Wiping spatial partitioning buckets or grid cells containing
references to body bounding boxes (
AABB). - Resetting the internal pair candidate list generated by
Detector.collisions(). - Ensuring that dead spatial nodes no longer reference body identifiers.
This prevents the narrowphase collision solver from receiving stale body pairs that no longer exist in the physics world.
Resetting Engine Timing and Metrics
The engine's internal step pipeline relies on frame delta accumulation to maintain deterministic updates. When cleared:
- Timers: The accumulator tracking fractional frame times is zeroed out.
- Metrics: Simulation metrics, such as frame counter, broadphase time, narrowphase time, and solver duration, are re-initialized.
- Event Queues: Internal event hooks registered directly on engine update loops are cleared of pending tick payloads.
Facilitating Garbage Collection
JavaScript utilizes reference-counting and mark-and-sweep garbage
collection. By systematically emptying arrays (bodies,
constraints, composites,
pairs.list) and setting hash table entries
(pairs.table) to empty structures,
Matter.Engine.clear breaks circular references between
collision pairs and body definitions.
Once these references are severed from the root engine
instance, the JavaScript runtime's garbage collector can safely reclaim
the memory allocated for body vertices, collision caches, parts arrays,
and render bindings.