Files
airdef/airdef-mod/src/film.rs
T
chexit f28e68db62 Record measured scene transitions and isolate combat effects from recorder (#88)
Capture actual missile launch/ignition, track transitions, fire state, SAM health and components. Keep legacy fallback and bound scene transitions to 65536. Renderers still use incremental adapters; shared SceneTimeline remains follow-up work.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-02 21:00:22 +03:00

694 lines
30 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.
//! The replay director: a raid's best moments planned as a film. Every event becomes a few shots
//! from different angles (the launcher, behind the interceptor, ahead of the target, a slow-motion
//! close-up at the kill, a wide aftermath), joined by cuts, with eased camera moves and the time
//! slowed round the moment itself.
//!
//! The plan is made once, from the recording alone: nothing random, nothing read from the live
//! raid, so the same film comes out every time. The land is asked for before the film starts (the
//! planner needs the heights under every camera and along every line of sight); each shot has a
//! few candidate placements, and the one the land hides least is kept; the camera is lifted over
//! the ground wherever it would dip into it. Only what the recording knows is shown: launches use the recorded transition where available (older tracks use their first point);
//! no lock-on or detection is invented.
use crate::replay::{interest, title};
use crate::sim::record::{EventKind, Recording, STEP};
use crate::sim::Ground;
use glam::DVec3;
use std::collections::{HashMap, HashSet};
/// Seconds of film in one game tick.
pub const TICK_S: f64 = 0.05;
/// Seconds between the samples the planner checks a shot at.
const SAMPLE_S: f64 = 0.5;
/// Ticks the planner waits for the land's answers.
const PREP_TICKS: u32 = 160;
/// A land lattice cell, as the ground samples it.
const CELL: f64 = 8.0;
/// Seconds of black at the start and the end.
const FADE_S: f64 = 0.7;
/// Which moments a film is made of.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Which {
/// The three best.
Best,
/// Every worthwhile one.
All,
/// The n best.
Top(usize),
}
#[derive(Clone, Debug)]
enum Aim {
Track(u32, DVec3),
Point(DVec3),
/// Between two tracks (the interceptor and its target): both stay in frame.
Mid(u32, u32, DVec3),
}
#[derive(Clone, Debug)]
enum Eye {
/// From one place to another, eased over the shot.
Dolly(DVec3, DVec3),
/// Behind a track, a little above and to its side.
Behind { track: u32, back: f64, up: f64, side: f64 },
/// In front of a track, looking back at what comes.
Ahead { track: u32, ahead: f64, up: f64, side: f64 },
Static(DVec3),
}
#[derive(Clone, Debug)]
struct Rig {
eye: Eye,
aim: Aim,
fov: (f32, f32),
}
struct Shot {
start: f64,
len: f64,
/// The replay's tick at every `TICK_S` of the shot.
table: Vec<f64>,
variants: Vec<Rig>,
pick: usize,
/// The least height the eye keeps, at the planner's samples.
clear: Vec<f32>,
head: String,
sub: String,
event: usize,
}
/// Where the camera is, and what the replay shows, at a moment of the film.
pub struct Frame {
pub shot: usize,
pub eye: DVec3,
pub look: DVec3,
pub fov: f32,
/// The replay's tick.
pub t: f64,
pub event: usize,
/// 0 to 1 how visible the caption is.
pub caption: f32,
/// 0 to 1 how black the picture is (the film's start and end).
pub black: f32,
}
pub struct Film {
shots: Vec<Shot>,
pub len: f64,
cells: Vec<(i32, i32)>,
heights: HashMap<(i32, i32), Option<f64>>,
waited: u32,
pub ready: bool,
}
fn smooth(x: f64) -> f64 {
let x = x.clamp(0.0, 1.0);
x * x * (3.0 - 2.0 * x)
}
fn cell(p: DVec3) -> (i32, i32) {
((p.x / CELL).floor() as i32, (p.z / CELL).floor() as i32)
}
fn cell_centre(c: (i32, i32)) -> DVec3 {
DVec3::new((c.0 as f64 + 0.5) * CELL, 0.0, (c.1 as f64 + 0.5) * CELL)
}
/// Where a track was at `t`, held at its ends.
fn at(rec: &Recording, id: u32, t: f64) -> Option<DVec3> {
let tr = rec.track(id)?;
tr.at(rec.origin, t.clamp(tr.first as f64, tr.last() as f64))
}
/// Its heading, from a window wide enough not to shake with the recording's steps.
fn heading(rec: &Recording, id: u32, t: f64) -> DVec3 {
let w = 3.0 * STEP as f64;
match (at(rec, id, t - w), at(rec, id, t + w)) {
(Some(a), Some(b)) => (b - a).normalize_or(DVec3::NEG_Z),
_ => DVec3::NEG_Z,
}
}
/// Horizontal, across the line from `from` to `at`.
fn across(at: DVec3, from: DVec3) -> DVec3 {
DVec3::new(-(at - from).z, 0.0, (at - from).x).normalize_or(DVec3::X)
}
impl Aim {
fn at(&self, rec: &Recording, t: f64) -> DVec3 {
match self {
Aim::Track(id, fallback) => at(rec, *id, t).unwrap_or(*fallback),
Aim::Point(p) => *p,
Aim::Mid(a, b, fallback) => match (at(rec, *a, t), at(rec, *b, t)) {
(Some(a), Some(b)) => a.lerp(b, 0.5),
(Some(p), None) | (None, Some(p)) => p,
_ => *fallback,
},
}
}
}
impl Rig {
/// The eye, the look-at point and the field of view at replay tick `t`, a fraction `f` into the shot.
fn at(&self, rec: &Recording, t: f64, f: f64) -> (DVec3, DVec3, f32) {
let look = self.aim.at(rec, t);
let eye = match &self.eye {
Eye::Dolly(a, b) => a.lerp(*b, smooth(f)),
Eye::Static(p) => *p,
Eye::Behind { track, back, up, side } => match at(rec, *track, t) {
Some(p) => {
let d = heading(rec, *track, t);
let s = across(p + d, p);
p - d * *back + DVec3::Y * *up + s * *side
}
None => look + DVec3::new(30.0, 10.0, 30.0),
},
Eye::Ahead { track, ahead, up, side } => match at(rec, *track, t) {
Some(p) => {
let d = heading(rec, *track, t);
let s = across(p + d, p);
p + d * *ahead + DVec3::Y * *up + s * *side
}
None => look + DVec3::new(30.0, 10.0, 30.0),
},
};
let fov = self.fov.0 + (self.fov.1 - self.fov.0) * smooth(f) as f32;
(eye, look, fov)
}
}
impl Shot {
fn new(a: f64, b: f64, profile: &[(f64, f64)], variants: Vec<Rig>, head: &str, sub: &str, event: usize) -> Shot {
// Replay ticks a game tick of film plays: the profile's speed at the replay's moment.
let speed = |t: f64| -> f64 {
let mut v = profile.first().map_or(1.0, |p| p.1);
for w in profile.windows(2) {
if t >= w[0].0 && t <= w[1].0 {
let k = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-9);
v = w[0].1 + (w[1].1 - w[0].1) * k;
} else if t > w[1].0 {
v = w[1].1;
}
}
v.max(0.02)
};
let mut table = vec![a];
let mut t = a;
while t < b && table.len() < 4000 {
t = (t + speed(t)).min(b);
table.push(t);
}
if table.len() < 2 {
table.push(b.max(a));
}
let len = (table.len() - 1) as f64 * TICK_S;
Shot { start: 0.0, len, table, variants, pick: 0, clear: Vec::new(), head: head.into(), sub: sub.into(), event }
}
/// The replay's tick `local` seconds into the shot.
fn t_at(&self, local: f64) -> f64 {
let k = (local / TICK_S).clamp(0.0, (self.table.len() - 1) as f64);
let i = (k.floor() as usize).min(self.table.len() - 1);
let j = (i + 1).min(self.table.len() - 1);
self.table[i] + (self.table[j] - self.table[i]) * (k - i as f64)
}
fn samples(&self) -> usize {
((self.len / SAMPLE_S).ceil() as usize + 1).clamp(3, 17)
}
}
/// The events a film of `which` is made of, in the order they happened.
pub fn pick(rec: &Recording, which: Which) -> Vec<usize> {
let (n, floor) = match which {
Which::Best => (3, 2.0),
Which::All => (12, 2.0),
Which::Top(n) => (n.clamp(1, 12), 2.0),
};
let mut best: Vec<(f64, usize)> = (0..rec.events.len()).map(|i| (interest(rec, i), i)).filter(|b| b.0 >= floor).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() >= n {
break;
}
let at = rec.events[i].at as i64;
if chosen.iter().all(|&c| (rec.events[c].at as i64 - at).abs() > 160) {
chosen.push(i);
}
}
chosen.sort_by_key(|&i| rec.events[i].at);
chosen
}
/// The four placements a shot is tried in: either side, low and lifted.
fn placements<F: Fn(f64, f64) -> Rig>(mk: F) -> Vec<Rig> {
vec![mk(1.0, 0.0), mk(-1.0, 0.0), mk(1.0, 28.0), mk(-1.0, 28.0)]
}
/// Shortest shot worth cutting to, in replay ticks.
const MIN_SHOT: f64 = 8.0;
/// The replay tick a shot ends at.
fn shot_end(s: &Shot) -> f64 {
s.table.last().copied().unwrap_or(0.0)
}
/// The shots of event `i`, with replay time never running back: no shot starts before `floor` (the
/// end of the one before it, or of the previous event's last), a stage the real intervals leave no
/// room for is merged into its neighbour or left out, and what happens in the story comes in the
/// order it happened (a launch before its kill; an interceptor not before its first point).
fn plan_event(rec: &Recording, i: usize, floor: f64) -> Vec<Shot> {
let e = rec.events[i];
let te = e.at as f64;
let o = rec.origin;
let end = rec.len as f64;
let pos = e.pos;
let mut shots: Vec<Shot> = Vec::new();
let cur = std::cell::Cell::new(floor);
let mut add = |shot: Shot| {
cur.set(shot_end(&shot));
shots.push(shot);
};
// The interval a stage may use: not before the cursor, and long enough to be a shot.
let span = |a: f64, b: f64| -> Option<(f64, f64)> {
let a = a.max(0.0).max(cur.get());
(b - a >= MIN_SHOT).then_some((a, b))
};
// The slow moment: half speed into it, a tenth through it, back to normal after.
let slow = |lead: f64, after: f64| -> Vec<(f64, f64)> {
vec![(te - lead, 0.6), (te - 4.0, 0.15), (te + 6.0, 0.15), (te + 22.0, 0.6), (te + after, 1.0)]
};
let kill_close = |from: DVec3, aim_id: Option<u32>, head: &str, sub: String| -> Shot {
// Never before the story so far; held to at least a few ticks.
let a = (te - 10.0).max(0.0).max(cur.get());
let b = (te + 48.0).min(end).max(a + 4.0);
let variants = placements(|side, lift| {
let s = across(pos, from) * side;
let near = pos + s * 42.0 + DVec3::Y * (6.0 + lift * 0.4);
let closer = pos + s * 26.0 + DVec3::Y * (4.0 + lift * 0.3);
Rig {
eye: Eye::Dolly(near, closer),
aim: aim_id.map_or(Aim::Point(pos), |id| Aim::Track(id, pos)),
fov: (44.0, 30.0),
}
});
Shot::new(a, b, &slow(10.0, 48.0), variants, head, &sub, i)
};
let aftermath = |from: DVec3, head: &str| -> Option<Shot> {
let (a, b) = span((te + 48.0).min(end), (te + 150.0).min(end))?;
if b - a < 20.0 {
return None;
}
let variants = placements(|side, lift| {
let s = across(pos, from) * side;
Rig {
eye: Eye::Dolly(pos + s * 90.0 + DVec3::Y * (34.0 + lift), pos + s * 150.0 + DVec3::Y * (52.0 + lift)),
aim: Aim::Point(pos + DVec3::Y * 6.0),
fov: (58.0, 52.0),
}
});
Some(Shot::new(a, b, &[(a, 1.0), (b, 1.4)], variants, head, "", i))
};
match e.kind {
EventKind::Kill { drone, kind, sam, sam_kind, sam_index, missile, outcome } => {
let launch_tick = missile.and_then(|m| rec.missile_launch(m).map(|e| e.at as f64)).unwrap_or(te);
let sp = rec.sam_at(sam, launch_tick).map_or(pos - DVec3::new(150.0, 0.0, 0.0), |s| s.1);
let name = format!("{} №{}", sam_kind.name(), sam_index + 1);
let how = match outcome {
crate::sim::outcome::Outcome::DisabledFalling => "",
crate::sim::outcome::Outcome::Breakup => ": разрушение в воздухе",
crate::sim::outcome::Outcome::AirDetonation => ": детонация в воздухе",
};
let sub = format!("Перехват «{}»{how}", kind.spec().name);
let mt = missile.and_then(|m| rec.track(m).map(|t| (m, rec.missile_launch(m).map_or(t.first as f64, |e| e.at as f64))));
match mt {
Some((m, tl)) => {
// The facts, in order: the launcher waits, the interceptor leaves it at `tl`, it
// flies, it meets the target at `te`. Each stage gets the time the real flight
// has for it; what has none is merged into the one before, or left out.
let tl = tl.min(te);
// The hero: the launcher, three-quarters, until the launch.
if let Some((a, b)) = span(tl - 60.0, tl) {
let launcher = sp + DVec3::Y * 4.0;
let variants = placements(|side, lift| {
let dir = (pos - sp).with_y(0.0).normalize_or(DVec3::X);
let s = across(pos, sp) * side;
let base = sp - dir * 38.0 + s * 34.0;
Rig {
eye: Eye::Dolly(base + DVec3::Y * (7.0 + lift), base + s * 6.0 - dir * 4.0 + DVec3::Y * (9.0 + lift)),
aim: Aim::Point(launcher),
fov: (46.0, 40.0),
}
});
add(Shot::new(a, b, &[(a, 1.0)], variants, &name, &sub, i));
}
// The flight proper runs from the launch to ten ticks before the kill (where the
// close-up begins); under 6 ticks of it there is no room for more than the close-up.
let from = tl.max(cur.get());
let ke = te - 10.0;
let room = ke - from;
if room >= 6.0 {
let launch_len = (room * 0.4).clamp(6.0, 44.0);
let mut b2 = from + launch_len;
let rest = ke - b2;
// The launch, from the side, the camera low and the interceptor climbing away.
let launch_at = |b2: f64| {
let variants = placements(|side, lift| {
let s = across(pos, sp) * side;
Rig { eye: Eye::Static(sp + s * 46.0 + DVec3::Y * (3.0 + lift * 0.3)), aim: Aim::Track(m, sp), fov: (42.0, 24.0) }
});
Shot::new(from, b2, &[(from, 1.0)], variants, "Пуск", "", i)
};
if rest < 14.0 {
// Too short to fly on camera: the launch shot runs to the close-up.
b2 = ke;
add(launch_at(b2));
} else {
add(launch_at(b2));
// The flight, from behind the interceptor with the target ahead; long flights run faster.
let b3 = if rest >= 36.0 { te - 32.0 } else { ke };
let sp3 = (((b3 - b2) / 6.0) / 20.0).clamp(1.0, 4.0);
let variants = placements(|side, lift| Rig {
eye: Eye::Behind { track: m, back: 15.0, up: 3.5 + lift * 0.2, side: 5.0 * side },
aim: Aim::Track(drone, pos),
fov: (56.0, 56.0),
});
add(Shot::new(b2, b3, &[(b2, sp3)], variants, "Сближение", "", i));
// Ahead of the target, looking back at the interceptor closing.
if rest >= 36.0 {
let variants = placements(|side, lift| Rig {
eye: Eye::Ahead { track: drone, ahead: 48.0, up: 6.0 + lift * 0.3, side: 14.0 * side },
aim: Aim::Mid(m, drone, pos),
fov: (46.0, 38.0),
});
add(Shot::new(b3, ke, &[(b3, 0.6)], variants, "", "", i));
}
}
}
}
None => {
// A gun kill: the gun's view of the target (if the recording has room before it).
if let Some((a, b)) = span(te - 110.0, te - 10.0) {
let variants = placements(|side, lift| {
let s = across(pos, sp) * side;
Rig { eye: Eye::Static(sp + s * 14.0 + DVec3::Y * (5.0 + lift * 0.3)), aim: Aim::Track(drone, pos), fov: (34.0, 18.0) }
});
add(Shot::new(a, b, &[(a, 1.0)], variants, &name, &sub, i));
}
}
}
let high = (pos.y - sp.y).max(0.0);
add(kill_close(sp, Some(drone), "Поражение цели", format!("высота {high:.0} м")));
if let Some(s) = aftermath(sp, "") {
add(s);
}
}
EventKind::Hit { drone, .. } | EventKind::Crash { drone, .. } => {
let from = rec.track(drone).and_then(|t| t.at(o, te - 60.0)).unwrap_or(o);
let head = title(rec, i);
if let Some((a, b)) = span(te - 150.0, te - 55.0) {
let variants = placements(|side, lift| Rig {
eye: Eye::Behind { track: drone, back: 16.0, up: 4.0 + lift * 0.2, side: 6.0 * side },
aim: Aim::Point(pos),
fov: (55.0, 55.0),
});
add(Shot::new(a, b, &[(a, 1.4)], variants, &head, "", i));
}
if let Some((a2, b2)) = span(te - 55.0, te - 10.0) {
let variants = placements(|side, lift| {
let s = across(pos, from) * side;
Rig { eye: Eye::Static(pos + s * 80.0 + DVec3::Y * (3.0 + lift * 0.3)), aim: Aim::Track(drone, pos), fov: (40.0, 28.0) }
});
add(Shot::new(a2, b2, &[(a2, 0.8)], variants, "", "", i));
}
let sub = match e.kind {
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => {
format!("сила взрыва: {}", ["хлопок", "средний", "сильный", "тяжёлый", "мощнейший"][(power as usize).min(4)])
}
_ => String::new(),
};
add(kill_close(from, None, "Прилёт", sub));
if let Some(s) = aftermath(from, "") {
add(s);
}
}
EventKind::SamLost { .. } => {
let from = pos + DVec3::new(300.0, 0.0, 0.0);
if let Some((a, b)) = span(te - 70.0, te - 10.0) {
let variants = placements(|side, lift| {
let s = across(pos, from) * side;
Rig { eye: Eye::Dolly(pos + s * 70.0 + DVec3::Y * (12.0 + lift), pos + s * 52.0 + DVec3::Y * (9.0 + lift)), aim: Aim::Point(pos + DVec3::Y * 3.0), fov: (50.0, 44.0) }
});
add(Shot::new(a, b, &[(a, 1.0)], variants, &title(rec, i), "", i));
}
add(kill_close(from, None, "Комплекс уничтожен", String::new()));
if let Some(s) = aftermath(from, "") {
add(s);
}
}
EventKind::Split { .. } => {
let ground = DVec3::new(pos.x, o.y, pos.z);
let a = (te - 40.0).max(0.0).max(cur.get());
let b = (te + 170.0).min(end).max(a + 20.0);
let variants = placements(|side, lift| Rig {
eye: Eye::Dolly(ground + DVec3::new(170.0 * side, 8.0 + lift, 40.0), ground + DVec3::new(150.0 * side, 14.0 + lift, 20.0)),
aim: Aim::Point(pos.lerp(ground, 0.4)),
fov: (60.0, 52.0),
});
add(Shot::new(a, b, &[(a, 1.0), (te - 4.0, 0.3), (te + 40.0, 1.0)], variants, &title(rec, i), "", i));
}
// A strike on a launch site (#101) is in the event list and on the map, not in the auto-camera's films.
EventKind::Strike { .. } => {}
}
shots
}
impl Film {
/// The film of the best moments of recording `rec`, or None when there is nothing to show.
pub fn build(rec: &Recording, which: Which) -> Option<Film> {
let events = pick(rec, which);
if events.is_empty() {
return None;
}
let mut shots: Vec<Shot> = Vec::new();
// Replay time only moves on through the film: an event's shots start where the last ended.
let mut floor = 0.0;
for i in events {
let planned = plan_event(rec, i, floor);
if let Some(last) = planned.last() {
floor = shot_end(last);
}
shots.extend(planned);
}
let mut start = 0.0;
for s in &mut shots {
s.start = start;
start += s.len;
}
let len = start;
// Every land cell the planner will look at: under each sample's eye and along its line of sight.
let mut cells: HashSet<(i32, i32)> = HashSet::new();
for s in &shots {
let n = s.samples();
for rig in &s.variants {
for k in 0..n {
let f = k as f64 / (n - 1) as f64;
let (eye, look, _) = rig.at(rec, s.t_at(f * s.len), f);
cells.insert(cell(eye));
let steps = ((eye.distance(look) / CELL) as usize).min(40);
for j in 1..steps {
cells.insert(cell(eye.lerp(look, j as f64 / steps as f64)));
}
}
}
}
let mut cells: Vec<(i32, i32)> = cells.into_iter().collect();
cells.sort_unstable();
Some(Film { shots, len, cells, heights: HashMap::new(), waited: 0, ready: false })
}
/// Asks the game for the land the plan needs; true once the shots are placed. Call every tick.
pub fn prepare(&mut self, rec: &Recording, ground: &mut Ground) -> bool {
if self.ready {
return true;
}
let mut pending = 0;
for c in &self.cells {
if self.heights.contains_key(c) {
continue;
}
match ground.land_state(cell_centre(*c)) {
Some(h) => {
self.heights.insert(*c, h);
}
None => pending += 1,
}
}
self.waited += 1;
if pending == 0 || self.waited > PREP_TICKS {
self.place(rec);
self.ready = true;
}
self.ready
}
/// How far the land's answers are, for a progress line.
pub fn progress(&self) -> f32 {
if self.cells.is_empty() { 1.0 } else { self.heights.len() as f32 / self.cells.len() as f32 }
}
/// Picks each shot's placement: the one with the fewest hidden samples (a ridge across the line of sight).
fn place(&mut self, rec: &Recording) {
let land = |h: &HashMap<(i32, i32), Option<f64>>, p: DVec3| h.get(&cell(p)).copied().flatten();
for s in &mut self.shots {
let n = s.samples();
let mut best = (usize::MAX, 0usize);
for (v, rig) in s.variants.iter().enumerate() {
let mut hidden = 0;
for k in 0..n {
let f = k as f64 / (n - 1) as f64;
let (eye, look, _) = rig.at(rec, s.t_at(f * s.len), f);
let steps = ((eye.distance(look) / CELL) as usize).min(40);
// The camera inside the ground counts a little: it is lifted, but a better place is kept.
if land(&self.heights, eye).is_some_and(|g| eye.y < g + 1.5) {
hidden += 1;
}
for j in 1..steps.saturating_sub(1) {
let u = j as f64 / steps as f64;
let p = eye.lerp(look, u);
if land(&self.heights, p).is_some_and(|g| g > p.y - 1.0) {
hidden += 3;
break;
}
}
}
if hidden < best.0 {
best = (hidden, v);
}
}
s.pick = best.1;
let rig = &s.variants[s.pick];
s.clear = (0..n)
.map(|k| {
let f = k as f64 / (n - 1) as f64;
let (eye, _, _) = rig.at(rec, s.t_at(f * s.len), f);
land(&self.heights, eye).map_or(f32::MIN, |g| g as f32 + 3.0)
})
.collect();
}
}
/// The shot at video time `tau`, with its local time.
fn locate(&self, tau: f64) -> (usize, f64) {
let i = self.shots.iter().rposition(|s| s.start <= tau).unwrap_or(0);
(i, (tau - self.shots[i].start).clamp(0.0, self.shots[i].len))
}
/// The camera and the replay's moment at video time `tau` (seconds from the film's start).
pub fn frame(&self, rec: &Recording, tau: f64) -> Frame {
let (i, local) = self.locate(tau);
let s = &self.shots[i];
let f = if s.len > 0.0 { local / s.len } else { 0.0 };
let t = s.t_at(local);
let (mut eye, look, fov) = s.variants[s.pick.min(s.variants.len() - 1)].at(rec, t, f);
if !s.clear.is_empty() {
let x = f * (s.clear.len() - 1) as f64;
let k = (x.floor() as usize).min(s.clear.len() - 1);
let l = (k + 1).min(s.clear.len() - 1);
// The least of the two neighbours that is known, so an unknown never lowers the floor.
let (a, b) = (s.clear[k], s.clear[l]);
let floor = if a == f32::MIN || b == f32::MIN { a.max(b) } else { a + (b - a) * (x - k as f64) as f32 };
if floor > f32::MIN {
eye.y = eye.y.max(floor as f64);
}
}
// Captions come in after a beat and go out before the cut.
let caption = if s.head.is_empty() && s.sub.is_empty() {
0.0
} else {
(smooth((local - 0.25) / 0.4).min(smooth((s.len - 0.2 - local) / 0.4))) as f32
};
let black = smooth(1.0 - tau / FADE_S).max(smooth(1.0 - (self.len - tau) / FADE_S)) as f32;
Frame { shot: i, eye, look, fov, t, event: s.event, caption, black }
}
/// The caption of a shot: (head, sub).
pub fn caption(&self, shot: usize) -> (&str, &str) {
self.shots.get(shot).map_or(("", ""), |s| (s.head.as_str(), s.sub.as_str()))
}
pub fn shots(&self) -> usize {
self.shots.len()
}
/// The video time a shot starts at.
pub fn start_of(&self, shot: usize) -> f64 {
self.shots.get(shot).map_or(0.0, |s| s.start)
}
/// A one-line plan, for the chat.
pub fn summary(&self) -> String {
let events: HashSet<usize> = self.shots.iter().map(|s| s.event).collect();
format!("{} моментов, {} планов, {:.0} с", events.len(), self.shots.len(), self.len)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::record::{Event, What};
use crate::sim::{DroneKind, MissileKind, SamKind};
/// A recording with one interception: the interceptor leaves at `launch`, the kill is at `kill`.
fn intercept(len: u32, launch: u32, kill: u32, missile: bool) -> Recording {
let mut rec = Recording::blank(len);
let pos = DVec3::new(0.0, 100.0, 300.0);
rec.sams.push((5, SamKind::S400, DVec3::new(0.0, 64.0, 0.0)));
rec.straight(1, What::Drone(DroneKind::Geran3), 0, kill + 20, DVec3::new(0.0, 100.0, 900.0), pos);
if missile {
rec.straight(2, What::Missile(MissileKind::M48n6, 5), launch, kill, DVec3::new(0.0, 66.0, 0.0), pos);
}
rec.events.push(Event {
at: kill,
pos,
kind: EventKind::Kill { drone: 1, kind: DroneKind::Geran3, sam: 5, sam_kind: SamKind::S400, sam_index: 0, missile: missile.then_some(2), outcome: Default::default() },
});
rec
}
/// (head, start, end) of each shot in replay ticks.
fn spans(rec: &Recording, floor: f64) -> Vec<(String, f64, f64)> {
plan_event(rec, 0, floor).iter().map(|s| (s.head.clone(), s.table[0], shot_end(s))).collect()
}
// #77: the shots follow the real intervals: replay time never runs back, the launch is not after
// the kill, nothing about the interceptor is shown before its first point.
#[test]
fn a_short_interception_is_cut_in_the_order_it_happened() {
// The issue's case (flight 100 to 105), then 1, 5, 15 and 100+ ticks, the kill near the
// start and near the end of the recording, and a gun kill.
let cases = [(100, 105, true, 400), (100, 101, true, 400), (100, 105, true, 120), (100, 115, true, 400), (100, 260, true, 400), (3, 8, true, 400), (0, 4, true, 30), (0, 300, true, 300), (250, 255, false, 400), (5, 12, false, 400)];
for (launch, kill, missile, len) in cases {
let rec = intercept(len, launch, kill, missile);
let sp = spans(&rec, 0.0);
assert!(!sp.is_empty(), "{launch}->{kill}");
let mut prev_end = 0.0;
for (head, a, b) in &sp {
assert!(b >= a, "{launch}->{kill} {head}: {a}..{b}");
assert!(*a >= prev_end - 1e-9, "{launch}->{kill}: {head} starts at {a}, before the shot before it ended at {prev_end}: {sp:?}");
prev_end = *b;
if head == "Пуск" || head == "Сближение" {
assert!(*a >= launch as f64 - 1e-9 && *b <= kill as f64, "{launch}->{kill}: {head} {a}..{b} outside the flight");
}
}
// The launch comes before the close-up of the kill, which holds the kill itself.
let close = sp.iter().position(|s| s.0 == "Поражение цели").expect("close-up");
assert!(sp[..close].iter().all(|s| s.2 <= kill as f64 + 1e-9), "{launch}->{kill}: {sp:?}");
assert!(sp[close].2 >= kill as f64 || sp[close].2 >= len as f64 - 1.0, "{launch}->{kill}: {sp:?}");
}
}
#[test]
fn a_second_event_does_not_run_the_film_back() {
let rec = intercept(600, 100, 300, true);
// The previous event's last shot ended late: this one starts there.
let sp = spans(&rec, 180.0);
assert!(sp.iter().all(|s| s.1 >= 180.0 - 1e-9), "{sp:?}");
}
}