siege_foundry/
lib.rs

1//! A compact destruction range: all knockdowns come from rigid-body contacts.
2//!
3//! The host uses a shared session to gate fixed physics ticks. Starting or
4//! rebuilding never fires a shot; only a fresh Fire edge can spend ammunition.
5//!
6//! ```
7//! use ferravex_core::session::{GameSession, SessionState};
8//! let mut session = GameSession::new(120.0, 12, false);
9//! assert!(session.start());
10//! let frame = session.advance(1.0 / 60.0);
11//! assert_eq!(frame.steps, 2);
12//! assert!(session.finish(true));
13//! assert_eq!(session.state(), SessionState::Won);
14//! assert_eq!(session.advance(1.0).steps, 0);
15//! session.restart(); // The host also rebuilds bodies, ammunition and feedback.
16//! assert_eq!(session.tick(), 0);
17//! ```
18mod atmosphere;
19#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
20mod capture;
21mod glyph;
22mod hud;
23mod juice;
24mod quips;
25mod score;
26
27use ferravex_core::session::{GameSession, SessionState};
28use ferravex_physics::d3::{
29    ColliderBuilder, PhysicsWorld, RigidBodyBuilder, RigidBodyHandle, Vector,
30};
31use ferravex_render::audio::{Cue, GameAudio, Surface};
32use ferravex_render::input::{
33    HintDevice, PlayerInput, Preset,
34    touch::{Control, Output, Region},
35};
36use ferravex_render::{
37    demo::Demo,
38    mesh::Mesh3d,
39    preferences,
40    prelude::*,
41    shaders::{LitMaterial, LitSettings},
42};
43use juice::{Juice, Material};
44use quips::{Banter, Mood};
45use score::{Callout, Events, RangeEvent, Tally};
46
47#[cfg(test)]
48const DT: f32 = 1.0 / 120.0;
49const AMMO: u8 = 8;
50const GOAL: usize = 6;
51const SPEED: f32 = 28.0;
52const RELOAD: f32 = 0.8;
53const SETTLE: f32 = 6.0;
54const PIVOT: Vec3 = Vec3::new(0.0, 1.3, 15.0);
55const INK: Color = Color::from_rgba(34, 40, 39, 255);
56const PAPER: Color = Color::from_rgba(246, 235, 211, 255);
57const RUST: Color = Color::from_rgba(176, 86, 48, 255);
58const SAND: Color = Color::from_rgba(194, 169, 124, 255);
59const STEEL: Color = Color::from_rgba(65, 81, 78, 255);
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62enum Phase {
63    Aiming,
64    Won,
65    Lost,
66}
67
68struct Block {
69    handle: RigidBodyHandle,
70    home: Vec3,
71    target: bool,
72    down: bool,
73    previous_position: Vec3,
74    previous_rotation: Quat,
75}
76
77struct Shot {
78    handle: RigidBodyHandle,
79    previous_position: Vec3,
80    /// Velocity after the previous tick; a sharp change is a reported impact.
81    velocity: Vec3,
82    impacts: u8,
83}
84
85struct Range {
86    physics: PhysicsWorld,
87    blocks: Vec<Block>,
88    shots: Vec<Shot>,
89    yaw: f32,
90    elevation: f32,
91    ammo: u8,
92    cooldown: f32,
93    since_shot: f32,
94    elapsed: f32,
95    phase: Phase,
96    preview: Vec<Vec3>,
97    preview_hit: Option<Vec3>,
98    preview_aim: (u32, u32),
99    /// Demolition score, fed only by accepted ticks and shots.
100    tally: Tally,
101    /// Accepted events from the latest fire/step, drained by the session host.
102    events: Events,
103}
104
105impl Range {
106    fn new() -> Self {
107        let mut physics = PhysicsWorld::new([0.0, -9.81, 0.0]);
108        physics.add_box([0.0, -0.4, 4.0], [14.0, 0.4, 20.0], false);
109        let mut blocks = Vec::new();
110        for x in [-4.0, 0.0, 4.0] {
111            let mut previous = None;
112            for layer in 0..4 {
113                let home = vec3(x, 0.6 + layer as f32 * 1.202, -4.0);
114                let (handle, _) = physics.insert(
115                    RigidBodyBuilder::dynamic()
116                        .translation(Vector::from_array(home.to_array()))
117                        .linear_damping(0.12)
118                        .angular_damping(0.18)
119                        .ccd_enabled(true),
120                    ColliderBuilder::cuboid(0.6, 0.6, 0.6)
121                        .density(0.85)
122                        .friction(0.55)
123                        .restitution(0.025),
124                );
125                if let Some(a) = previous {
126                    physics
127                        .insert_joint(
128                            a,
129                            handle,
130                            ferravex_physics::d3::JointBuilder::fixed()
131                                .local_anchor1(Vec3::Y * 0.601)
132                                .local_anchor2(-Vec3::Y * 0.601)
133                                .break_limits(500., 80.),
134                        )
135                        .unwrap();
136                }
137                previous = Some(handle);
138                blocks.push(Block {
139                    handle,
140                    home,
141                    target: layer >= 2,
142                    down: false,
143                    previous_position: home,
144                    previous_rotation: Quat::IDENTITY,
145                });
146            }
147        }
148        Self {
149            physics,
150            blocks,
151            shots: Vec::with_capacity(AMMO as usize),
152            yaw: 0.0,
153            elevation: 0.13,
154            ammo: AMMO,
155            cooldown: 0.0,
156            since_shot: 0.0,
157            elapsed: 0.0,
158            phase: Phase::Aiming,
159            preview: Vec::with_capacity(45),
160            preview_hit: None,
161            preview_aim: (u32::MAX, u32::MAX),
162            tally: Tally::default(),
163            events: Events::new(),
164        }
165    }
166
167    /// The nearest block whose cube is touched by a ball centred at `point`
168    /// (the preview reports the ball's centre at first contact).
169    fn block_at(&self, point: Vec3) -> Option<&Block> {
170        self.blocks
171            .iter()
172            .filter_map(|block| {
173                let body = &self.physics.bodies[block.handle];
174                let center = Vec3::from_array(body.translation().to_array());
175                let rotation = Quat::from_array(body.rotation().to_array());
176                let local = (rotation.inverse() * (point - center)).abs();
177                (local.max_element() < 1.0).then_some((block, local.length()))
178            })
179            .min_by(|a, b| a.1.total_cmp(&b.1))
180            .map(|(block, _)| block)
181    }
182
183    fn refresh_preview(&mut self, simulated: bool) {
184        if self.cooldown > 0. {
185            return;
186        }
187        let aim = (self.yaw.to_bits(), self.elevation.to_bits());
188        let moving = simulated
189            && (self.blocks.iter().any(|block| {
190                let body = &self.physics.bodies[block.handle];
191                Vec3::from_array(body.translation().to_array()) != block.previous_position
192                    || Quat::from_array(body.rotation().to_array()) != block.previous_rotation
193            }) || self.shots.iter().any(|shot| {
194                Vec3::from_array(self.physics.bodies[shot.handle].translation().to_array())
195                    != shot.previous_position
196            }));
197        if aim == self.preview_aim && !moving {
198            return;
199        }
200        self.preview_aim = aim;
201        self.preview.clear();
202        self.preview_hit = None;
203        let direction = self.direction();
204        let start = PIVOT + direction * 1.6;
205        self.preview.push(start);
206        for i in 1..=44 {
207            let t = i as f32 * 0.035;
208            let next = start + direction * SPEED * t - Vec3::Y * (4.905 * t * t);
209            let previous = *self.preview.last().unwrap();
210            let delta = next - previous;
211            if let Some(hit) = self.physics.spherecast(
212                previous.to_array(),
213                delta.to_array(),
214                delta.length(),
215                0.36,
216                u32::MAX,
217                None,
218            ) {
219                let point = Vec3::from_array(hit.point);
220                self.preview.push(point);
221                self.preview_hit = Some(point);
222                break;
223            }
224            self.preview.push(next);
225        }
226    }
227
228    fn direction(&self) -> Vec3 {
229        vec3(
230            self.yaw.sin() * self.elevation.cos(),
231            self.elevation.sin(),
232            -self.yaw.cos() * self.elevation.cos(),
233        )
234    }
235
236    fn score(&self) -> usize {
237        self.blocks.iter().filter(|b| b.target && b.down).count()
238    }
239
240    fn fire(&mut self) -> bool {
241        if !self.can_fire() {
242            return false;
243        }
244        let direction = self.direction();
245        let muzzle = PIVOT + direction * 1.6;
246        let (handle, _) = self.physics.insert(
247            RigidBodyBuilder::dynamic()
248                .translation(Vector::from_array(muzzle.to_array()))
249                .linvel(Vector::from_array((direction * SPEED).to_array()))
250                .ccd_enabled(true),
251            ColliderBuilder::ball(0.36)
252                .density(18.0)
253                .friction(0.6)
254                .restitution(0.08),
255        );
256        self.shots.push(Shot {
257            handle,
258            previous_position: muzzle,
259            velocity: direction * SPEED,
260            impacts: 0,
261        });
262        self.ammo -= 1;
263        self.cooldown = RELOAD;
264        self.since_shot = 0.0;
265        let cleared = (0..score::COLUMNS)
266            .filter(|column| self.blocks[column * 4 + 2].down && self.blocks[column * 4 + 3].down)
267            .fold(0, |mask, column| mask | 1 << column);
268        self.tally.fired(cleared, &mut self.events);
269        self.events.push(RangeEvent::Fired {
270            muzzle,
271            direction,
272            last: self.ammo == 0,
273        });
274        true
275    }
276
277    fn can_fire(&self) -> bool {
278        self.phase == Phase::Aiming && self.cooldown <= 0.0 && self.ammo > 0
279    }
280
281    fn step(&mut self, dt: f32) {
282        // A result is final: late debris must not change a loss into a win.
283        if self.phase != Phase::Aiming {
284            return;
285        }
286        self.elapsed += dt;
287        self.since_shot += dt;
288        self.cooldown = (self.cooldown - dt).max(0.0);
289        for block in &mut self.blocks {
290            let body = &self.physics.bodies[block.handle];
291            block.previous_position = Vec3::from_array(body.translation().to_array());
292            block.previous_rotation = Quat::from_array(body.rotation().to_array());
293        }
294        for shot in &mut self.shots {
295            shot.previous_position =
296                Vec3::from_array(self.physics.bodies[shot.handle].translation().to_array());
297        }
298        self.physics.step(dt);
299        for shot in &mut self.shots {
300            let body = &self.physics.bodies[shot.handle];
301            let position = Vec3::from_array(body.translation().to_array());
302            let velocity = Vec3::from_array(body.linvel().to_array());
303            let change = (velocity - shot.velocity).length();
304            if change > 6.0 && shot.impacts < 3 {
305                shot.impacts += 1;
306                self.events.push(RangeEvent::Impact {
307                    at: position,
308                    strength: change,
309                });
310            }
311            shot.velocity = velocity;
312            if position.distance(score::BELL) < score::BELL_RADIUS {
313                self.tally.bell(score::BELL, &mut self.events);
314            }
315        }
316        // Every block can be knocked down for points; only targets count
317        // toward the win. Blocks are stored tower by tower, bottom to top.
318        let mut down: [bool; 12] = std::array::from_fn(|i| self.blocks[i].down);
319        let mut fallen = [0_usize; 12];
320        let mut count = 0;
321        for (index, block) in self.blocks.iter_mut().enumerate() {
322            if block.down {
323                continue;
324            }
325            let body = &self.physics.bodies[block.handle];
326            let p = Vec3::from_array(body.translation().to_array());
327            let rotation = Quat::from_array(body.rotation().to_array());
328            let up = (rotation * Vec3::Y).y;
329            block.down = p.distance(block.home) > 1.3 || p.y < block.home.y - 0.75 || up < 0.45;
330            if block.down {
331                fallen[count] = index;
332                count += 1;
333            } else if index % 4 == 3 && (up < 0.985 || p.distance(block.home) > 0.25) {
334                self.tally.wobble(index / 4, p, &mut self.events);
335            }
336        }
337        for &index in &fallen[..count] {
338            down[index] = true;
339            let column = index / 4;
340            let block = &self.blocks[index];
341            let at = Vec3::from_array(self.physics.bodies[block.handle].translation().to_array());
342            let tower = [0, 1, 2, 3].map(|layer| down[column * 4 + layer]);
343            self.tally
344                .knocked(column, block.target, at, tower, &mut self.events);
345        }
346        self.tally.tick(self.since_shot, &mut self.events);
347        if self.score() == GOAL {
348            self.phase = Phase::Won;
349            self.tally
350                .won(self.ammo, vec3(0.0, 2.4, -4.0), &mut self.events);
351        } else if self.ammo == 0 && self.since_shot > SETTLE {
352            self.phase = Phase::Lost;
353        }
354    }
355
356    /// A physical low arc from the barrel muzzle to a selected point.
357    fn aim_at(&mut self, point: Vec3) {
358        let delta = point - PIVOT;
359        self.yaw = delta.x.atan2(-delta.z);
360        let distance = vec2(delta.x, delta.z).length();
361        let mut low: f32 = 0.025;
362        let mut high: f32 = 0.7;
363        for _ in 0..24 {
364            let angle = (low + high) * 0.5;
365            let time = (distance - 1.6 * angle.cos()) / (SPEED * angle.cos());
366            let height = PIVOT.y + distance * angle.tan() - 4.905 * time * time;
367            if height < point.y {
368                low = angle;
369            } else {
370                high = angle;
371            }
372        }
373        self.elevation = (low + high) * 0.5;
374    }
375
376    /// Autoplay chooses the next standing tower and uses the same fire operation.
377    fn autoplay(&mut self) -> bool {
378        if self.phase != Phase::Aiming || self.elapsed < 0.7 || self.since_shot < 2.0 {
379            return false;
380        }
381        if let Some(target) = self.blocks.iter().find(|b| b.target && !b.down) {
382            self.aim_at(vec3(target.home.x, 1.8, target.home.z));
383            true
384        } else {
385            false
386        }
387    }
388}
389
390#[derive(Default)]
391struct Feedback {
392    shot: f32,
393    destruction: f32,
394    knocked_down: usize,
395    rebuilt: f32,
396    recoil: f32,
397    motion_scale: f32,
398}
399
400impl Feedback {
401    fn sync_preferences(&mut self) {
402        let policy = preferences::feedback_policy();
403        self.apply_motion(policy.reduced_motion(), policy.intensity());
404        // This range has no flash, camera shake or particle channels. Static
405        // confirmations and target colors remain visible under either policy.
406    }
407
408    fn apply_motion(&mut self, reduced: bool, intensity: f32) {
409        self.motion_scale = if reduced { 0.0 } else { intensity };
410        if self.motion_scale == 0.0 {
411            // Forget the old pose impulse, including during paused/zero ticks.
412            self.recoil = 0.0;
413        }
414    }
415
416    fn accepted_shot(&mut self) {
417        self.shot = 1.0;
418        self.rebuilt = 0.0;
419        self.recoil = if self.motion_scale > 0.0 { 0.3 } else { 0.0 };
420    }
421
422    fn barrel_offset(&self) -> f32 {
423        self.recoil * self.motion_scale
424    }
425
426    fn step(&mut self, dt: f32) {
427        self.shot = (self.shot - dt).max(0.0);
428        self.destruction = (self.destruction - dt).max(0.0);
429        self.rebuilt = (self.rebuilt - dt).max(0.0);
430        self.recoil = (self.recoil - dt * 1.2).max(0.0);
431    }
432}
433
434#[derive(Default)]
435struct FrameFeedback {
436    alpha: f32,
437    fired: bool,
438    destroyed: usize,
439    outcome: Option<Phase>,
440    /// Sandstone supports knocked down this frame.
441    loosened: usize,
442    impacts: usize,
443    wobbled: bool,
444    /// The most important callout this frame, for audio.
445    callout: Option<Callout>,
446}
447
448#[derive(Default)]
449struct TickInput {
450    fire: bool,
451    aim: Vec2,
452}
453
454/// Session host shared by interactive play and headless tests. Presentation
455/// policy is read here, outside the range's fixed physics and gameplay rules.
456struct Foundry {
457    range: Range,
458    session: GameSession,
459    pending_fire: bool,
460    feedback: Feedback,
461    juice: Juice,
462    /// Foreman Gus's line counters; kept across rebuilds so retries vary.
463    banter: Banter,
464    /// Debug capture only: replaces autoplay's next aim. Always `None` in play.
465    scripted_aim: Option<(f32, f32)>,
466}
467
468impl Foundry {
469    fn new(autoplay: bool) -> Self {
470        let mut foundry = Self {
471            range: Range::new(),
472            session: GameSession::new(120.0, 12, autoplay),
473            pending_fire: false,
474            feedback: Feedback::default(),
475            juice: Juice::new(),
476            banter: Banter::default(),
477            scripted_aim: None,
478        };
479        if foundry.session.is_playing() {
480            // Autoplay sessions start themselves; Gus still says hello.
481            foundry.juice.say(&mut foundry.banter, Mood::Start);
482        }
483        foundry
484    }
485
486    fn start(&mut self) -> bool {
487        let started = self.session.start();
488        if started {
489            self.juice.say(&mut self.banter, Mood::Start);
490        }
491        started
492    }
493
494    fn rebuild(&mut self) {
495        self.range = Range::new();
496        self.session.restart();
497        self.pending_fire = false;
498        self.feedback = Feedback {
499            rebuilt: 1.8,
500            ..Feedback::default()
501        };
502        self.juice.reset();
503        self.juice.say(&mut self.banter, Mood::Retry);
504    }
505
506    fn set_paused(&mut self, paused: bool) {
507        let was_paused = self.session.is_paused();
508        self.session.set_paused(paused);
509        if paused {
510            self.pending_fire = false;
511            if !was_paused && self.session.is_paused() {
512                self.banter.pause();
513            }
514        }
515    }
516
517    fn queue_fire(&mut self) {
518        // Ignore reload/terminal presses instead of deferring an unwanted shot.
519        if self.session.is_playing() && self.range.can_fire() {
520            self.pending_fire = true;
521        }
522    }
523
524    /// The finished (or current) run for the results card and rank title.
525    fn summary(&self) -> quips::RunSummary {
526        let tally = &self.range.tally;
527        let won = self.range.phase == Phase::Won;
528        quips::RunSummary {
529            won,
530            stars: score::stars(won, tally.shots),
531            targets: self.range.score() as u32,
532            misses: tally.misses,
533            wonder: tally.wonders > 0,
534            domino: tally.dominoes > 0,
535            bell: tally.bell,
536        }
537    }
538
539    #[cfg(test)]
540    fn advance(&mut self, elapsed: f64, autoplay: bool) -> FrameFeedback {
541        self.advance_input(elapsed, autoplay, TickInput::default)
542    }
543
544    fn advance_input(
545        &mut self,
546        elapsed: f64,
547        autoplay: bool,
548        mut input: impl FnMut() -> TickInput,
549    ) -> FrameFeedback {
550        // Presentation settings are sampled even when session.advance produces
551        // no ticks (ready, paused, controls, results, or a high render rate).
552        self.feedback.sync_preferences();
553        let policy = preferences::feedback_policy();
554        self.juice.apply_policy(
555            policy.reduced_motion(),
556            policy.reduced_flash(),
557            policy.intensity(),
558        );
559        let frame = self.session.advance(elapsed);
560        let mut events = FrameFeedback {
561            alpha: frame.alpha,
562            ..FrameFeedback::default()
563        };
564        for _ in 0..frame.steps {
565            self.feedback.step(frame.dt);
566            self.juice.step(frame.dt, self.range.tally.points);
567            let input = input();
568            if !autoplay {
569                self.range.yaw =
570                    (self.range.yaw + input.aim.x * frame.dt * 0.33).clamp(-0.55, 0.55);
571                self.range.elevation =
572                    (self.range.elevation + input.aim.y * frame.dt * 0.2).clamp(0.025, 0.65);
573                if input.fire {
574                    self.queue_fire();
575                }
576            }
577            if autoplay && self.range.autoplay() {
578                if let Some((yaw, elevation)) = self.scripted_aim.take() {
579                    self.range.yaw = yaw;
580                    self.range.elevation = elevation;
581                }
582                self.queue_fire();
583            }
584            if std::mem::take(&mut self.pending_fire) && self.range.fire() {
585                self.feedback.accepted_shot();
586                events.fired = true;
587            }
588            let before = self.range.score();
589            self.range.step(frame.dt);
590            let destroyed = self.range.score() - before;
591            if destroyed > 0 {
592                self.feedback.knocked_down = if self.feedback.destruction > 0.0 {
593                    self.feedback.knocked_down + destroyed
594                } else {
595                    destroyed
596                };
597                self.feedback.destruction = 2.0;
598                events.destroyed += destroyed;
599            }
600            // Juice and audio react only to events the range accepted.
601            for event in self.range.events.as_slice() {
602                match *event {
603                    RangeEvent::Knocked { target: false, .. } => events.loosened += 1,
604                    RangeEvent::Impact { .. } => events.impacts += 1,
605                    RangeEvent::Wobble { .. } => events.wobbled = true,
606                    RangeEvent::Callout { callout, .. }
607                        if events
608                            .callout
609                            .is_none_or(|old| callout.priority() > old.priority()) =>
610                    {
611                        events.callout = Some(callout);
612                    }
613                    _ => {}
614                }
615                self.juice.event(*event, &mut self.banter);
616            }
617            self.range.events.clear();
618            self.juice.sample_trail(self.range.shots.last().map(|shot| {
619                let body = &self.range.physics.bodies[shot.handle];
620                (
621                    Vec3::from_array(body.translation().to_array()),
622                    Vec3::from_array(body.linvel().to_array()).length(),
623                )
624            }));
625            if self.range.ammo == 0
626                && self.range.phase == Phase::Aiming
627                && self.range.since_shot > score::MISS_AFTER
628            {
629                self.juice.settling(&mut self.banter);
630            }
631            if self.range.phase != Phase::Aiming {
632                self.session.finish(self.range.phase == Phase::Won);
633                self.pending_fire = false;
634                events.outcome = Some(self.range.phase);
635                break;
636            }
637        }
638        if !self.session.is_playing() {
639            // Show the current pose when frozen, not the prior tick's pose.
640            events.alpha = 1.0;
641        }
642        self.range.refresh_preview(frame.steps > 0);
643        events
644    }
645}
646
647/// Foreman Gus stands beside the right tower, safely out of the line of fire.
648const GUS: Vec3 = vec3(6.7, 0.0, -2.0);
649const GUS_FACING: f32 = 0.5;
650/// Gus is a big lad, drawn half again life size so he reads at a distance.
651const GUS_SCALE: f32 = 1.5;
652/// The bell hangs from the girder's centre on a short rope.
653const BELL_PIVOT: Vec3 = vec3(0.0, 6.75, -9.0);
654const HIVIS: Color = Color::from_rgba(240, 150, 44, 255);
655const HARDHAT: Color = Color::from_rgba(250, 206, 64, 255);
656const SKIN: Color = Color::from_rgba(226, 178, 138, 255);
657const DENIM: Color = Color::from_rgba(58, 72, 98, 255);
658const BRASS: Color = Color::from_rgba(214, 168, 72, 255);
659const SOOT: Color = Color::from_rgba(76, 78, 72, 255);
660
661struct Art {
662    floor: Mesh3d,
663    stone: Mesh3d,
664    target: Mesh3d,
665    fallen: Mesh3d,
666    ball: Mesh3d,
667    barrel: Mesh3d,
668    muzzle: Mesh3d,
669    wheel: Mesh3d,
670    chassis: Mesh3d,
671    line: Mesh3d,
672    column: Mesh3d,
673    girder: Mesh3d,
674    chimney: Mesh3d,
675    roof: Mesh3d,
676    building: Mesh3d,
677    rivet: Mesh3d,
678    chunk_rust: Mesh3d,
679    chunk_sand: Mesh3d,
680    chunk_soot: Mesh3d,
681    bell: Mesh3d,
682    clapper: Mesh3d,
683    rope: Mesh3d,
684    gus_legs: Mesh3d,
685    gus_torso: Mesh3d,
686    gus_stripe: Mesh3d,
687    gus_arm: Mesh3d,
688    gus_head: Mesh3d,
689    gus_hat: Mesh3d,
690    gus_brim: Mesh3d,
691    gus_tash: Mesh3d,
692    gus_eye: Mesh3d,
693    gus_board: Mesh3d,
694    ground: Mesh3d,
695    shed: Mesh3d,
696    stack: Mesh3d,
697    furnace: Mesh3d,
698    furnace_arch: Mesh3d,
699    channel: Mesh3d,
700    channel_rail: Mesh3d,
701}
702
703/// Warm, sooty foundry palette for the world (targets keep their rust red).
704const FLOOR: Color = Color::from_rgba(92, 78, 66, 255);
705const BRICK: Color = Color::from_rgba(122, 82, 62, 255);
706const CHARRED: Color = Color::from_rgba(70, 60, 54, 255);
707
708impl Art {
709    fn new() -> Self {
710        Self {
711            floor: Mesh3d::cuboid(vec3(28.0, 0.8, 40.0), FLOOR),
712            stone: Mesh3d::cuboid(Vec3::splat(1.17), SAND),
713            target: Mesh3d::cuboid(Vec3::splat(1.17), RUST),
714            fallen: Mesh3d::cuboid(Vec3::splat(1.2), CHARRED),
715            ball: Mesh3d::sphere(0.36, INK, 10, 6),
716            barrel: Mesh3d::frustum(0.34, 0.27, 2.4, STEEL, 12),
717            muzzle: Mesh3d::cylinder(0.2, 0.035, INK, 12),
718            wheel: Mesh3d::cylinder(0.6, 0.3, INK, 10),
719            chassis: Mesh3d::cuboid(vec3(1.5, 0.45, 1.6), RUST),
720            line: Mesh3d::cuboid(
721                vec3(0.075, 0.008, 26.0),
722                Color::from_rgba(168, 128, 84, 255),
723            ),
724            column: Mesh3d::cuboid(vec3(0.32, 7.0, 0.32), STEEL),
725            girder: Mesh3d::cuboid(vec3(18.0, 0.3, 0.34), RUST),
726            chimney: Mesh3d::frustum(1.0, 0.7, 12.0, Color::from_rgba(112, 76, 60, 255), 8),
727            roof: Mesh3d::cuboid(vec3(8.5, 0.3, 6.5), STEEL),
728            building: Mesh3d::cuboid(vec3(8.0, 4.0, 6.0), BRICK),
729            rivet: Mesh3d::cylinder(0.16, 0.015, PAPER, 8),
730            chunk_rust: Mesh3d::cuboid(Vec3::ONE, RUST),
731            chunk_sand: Mesh3d::cuboid(Vec3::ONE, SAND),
732            chunk_soot: Mesh3d::cuboid(Vec3::ONE, SOOT),
733            bell: Mesh3d::frustum(0.44, 0.2, 0.55, BRASS, 10),
734            clapper: Mesh3d::sphere(0.09, INK, 6, 4),
735            rope: Mesh3d::cuboid(vec3(0.05, 0.72, 0.05), INK),
736            gus_legs: Mesh3d::cuboid(vec3(0.42, 0.62, 0.28), DENIM),
737            gus_torso: Mesh3d::cuboid(vec3(0.62, 0.62, 0.38), HIVIS),
738            gus_stripe: Mesh3d::cuboid(vec3(0.64, 0.07, 0.4), PAPER),
739            gus_arm: Mesh3d::cuboid(vec3(0.14, 0.5, 0.14), HIVIS),
740            gus_head: Mesh3d::sphere(0.21, SKIN, 10, 6),
741            gus_hat: Mesh3d::frustum(0.24, 0.16, 0.16, HARDHAT, 10),
742            gus_brim: Mesh3d::cylinder(0.31, 0.03, HARDHAT, 10),
743            gus_tash: Mesh3d::cuboid(vec3(0.22, 0.05, 0.05), Color::from_rgba(92, 62, 44, 255)),
744            gus_eye: Mesh3d::cuboid(Vec3::splat(0.045), INK),
745            gus_board: Mesh3d::cuboid(vec3(0.3, 0.38, 0.04), Color::from_rgba(150, 112, 70, 255)),
746            ground: Mesh3d::cuboid(vec3(260.0, 1.0, 220.0), Color::from_rgba(52, 38, 34, 255)),
747            shed: Mesh3d::cuboid(vec3(10.0, 6.0, 8.0), Color::from_rgba(70, 50, 44, 255)),
748            stack: Mesh3d::frustum(1.6, 1.0, 22.0, Color::from_rgba(66, 46, 40, 255), 8),
749            furnace: Mesh3d::cuboid(vec3(2.4, 1.6, 0.12), atmosphere::MOLTEN),
750            furnace_arch: Mesh3d::cuboid(vec3(3.2, 2.3, 0.3), Color::from_rgba(58, 44, 40, 255)),
751            channel: Mesh3d::cuboid(vec3(0.7, 0.06, 28.0), Color::from_rgba(196, 74, 26, 255)),
752            channel_rail: Mesh3d::cuboid(vec3(0.22, 0.2, 28.0), Color::from_rgba(54, 44, 40, 255)),
753        }
754    }
755
756    #[allow(clippy::too_many_arguments)]
757    fn draw(
758        &self,
759        game: &Range,
760        alpha: f32,
761        recoil: f32,
762        juice: &Juice,
763        camera: &RangeCamera,
764        material: &LitMaterial,
765        ambient_time: f32,
766    ) {
767        set_camera(camera);
768        material.begin(LitSettings {
769            // Low evening sun from the furnace side for long warm shading.
770            light_direction: vec3(-0.55, 0.7, 0.45),
771            camera_position: camera.eye,
772            fog_color: atmosphere::HAZE,
773            fog_start: 42.0,
774            fog_end: 120.0,
775            ambient: 0.5,
776        });
777        // The yard below the raised range, and the foundry town in the haze.
778        self.ground.draw(vec3(0.0, -4.5, -20.0), Quat::IDENTITY);
779        for (x, z, turn) in [
780            (-46.0, -48.0, 0.2),
781            (-28.0, -62.0, -0.1),
782            (-6.0, -58.0, 0.05),
783            (18.0, -64.0, 0.3),
784            (40.0, -50.0, -0.25),
785            (-60.0, -20.0, 0.4),
786        ] {
787            self.shed
788                .draw(vec3(x, -1.0, z), Quat::from_rotation_y(turn));
789        }
790        for (x, z) in [(-36.0, -58.0), (-14.0, -66.0), (8.0, -70.0), (30.0, -60.0)] {
791            self.stack.draw(vec3(x, 7.0, z), Quat::IDENTITY);
792        }
793        self.floor.draw(vec3(0.0, -0.4, 4.0), Quat::IDENTITY);
794        // The furnace mouth and the molten channel it feeds.
795        self.furnace_arch
796            .draw(atmosphere::FURNACE - Vec3::Z * 0.1, Quat::IDENTITY);
797        self.furnace.draw(atmosphere::FURNACE, Quat::IDENTITY);
798        let channel_z = (atmosphere::CHANNEL_Z.0 + atmosphere::CHANNEL_Z.1) * 0.5;
799        self.channel
800            .draw(vec3(atmosphere::CHANNEL_X, 0.02, channel_z), Quat::IDENTITY);
801        for side in [-0.5, 0.5] {
802            self.channel_rail.draw(
803                vec3(atmosphere::CHANNEL_X + side, 0.1, channel_z),
804                Quat::IDENTITY,
805            );
806        }
807        for x in [-8.0, -6.0, 6.0, 8.0] {
808            self.line.draw(vec3(x, 0.012, 4.0), Quat::IDENTITY);
809        }
810        for x in [-9.0, 9.0] {
811            self.column.draw(vec3(x, 3.5, -9.0), Quat::IDENTITY);
812        }
813        self.girder.draw(vec3(0.0, 6.9, -9.0), Quat::IDENTITY);
814        self.building.draw(vec3(-15.0, 2.0, -15.0), Quat::IDENTITY);
815        self.roof
816            .draw(vec3(-15.0, 4.15, -15.0), Quat::from_rotation_z(-0.1));
817        self.chimney.draw(vec3(-12.0, 6.0, -17.0), Quat::IDENTITY);
818        self.chimney.draw(vec3(-16.0, 5.0, -18.0), Quat::IDENTITY);
819        // The secret lunch bell swings when rung (motion only).
820        let swing = Quat::from_rotation_x(juice.bell_angle());
821        self.rope
822            .draw(BELL_PIVOT + swing * vec3(0.0, -0.36, 0.0), swing);
823        self.bell
824            .draw(BELL_PIVOT + swing * (score::BELL - BELL_PIVOT), swing);
825        self.clapper
826            .draw(BELL_PIVOT + swing * vec3(0.0, -1.3, 0.0), swing);
827        for block in &game.blocks {
828            let body = &game.physics.bodies[block.handle];
829            let p = block
830                .previous_position
831                .lerp(Vec3::from_array(body.translation().to_array()), alpha);
832            let q = block
833                .previous_rotation
834                .slerp(Quat::from_array(body.rotation().to_array()), alpha);
835            let mesh = match (block.target, block.down) {
836                (true, true) => &self.fallen,
837                (true, false) => &self.target,
838                (false, _) => &self.stone,
839            };
840            mesh.draw(p, q);
841            if block.target && !block.down {
842                self.rivet.draw(
843                    p + q * vec3(0.0, 0.0, 0.594),
844                    q * Quat::from_rotation_x(std::f32::consts::FRAC_PI_2),
845                );
846            }
847        }
848        for shot in &game.shots {
849            let p = shot.previous_position.lerp(
850                Vec3::from_array(game.physics.bodies[shot.handle].translation().to_array()),
851                alpha,
852            );
853            self.ball.draw(p, Quat::IDENTITY);
854        }
855        for chunk in juice.chunks.iter().flatten() {
856            let mesh = match chunk.material {
857                Material::Rust => &self.chunk_rust,
858                Material::Sand => &self.chunk_sand,
859                Material::Soot => &self.chunk_soot,
860            };
861            mesh.draw_transformed(Mat4::from_scale_rotation_translation(
862                Vec3::splat(chunk.scale()),
863                chunk.rotation,
864                chunk.position,
865            ));
866        }
867        self.draw_gus(juice, ambient_time);
868        let direction = game.direction();
869        let q = Quat::from_rotation_arc(Vec3::Y, direction);
870        self.chassis
871            .draw_transformed(Mat4::from_scale_rotation_translation(
872                juice.carriage_scale(),
873                Quat::from_rotation_y(-game.yaw),
874                vec3(0.0, 0.7, 15.0),
875            ));
876        for x in [-0.95, 0.95] {
877            self.wheel.draw(
878                vec3(x, 0.6, 15.0),
879                Quat::from_rotation_z(std::f32::consts::FRAC_PI_2),
880            );
881        }
882        self.barrel.draw(PIVOT + direction * (0.3 - recoil), q);
883        self.muzzle.draw(PIVOT + direction * (1.515 - recoil), q);
884        material.end();
885        // Screen-space atmosphere follows; the HUD boundary is explicit.
886        set_default_camera();
887    }
888
889    /// Foreman Gus: idles, frets while a tower wobbles, and hops at a collapse.
890    fn draw_gus(&self, juice: &Juice, ambient_time: f32) {
891        let motion = juice.motion().min(1.0);
892        let bob = (ambient_time * 3.1).sin() * 0.025 * motion;
893        let root = Mat4::from_scale_rotation_translation(
894            Vec3::splat(GUS_SCALE),
895            Quat::from_rotation_y(GUS_FACING) * Quat::from_rotation_z(juice.fret()),
896            GUS + Vec3::Y * (juice.hop_height() + bob),
897        );
898        let part = |mesh: &Mesh3d, at: Vec3, rotation: Quat| {
899            mesh.draw_transformed(root * Mat4::from_rotation_translation(rotation, at));
900        };
901        part(&self.gus_legs, vec3(0.0, 0.31, 0.0), Quat::IDENTITY);
902        part(&self.gus_torso, vec3(0.0, 0.93, 0.0), Quat::IDENTITY);
903        part(&self.gus_stripe, vec3(0.0, 0.86, 0.0), Quat::IDENTITY);
904        part(&self.gus_head, vec3(0.0, 1.46, 0.0), Quat::IDENTITY);
905        part(&self.gus_tash, vec3(0.0, 1.4, 0.2), Quat::IDENTITY);
906        for x in [-0.075, 0.075] {
907            part(&self.gus_eye, vec3(x, 1.5, 0.19), Quat::IDENTITY);
908        }
909        part(&self.gus_brim, vec3(0.0, 1.57, 0.03), Quat::IDENTITY);
910        part(&self.gus_hat, vec3(0.0, 1.66, 0.0), Quat::IDENTITY);
911        part(
912            &self.gus_board,
913            vec3(0.12, 0.95, 0.23),
914            Quat::from_rotation_x(-0.35),
915        );
916        // Arms rise in despair on a collapse and flap while he frets.
917        let raise = (juice.hop * 2.6).min(1.0).max(juice.alarm * 0.7) * motion;
918        for side in [-1.0_f32, 1.0] {
919            let flap = (juice.time * 16.0 + side).sin() * 0.25 * juice.alarm * motion;
920            let angle = side * (0.12 + 2.5 * raise + flap);
921            let shoulder = vec3(side * 0.39, 1.2, 0.0);
922            let rotation = Quat::from_rotation_z(angle);
923            part(
924                &self.gus_arm,
925                shoulder + rotation * vec3(0.0, -0.25, 0.0),
926                rotation,
927            );
928        }
929    }
930}
931
932/// Fits the authored range between the HUD panels without moving the eye,
933/// changing depth/fog, or coupling the view to moving debris or player aim.
934struct RangeCamera {
935    matrix: Mat4,
936    eye: Vec3,
937}
938
939impl RangeCamera {
940    fn new(w: f32, h: f32) -> Self {
941        let base = Camera3D {
942            position: vec3(23.0, 18.0, 28.0),
943            target: vec3(0.0, 1.5, 3.5),
944            up: Vec3::Y,
945            fovy: 43.0_f32.to_radians(),
946            z_near: 0.1,
947            z_far: 130.0,
948            ..Default::default()
949        };
950        let matrix = base.matrix(w, h);
951        let scene = HudLayout::new(w, h).scene;
952        let mut low = vec2(f32::INFINITY, f32::INFINITY);
953        let mut high = vec2(f32::NEG_INFINITY, f32::NEG_INFINITY);
954        // Standing towers, cannon including every legal muzzle direction, and
955        // the low arcs that reach the supports. The decoration may extend under
956        // the HUD; flying balls/debris never cause camera motion.
957        for (min, max) in [
958            (vec3(-4.6, 0.0, -4.6), vec3(4.6, 4.81, -3.4)),
959            (vec3(-1.4, 0.0, 13.0), vec3(1.4, 3.0, 16.4)),
960        ] {
961            for x in [min.x, max.x] {
962                for y in [min.y, max.y] {
963                    for z in [min.z, max.z] {
964                        let p = matrix.project_point3(vec3(x, y, z));
965                        let p = vec2((p.x + 1.0) * w * 0.5, (1.0 - p.y) * h * 0.5);
966                        low = low.min(p);
967                        high = high.max(p);
968                    }
969                }
970            }
971        }
972        let scale = (scene.w / (high.x - low.x))
973            .min(scene.h / (high.y - low.y))
974            .min(1.0);
975        // Smallest translation that contains the fitted bounds. In particular,
976        // an already fitting desktop view retains its original composition.
977        let shift_axis = |low: f32, high: f32, start: f32, size: f32| {
978            if low * scale < start {
979                start - low * scale
980            } else if high * scale > start + size {
981                start + size - high * scale
982            } else {
983                0.0
984            }
985        };
986        let shift = vec2(
987            shift_axis(low.x, high.x, scene.x, scene.w),
988            shift_axis(low.y, high.y, scene.y, scene.h),
989        );
990        let offset = vec3(
991            scale - 1.0 + 2.0 * shift.x / w,
992            1.0 - scale - 2.0 * shift.y / h,
993            0.0,
994        );
995        Self {
996            matrix: Mat4::from_translation(offset)
997                * Mat4::from_scale(vec3(scale, scale, 1.0))
998                * matrix,
999            eye: base.position,
1000        }
1001    }
1002
1003    /// A screen-space presentation offset in pixels (camera kick and shake).
1004    /// The eye, depth and fog are unchanged.
1005    fn shifted(mut self, w: f32, h: f32, pixels: Vec2) -> Self {
1006        if pixels != Vec2::ZERO && w > 0.0 && h > 0.0 {
1007            let offset = vec3(2.0 * pixels.x / w, -2.0 * pixels.y / h, 0.0);
1008            self.matrix = Mat4::from_translation(offset) * self.matrix;
1009        }
1010        self
1011    }
1012
1013    /// Screen position of a world point, or `None` behind the eye.
1014    fn project(&self, w: f32, h: f32, point: Vec3) -> Option<Vec2> {
1015        let clip = self.matrix * point.extend(1.0);
1016        (clip.w > 0.01).then(|| {
1017            vec2(
1018                (clip.x / clip.w + 1.0) * w * 0.5,
1019                (1.0 - clip.y / clip.w) * h * 0.5,
1020            )
1021        })
1022    }
1023}
1024
1025impl Camera for RangeCamera {
1026    fn matrix(&self, _: f32, _: f32) -> Mat4 {
1027        self.matrix
1028    }
1029
1030    fn depth(&self) -> bool {
1031        true
1032    }
1033
1034    fn position(&self) -> Option<Vec3> {
1035        Some(self.eye)
1036    }
1037}
1038
1039fn clicked(rect: Rect) -> bool {
1040    rect.contains(Vec2::from(mouse_position())) && is_mouse_button_pressed(MouseButton::Left)
1041}
1042
1043fn action_hint<'a>(input: &PlayerInput, action: &str, buffer: &'a mut [u8]) -> &'a str {
1044    if input.current_device() == HintDevice::Touch {
1045        // The preset's Touch 2/confirm channels are not installed here: this
1046        // range uses its visible pointer buttons and a look-only touch region.
1047        return "on-screen button";
1048    }
1049    // Never silently advertise a default binding after a remap or format error.
1050    input.format_hint(action, buffer).unwrap_or("See Controls")
1051}
1052
1053struct HudLayout {
1054    scene: Rect,
1055    panel: Rect,
1056    fire: Rect,
1057    rebuild: Rect,
1058    pause: Rect,
1059}
1060
1061impl HudLayout {
1062    fn new(w: f32, h: f32) -> Self {
1063        let height = 116.0;
1064        let panel = Rect::new(16.0, h - height - 16.0, w - 32.0, height);
1065        let width = (panel.w - 48.0) / 3.0;
1066        let y = panel.y + panel.h - 54.0;
1067        Self {
1068            scene: Rect::new(16.0, 56.0, w - 32.0, (panel.y - 64.0).max(1.0)),
1069            panel,
1070            fire: Rect::new(32.0, y, width, 44.0),
1071            rebuild: Rect::new(40.0 + width, y, width, 44.0),
1072            pause: Rect::new(48.0 + width * 2.0, y, width, 44.0),
1073        }
1074    }
1075}
1076
1077/// Personal records are stored per layout/rules version.
1078const RECORD_CONTEXT: u64 = 1;
1079
1080/// Read the stored best points and best stars, if any.
1081fn stored_best(records: Option<&ferravex_render::storage::Records>) -> hud::Best {
1082    let Some(records) = records else {
1083        return hud::Best::default();
1084    };
1085    hud::Best {
1086        points: records.get("points", RECORD_CONTEXT).map(|r| r.score),
1087        stars: records.get("spared", RECORD_CONTEXT).map_or(0, |r| {
1088            score::stars(true, AMMO.saturating_sub(r.score as u8))
1089        }),
1090    }
1091}
1092
1093/// Capture the comparison once at the result, then record the attempt.
1094fn finish_run(
1095    records: Option<&mut ferravex_render::storage::Records>,
1096    foundry: &Foundry,
1097    fake_best: Option<u64>,
1098) -> hud::Results {
1099    let tally = &foundry.range.tally;
1100    let won = foundry.range.phase == Phase::Won;
1101    let points = u64::from(tally.points);
1102    let mut previous = stored_best(records.as_deref());
1103    if fake_best.is_some() {
1104        previous.points = fake_best;
1105    }
1106    if let Some(records) = records {
1107        // Storage failures keep the in-memory session best; play continues.
1108        let _ = records.attempt("points", RECORD_CONTEXT, points, None);
1109        if won {
1110            let _ = records.attempt("spared", RECORD_CONTEXT, u64::from(tally.spare), None);
1111        }
1112    }
1113    let stars = score::stars(won, tally.shots);
1114    hud::Results {
1115        previous,
1116        new_best: points > 0 && previous.points.is_none_or(|best| points > best),
1117        new_stars: stars > previous.stars,
1118    }
1119}
1120
1121fn window_conf() -> Conf {
1122    #[allow(unused_mut)]
1123    let mut conf = ferravex_render::window_conf("Siege Foundry / Ferravex");
1124    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1125    capture::window(&mut conf);
1126    conf
1127}
1128
1129ferravex_render::game!(window_conf, game);
1130async fn game() {
1131    let mut demo = Demo::new();
1132    let mut foundry = Foundry::new(demo.autoplay);
1133    let art = Art::new();
1134    let material = LitMaterial::new().expect("Ferravex lit material");
1135    let mut sound = GameAudio::new();
1136    let mut player_input = PlayerInput::preset("siege-foundry", Preset::Turret);
1137    player_input.set_mouse_look_button(Some(1)).unwrap();
1138    let mut records = ferravex_render::storage::Records::new("siege-foundry").ok();
1139    let mut results = hud::Results::default();
1140    let mut coach = hud::Coach::default();
1141    let mut hints = hud::Hints::default();
1142    let mut hud_anim = hud::HudAnim::default();
1143    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1144    let mut capture = capture::Capture::from_env();
1145    let mut look_state = None;
1146    let mut air = atmosphere::Air {
1147        time: 0.0,
1148        motion: 1.0,
1149        flicker: 1.0,
1150    };
1151    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1152    let fake_best = capture.fake_best();
1153    #[cfg(not(all(debug_assertions, not(target_arch = "wasm32"))))]
1154    let fake_best = None;
1155    loop {
1156        let (w, h) = (screen_width(), screen_height());
1157        let layout = HudLayout::new(w, h);
1158        player_input
1159            .set_touch_layout(&[Control {
1160                region: Region::Rect(Rect::new(0.0, 90.0, w, (layout.panel.y - 90.0).max(1.0))),
1161                output: Output::Look { x: 0, y: 1 },
1162            }])
1163            .unwrap();
1164        // Resolve pointer pause before sampling, so keyboard and pointer resume
1165        // both re-enable the gameplay context on this frame.
1166        let pausable = matches!(
1167            foundry.session.state(),
1168            SessionState::Playing | SessionState::Paused
1169        );
1170        if !demo.autoplay && !player_input.controls_open() && pausable && clicked(layout.pause) {
1171            player_input.set_paused(!foundry.session.is_paused());
1172        }
1173        player_input.sample_play();
1174        hints.refresh(&player_input);
1175        let dt = demo.dt();
1176        #[allow(unused_mut)]
1177        let mut active = demo.autoplay || player_input.gameplay_active() && !player_input.paused();
1178        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1179        {
1180            if capture.hold(foundry.session.is_playing()) {
1181                player_input.set_paused(true);
1182                active = false;
1183            }
1184        }
1185        let controls_open = player_input.controls_open();
1186        let confirm = player_input.pressed("confirm");
1187        let rebuild = player_input.pressed("restart") || !controls_open && clicked(layout.rebuild);
1188        // Drain relative look while inactive, including the rebuild frame.
1189        let look = player_input.look(dt);
1190        let state = foundry.session.state();
1191        let pointer_fire = !controls_open && clicked(layout.fire);
1192        // Fire doubles as a menu action only outside play. During play, leave
1193        // its edge in PlayerInput until an actual simulation tick consumes it.
1194        let menu_fire = if state != SessionState::Playing || rebuild {
1195            player_input.pressed("fire")
1196        } else {
1197            false
1198        };
1199        let restarted = rebuild
1200            || matches!(state, SessionState::Won | SessionState::Lost)
1201                && (confirm || menu_fire || pointer_fire);
1202        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1203        let scripted_start = capture.start();
1204        #[cfg(not(all(debug_assertions, not(target_arch = "wasm32"))))]
1205        let scripted_start = false;
1206        let started = state == SessionState::Ready
1207            && (confirm || menu_fire || pointer_fire || scripted_start);
1208        if restarted {
1209            foundry.rebuild();
1210            hud_anim.open_doors();
1211            player_input.set_paused(false);
1212            sound.reset();
1213            results = hud::Results::default();
1214        } else if started {
1215            foundry.start();
1216            player_input.set_paused(false);
1217        } else {
1218            foundry.set_paused(!active);
1219        }
1220        let aim_before = (foundry.range.yaw, foundry.range.elevation);
1221        if foundry.session.is_playing() && active && !restarted && !started {
1222            let game = &mut foundry.range;
1223            let pointer = Vec2::from(mouse_position());
1224            if pointer.y > 90.0 && pointer.y < layout.panel.y || player_input.touch_active() {
1225                game.yaw += look.x * 0.7;
1226                game.elevation -= look.y * 0.45;
1227            }
1228            game.yaw = game.yaw.clamp(-0.55, 0.55);
1229            game.elevation = game.elevation.clamp(0.025, 0.65);
1230            if pointer_fire {
1231                foundry.queue_fire();
1232            }
1233        }
1234        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1235        if demo.autoplay
1236            && foundry.scripted_aim.is_none()
1237            && let Some(aim) = capture.aim(foundry.range.tally.shots)
1238        {
1239            foundry.scripted_aim = Some(match aim {
1240                capture::Aim::Bell => BELL_AIM,
1241                capture::Aim::Miss => (0.5, 0.13),
1242            });
1243        }
1244        let events = foundry.advance_input(
1245            if restarted || started {
1246                0.0
1247            } else {
1248                f64::from(dt)
1249            },
1250            demo.autoplay,
1251            || TickInput {
1252                fire: player_input.take_tick(["fire"])[0].pressed,
1253                aim: player_input.movement(),
1254            },
1255        );
1256        let aimed = (foundry.range.yaw, foundry.range.elevation) != aim_before;
1257        coach.aimed |= aimed && !demo.autoplay || events.fired && demo.autoplay;
1258        coach.fired |= events.fired;
1259        coach.knocked |= events.destroyed > 0 || events.loosened > 0;
1260        if events.fired {
1261            sound.cue(Cue::Fire, 0.8);
1262        }
1263        if events.impacts > 0 {
1264            sound.cue(Cue::Impact(Surface::Stone), 0.45);
1265        }
1266        if events.loosened > 0 {
1267            sound.cue(Cue::Impact(Surface::Wood), 0.5);
1268        }
1269        if events.destroyed > 0 {
1270            sound.cue(Cue::Impact(Surface::Metal), 0.6);
1271        }
1272        if events.wobbled {
1273            sound.cue(Cue::Footstep(Surface::Wood), 0.4);
1274        }
1275        match events.callout {
1276            Some(Callout::Bell) => {
1277                sound.cue(Cue::Pickup, 0.8);
1278            }
1279            Some(Callout::Domino | Callout::OneShotWonder | Callout::Overkill) => {
1280                sound.cue(Cue::Pickup, 0.55);
1281            }
1282            Some(Callout::Chain(_) | Callout::Timber | Callout::Delayed) => {
1283                sound.cue(Cue::Reload, 0.45);
1284            }
1285            Some(Callout::Spare(_)) | None => {}
1286        }
1287        if let Some(outcome) = events.outcome {
1288            sound.cue(
1289                if outcome == Phase::Won {
1290                    Cue::Success
1291                } else {
1292                    Cue::Failure
1293                },
1294                0.65,
1295            );
1296            results = finish_run(records.as_mut(), &foundry, fake_best);
1297        }
1298        if matches!(
1299            foundry.session.state(),
1300            SessionState::Won | SessionState::Lost
1301        ) {
1302            foundry.juice.result_time(dt);
1303        }
1304        let state = foundry.session.state();
1305        if look_state != Some(state) {
1306            // Sticky post settings change only when the screen changes.
1307            set_post_fx(atmosphere::look(state));
1308            look_state = Some(state);
1309        }
1310        let policy = preferences::feedback_policy();
1311        let air_motion = if policy.reduced_motion() {
1312            0.0
1313        } else {
1314            policy.intensity().min(1.0)
1315        };
1316        air.time += dt * air_motion;
1317        air.motion = air_motion;
1318        air.flicker = if policy.reduced_flash() { 0.0 } else { 1.0 };
1319        clear_background(atmosphere::SKY_TOP);
1320        atmosphere::sky(w, h);
1321        let camera = RangeCamera::new(w, h).shifted(w, h, foundry.juice.camera_offset());
1322        art.draw(
1323            &foundry.range,
1324            events.alpha,
1325            foundry.feedback.barrel_offset(),
1326            &foundry.juice,
1327            &camera,
1328            &material,
1329            air.time,
1330        );
1331        atmosphere::world(&foundry, &camera, w, h, air);
1332        post_fx_hud_begin();
1333        let best = stored_best(records.as_ref());
1334        hud_anim.update(
1335            dt.clamp(0., 0.1),
1336            state,
1337            &layout,
1338            hud::enabled_buttons(&foundry, state, controls_open),
1339            &coach,
1340        );
1341        hud::draw(&hud::View {
1342            foundry: &foundry,
1343            layout: &layout,
1344            camera: &camera,
1345            w,
1346            h,
1347            controls_open,
1348            hints: &hints,
1349            results: &results,
1350            best,
1351            coach: &coach,
1352            anim: &hud_anim,
1353        });
1354        // The range supplies its own pause panel; retain the shared editor.
1355        if !player_input.paused() || controls_open {
1356            player_input.draw_settings();
1357        }
1358        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1359        capture.end_frame();
1360        if demo.finish_frame() {
1361            break;
1362        }
1363        next_frame().await;
1364    }
1365}
1366
1367/// Yaw and elevation that send a ball over the centre tower and through the
1368/// secret lunch bell. Used by debug captures; kept honest by a regression test
1369/// that fires it through real physics.
1370#[cfg_attr(
1371    not(any(test, all(debug_assertions, not(target_arch = "wasm32")))),
1372    allow(dead_code)
1373)]
1374const BELL_AIM: (f32, f32) = (0.0, 0.335);
1375
1376#[cfg(test)]
1377mod journey200_tests;
1378
1379#[cfg(test)]
1380mod journey200_194;
1381
1382#[cfg(test)]
1383mod tests {
1384    use super::*;
1385    use ferravex_render::ui;
1386
1387    #[test]
1388    fn tick_input_is_not_read_while_ready_paused_or_on_zero_tick_frames() {
1389        let mut foundry = Foundry::new(false);
1390        let mut calls = 0;
1391        let mut fire = true;
1392        let mut input = || {
1393            calls += 1;
1394            TickInput {
1395                fire: std::mem::take(&mut fire),
1396                aim: Vec2::ZERO,
1397            }
1398        };
1399        foundry.advance_input(1.0, false, &mut input);
1400        foundry.session.start();
1401        foundry.advance_input(0.001, false, &mut input);
1402        foundry.set_paused(true);
1403        foundry.advance_input(1.0, false, &mut input);
1404        foundry.set_paused(false);
1405        let events = foundry.advance_input(0.05, false, &mut input);
1406        assert!(events.fired);
1407        assert_eq!(calls, 6);
1408        assert!(!fire);
1409        assert_eq!(foundry.range.shots.len(), 1);
1410        assert_eq!(foundry.range.ammo, AMMO - 1);
1411    }
1412
1413    #[test]
1414    fn player_input_taps_survive_zero_ticks_and_reload_rejection_is_not_buffered() {
1415        use ferravex_render::input::{self, ActionKind, Binding, InputCode, PadState};
1416        let mut player = PlayerInput::transient("journey200-139-ticks");
1417        player
1418            .action(
1419                "fire",
1420                "Fire",
1421                ActionKind::Button,
1422                vec![Binding::digital(InputCode::PadButton(7))],
1423            )
1424            .unwrap();
1425        let mut pad = PadState {
1426            connected: true,
1427            ..Default::default()
1428        };
1429        let mut foundry = Foundry::new(true);
1430        foundry.range.yaw = 0.5;
1431        let mut frame = |dt, button| {
1432            pad.buttons[7] = button;
1433            assert!(input::gamepad_sample(0, pad));
1434            input::host_frame(dt as f32, 320, 448, || {
1435                player.sample_play();
1436                foundry
1437                    .advance_input(dt, false, || TickInput {
1438                        fire: player.take_tick(["fire"])[0].pressed,
1439                        aim: Vec2::ZERO,
1440                    })
1441                    .fired
1442            })
1443        };
1444        // Connect released first, then press/release entirely before a tick.
1445        assert!(!frame(0.0, 0.0));
1446        assert!(!frame(0.001, 1.0));
1447        assert!(!frame(0.001, 0.0));
1448        assert!(frame(0.05, 0.0));
1449        assert!(!frame(0.001, 1.0));
1450        assert!(!frame(0.1, 0.0)); // Rejected at the tick while still loading.
1451        for _ in 0..10 {
1452            assert!(!frame(0.1, 0.0));
1453        }
1454        assert!(frame(0.01, 1.0)); // Only a fresh ready press fires again.
1455        assert_eq!(foundry.range.ammo, AMMO - 2);
1456        assert_eq!(foundry.range.shots.len(), 2);
1457        assert!(input::gamepad_sample(0, PadState::default()));
1458    }
1459
1460    #[test]
1461    fn held_aim_uses_equal_fixed_ticks_at_30_60_and_144_hz() {
1462        let mut reference = None;
1463        for fps in [30, 60, 144] {
1464            let mut foundry = Foundry::new(true);
1465            for _ in 0..fps {
1466                foundry.advance_input(1.0 / f64::from(fps), false, || TickInput {
1467                    fire: false,
1468                    aim: vec2(0.5, 0.25),
1469                });
1470            }
1471            assert_eq!(foundry.session.tick(), 120);
1472            let aim = (foundry.range.yaw, foundry.range.elevation);
1473            assert!(aim.0 > 0.16 && aim.0 < 0.17);
1474            assert!(aim.1 > 0.17 && aim.1 < 0.19);
1475            if let Some(reference) = reference {
1476                assert_eq!(aim, reference);
1477            }
1478            reference = Some(aim);
1479        }
1480    }
1481
1482    #[test]
1483    fn motion_policy_cancels_old_recoil_without_erasing_shot_confirmation() {
1484        let mut feedback = Feedback::default();
1485        feedback.apply_motion(false, 1.0);
1486        feedback.accepted_shot();
1487        assert_eq!(feedback.barrel_offset(), 0.3);
1488        feedback.apply_motion(false, 0.5);
1489        assert_eq!(feedback.barrel_offset(), 0.15);
1490        // No time need pass: changing policy while paused must retire the pose.
1491        feedback.apply_motion(true, 1.0);
1492        assert_eq!(feedback.barrel_offset(), 0.0);
1493        assert_eq!(feedback.shot, 1.0);
1494        feedback.apply_motion(false, 1.0);
1495        assert_eq!(feedback.barrel_offset(), 0.0);
1496        feedback.apply_motion(true, 1.0);
1497        feedback.accepted_shot();
1498        feedback.apply_motion(false, 1.0);
1499        assert_eq!(
1500            feedback.barrel_offset(),
1501            0.0,
1502            "disabled shots cannot revive"
1503        );
1504        feedback.accepted_shot();
1505        assert!(feedback.barrel_offset() > 0.0);
1506        feedback.apply_motion(false, 0.0);
1507        feedback.apply_motion(false, 1.0);
1508        assert_eq!(feedback.barrel_offset(), 0.0);
1509    }
1510
1511    #[test]
1512    fn ready_paused_and_terminal_frames_sample_shared_presentation_policy() {
1513        preferences::set_feedback_policy(Default::default());
1514        let mut foundry = Foundry::new(false);
1515        for state in [
1516            SessionState::Ready,
1517            SessionState::Playing,
1518            SessionState::Paused,
1519            SessionState::Won,
1520        ] {
1521            match state {
1522                SessionState::Playing => {
1523                    foundry.session.start();
1524                }
1525                SessionState::Paused => foundry.set_paused(true),
1526                SessionState::Won => {
1527                    foundry.session.finish(true);
1528                }
1529                _ => {}
1530            }
1531            foundry.feedback.motion_scale = 0.25;
1532            foundry.advance(0.0, false);
1533            assert_eq!(foundry.feedback.motion_scale, 1.0, "{state:?}");
1534            assert_eq!(foundry.session.tick(), 0);
1535            assert_eq!(foundry.range.ammo, AMMO);
1536        }
1537    }
1538
1539    #[test]
1540    fn hud_hints_follow_remaps_unbound_actions_and_bounded_buffer_errors() {
1541        use ferravex_render::input::{ActionKind, Binding, InputCode};
1542        let mut player = PlayerInput::transient("journey200-139-hints");
1543        player
1544            .action(
1545                "fire",
1546                "Fire",
1547                ActionKind::Button,
1548                vec![Binding::digital(InputCode::Key(32))],
1549            )
1550            .unwrap();
1551        let mut buffer = [0; 512];
1552        assert_eq!(action_hint(&player, "fire", &mut buffer), "Space");
1553        player
1554            .rebind("fire", vec![Binding::digital(InputCode::Key(b'f' as u16))])
1555            .unwrap();
1556        assert_eq!(action_hint(&player, "fire", &mut buffer), "F");
1557        player.rebind("fire", vec![]).unwrap();
1558        assert_eq!(action_hint(&player, "fire", &mut buffer), "Unbound");
1559        assert_eq!(action_hint(&player, "fire", &mut []), "See Controls");
1560        assert_eq!(action_hint(&player, "missing", &mut buffer), "See Controls");
1561    }
1562
1563    #[test]
1564    fn narrow_hud_keeps_controls_and_fixed_size_text_inside_panels() {
1565        let metrics = get_default_font().try_metrics(16, 1.0).unwrap();
1566        for width in [320.0, 390.0, 700.0, 1280.0] {
1567            let layout = HudLayout::new(width, 448.0);
1568            let mut last_right = layout.panel.x;
1569            for rect in [layout.fire, layout.rebuild, layout.pause] {
1570                assert!(rect.x >= last_right);
1571                assert!(rect.x + rect.w <= layout.panel.x + layout.panel.w);
1572                assert!(rect.y >= layout.panel.y);
1573                assert!(rect.y + rect.h <= layout.panel.y + layout.panel.h);
1574                assert!(rect.h >= 44.0);
1575                last_right = rect.x + rect.w;
1576            }
1577            assert!(
1578                layout.panel.y > 216.0,
1579                "result panel must not cover buttons"
1580            );
1581            for text in [
1582                "YAW -32 / ELEV 37.2",
1583                "POWER 28 m/s - fixed",
1584                "REBUILT: 8 SHOTS READY",
1585                "SETTLING 6.0s",
1586            ] {
1587                let measured = metrics.measure_line(text).unwrap();
1588                assert_eq!(measured.unsupported_glyphs, 0);
1589                assert!(measured.width <= layout.panel.w - 24.0, "{text}: {width}");
1590            }
1591            let long_hint = "FIRE: Left Shift / Right Shift / Space / Enter";
1592            let fitted =
1593                ui::fit_label(long_hint, layout.panel.w - 24.0, metrics.glyph_advance()).unwrap();
1594            assert!(fitted.width <= layout.panel.w - 24.0);
1595            assert_eq!(
1596                metrics.measure_line(fitted.prefix).unwrap().width
1597                    + metrics.measure_line(fitted.suffix).unwrap().width,
1598                fitted.width
1599            );
1600        }
1601    }
1602
1603    #[test]
1604    fn trajectory_preview_stops_at_real_tower_geometry_and_reuses_storage() {
1605        let mut game = Range::new();
1606        game.aim_at(vec3(0., 1.8, -4.));
1607        game.refresh_preview(false);
1608        let hit = game
1609            .preview_hit
1610            .expect("arc should hit the front of the tower");
1611        assert!(hit.z > -3.2 && hit.z < -2.8, "{hit:?}");
1612        assert_eq!(game.preview.last(), Some(&hit));
1613        let capacity = game.preview.capacity();
1614        let old = game.preview.clone();
1615        game.refresh_preview(false);
1616        assert_eq!(game.preview, old);
1617        game.yaw += 0.4;
1618        game.refresh_preview(false);
1619        assert_ne!(game.preview, old);
1620        assert_eq!(game.preview.capacity(), capacity);
1621    }
1622
1623    fn tick(game: &mut Range, seconds: f32) {
1624        for _ in 0..(seconds / DT).round() as usize {
1625            game.step(DT);
1626        }
1627    }
1628
1629    #[test]
1630    fn stack_stays_upright_without_projectiles() {
1631        let mut game = Range::new();
1632        tick(&mut game, 8.0);
1633        assert_eq!(game.score(), 0);
1634        assert_eq!(game.phase, Phase::Aiming);
1635    }
1636
1637    #[test]
1638    fn ammunition_cooldown_ccd_and_loss_are_real() {
1639        let mut game = Range::new();
1640        game.yaw = 0.5;
1641        assert!(game.fire());
1642        assert!(!game.fire());
1643        assert!(game.physics.bodies[game.shots[0].handle].is_ccd_enabled());
1644        while game.ammo > 0 {
1645            tick(&mut game, 0.9);
1646            assert!(game.fire());
1647        }
1648        tick(&mut game, 6.2);
1649        assert_eq!(game.phase, Phase::Lost);
1650        assert_eq!(game.shots.len(), AMMO as usize);
1651        assert!(!game.fire());
1652    }
1653
1654    #[test]
1655    fn autoplay_wins_through_ballistic_contacts() {
1656        for fps in [30, 144] {
1657            let mut foundry = Foundry::new(true);
1658            let mut fired = 0;
1659            let mut destroyed = 0;
1660            let mut outcomes = 0;
1661            for _ in 0..30 * fps {
1662                let events = foundry.advance(1.0 / f64::from(fps), true);
1663                fired += usize::from(events.fired);
1664                destroyed += events.destroyed;
1665                outcomes += usize::from(events.outcome.is_some());
1666                if foundry.session.state() == SessionState::Won {
1667                    break;
1668                }
1669            }
1670            let game = &foundry.range;
1671            assert_eq!(game.score(), GOAL, "{fps} FPS, ammo {}", game.ammo);
1672            assert_eq!(game.phase, Phase::Won);
1673            assert_eq!(foundry.session.state(), SessionState::Won);
1674            assert!(game.ammo > 0);
1675            assert!(fired > 0);
1676            assert_eq!(fired, game.shots.len());
1677            assert_eq!(destroyed, GOAL);
1678            assert_eq!(outcomes, 1);
1679        }
1680    }
1681
1682    #[test]
1683    fn shot_input_survives_zero_step_frame_and_is_consumed_once_during_catchup() {
1684        let mut foundry = Foundry::new(true);
1685        foundry.range.yaw = 0.5;
1686        foundry.queue_fire();
1687        assert!(!foundry.advance(0.001, false).fired);
1688        assert!(foundry.pending_fire);
1689        assert_eq!(foundry.range.ammo, AMMO);
1690        assert!(foundry.advance(0.05, false).fired);
1691        assert!(!foundry.pending_fire);
1692        assert_eq!(foundry.range.ammo, AMMO - 1);
1693        for _ in 0..20 {
1694            assert!(!foundry.advance(0.1, false).fired);
1695        }
1696        assert_eq!(foundry.range.shots.len(), 1);
1697    }
1698
1699    #[test]
1700    fn ready_session_cannot_spend_ammo_or_accumulate_physics_time() {
1701        let mut foundry = Foundry::new(false);
1702        foundry.queue_fire();
1703        let events = foundry.advance(50.0, false);
1704        assert!(!events.fired);
1705        assert_eq!(foundry.range.elapsed, 0.0);
1706        assert_eq!(foundry.range.ammo, AMMO);
1707        assert_eq!(foundry.session.tick(), 0);
1708        assert!(foundry.session.start());
1709        assert!(!foundry.advance(1.0 / 120.0, false).fired);
1710        assert_eq!(foundry.session.tick(), 1);
1711        foundry.queue_fire();
1712        assert!(foundry.advance(1.0 / 120.0, false).fired);
1713    }
1714
1715    #[test]
1716    fn rejected_reload_edge_does_not_fire_later_or_refresh_feedback() {
1717        let mut foundry = Foundry::new(true);
1718        foundry.range.yaw = 0.5;
1719        foundry.queue_fire();
1720        assert!(foundry.advance(1.0 / 120.0, false).fired);
1721        let shot_feedback = foundry.feedback.shot;
1722        foundry.queue_fire();
1723        assert!(!foundry.pending_fire);
1724        assert_eq!(foundry.feedback.shot, shot_feedback);
1725        for _ in 0..12 {
1726            assert!(!foundry.advance(0.1, false).fired);
1727        }
1728        assert_eq!(foundry.range.ammo, AMMO - 1);
1729        assert_eq!(foundry.feedback.shot, 0.0);
1730        foundry.queue_fire();
1731        assert!(foundry.advance(1.0 / 120.0, false).fired);
1732    }
1733
1734    #[test]
1735    fn pause_clears_buffered_input_and_freezes_reload_feedback_and_physics() {
1736        let mut foundry = Foundry::new(true);
1737        foundry.queue_fire();
1738        foundry.advance(0.001, false);
1739        foundry.set_paused(true);
1740        foundry.queue_fire();
1741        assert!(!foundry.pending_fire);
1742        foundry.advance(10.0, false);
1743        assert_eq!(foundry.range.elapsed, 0.0);
1744        foundry.set_paused(false);
1745        assert!(!foundry.advance(1.0 / 120.0, false).fired);
1746        assert_eq!(foundry.session.tick(), 1);
1747        foundry.queue_fire();
1748        foundry.advance(1.0 / 120.0, false);
1749        let before = (
1750            foundry.range.elapsed,
1751            foundry.range.cooldown,
1752            foundry.feedback.shot,
1753        );
1754        let handle = foundry.range.shots[0].handle;
1755        let position = foundry.range.physics.bodies[handle].translation();
1756        let tick = foundry.session.tick();
1757        foundry.set_paused(true);
1758        let events = foundry.advance(60.0, true);
1759        assert_eq!(events.alpha, 1.0);
1760        assert!(!events.fired);
1761        assert_eq!(
1762            before,
1763            (
1764                foundry.range.elapsed,
1765                foundry.range.cooldown,
1766                foundry.feedback.shot
1767            )
1768        );
1769        assert_eq!(position, foundry.range.physics.bodies[handle].translation());
1770        assert_eq!(tick, foundry.session.tick());
1771    }
1772
1773    #[test]
1774    fn rebuild_restores_resources_and_drops_input_clock_and_feedback_debt() {
1775        let mut foundry = Foundry::new(true);
1776        foundry.range.yaw = 0.4;
1777        foundry.range.elevation = 0.6;
1778        foundry.queue_fire();
1779        foundry.advance(0.05, false);
1780        assert_eq!(foundry.range.physics.bodies.len(), 14);
1781        for _ in 0..9 {
1782            foundry.advance(0.1, false);
1783        }
1784        foundry.range.blocks[3].down = true;
1785        foundry.feedback.destruction = 1.0;
1786        foundry.feedback.knocked_down = 1;
1787        foundry.queue_fire();
1788        assert!(foundry.pending_fire);
1789        foundry.rebuild();
1790        let game = &foundry.range;
1791        assert_eq!(foundry.session.state(), SessionState::Playing);
1792        assert_eq!(foundry.session.tick(), 0);
1793        assert_eq!(game.ammo, AMMO);
1794        assert_eq!(game.score(), 0);
1795        assert_eq!(game.phase, Phase::Aiming);
1796        assert!(game.shots.is_empty());
1797        assert_eq!(game.physics.bodies.len(), 13);
1798        assert_eq!(game.physics.colliders.len(), 13);
1799        assert_eq!(game.yaw, 0.0);
1800        assert_eq!(game.elevation, 0.13);
1801        assert_eq!(
1802            (game.elapsed, game.cooldown, game.since_shot),
1803            (0.0, 0.0, 0.0)
1804        );
1805        assert!(game.preview.is_empty());
1806        assert!(game.preview_hit.is_none());
1807        assert!(!foundry.pending_fire);
1808        assert_eq!(
1809            (foundry.feedback.shot, foundry.feedback.destruction),
1810            (0.0, 0.0)
1811        );
1812        assert_eq!(foundry.feedback.knocked_down, 0);
1813        assert!(foundry.feedback.rebuilt > 0.0);
1814        assert!(!foundry.advance(0.001, false).fired);
1815        assert_eq!(foundry.session.tick(), 0);
1816        assert_eq!(foundry.range.elapsed, 0.0);
1817        foundry.set_paused(true);
1818        foundry.rebuild();
1819        assert_eq!(foundry.session.state(), SessionState::Playing);
1820        assert_eq!(foundry.range.ammo, AMMO);
1821    }
1822
1823    #[test]
1824    fn last_shot_gets_full_settling_time_before_loss() {
1825        let mut foundry = Foundry::new(true);
1826        foundry.range.yaw = 0.5;
1827        while foundry.range.ammo > 0 {
1828            foundry.queue_fire();
1829            foundry.advance(1.0 / 120.0, false);
1830            if foundry.range.ammo > 0 {
1831                for _ in 0..9 {
1832                    foundry.advance(0.1, false);
1833                }
1834            }
1835        }
1836        for _ in 0..59 {
1837            foundry.advance(0.1, false);
1838        }
1839        assert_eq!(foundry.session.state(), SessionState::Playing);
1840        assert_eq!(foundry.range.phase, Phase::Aiming);
1841        let events = foundry.advance(0.1, false);
1842        assert_eq!(events.outcome, Some(Phase::Lost));
1843        assert_eq!(foundry.session.state(), SessionState::Lost);
1844        assert!(!foundry.range.fire());
1845    }
1846
1847    #[test]
1848    fn terminal_result_is_emitted_once_and_stops_remaining_catchup_steps() {
1849        for won in [true, false] {
1850            let mut foundry = Foundry::new(true);
1851            if won {
1852                for block in &mut foundry.range.blocks {
1853                    block.down = block.target;
1854                }
1855            } else {
1856                foundry.range.ammo = 0;
1857                foundry.range.since_shot = SETTLE;
1858            }
1859            let phase = if won { Phase::Won } else { Phase::Lost };
1860            let events = foundry.advance(0.1, false);
1861            assert_eq!(events.outcome, Some(phase));
1862            assert_eq!(events.alpha, 1.0);
1863            assert_eq!(foundry.range.elapsed, DT);
1864            let handle = foundry.range.blocks[3].handle;
1865            let position = foundry.range.physics.bodies[handle].translation();
1866            for block in &mut foundry.range.blocks {
1867                block.down = block.target;
1868            }
1869            foundry.queue_fire();
1870            assert!(!foundry.advance(1.0, true).fired);
1871            assert!(foundry.advance(1.0, true).outcome.is_none());
1872            foundry.range.step(DT);
1873            assert_eq!(
1874                foundry.range.phase, phase,
1875                "a late knockdown cannot reverse a verdict"
1876            );
1877            assert_eq!(foundry.range.elapsed, DT);
1878            assert_eq!(position, foundry.range.physics.bodies[handle].translation());
1879            foundry.rebuild();
1880            assert_eq!(foundry.session.state(), SessionState::Playing);
1881            assert_eq!(foundry.range.ammo, AMMO);
1882            assert_eq!(foundry.range.score(), 0);
1883        }
1884    }
1885
1886    fn started(autoplay: bool) -> Foundry {
1887        let mut foundry = Foundry::new(autoplay);
1888        // Autoplay sessions start themselves; interactive ones need Start.
1889        assert_eq!(foundry.start(), !autoplay);
1890        assert!(foundry.session.is_playing());
1891        foundry
1892    }
1893
1894    #[test]
1895    fn bell_aim_rings_the_secret_bell_once_without_touching_physics() {
1896        let mut foundry = started(false);
1897        let bodies = foundry.range.physics.bodies.len();
1898        (foundry.range.yaw, foundry.range.elevation) = BELL_AIM;
1899        foundry.queue_fire();
1900        let mut callouts = Vec::new();
1901        for _ in 0..360 {
1902            callouts.extend(foundry.advance(1.0 / 120.0, false).callout);
1903        }
1904        let tally = &foundry.range.tally;
1905        assert!(tally.bell);
1906        assert_eq!(callouts, [Callout::Bell]);
1907        assert_eq!(tally.points, score::BELL_BONUS, "clean over the tower");
1908        assert_eq!(foundry.range.score(), 0);
1909        assert_eq!(
1910            foundry.range.physics.bodies.len(),
1911            bodies + 1,
1912            "sensor only"
1913        );
1914        assert_eq!(tally.misses, 0, "ringing the bell is not a miss");
1915        assert_eq!(foundry.juice.bubble.unwrap().mood, Mood::Bell);
1916        assert!(quips::rank(foundry.summary()).title.contains("BELL"));
1917    }
1918
1919    #[test]
1920    fn autoplay_score_events_and_stars_match_across_frame_rates() {
1921        let mut reference = None;
1922        for fps in [30, 60, 144] {
1923            let mut foundry = started(true);
1924            let mut timbers = 0;
1925            for _ in 0..20 * fps {
1926                let events = foundry.advance(1.0 / f64::from(fps), true);
1927                timbers += usize::from(events.callout == Some(Callout::Timber));
1928                assert!(foundry.range.events.as_slice().is_empty(), "drained");
1929            }
1930            assert_eq!(foundry.session.state(), SessionState::Won);
1931            let tally = foundry.range.tally.clone();
1932            assert_eq!(usize::from(tally.shots), foundry.range.shots.len());
1933            assert_eq!(tally.targets, GOAL as u32);
1934            assert_eq!(tally.spare, foundry.range.ammo);
1935            assert!(timbers >= 1, "{fps}: a tower fell with a TIMBER call");
1936            let summary = foundry.summary();
1937            assert!(summary.won && summary.stars >= 2, "{summary:?}");
1938            // Targets pay at least 100 each, and spare shells pay a bonus.
1939            assert!(
1940                tally.points
1941                    >= 6 * score::TARGET_POINTS + u32::from(tally.spare) * score::SPARE_BONUS
1942            );
1943            if let Some(reference) = &reference {
1944                assert_eq!(&tally, reference, "{fps} Hz score diverged");
1945            }
1946            reference = Some(tally);
1947        }
1948    }
1949
1950    #[test]
1951    fn a_wide_shot_is_a_miss_that_gus_comments_on_and_pause_freezes_juice() {
1952        let mut foundry = started(false);
1953        foundry.range.yaw = 0.5;
1954        foundry.queue_fire();
1955        assert!(foundry.advance(1.0 / 120.0, false).fired);
1956        for _ in 0..40 {
1957            foundry.advance(0.1, false);
1958        }
1959        assert_eq!(foundry.range.tally.misses, 1);
1960        assert_eq!(foundry.range.tally.points, 0);
1961        let bubble = foundry.juice.bubble.expect("Gus reacts to the miss");
1962        assert_eq!(bubble.mood, Mood::Miss);
1963        foundry.set_paused(true);
1964        let age = bubble.age;
1965        let time = foundry.juice.time;
1966        foundry.advance(30.0, false);
1967        assert_eq!(foundry.juice.bubble.unwrap().age, age);
1968        assert_eq!(foundry.juice.time, time);
1969        // Rebuild resets the run's score but keeps Gus's line counters moving.
1970        foundry.rebuild();
1971        assert_eq!(foundry.range.tally, Tally::default());
1972        assert_eq!(foundry.juice.bubble.unwrap().mood, Mood::Retry);
1973    }
1974
1975    #[test]
1976    fn camera_kick_is_presentation_only_and_keeps_eye_and_depth() {
1977        let base = RangeCamera::new(1280.0, 800.0);
1978        let shifted = RangeCamera::new(1280.0, 800.0).shifted(1280.0, 800.0, vec2(6.0, -4.0));
1979        assert_eq!(shifted.eye, base.eye);
1980        let a = base.project(1280.0, 800.0, PIVOT).unwrap();
1981        let b = shifted.project(1280.0, 800.0, PIVOT).unwrap();
1982        assert!((b - a - vec2(6.0, -4.0)).length() < 0.01, "{a:?} -> {b:?}");
1983        let clip = |camera: &RangeCamera| camera.matrix * PIVOT.extend(1.0);
1984        assert_eq!(clip(&base).z, clip(&shifted).z);
1985        assert_eq!(clip(&base).w, clip(&shifted).w);
1986        let same = RangeCamera::new(1280.0, 800.0).shifted(1280.0, 800.0, Vec2::ZERO);
1987        assert_eq!(same.matrix, base.matrix);
1988    }
1989
1990    #[test]
1991    fn reticle_identifies_targets_and_supports_under_the_preview() {
1992        let mut game = Range::new();
1993        let support = game.blocks[5].home + vec3(0.0, 0.0, 0.96);
1994        assert!(!game.block_at(support).unwrap().target);
1995        let target = game.blocks[6].home + vec3(0.0, 0.1, 0.96);
1996        assert!(game.block_at(target).unwrap().target);
1997        assert!(game.block_at(vec3(0.0, 0.0, 10.0)).is_none());
1998        game.aim_at(vec3(0.0, 1.8, -4.0));
1999        game.refresh_preview(false);
2000        let hit = game.preview_hit.unwrap();
2001        assert!(
2002            !game.block_at(hit).unwrap().target,
2003            "autoplay aims at supports"
2004        );
2005    }
2006}