aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-13 22:57:42 +0300
committerValentin Popov <valentin@popov.link>2026-11-13 22:57:42 +0300
commitbb6b393060d7075c2bcf6411f9646c470115248e (patch)
tree67142b6aecf2ace0a1175b18dd642fc4bccfa59b
parent79676599f37dd35dcbde68b8951165d7dbd0d1ed (diff)
downloadfparkan-bb6b393060d7075c2bcf6411f9646c470115248e.tar.xz
fparkan-bb6b393060d7075c2bcf6411f9646c470115248e.zip
fix(capture): preserve geometry projection after sky pass
-rw-r--r--apps/fparkan-game/src/camera_capture.rs17
-rw-r--r--docs/reference/render-frame.md14
-rw-r--r--tools/native-frame-capture/NativeFrameCapture.cs53
-rw-r--r--tools/native-frame-capture/README.md2
4 files changed, 76 insertions, 10 deletions
diff --git a/apps/fparkan-game/src/camera_capture.rs b/apps/fparkan-game/src/camera_capture.rs
index 987897d9..fb193f8f 100644
--- a/apps/fparkan-game/src/camera_capture.rs
+++ b/apps/fparkan-game/src/camera_capture.rs
@@ -366,6 +366,23 @@ mod tests {
}
#[test]
+ fn geometry_projection_survives_later_sky_depth_range() {
+ let mut json = json();
+ let world = parse_legacy_camera_capture(&serde_json::to_vec(&json).unwrap())
+ .unwrap()
+ .preview_camera_frame()
+ .unwrap();
+ json["near_plane"] = serde_json::json!(700.0);
+ json["far_plane"] = serde_json::json!(50000.0);
+ let after_sky = parse_legacy_camera_capture(&serde_json::to_vec(&json).unwrap())
+ .unwrap()
+ .preview_camera_frame()
+ .unwrap();
+ assert_eq!(after_sky.clip_from_world, world.clip_from_world);
+ assert_eq!(after_sky.near_plane, 0.5);
+ }
+
+ #[test]
fn geometry_projection_rejects_unverified_mismatched_or_invalid_input() {
for (field, value) in [
("verified", serde_json::json!(false)),
diff --git a/docs/reference/render-frame.md b/docs/reference/render-frame.md
index f7965646..0ede2532 100644
--- a/docs/reference/render-frame.md
+++ b/docs/reference/render-frame.md
@@ -372,12 +372,16 @@ IMMEDIATE, затем FIFO. IMMEDIATE допускает разрывы изоб
Проекция во время рисования может отличаться от восстановленного состояния
камеры после обхода мира. В GOG у `CStridedPrimitive::RenderVB` (Terrain RVA
-`0x1D110`) renderer содержит `near = 0.5`, а на границе World3D RVA `0x13CE4`
-уже `near = 5`. Поэтому захват отдельно сохраняет `geometry_projection` при
+`0x1D110`) renderer содержит диапазон `0.5..700`, а на границе World3D RVA
+`0x13CE4` уже может быть `near = 5` или оставшийся после неба диапазон
+`700..50000`. Поэтому захват отдельно сохраняет `geometry_projection` при
первом вызове геометрии с той же мировой матрицей камеры. Поток, поколение,
-renderer, viewport, far и FOV сверяются с последующей границей; только
-подтверждённая запись используется при воспроизведении. Иначе пол в трёх
-единицах от камеры может исчезнуть из-за чужой ближней плоскости. Старые JSON
+renderer, режим перспективы, viewport, FOV и все 64 байта мировой матрицы
+сверяются с последующей границей; только подтверждённая запись используется
+при воспроизведении. При выборе ракурса требуемая проекция может совпасть
+с этой записью геометрии, даже если последующий проход сменил глубину.
+Проверки восстановления камеры и принадлежности пикселей кадру сохраняются.
+Иначе пол в трёх единицах от камеры может исчезнуть из-за чужой ближней плоскости. Старые JSON
без этой записи сохраняют прежнее поведение с явным счётчиком
`captured_projection_unverified`; их нужно переснять для проверки близких поверхностей.
Сравнивайте результат с фрагментом исходного PNG по прямоугольнику
diff --git a/tools/native-frame-capture/NativeFrameCapture.cs b/tools/native-frame-capture/NativeFrameCapture.cs
index c5311216..c708cd48 100644
--- a/tools/native-frame-capture/NativeFrameCapture.cs
+++ b/tools/native-frame-capture/NativeFrameCapture.cs
@@ -104,6 +104,7 @@ internal static partial class NativeFrameCapture
public uint ProjectionThreadId;
public ProjectionReadback Projection;
public ProjectionReadback GeometryProjection;
+ public byte[] GeometryEffectiveWorldMatrixBytes;
public uint GeometryProjectionGeneration;
public uint GeometryProjectionThreadId;
public SkyUvReadback SkyUv;
@@ -766,13 +767,26 @@ internal static partial class NativeFrameCapture
|| frame.GeometryProjectionGeneration != frame.ProjectionGeneration
|| frame.GeometryProjectionThreadId != frame.CameraThreadId
|| frame.GeometryProjectionThreadId != frame.ProjectionThreadId
- || geometry.Renderer != boundary.Renderer || geometry.Far != boundary.Far
- || geometry.Fov != boundary.Fov) return false;
+ || geometry.Renderer != boundary.Renderer || geometry.Mode != boundary.Mode
+ || geometry.Fov != boundary.Fov
+ || frame.Camera == null || !frame.Camera.CurrentAtProjectionVerified
+ || !frame.Camera.EffectiveWorldAtProjectionVerified
+ || frame.GeometryEffectiveWorldMatrixBytes == null
+ || !ByteArraysEqual(frame.GeometryEffectiveWorldMatrixBytes,
+ frame.Camera.ProjectionEffectiveWorldMatrixBytes)) return false;
for (int i = 0; i < 4; i++)
if (geometry.Viewport[i] != boundary.Viewport[i]) return false;
return true;
}
+ private static bool SelectedProjectionMatchesInput(FrameSnapshot frame, SelectedCameraInput input)
+ {
+ // A later sky pass may leave its depth range at the World3D return boundary.
+ return ProjectionMatchesCameraInput(frame.Projection, input)
+ || GeometryProjectionMatchesFrame(frame)
+ && ProjectionMatchesCameraInput(frame.GeometryProjection, input);
+ }
+
private static void AppendGeometryProjectionJson(StringBuilder json, FrameSnapshot frame)
{
if (!GeometryProjectionMatchesFrame(frame))
@@ -2520,6 +2534,9 @@ internal static partial class NativeFrameCapture
FrameSnapshot frame = new FrameSnapshot {
CameraGeneration = 7, ProjectionGeneration = 7, GeometryProjectionGeneration = 7,
CameraThreadId = 11, ProjectionThreadId = 11, GeometryProjectionThreadId = 11,
+ Camera = new CameraReadback { CurrentAtProjectionVerified = true,
+ EffectiveWorldAtProjectionVerified = true, ProjectionEffectiveWorldMatrixBytes = new byte[64] },
+ GeometryEffectiveWorldMatrixBytes = new byte[64],
Projection = new ProjectionReadback { Renderer = 100, Viewport = new int[] { 0, 0, 1280, 1024 },
Near = 5, Far = 700, Fov = 1.3f, Mode = 1, Verified = true },
GeometryProjection = new ProjectionReadback { Renderer = 100, Viewport = new int[] { 0, 0, 1280, 1024 },
@@ -2533,6 +2550,28 @@ internal static partial class NativeFrameCapture
Dictionary<string, object> projection = (Dictionary<string, object>)parsed["geometry_projection"];
if (Convert.ToSingle(projection["near_plane"]) != 0.5f)
throw new InvalidOperationException("Geometry projection must preserve draw near, not restored camera near.");
+ frame.Projection.Near = 700;
+ frame.Projection.Far = 50000;
+ if (!GeometryProjectionMatchesFrame(frame))
+ throw new InvalidOperationException("Same-frame geometry projection was lost when the sky left a different depth range.");
+ SelectedCameraInput input = new SelectedCameraInput { Viewport = new int[] { 0, 0, 1280, 1024 },
+ Near = 0.5f, Far = 700, FieldOfView = 1.3f, ProjectionMode = 1 };
+ if (!SelectedProjectionMatchesInput(frame, input))
+ throw new InvalidOperationException("Selected camera rejected its verified geometry projection.");
+ frame.GeometryEffectiveWorldMatrixBytes[0] = 1;
+ if (GeometryProjectionMatchesFrame(frame) || SelectedProjectionMatchesInput(frame, input))
+ throw new InvalidOperationException("Geometry projection accepted a different draw camera matrix.");
+ frame.GeometryEffectiveWorldMatrixBytes[0] = 0;
+ input.Far = 701;
+ if (SelectedProjectionMatchesInput(frame, input))
+ throw new InvalidOperationException("Selected camera accepted a different geometry depth range.");
+ input.Far = 700;
+ frame.GeometryProjection.Renderer++;
+ if (GeometryProjectionMatchesFrame(frame)) throw new InvalidOperationException("Geometry projection renderer mismatch accepted.");
+ frame.GeometryProjection.Renderer--;
+ frame.GeometryProjection.Fov = 1.04f;
+ if (GeometryProjectionMatchesFrame(frame)) throw new InvalidOperationException("Geometry projection FOV mismatch accepted.");
+ frame.GeometryProjection.Fov = 1.3f;
frame.GeometryProjectionThreadId++;
if (GeometryProjectionMatchesFrame(frame)) throw new InvalidOperationException("Geometry projection thread mismatch accepted.");
frame.GeometryProjectionThreadId--;
@@ -3927,6 +3966,7 @@ internal static partial class NativeFrameCapture
throw new InvalidOperationException("Could not disarm the previous generation's native fog boundary.");
frame.CameraGeneration++;
frame.GeometryProjection = null;
+ frame.GeometryEffectiveWorldMatrixBytes = null;
frame.SkyUv = null;
if (skyUvBreakpoint != null && !skyUvBreakpoint.Armed)
skyUvBreakpoint = ArmBreakpoint(process, "Terrain.sky-uv-clock",
@@ -4038,9 +4078,12 @@ internal static partial class NativeFrameCapture
&& ReadU32Exact(process, esp + 4) == ReadU32Exact(process, ngiBase + NgiRendererGlobalRva))
{
ProjectionReadback p = ReadProjection(process, ngiBase);
- if (p.Verified && p.Mode != 0)
+ byte[] drawMatrix = new byte[64];
+ if (p.Verified && p.Mode != 0
+ && ReadExact(process, frame.Camera.Camera + 0x60, drawMatrix))
{
frame.GeometryProjection = p;
+ frame.GeometryEffectiveWorldMatrixBytes = drawMatrix;
frame.GeometryProjectionGeneration = frame.CameraGeneration;
frame.GeometryProjectionThreadId = eventTid;
Log("GEOMETRY_PROJECTION generation=" + frame.CameraGeneration + " tid=" + eventTid
@@ -4130,7 +4173,7 @@ internal static partial class NativeFrameCapture
bool cameraMatrixMatchesInput = selectedCamera == null || !selectedCamera.Applied
|| SelectedMatrixMatchesProjection(frame);
bool projectionMatchesInput = selectedCamera == null
- || ProjectionMatchesCameraInput(frame.Projection, selectedCamera.Input)
+ || SelectedProjectionMatchesInput(frame, selectedCamera.Input)
&& cameraMatrixMatchesInput;
bool traceProjectionMatchesInput = projectionSelectorMode && traceCameraInput != null
&& ProjectionMatchesCameraInput(frame.Projection, traceCameraInput);
@@ -4205,6 +4248,8 @@ internal static partial class NativeFrameCapture
}
Log("SELECTED_CAMERA_PROJECTION_MATCH " + projectionMatchesInput
+ " cameraMatrixMatchesInput=" + cameraMatrixMatchesInput
+ + " verifiedGeometryMatch=" + (GeometryProjectionMatchesFrame(frame)
+ && ProjectionMatchesCameraInput(frame.GeometryProjection, selectedCamera.Input))
+ " inputViewport=" + String.Join(",", selectedCamera.Input.Viewport)
+ " actualViewport=" + (frame.Projection.Viewport == null ? "unreadable" : String.Join(",", frame.Projection.Viewport))
+ " inputNear=" + selectedCamera.Input.Near.ToString("R", CultureInfo.InvariantCulture)
diff --git a/tools/native-frame-capture/README.md b/tools/native-frame-capture/README.md
index 338f3438..1099b8d9 100644
--- a/tools/native-frame-capture/README.md
+++ b/tools/native-frame-capture/README.md
@@ -2,7 +2,7 @@
Capture modes attach only to the isolated GOG-compatible scratch copy of `Parkan - Iron Strategy`. Capture writes a PNG and a `fparkan-legacy-camera-v1` JSON file; boundary-trace mode writes a log and captures no pixels. `selector0_words` remains the local camera matrix at `camera+0x20`; the capture also records `effective_world_matrix_words` from `camera+0x60` with `effective_world_matrix_space: "world"` and a `parented_camera` marker. Both local and world matrices are sampled at the World3D render entry and reread at the projection-building boundary; only a same-thread, byte-compared snapshot paired with perspective values can produce usable renderer input. A passive `iron3d.dll` callsite probe records a path only when the active call arguments and path string are verified. It also samples `Terrain+0x421DC` after verifying the GOG module hash and the `EBP - [ESI+0x144]`, remainder by `[ESI+0x150]` instruction bytes. `atmosphere_seconds` is emitted only if the sampled `EDX` phase matches that arithmetic, the raw clock matches `World3D+0x32A38`, and sample, camera, and projection share the same render thread and generation. Otherwise it is `null`. This phase does not establish a general simulation-time, weather, or RNG value.
-`geometry_projection` records the renderer's perspective values at the first indexed geometry draw (`Terrain+0x1D110`) using that world's camera matrix and renderer. It is emitted only when thread, generation, renderer, viewport, far plane and FOV match the later World3D boundary. The near plane may differ: the observed world draw uses `0.5`, while the restored camera boundary contains `5`. FParkan prefers this verified object when replaying the capture. The top-level projection fields remain the camera-boundary tuple used for selected-camera preflight. Older captures without this object still load, with `render_coverage captured_projection_unverified=1`; nearby surfaces in those replays can be clipped incorrectly. Capture a fresh frame to verify them.
+`geometry_projection` records the renderer's perspective values at the first indexed geometry draw (`Terrain+0x1D110`) using that world's camera matrix and renderer. It is emitted only when thread, generation, renderer, perspective mode, viewport, FOV and all 64 world-matrix bytes match the later World3D boundary. The depth range may differ: the observed world draw uses `0.5..700`, while the later boundary can contain the restored camera near plane `5` or the sky range `700..50000`. FParkan prefers this verified object when replaying the capture. The top-level projection fields preserve the later boundary; selected-camera preflight and verification accept either that tuple or the paired geometry tuple matching the requested projection. Camera-matrix, restoration and pixel-attribution checks still apply. Older captures without this object still load, with `render_coverage captured_projection_unverified=1`; surfaces in those replays can be clipped incorrectly. Capture a fresh frame to verify them.
`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.