Searchlights with real spot lights and volumetric beams (#60); replay director: several angles per event, slow-motion kills, /airdef replay film and export to MP4 (#58) (fork patch 32)
build / mod (push) Successful in 3m32s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 09:28:13 +03:00
parent 8a12225ba1
commit 76f680eba6
40 changed files with 3827 additions and 52 deletions
+215 -5
View File
@@ -7,12 +7,13 @@ use horizon_mod_sdk::{
Mod, Registration, chat, command, game,
hud::{self, Corner},
input::{self, Event},
render::{self, Lighting, ModelInstanceId, ParticleSpawn, PointLight},
render::{self, Lighting, ModelInstanceId, ParticleSpawn, PointLight, SpotLight},
storage,
ui::{self, ButtonWidget, ItemWidget, ListWidget, Screen, Widget},
};
mod cinema;
mod film;
mod monitor;
mod panel;
mod radar;
@@ -75,6 +76,10 @@ struct AirDef {
wave: wave::WaveConfig,
/// A replay playing (it takes the screen and the mouse wheel).
replay: Option<replay::Player>,
/// An MP4 export in progress (`/airdef replay export`).
export: Option<Export>,
/// The effects preset a film replaced: (shader, hd).
film_prev: Option<(bool, bool)>,
/// The world drawn beyond the render distance (replays and cameras see far off).
far: bool,
/// The unit the move remote picked (its id), waiting for where to go.
@@ -101,6 +106,29 @@ struct AirDef {
by_id: Vec<ModelInstanceId>,
}
/// What `/airdef replay export` was asked for.
struct ExportOpts {
name: String,
which: String,
fps: u32,
size: (u32, u32),
crf: u32,
audio: bool,
seconds: Option<f64>,
}
#[derive(PartialEq)]
enum Stage {
Planning,
Arming,
Recording,
Finishing,
}
struct Export {
opts: ExportOpts,
stage: Stage,
ticks: u32,
}
/// A sound heard later: when, what, where, and how loud and high it was.
struct PendingSound {
due: u64,
@@ -377,8 +405,9 @@ impl AirDef {
if !s.alive() && s.burning() {
add(s.id + 15, s.pos + DVec3::Y * 1.5, (1.0, 0.5, 0.18), 80.0 * flicker(s.id), 30.0);
}
// A searchlight's spot where its beam meets the target.
if s.kind == SamKind::Light
// Without the renderer's spot lights, a searchlight's spot where its beam meets the target.
if !self.sim.spot_hd
&& s.kind == SamKind::Light
&& let Some(t) = s.target.and_then(|t| self.sim.drones.iter().find(|d| d.id == t))
&& self.sim.lit.contains(&t.id)
{
@@ -388,6 +417,35 @@ impl AirDef {
lights
}
/// The searchlights' spot lights (HD): a cone from the head along its real direction, as far
/// as the beam runs free; at most 16, the renderer draws the nearest.
fn spots(&self) -> Vec<SpotLight> {
if self.shown().replay {
return Vec::new();
}
self.sim
.sams
.iter()
.filter_map(|s| s.spot_beam())
.take(16)
.map(|b| SpotLight {
id: b.id,
x: b.origin.x,
y: b.origin.y,
z: b.origin.z,
dx: b.dir.x as f32,
dy: b.dir.y as f32,
dz: b.dir.z as f32,
color: (0.95, 0.97, 1.0),
intensity: 90_000.0,
range: (b.free + 3.5).min(1024.0) as f32,
inner_angle: sim::lights::BEAM_INNER as f32,
outer_angle: sim::lights::BEAM_OUTER as f32,
beam: 1.0,
})
.collect()
}
/// The effects preset: none, the post pass, or the post pass under the HD lighting.
fn set_effects(&mut self, shader: bool, hd: bool) {
self.sim.shader = shader;
@@ -398,6 +456,9 @@ impl AirDef {
}
self.hd = shader && hd;
self.apply_hd();
if !self.hd {
self.sim.spot_hd = false;
}
self.dirty = true;
}
@@ -407,6 +468,7 @@ impl AirDef {
// (The punch of the next blast sets its own.)
if !self.hd {
render::set_lights(&[]);
let _ = render::set_spot_lights(&[]);
}
}
@@ -545,6 +607,7 @@ impl AirDef {
render::set_lighting(Lighting { hd: true, exposure: 1.0 + 0.4 * p, bloom: 0.55 + 0.9 * p });
}
render::set_lights(&self.lights(&out));
self.sim.spot_hd = render::set_spot_lights(&self.spots());
let (clock, segments) = self.shown_smoke();
self.smoke.hd = render::set_smoke(clock, &segments);
} else {
@@ -893,6 +956,14 @@ impl AirDef {
}
fn stop_replay(&mut self) {
if self.export.take().is_some() {
render::capture_stop(true);
say("Экспорт отменён");
}
render::set_film_quality(false);
if let Some((shader, hd)) = self.film_prev.take() {
self.set_effects(shader, hd);
}
self.replay = None;
render::set_time_override(None);
render::set_main_view(None);
@@ -902,6 +973,140 @@ impl AirDef {
self.monitor_shown = false;
}
/// Plays the director's film of the last raid at the best quality: HD effects on (restored after).
fn start_film(&mut self, which: &str, export: Option<&ExportOpts>) -> Result<(), String> {
let n = self.sim.replays.len();
if n == 0 {
return Err("Повторов пока нет: запишется первый же налёт (когда небо очистится)".into());
}
let which = match which {
"best" => film::Which::Best,
"all" => film::Which::All,
n => film::Which::Top(n.parse().map_err(|_| "/airdef replay film [best|all|N]")?),
};
let rec = &self.sim.replays[n - 1];
let f = film::Film::build(rec, which).ok_or("В этом налёте нечего показать")?;
let mut player = replay::Player::new(rec.number, replay::Mode::Film(Box::new(f)), &self.sim);
if let Some(o) = export {
player.wait = true;
player.clean = true;
player.limit = o.seconds;
}
self.replay = Some(player);
self.grid = false;
input::claim_wheel(true);
// The best picture: HD on, the renderer's film quality (full-size world, more cloud and fog steps).
if self.film_prev.is_none() {
self.film_prev = Some((self.sim.shader, self.hd));
}
self.set_effects(true, true);
render::set_film_quality(true);
Ok(())
}
/// `/airdef replay export [имя] [best|all|N] [fps=60] [size=1920x1080] [crf=14] [sec=N] [noaudio]`.
fn start_export(&mut self, args: &[&str]) -> Result<(), String> {
let mut o = ExportOpts { name: String::new(), which: "best".into(), fps: 60, size: (1920, 1080), crf: 14, audio: true, seconds: None };
for a in args {
if let Some(v) = a.strip_prefix("fps=") {
o.fps = v.parse().map_err(|_| "fps=число")?;
} else if let Some(v) = a.strip_prefix("size=") {
let (w, h) = v.split_once('x').ok_or("size=1920x1080")?;
o.size = (w.parse().map_err(|_| "size=1920x1080")?, h.parse().map_err(|_| "size=1920x1080")?);
} else if let Some(v) = a.strip_prefix("crf=") {
o.crf = v.parse().map_err(|_| "crf=число")?;
} else if let Some(v) = a.strip_prefix("sec=") {
o.seconds = Some(v.parse().map_err(|_| "sec=число")?);
} else if *a == "noaudio" {
o.audio = false;
} else if matches!(*a, "best" | "all") || a.parse::<usize>().is_ok() {
o.which = a.to_string();
} else {
o.name = a.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_')).collect();
}
}
if self.export.is_some() {
return Err("Экспорт уже идёт (/airdef replay stop — отмена)".into());
}
if o.name.is_empty() {
let n = self.sim.replays.last().map_or(0, |r| r.number);
o.name = format!("raid{n}-{}", o.which);
}
let which = o.which.clone();
self.start_film(&which, Some(&o))?;
say(&format!("Экспорт «{}»: {} fps, {}x{}; планирую кадры…", o.name, o.fps, o.size.0, o.size.1));
self.export = Some(Export { opts: o, stage: Stage::Planning, ticks: 0 });
Ok(())
}
/// Drives an export: plan, start the recorder, wait for its first frame, report, stop at the end.
fn export_step(&mut self, r: &mut replay::Player) {
let Some(ex) = &mut self.export else { return };
ex.ticks += 1;
let st = render::capture_status();
let failed = |s: &render::CaptureState| s.phase == render::CapturePhase::Failed;
let mut finish: Option<Result<String, String>> = None;
match ex.stage {
Stage::Planning if r.film_ready() => {
let o = &ex.opts;
let res = render::capture_start(&render::CaptureOptions {
folder: "airdef-films".into(),
name: o.name.clone(),
fps: o.fps,
width: o.size.0,
height: o.size.1,
crf: o.crf,
audio: o.audio,
warmup: 8,
});
match res {
Ok(()) => {
say(&format!("Кадры готовы ({}); запись…", r.film_summary()));
ex.stage = Stage::Arming;
}
Err(e) => finish = Some(Err(e)),
}
}
Stage::Arming => {
if st.phase == render::CapturePhase::Recording {
r.wait = false;
ex.stage = Stage::Recording;
ex.ticks = 0;
} else if failed(&st) {
finish = Some(Err(st.message.clone()));
}
}
Stage::Recording => {
if failed(&st) {
finish = Some(Err(st.message.clone()));
} else if r.ended {
render::capture_stop(false);
ex.stage = Stage::Finishing;
} else if ex.ticks % 100 == 0 {
let len = r.film_len().unwrap_or(1.0).max(0.1);
say(&format!("Экспорт: {:.0}% ({} кадров)", (r.film_time() / len * 100.0).min(100.0), st.frames));
}
}
Stage::Finishing => match st.phase {
render::CapturePhase::Done => {
let note = if st.message.is_empty() { String::new() } else { format!(" ({})", st.message) };
finish = Some(Ok(format!("{}x{}, {} кадров: {}{note}", st.width, st.height, st.frames, st.file)));
}
render::CapturePhase::Failed => finish = Some(Err(st.message.clone())),
_ => {}
},
_ => {}
}
if let Some(res) = finish {
self.export = None;
match res {
Ok(m) => say(&format!("Экспорт готов: {m}")),
Err(e) => say(&format!("Экспорт не удался: {e}")),
}
r.done = true;
}
}
/// What a raid strikes: the marked objects, else where the player stands.
fn objects(&self, player: DVec3) -> Vec<DVec3> {
let live: Vec<DVec3> = self
@@ -1090,7 +1295,7 @@ impl AirDef {
}
}
const HELP: &str = "/airdef menu | monitor | grid | replay [map|full|reel|stop] | scenario save|load|list|delete | why [номер] | raid | repair | import | ew on|off | flare | move <номер> | target here | give | deploy <комплекс> | wave <тип|mix> [кол-во] [дальность] | clear | targets clear | damage on|off | truth on|off | shader on|off|hd | hold on|off | roles [комплекс классы] | stats";
const HELP: &str = "/airdef menu | monitor | grid | replay [map|full|reel|film [best|all|N]|export [имя] [best|all|N] [fps=60 size=1920x1080 crf=14 sec=N noaudio]|stop] | scenario save|load|list|delete | why [номер] | raid | repair | import | ew on|off | flare | move <номер> | target here | give | deploy <комплекс> | wave <тип|mix> [кол-во] [дальность] | clear | targets clear | damage on|off | truth on|off | shader on|off|hd | hold on|off | roles [комплекс классы] | stats";
impl Mod for AirDef {
fn init() -> Result<(Self, Registration), String> {
@@ -1107,6 +1312,8 @@ impl Mod for AirDef {
grid_ids: Vec::new(),
wave: wave::WaveConfig::default(),
replay: None,
export: None,
film_prev: None,
smoke: Default::default(),
far: true,
moving: None,
@@ -1258,7 +1465,8 @@ impl Mod for AirDef {
out.sounds.clear();
out.shake = None;
}
r.tick(&self.sim, self.listener, &mut out);
r.tick(&self.sim, &mut self.ground, self.listener, &mut out);
self.export_step(&mut r);
if r.done {
self.replay = Some(r);
self.stop_replay();
@@ -1527,6 +1735,8 @@ impl Mod for AirDef {
["replay", rest @ ..] => {
match rest.first().copied().unwrap_or("map") {
"stop" => self.stop_replay(),
"film" => self.start_film(rest.get(1).copied().unwrap_or("best"), None)?,
"export" => self.start_export(&rest[1..])?,
what => self.start_replay(what, None)?,
}
None