Film export: every frame in flight reaches the writer, listener follows the main view, cloud wind on film frames, set-smoke reports real activity

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 15:19:32 +03:00
committed by airdef
parent 288bfb66a5
commit 94dc8eda1a
7 changed files with 198 additions and 39 deletions
+24 -12
View File
@@ -6,26 +6,34 @@
use std::sync::Mutex;
use std::time::{Duration, Instant};
static FILM: Mutex<Option<Instant>> = Mutex::new(None);
/// While a film records: where its clock began (real time) and how much film time has passed.
static FILM: Mutex<Option<(Instant, Duration)>> = Mutex::new(None);
/// The film's moment (frozen for the frame), or None to run on real time again.
pub fn set(now: Option<Instant>) {
/// The film's moment (frozen for the frame) as (its origin, film time since it), or None to run on
/// real time again.
pub fn set(now: Option<(Instant, Duration)>) {
if let Ok(mut f) = FILM.lock() {
*f = now;
}
}
/// What the animations take as now.
pub fn now() -> Instant {
FILM.lock()
.ok()
.and_then(|f| *f)
.unwrap_or_else(Instant::now)
fn film() -> Option<(Instant, Duration)> {
FILM.lock().ok().and_then(|f| *f)
}
/// Time since `start` on this clock.
/// What the animations take as now.
pub fn now() -> Instant {
film().map_or_else(Instant::now, |(origin, t)| origin + t)
}
/// Time since `start` on this clock. In a film that is the film's own time since it began
/// whatever `start` was (an animation that began with the program would otherwise carry the
/// real time the program ran before the film): two exports of one recording agree frame by frame.
pub fn since(start: Instant) -> Duration {
now().saturating_duration_since(start)
match film() {
Some((_, t)) => t,
None => Instant::now().saturating_duration_since(start),
}
}
#[cfg(test)]
@@ -35,10 +43,14 @@ mod tests {
#[test]
fn film_time_is_the_frames_not_the_wall() {
let origin = Instant::now();
set(Some(origin + Duration::from_millis(50)));
// Whatever the animation started at, a film second is a second of its animation.
let long_ago = origin.checked_sub(Duration::from_secs(1000)).unwrap_or(origin);
set(Some((origin, Duration::from_millis(50))));
assert_eq!(since(origin), Duration::from_millis(50));
assert_eq!(since(long_ago), Duration::from_millis(50));
std::thread::sleep(Duration::from_millis(5));
assert_eq!(since(origin), Duration::from_millis(50));
assert_eq!(now(), origin + Duration::from_millis(50));
set(None);
assert!(since(origin) >= Duration::from_millis(5));
}
+18 -7
View File
@@ -11584,6 +11584,8 @@ impl Game<'_> {
),
};
let (view_yaw, view_pitch) = self.shaken_view(view_yaw, view_pitch);
// AirDef fork: the position stays the player's (a mod places its sounds round it); the
// orientation is the main view's below, in every filming mode, preview and export alike.
self.audio
.set_listener([camera.x, camera.y, camera.z], view_yaw, view_pitch);
// AirDef fork: a mod's camera as the screen's own view (replays): the listener stays the
@@ -11598,11 +11600,10 @@ impl Game<'_> {
r.cut = true;
}
}
if let Some(v) = &main_view
&& self.film.recording()
{
if let Some(v) = &main_view {
let (yaw, pitch) = film::listener_orientation(Some((v.yaw, v.pitch)), (view_yaw, view_pitch));
self.audio
.set_listener([camera.x, camera.y, camera.z], v.yaw, v.pitch);
.set_listener([camera.x, camera.y, camera.z], yaw, pitch);
}
let (camera, underwater, view_yaw, view_pitch) = match &main_view {
Some(v) => (v.camera, false, v.yaw, v.pitch),
@@ -11701,6 +11702,9 @@ impl Game<'_> {
let debug_lines = horizon_client::gizmos::camera_relative(&lines, at, view);
let debug_lines_on_top = horizon_client::gizmos::camera_relative(&on_top, at, view);
let debug_crosshair = horizon_client::gizmos::camera_relative(&crosshair.on_top, at, view);
// AirDef fork: while a film records, the clouds' wind runs on the film's own frames, not the
// world's ticks (so two exports of one recording show the same sky at frame N).
let cloud_clock = self.film_cloud_clock();
// LevelExtractor.extractBlockOutline: model translucency controls draw order.
let mut outline_after_terrain = false;
// GameRenderer.shouldRenderBlockOutline: not with the HUD hidden (F1), and only for a
@@ -11880,7 +11884,14 @@ impl Game<'_> {
.collect();
let hd_lights = self.mod_lights(camera, alpha);
let hd_spots = self.mod_spots(camera, alpha);
let (hd_smoke, hd_smoke_clock) = self.mod_smoke(camera, alpha);
// The smoke volume is ray-marched inside the fog pass: it is drawn only where that runs (fog
// on, an Overworld sky, not under water). The mods are told exactly that, so a mod keeps its
// own smoke where HD would draw none.
let smoke_drawn = horizon_client::gfx::hd_smoke_possible()
&& self.dim == Dim::Overworld
&& self.settings.horizon.sky
&& !underwater;
let (hd_smoke, hd_smoke_clock) = self.mod_smoke(camera, alpha, smoke_drawn);
// AirDef fork: HD's fog reads the ground's height round the camera.
let hd_ground = |x: i32, z: i32| {
self.world
@@ -11969,8 +11980,8 @@ impl Game<'_> {
texture: &self.pack.clouds,
uv: [(white.u0 + white.u1) / 2.0, (white.v0 + white.v1) / 2.0],
camera,
time: self.world.game_time,
partial_tick: alpha,
time: cloud_clock.map_or(self.world.game_time, |c| c.0),
partial_tick: cloud_clock.map_or(alpha, |c| c.1),
range: self.settings.cloud_range,
fast: self.settings.clouds == "fast",
color: sky.cloud_color,
+124 -16
View File
@@ -446,6 +446,40 @@ fn write_wav(raw: &Path, wav: &Path) -> Result<bool, String> {
Ok(true)
}
/// The frames left in flight at the end, in order, each to the writer exactly once. A readback
/// or send error is returned (the film is then not passed off as complete).
fn send_rest(
rest: Result<Vec<CapturedFrame>, String>,
sink: Option<&mpsc::SyncSender<Msg>>,
sent: &mut u32,
) -> Result<(), String> {
let frames = rest.map_err(|e| format!("the last frames could not be read back: {e}"))?;
for f in frames {
let Some(tx) = sink else {
return Err("the writer is gone: the last frames were lost".into());
};
tx.send(Msg::Frame(f))
.map_err(|_| "the writer stopped: the last frames were lost".to_string())?;
*sent += 1;
}
Ok(())
}
/// The cloud clock of frame number `stepped` of a film at `fps`: (whole game ticks, the fraction
/// of a tick), from the film's own frame count alone.
pub(super) fn film_cloud_time(stepped: u64, fps: u32) -> (i64, f64) {
let fps = u64::from(fps.max(1));
let ticks = stepped * 20 / fps;
let rest = (stepped * 20 % fps) as f64 / fps as f64;
(ticks as i64, rest)
}
/// The listener's orientation: the main view's (a replay or film camera) whenever there is one,
/// else the player's own. Only the orientation: the position is the player's either way.
pub(super) fn listener_orientation(main: Option<(f32, f32)>, own: (f32, f32)) -> (f32, f32) {
main.unwrap_or(own)
}
impl FilmState {
/// Whether frames are being recorded now.
pub(super) fn recording(&self) -> bool {
@@ -456,6 +490,12 @@ impl FilmState {
}
impl Game<'_> {
/// The clouds' time for the frame being drawn while a film records, else None (the world's).
pub(super) fn film_cloud_clock(&self) -> Option<(i64, f64)> {
let film = self.film.film.as_ref().filter(|f| f.phase == Phase::Recording)?;
Some(film_cloud_time(film.stepped, film.req.fps))
}
/// Start of a frame: a mod's start or stop, the writer's end, and the time step to run the
/// frame by: `real` normally, exactly one frame of the film while it records.
pub(super) fn film_step(&mut self, real: Duration) -> Duration {
@@ -479,9 +519,10 @@ impl Game<'_> {
film.stepped += 1;
let at = |k: u64| (k * 1_000_000_000 + fps / 2) / fps;
// Animations on wall time follow the film's frames, not the machine's speed.
horizon_client::film_clock::set(Some(
film.origin + Duration::from_nanos(at(n + 1)),
));
horizon_client::film_clock::set(Some((
film.origin,
Duration::from_nanos(at(n + 1)),
)));
Duration::from_nanos(at(n + 1) - at(n))
}
_ => real,
@@ -523,6 +564,7 @@ impl Game<'_> {
let cancelled = film.cancel;
let before = film.before;
let audio = film.req.audio;
let note = film.note.clone();
self.film.film = None;
if audio {
self.audio.film_end();
@@ -533,7 +575,9 @@ impl Game<'_> {
frames,
size,
file: o.file,
message: if cancelled && !o.ok {
message: if !note.is_empty() && (cancelled || !o.ok) {
note
} else if cancelled && !o.ok {
"cancelled".into()
} else {
o.message
@@ -659,7 +703,7 @@ impl Game<'_> {
film.phase = Phase::Recording;
film.stepped = 0;
film.origin = std::time::Instant::now();
horizon_client::film_clock::set(Some(film.origin));
horizon_client::film_clock::set(Some((film.origin, Duration::ZERO)));
if film.req.audio {
self.audio.film_begin();
}
@@ -779,21 +823,17 @@ impl Game<'_> {
};
}
Phase::Recording => {
let mut cancel = cancel;
if let Some(r) = self.renderer.as_mut() {
r.capture_next = false;
let rest = if cancel {
if cancel {
r.capture_discard();
Ok(Vec::new())
} else {
r.capture_ready(0).and_then(|_| {
// Everything in flight, waited for.
r.capture_ready(0)
})
};
if let (Ok(frames), Some(tx)) = (rest, &film.sink) {
for f in frames {
film.sent += 1;
let _ = tx.send(Msg::Frame(f));
// One wait for everything in flight; every frame of it goes on.
let rest = r.capture_ready(0).map_err(|e| e.to_string());
if let Err(e) = send_rest(rest, film.sink.as_ref(), &mut film.sent) {
film.note = e;
cancel = true;
}
}
}
@@ -821,3 +861,71 @@ impl Game<'_> {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn frame(n: u8) -> CapturedFrame {
CapturedFrame {
size: [1, 1],
bgra: true,
data: vec![n, 0, 0, 255],
}
}
fn drain(rx: &mpsc::Receiver<Msg>) -> Vec<u8> {
rx.try_iter()
.filter_map(|m| match m {
Msg::Frame(f) => Some(f.data[0]),
_ => None,
})
.collect()
}
/// #79: whatever is still in flight at the stop (0, 1 or 2 frames, ready or not) reaches the
/// writer once, in order; none is thrown away.
#[test]
fn the_frames_in_flight_at_the_stop_all_reach_the_writer() {
for pending in 0..=3u8 {
let (tx, rx) = mpsc::sync_channel(8);
let mut sent = 7;
let rest = (0..pending).map(|i| frame(10 + i)).collect();
send_rest(Ok(rest), Some(&tx), &mut sent).unwrap();
assert_eq!(sent, 7 + u32::from(pending));
assert_eq!(drain(&rx), (0..pending).map(|i| 10 + i).collect::<Vec<_>>());
}
}
/// #84: the main view's orientation is used with or without a capture.
#[test]
fn the_listener_follows_the_main_view_in_every_filming_mode() {
assert_eq!(listener_orientation(Some((90.0, 5.0)), (0.0, 0.0)), (90.0, 5.0));
assert_eq!(listener_orientation(None, (12.0, -3.0)), (12.0, -3.0));
}
/// #80: the cloud wind of frame N depends on N and the frame rate only.
#[test]
fn the_cloud_clock_is_the_films_frames() {
// One second of film is 20 ticks at any frame rate; the frame in between is a fraction.
for fps in [24u32, 30, 60] {
assert_eq!(film_cloud_time(u64::from(fps), fps), (20, 0.0));
assert_eq!(film_cloud_time(u64::from(fps) * 5, fps).0, 100);
}
let (t, p) = film_cloud_time(1, 60);
assert_eq!(t, 0);
assert!((p - 20.0 / 60.0).abs() < 1e-12);
// Pure: the same frame, the same sky.
assert_eq!(film_cloud_time(777, 30), film_cloud_time(777, 30));
}
#[test]
fn a_failed_readback_or_dead_writer_is_an_error_not_a_short_success() {
let (tx, rx) = mpsc::sync_channel(8);
let mut sent = 0;
assert!(send_rest(Err("gpu".into()), Some(&tx), &mut sent).is_err());
drop(rx);
assert!(send_rest(Ok(vec![frame(1)]), Some(&tx), &mut sent).is_err());
assert_eq!(sent, 0);
}
}
+5 -1
View File
@@ -96,6 +96,7 @@ impl Game<'_> {
&mut self,
_camera: glam::DVec3,
_alpha: f64,
_drawn: bool,
) -> (Vec<horizon_client::gfx::HdSmoke>, f32) {
(Vec::new(), 0.0)
}
@@ -310,8 +311,11 @@ impl Game<'_> {
&mut self,
camera: DVec3,
alpha: f64,
drawn: bool,
) -> (Vec<horizon_client::gfx::HdSmoke>, f32) {
let on = self.mod_hd().is_some() && horizon_client::gfx::hd_smoke_enabled();
// What the mod is told is what is drawn: HD on, the smoke pass possible, and this frame's
// fog pass (an Overworld sky, above water) running.
let on = self.mod_hd().is_some() && drawn;
self.mods.mods.set_smoke_active(on);
let Some((before, now)) = self.mods.mods.smoke_clock().filter(|_| on) else {
return (Vec::new(), 0.0);
+1 -1
View File
@@ -87,7 +87,7 @@ mod native_post;
pub use hd::set_film_quality;
pub use hd::{
HdLight, HdSettings, HdSmoke, HdSpot, MAX_SPOTS as HD_MAX_SPOTS,
smoke_enabled as hd_smoke_enabled, spots_enabled as hd_spots_enabled,
smoke_enabled as hd_smoke_enabled, smoke_possible as hd_smoke_possible, spots_enabled as hd_spots_enabled,
};
pub use mod_views::ModView;
mod native_sky;
+2 -2
View File
@@ -97,7 +97,7 @@ pub use frame::{HdLight, HdScene, HdSettings, HdSpot, MAX_SPOTS, light_of, vanil
pub use gbuffer::{ALBEDO, LIGHT_LEVELS, NORMAL};
pub use materials::{Table as MaterialTable, table as material_table, wind_enabled, wind_seconds};
pub use shadows::{CASCADES, SHADOW_TINT, cascades, color_shadows_enabled};
pub use smoke::{HdSmoke, smoke_enabled};
pub use smoke::{HdSmoke, smoke_enabled, smoke_possible};
pub use taa::{film_quality, jitter, jitter_count, scale_override, set_film_quality, taa_enabled};
pub use volumes::clouds_enabled;
@@ -746,7 +746,7 @@ impl Hd {
lights: &[HdLight],
clock: f32,
) {
if scene.sky && volumes::fog_enabled() && smoke_enabled() {
if scene.sky && smoke::smoke_possible() {
self.smoke.prepare(queue, scene, smoke, lights, clock);
} else {
self.smoke.frame = Default::default();
+24
View File
@@ -64,6 +64,30 @@ pub fn smoke_enabled() -> bool {
*ON.get_or_init(|| std::env::var("HORIZON_HD_SMOKE").map_or(true, |v| v != "0"))
}
/// Whether the smoke can be drawn at all: its volume is ray-marched in the fog pass, so it needs
/// the volumetric fog as well as `HORIZON_HD_SMOKE`. This is what the mods are told.
pub fn smoke_possible() -> bool {
smoke_possible_with(super::volumes::fog_enabled(), smoke_enabled())
}
fn smoke_possible_with(fog: bool, smoke: bool) -> bool {
fog && smoke
}
#[cfg(test)]
mod possible_tests {
use super::smoke_possible_with;
/// #81: the answer to the mods is the real one: no fog pass, no smoke promised.
#[test]
fn smoke_is_promised_only_with_the_fog_pass() {
assert!(smoke_possible_with(true, true));
assert!(!smoke_possible_with(false, true));
assert!(!smoke_possible_with(true, false));
assert!(!smoke_possible_with(false, false));
}
}
/// A segment of smoke as the game hands it over for a frame, relative to the camera.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]