From 0697475318920de466fe2a2ceebfa56bb0a6bc07 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Thu, 12 Nov 2026 08:24:13 +0400 Subject: fix(capture): replay actual celestial birth clocks --- apps/fparkan-game/src/camera_capture.rs | 115 +++++++++++++++++++++++ apps/fparkan-game/src/main.rs | 14 ++- docs/appendices/knowledge-boundaries.md | 5 +- docs/reference/atmosphere.md | 21 +++++ tools/native-frame-capture/NativeFrameCapture.cs | 76 ++++++++++++++- tools/native-frame-capture/README.md | 2 + 6 files changed, 227 insertions(+), 6 deletions(-) diff --git a/apps/fparkan-game/src/camera_capture.rs b/apps/fparkan-game/src/camera_capture.rs index dccb738e..987897d9 100644 --- a/apps/fparkan-game/src/camera_capture.rs +++ b/apps/fparkan-game/src/camera_capture.rs @@ -1,4 +1,5 @@ use super::{CapturedViewport, PreviewCameraFrame}; +use fparkan_fx::atmosphere::{AtmosphereFrame, SunBirth}; use fparkan_render::{LegacyD3d7Projection, RawCameraTransform}; use serde::Deserialize; @@ -24,6 +25,36 @@ pub(super) struct SkyUvClock { pub(super) verified: bool, pub(super) elapsed_milliseconds: u32, pub(super) raw_clock: Option, + pub(super) celestial_births: Option, +} + +#[derive(Clone, Debug, Deserialize, PartialEq)] +pub(super) struct CelestialBirthClocks { + sun: Option, + moon: Option, +} + +#[derive(Clone, Debug, Deserialize, PartialEq)] +struct CelestialClock { + elapsed_milliseconds: u32, + lifetime_milliseconds: u32, +} + +impl CelestialBirthClocks { + pub(super) fn apply(&self, atmosphere: &mut AtmosphereFrame) { + for (sample, clock, angles, row) in [ + (&mut atmosphere.sun, &self.sun, [90.0, 30.0], 3), + (&mut atmosphere.moon, &self.moon, [0.0, 50.0], 4), + ] { + sample.active = clock.is_some(); + sample.birth = clock.as_ref().map(|clock| SunBirth { + start_seconds: atmosphere.real_seconds - clock.elapsed_milliseconds as f32 / 1000.0, + lifetime_seconds: clock.lifetime_milliseconds as f32 / 1000.0, + initial_angles_degrees: angles, + material_row: row, + }); + } + } } #[derive(Clone, Debug, Deserialize, PartialEq)] @@ -129,6 +160,14 @@ pub(super) fn load_legacy_camera_capture( if capture.sky_uv_clock.is_none() { eprintln!("render_coverage captured_sky_phase_unverified=1 (capture has no sky UV clock; using replay elapsed time)"); } + if capture + .sky_uv_clock + .as_ref() + .and_then(|c| c.celestial_births.as_ref()) + .is_none() + { + eprintln!("render_coverage captured_celestial_clock_unverified=1 (capture has no celestial birth clocks; using nominal schedule births)"); + } Ok(capture) } @@ -161,6 +200,22 @@ pub(super) fn parse_legacy_camera_capture(bytes: &[u8]) -> Result i32::MAX as u32 { + return Err( + "legacy camera celestial clock has an invalid lifetime or age".to_string(), + ); + } + } + } if capture .atmosphere_seconds .is_some_and(|seconds| !seconds.is_finite() || seconds < 0.0) @@ -230,6 +285,66 @@ mod tests { }) } + #[test] + fn celestial_capture_rejects_invalid_lifetime() { + for lifetime in [0, i32::MAX as u32 + 1] { + let mut json = json(); + json["atmosphere_seconds"] = serde_json::json!(395.471); + json["sky_uv_clock"] = serde_json::json!({ + "verified": true, "elapsed_milliseconds": 123, + "celestial_births": {"sun": {"elapsed_milliseconds": 1000, + "lifetime_milliseconds": lifetime}, "moon": null} + }); + assert!(parse_legacy_camera_capture(&serde_json::to_vec(&json).unwrap()).is_err()); + } + } + + #[test] + fn celestial_capture_preserves_executed_sun_age_and_inactive_moon() { + use fparkan_fx::{ + atmosphere::TypedAtmosphere, + sky::{SkyFrame, SkyMaterials}, + }; + let mut json = json(); + json["atmosphere_seconds"] = serde_json::json!(395.471); + json["sky_uv_clock"] = serde_json::json!({ + "verified": true, "elapsed_milliseconds": 123, + "celestial_births": {"sun": {"elapsed_milliseconds": 378466, + "lifetime_milliseconds": 525000}, "moon": null} + }); + let capture = parse_legacy_camera_capture(&serde_json::to_vec(&json).unwrap()).unwrap(); + let mut missing_phase = json.clone(); + missing_phase + .as_object_mut() + .unwrap() + .remove("atmosphere_seconds"); + assert!(parse_legacy_camera_capture(&serde_json::to_vec(&missing_phase).unwrap()).is_err()); + let births = capture.sky_uv_clock.unwrap().celestial_births.unwrap(); + let mut atmosphere = TypedAtmosphere { + marker: 0, + version: 0, + tracks: Vec::new(), + trailer: Default::default(), + } + .sample(395.471); + births.apply(&mut atmosphere); + let materials = SkyMaterials::default(); + let sky = SkyFrame::from_atmosphere(&atmosphere, &materials, atmosphere.real_seconds); + // Executed GOG CSun state; its actual birth was at phase 17.005, not nominal 18. + for (actual, native) in + sky.sun + .direction + .into_iter() + .zip([-0.33643198, -0.7397671, -0.5827162]) + { + assert!((actual - native).abs() < 3e-6); + } + assert!(sky.sun.active); + assert!(!sky.moon.active); + assert_eq!(atmosphere.sun.birth.unwrap().lifetime_seconds, 525.0); + assert!(atmosphere.moon.birth.is_none()); + } + #[test] fn geometry_projection_preserves_surfaces_closer_than_restored_camera_near() { let mut json = json(); diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index 09de2b07..c7c8032c 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -146,6 +146,11 @@ fn run(args: &[String]) -> Result { .as_ref() .and_then(|c| c.sky_uv_clock.as_ref()) .map(|c| c.elapsed_milliseconds); + let captured_celestial_births = camera + .as_ref() + .filter(|_| args.atmosphere_seconds.is_none()) + .and_then(|c| c.sky_uv_clock.as_ref()) + .and_then(|c| c.celestial_births.clone()); let hold_schedule_phase = camera.is_some() && atmosphere_seconds.is_some(); let terrain_materials_duration_started = Instant::now(); let preview = static_preview_mesh_and_materials( @@ -172,6 +177,7 @@ fn run(args: &[String]) -> Result { )?; if let Some(environment) = &mut environment { environment.fixed_sky_uv_ms = captured_sky_uv_ms; + environment.captured_celestial_births = captured_celestial_births; } let sky_duration = sky_started.elapsed(); let audio = match audio::GameAudio::new(Arc::new(DirectoryVfs::new(&args.root)), &args.mission) @@ -4208,6 +4214,7 @@ struct DynamicEnvironment { fixed_schedule_seconds: Option, fixed_phase_reported: bool, fixed_sky_uv_ms: Option, + captured_celestial_births: Option, } struct DynamicEnvironmentFrame { @@ -4278,7 +4285,10 @@ impl DynamicEnvironment { self.fixed_phase_reported = true; } } - let atmosphere = self.schedule.sample(absolute_time_seconds); + let mut atmosphere = self.schedule.sample(absolute_time_seconds); + if let Some(births) = &self.captured_celestial_births { + births.apply(&mut atmosphere); + } let mut sky_mesh = self.sky.mesh().clone(); sky_mesh.update_uvs(self.fixed_sky_uv_ms.unwrap_or(clock_ms)); let sky_frame = @@ -4490,6 +4500,7 @@ fn load_environment( fixed_schedule_seconds, fixed_phase_reported: false, fixed_sky_uv_ms: None, + captured_celestial_births: None, })) } @@ -13791,6 +13802,7 @@ mod tests { fixed_schedule_seconds: None, fixed_phase_reported: false, fixed_sky_uv_ms: None, + captured_celestial_births: None, }; let mut land = fparkan_terrain_format::LandMeshDocument { diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index 1caee4c3..9dab56ab 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -69,8 +69,9 @@ MSH-запрос со свободной preview-камерой; это не п Собственный туман облачного купола и его нулевой additive RGB подтверждены живым VBO обычного прохода. Отдельный контекст неба в водном отражении и общий выбор fog для остальных проходов ещё не приняты (`fog_pass_eligibility_approx`). -Временные вспышки и состав света облаков не выровнены -(`sky_cloud_lighting_approx`); совпадение steady-state кадров не доказывает их. +Рождения небесных объектов в обычном просмотре ещё номинальные (`sky_cloud_lighting_approx`); +новые захваты сохраняют фактический возраст, старые отмечены `captured_celestial_clock_unverified`. +Остаточный пересвет и полная временная последовательность облачного света ещё не приняты. Внутренний ракурс «Конструктора» после настоящего входа игрока подтверждает исчезновение чёрной поверхности в проходе; наружные окна обеих миссий сверены на расстояниях около 60/85/110, а ближние diff --git a/docs/reference/atmosphere.md b/docs/reference/atmosphere.md index 03af2754..55a4e359 100644 --- a/docs/reference/atmosphere.md +++ b/docs/reference/atmosphere.md @@ -102,6 +102,27 @@ Rust-тест проверяет этот результат с допуском translation и половины far plane. Материал, строка и состояние объекта берутся из его `SunBirth` и таблицы `sky.wea`. +## Фактический возраст небесного объекта + +Фаза расписания и возраст солнца — разные величины. `CSun` хранит момент +рождения в поле `+0x28` и длительность в `+0x2C`; обновление RVA `0x4B570` +берёт разность текущих миллисекунд и этого момента с переполнением `u32`. +Обработчик атмосферы выбирает события по округлённой вверх секунде +(RVA `0x42291–0x422A7`). Поэтому фактическое создание не обязано совпадать с +номинальным временем ключа. В живом «Конструкторе» оно произошло на фазе +17,002 с вместо номинальных 18 с. При взгляде в сторону солнца даже такой +сдвиг меняет усиление света, а вслед за ним — цвет облаков. + +Захват читает массив объектов атмосферы `+0x1A0/+0x1A4/+0x1A8` на входе +в рендер неба. Для проверенного класса `CSun` он сохраняет возраст и +длительность в `sky_uv_clock.celestial_births`, отдельно для углов солнца +`[90, 30]` и луны `[0, 50]`. Данные принимаются вместе с часами неба только +при совпадении кадра, потока и world clock. Replay восстанавливает входной +`SunBirth`; направление, засветка и цвета затем вычисляются самим движком. +При явном `--atmosphere-seconds` эти захваченные возрасты не применяются. +Обычный просмотр пока берёт рождения из номинального расписания; захват +не восстанавливает полный диспетчер событий оригинала. + ## Купол Оригинальный `CSky` строит конечный купол, а не кубическую skybox. Значения diff --git a/tools/native-frame-capture/NativeFrameCapture.cs b/tools/native-frame-capture/NativeFrameCapture.cs index 9721049c..c5311216 100644 --- a/tools/native-frame-capture/NativeFrameCapture.cs +++ b/tools/native-frame-capture/NativeFrameCapture.cs @@ -138,6 +138,13 @@ internal static partial class NativeFrameCapture private sealed class SkyUvReadback { public uint Object, Origin, RawClock, ElapsedMilliseconds, Generation, ThreadId; + public CelestialBirthReadback[] Births; + } + + private sealed class CelestialBirthReadback + { + public bool Moon; + public uint ElapsedMilliseconds, LifetimeMilliseconds; } private sealed class AtmosphereReadback @@ -818,7 +825,60 @@ internal static partial class NativeFrameCapture Log("SKY_UV_CLOCK generation=" + frame.CameraGeneration + " tid=" + threadId + " raw=" + rawClock + " origin=" + origin + " elapsed_ms=" + elapsed); return new SkyUvReadback { Object = obj, Origin = origin, RawClock = rawClock, - ElapsedMilliseconds = elapsed, Generation = frame.CameraGeneration, ThreadId = threadId }; + ElapsedMilliseconds = elapsed, Generation = frame.CameraGeneration, ThreadId = threadId, + Births = CaptureCelestialBirths(process, terrainBase, rawClock, obj, frame) }; + } + + private static CelestialBirthReadback[] CaptureCelestialBirths(IntPtr process, uint terrainBase, + uint rawClock, uint skyObject, FrameSnapshot frame) + { + AtmosphereReadback sample; + if (frame.AtmosphereByThread == null + || !frame.AtmosphereByThread.TryGetValue(frame.CameraThreadId, out sample) + || !sample.ArithmeticVerified || !sample.TerrainModuleHashVerified + || !sample.WorldTimeMatchesRawClock || sample.RawClock != rawClock) return null; + uint atmosphere = sample.AtmosphereObject; + uint array = ReadU32Exact(process, checked(atmosphere + 0x1A0)); + uint count = ReadU32Exact(process, checked(atmosphere + 0x1A4)); + uint capacity = ReadU32Exact(process, checked(atmosphere + 0x1A8)); + if (count > capacity || capacity > 64 || (count != 0 && array == 0)) + throw new InvalidOperationException("Atmosphere object array bounds changed."); + List births = new List(); + bool skyFound = false; + for (uint i = 0; i < count; i++) { + uint obj = ReadU32Exact(process, checked(array + i * 4)); + skyFound |= obj == skyObject; + if (ReadU32Exact(process, obj) != checked(terrainBase + 0x6610C)) continue; + byte[] state = new byte[0x38]; + if (!ReadExact(process, obj, state)) throw new InvalidOperationException("Celestial birth unreadable."); + float angleA = BitConverter.ToSingle(state, 0x30), angleB = BitConverter.ToSingle(state, 0x34); + bool sun = Math.Abs(angleA - Math.PI / 2) < 1e-4 && Math.Abs(angleB - Math.PI / 6) < 1e-4; + bool moon = Math.Abs(angleA) < 1e-4 && Math.Abs(angleB - 50 * Math.PI / 180) < 1e-4; + uint lifetime = BitConverter.ToUInt32(state, 0x2C); + if ((!sun && !moon) || lifetime == 0 || lifetime > Int32.MaxValue + || births.Exists(delegate(CelestialBirthReadback b) { return b.Moon == moon; })) + throw new InvalidOperationException("Celestial birth layout or role changed."); + births.Add(new CelestialBirthReadback { Moon = moon, + ElapsedMilliseconds = unchecked(rawClock - BitConverter.ToUInt32(state, 0x28)), + LifetimeMilliseconds = lifetime }); + } + if (!skyFound) throw new InvalidOperationException("Captured sky is absent from its atmosphere object array."); + return births.ToArray(); + } + + private static void AppendCelestialBirthJson(StringBuilder json, CelestialBirthReadback[] births) + { + if (births == null) { json.Append("null"); return; } + json.Append("{"); + for (int role = 0; role < 2; role++) { + if (role != 0) json.Append(", "); + json.Append(role == 0 ? "\"sun\": " : "\"moon\": "); + CelestialBirthReadback found = Array.Find(births, delegate(CelestialBirthReadback b) { return b.Moon == (role == 1); }); + if (found == null) json.Append("null"); + else json.Append("{\"elapsed_milliseconds\": " + found.ElapsedMilliseconds + + ", \"lifetime_milliseconds\": " + found.LifetimeMilliseconds + "}"); + } + json.Append("}"); } private static bool SkyUvMatchesFrame(FrameSnapshot frame) @@ -843,7 +903,10 @@ internal static partial class NativeFrameCapture json.AppendLine(" \"origin_raw_clock\": " + sky.Origin + ","); json.AppendLine(" \"frame_generation\": " + sky.Generation + ","); json.AppendLine(" \"thread_id\": " + sky.ThreadId + ","); - json.AppendLine(" \"elapsed_milliseconds\": " + sky.ElapsedMilliseconds); + json.AppendLine(" \"elapsed_milliseconds\": " + sky.ElapsedMilliseconds + ","); + json.Append(" \"celestial_births\": "); + AppendCelestialBirthJson(json, sky.Births); + json.AppendLine(); json.AppendLine(" },"); } @@ -2426,11 +2489,18 @@ internal static partial class NativeFrameCapture CameraWorldGameTimeWordReadable = true, CameraWorldGameTimeWord = 265584022, WorldGameTimeWord = 265584022, SkyUv = new SkyUvReadback { Generation = 7, ThreadId = 11, RawClock = 265584022, - Origin = 509280060, ElapsedMilliseconds = unchecked(265584022U - 509280060U) } }; + Origin = 509280060, ElapsedMilliseconds = unchecked(265584022U - 509280060U), + Births = new CelestialBirthReadback[] { new CelestialBirthReadback { + ElapsedMilliseconds = 378466, LifetimeMilliseconds = 525000 } } } }; StringBuilder json = new StringBuilder(); AppendSkyUvJson(json, frame); if (!SkyUvMatchesFrame(frame) || json.ToString().IndexOf("4051271258", StringComparison.Ordinal) < 0) throw new InvalidOperationException("Verified sky UV wrapping clock was rejected."); + if (json.ToString().IndexOf("\"elapsed_milliseconds\": 378466", StringComparison.Ordinal) < 0 + || json.ToString().IndexOf("\"moon\": null", StringComparison.Ordinal) < 0) + throw new InvalidOperationException("Celestial age or inactive role was lost."); + if (CaptureCelestialBirths(IntPtr.Zero, 0, 0, 0, new FrameSnapshot()) != null) + throw new InvalidOperationException("Unpaired celestial clock accepted."); frame.SkyUv.ThreadId++; if (SkyUvMatchesFrame(frame)) throw new InvalidOperationException("Sky UV thread mismatch accepted."); frame.SkyUv.ThreadId--; diff --git a/tools/native-frame-capture/README.md b/tools/native-frame-capture/README.md index 1f7166b4..338f3438 100644 --- a/tools/native-frame-capture/README.md +++ b/tools/native-frame-capture/README.md @@ -6,6 +6,8 @@ Capture modes attach only to the isolated GOG-compatible scratch copy of `Parkan `sky_uv_clock` records the independent scrolling-texture clock at sky render entry (`Terrain+0x48110`). It requires a verified module/prologue, the selected camera, matching render thread/generation/world clock, and zenith UV values matching all three native scroll formulas. It preserves wrapping `u32` subtraction from the sky object's origin clock. FParkan holds this phase during exact capture replay; ordinary application frames animate the cloud, star and nebula UVs with periods of 50, 100 and 300 seconds. Older captures without this object still load and report `render_coverage captured_sky_phase_unverified=1`; their sky texture phase is not a native reference. +`sky_uv_clock.celestial_births` records the actual elapsed/lifetime milliseconds of sun and moon objects at the same sky boundary. The bounded atmosphere object array, CSun vtable and native birth angles are checked before reading these clocks. A null role means that object is absent; a null `celestial_births` means the clocks were not verified. Replay uses the captured ages with its own orbit/glare calculations; it does not import rendered light colors. An explicit `--atmosphere-seconds` override keeps nominal schedule births instead. Old captures report `captured_celestial_clock_unverified`. + The JSON keeps the `fparkan-legacy-camera-v1` schema and adds `native_fog_status`, diagnostic counts, and `native_fog`. The latter is an optional passive CPU-side snapshot of the effective sink flags/RGB/range plus the paired calls to the `Terrain+0x2F230` consumer. The flags byte is raw and not a decoded fog mode. Each draw record preserves the distance argument, raw bypass dword and effective low byte, source color, output pointers, and return address. Geometry at `EBP` is included only for the verified `Terrain+0x18A6A` caller with the expected geometry vtable and slot+0x14 target; other callers have `distance_geometry: null`. The fog object is `null` unless the samples match the same render thread, camera, generation, and projection matrix and agree on sink settings. `native_fog_status` is `paired`, `conflict`, `unpaired`, or `incomplete`; `native_fog_status_reason` explains an unpaired, conflicting, or incomplete result. The counts include processed, overflow, paired, rejected, other-thread, and matrix-mismatch calls. At most 512 calls are processed per camera generation; reaching the limit stops sampling and reports an incomplete result. These fields are additive: camera-input validation continues to accept older JSON without them. This probe observes CPU consumer state; it does not set fog or change GPU state. The capture helper expects an isolated copy at `target\shadow-probe\Parkan - Iron Strategy`; the original GOG installation stays untouched. For the default local install path, create that scratch copy from the repository root with: -- cgit v1.2.3