physics_3d/
lib.rs

1//! Flat-shaded 3D rigid bodies, interpolated fixed-tick physics, and an orbit camera.
2//!
3//! The lab starts playing immediately. Its host uses the shared session clock;
4//! a paused manual step advances physics by exactly `session.dt()` without
5//! resuming the session or consuming any wall time:
6//! ```
7//! use ferravex_core::session::GameSession;
8//! use ferravex_physics::d3::PhysicsWorld;
9//! let mut session = GameSession::new(120.0, 8, true);
10//! let mut physics = PhysicsWorld::new([0.0, -9.81, 0.0]);
11//! let frame = session.advance(1.0 / 60.0);
12//! for _ in 0..frame.steps { physics.step(frame.dt); }
13//! session.set_paused(true);
14//! assert_eq!(session.advance(10.0).steps, 0);
15//! for dt in session.step_paused().unwrap().ticks() { physics.step(dt); }
16//! assert_eq!(session.tick(), 3); // Two automatic ticks and one manual tick.
17//! assert!(session.is_paused());
18//! ```
19use ferravex_core::session::GameSession;
20use ferravex_physics::d3::{
21    ColliderBuilder, JointBuilder, PhysicsWorld, QueryOptions, QueryReport, RayHit,
22    RigidBodyBuilder, RigidBodyHandle,
23};
24use ferravex_physics::{ContactEvent, JointHandle, JointMotor};
25use ferravex_play::camera::{Input3, Mode3, NoObstructions, Rig3, Settings3, Target3};
26use ferravex_play::feedback::FeedbackPolicy;
27use ferravex_render::audio::{Cue, GameAudio, Surface};
28use ferravex_render::input::{
29    ActionKind, Binding, InputCode, PlayerInput, Preset,
30    touch::{Control, Output, Region},
31};
32use ferravex_render::{
33    mesh::Mesh3d,
34    preferences,
35    prelude::*,
36    shaders::{LitMaterial, LitSettings},
37    ui,
38};
39
40#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
41mod capture;
42mod hud;
43mod juice;
44mod look;
45mod quips;
46mod toys;
47
48use toys::Fun;
49
50const MAX_BODIES: usize = 180;
51const CONCRETE: Color = Color::from_rgba(106, 116, 116, 255);
52const CRATE: Color = Color::from_rgba(173, 125, 68, 255);
53const PAINT: Color = Color::from_rgba(102, 143, 141, 255);
54
55struct Body {
56    handle: RigidBodyHandle,
57    ball: bool,
58    compound: bool,
59    /// A dense bowling ball launched by BOWL.
60    heavy: bool,
61    previous_position: Vec3,
62    previous_rotation: Quat,
63}
64
65struct Sandbox {
66    physics: PhysicsWorld,
67    terrain: Vec<(Mesh3d, ferravex_play::environment::BoxPiece)>,
68    bodies: Vec<Body>,
69    sequence: u32,
70    links: Vec<JointHandle>,
71    impact: Option<(f32, Surface)>,
72    pulse_time: f32,
73    pulse_center: Vec3,
74}
75
76impl Sandbox {
77    fn new() -> Self {
78        let mut sandbox = Self {
79            physics: PhysicsWorld::new([0.0, -9.81, 0.0]),
80            terrain: Vec::new(),
81            bodies: Vec::new(),
82            sequence: 0,
83            links: Vec::new(),
84            impact: None,
85            pulse_time: 0.,
86            pulse_center: Vec3::ZERO,
87        };
88        sandbox.record_impacts();
89        sandbox
90            .physics
91            .add_box([0.0, -0.4, 0.0], [10.0, 0.4, 8.0], false);
92        // Low perimeter curbs catch rolling objects without obscuring the scene.
93        for (position, half) in [
94            ([0.0, 0.25, -8.0], [10.25, 0.25, 0.25]),
95            ([0.0, 0.25, 8.0], [10.25, 0.25, 0.25]),
96            ([-10.0, 0.25, 0.0], [0.25, 0.25, 8.0]),
97            ([10.0, 0.25, 0.0], [0.25, 0.25, 8.0]),
98        ] {
99            sandbox.physics.add_box(position, half, false);
100        }
101        for x in [-9.4, 9.4] {
102            for z in [-7.4, 7.4] {
103                sandbox
104                    .physics
105                    .add_box([x, 0.4, z], [0.29, 0.4, 0.29], false);
106            }
107        }
108        let mut plan = ferravex_play::environment::EnvironmentPlan::new(16).unwrap();
109        plan.stairs(vec3(5., 0., -5.), 2., 0.2, 0.6, 6, 0).unwrap();
110        plan.ramp(vec3(-7., 0., -5.), 2., 1.2, 3.6, 0.2, 1).unwrap();
111        for &part in plan.pieces() {
112            sandbox.physics.insert(
113                RigidBodyBuilder::fixed().translation(part.center),
114                ColliderBuilder::cuboid(
115                    part.half_extents.x,
116                    part.half_extents.y,
117                    part.half_extents.z,
118                )
119                .rotation(part.rotation),
120            );
121            sandbox.terrain.push((
122                Mesh3d::cuboid(
123                    part.half_extents * 2.,
124                    if part.material == 0 { CONCRETE } else { PAINT },
125                ),
126                part,
127            ));
128        }
129        // A compact crate stack built at physical scale: one unit is one meter.
130        for y in 0..5 {
131            for x in 0..3 {
132                for z in 0..2 {
133                    sandbox.spawn(
134                        vec3(
135                            -1.8 + x as f32 * 1.22,
136                            0.6 + y as f32 * 1.21,
137                            -0.7 + z as f32 * 1.22,
138                        ),
139                        false,
140                    );
141                }
142            }
143        }
144        for index in 0..5 {
145            sandbox.spawn(
146                vec3(-5.0 + index as f32 * 0.9, 7.5 + index as f32 * 0.45, 2.5),
147                true,
148            );
149        }
150        sandbox.mechanisms();
151        sandbox
152    }
153
154    fn spawn(&mut self, position: Vec3, ball: bool) {
155        if !position.is_finite() {
156            return;
157        }
158        if self.bodies.len() >= MAX_BODIES {
159            return;
160        }
161        let handle = if ball {
162            self.physics.add_ball(position.to_array(), 0.58, true)
163        } else {
164            self.physics.add_box(position.to_array(), [0.58; 3], true)
165        };
166        let collider = self.physics.bodies[handle].colliders()[0];
167        self.physics.colliders[collider].set_restitution(if ball { 0.45 } else { 0.05 });
168        self.physics.bodies[handle].enable_ccd(true);
169        self.bodies.push(Body {
170            handle,
171            ball,
172            compound: false,
173            heavy: false,
174            previous_position: position,
175            previous_rotation: Quat::IDENTITY,
176        });
177    }
178
179    fn compound(&mut self, position: Vec3) -> RigidBodyHandle {
180        let handle = self
181            .physics
182            .insert_compound(
183                RigidBodyBuilder::dynamic()
184                    .translation(position)
185                    .ccd_enabled(true),
186                [
187                    ColliderBuilder::cuboid(0.8, 0.13, 0.13),
188                    ColliderBuilder::ball(0.36).translation(-Vec3::X * 0.8),
189                    ColliderBuilder::ball(0.36).translation(Vec3::X * 0.8),
190                ],
191            )
192            .unwrap();
193        self.bodies.push(Body {
194            handle,
195            ball: false,
196            compound: true,
197            heavy: false,
198            previous_position: position,
199            previous_rotation: Quat::IDENTITY,
200        });
201        handle
202    }
203    fn mechanisms(&mut self) {
204        let hinge_anchor = self
205            .physics
206            .insert_body(RigidBodyBuilder::fixed().translation(vec3(6., 6., -4.)))
207            .unwrap();
208        let door = self.compound(vec3(6., 5., -4.));
209        self.links.push(
210            self.physics
211                .insert_joint(
212                    hinge_anchor,
213                    door,
214                    JointBuilder::hinge()
215                        .local_anchor2(Vec3::Y)
216                        .limits(-1.2, 1.2)
217                        .motor(JointMotor::position(0.9, 8., 2., 20.)),
218                )
219                .unwrap(),
220        );
221        self.spawn(vec3(6., 3.7, -4.), false);
222        let pendant = self.bodies.last().unwrap().handle;
223        self.links.push(
224            self.physics
225                .insert_joint(
226                    door,
227                    pendant,
228                    JointBuilder::fixed()
229                        .local_anchor1(vec3(0., -0.6, 0.))
230                        .local_anchor2(vec3(0., 0.7, 0.)),
231                )
232                .unwrap(),
233        );
234        let a = self
235            .physics
236            .insert_body(RigidBodyBuilder::fixed().translation(vec3(-6., 7., -4.)))
237            .unwrap();
238        self.spawn(vec3(-4.5, 5., -4.), true);
239        let bob = self.bodies.last().unwrap().handle;
240        self.bodies.last_mut().unwrap().previous_position = vec3(-4.5, 5., -4.);
241        self.links.push(
242            self.physics
243                .insert_joint(a, bob, JointBuilder::distance(2.5))
244                .unwrap(),
245        );
246        let a = self
247            .physics
248            .insert_body(RigidBodyBuilder::fixed().translation(vec3(5., 7., 4.)))
249            .unwrap();
250        let bob = self.compound(vec3(5., 4.6, 4.));
251        self.links.push(
252            self.physics
253                .insert_joint(a, bob, JointBuilder::spring(2., 25., 5.))
254                .unwrap(),
255        );
256    }
257
258    fn drop_body(&mut self, ball: bool) -> bool {
259        if self.bodies.len() >= MAX_BODIES {
260            return false;
261        }
262        self.sequence = self.sequence.wrapping_add(1);
263        let phase = self.sequence as f32 * 2.399_963;
264        self.spawn(vec3(phase.cos() * 2.3, 10.0, phase.sin() * 2.3), ball);
265        true
266    }
267
268    fn pulse(&mut self, center: Vec3) -> bool {
269        if self.pulse_time > 0. {
270            return false;
271        }
272        self.pulse_time = 0.65;
273        self.pulse_center = center;
274        for body in &self.bodies {
275            let rigid = &mut self.physics.bodies[body.handle];
276            let position = rigid.translation();
277            if let Some(mut kick) =
278                ferravex_play::motion::radial_velocity(center, position, 8., 11.)
279            {
280                kick.y = kick.y.max(0.) + kick.length() * 0.55;
281                rigid.apply_impulse(kick * rigid.mass(), true);
282            }
283        }
284        true
285    }
286
287    fn step(&mut self, dt: f32) {
288        self.pulse_time = (self.pulse_time - dt).max(0.);
289        let mut velocities = [Vec3::ZERO; MAX_BODIES];
290        for (i, body) in self.bodies.iter_mut().enumerate() {
291            velocities[i] = Vec3::from_array(self.physics.bodies[body.handle].linvel().to_array());
292            let rigid_body = &self.physics.bodies[body.handle];
293            body.previous_position = Vec3::from_array(rigid_body.translation().to_array());
294            body.previous_rotation = Quat::from_array(rigid_body.rotation().to_array());
295        }
296        self.physics.step(dt);
297        self.impact = None;
298        // A constraint/motor velocity change alone is not an impact. Only
299        // accepted solid contact starts can produce a sound, including CCD hits.
300        for event in self.physics.contact_events() {
301            let &ContactEvent::Started(a, b) = event else {
302                continue;
303            };
304            let Some(pair) = self.physics.contact_pair(a, b).filter(|p| !p.sensor) else {
305                continue;
306            };
307            let index = |collider| {
308                let parent = self.physics.colliders[collider].parent();
309                self.bodies
310                    .iter()
311                    .position(|body| Some(body.handle) == parent)
312            };
313            let (a, b) = (index(a), index(b));
314            let va = a.map_or(Vec3::ZERO, |i| velocities[i]);
315            let vb = b.map_or(Vec3::ZERO, |i| velocities[i]);
316            let strength = (va - vb).dot(Vec3::from_array(pair.normal)).abs();
317            if strength <= 1.2 || self.impact.is_some_and(|(old, _)| old >= strength) {
318                continue;
319            }
320            let Some(body) = a.or(b).map(|i| &self.bodies[i]) else {
321                continue;
322            };
323            self.impact = Some((
324                strength,
325                if body.compound {
326                    Surface::Metal
327                } else if body.ball {
328                    Surface::Stone
329                } else {
330                    Surface::Wood
331                },
332            ));
333        }
334    }
335
336    fn snap_interpolation(&mut self) {
337        for body in &mut self.bodies {
338            let rigid = &self.physics.bodies[body.handle];
339            body.previous_position = rigid.translation();
340            body.previous_rotation = *rigid.rotation();
341        }
342    }
343}
344
345#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
346enum DropShape {
347    #[default]
348    Crate,
349    Ball,
350}
351
352struct Orbit {
353    yaw: f32,
354    pitch: f32,
355    radius: f32,
356    rig: Rig3,
357}
358
359impl Default for Orbit {
360    fn default() -> Self {
361        Self {
362            yaw: 0.68,
363            pitch: 0.48,
364            radius: 25.,
365            rig: Rig3::new(Settings3 {
366                position_half_life: 0.045,
367                target_half_life: 0.,
368                ..Default::default()
369            })
370            .unwrap(),
371        }
372    }
373}
374
375impl Orbit {
376    fn input(&mut self, dt: f32, look: Vec2, movement: Vec2, zoom: f32) {
377        if !look.is_finite() || !movement.is_finite() || !zoom.is_finite() {
378            return;
379        }
380        let dt = presentation_dt(dt);
381        let tau = std::f32::consts::TAU;
382        self.yaw = (self.yaw - look.x.clamp(-tau, tau) + movement.x.clamp(-1., 1.) * dt * 1.2)
383            .rem_euclid(tau);
384        self.pitch = (self.pitch + look.y.clamp(-tau, tau) + movement.y.clamp(-1., 1.) * dt * 1.2)
385            .clamp(0.12, 1.35);
386        self.radius = (self.radius - zoom).clamp(12., 42.);
387    }
388
389    fn reset(&mut self) {
390        self.yaw = 0.68;
391        self.pitch = 0.48;
392        self.radius = 25.;
393        self.rig.cut();
394    }
395
396    fn view(&mut self, dt: f32) -> ferravex_play::camera::Pose3 {
397        self.rig
398            .update(
399                presentation_dt(dt),
400                Input3 {
401                    target: Target3::at(vec3(0., 2.2, 0.)),
402                    mode: Mode3::Orbit {
403                        yaw: self.yaw,
404                        pitch: self.pitch,
405                        distance: self.radius,
406                        pivot: Vec3::ZERO,
407                    },
408                    fov_y: 43_f32.to_radians(),
409                },
410                &NoObstructions,
411            )
412            .expect("valid laboratory orbit")
413            .pose
414    }
415}
416
417// Inspector edits and lifecycle controls are render-frame commands so drops
418// remain available while paused. Pulses are queued until an actual running tick.
419#[derive(Default)]
420struct Commands {
421    crate_drop: bool,
422    ball_drop: bool,
423    drop: bool,
424    pulse: bool,
425    pause: bool,
426    step: bool,
427    view: bool,
428    reset: bool,
429    /// Roll a heavy ball at the stack from the camera's side (immediate edit).
430    bowl: bool,
431    /// Throw in a ring of mixed shapes (immediate edit).
432    chaos: bool,
433}
434
435struct LabFrame {
436    alpha: f32,
437    /// Physics ticks executed this frame, including a manual step.
438    ticks: u32,
439    pulse: bool,
440    impact: Option<(f32, Surface)>,
441    reset: bool,
442}
443
444struct Lab {
445    sandbox: Sandbox,
446    fun: Fun,
447    session: GameSession,
448    orbit: Orbit,
449    shape: DropShape,
450    pending_pulse: bool,
451    dropped_seconds: f64,
452    impact_cooldown: f32,
453    /// The latest accepted or refused command, for presentation only. The HUD
454    /// shows refusals as a red wobble and a short popup on the tool involved.
455    notice: Notice,
456    /// Increments with every notice, so presentation reacts exactly once.
457    notice_serial: u32,
458}
459
460/// What the yard last did with a command. Presentation maps these to icons,
461/// key caps and one- or two-word popups instead of sentences.
462#[derive(Clone, Copy, Debug, PartialEq, Eq)]
463enum Notice {
464    /// Freshly opened yard.
465    Ready,
466    /// RESET rebuilt the yard and restored the view.
467    Rebuilt,
468    Dropped,
469    /// A drop refused by the body cap.
470    DropFull,
471    Bowled,
472    /// A bowl refused by the body cap.
473    BowlFull,
474    Chaos,
475    /// CHAOS refused by the body cap.
476    ChaosFull,
477    /// VIEW restored the default orbit.
478    ViewRestored,
479    Paused,
480    Resumed,
481    /// A pulse requested while paused.
482    PulsePaused,
483    Pulsed,
484    PulseRecharging,
485    /// One manual tick while paused.
486    Stepped,
487    /// STEP pressed while running.
488    StepWhileRunning,
489}
490
491impl Lab {
492    fn new() -> Self {
493        let sandbox = Sandbox::new();
494        let mut fun = Fun::default();
495        fun.on_rebuild(&sandbox);
496        Self {
497            sandbox,
498            fun,
499            session: GameSession::try_new(120., 8, true).expect("valid laboratory clock"),
500            orbit: Orbit::default(),
501            shape: DropShape::Crate,
502            pending_pulse: false,
503            dropped_seconds: 0.,
504            impact_cooldown: 0.,
505            notice: Notice::Ready,
506            notice_serial: 0,
507        }
508    }
509
510    fn notice(&mut self, notice: Notice) {
511        self.notice = notice;
512        self.notice_serial = self.notice_serial.wrapping_add(1);
513    }
514
515    fn reset(&mut self) {
516        self.sandbox = Sandbox::new();
517        self.fun.on_rebuild(&self.sandbox);
518        self.session.restart();
519        self.orbit.reset();
520        self.shape = DropShape::Crate;
521        self.pending_pulse = false;
522        self.dropped_seconds = 0.;
523        self.impact_cooldown = 0.;
524        self.notice(Notice::Rebuilt);
525    }
526
527    fn drop(&mut self) {
528        let dropped = self.sandbox.drop_body(self.shape == DropShape::Ball);
529        self.fun.stats.drops += u32::from(dropped);
530        self.notice(if dropped {
531            Notice::Dropped
532        } else {
533            Notice::DropFull
534        });
535    }
536
537    fn bowl(&mut self) {
538        match self.sandbox.bowl(self.orbit.yaw) {
539            Some(at) => {
540                self.fun.bowled(at);
541                self.notice(Notice::Bowled);
542            }
543            None => self.notice(Notice::BowlFull),
544        }
545    }
546
547    fn chaos(&mut self) {
548        let count = self.sandbox.chaos(self.fun.chaos_serial);
549        if count == 0 {
550            self.notice(Notice::ChaosFull);
551            return;
552        }
553        self.fun.chaos_serial = self.fun.chaos_serial.wrapping_add(1);
554        self.fun.stats.chaos += 1;
555        self.fun.events.chaos += count;
556        self.fun.touch();
557        self.notice(Notice::Chaos);
558    }
559
560    fn step(&mut self, dt: f32, frame: &mut LabFrame) {
561        frame.ticks += 1;
562        self.sandbox.step(dt);
563        self.fun.after_tick(&mut self.sandbox, dt);
564        self.impact_cooldown = (self.impact_cooldown - dt).max(0.);
565        if self.impact_cooldown == 0. && self.sandbox.impact.is_some() {
566            frame.impact = self.sandbox.impact;
567            self.impact_cooldown = 0.055;
568        }
569    }
570
571    #[cfg(test)]
572    fn advance(&mut self, elapsed: f64, commands: Commands) -> LabFrame {
573        self.advance_with_input(elapsed, commands, || false)
574    }
575
576    fn advance_with_input(
577        &mut self,
578        elapsed: f64,
579        commands: Commands,
580        mut pulse_input: impl FnMut() -> bool,
581    ) -> LabFrame {
582        let mut result = LabFrame {
583            alpha: 1.,
584            ticks: 0,
585            pulse: false,
586            impact: None,
587            reset: false,
588        };
589        self.fun.begin_frame();
590        // Reset wins over all simultaneous input and renders the fresh pose.
591        if commands.reset {
592            self.reset();
593            result.reset = true;
594            return result;
595        }
596        if commands.view {
597            self.orbit.reset();
598            self.notice(Notice::ViewRestored);
599        }
600        if commands.pause {
601            self.session.toggle_pause();
602            if self.session.is_paused() {
603                self.sandbox.snap_interpolation();
604            }
605            self.notice(if self.session.is_paused() {
606                Notice::Paused
607            } else {
608                Notice::Resumed
609            });
610        }
611        if commands.crate_drop || commands.ball_drop || commands.drop {
612            if commands.crate_drop {
613                self.shape = DropShape::Crate;
614            } else if commands.ball_drop {
615                self.shape = DropShape::Ball;
616            }
617            self.drop();
618        }
619        if commands.bowl {
620            self.bowl();
621        }
622        if commands.chaos {
623            self.chaos();
624        }
625        if self.session.is_paused() {
626            self.pending_pulse = false;
627            if pulse_input() | commands.pulse {
628                self.notice(Notice::PulsePaused);
629            }
630        } else {
631            self.pending_pulse |= commands.pulse;
632        }
633        let frame = self.session.advance(elapsed);
634        self.dropped_seconds += frame.dropped_seconds;
635        for _ in 0..frame.steps {
636            let requested = pulse_input() | std::mem::take(&mut self.pending_pulse);
637            if requested && self.sandbox.pulse(vec3(0., 0.5, 0.)) {
638                result.pulse = true;
639                self.fun.stats.pulses += 1;
640                self.notice(Notice::Pulsed);
641            } else if requested {
642                self.notice(Notice::PulseRecharging);
643            }
644            self.step(frame.dt, &mut result);
645        }
646        if commands.step {
647            if self.session.is_paused() {
648                let step = self.session.step_paused().expect("paused inspector");
649                self.step(step.dt, &mut result);
650                self.sandbox.snap_interpolation();
651                self.notice(Notice::Stepped);
652            } else {
653                self.notice(Notice::StepWhileRunning);
654            }
655        }
656        result.alpha = if self.session.is_paused() {
657            1.
658        } else {
659            frame.alpha
660        };
661        result
662    }
663}
664
665fn presentation_dt(dt: f32) -> f32 {
666    if dt.is_finite() {
667        dt.clamp(0., 0.1)
668    } else {
669        0.
670    }
671}
672
673// Presentation owns the pulse ring's lifetime, independently of its simulation
674// cooldown. Clearing it under either visual preference is permanent for that
675// pulse, including when the world is paused or Controls has focus.
676#[derive(Default)]
677struct Presentation {
678    policy: FeedbackPolicy,
679    pulse: Option<(Vec3, f32)>,
680}
681
682impl Presentation {
683    fn begin_frame(&mut self, dt: f32) {
684        self.policy = preferences::feedback_policy();
685        if !self.pulse_allowed() {
686            self.pulse = None;
687        } else if let Some((_, remaining)) = &mut self.pulse {
688            *remaining -= presentation_dt(dt);
689            if *remaining <= 0. {
690                self.pulse = None;
691            }
692        }
693    }
694
695    fn pulse_allowed(&self) -> bool {
696        !self.policy.reduced_motion()
697            && !self.policy.reduced_flash()
698            && self.policy.intensity() > 0.
699    }
700
701    fn accept(&mut self, frame: &LabFrame, center: Vec3) {
702        if frame.reset {
703            self.pulse = None;
704        } else if frame.pulse && self.pulse_allowed() {
705            self.pulse = Some((center, 0.65));
706        }
707    }
708}
709
710// One current-pose camera-center ray per presentation frame. Collider hits
711// (including individual compound children) are distinct from body counts.
712struct Inspector {
713    hits: [Option<RayHit>; 8],
714    query: QueryReport,
715}
716
717impl Inspector {
718    fn new() -> Self {
719        Self {
720            hits: [None; 8],
721            query: QueryReport::default(),
722        }
723    }
724
725    fn sample(&mut self, physics: &PhysicsWorld, eye: Vec3, target: Vec3) {
726        self.query = physics
727            .raycast_into(
728                eye.to_array(),
729                (target - eye).to_array(),
730                QueryOptions::new(60.),
731                &mut self.hits,
732            )
733            .expect("finite laboratory camera ray");
734    }
735}
736
737#[cfg(test)]
738fn binding_hint<'a>(input: &PlayerInput, name: &str, buffer: &'a mut [u8]) -> &'a str {
739    input.format_hint(name, buffer).unwrap_or("Controls")
740}
741
742/// CRATE, BALL, DROP, PULSE, PAUSE, STEP, VIEW, RESET, BOWL, CHAOS.
743const BUTTONS: usize = 10;
744/// Visual groups: CRATE BALL DROP | PULSE BOWL CHAOS | PAUSE STEP VIEW RESET.
745/// Indexed by the stable button index above.
746const SLOT: [usize; BUTTONS] = [0, 1, 2, 3, 6, 7, 8, 9, 4, 5];
747
748fn footer_columns(width: f32) -> usize {
749    if width >= 900. {
750        BUTTONS
751    } else if width >= 540. {
752        5
753    } else if width >= 370. {
754        4
755    } else {
756        3
757    }
758}
759
760fn footer_layout(width: f32, height: f32) -> (Rect, [Rect; BUTTONS]) {
761    let columns = footer_columns(width);
762    let rows = BUTTONS.div_ceil(columns);
763    // One row of icon readouts sits above the buttons.
764    let text_height = hud::STATUS_ROW;
765    let panel = Rect::new(
766        12.,
767        height - (text_height + 12. + rows as f32 * 44.),
768        width - 24.,
769        text_height + rows as f32 * 44.,
770    );
771    let gaps = if columns == BUTTONS { 20. } else { 0. };
772    let button_width = (panel.w - 24. - (columns - 1) as f32 * 6. - gaps) / columns as f32;
773    let buttons = std::array::from_fn(|i| {
774        let slot = SLOT[i];
775        let column = slot % columns;
776        let group = if columns == BUTTONS {
777            if column >= 6 {
778                20.
779            } else if column >= 3 {
780                10.
781            } else {
782                0.
783            }
784        } else {
785            0.
786        };
787        Rect::new(
788            panel.x + 12. + column as f32 * (button_width + 6.) + group,
789            panel.y + text_height - 4. + (slot / columns) as f32 * 44.,
790            button_width,
791            36.,
792        )
793    });
794    (panel, buttons)
795}
796
797// Wraps bounded text into fixed-size rows. The play HUD now reads as icon
798// readouts; tests keep this helper to prove long bindings stay explicit.
799#[cfg(test)]
800fn hud_lines(mut text: &str, width: f32, size: u16) -> impl Iterator<Item = &str> {
801    let metrics = get_default_font().try_metrics(size, 1.).expect("HUD font");
802    let columns = (width / metrics.glyph_advance()).floor().max(1.) as usize;
803    std::iter::from_fn(move || {
804        text = text.trim_start();
805        if text.is_empty() {
806            return None;
807        }
808        let mut end = text
809            .char_indices()
810            .nth(columns)
811            .map_or(text.len(), |(i, _)| i);
812        if end < text.len()
813            && !text[end..].starts_with(' ')
814            && let Some(space) = text[..end].rfind(' ')
815            && space > 0
816        {
817            end = space;
818        }
819        let line = &text[..end];
820        text = &text[end..];
821        Some(line)
822    })
823}
824
825#[cfg(test)]
826fn inspector_hint(text: &str, width: f32, narrow: bool) -> &str {
827    let (size, rows) = if narrow { (14, 2) } else { (16, 1) };
828    if hud_lines(text, width, size).count() <= rows {
829        text
830    } else {
831        "Bindings: Controls"
832    }
833}
834
835// Fit only narrow views into the same scene band used by pointer/touch input.
836// Pose, clipping depth, fog and relative orbit/zoom input remain authored.
837struct SceneCamera {
838    camera: Camera3D,
839    scene: Rect,
840}
841
842impl Camera for SceneCamera {
843    fn matrix(&self, width: f32, height: f32) -> Mat4 {
844        if width >= 540. {
845            return self.camera.matrix(width, height);
846        }
847        let aspect = self.scene.w / self.scene.h.max(1.);
848        let camera = Camera3D {
849            fovy: 2. * ((self.camera.fovy * 0.5).tan() * (1.6 / aspect).max(1.)).atan(),
850            ..self.camera
851        };
852        Mat4::from_translation(vec3(
853            self.scene.center().x * 2. / width - 1.,
854            1. - self.scene.center().y * 2. / height,
855            0.,
856        )) * Mat4::from_scale(vec3(self.scene.w / width, self.scene.h / height, 1.))
857            * camera.matrix(self.scene.w, self.scene.h)
858    }
859
860    fn depth(&self) -> bool {
861        self.camera.depth()
862    }
863    fn position(&self) -> Option<Vec3> {
864        Some(self.camera.position)
865    }
866}
867
868fn scene_rect(width: f32, panel: Rect) -> Rect {
869    Rect::new(0., 44., width, (panel.y - 44.).max(1.))
870}
871
872fn window_conf() -> Conf {
873    #[allow(unused_mut)]
874    let mut conf = ferravex_render::window_conf("Ferravex / low-poly physics laboratory");
875    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
876    capture::window(&mut conf);
877    conf
878}
879
880fn register_lab_actions(player_input: &mut PlayerInput) {
881    for (name, label, key, pad) in [
882        ("drop", "Drop selected shape", KeyCode::Enter, 2),
883        ("step", "Step once while paused", KeyCode::N, 5),
884        ("reset_view", "Reset orbit view", KeyCode::C, 3),
885        ("bowl", "Bowl a heavy ball at the stack", KeyCode::B, 10),
886        ("chaos", "Chaos: throw in sixteen shapes", KeyCode::Key3, 11),
887    ] {
888        player_input
889            .action(
890                name,
891                label,
892                ActionKind::Button,
893                vec![
894                    Binding::digital(InputCode::Key(key as u16)),
895                    Binding::digital(InputCode::PadButton(pad)),
896                ],
897            )
898            .unwrap();
899    }
900    player_input
901        .action(
902            "stats",
903            "Show engine stats",
904            ActionKind::Button,
905            vec![Binding::digital(InputCode::Key(KeyCode::G as u16))],
906        )
907        .unwrap();
908}
909
910fn mix(a: Color, b: Color, t: f32) -> Color {
911    let t = t.clamp(0., 1.);
912    Color::new(
913        a.r + (b.r - a.r) * t,
914        a.g + (b.g - a.g) * t,
915        a.b + (b.b - a.b) * t,
916        a.a,
917    )
918}
919
920ferravex_render::game!(window_conf, game);
921async fn game() {
922    let mut demo = ferravex_render::demo::Demo::new();
923    set_post_fx(
924        PostFx::subtle()
925            .bloom(0.65, 0.92, 1.1)
926            .contrast(1.04)
927            .vignette(0.26, 0.6),
928    );
929    let mut lab = Lab::new();
930    let mut presentation = Presentation::default();
931    let mut inspector = Inspector::new();
932    let mut sound = GameAudio::new();
933    let mut juice = juice::Juice::new();
934    juice.rebuild(lab.sandbox.bodies.len());
935    let mut hud = hud::Hud::default();
936    // Personal bests are optional; autoplay demos never claim one.
937    let mut bests = hud::Bests::load(!demo.autoplay);
938    let mut particles = ferravex_render::effects::ParticleRenderer::new(480)
939        .expect("bounded presentation particles");
940    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
941    let mut capture = capture::Capture::from_env();
942    let material = LitMaterial::new()
943        .expect("The built-in Ferravex material must compile on the selected GPU backend");
944    let crate_mesh = Mesh3d::cuboid(vec3(1.16, 1.16, 1.16), CRATE);
945    let ball_mesh = Mesh3d::sphere(0.58, PAINT, 10, 6);
946    let bowling_mesh = Mesh3d::sphere(0.58, Color::from_rgba(150, 64, 112, 255), 12, 8);
947    let compound_bar = Mesh3d::cuboid(vec3(1.6, 0.26, 0.26), CONCRETE);
948    let compound_end = Mesh3d::sphere(0.36, ui::AMBER, 10, 6);
949    let floor_mesh = Mesh3d::cuboid(vec3(20.0, 0.8, 16.0), Color::from_rgba(71, 81, 86, 255));
950    let curb_x = Mesh3d::cuboid(vec3(20.5, 0.5, 0.5), CONCRETE);
951    let curb_z = Mesh3d::cuboid(vec3(0.5, 0.5, 16.0), CONCRETE);
952    let floor_mark = Mesh3d::cuboid(
953        vec3(0.12, 0.012, 14.0),
954        Color::from_rgba(152, 146, 117, 255),
955    );
956    let cross_mark = Mesh3d::cuboid(
957        vec3(18.0, 0.012, 0.12),
958        Color::from_rgba(152, 146, 117, 255),
959    );
960    let pedestal = Mesh3d::cuboid(vec3(0.55, 0.8, 0.55), Color::from_rgba(82, 92, 98, 255));
961    let marker = Mesh3d::cuboid(vec3(0.58, 0.13, 0.58), Color::from_rgba(208, 163, 74, 255));
962    let mut player_input = PlayerInput::preset("physics-3d", Preset::Lab3);
963    player_input.set_mouse_look_button(Some(1)).unwrap();
964    register_lab_actions(&mut player_input);
965    let mut pending = Commands::default();
966    loop {
967        let dt = demo.dt();
968        // Always consume the shared policy before accepted feedback and camera
969        // sampling, even when input or simulation is inactive.
970        presentation.begin_frame(dt);
971        juice.apply_policy(presentation.policy);
972        ui::warm_up_font();
973        let (panel, buttons) = footer_layout(screen_width(), screen_height());
974        let scene = scene_rect(screen_width(), panel);
975        player_input
976            .set_touch_layout(&[Control {
977                region: Region::Rect(scene),
978                output: Output::Look { x: 0, y: 1 },
979            }])
980            .unwrap();
981        player_input.sample(true);
982        // Debug captures may keep an unfocused review window running.
983        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
984        let forced = capture.forced();
985        #[cfg(not(all(debug_assertions, not(target_arch = "wasm32"))))]
986        let forced = false;
987        let active = player_input.gameplay_active() || forced;
988        let pointer = Vec2::from(mouse_position());
989        let in_scene = scene.contains(pointer);
990        let clicked = is_mouse_button_pressed(MouseButton::Left);
991        let card_closed = active && clicked && hud.dismiss_card();
992        let mut look = player_input.look(presentation_dt(dt));
993        if !(in_scene
994            || player_input.touch_active()
995            || player_input.value("look_rate_x").abs() > 0.001
996            || player_input.value("look_rate_y").abs() > 0.001)
997            || hud.card.is_some()
998        {
999            look = Vec2::ZERO;
1000        }
1001        let zoom = player_input.take("zoom").value;
1002        let movement = player_input.movement();
1003        // A deliberate orbit retires the drag-to-orbit demonstration.
1004        let orbited = active
1005            && (look.length() > 0.004 || movement.length() > 0.1 || (in_scene && zoom != 0.));
1006        lab.orbit.input(
1007            dt,
1008            look,
1009            movement,
1010            if in_scene { zoom * 0.8 } else { 0. }
1011                + player_input.value("zoom_rate") * presentation_dt(dt) * 4.,
1012        );
1013        pending.pause |= player_input.pressed("pause");
1014        pending.reset |= player_input.pressed("restart");
1015        pending.crate_drop |= player_input.pressed("select_one");
1016        pending.ball_drop |= player_input.pressed("select_two");
1017        pending.drop |= player_input.pressed("drop");
1018        pending.step |= player_input.pressed("step");
1019        pending.view |= player_input.pressed("reset_view");
1020        pending.bowl |= player_input.pressed("bowl");
1021        pending.chaos |= player_input.pressed("chaos");
1022        if player_input.pressed("stats") {
1023            hud.stats = !hud.stats;
1024        }
1025        if !active || card_closed {
1026            pending = Commands::default();
1027            lab.pending_pulse = false;
1028        }
1029        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1030        capture.inject(&mut lab, &mut pending, &mut hud);
1031        let simulation_dt = if forced {
1032            presentation_dt(dt)
1033        } else {
1034            player_input.simulation_dt(dt)
1035        };
1036        let frame =
1037            lab.advance_with_input(simulation_dt as f64, std::mem::take(&mut pending), || {
1038                player_input.take_tick(["pulse"])[0].pressed
1039            });
1040        if frame.reset {
1041            // Discard a pulse sampled in the same frame as RESET.
1042            player_input.take("pulse");
1043        }
1044        presentation.accept(&frame, lab.sandbox.pulse_center);
1045        // Feedback follows accepted lab events only.
1046        let added = lab.sandbox.bodies.len() > juice.known() && !frame.reset;
1047        juice.on_frame(&lab, &frame);
1048        juice.advance_sim(frame.ticks as f32 / 120.);
1049        juice.advance_render(dt);
1050        let paused = lab.session.is_paused();
1051        let room = lab.sandbox.bodies.len() < MAX_BODIES;
1052        // Stable index order: CRATE BALL DROP PULSE PAUSE STEP VIEW RESET BOWL CHAOS.
1053        let enabled = [
1054            true,
1055            true,
1056            true,
1057            !paused && lab.sandbox.pulse_time == 0.,
1058            true,
1059            paused,
1060            true,
1061            true,
1062            room,
1063            room,
1064        ];
1065        let selected = [
1066            lab.shape == DropShape::Crate,
1067            lab.shape == DropShape::Ball,
1068            false,
1069            false,
1070            paused,
1071            false,
1072            false,
1073            false,
1074            false,
1075            false,
1076        ];
1077        let mouse_down = is_mouse_button_down(MouseButton::Left);
1078        let tools: [look::ToolState; BUTTONS] = std::array::from_fn(|i| {
1079            let over = active && buttons[i].contains(pointer);
1080            look::ToolState {
1081                hovered: over,
1082                pressed: over && mouse_down,
1083                selected: selected[i],
1084                enabled: enabled[i],
1085            }
1086        });
1087        hud.advance(
1088            &lab,
1089            active,
1090            dt,
1091            ferravex_play::tween::Motion::from_reduced(presentation.policy.reduced_motion()),
1092            &tools,
1093            orbited,
1094        );
1095        let events = &lab.fun.events;
1096        if frame.pulse {
1097            sound.cue(Cue::Impact(Surface::Metal), 0.5);
1098        }
1099        if let Some((strength, surface)) = frame.impact {
1100            sound.cue(Cue::Impact(surface), (strength * 0.09).clamp(0.15, 0.7));
1101        }
1102        if added {
1103            sound.cue(Cue::Click, if events.chaos > 0 { 0.45 } else { 0.25 });
1104        }
1105        if events.bowled.is_some() {
1106            sound.cue(Cue::Jump, 0.5);
1107        }
1108        if let Some(knocked) = events.bowl_result {
1109            sound.cue(
1110                if knocked >= 8 {
1111                    Cue::Success
1112                } else {
1113                    Cue::Failure
1114                },
1115                0.5,
1116            );
1117        }
1118        if events.collapse.is_some() {
1119            sound.cue(Cue::Impact(Surface::Stone), 0.8);
1120        }
1121        if !events.goals.is_empty() || events.secret {
1122            sound.cue(Cue::Success, 0.7);
1123        }
1124        if events.returned > 0 {
1125            sound.cue(Cue::Pickup, 0.4);
1126        }
1127        if let Some(best) = bests.update(&lab.fun) {
1128            juice.toast(
1129                "New best!",
1130                Some(look::Glyph::Pict(ferravex_render::icons::Icon::Trophy)),
1131                Some((best.glyph, best.value)),
1132                juice::GOLD,
1133                2.6,
1134                juice::Priority::Alert,
1135            );
1136            sound.cue(Cue::Success, 0.6);
1137        }
1138        let alpha = frame.alpha;
1139        let sandbox = &lab.sandbox;
1140        clear_background(ui::BACKGROUND);
1141        if presentation.policy.reduced_motion() {
1142            lab.orbit.rig.cut();
1143        }
1144        let view = lab.orbit.view(dt);
1145        // The probe uses the steady orbit; shake and the beat are cosmetic.
1146        inspector.sample(&sandbox.physics, view.position, view.target);
1147        let (eye, target) = juice.camera(view.position, view.target);
1148        let camera = SceneCamera {
1149            camera: Camera3D {
1150                position: eye,
1151                target,
1152                up: view.up,
1153                fovy: view.fov_y,
1154                z_near: 0.1,
1155                z_far: 100.0,
1156                ..Default::default()
1157            },
1158            scene,
1159        };
1160        let view_proj = camera.matrix(screen_width(), screen_height());
1161        set_camera(&camera);
1162        material.begin(LitSettings {
1163            camera_position: eye,
1164            fog_start: 22.0,
1165            fog_end: 65.0,
1166            ambient: 0.48,
1167            ..Default::default()
1168        });
1169        floor_mesh.draw(vec3(0.0, -0.4, 0.0), Quat::IDENTITY);
1170        for (mesh, part) in &sandbox.terrain {
1171            mesh.draw(part.center, part.rotation);
1172        }
1173        for z in [-8.0, 8.0] {
1174            curb_x.draw(vec3(0.0, 0.25, z), Quat::IDENTITY);
1175        }
1176        for x in [-10.0, 10.0] {
1177            curb_z.draw(vec3(x, 0.25, 0.0), Quat::IDENTITY);
1178        }
1179        for x in [-5.8, 5.8] {
1180            floor_mark.draw(vec3(x, 0.008, 0.0), Quat::IDENTITY);
1181        }
1182        for z in [-4.5, 4.5] {
1183            cross_mark.draw(vec3(0.0, 0.008, z), Quat::IDENTITY);
1184        }
1185        for x in [-9.4, 9.4] {
1186            for z in [-7.4, 7.4] {
1187                pedestal.draw(vec3(x, 0.4, z), Quat::IDENTITY);
1188                marker.draw(vec3(x, 0.65, z), Quat::IDENTITY);
1189            }
1190        }
1191        let interpolated = |body: &Body| {
1192            let rigid = &sandbox.physics.bodies[body.handle];
1193            (
1194                body.previous_position.lerp(rigid.translation(), alpha),
1195                body.previous_rotation.slerp(*rigid.rotation(), alpha),
1196            )
1197        };
1198        // Group opaque parts by resident mesh so assemblies retain instancing.
1199        for body in sandbox.bodies.iter().filter(|b| !b.compound && !b.ball) {
1200            let (p, r) = interpolated(body);
1201            crate_mesh.draw(p, r);
1202        }
1203        for body in sandbox.bodies.iter().filter(|b| b.ball && !b.heavy) {
1204            let (p, r) = interpolated(body);
1205            ball_mesh.draw(p, r);
1206        }
1207        for body in sandbox.bodies.iter().filter(|b| b.heavy) {
1208            let (p, r) = interpolated(body);
1209            bowling_mesh.draw(p, r);
1210        }
1211        for body in sandbox.bodies.iter().filter(|b| b.compound) {
1212            let (p, r) = interpolated(body);
1213            compound_bar.draw(p, r);
1214        }
1215        for body in sandbox.bodies.iter().filter(|b| b.compound) {
1216            let (p, r) = interpolated(body);
1217            for x in [-0.8, 0.8] {
1218                compound_end.draw(p + r * vec3(x, 0., 0.), r);
1219            }
1220        }
1221        for id in &sandbox.links {
1222            if let Some([a, _]) = sandbox.physics.joint_anchors(*id) {
1223                compound_end.draw(a, Quat::IDENTITY);
1224            }
1225        }
1226        material.end();
1227        // Wire detail belongs only to crates: it reads as a shipping frame and
1228        // keeps geometry simple rather than requiring a texture atlas. Strong
1229        // hits flash the frame (reduced flash disables this).
1230        for (index, body) in sandbox.bodies.iter().enumerate() {
1231            if body.ball || body.compound {
1232                continue;
1233            }
1234            let (position, rotation) = interpolated(body);
1235            let points = [
1236                vec3(-0.582, -0.582, -0.582),
1237                vec3(0.582, -0.582, -0.582),
1238                vec3(0.582, 0.582, -0.582),
1239                vec3(-0.582, 0.582, -0.582),
1240                vec3(-0.582, -0.582, 0.582),
1241                vec3(0.582, -0.582, 0.582),
1242                vec3(0.582, 0.582, 0.582),
1243                vec3(-0.582, 0.582, 0.582),
1244            ]
1245            .map(|v| position + rotation * v);
1246            let color = mix(
1247                Color::from_rgba(84, 64, 43, 255),
1248                Color::from_rgba(255, 236, 190, 255),
1249                juice.body_flash(index),
1250            );
1251            for (a, b) in [
1252                (0, 1),
1253                (1, 2),
1254                (2, 3),
1255                (3, 0),
1256                (4, 5),
1257                (5, 6),
1258                (6, 7),
1259                (7, 4),
1260                (0, 4),
1261                (1, 5),
1262                (2, 6),
1263                (3, 7),
1264            ] {
1265                draw_line_3d(points[a], points[b], color);
1266            }
1267        }
1268        for id in &sandbox.links {
1269            if let Some([a, b]) = sandbox.physics.joint_anchors(*id) {
1270                draw_line_3d(a, b, ui::CYAN);
1271            }
1272        }
1273        if !juice.particles.is_empty()
1274            && let Ok(billboard) = ferravex_render::effects::BillboardView::new(
1275                eye,
1276                (target - eye).cross(view.up),
1277                view.up,
1278            )
1279        {
1280            let _ = particles.draw_3d(
1281                &juice.particles,
1282                billboard,
1283                ferravex_render::effects::ParticleStyle::default(),
1284            );
1285        }
1286        set_default_camera();
1287        // Shockwaves ride the floor plane, projected for crisp glowing loops.
1288        hud::rings(
1289            &juice,
1290            presentation.pulse,
1291            presentation.policy.intensity(),
1292            view_proj,
1293        );
1294        if let Some((_, beat)) = juice.beat()
1295            && beat > 0.
1296        {
1297            // Cinematic letterbox for the collapse beat (motion only).
1298            let bar = 30. * beat;
1299            draw_rectangle(0., 44., screen_width(), bar, Color::new(0., 0., 0., 0.85));
1300            draw_rectangle(
1301                0.,
1302                panel.y - bar,
1303                screen_width(),
1304                bar,
1305                Color::new(0., 0., 0., 0.85),
1306            );
1307        }
1308        // Buttons act on the next frame, like the keyboard edges sampled above.
1309        let mut presses = [false; BUTTONS];
1310        let mut refused = [false; BUTTONS];
1311        for (i, tool) in tools.iter().enumerate() {
1312            let hit = tool.hovered && clicked;
1313            presses[i] = hit && tool.enabled;
1314            refused[i] = hit && !tool.enabled;
1315        }
1316        pending.crate_drop = presses[0];
1317        pending.ball_drop = presses[1];
1318        pending.drop = presses[2];
1319        pending.pulse = presses[3];
1320        pending.pause = presses[4];
1321        pending.step = presses[5];
1322        pending.view = presses[6];
1323        pending.reset = presses[7];
1324        pending.bowl = presses[8];
1325        pending.chaos = presses[9];
1326        if !active || card_closed || (hud.card.is_some() && clicked) {
1327            pending = Commands::default();
1328        } else {
1329            for i in 0..BUTTONS {
1330                if presses[i] {
1331                    hud.tool_kick(i);
1332                }
1333                if refused[i] {
1334                    hud.refuse(&lab, i);
1335                    sound.cue(Cue::Failure, 0.3);
1336                }
1337            }
1338        }
1339        hud.draw(&hud::Frame {
1340            lab: &lab,
1341            juice: &juice,
1342            bests: &bests,
1343            input: &player_input,
1344            panel,
1345            buttons,
1346            tools,
1347            view_proj,
1348            inspector: &inspector,
1349            active,
1350        });
1351        player_input.draw_settings();
1352        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1353        capture.end_frame();
1354        if demo.finish_frame() {
1355            break;
1356        }
1357        next_frame().await;
1358    }
1359}
1360
1361#[cfg(test)]
1362mod journey200_198;
1363#[cfg(test)]
1364mod journey200_tests;
1365
1366#[cfg(test)]
1367mod tests {
1368    use super::*;
1369
1370    #[test]
1371    fn pulse_waits_for_one_tick_and_reset_discards_pending_requests() {
1372        let mut lab = Lab::new();
1373        let before = poses(&lab);
1374        let mut edge = true;
1375        let frame = lab.advance_with_input(0., Commands::default(), || std::mem::take(&mut edge));
1376        assert!(edge, "zero-tick frames must not consume the gameplay edge");
1377        assert!(!frame.pulse);
1378        assert_eq!(poses(&lab), before);
1379        let frame =
1380            lab.advance_with_input(8. / 120., Commands::default(), || std::mem::take(&mut edge));
1381        assert!(frame.pulse);
1382        assert!(!edge);
1383        assert_eq!(lab.session.tick(), 8);
1384        assert!((lab.sandbox.pulse_time - (0.65 - 8. / 120.)).abs() < 1e-6);
1385        lab.advance(
1386            0.,
1387            Commands {
1388                pulse: true,
1389                ..Default::default()
1390            },
1391        );
1392        assert!(lab.pending_pulse, "footer input also survives zero ticks");
1393        let reset = lab.advance(
1394            0.,
1395            Commands {
1396                reset: true,
1397                ..Default::default()
1398            },
1399        );
1400        assert!(reset.reset);
1401        assert!(!lab.pending_pulse);
1402        assert!(!lab.advance(1. / 120., Commands::default()).pulse);
1403        assert_eq!(lab.sandbox.pulse_time, 0.);
1404    }
1405
1406    #[test]
1407    fn paused_step_preserves_fractional_time_and_live_inspector_counts() {
1408        let mut lab = Lab::new();
1409        lab.advance(0.5 / 120., Commands::default());
1410        lab.advance(
1411            0.,
1412            Commands {
1413                pause: true,
1414                ..Default::default()
1415            },
1416        );
1417        lab.advance(
1418            0.,
1419            Commands {
1420                drop: true,
1421                ..Default::default()
1422            },
1423        );
1424        let sleep = lab.sandbox.physics.sleep_stats();
1425        assert_eq!(sleep.awake_bodies + sleep.sleeping_bodies, 40);
1426        assert_eq!(lab.sandbox.physics.contacts().count(), 0);
1427        assert!(lab.sandbox.physics.contact_events().is_empty());
1428        lab.advance(
1429            50.,
1430            Commands {
1431                step: true,
1432                ..Default::default()
1433            },
1434        );
1435        assert_eq!(lab.session.tick(), 1);
1436        assert!(lab.session.is_paused());
1437        let contacts = lab.sandbox.physics.contacts().count();
1438        assert!(contacts > 0);
1439        let before = poses(&lab);
1440        lab.advance(10., Commands::default());
1441        assert_eq!(lab.sandbox.physics.contacts().count(), contacts);
1442        assert_eq!(poses(&lab), before);
1443        lab.advance(
1444            0.5 / 120.,
1445            Commands {
1446                pause: true,
1447                ..Default::default()
1448            },
1449        );
1450        assert_eq!(lab.session.tick(), 2);
1451        assert_eq!(lab.dropped_seconds, 0.);
1452    }
1453
1454    #[test]
1455    fn resume_before_next_tick_keeps_the_inspected_pose() {
1456        for manual_step in [false, true] {
1457            let mut lab = Lab::new();
1458            lab.advance(2.25 / 120., Commands::default());
1459            lab.advance(
1460                0.,
1461                Commands {
1462                    pause: true,
1463                    ..Default::default()
1464                },
1465            );
1466            if manual_step {
1467                lab.advance(
1468                    0.,
1469                    Commands {
1470                        step: true,
1471                        ..Default::default()
1472                    },
1473                );
1474            }
1475            let before = poses(&lab);
1476            let frame = lab.advance(
1477                0.,
1478                Commands {
1479                    pause: true,
1480                    ..Default::default()
1481                },
1482            );
1483            assert_eq!(poses(&lab), before);
1484            for body in &lab.sandbox.bodies {
1485                let rigid = &lab.sandbox.physics.bodies[body.handle];
1486                assert_eq!(body.previous_position, rigid.translation());
1487                assert_eq!(body.previous_rotation, *rigid.rotation());
1488                assert!(
1489                    body.previous_position
1490                        .lerp(rigid.translation(), frame.alpha)
1491                        .distance(rigid.translation())
1492                        < 1e-6
1493                );
1494            }
1495        }
1496    }
1497
1498    #[test]
1499    fn inspector_ray_reports_truncation_current_edits_and_misses_without_ticks() {
1500        let mut physics = PhysicsWorld::new([0.; 3]);
1501        let handles: Vec<_> = (1..=10)
1502            .map(|x| physics.add_ball([x as f32 * 2., 0., 0.], 0.4, true))
1503            .collect();
1504        let mut inspector = Inspector::new();
1505        inspector.sample(&physics, Vec3::ZERO, Vec3::X);
1506        assert_eq!((inspector.query.written, inspector.query.total), (8, 10));
1507        assert!(inspector.query.is_truncated());
1508        assert_eq!(inspector.hits[0].unwrap().body, Some(handles[0]));
1509        assert!((inspector.hits[0].unwrap().distance - 1.6).abs() < 1e-4);
1510        for handle in handles {
1511            assert!(physics.remove_body(handle));
1512        }
1513        inspector.sample(&physics, Vec3::ZERO, Vec3::X);
1514        assert_eq!(inspector.query.total, 0);
1515        assert!(inspector.hits.iter().all(Option::is_none));
1516        assert_eq!(
1517            physics.last_step.substeps, 0,
1518            "inspection must not step physics"
1519        );
1520    }
1521
1522    #[test]
1523    fn contact_sounds_exclude_free_fall_and_unrelated_joint_forces() {
1524        let mut sandbox = Sandbox::new();
1525        sandbox.physics = PhysicsWorld::new([0., -9.81, 0.]);
1526        sandbox.bodies.clear();
1527        sandbox.spawn(vec3(0., 100., 0.), true);
1528        let body = sandbox.bodies[0].handle;
1529        sandbox.physics.bodies[body].set_linvel(vec3(0., -10., 0.), true);
1530        for _ in 0..4 {
1531            sandbox.step(1. / 120.);
1532            assert!(sandbox.impact.is_none());
1533        }
1534        // A distance constraint causes a large velocity change without contact.
1535        let anchor = sandbox
1536            .physics
1537            .insert_body(RigidBodyBuilder::fixed().translation(vec3(0., 105., 0.)))
1538            .unwrap();
1539        sandbox
1540            .physics
1541            .insert_joint(anchor, body, JointBuilder::distance(1.))
1542            .unwrap();
1543        sandbox.step(1. / 120.);
1544        assert!(sandbox.physics.contact_events().is_empty());
1545        assert!(sandbox.impact.is_none());
1546    }
1547
1548    #[test]
1549    fn visual_policy_clears_existing_and_new_pulses_without_changing_physics() {
1550        let saved = preferences::feedback_policy();
1551        for (motion, flash) in [(true, false), (false, true), (true, true)] {
1552            preferences::set_feedback_policy(FeedbackPolicy::default());
1553            let mut presentation = Presentation::default();
1554            let mut lab = Lab::new();
1555            let frame = lab.advance(
1556                1. / 120.,
1557                Commands {
1558                    pulse: true,
1559                    ..Default::default()
1560                },
1561            );
1562            presentation.begin_frame(0.);
1563            presentation.accept(&frame, lab.sandbox.pulse_center);
1564            assert!(presentation.pulse.is_some());
1565            lab.advance(
1566                0.,
1567                Commands {
1568                    pause: true,
1569                    ..Default::default()
1570                },
1571            );
1572            let before = poses(&lab);
1573            let cooldown = lab.sandbox.pulse_time;
1574            preferences::set_feedback_policy(FeedbackPolicy::new(motion, flash, 1.).unwrap());
1575            presentation.begin_frame(0.); // Also the Controls / zero-tick path.
1576            assert!(presentation.pulse.is_none());
1577            presentation.accept(&frame, lab.sandbox.pulse_center);
1578            assert!(
1579                presentation.pulse.is_none(),
1580                "suppressed accepted events stay hidden"
1581            );
1582            preferences::set_feedback_policy(FeedbackPolicy::default());
1583            presentation.begin_frame(0.);
1584            assert!(presentation.pulse.is_none(), "old effects cannot revive");
1585            assert_eq!(poses(&lab), before);
1586            assert_eq!(lab.sandbox.pulse_time, cooldown);
1587            assert!(lab.session.is_paused());
1588            presentation.accept(&frame, lab.sandbox.pulse_center);
1589            for _ in 0..7 {
1590                presentation.begin_frame(0.1);
1591            }
1592            assert!(
1593                presentation.pulse.is_none(),
1594                "cosmetics expire even while physics is paused"
1595            );
1596            presentation.accept(&frame, lab.sandbox.pulse_center);
1597            let reset = lab.advance(
1598                0.,
1599                Commands {
1600                    reset: true,
1601                    ..Default::default()
1602                },
1603            );
1604            presentation.accept(&reset, lab.sandbox.pulse_center);
1605            assert!(presentation.pulse.is_none());
1606        }
1607        preferences::set_feedback_policy(saved);
1608    }
1609
1610    #[test]
1611    fn camera_inputs_are_finite_bounded_and_rate_independent() {
1612        let mut thirty = Orbit::default();
1613        let mut fast = Orbit::default();
1614        for _ in 0..30 {
1615            thirty.input(1. / 30., Vec2::ZERO, vec2(1., 0.), 0.);
1616        }
1617        for _ in 0..144 {
1618            fast.input(1. / 144., Vec2::ZERO, vec2(1., 0.), 0.);
1619        }
1620        assert!((thirty.yaw - fast.yaw).abs() < 1e-5);
1621        assert!(thirty.view(f32::NAN).position.is_finite());
1622        let before = (thirty.yaw, thirty.pitch, thirty.radius);
1623        thirty.input(0.1, vec2(f32::NAN, 0.), Vec2::ZERO, 0.);
1624        assert_eq!((thirty.yaw, thirty.pitch, thirty.radius), before);
1625        thirty.input(0.1, vec2(f32::MAX, f32::MAX), Vec2::ZERO, -f32::MAX);
1626        assert!((0. ..std::f32::consts::TAU).contains(&thirty.yaw));
1627        assert_eq!(thirty.pitch, 1.35);
1628        assert_eq!(thirty.radius, 42.);
1629        assert!(thirty.view(f32::INFINITY).position.is_finite());
1630    }
1631
1632    #[test]
1633    fn remapped_hints_use_current_binding_and_bounded_fallback() {
1634        let mut input = PlayerInput::transient("journey200-143-hints");
1635        input
1636            .action(
1637                "step",
1638                "Step",
1639                ActionKind::Button,
1640                vec![Binding::digital(InputCode::Key(KeyCode::N as u16))],
1641            )
1642            .unwrap();
1643        let mut buffer = [0; 128];
1644        assert_eq!(binding_hint(&input, "step", &mut buffer), "N");
1645        input
1646            .rebind(
1647                "step",
1648                vec![Binding::digital(InputCode::Key(KeyCode::J as u16))],
1649            )
1650            .unwrap();
1651        assert_eq!(binding_hint(&input, "step", &mut buffer), "J");
1652        assert_eq!(binding_hint(&input, "step", &mut []), "Controls");
1653        assert_eq!(binding_hint(&input, "missing", &mut buffer), "Controls");
1654    }
1655
1656    #[test]
1657    fn player_pulse_tap_survives_zero_tick_frame_and_menu_cancels_it() {
1658        use ferravex_render::input::{PadState, gamepad_sample, host_frame};
1659        let mut input = PlayerInput::transient("journey200-143-pulse");
1660        input
1661            .action(
1662                "pulse",
1663                "Impulse pulse",
1664                ActionKind::Button,
1665                vec![Binding::digital(InputCode::PadButton(4))],
1666            )
1667            .unwrap();
1668        let mut pad = PadState {
1669            connected: true,
1670            ..Default::default()
1671        };
1672        assert!(gamepad_sample(0, pad));
1673        host_frame(0., 640, 480, || input.sample(true));
1674        pad.buttons[4] = 1.;
1675        assert!(gamepad_sample(0, pad));
1676        pad.buttons[4] = 0.;
1677        assert!(gamepad_sample(0, pad));
1678        let mut lab = Lab::new();
1679        host_frame(0., 640, 480, || {
1680            input.sample(true);
1681            let frame = lab.advance_with_input(0., Commands::default(), || {
1682                input.take_tick(["pulse"])[0].pressed
1683            });
1684            assert!(!frame.pulse);
1685        });
1686        host_frame(0.05, 640, 480, || {
1687            input.sample(true);
1688            let frame = lab.advance_with_input(0.05, Commands::default(), || {
1689                input.take_tick(["pulse"])[0].pressed
1690            });
1691            assert!(frame.pulse);
1692        });
1693        assert_eq!(lab.session.tick(), 6);
1694        assert!((lab.sandbox.pulse_time - 0.6).abs() < 1e-6);
1695        lab.reset();
1696        pad.buttons[4] = 1.;
1697        assert!(gamepad_sample(0, pad));
1698        pad.buttons[4] = 0.;
1699        assert!(gamepad_sample(0, pad));
1700        host_frame(0., 640, 480, || input.sample(true));
1701        host_frame(0., 640, 480, || input.sample(false));
1702        host_frame(1. / 120., 640, 480, || {
1703            input.sample(true);
1704            let frame = lab.advance_with_input(1. / 120., Commands::default(), || {
1705                input.take_tick(["pulse"])[0].pressed
1706            });
1707            assert!(!frame.pulse, "menu transition discards the pending tap");
1708        });
1709        assert!(gamepad_sample(0, PadState::default()));
1710    }
1711
1712    fn poses(lab: &Lab) -> Vec<(Vec3, Vec3, Quat)> {
1713        lab.sandbox
1714            .bodies
1715            .iter()
1716            .map(|body| {
1717                let rigid = &lab.sandbox.physics.bodies[body.handle];
1718                (rigid.translation(), rigid.linvel(), *rigid.rotation())
1719            })
1720            .collect()
1721    }
1722
1723    #[test]
1724    fn session_autoplays_and_paused_time_never_catches_up() {
1725        let mut lab = Lab::new();
1726        assert!(lab.session.is_playing());
1727        lab.advance(1. / 60., Commands::default());
1728        assert_eq!(lab.session.tick(), 2);
1729        lab.advance(
1730            0.,
1731            Commands {
1732                pause: true,
1733                ..Default::default()
1734            },
1735        );
1736        let paused = poses(&lab);
1737        let frame = lab.advance(3600., Commands::default());
1738        assert_eq!(poses(&lab), paused);
1739        assert_eq!(lab.session.tick(), 2);
1740        assert_eq!(frame.alpha, 1.);
1741        assert!(frame.impact.is_none());
1742        lab.advance(
1743            1. / 120.,
1744            Commands {
1745                pause: true,
1746                ..Default::default()
1747            },
1748        );
1749        assert_eq!(lab.session.tick(), 3);
1750    }
1751
1752    #[test]
1753    fn manual_step_advances_exactly_one_tick_and_remains_paused() {
1754        let mut lab = Lab::new();
1755        lab.advance(
1756            0.,
1757            Commands {
1758                pause: true,
1759                ball_drop: true,
1760                ..Default::default()
1761            },
1762        );
1763        let body = lab.sandbox.bodies.last().unwrap().handle;
1764        assert_eq!(lab.sandbox.physics.bodies[body].translation().y, 10.);
1765        let frame = lab.advance(
1766            60.,
1767            Commands {
1768                step: true,
1769                ..Default::default()
1770            },
1771        );
1772        assert!(lab.session.is_paused());
1773        assert_eq!(lab.session.tick(), 1);
1774        assert_eq!(frame.alpha, 1.);
1775        assert!(lab.sandbox.physics.bodies[body].translation().y < 10.);
1776        assert!((lab.sandbox.physics.bodies[body].linvel().y + 9.81 / 120.).abs() < 0.001);
1777        let after = poses(&lab);
1778        lab.advance(60., Commands::default());
1779        assert_eq!(poses(&lab), after);
1780        lab.advance(
1781            0.,
1782            Commands {
1783                pause: true,
1784                step: true,
1785                ..Default::default()
1786            },
1787        );
1788        assert_eq!(lab.session.tick(), 1, "STEP must not add a running tick");
1789    }
1790
1791    #[test]
1792    fn reset_restores_world_view_clock_and_feedback_even_when_paused() {
1793        let mut lab = Lab::new();
1794        let home = lab.orbit.view(1. / 60.);
1795        lab.advance(
1796            0.02,
1797            Commands {
1798                ball_drop: true,
1799                pulse: true,
1800                ..Default::default()
1801            },
1802        );
1803        lab.orbit.yaw = -1.4;
1804        lab.orbit.pitch = 1.;
1805        lab.orbit.radius = 40.;
1806        lab.orbit.view(1. / 60.);
1807        lab.advance(
1808            0.,
1809            Commands {
1810                pause: true,
1811                ..Default::default()
1812            },
1813        );
1814        lab.impact_cooldown = 0.05;
1815        let frame = lab.advance(
1816            1.,
1817            Commands {
1818                reset: true,
1819                ball_drop: true,
1820                step: true,
1821                pulse: true,
1822                ..Default::default()
1823            },
1824        );
1825        let fresh = Lab::new();
1826        assert_eq!(poses(&lab), poses(&fresh));
1827        assert_eq!(lab.shape, DropShape::Crate);
1828        assert!(lab.session.is_playing());
1829        assert_eq!(lab.session.tick(), 0);
1830        assert_eq!(lab.sandbox.sequence, 0);
1831        assert_eq!(lab.sandbox.pulse_time, 0.);
1832        assert_eq!(lab.impact_cooldown, 0.);
1833        assert!(frame.impact.is_none() && !frame.pulse);
1834        assert_eq!(
1835            lab.orbit.view(0.),
1836            home,
1837            "camera must snap, not ease from the old view"
1838        );
1839        assert_eq!(lab.notice, Notice::Rebuilt);
1840        lab.advance(0.5 / 120., Commands::default());
1841        assert_eq!(lab.session.tick(), 0, "old fractional time must be cleared");
1842    }
1843
1844    #[test]
1845    fn view_reset_does_not_change_paused_physics_or_shape() {
1846        let mut lab = Lab::new();
1847        let home = lab.orbit.view(0.);
1848        lab.advance(
1849            0.,
1850            Commands {
1851                ball_drop: true,
1852                pause: true,
1853                ..Default::default()
1854            },
1855        );
1856        let before = poses(&lab);
1857        lab.orbit.yaw = 2.;
1858        lab.orbit.radius = 12.;
1859        lab.orbit.view(0.1);
1860        lab.advance(
1861            30.,
1862            Commands {
1863                view: true,
1864                ..Default::default()
1865            },
1866        );
1867        assert_eq!(lab.orbit.view(0.), home);
1868        assert_eq!(poses(&lab), before);
1869        assert_eq!(lab.shape, DropShape::Ball);
1870        assert!(lab.session.is_paused());
1871    }
1872
1873    #[test]
1874    fn drop_selection_is_repeated_once_and_limit_reports_rejection() {
1875        let mut lab = Lab::new();
1876        lab.advance(
1877            0.,
1878            Commands {
1879                ball_drop: true,
1880                drop: true,
1881                ..Default::default()
1882            },
1883        );
1884        assert_eq!(lab.sandbox.bodies.len(), 40, "combined inputs drop once");
1885        assert!(lab.sandbox.bodies.last().unwrap().ball);
1886        lab.advance(
1887            8. / 120.,
1888            Commands {
1889                drop: true,
1890                ..Default::default()
1891            },
1892        );
1893        assert_eq!(
1894            lab.sandbox.bodies.len(),
1895            41,
1896            "catch-up must not repeat the input edge"
1897        );
1898        assert!(lab.sandbox.bodies.last().unwrap().ball);
1899        lab.advance(
1900            0.,
1901            Commands {
1902                pause: true,
1903                crate_drop: true,
1904                ..Default::default()
1905            },
1906        );
1907        assert_eq!(lab.shape, DropShape::Crate);
1908        assert!(!lab.sandbox.bodies.last().unwrap().ball);
1909        for _ in 0..MAX_BODIES {
1910            lab.advance(
1911                0.,
1912                Commands {
1913                    drop: true,
1914                    ..Default::default()
1915                },
1916            );
1917        }
1918        assert_eq!(lab.sandbox.bodies.len(), MAX_BODIES);
1919        let sequence = lab.sandbox.sequence;
1920        lab.advance(
1921            0.,
1922            Commands {
1923                drop: true,
1924                ..Default::default()
1925            },
1926        );
1927        assert_eq!(lab.sandbox.sequence, sequence);
1928        assert_eq!(lab.notice, Notice::DropFull);
1929        let before = poses(&lab);
1930        let frame = lab.advance(
1931            0.,
1932            Commands {
1933                pulse: true,
1934                ..Default::default()
1935            },
1936        );
1937        assert!(!frame.pulse);
1938        assert_eq!(poses(&lab), before);
1939    }
1940
1941    #[test]
1942    fn autoplay_fixed_physics_matches_across_render_rates() {
1943        let mut sixty = Lab::new();
1944        let mut thirty = Lab::new();
1945        for _ in 0..60 {
1946            sixty.advance(1. / 60., Commands::default());
1947        }
1948        for _ in 0..30 {
1949            thirty.advance(1. / 30., Commands::default());
1950        }
1951        assert_eq!(sixty.session.tick(), 120);
1952        assert_eq!(thirty.session.tick(), 120);
1953        assert_eq!(poses(&sixty), poses(&thirty));
1954        let before = sixty.session.tick();
1955        sixty.advance(100., Commands::default());
1956        assert_eq!(sixty.session.tick() - before, 8, "catch-up remains bounded");
1957    }
1958
1959    #[test]
1960    fn footer_buttons_fit_narrow_and_wide_viewports_without_overlap() {
1961        for (width, height) in [(320., 480.), (640., 360.), (1280., 720.)] {
1962            let (panel, buttons) = footer_layout(width, height);
1963            assert!(panel.y >= 104.);
1964            for (i, button) in buttons.iter().enumerate() {
1965                assert!(button.w >= 50. && button.h >= 36.);
1966                assert!(button.x >= panel.x && button.x + button.w <= panel.x + panel.w);
1967                assert!(button.y >= panel.y && button.y + button.h <= panel.y + panel.h);
1968                for other in &buttons[i + 1..] {
1969                    assert!(
1970                        button.x + button.w <= other.x
1971                            || other.x + other.w <= button.x
1972                            || button.y + button.h <= other.y
1973                            || other.y + other.h <= button.y
1974                    );
1975                }
1976            }
1977        }
1978    }
1979
1980    #[test]
1981    fn ten_grouped_buttons_stay_readable_and_leave_scene_room() {
1982        let labels = [
1983            "Crate", "Ball", "Drop", "Pulse", "Resume", "Step", "View", "Reset", "Bowl", "Chaos",
1984        ];
1985        for (width, height) in [
1986            (296., 640.),
1987            (369., 640.),
1988            (370., 640.),
1989            (539., 700.),
1990            (540., 400.),
1991            (899., 600.),
1992            (900., 600.),
1993            (1280., 800.),
1994            (1600., 1000.),
1995        ] {
1996            let (panel, buttons) = footer_layout(width, height);
1997            assert!(scene_rect(width, panel).h >= 190., "{width}x{height}");
1998            for (i, button) in buttons.iter().enumerate() {
1999                assert!(button.x >= panel.x + 12. - 0.01);
2000                assert!(
2001                    button.x + button.w <= panel.x + panel.w - 12. + 0.01,
2002                    "{width}: {i}"
2003                );
2004                // The status row of icon readouts sits above every button.
2005                assert!(
2006                    button.y >= panel.y + hud::STATUS_ROW - 4.
2007                        && button.y + button.h <= panel.y + panel.h
2008                );
2009                let measured = get_default_font()
2010                    .try_metrics(17, 1.)
2011                    .unwrap()
2012                    .measure_line(labels[i])
2013                    .unwrap()
2014                    .width;
2015                let size = 17. * ((button.w - 12.) / measured).min(1.);
2016                assert!(size >= 14., "{width}: {} at {size}", labels[i]);
2017                for other in &buttons[i + 1..] {
2018                    assert!(
2019                        button.x + button.w <= other.x
2020                            || other.x + other.w <= button.x
2021                            || button.y + button.h <= other.y
2022                            || other.y + other.h <= button.y
2023                    );
2024                }
2025            }
2026        }
2027    }
2028
2029    #[test]
2030    fn procedural_stair_render_and_collision_share_dimensions() {
2031        let s = Sandbox::new();
2032        let (mesh, p) = &s.terrain[5];
2033        assert_eq!(mesh.mesh.vertices.len(), 24);
2034        let origin = p.center + Vec3::Y * 5.;
2035        let hit = s
2036            .physics
2037            .raycast(origin.to_array(), (-Vec3::Y).to_array(), 10.)
2038            .unwrap();
2039        assert!((hit.distance - (5. - p.half_extents.y)).abs() < 0.01);
2040    }
2041    #[test]
2042    fn pulse_wakes_and_lifts_props_and_cannot_be_spammed() {
2043        let mut sandbox = Sandbox::new();
2044        assert!(sandbox.pulse(vec3(0., 0.5, 0.)));
2045        assert!(
2046            sandbox
2047                .bodies
2048                .iter()
2049                .any(|body| sandbox.physics.bodies[body.handle].linvel().y > 0.1)
2050        );
2051        let velocities: Vec<_> = sandbox
2052            .bodies
2053            .iter()
2054            .map(|body| sandbox.physics.bodies[body.handle].linvel())
2055            .collect();
2056        assert!(!sandbox.pulse(vec3(0., 0.5, 0.)));
2057        for (body, velocity) in sandbox.bodies.iter().zip(velocities) {
2058            assert_eq!(sandbox.physics.bodies[body.handle].linvel(), velocity);
2059        }
2060        for _ in 0..80 {
2061            sandbox.step(1. / 120.);
2062        }
2063        assert!(sandbox.pulse(vec3(0., 0.5, 0.)));
2064    }
2065
2066    #[test]
2067    fn falling_bodies_produce_bounded_impact_hints() {
2068        let mut sandbox = Sandbox::new();
2069        let mut found = false;
2070        for _ in 0..360 {
2071            sandbox.step(1. / 120.);
2072            if let Some((strength, _)) = sandbox.impact {
2073                assert!(strength.is_finite() && strength > 1.2);
2074                found = true;
2075            }
2076        }
2077        assert!(found);
2078    }
2079    #[test]
2080    fn jointed_mechanisms_keep_their_constraints_under_load() {
2081        let mut sandbox = Sandbox::new();
2082        for _ in 0..1200 {
2083            sandbox.step(1. / 120.);
2084        }
2085        assert_eq!(sandbox.links.len(), 4);
2086        for &id in &sandbox.links {
2087            let joint = &sandbox.physics.joints[id];
2088            let [a, b] = sandbox.physics.joint_anchors(id).unwrap();
2089            match joint.description().kind {
2090                ferravex_physics::JointKind::Distance { length } => {
2091                    assert!((a.distance(b) - length).abs() < 0.005)
2092                }
2093                ferravex_physics::JointKind::Spring {
2094                    length, stiffness, ..
2095                } => {
2096                    let body = joint.bodies()[1];
2097                    let extension = sandbox.physics.bodies[body].mass() * 9.81 / stiffness;
2098                    assert!((a.distance(b) - length - extension).abs() < 0.025);
2099                }
2100                _ => assert!(a.distance(b) < 0.005),
2101            }
2102        }
2103    }
2104
2105    #[test]
2106    fn recovered_sandbox_settles_without_floor_tunneling() {
2107        let mut sandbox = Sandbox::new();
2108        for _ in 0..960 {
2109            sandbox.step(1.0 / 120.0);
2110            for body in &sandbox.bodies {
2111                let rigid = &sandbox.physics.bodies[body.handle];
2112                assert!(rigid.translation().is_finite());
2113                assert!(rigid.linvel().is_finite());
2114                assert!(rigid.rotation().is_finite());
2115                assert!(rigid.translation().y > 0.3);
2116            }
2117        }
2118        assert!(
2119            sandbox
2120                .bodies
2121                .iter()
2122                .any(|body| sandbox.physics.bodies[body.handle].is_sleeping())
2123        );
2124    }
2125
2126    #[test]
2127    fn dropping_is_bounded_and_rebuild_replaces_the_world() {
2128        let mut sandbox = Sandbox::new();
2129        for i in 0..MAX_BODIES + 10 {
2130            sandbox.drop_body(i % 2 == 0);
2131        }
2132        assert_eq!(sandbox.bodies.len(), MAX_BODIES);
2133        assert_eq!(
2134            sandbox.physics.bodies.len(),
2135            MAX_BODIES + 12 + sandbox.terrain.len()
2136        );
2137        sandbox = Sandbox::new();
2138        assert_eq!(sandbox.bodies.len(), 39);
2139        assert_eq!(sandbox.physics.bodies.len(), 51 + sandbox.terrain.len());
2140    }
2141}