1mod animation;
21mod bots;
22#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
23mod capture;
24mod cards;
25mod controls;
26#[cfg(test)]
27mod corner_tests;
28mod crew;
29mod effects;
30mod geometry;
31mod host;
32mod hud;
33#[cfg(test)]
34mod journey200_tests;
35mod juice;
36#[cfg(target_arch = "wasm32")]
37mod multiplayer;
38mod replay;
39mod scoreboard;
40mod style;
41
42use controls::Controls;
43use effects::CombatEffects;
44use ferravex_core::FrameStats;
45#[cfg(not(target_arch = "wasm32"))]
46use ferravex_fps::GameClient;
47use ferravex_fps::{Arena, Match, forward};
48use ferravex_play::camera::{Input3, Mode3, NoObstructions, Rig3, Settings3, Target3};
49use ferravex_render::audio::{self, Cue, GameAudio, Surface};
50use ferravex_render::prelude::*;
51use ferravex_render::shaders::{LitMaterial, LitSettings};
52use geometry::{build_operator, build_yard, rgb};
53use host::{Host, Mode};
54
55fn window_conf() -> Conf {
56 #[allow(unused_mut)]
57 let mut conf = ferravex_render::window_conf("Ferravex / Strike — Dockyard");
58 conf.window_width = 1440;
59 conf.window_height = 900;
60 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
61 capture::window(&mut conf);
62 conf
63}
64
65#[derive(Default)]
66struct Options {
67 #[cfg(not(target_arch = "wasm32"))]
68 connect: Option<String>,
69 smoke_frames: Option<u64>,
70 #[cfg(not(target_arch = "wasm32"))]
71 screenshot: Option<String>,
72 #[cfg(not(target_arch = "wasm32"))]
73 capture_dir: Option<String>,
74 play: bool,
75 #[cfg(not(target_arch = "wasm32"))]
76 record: Option<String>,
77 #[cfg(not(target_arch = "wasm32"))]
78 replay: Option<String>,
79}
80#[cfg(target_arch = "wasm32")]
81fn options() -> Options {
82 Options::default()
83}
84
85#[cfg(not(target_arch = "wasm32"))]
86fn options() -> Options {
87 let mut out = Options::default();
88 #[cfg(not(target_arch = "wasm32"))]
89 {
90 let mut args = std::env::args().skip(1);
91 while let Some(arg) = args.next() {
92 match arg.as_str() {
93 "--connect" => out.connect = args.next(),
94 "--smoke-frames" => out.smoke_frames = args.next().and_then(|s| s.parse().ok()),
95 "--screenshot" => out.screenshot = args.next(),
96 "--capture-dir" => out.capture_dir = args.next(),
97 "--play" => out.play = true,
98 "--record" => out.record = args.next(),
99 "--replay" => out.replay = args.next(),
100 "--help" => {
101 println!(
102 "strike [--connect 127.0.0.1:4000] [--play] [--smoke-frames N] [--screenshot path.png] [--capture-dir directory] [--record clip.fxrt] [--replay clip.fxrt]"
103 );
104 std::process::exit(0);
105 }
106 _ => eprintln!("Unknown option: {arg}"),
107 }
108 }
109 }
110 if out.connect.is_some() && (out.record.is_some() || out.replay.is_some()) {
111 eprintln!("Replay tools require offline practice; omit --connect");
112 std::process::exit(2);
113 }
114 out
115}
116
117fn practice() -> Match {
118 let mut game = Match::new(Arena::default());
119 for id in 0..6 {
120 game.spawn_player(id);
121 }
122 game
123}
124
125fn reset_practice(game: &mut Match, bots: &mut bots::PracticeBots, replays: &mut replay::Session) {
126 let recording = replays.recording();
127 replays.reset_practice();
128 *game = practice();
129 *bots = bots::PracticeBots::new(&game.arena);
130 if recording {
131 replays.start_record(game);
132 }
133}
134
135const MAX_TRACERS: usize = 32;
136fn apply_game_events(
139 events: impl IntoIterator<Item = ferravex_fps::GameEvent>,
140 local_id: u8,
141 effects: &mut CombatEffects,
142 sound: &mut GameAudio,
143) {
144 for event in events {
145 match event {
146 ferravex_fps::GameEvent::Shot {
147 player,
148 origin,
149 end,
150 } => {
151 if player == local_id {
152 if effects.local_shot(origin) {
153 sound.cue(Cue::Fire, 0.75);
154 }
155 } else {
156 sound.at(Cue::Fire, origin, 0.75);
157 }
158 effects.shot(player != local_id, origin, end);
159 }
160 ferravex_fps::GameEvent::Hit {
161 attacker, victim, ..
162 } => {
163 effects.hit(attacker == local_id, victim == local_id);
164 }
165 ferravex_fps::GameEvent::Killed { victim, .. } if victim == local_id => {
166 sound.cue(Cue::Failure, 0.5);
167 }
168 _ => {}
169 }
170 }
171}
172
173#[allow(clippy::too_many_arguments)]
176fn present_events(
177 events: &[ferravex_fps::GameEvent],
178 tick: u32,
179 local_id: u8,
180 bots: bool,
181 board: &mut scoreboard::Tracker,
182 juice: &mut juice::Juice,
183 effects: &mut CombatEffects,
184 sound: &mut GameAudio,
185) {
186 apply_game_events(events.iter().copied(), local_id, effects, sound);
187 for event in events {
188 if let ferravex_fps::GameEvent::Hit {
189 attacker,
190 victim,
191 damage,
192 headshot,
193 } = *event
194 {
195 if attacker == local_id && victim != local_id {
196 juice.hit(headshot, sound);
197 } else if victim == local_id {
198 juice.hurt(damage);
199 }
200 }
201 }
202 board.observe(tick, events, |moment| {
203 juice.moment(moment, local_id, bots, sound);
204 });
205}
206
207fn practice_over(host: &Host, replays: &replay::Session) -> bool {
209 host.finished() && !replays.playing()
210}
211
212fn practice_board() -> scoreboard::Tracker {
213 scoreboard::Tracker::new(0, true)
214}
215
216#[cfg(target_arch = "wasm32")]
218#[link(wasm_import_module = "env")]
219unsafe extern "C" {
220 fn ferravex_set_playing(playing: i32);
221}
222#[cfg(target_arch = "wasm32")]
223#[unsafe(no_mangle)]
224pub extern "C" fn ferravex_ui_crate_version() -> u32 {
225 1
226}
227
228fn sync_browser_ui(playing: bool) {
229 #[cfg(target_arch = "wasm32")]
230 unsafe {
232 ferravex_set_playing(i32::from(playing));
233 }
234 #[cfg(not(target_arch = "wasm32"))]
235 let _ = playing;
236}
237
238ferravex_render::game!(window_conf, game);
239async fn game() {
240 let opts = options();
241 simulate_mouse_with_touch(false);
242 let mut game = practice();
243 let mut bots = bots::PracticeBots::new(&game.arena);
244 let mut commands = Vec::with_capacity(ferravex_fps::MAX_PLAYERS);
245 ferravex_render::set_quality(ferravex_render::lighting::Quality::Medium);
246 let mut arena = build_yard(&game.arena);
247 let ao =
248 ferravex_render::ao::AoScene::new([(&arena.mesh, Mat4::IDENTITY)]).expect("yard AO scene");
249 ao.bake(
250 &mut arena.mesh,
251 Mat4::IDENTITY,
252 ferravex_render::ao::AoSettings {
253 samples: 8,
254 radius: 1.5,
255 strength: 0.3,
256 max_tests: 20_000_000,
257 ..Default::default()
258 },
259 )
260 .expect("yard vertex AO");
261 let operator = build_operator();
262 let weapons = geometry::Weapons::new();
263 let objectives = geometry::Objectives::new();
264 let operator_rig = animation::OperatorRig::new();
265 let mut operator_motion: Vec<_> = (0..ferravex_fps::MAX_PLAYERS)
266 .map(|_| animation::OperatorMotion::new(&operator_rig))
267 .collect();
268 let mut weapon_motion = animation::WeaponMotion::new();
269 let mut look_state = style::LookState::default();
270 let mut effects = CombatEffects::new();
271 let duck = geometry::build_duck();
272 let mut juice = juice::Juice::new();
273 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
274 let mut capture = capture::Capture::from_env();
275 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
276 let new_board =
277 |capture: &capture::Capture| practice_board().with_seconds(capture.match_seconds);
278 #[cfg(not(all(debug_assertions, not(target_arch = "wasm32"))))]
279 let new_board = |_: &()| practice_board();
280 #[cfg(not(all(debug_assertions, not(target_arch = "wasm32"))))]
281 let capture = ();
282 let mut board = new_board(&capture);
284 let mut tuning = bots::Tuning::new();
285 let mut view_board = scoreboard::Tracker::new(0, false);
286 let mut onboarding = juice::Onboarding::default();
287 let mut info_rows: [String; 3] = Default::default();
288 let mut records = ferravex_render::storage::Records::new("strike").ok();
290 let mut results: Option<cards::Results> = None;
291 #[cfg(not(target_arch = "wasm32"))]
292 let mut net_events = Vec::with_capacity(64);
293
294 let shader = LitMaterial::new();
295 #[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
296 let mut error = shader.as_ref().err().cloned().unwrap_or_default();
297 #[cfg(not(target_arch = "wasm32"))]
298 let mut client = opts
299 .connect
300 .as_ref()
301 .and_then(|addr| match GameClient::connect(addr) {
302 Ok(client) => Some(client),
303 Err(e) => {
304 error = format!("Connection error: {e}");
305 None
306 }
307 });
308 #[cfg(not(target_arch = "wasm32"))]
309 let network = opts.connect.is_some();
310 #[cfg(target_arch = "wasm32")]
311 let mut webnet = multiplayer::Session::default();
312 let mut host = Host::new(opts.play || ferravex_render::autoplay_enabled());
313 let mut diagnostics = false;
314 let mut browser_playing = host.active();
315 sync_browser_ui(host.active());
316 let mut controls = Controls::default();
317 let mut hud_ui = ferravex_render::ui::Ui::new();
318 let mut menu_fx = hud::MenuFx::new();
319 let mut replays = replay::Session::default();
320 #[cfg(not(target_arch = "wasm32"))]
321 if let Some(path) = &opts.replay {
322 match ferravex_render::storage::read_file(std::path::Path::new(path), 8 * 1024 * 1024) {
323 Ok(Some(bytes)) => {
324 if let Err(e) = replays.import(&bytes, &game) {
325 error = format!("Replay: {e}");
326 }
327 }
328 other => error = format!("Replay read failed: {other:?}"),
329 }
330 }
331 #[cfg(not(target_arch = "wasm32"))]
332 if opts.record.is_some() {
333 replays.start_record(&game);
334 }
335 let mut sound = GameAudio::new();
336 let mut was_reload = 0;
337 let mut stats = FrameStats::<120>::default();
338 let mut frames = 0u64;
339 let mut last_command = None;
340 let mut command_notice: Option<(&'static str, f32)> = None;
341 let mut local = game.players[0].clone();
342 let mut remote = game.players.clone();
343 let mut server_tick = 0;
344 let mut previous_local_position = local.position;
345 let mut view_rig = Rig3::new(Settings3 {
346 position_half_life: 0.,
347 target_half_life: 0.,
348 fov_half_life: 0.,
349 teleport_distance: Some(2.),
350 ..Default::default()
351 })
352 .unwrap();
353 if host.active() && opts.smoke_frames.is_none() {
354 set_cursor_grab(true);
355 show_mouse(false);
356 }
357
358 let mut replay_initial_cut = replays.playing();
359 loop {
360 let dt = if opts.smoke_frames.is_some() {
361 1.0 / 60.0
362 } else {
363 get_frame_time().min(0.25)
364 };
365 stats.record(get_frame_time());
366 if let Some((_, time)) = &mut command_notice {
367 *time -= dt;
368 if *time <= 0. {
369 command_notice = None;
370 }
371 }
372 #[cfg(not(target_arch = "wasm32"))]
373 {
374 controls.show_interact = client.as_ref().and_then(|c| c.tactical_view()).is_some();
375 }
376 #[cfg(target_arch = "wasm32")]
377 {
378 controls.show_interact = webnet.round().is_some();
379 }
380 controls.prepare(host.active());
381 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
384 let keep_focus = capture.keep_focus;
385 #[cfg(not(all(debug_assertions, not(target_arch = "wasm32"))))]
386 let keep_focus = false;
387 macro_rules! gameplay {
388 () => {
389 keep_focus || controls.input.gameplay_active()
390 };
391 }
392 effects.begin_frame();
393 let policy = ferravex_render::preferences::feedback_policy();
394 weapon_motion.set_reduced_motion(policy.reduced_motion() || policy.intensity() == 0.);
395 juice.apply_policy(policy);
396 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
397 if capture.pause_now() && host.active() {
398 host.open_menu();
399 }
400 if controls.input.pressed("pause") {
401 if host.active() {
402 host.open_menu();
403 } else if !practice_over(&host, &replays) {
404 host.resume();
405 controls.input.sample(true);
406 view_rig.cut();
407 }
408 }
409 if host.active() && !gameplay!() {
410 host.open_menu();
413 }
414 #[cfg(target_arch = "wasm32")]
415 let finished_practice = practice_over(&host, &replays) && !webnet.active();
416 #[cfg(not(target_arch = "wasm32"))]
417 let finished_practice = practice_over(&host, &replays) && !network;
418 if host.active() && finished_practice {
419 host.open_menu();
421 }
422 let active = host.active();
423 if active && gameplay!() {
424 sound.resume();
425 } else {
426 sound.pause();
427 }
428 if controls.input.pressed("diagnostics") {
429 diagnostics = !diagnostics;
430 }
431 #[cfg(target_arch = "wasm32")]
432 let net_changed = {
433 let changed = webnet.before_frame();
434 if changed && webnet.active() {
435 replays.stop_record();
436 if replays.playing() {
437 replays.toggle_playback(&game);
438 }
439 }
440 if webnet.active() {
441 if let Some(p) = webnet.local() {
442 local = p.clone();
443 }
444 remote = webnet.players();
445 server_tick = webnet.tick_number();
446 let local_id = local.id;
447 view_board.set_local(local_id);
448 let events = webnet.drain_events();
449 present_events(
450 &events,
451 server_tick,
452 local_id,
453 false,
454 &mut view_board,
455 &mut juice,
456 &mut effects,
457 &mut sound,
458 );
459 }
460 changed
461 };
462 #[cfg(target_arch = "wasm32")]
463 let network = webnet.active();
464 let mut cut_replay = replays.controls(&mut controls.input, &game, network);
465 #[cfg(target_arch = "wasm32")]
466 {
467 cut_replay |= net_changed;
468 }
469 cut_replay |= std::mem::take(&mut replay_initial_cut);
470 cut_replay |= replays.browser_poll(&game, network);
471 cut_replay |= replays.pump();
472 let mode = if network {
473 Mode::Network
474 } else if replays.playing() {
475 Mode::Replay
476 } else {
477 Mode::Practice
478 };
479 if cut_replay {
480 controls.cut();
481 command_notice = None;
482 last_command = None;
483 if !network {
484 let source = replays.world.as_ref().map_or(&game, |w| &w.game);
485 local = source
486 .player(0)
487 .cloned()
488 .unwrap_or_else(|| game.players[0].clone());
489 remote.clone_from(&source.players);
490 server_tick = source.tick;
491 }
492 controls.yaw = local.yaw;
493 controls.pitch = local.pitch;
494 previous_local_position = local.position;
495 was_reload = local.reload_ticks;
496 effects = CombatEffects::new();
497 effects.begin_frame();
498 juice.reset();
499 view_board = scoreboard::Tracker::new(local.id, false);
500 sound.reset();
501 host.cut_replay();
502 view_rig.cut();
503 for motion in &mut operator_motion {
504 *motion = animation::OperatorMotion::new(&operator_rig);
505 }
506 weapon_motion = animation::WeaponMotion::new();
507 weapon_motion.set_reduced_motion(policy.reduced_motion() || policy.intensity() == 0.);
508 }
509 #[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
510 let mut input = controls.sample(active);
511 if replays.playing() {
512 controls.yaw = local.yaw;
513 controls.pitch = local.pitch;
514 }
515 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
516 if active
517 && mode == Mode::Practice
518 && let Some((yaw, pitch, fire)) = capture.aim(&game, board.duck_found())
519 {
520 controls.yaw = yaw;
521 controls.pitch = pitch;
522 input.yaw = yaw;
523 input.pitch = pitch;
524 input.buttons = if fire { ferravex_fps::BUTTON_FIRE } else { 0 };
525 if capture.walk() {
526 input.move_z = 1.;
527 }
528 }
529 #[cfg(not(target_arch = "wasm32"))]
530 if opts.capture_dir.is_some() && active {
531 let t = frames as f32 / 60.0;
532 input.yaw = (t * 0.18).sin() * 1.2;
533 input.pitch = -0.03;
534 input.move_z = if t < 8.0 { 0.8 } else { 0.2 };
535 input.move_x = (t * 0.7).sin() * 0.6;
536 input.buttons = if (frames / 120).is_multiple_of(3) {
537 ferravex_fps::BUTTON_RELOAD
538 } else {
539 ferravex_fps::BUTTON_FIRE
540 };
541 }
542 let frame = host.advance(mode, dt as f64, gameplay!(), !cut_replay && !replays.paused);
543 #[cfg(not(target_arch = "wasm32"))]
544 if let Some(c) = client.as_mut() {
545 if let Err(e) = c.poll() {
546 error = e.to_string();
547 }
548 let local_id = c.player_id().unwrap_or(local.id);
549 view_board.set_local(local_id);
550 net_events.clear();
551 net_events.extend(c.drain_events().into_iter().map(|message| message.event));
552 present_events(
553 &net_events,
554 c.server_tick(),
555 local_id,
556 false,
557 &mut view_board,
558 &mut juice,
559 &mut effects,
560 &mut sound,
561 );
562 }
563 #[cfg(not(target_arch = "wasm32"))]
564 let action_result = client.as_ref().and_then(|c| c.last_action_result());
565 #[cfg(target_arch = "wasm32")]
566 let action_result = webnet.action_result();
567 match action_result {
568 Some((sequence, result)) if last_command != Some(sequence) => {
569 last_command = Some(sequence);
570 command_notice = result.err().map(|e| (hud::rule_feedback(e), 2.5));
571 }
572 None => last_command = None,
573 _ => {}
574 }
575 for _ in 0..frame.steps {
576 let input = host.command(controls.tick(input), gameplay!());
577 #[cfg(not(target_arch = "wasm32"))]
578 let actions = controls.tactical_actions(
579 client.as_ref().and_then(|c| c.tactical_view()),
580 &local,
581 active,
582 );
583 #[cfg(target_arch = "wasm32")]
584 let actions = controls.tactical_actions(webnet.round(), &local, active);
585 for action in actions.into_iter().flatten() {
586 #[cfg(not(target_arch = "wasm32"))]
587 if let Some(c) = &mut client
588 && let Err(e) = c.queue_action(action)
589 {
590 error = e.to_string();
591 }
592 #[cfg(target_arch = "wasm32")]
593 webnet.act(action);
594 }
595 previous_local_position = local.position;
596 #[cfg(not(target_arch = "wasm32"))]
597 if let Some(c) = client.as_mut() {
598 if let Err(e) = c.tick(input) {
599 error = e.to_string();
600 }
601 if let Some(player) = c.local_player() {
602 local = player.clone();
603 }
604 remote.clear();
605 remote.extend_from_slice(c.players());
606 server_tick = c.server_tick();
607 continue;
608 }
609 #[cfg(target_arch = "wasm32")]
610 if webnet.active() {
611 let events = webnet.tick(input);
612 if let Some(p) = webnet.local() {
613 local = p.clone();
614 }
615 remote = webnet.players();
616 server_tick = webnet.tick_number();
617 present_events(
618 &events,
619 server_tick,
620 local.id,
621 false,
622 &mut view_board,
623 &mut juice,
624 &mut effects,
625 &mut sound,
626 );
627 continue;
628 }
629 if replays.playing() {
630 if !cut_replay && replays.advance() {
631 let w = replays.world.as_ref().unwrap();
632 present_events(
633 &w.events,
634 w.game.tick,
635 0,
636 true,
637 &mut view_board,
638 &mut juice,
639 &mut effects,
640 &mut sound,
641 );
642 local = w
643 .game
644 .player(0)
645 .cloned()
646 .unwrap_or_else(|| game.players[0].clone());
647 remote.clone_from(&w.game.players);
648 server_tick = w.game.tick;
649 controls.yaw = local.yaw;
650 controls.pitch = local.pitch;
651 }
652 continue;
653 }
654 if !network && active && gameplay!() {
655 bots.commands(&game, input, &mut commands);
656 tuning.adjust(&game, &mut commands);
657 let events = game.step(&commands);
658 replays.capture(&game, &commands, &events);
659 bots.events(&events);
660 tuning.events(game.tick, &events);
661 present_events(
662 &events,
663 game.tick,
664 0,
665 true,
666 &mut board,
667 &mut juice,
668 &mut effects,
669 &mut sound,
670 );
671 local = game.players[0].clone();
672 remote.clone_from(&game.players);
673 server_tick = game.tick;
674 if board.finished() && !host.finished() {
675 #[cfg(not(target_arch = "wasm32"))]
677 let recorded = opts.smoke_frames.is_none() && opts.capture_dir.is_none();
678 #[cfg(target_arch = "wasm32")]
679 let recorded = true;
680 let stored = records
681 .as_ref()
682 .and_then(|r| r.get(cards::RECORD_ID, cards::RECORD_RULES))
683 .map(|r| (r.score, r.runs));
684 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
685 let stored = capture.fake_best.map(|b| (b, 3)).or(stored);
686 if recorded && let Some(records) = records.as_mut() {
687 let _ = records.attempt(
688 cards::RECORD_ID,
689 cards::RECORD_RULES,
690 u64::from(board.summary.frags),
691 None,
692 );
693 }
694 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
695 let recorded = recorded || capture.fake_best.is_some();
696 let r = cards::Results::new(&board, stored.map(|(best, _)| best), recorded);
697 sound.cue(
698 if r.new_best {
699 Cue::Success
700 } else {
701 Cue::Pickup
702 },
703 0.7,
704 );
705 host.finish_match(board.summary.frags > board.summary.deaths);
706 results = Some(r);
707 break;
708 }
709 }
710 }
711 #[cfg(not(target_arch = "wasm32"))]
712 if let Some(c) = client.as_ref() {
713 remote = c.rendered_players();
714 if !c.is_connected() {
715 error = "Connecting to server...".into();
716 } else if error == "Connecting to server..." {
717 error.clear();
718 }
719 }
720 let fired = effects.fired;
721 onboarding.fired |= fired && mode == Mode::Practice;
722 onboarding.roster |= active && controls.input.held("roster");
723 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
724 if capture.learned {
725 onboarding = juice::Onboarding {
726 fired: true,
727 roster: true,
728 };
729 }
730 if !cut_replay && local.reload_ticks > 0 && was_reload == 0 {
731 sound.cue(Cue::Reload, 0.6);
732 }
733 was_reload = local.reload_ticks;
734 audio::listener(
735 Vec3::from_array(local.eye_position().to_array()),
736 vec3(controls.yaw.cos(), 0., controls.yaw.sin()),
737 );
738 sound.walk(
739 Vec3::from_array(local.position.to_array()),
740 local.grounded,
741 active && gameplay!() && local.health > 0,
742 Surface::Stone,
743 1.65,
744 );
745 effects.update(dt);
746 if let Some(playback) = &replays.playback {
747 ferravex_render::performance::context(Some(playback.position()), replays.diagnostic_id);
748 } else if !network {
749 ferravex_render::performance::context(Some(u64::from(game.tick)), None);
750 } else {
751 ferravex_render::performance::context(None, None);
752 }
753 let animation_dt = if cut_replay
754 || (mode == Mode::Practice && (!active || !gameplay!()))
755 || (replays.playing() && replays.paused)
756 {
757 0.
758 } else if active {
759 controls.input.simulation_dt(dt)
760 } else {
761 dt
762 };
763 for p in &remote {
764 if p.id == local.id {
765 continue;
766 }
767 if let Some(motion) = operator_motion.get_mut(p.id as usize) {
768 motion.update(&operator_rig, p, animation_dt);
769 motion.ground_contacts(&operator_rig, p, &game.arena, animation_dt);
770 if active && p.id != local.id && p.health > 0 && p.grounded {
771 for _ in 0..motion.footsteps() {
772 sound.at(Cue::Footstep(Surface::Stone), p.position, 0.28);
773 }
774 }
775 }
776 }
777 if let Some(motion) = operator_motion.get_mut(local.id as usize) {
780 motion.update(&operator_rig, &local, animation_dt);
781 motion.ground_contacts(&operator_rig, &local, &game.arena, animation_dt);
782 }
783 #[cfg(not(target_arch = "wasm32"))]
784 let round = client.as_ref().and_then(|c| c.tactical_view());
785 #[cfg(target_arch = "wasm32")]
786 let round = webnet.round();
787 juice.update(animation_dt);
788 juice.tactical(round, local.id, &mut sound);
789 let magazine_events =
790 weapon_motion.update(&local, if active { animation_dt } else { 0. }, fired);
791 if active {
792 for _ in 0..magazine_events {
793 sound.cue(Cue::Click, 0.2);
794 }
795 }
796 let sky = rgb(0xb8c4b7);
797 clear_background(sky);
798 let eye = if active {
799 let feet = if previous_local_position.distance_squared(local.position) < 4. {
800 previous_local_position.lerp(local.position, frame.alpha)
801 } else {
802 local.position
803 };
804 Vec3::from_array(feet.to_array()) + Vec3::Y * ferravex_fps::EYE_HEIGHT
805 } else {
806 let sway = if policy.reduced_motion() || policy.intensity() == 0. {
807 0.
808 } else {
809 (get_time() as f32 * 0.035).sin() * 2. * policy.intensity()
810 };
811 vec3(17. + sway, 11., 24.)
812 };
813 let direction = Vec3::from_array(forward(controls.yaw, controls.pitch).to_array());
814 let camera_input = if active {
815 let (kick_yaw, kick_pitch) = juice.kick();
817 Input3 {
818 target: Target3::at(eye),
819 mode: Mode3::FirstPerson {
820 eye_offset: Vec3::ZERO,
821 yaw: controls.yaw + kick_yaw,
822 pitch: controls.pitch + kick_pitch,
823 },
824 fov_y: 68_f32.to_radians(),
825 }
826 } else {
827 let focus = vec3(-3., 1., -3.);
828 Input3 {
829 target: Target3::at(focus),
830 mode: Mode3::Follow {
831 eye_offset: eye - focus,
832 look_offset: Vec3::ZERO,
833 },
834 fov_y: 68_f32.to_radians(),
835 }
836 };
837 let view = view_rig
838 .update(dt, camera_input, &NoObstructions)
839 .expect("valid shooter view")
840 .pose;
841 let eye = view.position;
842 let target = view.target;
843 let camera = Camera3D {
844 position: eye,
845 target,
846 up: view.up,
847 fovy: view.fov_y,
848 z_near: 0.04,
849 z_far: 150.,
850 ..Default::default()
851 };
852 set_camera(&camera);
853 let light = LitSettings {
854 camera_position: eye,
855 fog_color: sky,
856 fog_start: 28.,
857 fog_end: 100.,
858 ambient: 0.56,
859 light_direction: vec3(-0.5, 0.85, 0.3),
860 };
861 if let Ok(s) = &shader {
862 s.begin(light);
863 }
864 ferravex_render::set_sun_shadow(Some(ferravex_render::lighting::SunShadow {
865 center: vec3(eye.x, 0., eye.z),
866 direction: light.light_direction,
867 extent: 34.,
868 depth: 90.,
869 ..Default::default()
870 }))
871 .unwrap();
872 if effects.muzzle_timer > 0. {
873 ferravex_render::set_point_lights(&[ferravex_render::lighting::PointLight {
874 position: eye + direction * 0.8,
875 color: rgb(0xffb65c),
876 radius: 5.,
877 intensity: effects.muzzle_timer * 18.,
878 }])
879 .unwrap();
880 } else {
881 ferravex_render::set_point_lights(&[]).unwrap();
882 }
883 if let Some(g) = replays.ghost_sample(frame.alpha) {
884 replay::draw_ghost(g);
885 }
886 if active && local.health > 0 {
887 ferravex_render::draw_skinned_shadow(
888 &operator,
889 Mat4::from_rotation_translation(
890 Quat::from_rotation_y(-local.yaw),
891 Vec3::from_array(local.position.to_array()),
892 ),
893 operator_motion[local.id as usize].palette(),
894 );
895 }
896 arena.draw();
897 if !network
898 && let Some((position, yaw, scale)) =
899 juice.duck(mode == Mode::Practice && board.duck_found())
900 {
901 ferravex_render::draw_resident(
902 duck.resident(),
903 Mat4::from_scale_rotation_translation(
904 Vec3::splat(scale),
905 Quat::from_rotation_y(yaw),
906 position,
907 ),
908 );
909 }
910 if let Some(round) = round {
911 objectives.draw(round);
912 }
913 for p in &remote {
914 if (active && p.id == local.id) || p.health == 0 {
915 continue;
916 }
917 ferravex_render::draw_skinned(
918 &operator,
919 Mat4::from_rotation_translation(
920 Quat::from_rotation_y(-p.yaw),
921 Vec3::from_array(p.position.to_array()),
922 ),
923 operator_motion[p.id as usize].palette(),
924 );
925 }
926 let kind = round
927 .and_then(|r| r.player(local.id))
928 .map_or(ferravex_play::rounds::Weapon::Rifle, |p| p.weapon);
929 let (weapon, muzzle_local) = weapons.select(kind);
930 if active && local.health > 0 {
931 let side = direction.cross(Vec3::Y).normalize_or_zero();
932 let up = side.cross(direction).normalize_or_zero();
933 let offset = eye + side * 0.27 - up * 0.25 + direction * 0.47;
934 let rot = Quat::from_rotation_y(-controls.yaw) * Quat::from_rotation_x(controls.pitch);
935 ferravex_render::draw_skinned_viewmodel(
936 weapon,
937 Mat4::from_rotation_translation(rot, offset),
938 weapon_motion.palette(),
939 );
940 if fired {
941 let muzzle = offset
942 + rot
943 * weapon_motion
944 .palette()
945 .transform_point(
946 muzzle_local,
947 ferravex_render::skinning::SkinWeights::rigid(0),
948 )
949 .expect("valid muzzle bone");
950 effects.muzzle(muzzle);
951 }
952 }
953 if let Ok(s) = &shader {
954 s.end();
955 }
956 let effect_triangles = if active {
957 effects.draw(ferravex_render::effects::BillboardView::from_camera(&camera).unwrap())
958 as usize
959 } else {
960 0
961 };
962 look_state.apply(if !active {
963 style::Look::Menu
964 } else if local.health == 0 {
965 style::Look::Down
966 } else {
967 style::Look::Play
968 });
969 set_default_camera();
970 if effects.damage_flash > 0. {
971 draw_rectangle(
972 0.,
973 0.,
974 screen_width(),
975 screen_height(),
976 Color::new(0.6, 0.12, 0.05, effects.damage_flash),
977 );
978 }
979 if active {
980 juice.draw_glow();
981 }
982 let triangles = effect_triangles
983 + arena.triangles()
984 + remote
985 .iter()
986 .filter(|p| p.health > 0 && (!active || p.id != local.id))
987 .count()
988 * (operator.resident().vertex_count() / 3)
989 + if active && local.health > 0 {
990 weapon.resident().vertex_count() / 3
991 } else {
992 0
993 };
994 hud_ui.begin(
995 ferravex_render::ui::Viewport::fit(
996 [screen_width(), screen_height()],
997 [screen_width(), screen_height()],
998 [0.; 4],
999 )
1000 .unwrap(),
1001 );
1002 hud::overlay(
1003 &mut hud_ui,
1004 &local,
1005 hud::HudState {
1006 active,
1007 touch_mode: controls.touch_mode,
1008 diagnostics,
1009 frame_ms: stats.mean_ms(),
1010 triangles,
1011 tick: server_tick,
1012 hit_timer: effects.hit_timer,
1013 shot_timer: effects.shot_timer,
1014 input: &controls.input,
1015 round_phase: round.map(|r| r.phase),
1016 error: if error.is_empty() {
1017 command_notice.map_or("", |n| n.0)
1018 } else {
1019 &error
1020 },
1021 weapon: match kind {
1022 ferravex_play::rounds::Weapon::Rifle => "Rifle",
1023 ferravex_play::rounds::Weapon::Pistol => "Pistol",
1024 ferravex_play::rounds::Weapon::Sniper => "Sniper",
1025 },
1026 marker: juice.marker,
1027 death: juice.death,
1028 },
1029 );
1030 #[cfg(not(target_arch = "wasm32"))]
1031 {
1032 let round = client.as_ref().and_then(|c| c.tactical_view());
1033 let lobby = client.as_ref().and_then(|c| c.tactical_lobby());
1034 hud::tactical(&mut hud_ui, round, lobby, local.id, active, &controls.input);
1035 }
1036 #[cfg(target_arch = "wasm32")]
1037 hud::tactical(
1038 &mut hud_ui,
1039 webnet.round(),
1040 webnet.lobby(),
1041 local.id,
1042 active,
1043 &controls.input,
1044 );
1045 let footer = (!network || diagnostics) && replays.footer_visible(diagnostics);
1046 let mut info_card: Option<(f32, f32, cards::InfoStyle)> = None;
1047 let bots_named = !network;
1048 let shown_board = if mode == Mode::Practice {
1049 &board
1050 } else {
1051 &view_board
1052 };
1053 if active {
1054 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1055 let roster = controls.input.held("roster") || capture.roster();
1056 #[cfg(not(all(debug_assertions, not(target_arch = "wasm32"))))]
1057 let roster = controls.input.held("roster");
1058 let hint_kind = if mode == Mode::Practice && !roster && local.health > 0 {
1059 onboarding.hint(board.summary.frags)
1060 } else {
1061 None
1062 };
1063 let mut key_a = [0; 64];
1064 let mut key_b = [0; 64];
1065 let hint = hint_kind.map(|kind| {
1066 let (a, b) = match kind {
1067 juice::HintKind::FireReload => ("fire", "reload"),
1068 juice::HintKind::Scoreboard => ("roster", "roster"),
1069 };
1070 juice::Hint {
1071 kind,
1072 keys: [
1073 controls::hint(&controls.input, a, &mut key_a),
1074 controls::hint(&controls.input, b, &mut key_b),
1075 ],
1076 }
1077 });
1078 juice.draw_play(
1079 &board,
1080 juice::PlayLayout {
1081 practice: mode == Mode::Practice,
1082 round: round.is_some(),
1083 touch: controls.touch_mode,
1084 notice: !(error.is_empty() && command_notice.is_none()),
1085 footer,
1086 roster,
1087 alive: local.health > 0,
1088 hint,
1089 local: local.id,
1090 bots: bots_named,
1091 },
1092 );
1093 controls.draw_touch();
1094 if roster {
1095 hud::roster(&mut hud_ui, &remote, local.id, shown_board, bots_named);
1096 }
1097 } else if let Some(r) = results.as_ref().filter(|_| finished_practice) {
1098 cards::results(&mut hud_ui, r);
1099 } else {
1100 hud::menu(
1101 &mut hud_ui,
1102 mode,
1103 host.has_played(),
1104 controls.touch_mode,
1105 &controls.input,
1106 );
1107 if mode == Mode::Practice {
1108 let (left, bottom) = hud::menu_extent(
1109 screen_width(),
1110 screen_height(),
1111 mode,
1112 host.has_played(),
1113 controls.touch_mode,
1114 &controls.input,
1115 );
1116 let best = records
1117 .as_ref()
1118 .and_then(|r| r.get(cards::RECORD_ID, cards::RECORD_RULES))
1119 .map(|r| (r.score, r.runs));
1120 let style = if host.has_played() {
1121 cards::pause_rows(&board, best.map(|b| b.0), game.tick / 640, &mut info_rows);
1122 cards::PAUSE_STYLE
1123 } else {
1124 cards::briefing_rows(best, &controls.input, &mut info_rows);
1125 cards::BRIEFING_STYLE
1126 };
1127 cards::info(&mut hud_ui, left, bottom, &info_rows, style);
1128 info_card = Some((left, bottom, style));
1129 }
1130 }
1131 if footer && !finished_practice {
1132 replays.overlay(&mut hud_ui, diagnostics, &controls.input);
1133 }
1134 hud_ui.finish_player(&mut controls.input, !active);
1135 menu_fx.update(
1136 &hud_ui,
1137 !active && !finished_practice,
1138 dt.clamp(0., 0.1),
1139 style::motion(),
1140 );
1141 hud_ui.paint();
1142 if let Some((left, bottom, style)) = info_card {
1144 cards::info_glyphs(left, bottom, &info_rows, style);
1145 }
1146 if !active && let Some(r) = results.as_ref().filter(|_| finished_practice) {
1147 cards::results_glyphs(r);
1148 }
1149 if !active && !finished_practice {
1150 hud::menu_overlay(
1151 &menu_fx,
1152 mode,
1153 host.has_played(),
1154 controls.touch_mode,
1155 &controls.input,
1156 );
1157 }
1158 if !active && hud_ui.activated(1) {
1159 host.resume();
1160 controls.touch_mode |= !ferravex_render::input::logical_touches().is_empty();
1161 view_rig.cut();
1162 }
1163 if !active && hud_ui.activated(2) && host.restart_practice(mode) {
1164 reset_practice(&mut game, &mut bots, &mut replays);
1165 board = new_board(&capture);
1166 tuning = bots::Tuning::new();
1167 results = None;
1168 replay_initial_cut = true;
1169 }
1170 if !active && hud_ui.activated(3) && mode != Mode::Network {
1171 if mode == Mode::Replay {
1172 replays.toggle_playback(&game);
1173 } else {
1174 replays.stop_record();
1175 reset_practice(&mut game, &mut bots, &mut replays);
1176 board = new_board(&capture);
1177 tuning = bots::Tuning::new();
1178 results = None;
1179 host.return_to_briefing();
1180 }
1181 replay_initial_cut = true;
1182 }
1183 replays.browser_sync();
1184 #[cfg(target_arch = "wasm32")]
1185 webnet.sync();
1186 controls.input.draw_settings();
1187 let capture_mouse = host.active()
1188 && !controls.touch_mode
1189 && !controls.input.controls_open()
1190 && opts.smoke_frames.is_none();
1191 set_cursor_grab(capture_mouse);
1192 show_mouse(!capture_mouse);
1193 if browser_playing != host.active() {
1194 sync_browser_ui(host.active());
1195 browser_playing = host.active();
1196 }
1197 #[cfg(not(target_arch = "wasm32"))]
1198 if let Some(directory) = &opts.capture_dir {
1199 std::fs::create_dir_all(directory).expect("create capture directory");
1200 get_screen_data().export_png(&format!("{directory}/{frames:06}.png"));
1201 }
1202 frames += 1;
1203 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1204 capture.end_frame();
1205 if opts.smoke_frames.is_some_and(|limit| frames >= limit) {
1206 #[cfg(not(target_arch = "wasm32"))]
1207 println!(
1208 "STRIKE mode={} connected={} server_tick={} frames={} error={}",
1209 if network { "network" } else { "offline" },
1210 client.as_ref().is_some_and(|c| c.player_id().is_some()),
1211 server_tick,
1212 frames,
1213 error
1214 );
1215 #[cfg(not(target_arch = "wasm32"))]
1216 if let Some(path) = &opts.screenshot {
1217 get_screen_data().export_png(path);
1218 }
1219 break;
1220 }
1221 next_frame().await;
1222 }
1223 #[cfg(not(target_arch = "wasm32"))]
1224 if let Some(path) = &opts.record
1225 && let Some(bytes) = replays.export()
1226 {
1227 let path = std::path::Path::new(path);
1228 let path = if path.is_absolute() {
1229 path.to_path_buf()
1230 } else {
1231 std::env::current_dir().unwrap().join(path)
1232 };
1233 match ferravex_render::storage::write_file(&path, &bytes) {
1234 Ok(()) => println!(
1235 "REPLAY exported {} bytes to {}",
1236 bytes.len(),
1237 path.display()
1238 ),
1239 Err(e) => eprintln!("Replay export failed: {e:?}"),
1240 }
1241 }
1242}
1243
1244#[cfg(test)]
1245mod event_effect_tests {
1246 use super::*;
1247 #[test]
1248 fn actual_accepted_shots_drive_feedback_and_rejected_fire_stays_silent() {
1249 let mut game = practice();
1250 let mut effects = CombatEffects::new();
1251 let mut sound = GameAudio::new();
1252 let fire = [(
1253 0,
1254 ferravex_fps::InputFrame {
1255 buttons: ferravex_fps::BUTTON_FIRE,
1256 ..Default::default()
1257 },
1258 )];
1259 effects.begin_frame();
1260 let events = game.step(&fire);
1261 let hash = game.state_hash();
1262 apply_game_events(events, 0, &mut effects, &mut sound);
1263 assert!(effects.fired);
1264 assert_eq!(game.state_hash(), hash);
1265 effects.update(0.);
1266 effects.begin_frame();
1267 apply_game_events(game.step(&fire), 0, &mut effects, &mut sound);
1268 assert!(!effects.fired, "cooldown rejects another shot");
1269 game.players[0].fire_cooldown = 0;
1270 game.players[0].ammo = 0;
1271 apply_game_events(game.step(&fire), 0, &mut effects, &mut sound);
1272 assert!(!effects.fired, "empty magazine rejects fire");
1273 sound.pause();
1274 let before = audio::stats().active;
1275 apply_game_events(
1276 [ferravex_fps::GameEvent::Shot {
1277 player: 1,
1278 origin: Vec3::Y,
1279 end: Vec3::ZERO,
1280 }],
1281 0,
1282 &mut effects,
1283 &mut sound,
1284 );
1285 assert_eq!(
1286 audio::stats().active,
1287 before,
1288 "menu audio is suppressed independently"
1289 );
1290 }
1291
1292 #[test]
1293 fn shots_and_other_players_hits_never_confirm_a_local_hit() {
1294 let mut effects = CombatEffects::new();
1295 effects.begin_frame();
1296 let mut sound = GameAudio::new();
1297 apply_game_events(
1298 [
1299 ferravex_fps::GameEvent::Shot {
1300 player: 0,
1301 origin: [0., 1., 0.].into(),
1302 end: [0., 1., -5.].into(),
1303 },
1304 ferravex_fps::GameEvent::Hit {
1305 attacker: 2,
1306 victim: 3,
1307 damage: 34,
1308 headshot: false,
1309 },
1310 ],
1311 0,
1312 &mut effects,
1313 &mut sound,
1314 );
1315 assert_eq!(effects.hit_timer, 0.);
1316 effects.update(0.);
1317 assert_eq!(effects.damage_flash, 0.);
1318 }
1319
1320 #[test]
1321 fn replicated_hits_confirm_only_authority_and_remote_tracers_are_bounded() {
1322 let mut effects = CombatEffects::new();
1323 effects.begin_frame();
1324 let mut sound = GameAudio::new();
1325 apply_game_events(
1326 [ferravex_fps::GameEvent::Hit {
1327 attacker: 0,
1328 victim: 1,
1329 damage: 34,
1330 headshot: false,
1331 }],
1332 0,
1333 &mut effects,
1334 &mut sound,
1335 );
1336 assert_eq!(effects.hit_timer, 0.25);
1337 effects.update(0.);
1338 assert_eq!(effects.damage_flash, 0.);
1339 for player in std::iter::repeat_n(1, MAX_TRACERS + 10).chain([0]) {
1340 apply_game_events(
1341 [ferravex_fps::GameEvent::Shot {
1342 player,
1343 origin: [0., 1., 0.].into(),
1344 end: [0., 1., -5.].into(),
1345 }],
1346 0,
1347 &mut effects,
1348 &mut sound,
1349 );
1350 }
1351 assert_eq!(effects.beams.len(), MAX_TRACERS);
1352 assert!(effects.particles.len() <= effects.particles.capacity());
1353 apply_game_events(
1354 [ferravex_fps::GameEvent::Hit {
1355 attacker: 1,
1356 victim: 0,
1357 damage: 34,
1358 headshot: false,
1359 }],
1360 0,
1361 &mut effects,
1362 &mut sound,
1363 );
1364 effects.update(0.);
1365 assert!(effects.damage_flash > 0.);
1366 }
1367}