SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
PhysicsWorld.cpp
Go to the documentation of this file.
1#include <Camera/Camera.hpp>
2#include <Core/GameObject.hpp>
3#include <Core/Logger.hpp>
8#include <algorithm>
9#include <cmath>
10
11namespace Sleak {
12namespace Physics {
13
14namespace {
15
16/// Rigidbody that collision response can push, or nullptr if none.
17RigidbodyComponent* GetMovableBody(ColliderComponent* collider) {
18 GameObject* owner = collider->GetOwner();
19 if (!owner) return nullptr;
20 auto* rb = owner->GetComponent<RigidbodyComponent>();
21 if (!rb || rb->GetBodyType() == BodyType::Static) return nullptr;
22 return rb;
23}
24
25/// World position and scale the narrowphase uses for a collider.
26void GetColliderPose(ColliderComponent* collider, Vector3D& pos,
27 Vector3D& scale) {
28 GameObject* owner = collider->GetOwner();
29 if (auto* transform = owner->GetComponent<TransformComponent>()) {
30 pos = transform->GetWorldPosition() + collider->GetOffset();
31 scale = transform->GetWorldScale();
32 } else if (auto* cam = dynamic_cast<Camera*>(owner)) {
33 pos = cam->GetPosition() + collider->GetOffset();
34 }
35}
36
37/// Distance a dynamic body travels next step, zero for anything else.
38Vector3D PredictDisplacement(ColliderComponent* collider, float dt) {
39 Vector3D none(0, 0, 0);
40 RigidbodyComponent* rb = GetMovableBody(collider);
41 if (!rb || rb->GetBodyType() != BodyType::Dynamic) return none;
42
43 Vector3D d = rb->GetVelocity() * dt;
44 if (!std::isfinite(d.GetX()) || !std::isfinite(d.GetY()) ||
45 !std::isfinite(d.GetZ())) {
46 return none;
47 }
48 return d;
49}
50
51} // namespace
52
54 if (!collider) return;
55
56 // Check not already registered
57 for (auto* c : m_colliders) {
58 if (c == collider) return;
59 }
60
61 AABB worldAABB = collider->GetWorldAABB();
62 int proxyId = m_tree.Insert(worldAABB, collider);
63 collider->SetProxyId(proxyId);
64 m_colliders.push_back(collider);
65}
66
68 if (!collider) return;
69
70 int proxyId = collider->GetProxyId();
71 if (proxyId >= 0) {
72 m_tree.Remove(proxyId);
73 collider->SetProxyId(-1);
74 }
75
76 m_colliders.erase(
77 std::remove(m_colliders.begin(), m_colliders.end(), collider),
78 m_colliders.end());
79}
80
81void PhysicsWorld::Step(float dt) {
82 // We need wasGrounded BEFORE clearing, so gravity doesn't apply while standing
83 for (auto* collider : m_colliders) {
84 if (auto* owner = collider->GetOwner()) {
85 auto* rb = owner->GetComponent<RigidbodyComponent>();
86 if (!rb) continue;
87
88 bool wasGrounded = rb->IsGrounded();
89 rb->ClearCollisionState();
90
91 if (rb->GetBodyType() == BodyType::Dynamic) {
92 // Reset grounded — collision detection will re-set it if still touching ground
93 rb->SetGrounded(false);
94
95 if (rb->GetUseGravity()) {
96 Math::Vector3D vel = rb->GetVelocity();
97
98 if (!wasGrounded) {
99 // Airborne: apply full gravity
100 vel = vel + rb->GetGravity() * dt;
101 } else {
102 // Grounded: apply small downward force to maintain ground contact
103 // This ensures collision detection keeps finding the floor
104 // without causing visible jitter
105 if (vel.GetY() <= 0.0f) {
106 vel = Math::Vector3D(vel.GetX(), -0.5f, vel.GetZ());
107 }
108 // If vel.Y > 0 (jumping), don't override — let the jump happen
109 }
110
111 // Clamp to terminal velocity
112 float termVel = rb->GetTerminalVelocity();
113 if (vel.GetY() < -termVel) {
114 vel = Math::Vector3D(vel.GetX(), -termVel, vel.GetZ());
115 }
116
117 rb->SetVelocity(vel);
118 }
119
120 Math::Vector3D vel = rb->GetVelocity();
121 Math::Vector3D delta = vel * dt;
122
123 auto* transform = owner->GetComponent<TransformComponent>();
124 if (transform) {
125 transform->Translate(delta);
126 } else if (auto* cam = dynamic_cast<Camera*>(owner)) {
127 cam->AddPosition(delta);
128 }
129 }
130 }
131 }
132
133 UpdateBroadphase(dt);
134 FindPairsAndResolve();
135}
136
137void PhysicsWorld::UpdateBroadphase(float dt) {
138 for (auto* collider : m_colliders) {
139 int proxyId = collider->GetProxyId();
140 if (proxyId < 0) continue;
141
142 AABB newAABB = collider->GetWorldAABB();
143 m_tree.MoveProxy(proxyId, newAABB, PredictDisplacement(collider, dt));
144 }
145}
146
147void PhysicsWorld::FindPairsAndResolve() {
148 for (size_t i = 0; i < m_colliders.size(); ++i) {
149 ColliderComponent* colliderA = m_colliders[i];
150 if (colliderA->GetProxyId() < 0) continue;
151
152 // Passive colliders never drive queries; their pairs have no response
153 RigidbodyComponent* rbA = GetMovableBody(colliderA);
154 if (!rbA) continue;
155
156 AABB worldA = colliderA->GetWorldAABB();
157
158 m_tree.Query(worldA, [&](int proxyId) -> bool {
159 auto* colliderB =
160 static_cast<ColliderComponent*>(m_tree.GetUserData(proxyId));
161 if (colliderB == colliderA) return true;
162
163 // Movable pairs are visited from both sides: keep pointer order
164 RigidbodyComponent* rbB = GetMovableBody(colliderB);
165 if (rbB && colliderA > colliderB) return true;
166
167 // Layer filtering
168 if ((colliderA->GetLayer() & colliderB->GetMask()) == 0)
169 return true;
170 if ((colliderB->GetLayer() & colliderA->GetMask()) == 0)
171 return true;
172
173 // Skip if both are triggers
174 if (colliderA->IsTrigger() && colliderB->IsTrigger()) return true;
175
176 if (!colliderA->GetOwner() || !colliderB->GetOwner()) return true;
177
178 // Narrowphase argument order stays pointer-ordered
179 const bool aFirst = colliderA < colliderB;
180 ColliderComponent* first = aFirst ? colliderA : colliderB;
181 ColliderComponent* second = aFirst ? colliderB : colliderA;
182 RigidbodyComponent* rbFirst = aFirst ? rbA : rbB;
183 RigidbodyComponent* rbSecond = aFirst ? rbB : rbA;
184
185 Vector3D posFirst, posSecond;
186 Vector3D scaleFirst(1, 1, 1), scaleSecond(1, 1, 1);
187 GetColliderPose(first, posFirst, scaleFirst);
188 GetColliderPose(second, posSecond, scaleSecond);
189
190 CollisionManifold manifold =
191 TestCollision(first->GetShape(), posFirst, scaleFirst,
192 second->GetShape(), posSecond, scaleSecond);
193
194 if (!manifold.hasCollision) return true;
195
196 // Resolve: push rigidbodies apart
197 if (rbFirst) {
198 rbFirst->ResolveCollision(manifold.contact.normal * -1.0f,
199 manifold.contact.penetration);
200 }
201 if (rbSecond) {
202 rbSecond->ResolveCollision(manifold.contact.normal,
203 manifold.contact.penetration);
204 }
205
206 return true;
207 });
208 }
209}
210
211std::vector<CollisionPair> PhysicsWorld::OverlapSphere(const Vector3D& center, float radius, uint32_t layerMask) const {
212 std::vector<CollisionPair> results;
213 BoundingSphere sphere(center, radius);
214 AABB queryAABB = sphere.ToAABB();
215
216 m_tree.Query(queryAABB, [&](int proxyId) -> bool {
217 auto* collider = static_cast<ColliderComponent*>(m_tree.GetUserData(proxyId));
218 if ((collider->GetLayer() & layerMask) == 0) return true;
219
220 CollisionPair pair;
221 pair.b = collider;
222 results.push_back(pair);
223 return true;
224 });
225
226 return results;
227}
228
229std::vector<CollisionPair> PhysicsWorld::OverlapAABB(const AABB& aabb, uint32_t layerMask) const {
230 std::vector<CollisionPair> results;
231
232 m_tree.Query(aabb, [&](int proxyId) -> bool {
233 auto* collider = static_cast<ColliderComponent*>(m_tree.GetUserData(proxyId));
234 if ((collider->GetLayer() & layerMask) == 0) return true;
235
236 CollisionPair pair;
237 pair.b = collider;
238 results.push_back(pair);
239 return true;
240 });
241
242 return results;
243}
244
246 float radius, float maxDist, uint32_t layerMask) const {
247 SweepResult result;
248
249 // Expand ray into a fat AABB for broadphase query
250 Vector3D end = start + direction * maxDist;
251 AABB sweepAABB(
252 Vector3D(std::min(start.GetX(), end.GetX()) - radius,
253 std::min(start.GetY(), end.GetY()) - radius,
254 std::min(start.GetZ(), end.GetZ()) - radius),
255 Vector3D(std::max(start.GetX(), end.GetX()) + radius,
256 std::max(start.GetY(), end.GetY()) + radius,
257 std::max(start.GetZ(), end.GetZ()) + radius)
258 );
259
260 float closestDist = maxDist;
261
262 m_tree.Query(sweepAABB, [&](int proxyId) -> bool {
263 auto* collider = static_cast<ColliderComponent*>(m_tree.GetUserData(proxyId));
264 if ((collider->GetLayer() & layerMask) == 0) return true;
265
266 // Step along the sweep direction testing sphere collisions
267 AABB targetAABB = collider->GetWorldAABB();
268 Vector3D targetCenter = targetAABB.GetCenter();
269 Vector3D targetExtents = targetAABB.GetExtents();
270
271 // Expand target AABB by sweep radius for simplified test
272 AABB expandedTarget(
273 Vector3D(targetAABB.min.GetX() - radius,
274 targetAABB.min.GetY() - radius,
275 targetAABB.min.GetZ() - radius),
276 Vector3D(targetAABB.max.GetX() + radius,
277 targetAABB.max.GetY() + radius,
278 targetAABB.max.GetZ() + radius)
279 );
280
281 // Ray vs expanded AABB
282 Vector3D invDir(
283 std::abs(direction.GetX()) > 1e-8f ? 1.0f / direction.GetX() : 1e8f,
284 std::abs(direction.GetY()) > 1e-8f ? 1.0f / direction.GetY() : 1e8f,
285 std::abs(direction.GetZ()) > 1e-8f ? 1.0f / direction.GetZ() : 1e8f
286 );
287
288 float t1x = (expandedTarget.min.GetX() - start.GetX()) * invDir.GetX();
289 float t2x = (expandedTarget.max.GetX() - start.GetX()) * invDir.GetX();
290 float t1y = (expandedTarget.min.GetY() - start.GetY()) * invDir.GetY();
291 float t2y = (expandedTarget.max.GetY() - start.GetY()) * invDir.GetY();
292 float t1z = (expandedTarget.min.GetZ() - start.GetZ()) * invDir.GetZ();
293 float t2z = (expandedTarget.max.GetZ() - start.GetZ()) * invDir.GetZ();
294
295 float tmin = std::max({std::min(t1x, t2x), std::min(t1y, t2y), std::min(t1z, t2z)});
296 float tmax = std::min({std::max(t1x, t2x), std::max(t1y, t2y), std::max(t1z, t2z)});
297
298 if (tmax < 0 || tmin > tmax || tmin > closestDist) return true;
299
300 float hitDist = std::max(tmin, 0.0f);
301 if (hitDist < closestDist) {
302 closestDist = hitDist;
303 result.hit = true;
304 result.collider = collider;
305 result.distance = hitDist;
306 result.point = start + direction * hitDist;
307
308 // Compute approximate normal from hit point
309 Vector3D hitPt = result.point;
310 Vector3D diff = hitPt - targetCenter;
311
312 // Find which face we hit
313 float ax = std::abs(diff.GetX()) / std::max(targetExtents.GetX(), 0.001f);
314 float ay = std::abs(diff.GetY()) / std::max(targetExtents.GetY(), 0.001f);
315 float az = std::abs(diff.GetZ()) / std::max(targetExtents.GetZ(), 0.001f);
316
317 if (ax > ay && ax > az) {
318 result.normal = Vector3D(diff.GetX() > 0 ? 1.0f : -1.0f, 0, 0);
319 } else if (ay > az) {
320 result.normal = Vector3D(0, diff.GetY() > 0 ? 1.0f : -1.0f, 0);
321 } else {
322 result.normal = Vector3D(0, 0, diff.GetZ() > 0 ? 1.0f : -1.0f);
323 }
324 }
325
326 return true;
327 });
328
329 return result;
330}
331
332RayHit PhysicsWorld::Raycast(const Vector3D& origin, const Vector3D& direction,
333 float maxDist, uint32_t layerMask) const {
334 // Raycast is sphere sweep with radius 0, but use direct ray-AABB for better precision
335 SweepResult sweep = SphereSweep(origin, direction, 0.01f, maxDist, layerMask);
336 RayHit result;
337 result.hit = sweep.hit;
338 result.collider = sweep.collider;
339 result.point = sweep.point;
340 result.normal = sweep.normal;
341 result.distance = sweep.distance;
342 return result;
343}
344
345} // namespace Physics
346} // namespace Sleak
Physics::AABB GetWorldAABB() const
Local shape transformed into world space by the owner's current transform.
float GetY() const
Definition Vector.hpp:362
float GetX() const
Definition Vector.hpp:361
float GetZ() const
Definition Vector.hpp:363
void Query(const AABB &queryAABB, const std::function< bool(int)> &callback) const
Visits every leaf whose fat AABB overlaps queryAABB; stop early by returning false from callback.
bool MoveProxy(int proxyId, const AABB &newAABB, const Vector3D &displacement)
Refits a proxy's fat AABB to newAABB, re-inserting it only if it moved outside the fat margin.
void * GetUserData(int proxyId) const
std::vector< CollisionPair > OverlapSphere(const Vector3D &center, float radius, uint32_t layerMask=0xFFFFFFFF) const
Query API: colliders overlapping a sphere, filtered by layerMask.
void RegisterCollider(ColliderComponent *collider)
void UnregisterCollider(ColliderComponent *collider)
SweepResult SphereSweep(const Vector3D &start, const Vector3D &direction, float radius, float maxDist, uint32_t layerMask=0xFFFFFFFF) const
Sweeps a sphere from start along direction and returns the first collider it hits within maxDist.
RayHit Raycast(const Vector3D &origin, const Vector3D &direction, float maxDist, uint32_t layerMask=0xFFFFFFFF) const
Casts a ray and returns the closest collider hit within maxDist.
std::vector< CollisionPair > OverlapAABB(const AABB &aabb, uint32_t layerMask=0xFFFFFFFF) const
Colliders overlapping an AABB, filtered by layerMask.
Represents the position, rotation, and scale of an entity in 3D space.
Collision shapes, the broadphase tree, and the world that steps them.
Definition SceneBase.hpp:29
CollisionManifold TestCollision(const ColliderShape &shapeA, const Vector3D &posA, const Vector3D &scaleA, const ColliderShape &shapeB, const Vector3D &posB, const Vector3D &scaleB)
Dispatches to the right narrow-phase test based on the runtime shape held by each variant.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
Vector3D GetCenter() const
Definition Colliders.hpp:27
Vector3D GetExtents() const
Definition Colliders.hpp:31
ColliderComponent * collider
ColliderComponent * collider