Files
airdef/airdef-mod/src/replay.rs
T

993 lines
43 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Replays of recorded raids: the raid's map (every track over time), a clip
//! of any event, the whole raid, and a highlight reel of the best moments.
//! Clips are filmed: ghosts of the drones and interceptors fly again in the
//! world and a director's camera (a full-screen camera view) follows them —
//! behind the drone, then behind the interceptor or from the side — slowing
//! time round the moment itself.
use crate::film::{self, Film};
use crate::panel::distance;
use crate::sim::Ground;
use crate::sim::record::{EventKind, Recording, STEP, What};
use std::cell::Cell;
use crate::sim::{Class, DroneKind, Out, Sim};
use glam::DVec3;
use horizon_mod_sdk::render::{CameraView, FillShape, Point, QuadShape, Rect, Shape, TextShape};
/// Metres the camera keeps above the surface (land or water) it stands over.
const SURFACE_CLEAR: f64 = 2.5;
/// `eye` lifted above the surface under it (`Ground::land_state`: unanswered or no land: unchanged).
fn above_surface(eye: DVec3, land: Option<Option<f64>>) -> DVec3 {
match land {
Some(Some(h)) if eye.y < h + SURFACE_CLEAR => DVec3::new(eye.x, h + SURFACE_CLEAR, eye.z),
_ => eye,
}
}
/// Ghost models' ids, clear of the live ones.
const GHOSTS: u32 = 0x5000_0000;
/// The camera view's id (a new one each cut, so the game doesn't sweep between shots).
const VIEW: u32 = 0x7700_0000;
pub enum Mode {
/// The raid from above, its tracks drawn as time runs (the wheel scrubs).
Map,
/// The whole raid filmed, the director choosing what to follow (the wheel sets the speed).
Full,
/// Clips one after another (the wheel skips): one event, or the highlight reel.
Clips { list: Vec<Clip>, at: usize, reel: bool },
/// The director's film: planned shots from several angles with cuts and slow motion.
Film(Box<Film>),
}
pub struct Clip {
pub event: usize,
from: f64,
to: f64,
}
pub struct Player {
/// Which raid's recording (its number: the list drops the oldest as new ones come).
pub rec: u32,
pub mode: Mode,
t: f64,
speed: f64,
/// How fast the replay's time ran this tick (0 paused or held on a card; slowed round a moment).
rate: f64,
/// The director's current shot (event, shot) and the view id it films with.
shot: (usize, u8),
view: u32,
/// Ticks of black left after a cut, of the title card left.
fade: u32,
card: u32,
/// The camera where an interceptor met its target: it stays there after.
held: Option<DVec3>,
/// The eye this tick (sounds are heard from it).
eye: DVec3,
look: DVec3,
fov: f32,
/// The last tick whose events made their sounds.
heard: f64,
/// Time stands still (Space, or the end reached).
paused: bool,
/// The film's own clock in seconds (the replay's moment follows from the plan).
tau: f64,
/// The film waits for the recorder to start (an export).
pub wait: bool,
/// Titles and bars only: no keys, clock or help on the screen (an export).
pub clean: bool,
/// The film stops at this many seconds (a short test export).
pub limit: Option<f64>,
/// The film reached its end.
pub ended: bool,
/// Which of the two sets of ghost ids is in use (a cut changes it, so nothing glides across it).
alt: bool,
/// The film's shot, caption and blackness this tick.
cut: Option<(usize, f32, f32)>,
/// Ticks the controls stay on screen.
help: u32,
pub done: bool,
/// The map's area, worked out on the first map frame.
area: Cell<Option<[f64; 4]>>,
}
/// What the replay's keys do.
#[derive(Clone, Copy, PartialEq)]
pub enum Control {
Back,
Forward,
Faster,
Slower,
Pause,
}
/// The speeds ↑ and ↓ step through.
const SPEEDS: [f64; 8] = [0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0];
/// The keys, for the screen.
const KEYS_HELP: &str = "← → перемотка · ↑ ↓ скорость · Пробел пауза · R / Backspace выход";
fn fill(x: f32, y: f32, w: f32, h: f32, color: u32) -> Shape {
Shape::Fill(FillShape { rect: Rect { x, y, w, h }, color })
}
fn text(t: impl Into<String>, x: f32, y: f32, color: u32, centered: bool) -> Shape {
Shape::Text(TextShape { text: t.into(), at: Point { x, y }, color, centered, shadow: true })
}
fn line(a: (f32, f32), b: (f32, f32), w: f32, color: u32) -> Shape {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let len = (dx * dx + dy * dy).sqrt().max(0.01);
let (nx, ny) = (-dy / len * w * 0.5, dx / len * w * 0.5);
let p = |x: f32, y: f32| Point { x, y };
Shape::Quad(QuadShape { corners: (p(a.0 + nx, a.1 + ny), p(b.0 + nx, b.1 + ny), p(b.0 - nx, b.1 - ny), p(a.0 - nx, a.1 - ny)), color })
}
fn clock(ticks: f64) -> String {
let s = (ticks / 20.0).max(0.0);
format!("{:02}:{:04.1}", (s / 60.0) as u32, s % 60.0)
}
/// What an event was, in a line.
pub fn title(rec: &Recording, i: usize) -> String {
let e = &rec.events[i];
match e.kind {
EventKind::Kill { kind, sam_kind, sam_index, missile, .. } => {
let how = if missile.is_some() { "ракетой" } else { "огнём пушек" };
format!("{} №{} сбивает «{}» {how}", sam_kind.name(), sam_index + 1, kind.spec().name)
}
EventKind::Hit { kind, object: Some(o), .. } => format!("«{}» поражает объект №{}", kind.spec().name, o + 1),
EventKind::Hit { kind, sam: Some((sk, si)), .. } => format!("«{}» бьёт по {} №{}", kind.spec().name, sk.name(), si + 1),
EventKind::Hit { kind, .. } => format!("Прилёт: «{}»", kind.spec().name),
EventKind::SamLost { kind, index, .. } => format!("{} №{} уничтожен", kind.name(), index + 1),
EventKind::Split { .. } => "«Орешник»: разделение боевых блоков".into(),
EventKind::Crash { kind, .. } => format!("«{}» разбивается о препятствие", kind.spec().name),
}
}
/// A short line for the event list: its time and what it was.
pub fn row(rec: &Recording, i: usize) -> String {
let e = &rec.events[i];
let what = match e.kind {
EventKind::Kill { kind, sam_kind, sam_index, missile, .. } => {
format!("{}-{} > {}{}", sam_kind.name(), sam_index + 1, kind.spec().name, if missile.is_none() { " (пушки)" } else { "" })
}
EventKind::Hit { kind, object: Some(o), .. } => format!("{} > объект {}", kind.spec().name, o + 1),
EventKind::Hit { kind, sam: Some((sk, si)), .. } => format!("{} > {}-{}", kind.spec().name, sk.name(), si + 1),
EventKind::Hit { kind, .. } => format!("{}: прилёт", kind.spec().name),
EventKind::SamLost { kind, index, .. } => format!("{}-{} уничтожен", kind.name(), index + 1),
EventKind::Split { .. } => "Орешник: разделение".into(),
EventKind::Crash { kind, .. } => format!("{}: о рельеф", kind.spec().name),
};
format!("{} {what}", clock(e.at as f64))
}
/// How worth watching an event is: the reel takes the best.
pub fn interest(rec: &Recording, i: usize) -> f64 {
let e = &rec.events[i];
match e.kind {
EventKind::Kill { kind, missile, .. } => {
let spec = kind.spec();
let class = match spec.class {
Class::Ballistic => 10.0,
Class::Supersonic => 7.0,
Class::Cruise => 5.0,
Class::Jet => 4.0,
Class::Drone => 2.0,
};
let rare = match kind {
DroneKind::Kinzhal | DroneKind::Oreshnik | DroneKind::Zircon => 4.0,
DroneKind::OreshnikSub => -6.0,
_ => 0.0,
};
// A kill close to what it was going for.
let close = rec.objects.iter().chain(rec.sams.iter().map(|s| &s.2)).any(|o| o.distance(e.pos) < 40.0);
class + rare + if spec.decoy { -3.0 } else { 0.0 } + if missile.is_none() { 1.0 } else { 0.0 } + if close { 3.0 } else { 0.0 }
}
EventKind::Hit { power, object, sam, .. } => {
power as f64 * 1.5 + if object.is_some() { 6.0 } else if sam.is_some() { 5.0 } else { 0.0 }
}
EventKind::SamLost { .. } => 12.0,
EventKind::Crash { power, .. } => power as f64,
EventKind::Split { drone } => {
// The bus's split, not each block's.
let first = rec.events.iter().position(|o| matches!(o.kind, EventKind::Split { .. }));
if first == Some(i) || rec.track(drone).is_some_and(|t| t.what == What::Drone(DroneKind::Oreshnik)) { 11.0 } else { 0.0 }
}
}
}
/// The clip of event `i`: from a while before it to a little after.
fn clip(rec: &Recording, i: usize) -> Clip {
let at = rec.events[i].at as f64;
let (before, after) = match rec.events[i].kind {
EventKind::Kill { .. } => (140.0, 50.0),
EventKind::Hit { .. } => (160.0, 60.0),
EventKind::SamLost { .. } => (80.0, 90.0),
EventKind::Split { .. } => (40.0, 170.0),
EventKind::Crash { .. } => (120.0, 60.0),
};
Clip { event: i, from: (at - before).max(0.0), to: (at + after).min(rec.len as f64) }
}
/// The best moments, a few seconds apart, in order.
pub fn reel(rec: &Recording) -> Vec<Clip> {
let mut best: Vec<(f64, usize)> = (0..rec.events.len()).map(|i| (interest(rec, i), i)).filter(|b| b.0 >= 2.0).collect();
best.sort_by(|a, b| b.0.total_cmp(&a.0));
let mut chosen: Vec<usize> = Vec::new();
for (_, i) in best {
if chosen.len() >= 8 {
break;
}
let at = rec.events[i].at as i64;
if chosen.iter().all(|&c| (rec.events[c].at as i64 - at).abs() > 90) {
chosen.push(i);
}
}
chosen.sort_by_key(|&i| rec.events[i].at);
chosen.into_iter().map(|i| clip(rec, i)).collect()
}
impl Player {
pub fn new(rec: u32, mode: Mode, sim: &Sim) -> Self {
let start = match &mode {
Mode::Clips { list, .. } => list.first().map_or(0.0, |c| c.from),
_ => 0.0,
};
let reel = matches!(mode, Mode::Clips { reel: true, .. });
let speed = match mode {
Mode::Map => 8.0,
Mode::Full => 2.0,
Mode::Clips { .. } | Mode::Film(_) => 1.0,
};
let _ = sim;
Player {
area: Cell::new(None),
rec,
mode,
t: start,
speed,
rate: 0.0,
shot: (usize::MAX, 0),
view: VIEW,
fade: 0,
card: if reel { 50 } else { 0 },
held: None,
eye: DVec3::ZERO,
look: DVec3::NEG_Z,
fov: 50.0,
heard: start,
paused: false,
tau: 0.0,
wait: false,
clean: false,
limit: None,
ended: false,
alt: false,
cut: None,
help: 100,
done: false,
}
}
/// The wheel: scrubs the map and the full replay, skips clips.
pub fn wheel(&mut self, steps: f32, rec: &Recording) {
let c = if steps > 0.0 { Control::Back } else { Control::Forward };
for _ in 0..(steps.abs().round() as u32).max(1) {
self.control(c, rec);
}
}
/// A key: steps back or forward (5 s, or a moment of the reel), faster, slower, pause.
pub fn control(&mut self, c: Control, rec: &Recording) {
self.help = self.help.max(60);
match c {
Control::Faster | Control::Slower => {
let i = SPEEDS.iter().position(|s| *s >= self.speed).unwrap_or(2) as i32;
let j = (i + if c == Control::Faster { 1 } else { -1 }).clamp(0, SPEEDS.len() as i32 - 1);
self.speed = SPEEDS[j as usize];
self.paused = false;
}
Control::Pause => {
// At the end, Space plays it again.
if self.paused && self.at_end(rec) {
self.restart();
}
self.paused = !self.paused;
}
Control::Back | Control::Forward => {
let dir = if c == Control::Forward { 1 } else { -1 };
match &mut self.mode {
Mode::Map | Mode::Full => {
self.t = (self.t + dir as f64 * 100.0).clamp(0.0, rec.len as f64);
self.heard = self.t;
self.shot = (usize::MAX, 0);
}
Mode::Film(f) => {
// To the next or the previous plan.
let now = self.cut.map_or(0, |c| c.0);
let to = (now as i32 + dir).clamp(0, f.shots() as i32 - 1) as usize;
self.tau = f.start_of(to);
self.paused = false;
}
Mode::Clips { list, at, reel } => {
let next = (*at as i32 + dir).clamp(0, list.len() as i32 - 1) as usize;
// Back on the first moment: from its start again.
*at = next;
self.t = list[next].from;
self.heard = self.t;
self.fade = 6;
self.card = if *reel { 50 } else { 0 };
self.paused = false;
}
}
}
}
}
fn at_end(&self, rec: &Recording) -> bool {
match &self.mode {
Mode::Map | Mode::Full => self.t >= rec.len as f64,
Mode::Clips { list, at, .. } => *at + 1 >= list.len() && self.t >= list[*at].to,
Mode::Film(_) => self.ended,
}
}
fn restart(&mut self) {
let reel = matches!(self.mode, Mode::Clips { reel: true, .. });
self.t = match &mut self.mode {
Mode::Clips { list, at, .. } => {
*at = 0;
list[0].from
}
_ => 0.0,
};
self.tau = 0.0;
self.ended = false;
self.heard = self.t;
self.card = if reel { 50 } else { 0 };
self.fade = 6;
}
/// Where the camera is this tick.
pub fn eye(&self) -> DVec3 {
self.eye
}
/// The replay's moment, in the recording's ticks.
pub fn time(&self) -> f64 {
self.t
}
/// How fast the replay's time runs now, as a share of real time (1 normal, 0 held).
pub fn rate(&self) -> f32 {
self.rate as f32
}
/// Whether the world is filmed (the map is drawn on the HUD instead).
pub fn filming(&self) -> bool {
!matches!(self.mode, Mode::Map)
}
/// The camera the world is rendered from (`set-main-view`).
pub fn view_id(&self) -> u32 {
self.view
}
/// The time of day the raid was flown in, as of the replay's moment now.
pub fn day_time(&self, sim: &Sim) -> Option<u64> {
sim.replay(self.rec)?.day_time(self.t)
}
/// One tick: time runs, the ghosts fly, the director films. Models and sounds go to `out`.
pub fn tick(&mut self, sim: &Sim, ground: &mut Ground, listener: DVec3, out: &mut Out) {
let Some(rec) = sim.replay(self.rec) else {
self.done = true;
return;
};
if matches!(self.mode, Mode::Film(_)) {
self.tick_film(sim, ground, listener, out, rec);
return;
}
self.fade = self.fade.saturating_sub(1);
if self.card > 0 {
self.card -= 1;
}
self.help = self.help.saturating_sub(1);
// Time: slowed round the moment in clips (the chosen speed scales it), held still while a
// title card shows or paused.
let mut speed = self.speed;
if let Mode::Clips { list, at, .. } = &self.mode {
let te = rec.events[list[*at].event].at as f64;
if (te - 14.0..te + 18.0).contains(&self.t) {
speed *= 0.3;
}
if self.card > 25 {
speed = 0.0;
}
}
self.rate = if self.paused { 0.0 } else { speed };
if !self.paused {
self.t += speed;
}
// The end: it stops there, paused (Space plays it again, R leaves).
match &mut self.mode {
Mode::Map | Mode::Full => {
if self.t >= rec.len as f64 {
self.t = rec.len as f64;
self.paused = true;
}
}
Mode::Film(_) => {}
Mode::Clips { list, at, reel } => {
if self.t >= list[*at].to {
if *at + 1 < list.len() {
*at += 1;
self.t = list[*at].from;
self.heard = self.t;
self.fade = 6;
self.card = if *reel { 50 } else { 0 };
} else {
self.t = list[*at].to;
self.paused = true;
}
}
}
}
if matches!(self.mode, Mode::Map) {
return;
}
sim.draw_ghosts(rec, self.t, GHOSTS, out);
self.direct(rec, ground);
self.sounds(rec, listener, out);
}
/// Sounds as the camera hears them: moved so the player stands where the camera is.
fn sounds(&mut self, rec: &Recording, listener: DVec3, out: &mut Out) {
let heard = |p: DVec3| listener + (p - self.eye);
for e in rec.events.iter().filter(|e| (self.heard..self.t).contains(&(e.at as f64))) {
let event = match e.kind {
EventKind::Kill { .. } => "airdef:blast.air",
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => ["airdef:blast.air", "airdef:blast.medium", "airdef:blast.big", "airdef:blast.heavy", "airdef:blast.huge"][(power as usize).min(4)],
EventKind::SamLost { .. } => "airdef:blast.big",
EventKind::Split { .. } => "airdef:boom.sonic",
};
let gain = if let EventKind::Kill { kind, .. } = e.kind { crate::sim::record::kill_look(kind).2 } else { 1.0 };
out.sound(event, heard(e.pos), gain, 1.0);
}
for tr in rec.tracks.iter().filter(|tr| (self.heard..self.t).contains(&(tr.first as f64))) {
if let What::Missile(kind, _) = tr.what
&& let Some(p) = tr.at(rec.origin, tr.first as f64)
{
out.sound(kind.launch_sound(), heard(p), 1.0, 1.0);
}
}
self.heard = self.t;
}
/// One tick of the film: its clock runs, the plan gives the camera and the replay's moment.
fn tick_film(&mut self, sim: &Sim, ground: &mut Ground, listener: DVec3, out: &mut Out, rec: &Recording) {
let Mode::Film(mut film) = std::mem::replace(&mut self.mode, Mode::Map) else { return };
self.fade = self.fade.saturating_sub(1);
self.help = self.help.saturating_sub(1);
if !film.prepare(rec, ground) {
self.rate = 0.0;
self.mode = Mode::Film(film);
return;
}
let end = self.limit.map_or(film.len, |l| l.min(film.len));
if !self.paused && !self.wait && !self.ended {
self.tau += film::TICK_S;
}
if self.tau >= end {
self.tau = end;
self.ended = true;
// A live film stops on its last frame (Space plays it again); an export is ended by the caller.
if !self.clean {
self.paused = true;
}
}
let f = film.frame(rec, self.tau);
let changed = self.cut.is_none_or(|c| c.0 != f.shot);
if changed {
self.view = self.view.wrapping_add(1).max(VIEW);
self.alt = !self.alt;
self.heard = f.t;
self.fade = if self.cut.is_some() { 2 } else { 0 };
}
self.rate = if changed { 1.0 } else { (f.t - self.t).clamp(0.0, 1.0) };
self.t = f.t;
self.eye = f.eye;
self.look = f.look;
self.fov = f.fov;
self.shot = (f.event, f.shot.min(255) as u8);
self.cut = Some((f.shot, f.caption, f.black));
let base = GHOSTS + if self.alt { 0x0100_0000 } else { 0 };
sim.draw_ghosts(rec, self.t, base, out);
if !self.wait {
self.sounds(rec, listener, out);
} else {
self.heard = self.t;
}
self.mode = Mode::Film(film);
}
/// The film's length in seconds (what an export records), after the limit.
pub fn film_len(&self) -> Option<f64> {
match &self.mode {
Mode::Film(f) => Some(self.limit.map_or(f.len, |l| l.min(f.len))),
_ => None,
}
}
/// Whether the film's shots are placed (an export waits for it).
pub fn film_ready(&self) -> bool {
matches!(&self.mode, Mode::Film(f) if f.ready)
}
/// The film's clock, in seconds.
pub fn film_time(&self) -> f64 {
self.tau
}
/// A line about the film, for the chat.
pub fn film_summary(&self) -> String {
match &self.mode {
Mode::Film(f) => f.summary(),
_ => String::new(),
}
}
/// The film's screen: bars, captions, the black of its start and end.
fn film_hud(&self, rec: &Recording, film: &Film, sim: &Sim, gw: f32, gh: f32) -> Vec<Shape> {
let mut s: Vec<Shape> = Vec::new();
let bar = (gh * 0.09).round();
if !film.ready {
s.push(fill(0.0, 0.0, gw, gh, 0xFF000000));
s.push(text(format!("Готовлю кадры… {:.0}%", film.progress() * 100.0), gw / 2.0, gh / 2.0 - 4.0, 0xFFC0C0C0, true));
return s;
}
s.push(fill(0.0, 0.0, gw, bar, 0xFF000000));
s.push(fill(0.0, gh - bar, gw, bar, 0xFF000000));
let (shot, caption, black) = self.cut.unwrap_or((0, 0.0, 1.0));
if !self.clean {
let blink = (sim.tick / 10) % 2 == 0;
s.push(fill(8.0, bar / 2.0 - 3.0, 6.0, 6.0, if blink { 0xFFFF2020 } else { 0x60FF2020 }));
s.push(text(format!("ФИЛЬМ · налёт №{} · план {}/{}", rec.number, shot + 1, film.shots()), 18.0, bar / 2.0 - 4.0, 0xFFFFFFFF, false));
let time = format!("{} / {}{}", clock(self.tau * 20.0), clock(film.len * 20.0), if self.paused { " ПАУЗА" } else { "" });
let tw = horizon_mod_sdk::render::text_width(&time);
s.push(text(time, gw - 8.0 - tw, bar / 2.0 - 4.0, 0xFFC0C0C0, false));
// Progress.
s.push(fill(0.0, gh - bar - 2.0, gw * (self.tau / film.len.max(0.01)) as f32, 2.0, 0xC0FFD040));
}
// The caption: a lower third that comes in after the cut and goes before the next.
let (head, sub) = film.caption(shot);
if caption > 0.01 {
let a = (caption * 255.0) as u32;
let x = (gw * 0.07).round();
let y = gh - bar - 52.0;
let w = horizon_mod_sdk::render::text_width(head).max(horizon_mod_sdk::render::text_width(sub)) + 22.0;
s.push(fill(x - 8.0, y, 3.0, if sub.is_empty() { 18.0 } else { 30.0 }, (a << 24) | 0xFFD040));
s.push(fill(x - 5.0, y, w, if sub.is_empty() { 18.0 } else { 30.0 }, ((a * 140 / 255) << 24) | 0x000000));
s.push(text(head, x + 4.0, y + 5.0, (a << 24) | 0xFFFFFF, false));
if !sub.is_empty() {
s.push(text(sub, x + 4.0, y + 17.0, (a << 24) | 0xC0C0C0, false));
}
}
if self.fade > 0 {
s.push(fill(0.0, 0.0, gw, gh, ((self.fade.min(6) * 42) as u32) << 24));
}
if black > 0.003 {
s.push(fill(0.0, 0.0, gw, gh, (((black * 255.0) as u32).min(255)) << 24));
}
if !self.clean {
self.controls(&mut s, gw, gh, bar);
}
s
}
/// The event the camera films now: (eye, look, fov, shot).
fn shoot(&mut self, rec: &Recording, i: usize, ground: &mut Ground) -> (DVec3, DVec3, f32, u8) {
let e = rec.events[i];
let t = self.t;
let te = e.at as f64;
let o = rec.origin;
let chase = |id: u32, back: f64, up: f64| -> Option<(DVec3, DVec3)> {
let tr = rec.track(id)?;
let p = tr.at(o, t)?;
let d = tr.dir(o, t);
Some((p - d * back + DVec3::Y * up, p + d * 10.0))
};
let side = |at: DVec3, from: DVec3, dist: f64| {
let across = DVec3::new(-(at - from).z, 0.0, (at - from).x).normalize_or(DVec3::X);
at + across * dist + DVec3::Y * dist * 0.18
};
match e.kind {
EventKind::Kill { drone, missile, sam, .. } => {
let target = rec.track(drone).and_then(|tr| tr.at(o, t)).unwrap_or(e.pos);
if t < te - 40.0 {
if let Some((eye, look)) = chase(drone, 12.0, 4.0) {
return (eye, look, 55.0, 0);
}
}
match missile.and_then(|m| rec.track(m)) {
Some(mt) => {
// Behind the interceptor until it meets the target, then where it was.
if t < te && let Some(p) = mt.at(o, t) {
let eye = p - mt.dir(o, t) * 9.0 + DVec3::Y * 1.5;
self.held = Some(eye);
return (eye, target, 50.0, 1);
}
let eye = self.held.unwrap_or_else(|| side(e.pos, o, 40.0));
(eye, target.lerp(e.pos, 0.5), 50.0, 1)
}
None => {
// A gun kill, from the gun.
let at = rec.sam(sam).map_or(e.pos + DVec3::Y * 20.0, |s| s.1 + DVec3::Y * 4.0);
// A system on the sea floor (or a lake's) must not film from under the water:
// the game's ground height is the top of the highest block that blocks motion
// or holds a fluid, i.e. the water's surface there.
let at = above_surface(at, ground.land_state(at));
let dist = target.distance(at).max(1.0);
let fov = (2.0 * (10.0 / dist).atan()).to_degrees().clamp(6.0, 60.0) as f32;
(at, target, fov, 1)
}
}
}
EventKind::Hit { drone, .. } | EventKind::Crash { drone, .. } => {
if t < te - 50.0 {
if let Some((eye, look)) = chase(drone, 12.0, 4.0) {
return (eye, look, 55.0, 0);
}
}
let from = rec.track(drone).and_then(|tr| tr.at(o, te - 60.0)).unwrap_or(o);
let eye = side(e.pos, from, 55.0);
let look = rec.track(drone).and_then(|tr| tr.at(o, t)).filter(|_| t < te).unwrap_or(e.pos);
(eye, look, 50.0, 1)
}
EventKind::SamLost { .. } => (side(e.pos, o + DVec3::new(300.0, 0.0, 0.0), 45.0), e.pos, 50.0, 0),
EventKind::Split { .. } => {
let ground = DVec3::new(e.pos.x, o.y, e.pos.z);
let eye = ground + DVec3::new(170.0, 8.0, 40.0);
let k = ((t - te) / 170.0).clamp(0.0, 1.0);
(eye, e.pos.lerp(ground, k * 0.9), 60.0, 0)
}
}
}
/// Chooses the shot and moves the camera; a new shot is a cut.
fn direct(&mut self, rec: &Recording, ground: &mut Ground) {
let focus = match &self.mode {
Mode::Clips { list, at, .. } => Some(list[*at].event),
// The full replay follows what comes next: the next event within 6 s, else the drone
// nearest its target.
Mode::Full => rec
.events
.iter()
.position(|e| (self.t - 30.0..self.t + 120.0).contains(&(e.at as f64)))
.or(if self.shot.0 != usize::MAX && (rec.events[self.shot.0].at as f64) > self.t - 60.0 { Some(self.shot.0) } else { None }),
Mode::Map | Mode::Film(_) => None,
};
let (eye, look, fov, shot) = match focus {
Some(i) => {
let s = self.shoot(rec, i, ground);
(s.0, s.1, s.2, (i, s.3))
}
None => {
// The drone closest to where it is going.
let o = rec.origin;
let lead = rec
.tracks
.iter()
.filter(|tr| matches!(tr.what, What::Drone(_)) && tr.fell.is_none_or(|f| f as f64 > self.t))
.filter_map(|tr| tr.at(o, self.t).map(|p| (p, tr)))
.min_by(|a, b| a.0.distance(o).total_cmp(&b.0.distance(o)));
match lead {
Some((p, tr)) => {
let d = tr.dir(o, self.t);
(p - d * 14.0 + DVec3::Y * 5.0, p + d * 10.0, 55.0, (usize::MAX, (tr.id % 251) as u8))
}
None => (o + DVec3::new(60.0, 30.0, 60.0), o, 60.0, (usize::MAX, 0)),
}
}
};
if shot != self.shot {
self.shot = shot;
self.view = self.view.wrapping_add(1).max(VIEW);
self.held = None;
self.fade = self.fade.max(3);
}
self.eye = eye;
self.look = look;
self.fov = fov;
}
/// The camera the game renders for the replay.
pub fn views(&self, (gw, gh): (f32, f32)) -> Vec<CameraView> {
if matches!(self.mode, Mode::Map) {
return Vec::new();
}
let d = (self.look - self.eye).normalize_or(DVec3::NEG_Z);
let yaw = (-d.x).atan2(d.z).to_degrees() as f32;
let pitch = (-d.y).asin().to_degrees() as f32;
// The main view takes the window's size; the picture size only matters to the small views.
let width = 1920u32;
let height = ((width as f32) * gh / gw.max(1.0)) as u32;
vec![CameraView { id: self.view, x: self.eye.x, y: self.eye.y, z: self.eye.z, yaw, pitch, fov: self.fov, width, height: height.clamp(240, 2160) }]
}
/// The replay's screen: the film with its titles, or the map.
pub fn hud(&self, sim: &Sim, (gw, gh): (f32, f32)) -> Vec<Shape> {
let Some(rec) = sim.replay(self.rec) else { return Vec::new() };
if matches!(self.mode, Mode::Map) {
return self.map(rec, gw, gh);
}
if let Mode::Film(f) = &self.mode {
return self.film_hud(rec, f, sim, gw, gh);
}
// The world itself is the camera's (`set-main-view`): the HUD only frames it.
let mut s: Vec<Shape> = Vec::new();
// Letterbox, the recording's marks.
let bar = (gh * 0.09).round();
s.push(fill(0.0, 0.0, gw, bar, 0xFF000000));
s.push(fill(0.0, gh - bar, gw, bar, 0xFF000000));
let blink = (sim.tick / 10) % 2 == 0;
s.push(fill(8.0, bar / 2.0 - 3.0, 6.0, 6.0, if blink { 0xFFFF2020 } else { 0x60FF2020 }));
let what = match &self.mode {
Mode::Full => "ПОЛНЫЙ ПОВТОР".to_string(),
Mode::Clips { reel: true, at, list } => format!("ЛУЧШЕЕ · {}/{}", at + 1, list.len()),
_ => "ПОВТОР".to_string(),
};
let head = format!("{what} · налёт №{}", rec.number);
let head_w = horizon_mod_sdk::render::text_width(&head);
s.push(text(head, 18.0, bar / 2.0 - 4.0, 0xFFFFFFFF, false));
let speed = if let Mode::Clips { list, at, .. } = &self.mode {
let te = rec.events[list[*at].event].at as f64;
if (te - 14.0..te + 18.0).contains(&self.t) { self.speed * 0.3 } else { self.speed }
} else {
self.speed
};
let state = if self.paused { "ПАУЗА".to_string() } else { format!("×{speed}") };
let time = format!("{} / {} {state}", clock(self.t), clock(rec.len as f64));
let tw = horizon_mod_sdk::render::text_width(&time);
s.push(text(time, gw - 8.0 - tw, bar / 2.0 - 4.0, 0xFFC0C0C0, false));
let _ = head_w;
// Caption: what is happening.
let caption = match &self.mode {
Mode::Clips { list, at, .. } => Some(list[*at].event),
_ => (self.shot.0 != usize::MAX).then_some(self.shot.0),
};
if let Some(i) = caption.filter(|&i| i < rec.events.len()) {
let e = &rec.events[i];
s.push(text(title(rec, i), gw / 2.0, gh - bar + 4.0, 0xFFFFFFFF, true));
let detail = match e.kind {
EventKind::Kill { sam, .. } => rec
.sam(sam)
.map(|(_, p)| format!("высота {:.0} м · {} от комплекса", e.pos.y - p.y, distance(e.pos.distance(p))))
.unwrap_or_default(),
EventKind::Hit { power, .. } => format!("сила взрыва {}", ["хлопок", "средний", "сильный", "тяжёлый", "мощнейший"][(power as usize).min(4)]),
_ => String::new(),
};
s.push(text(detail, gw / 2.0, gh - bar + 15.0, 0xFFB0B0B0, true));
}
// Title card of a reel's moment.
if self.card > 0 && let Mode::Clips { list, at, .. } = &self.mode {
let a = ((self.card.min(15) as f32 / 15.0) * 255.0) as u32;
s.push(fill(0.0, gh / 2.0 - 22.0, gw, 44.0, (a.min(0xC0) << 24) | 0x000000));
s.push(text(format!("МОМЕНТ {} — {}", at + 1, clock(rec.events[list[*at].event].at as f64)), gw / 2.0, gh / 2.0 - 14.0, (a << 24) | 0xFFD040, true));
s.push(text(title(rec, list[*at].event), gw / 2.0, gh / 2.0 + 2.0, (a << 24) | 0xFFFFFF, true));
}
if self.fade > 0 {
let a = (self.fade.min(6) * 42) as u32;
s.push(fill(0.0, 0.0, gw, gh, a << 24));
}
self.controls(&mut s, gw, gh, bar);
s
}
/// The keys, shown at the start, after a key and while paused; a big pause mark.
fn controls(&self, s: &mut Vec<Shape>, gw: f32, gh: f32, bar: f32) {
if self.paused {
let (cx, cy) = (gw / 2.0, gh / 2.0);
s.push(fill(cx - 14.0, cy - 14.0, 10.0, 28.0, 0xC0FFFFFF));
s.push(fill(cx + 4.0, cy - 14.0, 10.0, 28.0, 0xC0FFFFFF));
}
if self.help > 0 || self.paused {
let line = match self.mode {
Mode::Clips { reel: true, .. } => KEYS_HELP.replace("перемотка", "моменты"),
Mode::Clips { .. } => KEYS_HELP.replace("← → перемотка · ", ""),
_ => KEYS_HELP.to_string(),
};
let w = horizon_mod_sdk::render::text_width(&line) + 12.0;
let a = if self.paused { 0xFF } else { (self.help.min(20) * 12) as u32 };
let y = gh - bar - 18.0;
s.push(fill(gw / 2.0 - w / 2.0, y, w, 13.0, (a.min(0xB0) << 24) | 0x000000));
s.push(text(line, gw / 2.0, y + 3.0, (a << 24) | 0xFFFFFF, true));
}
}
/// The raid from above: systems and their reach, objects, every track up to now, the events
/// so far, and a time line.
fn map(&self, rec: &Recording, gw: f32, gh: f32) -> Vec<Shape> {
let mut s = vec![fill(0.0, 0.0, gw, gh, 0xF0060A08)];
let o = rec.origin;
// The area is the same every tick: worked out once for the recording.
let [l0, l1, h0, h1] = match self.area.get() {
Some(a) => a,
None => {
let a = area(rec, o);
self.area.set(Some(a));
a
}
};
let (lo, hi) = ((l0, l1), (h0, h1));
let (top, bottom) = (20.0f32, 34.0f32);
let (aw, ah) = (gw - 16.0, gh - top - bottom);
let k = (aw as f64 / (hi.0 - lo.0).max(1.0)).min(ah as f64 / (hi.1 - lo.1).max(1.0));
let cx = 8.0 + (aw as f64 - (hi.0 - lo.0) * k) / 2.0;
let cy = top as f64 + (ah as f64 - (hi.1 - lo.1) * k) / 2.0;
let at = |p: DVec3| ((cx + (p.x - lo.0) * k) as f32, (cy + (p.z - lo.1) * k) as f32);
let inside = |(x, y): (f32, f32)| x > 0.0 && y > top - 4.0 && x < gw && y < gh - bottom + 4.0;
// Systems' reach (a few), positions.
let many = rec.sams.len() > 12;
for (_, kind, p) in &rec.sams {
let (x, y) = at(*p);
if !many {
let r = (kind.range() * k) as f32;
let seg = 24;
for i in 0..seg {
let a0 = i as f32 / seg as f32 * std::f32::consts::TAU;
let a1 = (i + 1) as f32 / seg as f32 * std::f32::consts::TAU;
let q = |a: f32| (x + a.sin() * r, y - a.cos() * r);
if inside(q(a0)) && inside(q(a1)) {
s.push(line(q(a0), q(a1), 1.0, 0x5040A0FF));
}
}
}
s.push(fill(x - 2.0, y - 2.0, 4.0, 4.0, 0xFF40A0FF));
}
for p in &rec.objects {
let (x, y) = at(*p);
s.push(fill(x - 3.0, y - 3.0, 6.0, 6.0, 0xFFFFFFFF));
}
// Tracks up to now: a budget of segments shared out. The stride is
// worked out from the points there are, so only the segments drawn
// are ever copied.
let n = rec.tracks.len().max(1);
let per = (640 / n).clamp(2, 14);
for tr in &rec.tracks {
let (color, head) = match tr.what {
What::Drone(kind) if kind.spec().decoy => (0x70A0A0A0, 0xFFC0C0C0),
What::Drone(_) => (0x90FF4040, 0xFFFF6060),
What::Missile(..) => (0x90FFD040, 0xFFFFE070),
};
let upto = ((self.t - tr.first as f64) / STEP as f64).floor();
if upto < 0.0 {
continue;
}
let last = ((tr.last() - tr.first) / STEP) as f64;
let count = upto.min(last) as usize + 1;
if count < 2 {
continue;
}
let pts = tr.path(o, count.div_ceil(per).max(1), self.t);
if pts.len() < 2 {
continue;
}
let mut prev = at(pts[0]);
for p in pts.iter().skip(1) {
let q = at(*p);
if inside(prev) && inside(q) {
s.push(line(prev, q, 1.0, color));
}
prev = q;
}
// Its head while it flies.
if (self.t as u32) < tr.last() && tr.fell.is_none_or(|f| (f as f64) > self.t) && inside(prev) {
s.push(fill(prev.0 - 1.5, prev.1 - 1.5, 3.0, 3.0, head));
}
}
// Events so far.
for e in rec.events.iter().filter(|e| (e.at as f64) <= self.t) {
let (x, y) = at(e.pos);
if !inside((x, y)) {
continue;
}
match e.kind {
EventKind::Kill { .. } => {
s.push(line((x - 2.5, y - 2.5), (x + 2.5, y + 2.5), 1.2, 0xFFFFE040));
s.push(line((x + 2.5, y - 2.5), (x - 2.5, y + 2.5), 1.2, 0xFFFFE040));
}
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => {
let r = 2.0 + power as f32;
s.push(fill(x - r, y - r, r * 2.0, r * 2.0, 0xB0FF3020));
}
EventKind::SamLost { .. } => s.push(fill(x - 4.0, y - 4.0, 8.0, 8.0, 0xFF200000)),
EventKind::Split { .. } => s.push(fill(x - 2.0, y - 2.0, 4.0, 4.0, 0xFFFF9020)),
}
}
// Header, legend, time line.
let kills = rec.events.iter().filter(|e| (e.at as f64) <= self.t && matches!(e.kind, EventKind::Kill { .. })).count();
let hits = rec.events.iter().filter(|e| (e.at as f64) <= self.t && matches!(e.kind, EventKind::Hit { .. })).count();
let state = if self.paused { "ПАУЗА".to_string() } else { format!("×{}", self.speed) };
s.push(text(format!("КАРТА НАЛЁТА №{} · {} / {} {state} · сбито {kills} · прилётов {hits}", rec.number, clock(self.t), clock(rec.len as f64)), 8.0, 6.0, 0xFF9FE0FF, false));
let legend = "красный: цели · серый: ложные · жёлтый: перехватчики · x сбит · квадрат: прилёт";
let lw = horizon_mod_sdk::render::text_width(legend);
if lw < gw - 16.0 {
s.push(text(legend, gw - 8.0 - lw, 6.0 + 11.0, 0x70FFFFFF, false));
}
let keys = format!("{KEYS_HELP} · колесо: время");
s.push(text(keys, gw / 2.0, gh - 12.0, 0xC0FFFFFF, true));
// What went wrong for the air defence, as counted during the raid.
let tally = rec.tally.text();
if !tally.is_empty() && horizon_mod_sdk::render::text_width(&tally) < gw - 24.0 - lw {
s.push(text(tally, 8.0, 6.0 + 11.0, 0xB0FFC080, false));
}
let (tx, ty, tw) = (8.0, gh - bottom + 6.0, gw - 16.0);
s.push(fill(tx, ty, tw, 3.0, 0x60FFFFFF));
let len = rec.len.max(1) as f32;
for e in &rec.events {
let x = tx + tw * e.at as f32 / len;
let c = match e.kind {
EventKind::Kill { .. } => 0xFFFFE040,
EventKind::Hit { .. } => 0xFFFF3020,
EventKind::Crash { .. } => 0xFF903020,
EventKind::SamLost { .. } => 0xFFFF00FF,
EventKind::Split { .. } => 0xFFFF9020,
};
s.push(fill(x, ty - 2.0, 1.0, 7.0, c));
}
s.push(fill(tx + tw * (self.t as f32 / len) - 1.0, ty - 4.0, 2.0, 11.0, 0xFFFFFFFF));
s.truncate(1024);
s
}
}
/// The ground the map shows, as [lo x, lo z, hi x, hi z]: everything that
/// flew (not the ballistic falls), with the systems and objects, or round the
/// origin when nothing did.
fn area(rec: &Recording, o: DVec3) -> [f64; 4] {
let mut lo = (f64::MAX, f64::MAX);
let mut hi = (f64::MIN, f64::MIN);
let mut grow = |p: DVec3| {
lo = (lo.0.min(p.x), lo.1.min(p.z));
hi = (hi.0.max(p.x), hi.1.max(p.z));
};
for tr in &rec.tracks {
if let What::Drone(k) = tr.what
&& k.spec().ballistic.is_some()
{
continue;
}
for p in tr.path(o, 20, rec.len as f64) {
grow(p);
}
}
// The systems, with some room round them.
for sam in &rec.sams {
grow(sam.2 - DVec3::splat(60.0));
grow(sam.2 + DVec3::splat(60.0));
}
for p in &rec.objects {
grow(*p);
}
if lo.0 > hi.0 {
lo = (o.x - 200.0, o.z - 200.0);
hi = (o.x + 200.0, o.z + 200.0);
}
[lo.0, lo.1, hi.0, hi.1]
}
impl Player {
pub fn event_clip(rec: &Recording, i: usize) -> Mode {
Mode::Clips { list: vec![clip(rec, i)], at: 0, reel: false }
}
}
#[cfg(test)]
mod surface_tests {
use super::*;
/// A gun standing on the sea floor films from above the water, not from under it.
#[test]
fn the_gun_camera_is_lifted_above_the_water() {
let eye = DVec3::new(10.0, 44.0, 5.0); // 4 above a Gepard on the floor at 40
let lifted = above_surface(eye, Some(Some(62.0))); // the surface
assert!(lifted.y >= 62.0 + SURFACE_CLEAR - 1e-9);
assert_eq!((lifted.x, lifted.z), (10.0, 5.0));
// On dry land, or with no answer yet, the camera stays where it was.
assert_eq!(above_surface(DVec3::new(0.0, 74.0, 0.0), Some(Some(70.0))), DVec3::new(0.0, 74.0, 0.0));
assert_eq!(above_surface(eye, None), eye);
assert_eq!(above_surface(eye, Some(None)), eye);
}
}