veloren_common_systems/phys/
mod.rs

1use common::{
2    comp::{
3        Body, CharacterState, Collider, Density, Immovable, Mass, Ori, PhysicsState, Pos,
4        PosVelOriDefer, PreviousPhysCache, Projectile, Scale, Stats, Sticky, Vel,
5        body::ship::{self, figuredata::VOXEL_COLLIDER_MANIFEST},
6        fluid_dynamics::{Fluid, Wings},
7        inventory::item::armor::Friction,
8    },
9    consts::{AIR_DENSITY, GRAVITY},
10    event::{EmitExt, EventBus, LandOnGroundEvent},
11    event_emitters,
12    link::Is,
13    mounting::{Rider, VolumeRider},
14    outcome::Outcome,
15    resources::{DeltaTime, GameMode, TimeOfDay},
16    spiral::Spiral2d,
17    states,
18    terrain::{CoordinateConversions, TerrainGrid},
19    uid::Uid,
20    util::{Dir, Projection, SpatialGrid},
21    weather::WeatherGrid,
22};
23use common_base::{prof_span, span};
24use common_ecs::{Job, Origin, ParMode, Phase, PhysicsMetrics, System};
25use rayon::iter::ParallelIterator;
26use specs::{
27    Entities, Join, LendJoin, ParJoin, Read, ReadExpect, ReadStorage, SystemData, Write,
28    WriteExpect, WriteStorage, shred,
29};
30use vek::*;
31
32mod collision;
33mod weather;
34use collision::ColliderData;
35
36/// The density of the fluid as a function of submersion ratio in given fluid
37/// where it is assumed that any unsubmersed part is is air.
38// TODO: Better suited partial submersion curve?
39fn fluid_density(height: f32, fluid: &Fluid) -> Density {
40    // If depth is less than our height (partial submersion), remove
41    // fluid density based on the ratio of displacement to full volume.
42    let immersion = fluid
43        .depth()
44        .map_or(1.0, |depth| (depth / height).clamp(0.0, 1.0));
45
46    Density(fluid.density().0 * immersion + AIR_DENSITY * (1.0 - immersion))
47}
48
49fn integrate_forces(
50    dt: &DeltaTime,
51    mut vel: Vel,
52    (body, wings): (&Body, Option<&Wings>),
53    density: &Density,
54    mass: &Mass,
55    fluid: &Fluid,
56    gravity: f32,
57    scale: Option<Scale>,
58) -> Vel {
59    let dim = body.dimensions();
60    let height = dim.z;
61    let rel_flow = fluid.relative_flow(&vel);
62    let fluid_density = fluid_density(height, fluid);
63    debug_assert!(mass.0 > 0.0);
64    debug_assert!(density.0 > 0.0);
65
66    // Aerodynamic/hydrodynamic forces
67    if !rel_flow.0.is_approx_zero() {
68        debug_assert!(!rel_flow.0.map(|a| a.is_nan()).reduce_or());
69        // HACK: We should really use the latter logic (i.e: `aerodynamic_forces`) for
70        // liquids, but it results in pretty serious dt-dependent problems that
71        // are extremely difficult to resolve. This is a compromise: for liquids
72        // only, we calculate drag using an incorrect (but still visually plausible)
73        // model that is much more resistant to differences in dt. Because it's
74        // physically incorrect anyway, there are magic coefficients that
75        // exist simply to get us closer to what water 'should' feel like.
76        if fluid.is_liquid() {
77            let fric = body
78                .drag_coefficient_liquid(fluid_density.0, scale.map_or(1.0, |s| s.0))
79                .powf(0.75)
80                * 0.02;
81
82            let fvel = fluid.flow_vel();
83
84            // Drag is relative to fluid velocity, so compensate before applying drag
85            vel.0 = (vel.0 - fvel.0) * (1.0 / (1.0 + fric)).powf(dt.0 * 10.0) + fvel.0;
86        } else {
87            let impulse = dt.0
88                * body.aerodynamic_forces(
89                    &rel_flow,
90                    fluid_density.0,
91                    wings,
92                    scale.map_or(1.0, |s| s.0),
93                );
94            debug_assert!(!impulse.map(|a| a.is_nan()).reduce_or());
95            if !impulse.is_approx_zero() {
96                let new_v = vel.0 + impulse / mass.0;
97                // If the new velocity is in the opposite direction, it's because the forces
98                // involved are too high for the current tick to handle. We deal with this by
99                // removing the component of our velocity vector along the direction of force.
100                // This way we can only ever lose velocity and will never experience a reverse
101                // in direction from events such as falling into water at high velocities.
102                if new_v.dot(vel.0) < 0.0 {
103                    // Multiply by a factor to prevent full stop,
104                    // as this can cause things to get stuck in high-density medium
105                    vel.0 -= vel.0.projected(&impulse) * 0.9;
106                } else {
107                    vel.0 = new_v;
108                }
109            }
110        }
111        debug_assert!(!vel.0.map(|a| a.is_nan()).reduce_or());
112    };
113
114    // Hydrostatic/aerostatic forces
115    // modify gravity to account for the effective density as a result of buoyancy
116    let down_force = dt.0 * gravity * (density.0 - fluid_density.0) / density.0;
117    vel.0.z -= down_force;
118
119    vel
120}
121
122fn calc_z_limit(char_state_maybe: Option<&CharacterState>, collider: &Collider) -> (f32, f32) {
123    let modifier = if char_state_maybe.is_some_and(|c_s| c_s.is_dodge() || c_s.is_glide()) {
124        0.5
125    } else {
126        1.0
127    };
128    collider.get_z_limits(modifier)
129}
130
131event_emitters! {
132    struct Events[Emitters] {
133        land_on_ground: LandOnGroundEvent,
134    }
135}
136
137/// This system applies forces and calculates new positions and velocities.
138#[derive(Default)]
139pub struct Sys;
140
141#[derive(SystemData)]
142pub struct PhysicsRead<'a> {
143    entities: Entities<'a>,
144    events: Events<'a>,
145    uids: ReadStorage<'a, Uid>,
146    terrain: ReadExpect<'a, TerrainGrid>,
147    dt: Read<'a, DeltaTime>,
148    game_mode: ReadExpect<'a, GameMode>,
149    scales: ReadStorage<'a, Scale>,
150    stickies: ReadStorage<'a, Sticky>,
151    immovables: ReadStorage<'a, Immovable>,
152    masses: ReadStorage<'a, Mass>,
153    colliders: ReadStorage<'a, Collider>,
154    is_riders: ReadStorage<'a, Is<Rider>>,
155    is_volume_riders: ReadStorage<'a, Is<VolumeRider>>,
156    projectiles: ReadStorage<'a, Projectile>,
157    character_states: ReadStorage<'a, CharacterState>,
158    bodies: ReadStorage<'a, Body>,
159    densities: ReadStorage<'a, Density>,
160    stats: ReadStorage<'a, Stats>,
161    weather: Option<Read<'a, WeatherGrid>>,
162    time_of_day: Read<'a, TimeOfDay>,
163}
164
165#[derive(SystemData)]
166pub struct PhysicsWrite<'a> {
167    physics_metrics: WriteExpect<'a, PhysicsMetrics>,
168    cached_spatial_grid: Write<'a, common::CachedSpatialGrid>,
169    physics_states: WriteStorage<'a, PhysicsState>,
170    positions: WriteStorage<'a, Pos>,
171    velocities: WriteStorage<'a, Vel>,
172    pos_vel_ori_defers: WriteStorage<'a, PosVelOriDefer>,
173    orientations: WriteStorage<'a, Ori>,
174    previous_phys_cache: WriteStorage<'a, PreviousPhysCache>,
175    outcomes: Read<'a, EventBus<Outcome>>,
176}
177
178#[derive(SystemData)]
179pub struct PhysicsData<'a> {
180    read: PhysicsRead<'a>,
181    write: PhysicsWrite<'a>,
182}
183
184impl PhysicsData<'_> {
185    /// Add/reset physics state components
186    fn reset(&mut self) {
187        span!(_guard, "Add/reset physics state components");
188        for (entity, _, _, _, _) in (
189            &self.read.entities,
190            &self.read.colliders,
191            &self.write.positions,
192            &self.write.velocities,
193            &self.write.orientations,
194        )
195            .join()
196        {
197            let _ = self
198                .write
199                .physics_states
200                .entry(entity)
201                .map(|e| e.or_insert_with(Default::default));
202        }
203    }
204
205    fn maintain_pushback_cache(&mut self) {
206        span!(_guard, "Maintain pushback cache");
207        // Add PreviousPhysCache for all relevant entities
208        for entity in (
209            &self.read.entities,
210            &self.read.colliders,
211            &self.write.velocities,
212            &self.write.positions,
213            !&self.write.previous_phys_cache,
214        )
215            .join()
216            .map(|(e, _, _, _, _)| e)
217            .collect::<Vec<_>>()
218        {
219            let _ = self
220                .write
221                .previous_phys_cache
222                .insert(entity, PreviousPhysCache {
223                    velocity: Vec3::zero(),
224                    velocity_dt: Vec3::zero(),
225                    in_fluid: None,
226                    center: Vec3::zero(),
227                    collision_boundary: 0.0,
228                    scale: 0.0,
229                    scaled_radius: 0.0,
230                    neighborhood_radius: 0.0,
231                    origins: None,
232                    pos: None,
233                    ori: Quaternion::identity(),
234                });
235        }
236
237        // Update PreviousPhysCache
238        for (_, vel, position, ori, phys_state, phys_cache, collider, scale, cs) in (
239            &self.read.entities,
240            &self.write.velocities,
241            &self.write.positions,
242            &self.write.orientations,
243            &self.write.physics_states,
244            &mut self.write.previous_phys_cache,
245            &self.read.colliders,
246            self.read.scales.maybe(),
247            self.read.character_states.maybe(),
248        )
249            .join()
250        {
251            let scale = scale.map(|s| s.0).unwrap_or(1.0);
252            let z_limits = calc_z_limit(cs, collider);
253            let (z_min, z_max) = z_limits;
254            let (z_min, z_max) = (z_min * scale, z_max * scale);
255            let half_height = (z_max - z_min) / 2.0;
256
257            phys_cache.velocity_dt = vel.0 * self.read.dt.0;
258            phys_cache.velocity = vel.0;
259            phys_cache.in_fluid = phys_state.in_fluid;
260            let entity_center = position.0 + Vec3::new(0.0, 0.0, z_min + half_height);
261            let flat_radius = collider.bounding_radius() * scale;
262            let radius = (flat_radius.powi(2) + half_height.powi(2)).sqrt();
263
264            // Move center to the middle between OLD and OLD+VEL_DT
265            // so that we can reduce the collision_boundary.
266            phys_cache.center = entity_center + phys_cache.velocity_dt / 2.0;
267            phys_cache.collision_boundary = radius + (phys_cache.velocity_dt / 2.0).magnitude();
268            phys_cache.scale = scale;
269            phys_cache.scaled_radius = flat_radius;
270
271            let neighborhood_radius = match collider {
272                Collider::CapsulePrism { radius, .. } => radius * scale,
273                Collider::Voxel { .. } | Collider::Volume(_) | Collider::Point => flat_radius,
274            };
275            phys_cache.neighborhood_radius = neighborhood_radius;
276
277            let ori = ori.to_quat();
278            let origins = match collider {
279                Collider::CapsulePrism { p0, p1, .. } => {
280                    let a = p1 - p0;
281                    let len = a.magnitude();
282                    // If origins are close enough, our capsule prism is cylinder
283                    // with one origin which we don't even need to rotate.
284                    //
285                    // Other advantage of early-return is that we don't
286                    // later divide by zero and return NaN
287                    if len < f32::EPSILON * 10.0 {
288                        Some((*p0, *p0))
289                    } else {
290                        // Apply orientation to origins of prism.
291                        //
292                        // We do this by building line between them,
293                        // rotate it and then split back to origins.
294                        // (Otherwise we will need to do the same with each
295                        // origin).
296                        //
297                        // Cast it to 3d and then convert it back to 2d
298                        // to apply quaternion.
299                        let a = a.with_z(0.0);
300                        let a = ori * a;
301                        let a = a.xy();
302                        // Previous operation could shrink x and y coordinates
303                        // if orientation had Z parameter.
304                        // Make sure we have the same length as before
305                        // (and scale it, while we on it).
306                        let a = a.normalized() * scale * len;
307                        let p0 = -a / 2.0;
308                        let p1 = a / 2.0;
309
310                        Some((p0, p1))
311                    }
312                },
313                Collider::Voxel { .. } | Collider::Volume(_) | Collider::Point => None,
314            };
315            phys_cache.origins = origins;
316        }
317    }
318
319    fn construct_spatial_grid(&mut self) -> SpatialGrid {
320        span!(_guard, "Construct spatial grid");
321        let &mut PhysicsData {
322            ref read,
323            ref write,
324        } = self;
325        // NOTE: i32 places certain constraints on how far out collision works
326        // NOTE: uses the radius of the entity and their current position rather than
327        // the radius of their bounding sphere for the current frame of movement
328        // because the nonmoving entity is what is collided against in the inner
329        // loop of the pushback collision code
330        // TODO: maintain frame to frame? (requires handling deletion)
331        // TODO: if not maintaining frame to frame consider counting entities to
332        // preallocate?
333        // TODO: assess parallelizing (overhead might dominate here? would need to merge
334        // the vecs in each hashmap)
335        let lg2_cell_size = 5;
336        let lg2_large_cell_size = 6;
337        let radius_cutoff = 8;
338        let mut spatial_grid = SpatialGrid::new(lg2_cell_size, lg2_large_cell_size, radius_cutoff);
339        for (entity, pos, phys_cache, _, _) in (
340            &read.entities,
341            &write.positions,
342            &write.previous_phys_cache,
343            write.velocities.mask(),
344            !&read.projectiles, // Not needed because they are skipped in the inner loop below
345        )
346            .join()
347        {
348            // Note: to not get too fine grained we use a 2D grid for now
349            let radius_2d = phys_cache.scaled_radius.ceil() as u32;
350            let pos_2d = pos.0.xy().map(|e| e as i32);
351            const POS_TRUNCATION_ERROR: u32 = 1;
352            spatial_grid.insert(pos_2d, radius_2d + POS_TRUNCATION_ERROR, entity);
353        }
354
355        spatial_grid
356    }
357
358    fn apply_pushback(&mut self, job: &mut Job<Sys>, spatial_grid: &SpatialGrid) {
359        span!(_guard, "Apply pushback");
360        job.cpu_stats.measure(ParMode::Rayon);
361        let &mut PhysicsData {
362            ref read,
363            ref mut write,
364        } = self;
365        let (positions, previous_phys_cache) = (&write.positions, &write.previous_phys_cache);
366        let metrics = (
367            &read.entities,
368            positions,
369            &mut write.velocities,
370            previous_phys_cache,
371            &read.masses,
372            &read.colliders,
373            read.is_riders.maybe(),
374            read.is_volume_riders.maybe(),
375            read.stickies.maybe(),
376            read.immovables.maybe(),
377            &mut write.physics_states,
378            // TODO: if we need to avoid collisions for other things consider
379            // moving whether it should interact into the collider component
380            // or into a separate component.
381            read.projectiles.maybe(),
382            read.character_states.maybe(),
383        )
384            .par_join()
385            .map_init(
386                || {
387                    prof_span!(guard, "physics e<>e rayon job");
388                    guard
389                },
390                |_guard,
391                 (
392                    entity,
393                    pos,
394                    vel,
395                    previous_cache,
396                    mass,
397                    collider,
398                    is_rider,
399                    is_volume_rider,
400                    sticky,
401                    immovable,
402                    physics,
403                    projectile,
404                    char_state_maybe,
405                )| {
406                    let is_sticky = sticky.is_some();
407                    let is_immovable = immovable.is_some();
408                    let is_mid_air = physics.on_surface().is_none();
409                    let mut entity_entity_collision_checks = 0;
410                    let mut entity_entity_collisions = 0;
411
412                    // TODO: quick fix for bad performance. At extrememly high
413                    // velocities use oriented rectangles at some threshold of
414                    // displacement/radius to query the spatial grid and limit
415                    // max displacement per tick somehow.
416                    if previous_cache.collision_boundary > 128.0 {
417                        return PhysicsMetrics {
418                            entity_entity_collision_checks,
419                            entity_entity_collisions,
420                        };
421                    }
422
423                    let z_limits = calc_z_limit(char_state_maybe, collider);
424
425                    // Resets touch_entities in physics
426                    physics.touch_entities.clear();
427
428                    let is_projectile = projectile.is_some();
429
430                    let mut vel_delta = Vec3::zero();
431
432                    let query_center = previous_cache.center.xy();
433                    let query_radius = previous_cache.collision_boundary;
434
435                    spatial_grid
436                        .in_circle_aabr(query_center, query_radius)
437                        .filter_map(|entity| {
438                            let uid = read.uids.get(entity)?;
439                            let pos = positions.get(entity)?;
440                            let previous_cache = previous_phys_cache.get(entity)?;
441                            let mass = read.masses.get(entity)?;
442                            let collider = read.colliders.get(entity)?;
443
444                            Some((
445                                entity,
446                                uid,
447                                pos,
448                                previous_cache,
449                                mass,
450                                collider,
451                                read.character_states.get(entity),
452                                read.is_riders.get(entity),
453                            ))
454                        })
455                        .for_each(
456                            |(
457                                entity_other,
458                                other,
459                                pos_other,
460                                previous_cache_other,
461                                mass_other,
462                                collider_other,
463                                char_state_other_maybe,
464                                other_is_rider_maybe,
465                            )| {
466                                let collision_boundary = previous_cache.collision_boundary
467                                    + previous_cache_other.collision_boundary;
468                                if previous_cache
469                                    .center
470                                    .distance_squared(previous_cache_other.center)
471                                    > collision_boundary.powi(2)
472                                    || entity == entity_other
473                                {
474                                    return;
475                                }
476
477                                let z_limits_other =
478                                    calc_z_limit(char_state_other_maybe, collider_other);
479
480                                entity_entity_collision_checks += 1;
481
482                                const MIN_COLLISION_DIST: f32 = 0.3;
483
484                                let increments = ((previous_cache.velocity_dt
485                                    - previous_cache_other.velocity_dt)
486                                    .magnitude()
487                                    / MIN_COLLISION_DIST)
488                                    .max(1.0)
489                                    .ceil()
490                                    as usize;
491                                let step_delta = 1.0 / increments as f32;
492
493                                let mut collision_registered = false;
494
495                                for i in 0..increments {
496                                    let factor = i as f32 * step_delta;
497                                    // We are not interested if collision succeed
498                                    // or no as of now.
499                                    // Collision reaction is done inside.
500                                    let _ = collision::resolve_e2e_collision(
501                                        // utility variables for our entity
502                                        &mut collision_registered,
503                                        &mut entity_entity_collisions,
504                                        factor,
505                                        physics,
506                                        char_state_maybe,
507                                        &mut vel_delta,
508                                        step_delta,
509                                        // physics flags
510                                        is_mid_air,
511                                        is_sticky,
512                                        is_immovable,
513                                        is_projectile,
514                                        // entity we colliding with
515                                        *other,
516                                        // symetrical collider context
517                                        ColliderData {
518                                            pos,
519                                            previous_cache,
520                                            z_limits,
521                                            collider,
522                                            mass: *mass,
523                                        },
524                                        ColliderData {
525                                            pos: pos_other,
526                                            previous_cache: previous_cache_other,
527                                            z_limits: z_limits_other,
528                                            collider: collider_other,
529                                            mass: *mass_other,
530                                        },
531                                        vel,
532                                        is_rider.is_some()
533                                            || is_volume_rider.is_some()
534                                            || other_is_rider_maybe.is_some(),
535                                    );
536                                }
537                            },
538                        );
539
540                    // Change velocity
541                    vel.0 += vel_delta * read.dt.0;
542
543                    // Metrics
544                    PhysicsMetrics {
545                        entity_entity_collision_checks,
546                        entity_entity_collisions,
547                    }
548                },
549            )
550            .reduce(PhysicsMetrics::default, |old, new| PhysicsMetrics {
551                entity_entity_collision_checks: old.entity_entity_collision_checks
552                    + new.entity_entity_collision_checks,
553                entity_entity_collisions: old.entity_entity_collisions
554                    + new.entity_entity_collisions,
555            });
556        write.physics_metrics.entity_entity_collision_checks =
557            metrics.entity_entity_collision_checks;
558        write.physics_metrics.entity_entity_collisions = metrics.entity_entity_collisions;
559    }
560
561    fn construct_voxel_collider_spatial_grid(&mut self) -> SpatialGrid {
562        span!(_guard, "Construct voxel collider spatial grid");
563        let &mut PhysicsData {
564            ref read,
565            ref write,
566        } = self;
567
568        let voxel_colliders_manifest = VOXEL_COLLIDER_MANIFEST.read();
569
570        // NOTE: i32 places certain constraints on how far out collision works
571        // NOTE: uses the radius of the entity and their current position rather than
572        // the radius of their bounding sphere for the current frame of movement
573        // because the nonmoving entity is what is collided against in the inner
574        // loop of the pushback collision code
575        // TODO: optimize these parameters (especially radius cutoff)
576        let lg2_cell_size = 7; // 128
577        let lg2_large_cell_size = 8; // 256
578        let radius_cutoff = 64;
579        let mut spatial_grid = SpatialGrid::new(lg2_cell_size, lg2_large_cell_size, radius_cutoff);
580        // TODO: give voxel colliders their own component type
581        for (entity, pos, collider, scale, ori) in (
582            &read.entities,
583            &write.positions,
584            &read.colliders,
585            read.scales.maybe(),
586            &write.orientations,
587        )
588            .join()
589        {
590            let vol = collider.get_vol(&voxel_colliders_manifest);
591
592            if let Some(vol) = vol {
593                let sphere = collision::voxel_collider_bounding_sphere(vol, pos, ori, scale);
594                let radius = sphere.radius.ceil() as u32;
595                let pos_2d = sphere.center.xy().map(|e| e as i32);
596                const POS_TRUNCATION_ERROR: u32 = 1;
597                spatial_grid.insert(pos_2d, radius + POS_TRUNCATION_ERROR, entity);
598            }
599        }
600
601        spatial_grid
602    }
603
604    fn handle_movement_and_terrain(
605        &mut self,
606        job: &mut Job<Sys>,
607        voxel_collider_spatial_grid: &SpatialGrid,
608    ) {
609        let &mut PhysicsData {
610            ref read,
611            ref mut write,
612        } = self;
613
614        prof_span!(guard, "Apply Weather");
615        if let Some(weather) = &read.weather {
616            for (_, state, pos, phys) in (
617                &read.entities,
618                &read.character_states,
619                &write.positions,
620                &mut write.physics_states,
621            )
622                .join()
623            {
624                // Always reset air_vel to zero
625                let mut air_vel = Vec3::zero();
626
627                'simulation: {
628                    // Don't simulate for non-gliding, for now
629                    if !state.is_glide() {
630                        break 'simulation;
631                    }
632
633                    let pos_2d = pos.0.as_().xy();
634                    let chunk_pos: Vec2<i32> = pos_2d.wpos_to_cpos();
635                    let Some(current_chunk) = &read.terrain.get_key(chunk_pos) else {
636                        // oopsie
637                        break 'simulation;
638                    };
639
640                    let meta = current_chunk.meta();
641
642                    // Skip simulating for entites deeply under the ground
643                    if pos.0.z < meta.alt() - 25.0 {
644                        break 'simulation;
645                    }
646
647                    // If couldn't simulate wind for some reason, skip
648                    if let Ok(simulated_vel) =
649                        weather::simulated_wind_vel(pos, weather, &read.terrain, &read.time_of_day)
650                    {
651                        air_vel = simulated_vel
652                    };
653                }
654
655                phys.in_fluid = phys.in_fluid.map(|f| match f {
656                    Fluid::Air { elevation, .. } => Fluid::Air {
657                        vel: Vel(air_vel),
658                        elevation,
659                    },
660                    fluid => fluid,
661                });
662            }
663        }
664
665        drop(guard);
666
667        prof_span!(guard, "insert PosVelOriDefer");
668        // NOTE: keep in sync with join below
669        (
670            &read.entities,
671            read.colliders.mask(),
672            &write.positions,
673            &write.velocities,
674            &write.orientations,
675            write.orientations.mask(),
676            write.physics_states.mask(),
677            !&write.pos_vel_ori_defers, // This is the one we are adding
678            write.previous_phys_cache.mask(),
679            !&read.is_riders,
680            !&read.is_volume_riders,
681        )
682            .join()
683            .map(|t| (t.0, *t.2, *t.3, *t.4))
684            .collect::<Vec<_>>()
685            .into_iter()
686            .for_each(|(entity, pos, vel, ori)| {
687                let _ = write.pos_vel_ori_defers.insert(entity, PosVelOriDefer {
688                    pos: Some(pos),
689                    vel: Some(vel),
690                    ori: Some(ori),
691                });
692            });
693        drop(guard);
694
695        // Apply movement inputs
696        span!(guard, "Apply movement");
697        let (positions, velocities) = (&write.positions, &mut write.velocities);
698
699        // First pass: update velocity using air resistance and gravity for each entity.
700        // We do this in a first pass because it helps keep things more stable for
701        // entities that are anchored to other entities (such as airships).
702        (
703            positions,
704            velocities,
705            read.stickies.maybe(),
706            &read.bodies,
707            read.character_states.maybe(),
708            &write.physics_states,
709            &read.masses,
710            &read.densities,
711            read.scales.maybe(),
712            !&read.is_riders,
713            !&read.is_volume_riders,
714        )
715            .par_join()
716            .for_each_init(
717                || {
718                    prof_span!(guard, "velocity update rayon job");
719                    guard
720                },
721                |_guard,
722                 (
723                    pos,
724                    vel,
725                    sticky,
726                    body,
727                    character_state,
728                    physics_state,
729                    mass,
730                    density,
731                    scale,
732                    _,
733                    _,
734                )| {
735                    let in_loaded_chunk = read
736                        .terrain
737                        .contains_key(read.terrain.pos_key(pos.0.map(|e| e.floor() as i32)));
738
739                    // Apply physics only if in a loaded chunk
740                    if in_loaded_chunk
741                    // And not already stuck on a block (e.g., for arrows)
742                    && !(physics_state.on_surface().is_some() && sticky.is_some())
743                    // HACK: Special-case boats. Experimentally, clients are *bad* at making guesses about movement,
744                    // and this is a particular problem for volume entities since careful control of velocity is
745                    // required for nice movement of entities on top of the volume. Special-case volume entities here
746                    // to prevent weird drag/gravity guesses messing with movement, relying on the client's hermite
747                    // interpolation instead.
748                    && !(matches!(body, Body::Ship(_)) && matches!(&*read.game_mode, GameMode::Client))
749                    {
750                        // Clamp dt to an effective 10 TPS, to prevent gravity
751                        // from slamming the players into the floor when
752                        // stationary if other systems cause the server
753                        // to lag (as observed in the 0.9 release party).
754                        let dt = DeltaTime(read.dt.0.min(0.1));
755
756                        match physics_state.in_fluid {
757                            None => {
758                                vel.0.z -= dt.0 * GRAVITY;
759                            },
760                            Some(fluid) => {
761                                let wings = match character_state {
762                                    Some(&CharacterState::Glide(states::glide::Data {
763                                        aspect_ratio,
764                                        planform_area,
765                                        ori,
766                                        ..
767                                    })) => Some(Wings {
768                                        aspect_ratio,
769                                        planform_area,
770                                        ori,
771                                    }),
772
773                                    _ => None,
774                                };
775                                vel.0 = integrate_forces(
776                                    &dt,
777                                    *vel,
778                                    (body, wings.as_ref()),
779                                    density,
780                                    mass,
781                                    &fluid,
782                                    GRAVITY,
783                                    scale.copied(),
784                                )
785                                .0
786                            },
787                        }
788                    }
789                },
790            );
791        drop(guard);
792        job.cpu_stats.measure(ParMode::Single);
793
794        // Second pass: resolve collisions for terrain-like entities, this is required
795        // in order to update their positions before resolving collisions for
796        // non-terrain-like entities, since otherwise, collision is resolved
797        // based on where the terrain-like entity was in the previous frame.
798        Self::resolve_et_collision(job, read, write, voxel_collider_spatial_grid, true);
799
800        // Third pass: resolve collisions for non-terrain-like entities
801        Self::resolve_et_collision(job, read, write, voxel_collider_spatial_grid, false);
802
803        // Update cached 'old' physics values to the current values ready for the next
804        // tick
805        prof_span!(guard, "record ori into phys_cache");
806        for (pos, ori, previous_phys_cache) in (
807            &write.positions,
808            &write.orientations,
809            &mut write.previous_phys_cache,
810        )
811            .join()
812        {
813            // Note: updating ori with the rest of the cache values above was attempted but
814            // it did not work (investigate root cause?)
815            previous_phys_cache.pos = Some(*pos);
816            previous_phys_cache.ori = ori.to_quat();
817        }
818        drop(guard);
819    }
820
821    fn resolve_et_collision(
822        job: &mut Job<Sys>,
823        read: &PhysicsRead,
824        write: &mut PhysicsWrite,
825        voxel_collider_spatial_grid: &SpatialGrid,
826        terrain_like_entities: bool,
827    ) {
828        let (positions, velocities, previous_phys_cache, orientations) = (
829            &write.positions,
830            &write.velocities,
831            &write.previous_phys_cache,
832            &write.orientations,
833        );
834        span!(guard, "Apply terrain collision");
835        job.cpu_stats.measure(ParMode::Rayon);
836        let (land_on_grounds, outcomes) = (
837            &read.entities,
838            read.scales.maybe(),
839            read.stickies.maybe(),
840            &read.colliders,
841            positions,
842            velocities,
843            orientations,
844            read.bodies.maybe(),
845            read.character_states.maybe(),
846            &mut write.physics_states,
847            &mut write.pos_vel_ori_defers,
848            previous_phys_cache,
849            !&read.is_riders,
850            !&read.is_volume_riders,
851        )
852            .par_join()
853            .filter(|tuple| tuple.3.is_voxel() == terrain_like_entities)
854            .map_init(
855                || {
856                    prof_span!(guard, "physics e<>t rayon job");
857                    guard
858                },
859                |_guard,
860                 (
861                    entity,
862                    scale,
863                    sticky,
864                    collider,
865                    pos,
866                    vel,
867                    ori,
868                    body,
869                    character_state,
870                    physics_state,
871                    pos_vel_ori_defer,
872                    previous_cache,
873                    _,
874                    _,
875                )| {
876                    let mut land_on_ground = None;
877                    let mut outcomes = Vec::new();
878                    // Defer the writes of positions, velocities and orientations
879                    // to allow an inner loop over terrain-like entities.
880                    let old_vel = *vel;
881                    let mut vel = *vel;
882                    let old_ori = *ori;
883                    let mut ori = *ori;
884
885                    let scale = if collider.is_voxel() {
886                        scale.map(|s| s.0).unwrap_or(1.0)
887                    } else {
888                        // TODO: Use scale & actual proportions when pathfinding is good
889                        // enough to manage irregular entity sizes
890                        1.0
891                    };
892
893                    if let Some(state) = character_state {
894                        let footwear = state.footwear().unwrap_or(Friction::Normal);
895                        if footwear != physics_state.footwear {
896                            physics_state.footwear = footwear;
897                        }
898                    }
899
900                    let in_loaded_chunk = read
901                        .terrain
902                        .contains_key(read.terrain.pos_key(pos.0.map(|e| e.floor() as i32)));
903
904                    // Don't move if we're not in a loaded chunk
905                    let pos_delta = if in_loaded_chunk {
906                        vel.0 * read.dt.0
907                    } else {
908                        Vec3::zero()
909                    };
910
911                    let mut tgt_pos = pos.0 + pos_delta;
912
913                    // What's going on here?
914                    // Because collisions need to be resolved against multiple
915                    // colliders, this code takes the current position and
916                    // propagates it forward according to velocity to find a
917                    // 'target' position.
918                    //
919                    // This is where we'd ideally end up at the end of the tick,
920                    // assuming no collisions. Then, we refine this target by
921                    // stepping from the original position to the target for
922                    // every obstacle, refining the target position as we go.
923                    //
924                    // It's not perfect, but it works pretty well in practice.
925                    // Oddities can occur on the intersection between multiple
926                    // colliders, but it's not like any game physics system
927                    // resolves these sort of things well anyway.
928                    // At the very least, we don't do things that result in glitchy
929                    // velocities or entirely broken position snapping.
930
931                    let was_on_ground = physics_state.on_ground.is_some();
932                    let block_snap =
933                        body.is_some_and(|b| !matches!(b, Body::Object(_) | Body::Ship(_)));
934                    let climbing =
935                        character_state.is_some_and(|cs| matches!(cs, CharacterState::Climb(_)));
936
937                    let friction_factor = |vel: Vec3<f32>| {
938                        if let Some(Body::Ship(ship)) = body
939                            && ship.has_wheels()
940                        {
941                            vel.try_normalized()
942                                .and_then(|dir| {
943                                    Some(orientations.get(entity)?.right().dot(dir).abs())
944                                })
945                                .unwrap_or(1.0)
946                                .max(0.2)
947                        } else {
948                            1.0
949                        }
950                    };
951
952                    // Snap trains to the closest track, skipping other collision code
953                    if matches!(body, Some(Body::Ship(ship::Body::Train)))
954                        // Get the 9 closest chunks...
955                        && let chunks = Spiral2d::new().take(9).filter_map(|r| read.terrain.get_key(tgt_pos.xy().as_().wpos_to_cpos() + r))
956                        // ...and each track in those chunks.
957                        && let tracks = chunks.flat_map(|c| c.meta().tracks().iter())
958                        // Find the closest point on the closest track
959                        && let Some(line) = tracks
960                            .flat_map(|bez| (0..32).map(move |i| LineSegment3 {
961                                start: bez.evaluate(i as f32 / 32.0),
962                                end: bez.evaluate((i + 1) as f32 / 32.0),
963                            }))
964                            .min_by_key(|line| (line.distance_to_point(tgt_pos) * 1000.0) as i32)
965                    {
966                        let track_dir = (line.end - line.start).normalized();
967                        let track_closest = line.projected_point(tgt_pos);
968
969                        // vel.0 = track_dir * vel.0.dot(track_dir); // Clamp velocity to direction of rail
970                        vel.0 += (track_closest - tgt_pos) / read.dt.0.max(0.001); // Correct velocity according to position update
971                        // Clamp position to track
972                        tgt_pos = track_closest;
973
974                        // Apply friction
975                        let fric = 0.0025f32;
976                        vel.0 *= (1.0 - fric).powf(read.dt.0 * 60.0);
977
978                        use common::terrain::{Block, BlockKind};
979                        // Fake the train being sat on the ground
980                        physics_state.on_ground = Some(Block::new(BlockKind::Rock, Rgb::zero()));
981                        physics_state.in_fluid = Some(Fluid::Air {
982                            elevation: tgt_pos.z,
983                            vel: Vel::default(),
984                        });
985
986                        let train_dir = if ori.look_vec().dot(track_dir) > 0.0 {
987                            Dir::new(track_dir)
988                        } else {
989                            Dir::new(-track_dir)
990                        };
991                        let tgt_ori = ori
992                            .yawed_towards(train_dir)
993                            .pitched_towards(train_dir)
994                            .uprighted();
995                        ori = ori.slerped_towards(tgt_ori, (1.0 - ori.angle_between(tgt_ori) * 25.0).clamp(0.15, 0.5));
996                    } else {
997                        match &collider {
998                            Collider::Voxel { .. } | Collider::Volume(_) => {
999                                // For now, treat entities with voxel colliders
1000                                // as their bounding cylinders for the purposes of
1001                                // colliding them with terrain.
1002                                //
1003                                // Additionally, multiply radius by 0.1 to make
1004                                // the cylinder smaller to avoid lag.
1005                                let radius = collider.bounding_radius() * scale * 0.1;
1006                                let (_, z_max) = collider.get_z_limits(scale);
1007                                let z_min = 0.0;
1008
1009                                let mut cpos = *pos;
1010                                let cylinder = (radius, z_min, z_max);
1011                                collision::box_voxel_collision(
1012                                    cylinder,
1013                                    &*read.terrain,
1014                                    entity,
1015                                    &mut cpos,
1016                                    tgt_pos,
1017                                    &mut vel,
1018                                    physics_state,
1019                                    &read.dt,
1020                                    was_on_ground,
1021                                    block_snap,
1022                                    climbing,
1023                                    |entity, vel, surface_normal| {
1024                                        land_on_ground = Some((entity, vel, surface_normal))
1025                                    },
1026                                    read,
1027                                    &ori,
1028                                    friction_factor,
1029                                );
1030                                tgt_pos = cpos.0;
1031                            },
1032                            Collider::CapsulePrism {
1033                                z_min: _,
1034                                z_max,
1035                                p0: _,
1036                                p1: _,
1037                                radius: _,
1038                            } => {
1039                                // Scale collider
1040                                let radius = collider.bounding_radius().min(0.45) * scale;
1041                                let z_min = 0.0;
1042                                let z_max = z_max.clamped(1.2, 1.95) * scale;
1043
1044                                let cylinder = (radius, z_min, z_max);
1045                                let mut cpos = *pos;
1046                                collision::box_voxel_collision(
1047                                    cylinder,
1048                                    &*read.terrain,
1049                                    entity,
1050                                    &mut cpos,
1051                                    tgt_pos,
1052                                    &mut vel,
1053                                    physics_state,
1054                                    &read.dt,
1055                                    was_on_ground,
1056                                    block_snap,
1057                                    climbing,
1058                                    |entity, vel, surface_normal| {
1059                                        land_on_ground = Some((entity, vel, surface_normal))
1060                                    },
1061                                    read,
1062                                    &ori,
1063                                    friction_factor,
1064                                );
1065
1066                                // Sticky things shouldn't move when on a surface
1067                                if physics_state.on_surface().is_some() && sticky.is_some() {
1068                                    vel.0 = physics_state.ground_vel;
1069                                }
1070
1071                                tgt_pos = cpos.0;
1072                            },
1073                            Collider::Point => {
1074                                let mut pos = *pos;
1075
1076                                collision::point_voxel_collision(
1077                                    entity,
1078                                    &mut pos,
1079                                    pos_delta,
1080                                    &mut vel,
1081                                    physics_state,
1082                                    sticky.is_some(),
1083                                    &mut outcomes,
1084                                    read,
1085                                );
1086
1087                                tgt_pos = pos.0;
1088                            },
1089                        }
1090                    }
1091
1092                    // Compute center and radius of tick path bounding sphere
1093                    // for the entity for broad checks of whether it will
1094                    // collide with a voxel collider
1095                    let path_sphere = {
1096                        // TODO: duplicated with maintain_pushback_cache,
1097                        // make a common function to call to compute all this info?
1098                        let z_limits = calc_z_limit(character_state, collider);
1099                        let z_limits = (z_limits.0 * scale, z_limits.1 * scale);
1100                        let half_height = (z_limits.1 - z_limits.0) / 2.0;
1101
1102                        let entity_center = pos.0 + (z_limits.0 + half_height) * Vec3::unit_z();
1103                        let path_center = entity_center + pos_delta / 2.0;
1104
1105                        let flat_radius = collider.bounding_radius() * scale;
1106                        let radius = (flat_radius.powi(2) + half_height.powi(2)).sqrt();
1107                        let path_bounding_radius = radius + (pos_delta / 2.0).magnitude();
1108
1109                        Sphere {
1110                            center: path_center,
1111                            radius: path_bounding_radius,
1112                        }
1113                    };
1114                    // Collide with terrain-like entities
1115                    let query_center = path_sphere.center.xy();
1116                    let query_radius = path_sphere.radius;
1117
1118                    let voxel_colliders_manifest = VOXEL_COLLIDER_MANIFEST.read();
1119
1120                    voxel_collider_spatial_grid
1121                        .in_circle_aabr(query_center, query_radius)
1122                        .filter_map(|entity| {
1123                            positions.get(entity).and_then(|pos| {
1124                                Some((
1125                                    entity,
1126                                    pos,
1127                                    velocities.get(entity)?,
1128                                    previous_phys_cache.get(entity)?,
1129                                    read.colliders.get(entity)?,
1130                                    read.scales.get(entity),
1131                                    orientations.get(entity)?,
1132                                ))
1133                            })
1134                        })
1135                        .for_each(
1136                            |(
1137                                entity_other,
1138                                pos_other,
1139                                vel_other,
1140                                previous_cache_other,
1141                                collider_other,
1142                                scale_other,
1143                                ori_other,
1144                            )| {
1145                                if entity == entity_other {
1146                                    return;
1147                                }
1148
1149                                let voxel_collider =
1150                                    collider_other.get_vol(&voxel_colliders_manifest);
1151
1152                                // use bounding cylinder regardless of our collider
1153                                // TODO: extract point-terrain collision above to its own
1154                                // function
1155                                let radius = collider.bounding_radius();
1156                                let (_, z_max) = collider.get_z_limits(1.0);
1157
1158                                let radius = radius.min(0.45) * scale;
1159                                let z_min = 0.0;
1160                                let z_max = z_max.clamped(1.2, 1.95) * scale;
1161
1162                                if let Some(voxel_collider) = voxel_collider {
1163                                    // TODO: cache/precompute sphere?
1164                                    let voxel_sphere = collision::voxel_collider_bounding_sphere(
1165                                        voxel_collider,
1166                                        pos_other,
1167                                        ori_other,
1168                                        scale_other,
1169                                    );
1170                                    // Early check
1171                                    if voxel_sphere.center.distance_squared(path_sphere.center)
1172                                        > (voxel_sphere.radius + path_sphere.radius).powi(2)
1173                                    {
1174                                        return;
1175                                    }
1176
1177                                    let mut physics_state_delta = PhysicsState::default();
1178
1179                                    // Helper function for computing a transformation matrix and its
1180                                    // inverse. Should
1181                                    // be much cheaper than using `Mat4::inverted`.
1182                                    let from_to_matricies =
1183                                        |entity_rpos: Vec3<f32>, collider_ori: Quaternion<f32>| {
1184                                            (
1185                                                Mat4::<f32>::translation_3d(entity_rpos)
1186                                                    * Mat4::from(collider_ori)
1187                                                    * Mat4::scaling_3d(previous_cache_other.scale)
1188                                                    * Mat4::translation_3d(
1189                                                        voxel_collider.translation,
1190                                                    ),
1191                                                Mat4::<f32>::translation_3d(
1192                                                    -voxel_collider.translation,
1193                                                ) * Mat4::scaling_3d(
1194                                                    1.0 / previous_cache_other.scale,
1195                                                ) * Mat4::from(collider_ori.inverse())
1196                                                    * Mat4::translation_3d(-entity_rpos),
1197                                            )
1198                                        };
1199
1200                                    // Compute matrices that allow us to transform to and from the
1201                                    // coordinate space of
1202                                    // the collider. We have two variants of each, one for the
1203                                    // current state and one for
1204                                    // the previous state. This allows us to 'perfectly' track
1205                                    // change in position
1206                                    // between ticks, which prevents entities falling through voxel
1207                                    // colliders due to spurious
1208                                    // issues like differences in ping/variable dt.
1209                                    // TODO: Cache the matrices here to avoid recomputing for each
1210                                    // entity on them
1211                                    let (_transform_last_from, transform_last_to) =
1212                                        from_to_matricies(
1213                                            previous_cache_other.pos.unwrap_or(*pos_other).0
1214                                                - previous_cache.pos.unwrap_or(*pos).0,
1215                                            previous_cache_other.ori,
1216                                        );
1217                                    let (transform_from, transform_to) =
1218                                        from_to_matricies(pos_other.0 - pos.0, ori_other.to_quat());
1219
1220                                    // Compute the velocity of the collider, accounting for changes
1221                                    // in orientation
1222                                    // from the last tick. We then model this change as a change in
1223                                    // surface velocity
1224                                    // for the collider.
1225                                    let vel_other = {
1226                                        let pos_rel =
1227                                            (Mat4::<f32>::translation_3d(
1228                                                -voxel_collider.translation,
1229                                            ) * Mat4::from(ori_other.to_quat().inverse()))
1230                                            .mul_point(pos.0 - pos_other.0);
1231                                        let rpos_last =
1232                                            (Mat4::<f32>::from(previous_cache_other.ori)
1233                                                * Mat4::translation_3d(voxel_collider.translation))
1234                                            .mul_point(pos_rel);
1235                                        vel_other.0
1236                                            + (pos.0 - (pos_other.0 + rpos_last)) / read.dt.0
1237                                    };
1238
1239                                    {
1240                                        // Transform the entity attributes into the coordinate space
1241                                        // of the collider ready
1242                                        // for collision resolution
1243                                        let mut rpos =
1244                                            Pos(transform_last_to.mul_point(Vec3::zero()));
1245                                        vel.0 = previous_cache_other.ori.inverse()
1246                                            * (vel.0 - vel_other);
1247
1248                                        // Perform collision resolution
1249                                        collision::box_voxel_collision(
1250                                            (radius, z_min, z_max),
1251                                            &voxel_collider.volume(),
1252                                            entity,
1253                                            &mut rpos,
1254                                            transform_to.mul_point(tgt_pos - pos.0),
1255                                            &mut vel,
1256                                            &mut physics_state_delta,
1257                                            &read.dt,
1258                                            was_on_ground,
1259                                            block_snap,
1260                                            climbing,
1261                                            |entity, vel, surface_normal| {
1262                                                land_on_ground = Some((
1263                                                    entity,
1264                                                    Vel(previous_cache_other.ori * vel.0
1265                                                        + vel_other),
1266                                                    previous_cache_other.ori * surface_normal,
1267                                                ));
1268                                            },
1269                                            read,
1270                                            &ori,
1271                                            |vel| friction_factor(previous_cache_other.ori * vel),
1272                                        );
1273
1274                                        // Transform entity attributes back into world space now
1275                                        // that we've performed
1276                                        // collision resolution with them
1277                                        tgt_pos = transform_from.mul_point(rpos.0) + pos.0;
1278                                        vel.0 = previous_cache_other.ori * vel.0 + vel_other;
1279                                    }
1280
1281                                    // Collision resolution may also change the physics state. Since
1282                                    // we may be interacting
1283                                    // with multiple colliders at once (along with the regular
1284                                    // terrain!) we keep track
1285                                    // of a physics state 'delta' and try to sensibly resolve them
1286                                    // against one-another at each step.
1287                                    if physics_state_delta.on_ground.is_some() {
1288                                        // TODO: Do we need to do this? Perhaps just take the
1289                                        // ground_vel regardless?
1290                                        physics_state.ground_vel = previous_cache_other.ori
1291                                            * physics_state_delta.ground_vel
1292                                            + vel_other;
1293                                    }
1294                                    if physics_state_delta.on_surface().is_some() {
1295                                        // If the collision resulted in us being on a surface,
1296                                        // rotate us with the
1297                                        // collider. Really this should be modelled via friction or
1298                                        // something, but
1299                                        // our physics model doesn't really take orientation into
1300                                        // consideration.
1301                                        ori = ori.rotated(
1302                                            ori_other.to_quat()
1303                                                * previous_cache_other.ori.inverse(),
1304                                        );
1305                                    }
1306                                    physics_state.on_ground =
1307                                        physics_state.on_ground.or(physics_state_delta.on_ground);
1308                                    physics_state.on_ceiling |= physics_state_delta.on_ceiling;
1309                                    physics_state.on_wall = physics_state.on_wall.or_else(|| {
1310                                        physics_state_delta
1311                                            .on_wall
1312                                            .map(|dir| previous_cache_other.ori * dir)
1313                                    });
1314                                    physics_state.in_fluid = match (
1315                                        physics_state.in_fluid,
1316                                        physics_state_delta.in_fluid,
1317                                    ) {
1318                                        (Some(x), Some(y)) => x
1319                                            .depth()
1320                                            .and_then(|xh| {
1321                                                y.depth()
1322                                                    .map(|yh| xh > yh)
1323                                                    .unwrap_or(true)
1324                                                    .then_some(x)
1325                                            })
1326                                            .or(Some(y)),
1327                                        (x @ Some(_), _) => x,
1328                                        (_, y @ Some(_)) => y,
1329                                        _ => None,
1330                                    };
1331                                }
1332                            },
1333                        );
1334
1335                    if tgt_pos != pos.0 {
1336                        pos_vel_ori_defer.pos = Some(Pos(tgt_pos));
1337                    } else {
1338                        pos_vel_ori_defer.pos = None;
1339                    }
1340                    if vel != old_vel {
1341                        pos_vel_ori_defer.vel = Some(vel);
1342                    } else {
1343                        pos_vel_ori_defer.vel = None;
1344                    }
1345                    if ori != old_ori {
1346                        pos_vel_ori_defer.ori = Some(ori);
1347                    } else {
1348                        pos_vel_ori_defer.ori = None;
1349                    }
1350
1351                    (land_on_ground, outcomes)
1352                },
1353            )
1354            .fold(
1355                || (Vec::new(), Vec::new()),
1356                |(mut land_on_grounds, mut all_outcomes), (land_on_ground, mut outcomes)| {
1357                    land_on_ground.map(|log| land_on_grounds.push(log));
1358                    all_outcomes.append(&mut outcomes);
1359                    (land_on_grounds, all_outcomes)
1360                },
1361            )
1362            .reduce(
1363                || (Vec::new(), Vec::new()),
1364                |(mut land_on_grounds_a, mut outcomes_a),
1365                 (mut land_on_grounds_b, mut outcomes_b)| {
1366                    land_on_grounds_a.append(&mut land_on_grounds_b);
1367                    outcomes_a.append(&mut outcomes_b);
1368                    (land_on_grounds_a, outcomes_a)
1369                },
1370            );
1371        drop(guard);
1372        job.cpu_stats.measure(ParMode::Single);
1373
1374        write.outcomes.emitter().emit_many(outcomes);
1375
1376        prof_span!(guard, "write deferred pos and vel");
1377        for (_, pos, vel, ori, pos_vel_ori_defer, _) in (
1378            &read.entities,
1379            &mut write.positions,
1380            &mut write.velocities,
1381            &mut write.orientations,
1382            &mut write.pos_vel_ori_defers,
1383            &read.colliders,
1384        )
1385            .join()
1386            .filter(|tuple| tuple.5.is_voxel() == terrain_like_entities)
1387        {
1388            if let Some(new_pos) = pos_vel_ori_defer.pos.take() {
1389                *pos = new_pos;
1390            }
1391            if let Some(new_vel) = pos_vel_ori_defer.vel.take() {
1392                *vel = new_vel;
1393            }
1394            if let Some(new_ori) = pos_vel_ori_defer.ori.take() {
1395                *ori = new_ori;
1396            }
1397        }
1398        drop(guard);
1399
1400        let mut emitters = read.events.get_emitters();
1401        emitters.emit_many(
1402            land_on_grounds
1403                .into_iter()
1404                .map(|(entity, vel, surface_normal)| LandOnGroundEvent {
1405                    entity,
1406                    vel: vel.0,
1407                    surface_normal,
1408                }),
1409        );
1410    }
1411
1412    fn update_cached_spatial_grid(&mut self) {
1413        span!(_guard, "Update cached spatial grid");
1414        let &mut PhysicsData {
1415            ref read,
1416            ref mut write,
1417        } = self;
1418
1419        let spatial_grid = &mut write.cached_spatial_grid.0;
1420        spatial_grid.clear();
1421        (
1422            &read.entities,
1423            &write.positions,
1424            read.scales.maybe(),
1425            read.colliders.maybe(),
1426        )
1427            .join()
1428            .for_each(|(entity, pos, scale, collider)| {
1429                let scale = scale.map(|s| s.0).unwrap_or(1.0);
1430                let radius_2d =
1431                    (collider.map(|c| c.bounding_radius()).unwrap_or(0.5) * scale).ceil() as u32;
1432                let pos_2d = pos.0.xy().map(|e| e as i32);
1433                const POS_TRUNCATION_ERROR: u32 = 1;
1434                spatial_grid.insert(pos_2d, radius_2d + POS_TRUNCATION_ERROR, entity);
1435            });
1436    }
1437}
1438
1439impl<'a> System<'a> for Sys {
1440    type SystemData = PhysicsData<'a>;
1441
1442    const NAME: &'static str = "phys";
1443    const ORIGIN: Origin = Origin::Common;
1444    const PHASE: Phase = Phase::Create;
1445
1446    fn run(job: &mut Job<Self>, mut physics_data: Self::SystemData) {
1447        physics_data.reset();
1448
1449        // Apply pushback
1450        //
1451        // Note: We now do this first because we project velocity ahead. This is slighty
1452        // imperfect and implies that we might get edge-cases where entities
1453        // standing right next to the edge of a wall may get hit by projectiles
1454        // fired into the wall very close to them. However, this sort of thing is
1455        // already possible with poorly-defined hitboxes anyway so it's not too
1456        // much of a concern.
1457        //
1458        // If this situation becomes a problem, this code should be integrated with the
1459        // terrain collision code below, although that's not trivial to do since
1460        // it means the step needs to take into account the speeds of both
1461        // entities.
1462        physics_data.maintain_pushback_cache();
1463
1464        let spatial_grid = physics_data.construct_spatial_grid();
1465        physics_data.apply_pushback(job, &spatial_grid);
1466
1467        let voxel_collider_spatial_grid = physics_data.construct_voxel_collider_spatial_grid();
1468        physics_data.handle_movement_and_terrain(job, &voxel_collider_spatial_grid);
1469
1470        // Spatial grid used by other systems
1471        physics_data.update_cached_spatial_grid();
1472    }
1473}