1mod clearance;
49mod collision_filter;
50mod debug;
51mod ignored_contacts;
52mod joints;
53
54pub use collision_filter::CollisionFilter;
55pub use debug::{CONTACT_NORMAL_LENGTH, PhysicsDebugLine};
56pub use ignored_contacts::ContactPairError;
57
58use std::collections::HashMap;
59
60use crcbl_core::{Handle, Pool};
61use crcbl_ecs::{Access, DebugCtx, Entity, SystemTrait};
62use glam::DVec3;
63
64use crate::collider::Aabb;
65use crate::components::{ColliderComponent, RigidBody, Transform};
66use crate::contact::broadphase::ProxyId;
67use crate::contact::island::{self, IslandId, Islands};
68use crate::contact::{
69 Bodies, ContactCounters, ContactPipeline, ContactReport, ContactSettings, KineticContact,
70 PlaneId, StageTimes,
71};
72use crate::forces::ForceProvider;
73use crate::integrator::{Integrator as _, SemiImplicitEuler};
74use crate::material::SurfaceMaterial;
75use crate::query::{OverlapHit, ShapeHit};
76use crate::world::{
77 ALL_LAYERS, ColliderId, OverlapQueries, PhysicsWorld, QueryFilter, QueryScratch,
78};
79use crate::{Ray, Segment};
80
81pub(crate) type BodyId = Handle<BodyRecord>;
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub(crate) enum BodySet {
91 Static,
93 Awake,
95 Sleeping,
98}
99
100#[derive(Debug)]
102pub(crate) struct BodyRecord {
103 pub(crate) entity: Entity,
105 pub(crate) set: BodySet,
107 pub(crate) index: usize,
109 pub(crate) collider: Option<(ColliderId, ColliderComponent)>,
111 pub(crate) layers: u32,
114 pub(crate) material: SurfaceMaterial,
116 pub(crate) proxies: Vec<ProxyId>,
120 pub(crate) island: Option<IslandId>,
123 pub(crate) substeps: u32,
126 pub(crate) filter: CollisionFilter,
129}
130
131#[derive(Debug, Default)]
133pub(crate) struct StaticSet {
134 pub(crate) ids: Vec<BodyId>,
135 pub(crate) transforms: Vec<Transform>,
136}
137
138#[derive(Debug, Default)]
140pub(crate) struct AwakeSet {
141 pub(crate) ids: Vec<BodyId>,
142 pub(crate) transforms: Vec<Transform>,
143 pub(crate) bodies: Vec<RigidBody>,
144 pub(crate) sleep_times: Vec<f64>,
146}
147
148impl StaticSet {
149 fn push(&mut self, id: BodyId, transform: Transform) -> usize {
150 self.ids.push(id);
151 self.transforms.push(transform);
152 self.ids.len() - 1
153 }
154
155 fn swap_remove(&mut self, index: usize) -> (Transform, Option<BodyId>) {
158 self.ids.swap_remove(index);
159 let transform = self.transforms.swap_remove(index);
160 (transform, self.ids.get(index).copied())
161 }
162}
163
164impl AwakeSet {
165 pub(crate) fn push(&mut self, id: BodyId, transform: Transform, body: RigidBody) -> usize {
167 self.ids.push(id);
168 self.transforms.push(transform);
169 self.bodies.push(body);
170 self.sleep_times.push(0.0);
171 self.ids.len() - 1
172 }
173
174 pub(crate) fn swap_remove(&mut self, index: usize) -> (Transform, RigidBody, Option<BodyId>) {
177 self.ids.swap_remove(index);
178 let transform = self.transforms.swap_remove(index);
179 let body = self.bodies.swap_remove(index);
180 self.sleep_times.swap_remove(index);
181 (transform, body, self.ids.get(index).copied())
182 }
183}
184
185pub struct PhysicsSystem {
222 world: PhysicsWorld,
223
224 records: Pool<BodyRecord>,
226 entity_to_body: HashMap<Entity, BodyId>,
228 statics: StaticSet,
230 awake: AwakeSet,
232 islands: Islands,
234 collider_count: usize,
236 collider_to_entity: Vec<Option<Entity>>,
238
239 force_providers: Vec<Box<dyn ForceProvider>>,
241
242 scratch: QueryScratch,
247
248 contacts: Option<Box<ContactPipeline>>,
251}
252
253#[derive(Clone, Copy, Debug)]
265pub struct EntityOverlapQueries<'a> {
266 queries: OverlapQueries<'a>,
267 collider_to_entity: &'a [Option<Entity>],
268}
269
270impl EntityOverlapQueries<'_> {
271 pub fn overlap_sphere_into(
281 &self,
282 centre: DVec3,
283 radius: f64,
284 scratch: &mut QueryScratch,
285 out: &mut Vec<(Entity, OverlapHit)>,
286 ) {
287 self.overlap_sphere_filtered_into(centre, radius, QueryFilter::ALL, scratch, out);
288 }
289
290 pub fn overlap_sphere_filtered_into(
293 &self,
294 centre: DVec3,
295 radius: f64,
296 filter: QueryFilter,
297 scratch: &mut QueryScratch,
298 out: &mut Vec<(Entity, OverlapHit)>,
299 ) {
300 out.clear();
301 let mut hits = std::mem::take(&mut scratch.hits);
302 self.queries
303 .overlap_sphere_filtered_into(centre, radius, filter, scratch, &mut hits);
304 for &(id, hit) in hits.iter() {
305 let Some(entity) = self.entity_for(id) else {
306 continue;
307 };
308 out.push((entity, hit));
309 }
310 scratch.hits = hits;
312 }
313
314 pub fn overlap_sphere_entities_into(
321 &self,
322 centre: DVec3,
323 radius: f64,
324 scratch: &mut QueryScratch,
325 out: &mut Vec<Entity>,
326 ) {
327 out.clear();
328 let mut ids = std::mem::take(&mut scratch.ids);
329 self.queries
330 .overlap_sphere_ids_into(centre, radius, scratch, &mut ids);
331 out.extend(ids.iter().filter_map(|&id| self.entity_for(id)));
332 scratch.ids = ids;
333 }
334
335 pub fn overlap_aabb_into(
344 &self,
345 aabb: &Aabb,
346 scratch: &mut QueryScratch,
347 out: &mut Vec<Entity>,
348 ) {
349 self.overlap_aabb_filtered_into(aabb, QueryFilter::ALL, scratch, out);
350 }
351
352 pub fn overlap_aabb_filtered_into(
355 &self,
356 aabb: &Aabb,
357 filter: QueryFilter,
358 scratch: &mut QueryScratch,
359 out: &mut Vec<Entity>,
360 ) {
361 out.clear();
362 let mut ids = std::mem::take(&mut scratch.ids);
363 self.queries
364 .overlap_aabb_filtered_into(aabb, filter, scratch, &mut ids);
365 for id in ids.iter() {
366 let Some(entity) = self.entity_for(*id) else {
367 continue;
368 };
369 out.push(entity);
370 }
371 scratch.ids = ids;
372 }
373
374 #[must_use]
381 pub fn cast_ray(&self, ray: &Ray, scratch: &mut QueryScratch) -> Option<(Entity, ShapeHit)> {
382 self.cast_ray_filtered(ray, QueryFilter::ALL, scratch)
383 }
384
385 #[must_use]
389 pub fn cast_ray_filtered(
390 &self,
391 ray: &Ray,
392 filter: QueryFilter,
393 scratch: &mut QueryScratch,
394 ) -> Option<(Entity, ShapeHit)> {
395 let (id, hit) = self.queries.cast_ray_filtered(ray, filter, scratch)?;
396 Some((self.entity_for(id)?, hit))
397 }
398
399 #[must_use]
407 pub fn sweep_sphere(
408 &self,
409 segment: &Segment,
410 radius: f64,
411 scratch: &mut QueryScratch,
412 ) -> Option<(Entity, ShapeHit)> {
413 self.sweep_sphere_filtered(segment, radius, QueryFilter::ALL, scratch)
414 }
415
416 #[must_use]
421 pub fn sweep_sphere_filtered(
422 &self,
423 segment: &Segment,
424 radius: f64,
425 filter: QueryFilter,
426 scratch: &mut QueryScratch,
427 ) -> Option<(Entity, ShapeHit)> {
428 let (id, hit) = self
429 .queries
430 .sweep_sphere_filtered(segment, radius, filter, scratch)?;
431 Some((self.entity_for(id)?, hit))
432 }
433
434 fn entity_for(&self, id: ColliderId) -> Option<Entity> {
439 entity_for_in(self.collider_to_entity, id)
440 }
441}
442
443fn entity_for_in(collider_to_entity: &[Option<Entity>], id: ColliderId) -> Option<Entity> {
448 collider_to_entity.get(id.index() as usize).and_then(|e| *e)
449}
450
451impl PhysicsSystem {
452 pub const NAME: &'static str = "physics";
455
456 #[must_use]
460 pub fn new() -> Self {
461 Self {
462 world: PhysicsWorld::new(),
463 records: Pool::new(),
464 entity_to_body: HashMap::new(),
465 statics: StaticSet::default(),
466 awake: AwakeSet::default(),
467 islands: Islands::default(),
468 collider_count: 0,
469 collider_to_entity: Vec::new(),
470 force_providers: Vec::new(),
471 scratch: QueryScratch::new(),
472 contacts: None,
473 }
474 }
475
476 #[must_use]
484 pub fn with_contacts(settings: ContactSettings) -> Self {
485 Self {
486 contacts: Some(Box::new(ContactPipeline::new(settings))),
487 ..Self::new()
488 }
489 }
490
491 #[must_use]
493 pub fn contact_settings(&self) -> Option<&ContactSettings> {
494 self.contacts.as_ref().map(|pipeline| &pipeline.settings)
495 }
496
497 pub fn contact_settings_mut(&mut self) -> Option<&mut ContactSettings> {
500 self.contacts
501 .as_mut()
502 .map(|pipeline| &mut pipeline.settings)
503 }
504
505 pub fn add_plane(&mut self, normal: DVec3, offset: f64, material: SurfaceMaterial) -> PlaneId {
517 assert!(
518 (normal.length_squared() - 1.0).abs() < 1e-9,
519 "a plane's normal has unit length: {normal:?}"
520 );
521 self.contacts
522 .as_mut()
523 .expect("planes are contact geometry: build the system with_contacts")
524 .add_plane(normal, offset, material)
525 }
526
527 #[must_use]
530 pub fn contact_counters(&self) -> ContactCounters {
531 self.contacts
532 .as_ref()
533 .map_or_else(ContactCounters::default, |pipeline| pipeline.counters)
534 }
535
536 #[must_use]
539 pub fn kinetic_contacts(&self) -> &[KineticContact] {
540 self.contacts
541 .as_ref()
542 .map_or(&[], |pipeline| pipeline.kinetic.as_slice())
543 }
544
545 #[must_use]
548 pub fn contacts(&self) -> Vec<ContactReport> {
549 self.contacts
550 .as_ref()
551 .map_or_else(Vec::new, |pipeline| pipeline.reports(&self.records))
552 }
553
554 #[must_use]
556 pub fn collider_count(&self) -> usize {
557 self.collider_count
558 }
559
560 #[must_use]
563 pub fn body_count(&self) -> usize {
564 self.awake.bodies.len() + self.islands.sleeping_bodies()
565 }
566
567 #[must_use]
572 pub fn is_sleeping(&self, entity: Entity) -> bool {
573 self.record(entity)
574 .is_some_and(|record| record.set == BodySet::Sleeping)
575 }
576
577 pub fn put_to_sleep(&mut self, entity: Entity) -> bool {
600 let sleeps = self
601 .contacts
602 .as_ref()
603 .is_some_and(|pipeline| pipeline.settings.sleep);
604 let Some(&id) = self.entity_to_body.get(&entity) else {
605 return false;
606 };
607 if !sleeps {
608 return false;
609 }
610 self.islands.reconcile(&mut self.records, &self.awake);
611 let Some(record) = self.records.get(id) else {
612 return false;
613 };
614 if record.set == BodySet::Awake
615 && let Some(island) = record.island
616 {
617 self.islands
618 .sleep(&mut self.records, &mut self.awake, island);
619 }
620 let asleep = self.is_sleeping(entity);
621 if asleep && let Some(pipeline) = self.contacts.as_mut() {
622 let island = self.records.get(id).and_then(|record| record.island);
626 match island.map(|island| self.islands.members(island)) {
627 Some(members) if !members.is_empty() => {
628 for &member in members {
629 pipeline.body_restored_asleep(member);
630 }
631 }
632 _ => pipeline.body_restored_asleep(id),
633 }
634 }
635 asleep
636 }
637
638 pub fn set_body(&mut self, entity: Entity, body: RigidBody) {
651 let id = self.record_for(entity, Transform::IDENTITY);
652 self.wake(id);
653 let record = self.records.get(id).expect("a live record");
654 assert!(
655 !body.is_dynamic()
656 || !matches!(record.collider, Some((_, ColliderComponent::Mesh { .. }))),
657 "a triangle mesh is for static and kinematic bodies, not dynamic ones"
658 );
659 let index = record.index;
660 match record.set {
661 BodySet::Awake => self.awake.bodies[index] = body,
662 BodySet::Sleeping => unreachable!("woken above"),
663 BodySet::Static => {
664 let (transform, moved) = self.statics.swap_remove(index);
665 self.reindex_to(moved, index);
666 let awake_index = self.awake.push(id, transform, body);
667 let record = self.records.get_mut(id).expect("a live record");
668 record.set = BodySet::Awake;
669 record.index = awake_index;
670 if let Some(pipeline) = self.contacts.as_mut() {
671 for &proxy in &record.proxies {
672 pipeline.body_changed_set(proxy, BodySet::Awake);
673 }
674 }
675 }
676 }
677 }
678
679 pub fn set_transform(&mut self, entity: Entity, transform: Transform) {
686 let id = self.record_for(entity, transform);
687 self.disturb(id);
688 *self.transform_slot(id) = transform;
689 self.sync_collider(id);
690 if let Some(pipeline) = self.contacts.as_mut() {
691 pipeline.body_placed(
692 id,
693 Bodies {
694 records: &self.records,
695 statics: &self.statics,
696 awake: &self.awake,
697 islands: &self.islands,
698 },
699 );
700 }
701 }
702
703 #[must_use]
706 pub fn body(&self, entity: Entity) -> Option<&RigidBody> {
707 let record = self.record(entity)?;
708 match record.set {
709 BodySet::Awake => Some(&self.awake.bodies[record.index]),
710 BodySet::Sleeping => Some(self.islands.body(record.island, record.index)),
711 BodySet::Static => None,
712 }
713 }
714
715 #[must_use]
732 pub fn body_mut(&mut self, entity: Entity) -> Option<&mut RigidBody> {
733 let &id = self.entity_to_body.get(&entity)?;
734 self.wake(id);
735 let record = self.records.get(id)?;
736 match record.set {
737 BodySet::Awake => Some(&mut self.awake.bodies[record.index]),
738 BodySet::Static | BodySet::Sleeping => None,
739 }
740 }
741
742 #[must_use]
744 pub fn transform(&self, entity: Entity) -> Option<&Transform> {
745 let record = self.record(entity)?;
746 Some(match record.set {
747 BodySet::Awake => &self.awake.transforms[record.index],
748 BodySet::Static => &self.statics.transforms[record.index],
749 BodySet::Sleeping => self.islands.transform(record.island, record.index),
750 })
751 }
752
753 pub fn set_material(&mut self, entity: Entity, material: SurfaceMaterial) -> bool {
763 let Some(&id) = self.entity_to_body.get(&entity) else {
764 return false;
765 };
766 self.disturb(id);
767 match self.records.get_mut(id) {
768 Some(record) => {
769 record.material = material;
770 true
771 }
772 None => false,
773 }
774 }
775
776 #[must_use]
778 pub fn material(&self, entity: Entity) -> Option<SurfaceMaterial> {
779 self.record(entity).map(|record| record.material)
780 }
781
782 pub fn add_force_provider(&mut self, provider: Box<dyn ForceProvider>) {
790 self.force_providers.push(provider);
791 }
792
793 pub fn apply_force(&mut self, entity: Entity, force: DVec3) -> bool {
810 match self.body_mut(entity) {
811 Some(body) => {
812 body.apply_force(force);
813 true
814 }
815 None => false,
816 }
817 }
818
819 pub fn apply_torque(&mut self, entity: Entity, torque: DVec3) -> bool {
826 match self.body_mut(entity) {
827 Some(body) => {
828 body.apply_torque(torque);
829 true
830 }
831 None => false,
832 }
833 }
834
835 pub fn set_collider(
856 &mut self,
857 entity: Entity,
858 component: &ColliderComponent,
859 transform: &Transform,
860 ) {
861 let id = self.record_for(entity, *transform);
862 self.wake(id);
863 if matches!(component, ColliderComponent::Mesh { .. }) {
864 let record = self.records.get(id).expect("a live record");
865 assert!(
866 record.set != BodySet::Awake || !self.awake.bodies[record.index].is_dynamic(),
867 "a triangle mesh is for static and kinematic bodies, not dynamic ones"
868 );
869 }
870 *self.transform_slot(id) = *transform;
871 self.remove_collider(entity);
872
873 let collider = self.world.add_collider(component, transform);
874
875 let record = self.records.get_mut(id).expect("a live record");
876 record.collider = Some((collider, component.clone()));
877 self.world.set_layers(collider, record.layers);
878 if let Some(pipeline) = self.contacts.as_mut() {
879 let proxies = pipeline.create_body_proxies(
880 id,
881 Bodies {
882 records: &self.records,
883 statics: &self.statics,
884 awake: &self.awake,
885 islands: &self.islands,
886 },
887 );
888 self.records.get_mut(id).expect("a live record").proxies = proxies;
889 }
890 self.collider_count += 1;
891 let slot = collider.index() as usize;
892 if slot >= self.collider_to_entity.len() {
893 self.collider_to_entity.resize(slot + 1, None);
894 }
895 self.collider_to_entity[slot] = Some(entity);
896 }
897
898 pub fn remove_entity(&mut self, entity: Entity) {
904 if let Some(&id) = self.entity_to_body.get(&entity) {
905 self.take_out_joints_of(id);
906 }
907 self.remove_collider(entity);
908 let Some(id) = self.entity_to_body.remove(&entity) else {
909 return;
910 };
911 if let Some(pipeline) = self.contacts.as_mut() {
912 pipeline.ignored.forget_body(id);
913 }
914 let Some(record) = self.records.remove(id) else {
915 return;
916 };
917 if let Some(island) = record.island {
918 self.islands.remove_member(island, id);
919 }
920 match record.set {
921 BodySet::Static => {
922 let (_, moved) = self.statics.swap_remove(record.index);
923 self.reindex_to(moved, record.index);
924 }
925 BodySet::Awake => {
926 let (_, _, moved) = self.awake.swap_remove(record.index);
927 self.reindex_to(moved, record.index);
928 }
929 BodySet::Sleeping => unreachable!("remove_collider woke it"),
930 }
931 }
932
933 pub fn remove_collider(&mut self, entity: Entity) {
939 let Some(&id) = self.entity_to_body.get(&entity) else {
940 return;
941 };
942 self.disturb(id);
943 let Some(record) = self.records.get_mut(id) else {
944 return;
945 };
946 let proxies = std::mem::take(&mut record.proxies);
947 if let Some(pipeline) = self.contacts.as_mut()
948 && !proxies.is_empty()
949 {
950 pipeline.destroy_proxies(&proxies);
951 if let Some(island) = record.island {
954 self.islands.mark_removed(island);
955 }
956 }
957 if let Some((collider, _)) = record.collider.take() {
958 self.world.remove(collider);
959 self.collider_count -= 1;
960 let slot = collider.index() as usize;
961 if slot < self.collider_to_entity.len() {
962 self.collider_to_entity[slot] = None;
963 }
964 }
965 }
966
967 pub fn set_collider_layers(&mut self, entity: Entity, bits: u32) -> bool {
986 let Some(&id) = self.entity_to_body.get(&entity) else {
987 return false;
988 };
989 let Some(record) = self.records.get_mut(id) else {
990 return false;
991 };
992 let Some((collider, _)) = record.collider else {
993 return false;
994 };
995 record.layers = bits;
996 self.world.set_layers(collider, bits)
997 }
998
999 #[must_use]
1008 pub fn collider_of(&self, entity: Entity) -> Option<ColliderId> {
1009 self.record(entity)?
1010 .collider
1011 .as_ref()
1012 .map(|(collider, _)| *collider)
1013 }
1014
1015 #[must_use]
1022 pub fn entity_of(&self, collider: ColliderId) -> Option<Entity> {
1023 let entity = self.entity_for(collider)?;
1024 (self.collider_of(entity) == Some(collider)).then_some(entity)
1028 }
1029
1030 pub fn step(&mut self, dt: f64) {
1056 self.step_with_clock(dt, None);
1057 }
1058
1059 pub fn step_timed(&mut self, dt: f64, clock: &mut dyn FnMut() -> f64) {
1068 self.step_with_clock(dt, Some(clock));
1069 }
1070
1071 fn step_with_clock(&mut self, dt: f64, clock: Option<&mut dyn FnMut() -> f64>) {
1072 if self.contacts.is_some() {
1073 self.step_contacts(dt, clock);
1074 } else {
1075 apply_forces(&mut self.awake, &self.force_providers, dt);
1076 let AwakeSet {
1077 transforms, bodies, ..
1078 } = &mut self.awake;
1079 for (body, transform) in bodies.iter_mut().zip(transforms.iter_mut()) {
1080 SemiImplicitEuler.step(body, transform, dt);
1081 }
1082 sync_colliders(&mut self.world, &self.records, &self.awake);
1083 }
1084 }
1085
1086 fn step_contacts(&mut self, dt: f64, mut clock: Option<&mut dyn FnMut() -> f64>) {
1092 let Some(pipeline) = self.contacts.as_mut() else {
1093 return;
1094 };
1095 let settings = pipeline.settings;
1096 let mut read = || clock.as_mut().map(|clock| clock());
1097 let start = read();
1098 if !settings.sleep && self.islands.sleeping_bodies() > 0 {
1099 self.islands.wake_all(&mut self.records, &mut self.awake);
1100 }
1101 self.islands.reconcile(&mut self.records, &self.awake);
1102 let reconciled = read();
1103
1104 let lent = Bodies {
1105 records: &self.records,
1106 statics: &self.statics,
1107 awake: &self.awake,
1108 islands: &self.islands,
1109 };
1110 pipeline.update_pairs(lent, dt);
1111 let paired = read();
1112 pipeline.collide(lent, dt);
1113 pipeline.joints.island_events(lent, &mut pipeline.events);
1114 let collided = read();
1115
1116 let events = std::mem::take(&mut pipeline.events);
1118 for &id in &events.wake {
1119 self.islands
1120 .wake_body(&mut self.records, &mut self.awake, id);
1121 }
1122 for &(a, b) in &events.links {
1123 self.islands.link(&mut self.records, &mut self.awake, a, b);
1124 }
1125 for &id in &events.unlinks {
1126 if let Some(island) = self.records.get(id).and_then(|record| record.island) {
1127 self.islands.mark_removed(island);
1128 }
1129 }
1130 let linked = read();
1131
1132 apply_forces(&mut self.awake, &self.force_providers, dt);
1133 pipeline.remember_starts(&self.awake);
1134 pipeline.solve(
1135 &self.records,
1136 &self.statics,
1137 &mut self.awake,
1138 &self.islands,
1139 dt,
1140 );
1141 let solved = read();
1142 pipeline.sweep(
1143 &self.records,
1144 &self.statics,
1145 &mut self.awake,
1146 &self.islands,
1147 dt,
1148 );
1149 let swept = read();
1150
1151 sync_colliders(&mut self.world, &self.records, &self.awake);
1154 pipeline.count_joints(Bodies {
1155 records: &self.records,
1156 statics: &self.statics,
1157 awake: &self.awake,
1158 islands: &self.islands,
1159 });
1160 let broken = std::mem::take(&mut pipeline.joints.broken);
1161 pipeline.counters.broken_joints = broken.len();
1162 for joint_break in &broken {
1163 self.take_out_joint(joint_break.joint);
1164 }
1165 let Some(pipeline) = self.contacts.as_mut() else {
1166 return;
1167 };
1168 pipeline.joints.broken = broken;
1169 let synced = read();
1170
1171 if settings.sleep {
1172 let records = &self.records;
1173 island::update_timers(
1174 &mut self.awake,
1175 settings.sleep_speed,
1176 settings.sleep_angular_speed,
1177 |id| {
1178 records
1179 .get(id)
1180 .and_then(|record| record.collider.as_ref())
1181 .map_or(0.0, |(_, collider)| collider.max_extent())
1182 },
1183 dt,
1184 );
1185 for &id in &events.stirred {
1186 if let Some(record) = self.records.get(id)
1187 && record.set == BodySet::Awake
1188 {
1189 self.awake.sleep_times[record.index] = 0.0;
1190 }
1191 }
1192 if let Some(island) =
1193 self.islands
1194 .split_candidate(&self.records, &self.awake, settings.time_to_sleep)
1195 {
1196 let edges = pipeline.island_edges(&self.records, island);
1197 self.islands.split(&mut self.records, island, edges);
1198 }
1199 self.islands
1200 .sleep_ready(&mut self.records, &mut self.awake, settings.time_to_sleep);
1201 }
1202 let settled = read();
1203 pipeline.events = events;
1204
1205 let counters = &mut pipeline.counters;
1206 counters.bodies = self.awake.ids.len();
1207 counters.sleeping = self.islands.sleeping_bodies();
1208 counters.islands = self.islands.awake_islands();
1209 counters.sleeping_islands = self.islands.sleeping_islands();
1210 counters.stages = match (
1211 start, reconciled, paired, collided, linked, solved, swept, synced, settled,
1212 ) {
1213 (
1214 Some(start),
1215 Some(reconciled),
1216 Some(paired),
1217 Some(collided),
1218 Some(linked),
1219 Some(solved),
1220 Some(swept),
1221 Some(synced),
1222 Some(settled),
1223 ) => Some(StageTimes {
1224 broadphase: paired - reconciled,
1225 narrow_phase: collided - paired,
1226 solver: solved - linked,
1227 islands: (reconciled - start) + (linked - collided) + (settled - synced),
1228 continuous: swept - solved,
1229 }),
1230 _ => None,
1231 };
1232 }
1233
1234 #[must_use]
1238 pub fn cast_ray(&mut self, ray: &Ray) -> Option<(Entity, ShapeHit)> {
1239 self.cast_ray_filtered(ray, QueryFilter::ALL)
1240 }
1241
1242 #[must_use]
1245 pub fn cast_ray_filtered(
1246 &mut self,
1247 ray: &Ray,
1248 filter: QueryFilter,
1249 ) -> Option<(Entity, ShapeHit)> {
1250 let mut scratch = std::mem::take(&mut self.scratch);
1253 let hit = self
1254 .overlap_queries()
1255 .cast_ray_filtered(ray, filter, &mut scratch);
1256 self.scratch = scratch;
1257 hit
1258 }
1259
1260 #[must_use]
1266 pub fn sweep_sphere(&mut self, segment: &Segment, radius: f64) -> Option<(Entity, ShapeHit)> {
1267 self.sweep_sphere_filtered(segment, radius, QueryFilter::ALL)
1268 }
1269
1270 #[must_use]
1273 pub fn sweep_sphere_filtered(
1274 &mut self,
1275 segment: &Segment,
1276 radius: f64,
1277 filter: QueryFilter,
1278 ) -> Option<(Entity, ShapeHit)> {
1279 let mut scratch = std::mem::take(&mut self.scratch);
1280 let hit =
1281 self.overlap_queries()
1282 .sweep_sphere_filtered(segment, radius, filter, &mut scratch);
1283 self.scratch = scratch;
1284 hit
1285 }
1286
1287 #[must_use]
1305 pub fn sweep_body(
1306 &mut self,
1307 entity: Entity,
1308 dt: f64,
1309 radius: f64,
1310 ) -> Option<(Entity, ShapeHit)> {
1311 self.sweep_body_filtered(entity, dt, radius, ALL_LAYERS)
1312 }
1313
1314 #[must_use]
1320 pub fn sweep_body_filtered(
1321 &mut self,
1322 entity: Entity,
1323 dt: f64,
1324 radius: f64,
1325 mask: u32,
1326 ) -> Option<(Entity, ShapeHit)> {
1327 let body = self.body(entity).copied()?;
1328 let transform = self.transform(entity).copied()?;
1329 let segment = Segment {
1330 start: transform.position - body.velocity * dt,
1331 end: transform.position,
1332 };
1333 let filter = QueryFilter::excluding(self.collider_of(entity)).with_mask(mask);
1334 let (id, hit) = self.world.sweep_sphere_filtered(&segment, radius, filter)?;
1335 Some((self.entity_for(id)?, hit))
1336 }
1337
1338 #[must_use]
1371 pub fn overlap_sphere(&mut self, centre: DVec3, radius: f64) -> Vec<(Entity, OverlapHit)> {
1372 let mut out = Vec::new();
1373 self.overlap_sphere_into(centre, radius, &mut out);
1374 out
1375 }
1376
1377 pub fn overlap_sphere_into(
1391 &mut self,
1392 centre: DVec3,
1393 radius: f64,
1394 out: &mut Vec<(Entity, OverlapHit)>,
1395 ) {
1396 self.overlap_sphere_filtered_into(centre, radius, QueryFilter::ALL, out);
1397 }
1398
1399 #[must_use]
1402 pub fn overlap_sphere_filtered(
1403 &mut self,
1404 centre: DVec3,
1405 radius: f64,
1406 filter: QueryFilter,
1407 ) -> Vec<(Entity, OverlapHit)> {
1408 let mut out = Vec::new();
1409 self.overlap_sphere_filtered_into(centre, radius, filter, &mut out);
1410 out
1411 }
1412
1413 pub fn overlap_sphere_filtered_into(
1416 &mut self,
1417 centre: DVec3,
1418 radius: f64,
1419 filter: QueryFilter,
1420 out: &mut Vec<(Entity, OverlapHit)>,
1421 ) {
1422 let mut scratch = std::mem::take(&mut self.scratch);
1426 self.overlap_queries().overlap_sphere_filtered_into(
1427 centre,
1428 radius,
1429 filter,
1430 &mut scratch,
1431 out,
1432 );
1433 self.scratch = scratch;
1434 }
1435
1436 pub fn overlap_queries(&mut self) -> EntityOverlapQueries<'_> {
1444 let Self {
1447 world,
1448 collider_to_entity,
1449 ..
1450 } = self;
1451 EntityOverlapQueries {
1452 queries: world.overlap_queries(),
1453 collider_to_entity,
1454 }
1455 }
1456
1457 #[must_use]
1462 pub fn overlap_aabb(&mut self, aabb: &Aabb) -> Vec<Entity> {
1463 self.overlap_aabb_filtered(aabb, QueryFilter::ALL)
1464 }
1465
1466 #[must_use]
1469 pub fn overlap_aabb_filtered(&mut self, aabb: &Aabb, filter: QueryFilter) -> Vec<Entity> {
1470 let mut scratch = std::mem::take(&mut self.scratch);
1471 let mut out = Vec::new();
1472 self.overlap_queries()
1473 .overlap_aabb_filtered_into(aabb, filter, &mut scratch, &mut out);
1474 self.scratch = scratch;
1475 out
1476 }
1477
1478 #[must_use]
1480 pub fn world(&self) -> &PhysicsWorld {
1481 &self.world
1482 }
1483
1484 pub fn world_mut(&mut self) -> &mut PhysicsWorld {
1486 &mut self.world
1487 }
1488
1489 fn entity_for(&self, id: ColliderId) -> Option<Entity> {
1494 entity_for_in(&self.collider_to_entity, id)
1495 }
1496
1497 fn record(&self, entity: Entity) -> Option<&BodyRecord> {
1499 self.records.get(*self.entity_to_body.get(&entity)?)
1500 }
1501
1502 fn record_for(&mut self, entity: Entity, transform: Transform) -> BodyId {
1505 if let Some(&id) = self.entity_to_body.get(&entity) {
1506 return id;
1507 }
1508 let id = self.records.insert(BodyRecord {
1509 entity,
1510 set: BodySet::Static,
1511 index: 0,
1512 collider: None,
1513 layers: ALL_LAYERS,
1514 material: SurfaceMaterial::DEFAULT,
1515 proxies: Vec::new(),
1516 island: None,
1517 substeps: 0,
1518 filter: CollisionFilter::DEFAULT,
1519 });
1520 let index = self.statics.push(id, transform);
1521 self.records.get_mut(id).expect("just inserted").index = index;
1522 self.entity_to_body.insert(entity, id);
1523 id
1524 }
1525
1526 fn transform_slot(&mut self, id: BodyId) -> &mut Transform {
1528 self.wake(id);
1529 let record = self.records.get(id).expect("a live record");
1530 match record.set {
1531 BodySet::Awake => &mut self.awake.transforms[record.index],
1532 BodySet::Static => &mut self.statics.transforms[record.index],
1533 BodySet::Sleeping => unreachable!("woken above"),
1534 }
1535 }
1536
1537 fn wake(&mut self, id: BodyId) {
1539 self.islands
1540 .wake_body(&mut self.records, &mut self.awake, id);
1541 }
1542
1543 fn disturb(&mut self, id: BodyId) {
1550 self.wake(id);
1551 if self.islands.sleeping_bodies() == 0 {
1552 return;
1553 }
1554 let (Some(pipeline), Some(record)) = (self.contacts.as_ref(), self.records.get(id)) else {
1555 return;
1556 };
1557 if record.proxies.is_empty() {
1558 return;
1559 }
1560 let mut touching = Vec::new();
1561 pipeline.touching_bodies(&record.proxies, &mut touching);
1562 for other in touching {
1563 self.wake(other);
1564 }
1565 }
1566
1567 fn reindex_to(&mut self, moved: Option<BodyId>, index: usize) {
1570 if let Some(record) = moved.and_then(|id| self.records.get_mut(id)) {
1571 record.index = index;
1572 }
1573 }
1574
1575 fn sync_collider(&mut self, id: BodyId) {
1578 let Some(record) = self.records.get(id) else {
1579 return;
1580 };
1581 let Some((collider, component)) = &record.collider else {
1582 return;
1583 };
1584 let transform = match record.set {
1585 BodySet::Awake => &self.awake.transforms[record.index],
1586 BodySet::Static => &self.statics.transforms[record.index],
1587 BodySet::Sleeping => self.islands.transform(record.island, record.index),
1588 };
1589 self.world.place_collider(*collider, component, transform);
1590 }
1591}
1592
1593fn apply_forces(awake: &mut AwakeSet, providers: &[Box<dyn ForceProvider>], dt: f64) {
1595 let AwakeSet {
1596 transforms, bodies, ..
1597 } = awake;
1598 for (body, transform) in bodies.iter_mut().zip(transforms.iter()) {
1599 for provider in providers {
1600 provider.apply(body, transform, dt);
1601 }
1602 }
1603}
1604
1605fn sync_colliders(world: &mut PhysicsWorld, records: &Pool<BodyRecord>, awake: &AwakeSet) {
1607 for (id, transform) in awake.ids.iter().zip(awake.transforms.iter()) {
1608 if let Some((collider, component)) = records.get(*id).and_then(|r| r.collider.as_ref()) {
1609 world.place_collider(*collider, component, transform);
1610 }
1611 }
1612}
1613
1614pub(crate) fn canonical_bits(value: f64) -> u64 {
1618 if value == 0.0 {
1619 0
1620 } else if value.is_nan() {
1621 f64::NAN.to_bits()
1622 } else {
1623 value.to_bits()
1624 }
1625}
1626
1627impl Default for PhysicsSystem {
1628 fn default() -> Self {
1629 Self::new()
1630 }
1631}
1632
1633impl std::fmt::Debug for PhysicsSystem {
1634 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1635 f.debug_struct("PhysicsSystem")
1636 .field("collider_count", &self.collider_count)
1637 .field("body_count", &self.body_count())
1638 .field("force_provider_count", &self.force_providers.len())
1639 .finish()
1640 }
1641}
1642
1643impl SystemTrait for PhysicsSystem {
1648 fn name(&self) -> &str {
1649 Self::NAME
1650 }
1651
1652 fn access(&self) -> Access {
1655 Access::none()
1656 }
1657
1658 fn tick(&mut self, dt: f64) {
1659 self.step(dt);
1664 }
1665
1666 fn entity_count(&self) -> usize {
1667 self.collider_count
1668 }
1669
1670 fn sweep(&mut self, dead: &[Entity]) {
1671 for &entity in dead {
1672 self.remove_entity(entity);
1673 }
1674 }
1675
1676 fn debug_draw(&mut self, _ctx: &DebugCtx) {}
1679
1680 fn hash_state(&self, hasher: &mut dyn std::hash::Hasher) {
1691 let mut entities: Vec<(u64, &BodyRecord)> = self
1692 .records
1693 .iter()
1694 .map(|(_, record)| (record.entity.to_bits(), record))
1695 .collect();
1696 entities.sort_unstable_by_key(|(bits, _)| *bits);
1697
1698 for (bits, record) in entities {
1699 hasher.write(&bits.to_le_bytes());
1700 let (transform, body) = match record.set {
1701 BodySet::Awake => (
1702 &self.awake.transforms[record.index],
1703 Some(&self.awake.bodies[record.index]),
1704 ),
1705 BodySet::Sleeping => (
1706 self.islands.transform(record.island, record.index),
1707 Some(self.islands.body(record.island, record.index)),
1708 ),
1709 BodySet::Static => (&self.statics.transforms[record.index], None),
1710 };
1711
1712 hasher.write(&[1]);
1713 for value in [
1714 transform.position.x,
1715 transform.position.y,
1716 transform.position.z,
1717 transform.rotation.x,
1718 transform.rotation.y,
1719 transform.rotation.z,
1720 transform.rotation.w,
1721 ] {
1722 hasher.write(&canonical_bits(value).to_le_bytes());
1723 }
1724
1725 match body {
1726 Some(body) => {
1727 hasher.write(&[1]);
1728 for value in [
1729 body.mass,
1730 body.inverse_mass,
1731 body.velocity.x,
1732 body.velocity.y,
1733 body.velocity.z,
1734 body.force_accum.x,
1735 body.force_accum.y,
1736 body.force_accum.z,
1737 body.angular_velocity.x,
1738 body.angular_velocity.y,
1739 body.angular_velocity.z,
1740 body.torque_accum.x,
1741 body.torque_accum.y,
1742 body.torque_accum.z,
1743 ]
1744 .into_iter()
1745 .chain(body.local_inertia.to_cols_array())
1746 {
1747 hasher.write(&canonical_bits(value).to_le_bytes());
1748 }
1749 if body.bullet {
1752 hasher.write(&[3]);
1753 }
1754 if record.substeps != 0 {
1757 hasher.write(&[5]);
1758 hasher.write(&record.substeps.to_le_bytes());
1759 }
1760 if self.contacts.is_some() {
1761 match record.set {
1762 BodySet::Awake => {
1763 hasher.write(&[0]);
1764 let still = self.awake.sleep_times[record.index];
1765 hasher.write(&canonical_bits(still).to_le_bytes());
1766 }
1767 BodySet::Sleeping | BodySet::Static => hasher.write(&[1]),
1768 }
1769 }
1770 }
1771 None => hasher.write(&[0]),
1772 }
1773 if record.filter != CollisionFilter::DEFAULT {
1776 hasher.write(&[7]);
1777 hasher.write(&record.filter.category.to_le_bytes());
1778 hasher.write(&record.filter.mask.to_le_bytes());
1779 }
1780 }
1781
1782 if let Some(pipeline) = &self.contacts {
1783 hasher.write(&[2]);
1784 pipeline.hash_state(&self.records, hasher);
1785 }
1786 }
1787
1788 fn contributes_to_hash(&self) -> bool {
1789 true
1790 }
1791
1792 fn replicate(&self, out: &mut Vec<u8>) -> bool {
1793 let mut entries: Vec<(u64, &Transform)> = self
1799 .records
1800 .iter()
1801 .map(|(_, record)| {
1802 let transform = match record.set {
1803 BodySet::Awake => &self.awake.transforms[record.index],
1804 BodySet::Static => &self.statics.transforms[record.index],
1805 BodySet::Sleeping => self.islands.transform(record.island, record.index),
1806 };
1807 (record.entity.to_bits(), transform)
1808 })
1809 .collect();
1810 entries.sort_unstable_by_key(|(bits, _)| *bits);
1811 let mut component = Vec::with_capacity(Transform::ENCODED_LEN);
1812 for (bits, transform) in &entries {
1813 component.clear();
1814 transform.encode_wire(&mut component);
1815 out.extend_from_slice(&bits.to_le_bytes());
1816 out.extend_from_slice(&(component.len() as u32).to_le_bytes());
1817 out.extend_from_slice(&component);
1818 }
1819 !entries.is_empty()
1820 }
1821
1822 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
1823 self
1824 }
1825}
1826
1827#[cfg(test)]
1832mod tests {
1833 use super::*;
1834 use crate::forces::GravityForce;
1835 use glam::DVec3;
1836
1837 fn test_entity(idx: u32) -> Entity {
1838 Entity::from_bits(((1u64) << 32) | idx as u64).expect("test entity")
1839 }
1840
1841 #[test]
1844 fn empty_system_has_no_colliders() {
1845 let phys = PhysicsSystem::new();
1846 assert_eq!(phys.collider_count(), 0);
1847 }
1848
1849 #[test]
1867 fn the_view_names_the_right_entities_from_every_thread_at_once() {
1868 const RADIUS: f64 = 0.45;
1869 const REACH: f64 = 1.5;
1870
1871 let mut phys = PhysicsSystem::new();
1872 let mut placed: Vec<(Entity, DVec3)> = Vec::new();
1873 for idx in 0..40u32 {
1874 let entity = test_entity(idx);
1875 let position = DVec3::new(f64::from(idx % 7), f64::from(idx / 7), 0.0);
1876 let transform = Transform::from_position(position);
1877 phys.set_collider(
1878 entity,
1879 &ColliderComponent::Sphere {
1880 offset: DVec3::ZERO,
1881 radius: RADIUS,
1882 is_trigger: false,
1883 },
1884 &transform,
1885 );
1886 phys.set_transform(entity, transform);
1887 placed.push((entity, position));
1888 }
1889
1890 let centres: Vec<DVec3> = placed.iter().map(|(_, p)| *p).collect();
1891 let oracle = |centre: DVec3| {
1894 let mut hits: Vec<Entity> = placed
1895 .iter()
1896 .filter(|(_, p)| p.distance(centre) <= REACH + RADIUS)
1897 .map(|(e, _)| *e)
1898 .collect();
1899 hits.sort_unstable_by_key(|e| e.to_bits());
1900 hits
1901 };
1902 let expected: Vec<Vec<Entity>> = centres.iter().map(|c| oracle(*c)).collect();
1903 let biggest = expected.iter().map(Vec::len).max().unwrap_or(0);
1904 assert!(
1905 biggest > 4,
1906 "the widest query in the fixture reaches {biggest} entities, which \
1907 is not a neighbourhood",
1908 );
1909
1910 let ask = |queries: &EntityOverlapQueries<'_>| {
1911 let mut scratch = crate::world::QueryScratch::new();
1912 let mut out = Vec::new();
1913 centres
1914 .iter()
1915 .map(|centre| {
1916 queries.overlap_sphere_into(*centre, REACH, &mut scratch, &mut out);
1917 let mut hits: Vec<Entity> = out.iter().map(|&(entity, _)| entity).collect();
1918 hits.sort_unstable_by_key(|entity| entity.to_bits());
1919 hits
1920 })
1921 .collect::<Vec<_>>()
1922 };
1923
1924 let queries = phys.overlap_queries();
1925 assert_eq!(ask(&queries), expected, "the calling thread's own answers");
1926
1927 std::thread::scope(|scope| {
1928 let handles: Vec<_> = (0..4)
1929 .map(|_| scope.spawn(|| ask(&queries)))
1930 .collect::<Vec<_>>();
1931 for handle in handles {
1932 assert_eq!(
1933 handle.join().expect("a query thread panicked"),
1934 expected,
1935 "a thread sharing the view disagreed with the scan",
1936 );
1937 }
1938 });
1939 }
1940
1941 #[derive(Debug, PartialEq)]
1944 struct EntityProbeAnswers {
1945 rays: Vec<Option<(Entity, ShapeHit)>>,
1946 sweeps: Vec<Option<(Entity, ShapeHit)>>,
1947 aabbs: Vec<Vec<Entity>>,
1948 }
1949
1950 #[test]
1966 fn the_view_casts_sweeps_and_boxes_for_the_right_entities_from_every_thread() {
1967 const RADIUS: f64 = 0.45;
1968 const ROWS: u32 = 5;
1972 const COLUMNS: u32 = 7;
1973 const SWEEP_RADIUS: f64 = 0.04;
1976
1977 let mut phys = PhysicsSystem::new();
1978 let mut placed: Vec<(Entity, DVec3)> = Vec::new();
1979 for idx in 0..ROWS * COLUMNS {
1980 let entity = test_entity(idx);
1981 let position = DVec3::new(f64::from(idx % COLUMNS), f64::from(idx / COLUMNS), 0.0);
1982 let transform = Transform::from_position(position);
1983 phys.set_collider(
1984 entity,
1985 &ColliderComponent::Sphere {
1986 offset: DVec3::ZERO,
1987 radius: RADIUS,
1988 is_trigger: false,
1989 },
1990 &transform,
1991 );
1992 phys.set_transform(entity, transform);
1993 placed.push((entity, position));
1994 }
1995
1996 let first_in_row = |row: f64| {
1999 placed
2000 .iter()
2001 .filter(|(_, p)| p.y == row)
2002 .min_by(|(_, a), (_, b)| a.x.total_cmp(&b.x))
2003 .map(|(entity, _)| *entity)
2004 };
2005
2006 let rays: Vec<Ray> = (0..ROWS)
2007 .map(|row| Ray::new(DVec3::new(-10.0, f64::from(row), 0.0), DVec3::X))
2008 .chain(std::iter::once(Ray::new(
2010 DVec3::new(-10.0, 1.5, 0.0),
2011 DVec3::X,
2012 )))
2013 .collect();
2014 let expected_rays: Vec<Option<Entity>> = (0..ROWS)
2015 .map(|row| first_in_row(f64::from(row)))
2016 .chain(std::iter::once(None))
2017 .collect();
2018
2019 let sweeps: Vec<(Segment, f64)> = (0..ROWS)
2020 .map(|row| {
2021 (
2022 Segment::new(
2023 DVec3::new(-10.0, f64::from(row), 0.0),
2024 DVec3::new(10.0, f64::from(row), 0.0),
2025 ),
2026 SWEEP_RADIUS,
2027 )
2028 })
2029 .chain(std::iter::once((
2030 Segment::new(DVec3::new(-10.0, 1.5, 0.0), DVec3::new(10.0, 1.5, 0.0)),
2031 SWEEP_RADIUS,
2032 )))
2033 .collect();
2034 let expected_sweeps = expected_rays.clone();
2035
2036 let aabbs = [
2037 Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(0.1)),
2038 Aabb::from_centre_half(DVec3::new(3.0, 2.0, 0.0), DVec3::splat(1.0)),
2039 Aabb::from_centre_half(DVec3::new(50.0, 50.0, 0.0), DVec3::splat(1.0)),
2040 ];
2041 let expected_aabbs: Vec<Vec<Entity>> = aabbs
2044 .iter()
2045 .map(|aabb| {
2046 let mut hits: Vec<Entity> = placed
2047 .iter()
2048 .filter(|(_, p)| {
2049 Aabb::from_centre_half(*p, DVec3::splat(RADIUS)).intersects(aabb)
2050 })
2051 .map(|(entity, _)| *entity)
2052 .collect();
2053 hits.sort_unstable_by_key(|entity| entity.to_bits());
2054 hits
2055 })
2056 .collect();
2057
2058 let mut named: Vec<Entity> = expected_rays.iter().flatten().copied().collect();
2062 assert_eq!(named.len(), ROWS as usize, "every row has a nearest entity");
2063 named.sort_unstable_by_key(|entity| entity.to_bits());
2064 named.dedup();
2065 assert_eq!(
2066 named.len(),
2067 ROWS as usize,
2068 "two rows expect the same entity, so a slot-to-entity mix-up could \\
2069 pass this",
2070 );
2071 let widest = expected_aabbs.iter().map(Vec::len).max().unwrap_or(0);
2072 assert!(
2073 widest > 4 && expected_aabbs.iter().any(Vec::is_empty),
2074 "the box probes reach at most {widest} entities and never nothing, \\
2075 so one of the two cases never runs",
2076 );
2077
2078 let exclusive = EntityProbeAnswers {
2079 rays: rays.iter().map(|ray| phys.cast_ray(ray)).collect(),
2080 sweeps: sweeps
2081 .iter()
2082 .map(|(segment, radius)| phys.sweep_sphere(segment, *radius))
2083 .collect(),
2084 aabbs: aabbs
2085 .iter()
2086 .map(|aabb| {
2087 let mut hits = phys.overlap_aabb(aabb);
2088 hits.sort_unstable_by_key(|entity| entity.to_bits());
2089 hits
2090 })
2091 .collect(),
2092 };
2093
2094 assert_eq!(
2095 exclusive
2096 .rays
2097 .iter()
2098 .map(|hit| hit.map(|(entity, _)| entity))
2099 .collect::<Vec<_>>(),
2100 expected_rays,
2101 "the entities the casts named",
2102 );
2103 assert_eq!(
2104 exclusive
2105 .sweeps
2106 .iter()
2107 .map(|hit| hit.map(|(entity, _)| entity))
2108 .collect::<Vec<_>>(),
2109 expected_sweeps,
2110 "the entities the sweeps named",
2111 );
2112 assert_eq!(exclusive.aabbs, expected_aabbs, "the entities in the boxes");
2113
2114 let ask = |queries: &EntityOverlapQueries<'_>| {
2118 let mut scratch = crate::world::QueryScratch::new();
2119 let mut found = Vec::new();
2120 EntityProbeAnswers {
2121 rays: rays
2122 .iter()
2123 .map(|ray| queries.cast_ray(ray, &mut scratch))
2124 .collect(),
2125 sweeps: sweeps
2126 .iter()
2127 .map(|(segment, radius)| queries.sweep_sphere(segment, *radius, &mut scratch))
2128 .collect(),
2129 aabbs: aabbs
2130 .iter()
2131 .map(|aabb| {
2132 queries.overlap_aabb_into(aabb, &mut scratch, &mut found);
2133 let mut hits = found.clone();
2134 hits.sort_unstable_by_key(|entity| entity.to_bits());
2135 hits
2136 })
2137 .collect(),
2138 }
2139 };
2140
2141 let queries = phys.overlap_queries();
2142 assert_eq!(ask(&queries), exclusive, "the calling thread's own answers");
2143
2144 std::thread::scope(|scope| {
2145 let handles: Vec<_> = (0..4).map(|_| scope.spawn(|| ask(&queries))).collect();
2146 for handle in handles {
2147 assert_eq!(
2148 handle.join().expect("a query thread panicked"),
2149 exclusive,
2150 "a thread sharing the view disagreed with the placements",
2151 );
2152 }
2153 });
2154 }
2155
2156 fn replicated_entries(out: &[u8]) -> Vec<(u64, Vec<u8>)> {
2158 let mut cursor = 0usize;
2159 let mut entries = Vec::new();
2160 while cursor < out.len() {
2161 let bits = u64::from_le_bytes(out[cursor..cursor + 8].try_into().unwrap());
2162 cursor += 8;
2163 let len = u32::from_le_bytes(out[cursor..cursor + 4].try_into().unwrap()) as usize;
2164 cursor += 4;
2165 entries.push((bits, out[cursor..cursor + len].to_vec()));
2166 cursor += len;
2167 }
2168 entries
2169 }
2170
2171 fn replicated(phys: &PhysicsSystem) -> Vec<u8> {
2173 let mut out = Vec::new();
2174 SystemTrait::replicate(phys, &mut out);
2175 out
2176 }
2177
2178 #[test]
2179 fn replicate_encodes_sorted_transform_blobs() {
2180 let mut phys = PhysicsSystem::new();
2181 let e1 = test_entity(9);
2182 let e2 = test_entity(2);
2183 phys.set_transform(e1, Transform::from_position(DVec3::new(1.0, 2.0, 3.0)));
2185 phys.set_transform(
2186 e2,
2187 Transform::new(
2188 DVec3::new(-4.0, 0.5, 8.0),
2189 glam::DQuat::from_xyzw(0.0, 0.0, 0.0, 1.0),
2190 ),
2191 );
2192
2193 let mut out = Vec::new();
2194 assert!(SystemTrait::replicate(&phys, &mut out));
2195
2196 let entity_len = 8 + 4 + Transform::QUANTIZED_LEN;
2197 assert_eq!(
2198 out.len(),
2199 2 * entity_len,
2200 "both inside the range: quantized"
2201 );
2202
2203 let decoded: Vec<_> = replicated_entries(&out)
2204 .into_iter()
2205 .map(|(bits, data)| (bits, Transform::decode_wire(&data).unwrap()))
2206 .collect();
2207 assert_eq!(decoded[0].0, e2.to_bits(), "sorted by entity bits");
2208 assert_eq!(decoded[1].0, e1.to_bits());
2209 assert_eq!(decoded[0].1.position, DVec3::new(-4.0, 0.5, 8.0));
2211 assert_eq!(decoded[1].1.position, DVec3::new(1.0, 2.0, 3.0));
2212
2213 let empty = PhysicsSystem::new();
2215 let mut out = Vec::new();
2216 assert!(!SystemTrait::replicate(&empty, &mut out));
2217 assert!(out.is_empty());
2218 }
2219
2220 #[test]
2224 fn a_sub_quantum_move_replicates_the_same_bytes_and_a_larger_one_does_not() {
2225 let q = Transform::WIRE_POSITION.quantum();
2226 let entity = test_entity(1);
2227 let at = |x: f64| {
2228 let mut phys = PhysicsSystem::new();
2229 phys.set_transform(
2230 entity,
2231 Transform::new(
2232 DVec3::new(x, 1.0, -2.0),
2233 crate::rotation_from_scaled_axis(DVec3::Y * 0.3),
2234 ),
2235 );
2236 phys
2237 };
2238 let still = replicated(&at(10.0));
2239 assert_eq!(replicated(&at(10.0 + q / 4.0)), still, "a quarter quantum");
2240 assert_eq!(replicated(&at(10.0 - q / 4.0)), still);
2241 assert_ne!(replicated(&at(10.0 + q)), still, "a whole quantum");
2242 }
2243
2244 #[test]
2249 fn the_determinism_hash_sees_what_quantization_rounds_away() {
2250 use std::collections::hash_map::DefaultHasher;
2251 use std::hash::Hasher;
2252
2253 let q = Transform::WIRE_POSITION.quantum();
2254 let entity = test_entity(1);
2255 let at = |x: f64| {
2256 let mut phys = PhysicsSystem::new();
2257 phys.set_transform(entity, Transform::from_position(DVec3::new(x, 0.0, 0.0)));
2258 phys
2259 };
2260 let (a, b) = (at(3.0), at(3.0 + q / 8.0));
2261 assert_eq!(
2262 replicated(&a),
2263 replicated(&b),
2264 "the wire cannot tell them apart"
2265 );
2266 let hash = |phys: &PhysicsSystem| {
2267 let mut hasher = DefaultHasher::new();
2268 SystemTrait::hash_state(phys, &mut hasher);
2269 hasher.finish()
2270 };
2271 assert_ne!(hash(&a), hash(&b), "the hash can");
2272 }
2273
2274 #[test]
2275 fn transform_encode_decode_roundtrips_and_lerp_midpoint() {
2276 let t = Transform::new(
2277 DVec3::new(1.25, -2.5, 3.75),
2278 crate::rotation_from_scaled_axis(DVec3::Y),
2279 );
2280 let mut buf = Vec::new();
2281 t.encode(&mut buf);
2282 assert_eq!(buf.len(), t.encoded_len());
2283 let decoded = Transform::decode(&buf).unwrap();
2284 assert_eq!(decoded.position, t.position);
2285 assert!((decoded.rotation.dot(t.rotation) - 1.0).abs() < 1e-12);
2286
2287 assert!(Transform::decode(&buf[..buf.len() - 1]).is_none());
2289 assert!(Transform::decode(&[]).is_none());
2290
2291 let a = Transform::from_position(DVec3::new(0.0, 0.0, 0.0));
2292 let b = Transform::from_position(DVec3::new(10.0, -4.0, 2.0));
2293 let mid = a.lerp(&b, 0.5);
2294 assert_eq!(mid.position, DVec3::new(5.0, -2.0, 1.0));
2295 let at_a = a.lerp(&b, 0.0);
2296 let at_b = a.lerp(&b, 1.0);
2297 assert_eq!(at_a.position, a.position);
2298 assert_eq!(at_b.position, b.position);
2299 }
2300
2301 #[test]
2302 fn set_and_remove_collider() {
2303 let mut phys = PhysicsSystem::new();
2304 let e = test_entity(0);
2305 let transform = Transform::from_position(DVec3::new(1.0, 2.0, 3.0));
2306 let comp = ColliderComponent::Sphere {
2307 offset: DVec3::ZERO,
2308 radius: 1.0,
2309 is_trigger: false,
2310 };
2311 phys.set_collider(e, &comp, &transform);
2312 assert_eq!(phys.collider_count(), 1);
2313 phys.remove_collider(e);
2314 assert_eq!(phys.collider_count(), 0);
2315 }
2316
2317 #[test]
2318 fn ray_cast_hits_entity() {
2319 let mut phys = PhysicsSystem::new();
2320 let e = test_entity(0);
2321 let transform = Transform::from_position(DVec3::new(5.0, 0.0, 0.0));
2322 let comp = ColliderComponent::Sphere {
2323 offset: DVec3::ZERO,
2324 radius: 1.0,
2325 is_trigger: false,
2326 };
2327 phys.set_collider(e, &comp, &transform);
2328 let ray = Ray::new(DVec3::ZERO, DVec3::X);
2329 let result = phys.cast_ray(&ray);
2330 assert!(result.is_some());
2331 let (hit_entity, _) = result.unwrap();
2332 assert_eq!(hit_entity, e);
2333 }
2334
2335 #[test]
2336 fn ray_cast_misses_when_no_collider() {
2337 let mut phys = PhysicsSystem::new();
2338 let ray = Ray::new(DVec3::ZERO, DVec3::X);
2339 assert!(phys.cast_ray(&ray).is_none());
2340 }
2341
2342 #[test]
2343 fn overlap_aabb_finds_entity() {
2344 let mut phys = PhysicsSystem::new();
2345 let e = test_entity(0);
2346 let transform = Transform::from_position(DVec3::new(2.0, 0.0, 0.0));
2347 let comp = ColliderComponent::Sphere {
2348 offset: DVec3::ZERO,
2349 radius: 1.0,
2350 is_trigger: false,
2351 };
2352 phys.set_collider(e, &comp, &transform);
2353 let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(3.0));
2354 let hits = phys.overlap_aabb(&query);
2355 assert_eq!(hits.len(), 1);
2356 assert_eq!(hits[0], e);
2357 }
2358
2359 #[test]
2360 fn sweep_removes_dead_entities() {
2361 let mut phys = PhysicsSystem::new();
2362 let e = test_entity(0);
2363 let transform = Transform::IDENTITY;
2364 let comp = ColliderComponent::Sphere {
2365 offset: DVec3::ZERO,
2366 radius: 1.0,
2367 is_trigger: false,
2368 };
2369 phys.set_collider(e, &comp, &transform);
2370 assert_eq!(phys.collider_count(), 1);
2371 phys.sweep(&[e]);
2372 assert_eq!(phys.collider_count(), 0);
2373 }
2374
2375 #[test]
2376 fn the_entity_count_starts_at_zero_and_follows_the_colliders_that_are_set() {
2377 let mut phys = PhysicsSystem::new();
2378 assert_eq!(phys.entity_count(), 0);
2379 let e = test_entity(0);
2380 phys.set_collider(
2381 e,
2382 &ColliderComponent::Sphere {
2383 offset: DVec3::ZERO,
2384 radius: 1.0,
2385 is_trigger: false,
2386 },
2387 &Transform::IDENTITY,
2388 );
2389 assert_eq!(phys.entity_count(), 1);
2390 }
2391
2392 #[test]
2393 fn replacing_collider_keeps_count_stable() {
2394 let mut phys = PhysicsSystem::new();
2395 let e = test_entity(0);
2396 let transform = Transform::IDENTITY;
2397 let comp1 = ColliderComponent::Sphere {
2398 offset: DVec3::ZERO,
2399 radius: 1.0,
2400 is_trigger: false,
2401 };
2402 let comp2 = ColliderComponent::Box {
2403 offset: DVec3::ZERO,
2404 half_extents: DVec3::splat(2.0),
2405 is_trigger: true,
2406 };
2407 phys.set_collider(e, &comp1, &transform);
2408 phys.set_collider(e, &comp2, &transform);
2409 assert_eq!(phys.collider_count(), 1);
2410 }
2411
2412 #[test]
2413 fn sweep_sphere_hits_entity() {
2414 let mut phys = PhysicsSystem::new();
2415 let e = test_entity(0);
2416 let transform = Transform::from_position(DVec3::new(5.0, 0.0, 0.0));
2417 let comp = ColliderComponent::Sphere {
2418 offset: DVec3::ZERO,
2419 radius: 1.0,
2420 is_trigger: false,
2421 };
2422 phys.set_collider(e, &comp, &transform);
2423 let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
2424 let result = phys.sweep_sphere(&seg, 0.5);
2425 assert!(result.is_some());
2426 let (hit_entity, _) = result.unwrap();
2427 assert_eq!(hit_entity, e);
2428 }
2429
2430 #[test]
2443 fn sweep_body_catches_a_crossing_a_stationary_overlap_would_miss() {
2444 let mut phys = PhysicsSystem::new();
2445 let bullet = test_entity(0);
2446 let rock = test_entity(1);
2447
2448 let mut body = RigidBody::new_kinematic();
2450 body.velocity = DVec3::new(10.0, 0.0, 0.0);
2451 phys.set_body(bullet, body);
2452 phys.set_transform(bullet, Transform::from_position(DVec3::ZERO));
2453
2454 phys.set_collider(
2457 rock,
2458 &ColliderComponent::Sphere {
2459 offset: DVec3::ZERO,
2460 radius: 1.0,
2461 is_trigger: false,
2462 },
2463 &Transform::from_position(DVec3::new(-5.0, 0.0, 0.0)),
2464 );
2465
2466 let (hit_entity, hit) = phys
2467 .sweep_body(bullet, 1.0, 0.5)
2468 .expect("the sweep crossed the rock");
2469 assert_eq!(hit_entity, rock, "the sweep hit the wrong entity");
2470 assert_eq!(hit.normal, DVec3::NEG_X, "the sweep ran the wrong way");
2473 }
2474
2475 #[test]
2484 fn a_stationary_body_sweeps_nothing_it_does_not_already_touch() {
2485 let mut phys = PhysicsSystem::new();
2486 let bullet = test_entity(0);
2487 phys.set_body(bullet, RigidBody::new_kinematic());
2488 phys.set_transform(bullet, Transform::from_position(DVec3::ZERO));
2489
2490 phys.set_collider(
2493 test_entity(1),
2494 &ColliderComponent::Sphere {
2495 offset: DVec3::ZERO,
2496 radius: 1.0,
2497 is_trigger: false,
2498 },
2499 &Transform::from_position(DVec3::new(1.4, 1.4, 0.0)),
2500 );
2501
2502 assert_eq!(phys.sweep_body(bullet, 1.0, 0.5), None);
2503 }
2504
2505 #[test]
2514 fn sweep_body_leaves_the_swept_colliders_registration_alone() {
2515 let mut phys = PhysicsSystem::new();
2516 let mover = test_entity(0);
2517 let mut body = RigidBody::new_kinematic();
2518 body.velocity = DVec3::new(10.0, 0.0, 0.0);
2519 phys.set_body(mover, body);
2520 phys.set_collider(
2521 mover,
2522 &ColliderComponent::Sphere {
2523 offset: DVec3::ZERO,
2524 radius: 1.0,
2525 is_trigger: false,
2526 },
2527 &Transform::from_position(DVec3::ZERO),
2528 );
2529
2530 let collider_of = |phys: &PhysicsSystem| {
2531 phys.record(mover)
2532 .and_then(|record| record.collider.as_ref())
2533 .map(|(collider, _)| *collider)
2534 .expect("the mover has a collider")
2535 };
2536 let before = collider_of(&phys);
2537 for _ in 0..8 {
2538 let _ = phys.sweep_body(mover, 1.0, 0.5);
2539 }
2540 assert_eq!(
2541 collider_of(&phys),
2542 before,
2543 "the sweep re-registered the collider it swept"
2544 );
2545 assert_eq!(phys.collider_count(), 1);
2546 }
2547
2548 #[test]
2559 fn sweep_body_never_hits_the_body_it_sweeps() {
2560 let sphere = ColliderComponent::Sphere {
2561 offset: DVec3::ZERO,
2562 radius: 1.0,
2563 is_trigger: false,
2564 };
2565 let mut phys = PhysicsSystem::new();
2566 let mover = test_entity(0);
2567 let wall = test_entity(1);
2568
2569 let mut body = RigidBody::new_kinematic();
2570 body.velocity = DVec3::new(10.0, 0.0, 0.0);
2571 phys.set_body(mover, body);
2572 phys.set_collider(mover, &sphere, &Transform::from_position(DVec3::ZERO));
2573
2574 assert_eq!(
2575 phys.sweep_body(mover, 1.0, 0.5),
2576 None,
2577 "the only collider in the world is the mover's own"
2578 );
2579
2580 phys.set_collider(
2583 wall,
2584 &sphere,
2585 &Transform::from_position(DVec3::new(0.5, 0.0, 0.0)),
2586 );
2587 let (hit_entity, hit) = phys
2588 .sweep_body(mover, 1.0, 0.5)
2589 .expect("the wall is on the segment");
2590 assert_eq!(hit_entity, wall, "the mover masked the wall with itself");
2591 assert!((hit.t - 0.90).abs() < 1e-9, "expected ~0.90, got {}", hit.t);
2592 }
2593
2594 #[test]
2605 fn overlap_sphere_into_answers_the_owned_form_and_reuses_the_buffer() {
2606 let mut phys = PhysicsSystem::new();
2607 for (index, x) in [0.0, 1.0, 2.0, 40.0].into_iter().enumerate() {
2608 let e = test_entity(index as u32);
2609 let at = Transform::from_position(DVec3::new(x, 0.0, 0.0));
2610 phys.set_collider(
2611 e,
2612 &ColliderComponent::Sphere {
2613 offset: DVec3::ZERO,
2614 radius: 0.5,
2615 is_trigger: false,
2616 },
2617 &at,
2618 );
2619 }
2620
2621 let owned = phys.overlap_sphere(DVec3::ZERO, 2.0);
2622 assert!(
2623 owned.len() > 1 && owned.len() < 4,
2624 "the fixture must include some colliders and exclude some: {}",
2625 owned.len(),
2626 );
2627
2628 let mut out = Vec::new();
2629 phys.overlap_sphere_into(DVec3::ZERO, 2.0, &mut out);
2630 assert_eq!(out, owned, "the two forms disagree");
2631
2632 out.push((test_entity(99), owned[0].1));
2635 phys.overlap_sphere_into(DVec3::ZERO, 2.0, &mut out);
2636 assert_eq!(
2637 out, owned,
2638 "the buffer was appended to rather than refilled"
2639 );
2640
2641 let capacity = out.capacity();
2642 for _ in 0..64 {
2643 phys.overlap_sphere_into(DVec3::ZERO, 2.0, &mut out);
2644 }
2645 assert_eq!(
2646 out.capacity(),
2647 capacity,
2648 "the buffer grew on a repeat query, so the loop still allocates",
2649 );
2650
2651 let mut scratch = crate::world::QueryScratch::new();
2654 let view = phys.overlap_queries();
2655 out.push((test_entity(99), owned[0].1));
2656 view.overlap_sphere_filtered_into(
2657 DVec3::ZERO,
2658 2.0,
2659 QueryFilter::ALL,
2660 &mut scratch,
2661 &mut out,
2662 );
2663 assert_eq!(out, owned, "the view's buffer was appended to");
2664 let mut entities = vec![test_entity(99)];
2665 view.overlap_sphere_entities_into(DVec3::ZERO, 2.0, &mut scratch, &mut entities);
2666 let named: Vec<Entity> = owned.iter().map(|&(entity, _)| entity).collect();
2667 assert_eq!(entities, named, "the entities-only form disagrees");
2668 }
2669
2670 #[test]
2681 fn a_velocity_written_through_body_mut_is_the_one_that_integrates() {
2682 let mut phys = PhysicsSystem::new();
2683 let e = test_entity(0);
2684 phys.set_body(e, RigidBody::new_kinematic());
2685 phys.set_transform(e, Transform::from_position(DVec3::ZERO));
2686 let comp = ColliderComponent::Sphere {
2687 offset: DVec3::ZERO,
2688 radius: 0.5,
2689 is_trigger: false,
2690 };
2691 phys.set_collider(e, &comp, &Transform::from_position(DVec3::ZERO));
2692
2693 phys.apply_force(e, DVec3::new(1000.0, 0.0, 0.0));
2695 phys.step(1.0 / 60.0);
2696 assert_eq!(
2697 phys.transform(e).expect("a transform").position,
2698 DVec3::ZERO,
2699 "a force moved a kinematic body",
2700 );
2701
2702 phys.body_mut(e).expect("a body").velocity = DVec3::new(3.0, 0.0, 0.0);
2703 let dt = 1.0 / 60.0;
2704 phys.step(dt);
2705 assert!(
2706 (phys.transform(e).expect("a transform").position.x - 3.0 * dt).abs() < 1e-12,
2707 "the written velocity did not reach the integrator: {:?}",
2708 phys.transform(e).expect("a transform").position,
2709 );
2710 assert_eq!(
2711 phys.body(e).expect("a body").velocity,
2712 DVec3::new(3.0, 0.0, 0.0),
2713 "the write did not survive the step",
2714 );
2715 }
2716
2717 #[test]
2724 fn a_steered_body_reaches_the_broadphase_on_the_step_and_not_before() {
2725 let mut phys = PhysicsSystem::new();
2726 let e = test_entity(0);
2727 phys.set_body(e, RigidBody::new_kinematic());
2728 let at = Transform::from_position(DVec3::new(10.0, 0.0, 0.0));
2729 phys.set_transform(e, at);
2730 let comp = ColliderComponent::Sphere {
2731 offset: DVec3::ZERO,
2732 radius: 0.5,
2733 is_trigger: false,
2734 };
2735 phys.set_collider(e, &comp, &at);
2736
2737 phys.body_mut(e).expect("a body").velocity = DVec3::new(0.0, 600.0, 0.0);
2739 assert_eq!(
2740 phys.overlap_sphere(DVec3::new(10.0, 0.0, 0.0), 1.0).len(),
2741 1,
2742 "writing a velocity moved the collider before anything stepped",
2743 );
2744
2745 phys.step(1.0 / 60.0);
2746 assert!(
2747 phys.overlap_sphere(DVec3::new(10.0, 0.0, 0.0), 1.0)
2748 .is_empty(),
2749 "the step moved the body and the broadphase did not hear about it",
2750 );
2751 assert_eq!(
2752 phys.overlap_sphere(phys.transform(e).expect("a transform").position, 1.0)
2753 .len(),
2754 1,
2755 "the collider is not where the body now is",
2756 );
2757 }
2758
2759 #[test]
2760 fn body_falls_under_gravity() {
2761 let mut phys = PhysicsSystem::new();
2762 phys.add_force_provider(Box::new(GravityForce::EARTH));
2763 let e = test_entity(0);
2764 phys.set_body(e, RigidBody::new_dynamic(1.0));
2765 phys.set_transform(e, Transform::from_position(DVec3::new(0.0, 100.0, 0.0)));
2766
2767 let dt = 1.0 / 60.0;
2769 for _ in 0..60 {
2770 phys.step(dt);
2771 }
2772
2773 let t = phys.transform(e).unwrap();
2774 assert!(
2776 t.position.y < 96.0 && t.position.y > 94.0,
2777 "expected pos.y ~95.1, got {}",
2778 t.position.y
2779 );
2780
2781 let b = phys.body(e).unwrap();
2782 assert!(
2784 b.velocity.y < -9.0 && b.velocity.y > -10.5,
2785 "expected vy ~-9.81, got {}",
2786 b.velocity.y
2787 );
2788 }
2789
2790 #[test]
2791 fn kinematic_body_stays_put() {
2792 let mut phys = PhysicsSystem::new();
2793 phys.add_force_provider(Box::new(GravityForce::EARTH));
2794 let e = test_entity(0);
2795 phys.set_body(e, RigidBody::new_kinematic());
2796 phys.set_transform(e, Transform::from_position(DVec3::new(5.0, 5.0, 5.0)));
2797
2798 phys.step(1.0 / 60.0);
2799 let t = phys.transform(e).unwrap();
2800 assert_eq!(t.position, DVec3::new(5.0, 5.0, 5.0));
2801 }
2802
2803 #[test]
2804 fn collider_moves_with_body_after_integration() {
2805 let mut phys = PhysicsSystem::new();
2806 let e = test_entity(0);
2807 let body = {
2808 let mut b = RigidBody::new_dynamic(1.0);
2809 b.velocity = DVec3::new(10.0, 0.0, 0.0);
2810 b
2811 };
2812 let transform = Transform::from_position(DVec3::new(0.0, 0.0, 0.0));
2813 let comp = ColliderComponent::Sphere {
2814 offset: DVec3::ZERO,
2815 radius: 1.0,
2816 is_trigger: false,
2817 };
2818 phys.set_body(e, body);
2819 phys.set_collider(e, &comp, &transform);
2820
2821 phys.step(0.5);
2823 let t = phys.transform(e).unwrap();
2825 assert!((t.position.x - 5.0).abs() < 1e-12);
2826
2827 let ray = Ray::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::X);
2829 let result = phys.cast_ray(&ray);
2830 assert!(result.is_some());
2831 let (hit_entity, hit) = result.unwrap();
2832 assert_eq!(hit_entity, e);
2833 assert!((hit.t - 9.0).abs() < 0.01, "t = {}", hit.t);
2837 }
2838
2839 #[test]
2840 fn remove_entity_cleans_up_all_data() {
2841 let mut phys = PhysicsSystem::new();
2842 let e = test_entity(0);
2843 phys.set_body(e, RigidBody::new_dynamic(1.0));
2844 phys.set_collider(
2845 e,
2846 &ColliderComponent::Sphere {
2847 offset: DVec3::ZERO,
2848 radius: 1.0,
2849 is_trigger: false,
2850 },
2851 &Transform::IDENTITY,
2852 );
2853 assert_eq!(phys.body_count(), 1);
2854 assert_eq!(phys.collider_count(), 1);
2855
2856 phys.remove_entity(e);
2857 assert_eq!(phys.body_count(), 0);
2858 assert_eq!(phys.collider_count(), 0);
2859 assert!(phys.body(e).is_none());
2860 assert!(phys.transform(e).is_none());
2861 }
2862
2863 #[test]
2864 fn multiple_bodies_integrate_independently() {
2865 let mut phys = PhysicsSystem::new();
2866 phys.add_force_provider(Box::new(GravityForce::EARTH));
2867
2868 let e1 = test_entity(0);
2869 let e2 = test_entity(1);
2870
2871 phys.set_body(e1, RigidBody::new_dynamic(1.0));
2872 phys.set_transform(e1, Transform::from_position(DVec3::new(0.0, 0.0, 0.0)));
2873
2874 phys.set_body(e2, RigidBody::new_kinematic());
2876 phys.set_transform(e2, Transform::from_position(DVec3::new(10.0, 10.0, 0.0)));
2877
2878 phys.step(1.0 / 60.0);
2879
2880 let t1 = phys.transform(e1).unwrap();
2881 let t2 = phys.transform(e2).unwrap();
2882 assert!(t1.position.y < 0.0, "dynamic body should fall");
2883 assert_eq!(
2884 t2.position,
2885 DVec3::new(10.0, 10.0, 0.0),
2886 "kinematic should not move"
2887 );
2888 }
2889
2890 #[test]
2898 fn a_step_with_no_bodies_applies_no_force_and_creates_nothing() {
2899 use std::collections::hash_map::DefaultHasher;
2900 use std::hash::Hasher as _;
2901 use std::sync::Arc;
2902 use std::sync::atomic::{AtomicUsize, Ordering};
2903
2904 #[derive(Debug)]
2905 struct CountingGravity(Arc<AtomicUsize>);
2906
2907 impl ForceProvider for CountingGravity {
2908 fn apply(&self, body: &mut RigidBody, transform: &Transform, dt: f64) {
2909 self.0.fetch_add(1, Ordering::SeqCst);
2910 GravityForce::EARTH.apply(body, transform, dt);
2911 }
2912 }
2913
2914 let applications = Arc::new(AtomicUsize::new(0));
2915
2916 let mut phys = PhysicsSystem::new();
2917 phys.add_force_provider(Box::new(CountingGravity(Arc::clone(&applications))));
2918
2919 let mut before = DefaultHasher::new();
2920 SystemTrait::hash_state(&phys, &mut before);
2921
2922 phys.step(1.0 / 60.0);
2923
2924 assert_eq!(
2925 applications.load(Ordering::SeqCst),
2926 0,
2927 "there is no body for a force provider to be applied to"
2928 );
2929 assert_eq!(phys.body_count(), 0);
2930 assert_eq!(phys.collider_count(), 0);
2931
2932 let mut after = DefaultHasher::new();
2933 SystemTrait::hash_state(&phys, &mut after);
2934 assert_eq!(after.finish(), before.finish(), "the step wrote state");
2935 }
2936
2937 #[test]
2940 fn tick_uses_the_schedule_dt_rather_than_an_assumed_rate() {
2941 let simulate = |hz: u32| {
2944 let mut phys = PhysicsSystem::new();
2945 let e = test_entity(0);
2946 let mut body = RigidBody::new_dynamic(1.0);
2947 body.velocity = DVec3::new(10.0, 0.0, 0.0);
2948 phys.set_body(e, body);
2949 phys.set_transform(e, Transform::IDENTITY);
2950
2951 let dt = 1.0 / f64::from(hz);
2952 for _ in 0..hz {
2953 SystemTrait::tick(&mut phys, dt);
2954 }
2955 phys.transform(e).unwrap().position.x
2956 };
2957
2958 let at_60 = simulate(60);
2959 let at_30 = simulate(30);
2960 assert!((at_60 - 10.0).abs() < 1e-9, "x = {at_60}");
2961 assert!((at_30 - 10.0).abs() < 1e-9, "x = {at_30}");
2962 }
2963
2964 #[test]
2965 fn step_visits_bodies_in_canonical_order() {
2966 let build = |reverse: bool| {
2971 let mut phys = PhysicsSystem::new();
2972 phys.add_force_provider(Box::new(GravityForce::EARTH));
2973 let mut indices: Vec<u32> = (0..16).collect();
2974 if reverse {
2975 indices.reverse();
2976 }
2977 for i in indices {
2978 let e = test_entity(i);
2979 let mut body = RigidBody::new_dynamic(1.0 + f64::from(i) * 0.25);
2980 body.velocity = DVec3::new(f64::from(i) * 0.1, 0.0, 0.0);
2981 phys.set_body(e, body);
2982 phys.set_transform(e, Transform::from_position(DVec3::splat(f64::from(i))));
2983 }
2984 for _ in 0..120 {
2985 phys.step(1.0 / 120.0);
2986 }
2987 phys
2988 };
2989
2990 let forward = build(false);
2991 let backward = build(true);
2992 for i in 0..16 {
2993 let e = test_entity(i);
2994 assert_eq!(
2995 forward.transform(e).unwrap().position,
2996 backward.transform(e).unwrap().position,
2997 "entity {i} diverged"
2998 );
2999 }
3000 }
3001
3002 #[test]
3003 fn hash_state_covers_physics_state_in_canonical_order() {
3004 use std::collections::hash_map::DefaultHasher;
3005 use std::hash::Hasher as _;
3006
3007 fn hash(phys: &PhysicsSystem) -> u64 {
3008 let mut h = DefaultHasher::new();
3009 SystemTrait::hash_state(phys, &mut h);
3010 h.finish()
3011 }
3012
3013 let build = |reverse: bool, y: f64| {
3014 let mut phys = PhysicsSystem::new();
3015 let mut indices: Vec<u32> = (0..8).collect();
3016 if reverse {
3017 indices.reverse();
3018 }
3019 for i in indices {
3020 let e = test_entity(i);
3021 phys.set_body(e, RigidBody::new_dynamic(1.0 + f64::from(i)));
3022 phys.set_transform(
3023 e,
3024 Transform::from_position(DVec3::new(f64::from(i), y, 0.0)),
3025 );
3026 }
3027 phys
3028 };
3029
3030 assert!(SystemTrait::contributes_to_hash(&build(false, 0.0)));
3033
3034 assert_eq!(hash(&build(false, 0.0)), hash(&build(true, 0.0)));
3036 assert_ne!(hash(&build(false, 0.0)), hash(&build(false, 1.0)));
3037
3038 let mut moving = build(false, 0.0);
3040 let e = test_entity(3);
3041 let mut body = *moving.body(e).unwrap();
3042 body.velocity = DVec3::new(0.0, -1.0, 0.0);
3043 moving.set_body(e, body);
3044 assert_ne!(hash(&build(false, 0.0)), hash(&moving));
3045 }
3046
3047 #[test]
3058 fn removing_from_the_middle_of_a_set_leaves_every_other_body_its_own_state() {
3059 let mut phys = PhysicsSystem::new();
3060 let at = |i: u32| DVec3::new(f64::from(i) * 10.0, 0.0, 0.0);
3061 let sphere = ColliderComponent::Sphere {
3062 offset: DVec3::ZERO,
3063 radius: 1.0,
3064 is_trigger: false,
3065 };
3066 for i in 0..12u32 {
3067 let e = test_entity(i);
3068 phys.set_collider(e, &sphere, &Transform::from_position(at(i)));
3069 if i % 3 != 0 {
3070 let mut body = RigidBody::new_dynamic(1.0 + f64::from(i));
3071 body.velocity = DVec3::Y;
3072 phys.set_body(e, body);
3073 }
3074 }
3075 for i in [1u32, 3, 7, 0, 11] {
3076 phys.remove_entity(test_entity(i));
3077 }
3078 phys.step(1.0);
3079
3080 for i in 0..12u32 {
3081 let e = test_entity(i);
3082 let removed = [1u32, 3, 7, 0, 11].contains(&i);
3083 if removed {
3084 assert!(phys.transform(e).is_none(), "{i} survived its removal");
3085 continue;
3086 }
3087 let has_body = i % 3 != 0;
3088 let want = at(i) + if has_body { DVec3::Y } else { DVec3::ZERO };
3089 assert_eq!(
3090 phys.transform(e).expect("a transform").position,
3091 want,
3092 "entity {i} has another's transform"
3093 );
3094 assert_eq!(
3095 phys.body(e).map(|body| body.mass),
3096 has_body.then(|| 1.0 + f64::from(i)),
3097 "entity {i} has another's body"
3098 );
3099 let hit = phys
3100 .cast_ray(&Ray::new(want - DVec3::Z * 5.0, DVec3::Z))
3101 .map(|(entity, _)| entity);
3102 assert_eq!(hit, Some(e), "entity {i}'s collider is not where it is");
3103 }
3104 assert_eq!(phys.body_count(), 5);
3105 assert_eq!(phys.collider_count(), 7);
3106 }
3107
3108 #[test]
3111 fn a_body_moves_a_static_entity_into_the_awake_set_with_its_transform() {
3112 let mut phys = PhysicsSystem::new();
3113 let (wall, prop, crate_) = (test_entity(0), test_entity(1), test_entity(2));
3114 phys.set_transform(wall, Transform::from_position(DVec3::X));
3115 phys.set_transform(crate_, Transform::from_position(DVec3::Y));
3116 phys.set_transform(prop, Transform::from_position(DVec3::Z));
3117
3118 let mut body = RigidBody::new_kinematic();
3119 body.velocity = DVec3::X;
3120 phys.set_body(wall, body);
3121 phys.step(1.0);
3122
3123 assert_eq!(
3124 phys.transform(wall).expect("a transform").position,
3125 DVec3::X * 2.0
3126 );
3127 assert_eq!(
3128 phys.transform(crate_).expect("a transform").position,
3129 DVec3::Y
3130 );
3131 assert_eq!(
3132 phys.transform(prop).expect("a transform").position,
3133 DVec3::Z
3134 );
3135 assert!(phys.body(crate_).is_none() && phys.body(prop).is_none());
3136 assert_eq!(phys.body_count(), 1);
3137 }
3138
3139 #[test]
3140 fn a_material_is_carried_on_its_entity_and_defaults_until_set() {
3141 let mut phys = PhysicsSystem::new();
3142 let (ice, floor) = (test_entity(0), test_entity(1));
3143 let ghost = test_entity(2);
3144 phys.set_body(ice, RigidBody::new_dynamic(1.0));
3145 phys.set_transform(floor, Transform::IDENTITY);
3146
3147 assert_eq!(phys.material(ice), Some(SurfaceMaterial::DEFAULT));
3148 let slick = SurfaceMaterial::new(0.02, 0.1);
3149 assert!(phys.set_material(ice, slick));
3150 assert!(phys.set_material(floor, SurfaceMaterial::new(0.9, 0.0)));
3151 assert_eq!(phys.material(ice), Some(slick));
3152 assert_eq!(phys.material(floor).map(|m| m.friction), Some(0.9));
3153
3154 assert!(!phys.set_material(ghost, slick), "an unregistered entity");
3155 assert_eq!(phys.material(ghost), None);
3156 phys.remove_entity(ice);
3157 assert_eq!(phys.material(ice), None, "the material outlived its entity");
3158 }
3159
3160 #[test]
3163 fn the_hash_does_not_tell_a_negative_zero_from_a_positive_one() {
3164 use std::collections::hash_map::DefaultHasher;
3165 use std::hash::Hasher as _;
3166
3167 let hash = |vx: f64| {
3168 let mut phys = PhysicsSystem::new();
3169 let mut body = RigidBody::new_dynamic(1.0);
3170 body.velocity = DVec3::new(vx, 1.0, 0.0);
3171 phys.set_body(test_entity(0), body);
3172 let mut h = DefaultHasher::new();
3173 SystemTrait::hash_state(&phys, &mut h);
3174 h.finish()
3175 };
3176 assert_eq!(hash(0.0), hash(-0.0));
3177 assert_ne!(
3178 hash(0.0),
3179 hash(f64::MIN_POSITIVE),
3180 "the hash cannot see velocity"
3181 );
3182 }
3183}
3184
3185#[cfg(test)]
3186#[path = "system/query_layer_tests.rs"]
3187mod query_layer_tests;