Fx2D
A C++20 2D rigid-body physics engine
Loading...
Searching...
No Matches
Scene.h
Go to the documentation of this file.
1#pragma once
2
3#include "Fx2D/Execution.h"
4#include <algorithm>
5#include <functional>
6#include <iostream>
7#include <memory>
8#include <stdexcept>
9#include <string>
10#include <unordered_map>
11#include <unordered_set>
12#include <utility>
13#include <vector>
14
15#include "Fx2D/Entity.h"
16#include "Fx2D/Input.h"
17#include "Fx2D/Joints.h"
18#include "Fx2D/Math.h"
19#include "Fx2D/Registry.h"
20#include "Fx2D/Solver.h"
21
22// A named set of entities managed as one thing: deleted together, enabled together, and by
23// default exempt from colliding with one another. Membership carries no connectivity or
24// uniformity requirement; builders that populate groups may impose their own.
26 friend class FxScene;
27 std::string m_name;
28 int32_t m_collision_group = 0; // unique negative id when self-collision is off, else 0
29 std::vector<std::shared_ptr<FxEntity>> m_members;
30
31 public:
32 explicit FxEntityGroup(const std::string& name) : m_name(name) {}
33 const std::string& get_name() const { return m_name; }
34 const std::vector<std::shared_ptr<FxEntity>>& members() const { return m_members; }
35 size_t size() const { return m_members.size(); }
36 void set_enabled(bool enabled) {
37 for (auto& e : m_members) {
38 if (!e) continue;
39 e->enabled = enabled;
40 if (enabled) e->wake();
41 }
42 }
43};
44
45// A pair of entities that started or stopped touching during a step.
47 // Borrowed, like FxContact's -- and kept alive by the same pins. Valid until the next
48 // step(); do not hold on to an event past the frame that produced it.
49 FxEntity* entity1 = nullptr;
50 FxEntity* entity2 = nullptr;
51 // True if either entity is a sensor, so no impulse was applied for this pair.
52 bool is_trigger = false;
53};
54
55// Scene class takes care of entities motion and collisions
56class FxScene {
57 private:
58 // Per-pair solver state surviving between substeps and steps. Held in a slot vector rather
59 // than looked up by key each time: at 14 substeps that lookup was the bulk of the step's
60 // hashing.
61 struct FxContactPairSlot {
62 // Warm-start impulses. Scalars only, so the cache never keeps entities alive.
63 float jn[2] = {0.0f, 0.0f};
64 float jt[2] = {0.0f, 0.0f};
65 FxVec2f normal{0.0f, 0.0f}; // contact normal at time of caching, used to detect basis flips
66
67 // Which step this pair was last seen in, and where its contact sits in m_step_contacts
68 // for that step. Together they let the per-substep write-back skip the hash entirely
69 // after the first substep that sees the pair.
70 uint64_t step_stamp = 0;
71 size_t step_slot = kNoStepSlot;
72 };
73 static constexpr size_t kNoStepSlot = static_cast<size_t>(-1);
74
75 // no of entities in the scene can not exceed 4096
76 static constexpr size_t m_enitities_limit = 4096;
77 // max and min time step values that can be use in step method
78 static constexpr double m_max_time_step = 0.06;
79 static constexpr double m_min_time_step = 1e-3;
80 // 14x4 measured fastest among configurations passing the full quality suite;
81 // fewer passes fail tall stacks, more substeps at 8 passes just cost more.
82 size_t m_substeps = 14;
83 size_t m_velocity_passes = 4;
84 // dirty flag to track when any entity is deleted
85 bool m_entities_dirty = false;
86 // total time elapsed since scene start
87 double m_time_elapsed = 0.0;
88 // Pair slots, plus the key -> slot map and the free list that recycles slots of pairs that
89 // stopped touching. A contact carries its slot index, so only the first substep that sees a
90 // pair in a given step pays for a lookup.
91 std::vector<FxContactPairSlot> m_contact_slots;
92 std::unordered_map<uint64_t, uint32_t> m_contact_slot_index;
93 std::vector<uint32_t> m_free_contact_slots;
94 // Slot already resolved for each entry of the current broad-phase pair list, or kNoSlot.
95 // Reset whenever that list is rebuilt; the pair list is stable across the substeps of a
96 // step, so after the first substep a contact finds its slot by index instead of by hash.
97 std::vector<uint32_t> m_pair_slot;
98 // The contact each broad-phase pair holds this step, re-measured by later substeps instead of
99 // detected again. Reset with the pair list, once per step.
100 std::vector<FxHeldContact> m_held_contacts;
101 // The velocity each body's proxy was swept with this step, by packed index.
102 std::vector<FxVec2f> m_swept_velocity;
103 // Monotonic step counter, used only to stamp pair slots. Never reset by reset(), because a
104 // stale stamp equal to the current step would revive a dead slot's step_slot.
105 uint64_t m_step_counter = 0;
106
107 // This step's touching pairs and the previous step's, keeping the last occurrence of each
108 // so impulses are final. The previous buffer lets end events still name their entities.
109 std::vector<FxContact> m_step_contacts;
110 std::unordered_map<uint64_t, size_t> m_step_contact_index;
111 std::vector<FxContact> m_prev_contacts;
112 std::unordered_map<uint64_t, size_t> m_prev_contact_index;
113 std::vector<FxContactEvent> m_begin_contacts;
114 std::vector<FxContactEvent> m_end_contacts;
115
116 // Ownership for the borrowed pointers in the contact buffers. Rebuilt once per step and
117 // swapped alongside them, so an entity deleted between steps stays alive exactly as long as
118 // a buffer still names it.
119 std::vector<std::shared_ptr<FxEntity>> m_step_pins;
120 std::vector<std::shared_ptr<FxEntity>> m_prev_pins;
121
122 // Solver-local velocity columns, gathered and scattered once per substep around the
123 // velocity passes. A member so the allocation happens once per scene, not once per step.
124 FxSolverBodies m_solver_bodies;
125 // Per-substep velocity-solver scratch, one entry per live contact.
126 std::vector<FxContactSolverData> m_contact_solver_data;
127
128 // Colour partition of the broad-phase pair list, the colour each contact inherited from its
129 // pair, the contact order that groups them, and the transposed batch the sweeps run over.
130 // All members for their capacity: rebuilt every substep, allocating only on the first.
131 FxContactGraph m_contact_graph;
132 std::vector<uint32_t> m_contact_colors;
133 std::vector<uint32_t> m_colored_contacts;
134 FxContactBatch m_contact_batch;
135
136 // One contiguous run of the batch: a single colour and a single manifold size.
137 struct FxBatchRun {
138 uint32_t begin = 0;
139 uint32_t end = 0;
140 int slots = 2;
141 };
142 std::vector<FxBatchRun> m_batch_runs;
143
144 // Inserts a contact into the current step buffer, replacing any earlier one for the pair.
145 void record_contact(const FxContact& contact);
146 // Takes ownership of every entity the current step buffer names, so the buffer can outlive
147 // a delete_entity call.
148 void pin_contact_entities();
149 // The velocity half of one substep: gather, solve colour by colour, scatter.
150 void solve_contact_velocities(std::vector<FxContact>& contacts,
151 const std::vector<std::shared_ptr<FxEntity>>& entities_vec,
152 size_t iter);
153 // Resolves (or allocates) the pair slot for a contact, stamping the key and slot onto it.
154 // `pair_index` addresses the broad-phase pair list, which is what lets the hash lookup
155 // happen once per pair per step rather than once per pair per substep.
156 void bind_contact_slot(FxContact& contact, size_t pair_index);
157 // Drops slots for pairs that produced no contact this step.
158 void evict_stale_contact_slots();
159 // Diffs the current step buffer against the previous one to build begin/end events.
160 void build_contact_events();
161
162 protected:
163 FxEntityRegistry m_entities; // stores pointers to all entities with collision management
166 FxNamedRegistry<FxJoint> m_joints; // stores all joints
167 FxMouseJoint m_mouse_joint; // the one transient click-drag spring
168 bool m_mouse_drag = false; // drive m_mouse_joint from input() each step
169 // Attaches, moves and releases the mouse joint from the left button and cursor.
171
172 public:
173 // scene size [x, y] units
175 // background color or texture path
176 FxVec4ui8 fillColor{230, 230, 230, 255};
177 std::string fillTexturePath = "";
178 // gravity config [x, y]
179 FxVec2f gravity{0.0f, -9.81f};
180
181 // constructor, destructor
182 FxScene(FxVec2ui SceneSize) : m_entities(m_enitities_limit), size(SceneSize) {}
183 ~FxScene() = default;
184
185 // Restores the captured composition and every entity to its initial state, clearing sleep,
186 // PID, contact and input state. Unconditional: nothing running can decline it.
187 void reset();
188 // Marks the current composition as what reset() restores. Taken on the first step() if not
189 // called explicitly; call it when entities are added or removed before that.
191 // simulation step
192 void step(double step_dt);
193 // get total time elapsed since scene start
194 double time_elapsed() const { return m_time_elapsed; }
195 void set_substeps(const size_t& substeps) { m_substeps = substeps; }
196 // Velocity sweeps per substep; convergence trades against cost jointly with substeps.
197 void set_velocity_passes(size_t passes) { m_velocity_passes = passes; }
198 void set_gravity(const FxVec2f& o_gravity) { gravity = o_gravity; }
199 // custom call back function called after every time step, user gets access to the scene.
200 void set_step_callback(const std::function<void(FxScene&, double dt)>& callback) {
201 m_func_step_callback = callback;
202 }
203 // Called at the end of reset(), once entities are restored, so state layered on top of the
204 // scene can be restored too.
205 void set_reset_callback(const std::function<void(FxScene&)>& callback) {
206 m_func_reset_callback = callback;
207 }
208 // Method to set a fillColor
209 void set_fillColor(const FxVec4ui8& color) {
210 fillColor = color;
211 fillTexturePath = "";
212 }
213 void set_fillTexture(const std::string& filePath) { fillTexturePath = filePath; }
214 // Returns true if added; false if an entity with the name already exists.
215 bool add_entity(const std::shared_ptr<FxEntity>& entity);
216 // Returns true if deletion succeeded, false if the entity wasn't found.
217 bool delete_entity(const std::string& name);
218 // Returns the entity pointer if found; otherwise returns nullptr.
219 std::shared_ptr<FxEntity> get_entity(const std::string& name) const;
220
221 // Returns true if added; false if a constraint with the name already exists
222 bool add_constraint(const std::shared_ptr<FxConstraint>& constraint);
223 // Returns true if deletion succeeded, false if the constraint wasn't found
224 bool delete_constraint(const std::string& name);
225 // Returns the constraint pointer if found; otherwise returns nullptr.
226 std::shared_ptr<FxConstraint> get_constraint(const std::string& name) const;
227
228 // Returns true if added; false if the name is taken or a constraint fails to register, in
229 // which case the joint and any constraints it already added are removed.
230 bool add_joint(const std::shared_ptr<FxJoint>& joint);
231 // Returns true if deletion succeeded, false if the joint wasn't found
232 bool delete_joint(const std::string& name);
233 // Returns the joint pointer if found; otherwise returns nullptr.
234 std::shared_ptr<FxJoint> get_joint(const std::string& name) const;
235
236 // Keyboard and mouse state, filled by a renderer each frame. A headless scene has none
237 // until user code injects it, which is how it scripts triggers.
238 const FxInput& input() const { return m_input; }
239 FxInput& input() { return m_input; }
240
241 // The click-drag spring. Drive it yourself through attach()/set_target()/release(), or
242 // enable_mouse_drag() to have the scene do so from input(): left button on a dynamic
243 // body attaches at the cursor, holding drags, releasing lets go. Off by default; the
244 // YAML key `scene: mouse_drag: true` turns it on.
246 const FxMouseJoint& mouse_joint() const { return m_mouse_joint; }
247 void enable_mouse_drag(bool enable) { m_mouse_drag = enable; }
248 bool mouse_drag_enabled() const { return m_mouse_drag; }
249
250 // Contacts from the most recent step, one per touching pair, in a reproducible but
251 // unspecified order. Sensor pairs appear with zero impulses. Valid until step() or reset().
252 const std::vector<FxContact>& contacts() const { return m_step_contacts; }
253 // Pairs that began touching during the most recent step (not touching in the step before).
254 const std::vector<FxContactEvent>& begin_contact_events() const { return m_begin_contacts; }
255 // Pairs that stopped touching during the most recent step (touching in the step before).
256 const std::vector<FxContactEvent>& end_contact_events() const { return m_end_contacts; }
257
258 // ---------------------------------------------------------------- spatial queries
259 // Overlap runs the simulation's own narrow phase, so queries and contacts agree. Disabled
260 // entities and those without collision geometry are never reported.
261
262 // Nearest entity struck, searching `max_distance` along `direction`. A ray starting inside
263 // a body reports it at distance 0.
264 bool raycast(const FxVec2f& origin, const FxVec2f& direction, float max_distance,
265 FxRayHit& out_hit) const;
266 // Every entity along the ray, nearest first.
267 void raycast_all(const FxVec2f& origin, const FxVec2f& direction, float max_distance,
268 std::vector<FxRayHit>& out_hits) const;
269
270 // Entities overlapping an arbitrary shape placed at `pose` (x, y, theta).
271 void overlap_shape(const FxShape& shape, const FxVec3f& pose,
272 std::vector<std::shared_ptr<FxEntity>>& out) const;
273 // Entities overlapping a circle, an axis-aligned box, or a single point.
274 void overlap_circle(const FxVec2f& centre, float radius,
275 std::vector<std::shared_ptr<FxEntity>>& out) const;
276 void overlap_box(const FxVec2f& centre, const FxVec2f& extents,
277 std::vector<std::shared_ptr<FxEntity>>& out) const;
278 void overlap_point(const FxVec2f& point, std::vector<std::shared_ptr<FxEntity>>& out) const;
279 // First entity covering the point, or nullptr — "what is under the cursor".
280 std::shared_ptr<FxEntity> entity_at_point(const FxVec2f& point) const;
281
282 // Registry access methods
283 size_t entity_count() const { return m_entities.size(); }
284 size_t constraint_count() const { return m_constraints.size(); }
285 size_t joint_count() const { return m_joints.size(); }
286 bool entity_exists(const std::string& name) const {
287 return m_entities.get_rawptr(name) != nullptr;
288 }
289 bool constraint_exists(const std::string& name) const {
290 return m_constraints.get_rawptr(name) != nullptr;
291 }
292 bool joint_exists(const std::string& name) const {
293 return m_joints.get_rawptr(name) != nullptr;
294 }
295
296 // ---------------------------------------------------------------- entity groups
297 // Returns the new group, or nullptr if the name is taken. With self_collide false the
298 // group's members never collide with one another; outsiders are unaffected.
299 std::shared_ptr<FxEntityGroup> create_group(const std::string& name, bool self_collide = false);
300 // Adds the entity to the scene if needed, then to the group.
301 bool add_to_group(const std::shared_ptr<FxEntityGroup>& group,
302 const std::shared_ptr<FxEntity>& entity);
303 std::shared_ptr<FxEntityGroup> get_group(const std::string& name) const {
304 return m_groups.get(name);
305 }
306 // Deletes every member entity, then the group itself.
307 bool delete_group(const std::string& name);
308 size_t group_count() const { return m_groups.size(); }
309 // base if free, else base_1, base_2, ... — for builders generating entity names.
310 std::string unique_entity_name(const std::string& base) const {
311 return m_entities.make_unique_name(base);
312 }
313
314 // Collision pair management (delegated to entity registry)
315 void enable_collision(const std::string& entity1_name, const std::string& entity2_name) {
316 m_entities.enable_collision(entity1_name, entity2_name);
317 }
318 void disable_collision(const std::string& entity1_name, const std::string& entity2_name) {
319 m_entities.disable_collision(entity1_name, entity2_name);
320 }
321
322 // for_each_entity applies the given function on each entity in a given execution mode
323 template<typename ExecPolicy, typename Func>
324 void for_each_entity(ExecPolicy&& policy, Func&& func) {
325 m_entities.for_each(std::forward<ExecPolicy>(policy), std::forward<Func>(func));
326 }
327
328 // transform_entities collects return values vector in a given execution mode
329 template<typename ExecPolicy, typename Func>
331 ExecPolicy&& policy, Func&& func,
332 std::vector<std::invoke_result_t<Func, std::shared_ptr<FxEntity>>>& results) {
333 m_entities.transform(std::forward<ExecPolicy>(policy), std::forward<Func>(func), results);
334 }
335
336 private:
337 // Removes constraints with dead entities
338 void sweep_dead_constraints();
339 // Removes joints with dead entities
340 void sweep_dead_joints();
341
342 // custom callback function invoked in the step method
343 std::function<void(FxScene&, double dt)> m_func_step_callback;
344 std::function<void(FxScene&)> m_func_reset_callback;
345
346 // Composition reset() restores; shared_ptr so a deleted entity can be put back.
347 std::vector<std::shared_ptr<FxEntity>> m_initial_entities;
348 std::vector<std::shared_ptr<FxConstraint>> m_initial_constraints;
349 std::vector<std::shared_ptr<FxJoint>> m_initial_joints;
350 // Membership is copied at capture, since the live group object mutates afterwards.
351 std::vector<std::pair<std::shared_ptr<FxEntityGroup>, std::vector<std::shared_ptr<FxEntity>>>>
352 m_initial_groups;
353 int32_t m_next_collision_group = -1;
354 bool m_has_initial_snapshot = false;
355
356 // Never read by the solver; input reaches the simulation only through user callbacks.
357 FxInput m_input;
358};
FxVec< unsigned int, 2 > FxVec2ui
Definition Math.h:421
FxVec< uint8_t, 4 > FxVec4ui8
Definition Math.h:422
void set_enabled(bool enabled)
Definition Scene.h:36
const std::string & get_name() const
Definition Scene.h:33
size_t size() const
Definition Scene.h:35
friend class FxScene
Definition Scene.h:26
const std::vector< std::shared_ptr< FxEntity > > & members() const
Definition Scene.h:34
FxEntityGroup(const std::string &name)
Definition Scene.h:32
A named rigid body with state, material properties, geometry, and forces.
Definition Entity.h:49
Input state read by gameplay code or injected by a headless producer.
Definition Input.h:28
Owns a simulated world and advances it with step().
Definition Scene.h:56
void reset()
const FxVec2ui size
Definition Scene.h:174
void set_gravity(const FxVec2f &o_gravity)
Definition Scene.h:198
FxNamedRegistry< FxConstraint > m_constraints
Definition Scene.h:164
size_t entity_count() const
Definition Scene.h:283
~FxScene()=default
void transform_entities(ExecPolicy &&policy, Func &&func, std::vector< std::invoke_result_t< Func, std::shared_ptr< FxEntity > > > &results)
Definition Scene.h:330
const std::vector< FxContactEvent > & begin_contact_events() const
Definition Scene.h:254
std::shared_ptr< FxEntity > entity_at_point(const FxVec2f &point) const
FxVec4ui8 fillColor
Definition Scene.h:176
bool add_joint(const std::shared_ptr< FxJoint > &joint)
bool delete_joint(const std::string &name)
FxMouseJoint m_mouse_joint
Definition Scene.h:167
void enable_mouse_drag(bool enable)
Definition Scene.h:247
FxScene(FxVec2ui SceneSize)
Definition Scene.h:182
void capture_initial_state()
void step(double step_dt)
void overlap_shape(const FxShape &shape, const FxVec3f &pose, std::vector< std::shared_ptr< FxEntity > > &out) const
void for_each_entity(ExecPolicy &&policy, Func &&func)
Definition Scene.h:324
FxInput & input()
Definition Scene.h:239
void overlap_point(const FxVec2f &point, std::vector< std::shared_ptr< FxEntity > > &out) const
void raycast_all(const FxVec2f &origin, const FxVec2f &direction, float max_distance, std::vector< FxRayHit > &out_hits) const
void set_reset_callback(const std::function< void(FxScene &)> &callback)
Definition Scene.h:205
void overlap_circle(const FxVec2f &centre, float radius, std::vector< std::shared_ptr< FxEntity > > &out) const
double time_elapsed() const
Definition Scene.h:194
void overlap_box(const FxVec2f &centre, const FxVec2f &extents, std::vector< std::shared_ptr< FxEntity > > &out) const
void enable_collision(const std::string &entity1_name, const std::string &entity2_name)
Definition Scene.h:315
size_t group_count() const
Definition Scene.h:308
bool constraint_exists(const std::string &name) const
Definition Scene.h:289
bool mouse_drag_enabled() const
Definition Scene.h:248
bool m_mouse_drag
Definition Scene.h:168
void set_fillTexture(const std::string &filePath)
Definition Scene.h:213
void drive_mouse_joint()
FxVec2f gravity
Definition Scene.h:179
const FxMouseJoint & mouse_joint() const
Definition Scene.h:246
std::shared_ptr< FxEntityGroup > create_group(const std::string &name, bool self_collide=false)
const std::vector< FxContactEvent > & end_contact_events() const
Definition Scene.h:256
std::shared_ptr< FxConstraint > get_constraint(const std::string &name) const
std::shared_ptr< FxJoint > get_joint(const std::string &name) const
size_t constraint_count() const
Definition Scene.h:284
bool delete_constraint(const std::string &name)
bool joint_exists(const std::string &name) const
Definition Scene.h:292
size_t joint_count() const
Definition Scene.h:285
const FxInput & input() const
Definition Scene.h:238
FxMouseJoint & mouse_joint()
Definition Scene.h:245
void set_substeps(const size_t &substeps)
Definition Scene.h:195
std::shared_ptr< FxEntity > get_entity(const std::string &name) const
std::string unique_entity_name(const std::string &base) const
Definition Scene.h:310
void set_step_callback(const std::function< void(FxScene &, double dt)> &callback)
Definition Scene.h:200
const std::vector< FxContact > & contacts() const
Definition Scene.h:252
void set_velocity_passes(size_t passes)
Definition Scene.h:197
bool entity_exists(const std::string &name) const
Definition Scene.h:286
void set_fillColor(const FxVec4ui8 &color)
Definition Scene.h:209
std::shared_ptr< FxEntityGroup > get_group(const std::string &name) const
Definition Scene.h:303
FxEntityRegistry m_entities
Definition Scene.h:163
bool delete_entity(const std::string &name)
bool add_entity(const std::shared_ptr< FxEntity > &entity)
bool add_constraint(const std::shared_ptr< FxConstraint > &constraint)
std::string fillTexturePath
Definition Scene.h:177
void disable_collision(const std::string &entity1_name, const std::string &entity2_name)
Definition Scene.h:318
FxNamedRegistry< FxEntityGroup > m_groups
Definition Scene.h:165
bool delete_group(const std::string &name)
bool add_to_group(const std::shared_ptr< FxEntityGroup > &group, const std::shared_ptr< FxEntity > &entity)
FxNamedRegistry< FxJoint > m_joints
Definition Scene.h:166
bool raycast(const FxVec2f &origin, const FxVec2f &direction, float max_distance, FxRayHit &out_hit) const
Single-precision 2D vector.
Single-precision three-component vector, including poses.
A begin/end contact event from the latest simulation step.
Definition Scene.h:46
bool is_trigger
Definition Scene.h:52
FxEntity * entity2
Definition Scene.h:50
FxEntity * entity1
Definition Scene.h:49
Contact data produced by the narrow phase and solver.
Definition Solver.h:71
Result from a ray cast against the scene.
Definition Geometry.h:478
Unified circle, capsule, polygon, edge, and chain representation.
Definition Geometry.h:46