aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-12 06:05:31 +0300
committerValentin Popov <valentin@popov.link>2026-11-12 06:05:31 +0300
commitbdee85ba7249bc2657eaed8a4796e3382f370939 (patch)
tree9dec72c96d73c41fb0763c2c460f05716714590e
parentdb1a2ab3db395ae81a06698e9e15468b03a6ff93 (diff)
downloadfparkan-bdee85ba7249bc2657eaed8a4796e3382f370939.tar.xz
fparkan-bdee85ba7249bc2657eaed8a4796e3382f370939.zip
fix(fx): restore the native CRT increment for weather randomness
-rw-r--r--apps/fparkan-game/src/main.rs2
-rw-r--r--crates/fparkan-fx/src/environment.rs68
-rw-r--r--docs/appendices/knowledge-boundaries.md4
-rw-r--r--docs/reference/atmosphere.md23
-rw-r--r--docs/tomes/05-render.md8
5 files changed, 88 insertions, 17 deletions
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index e4556ce5..e2f8e700 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -4475,7 +4475,9 @@ fn load_environment(
} else {
None
};
+ // shortcut: fixed preview seed until native world RNG state/order is connected in G.
let mut environment = EnvironmentSystem::new(0x4650_4152_4B41_4E_u64);
+ eprintln!("render_coverage weather_rng_schedule_approx=1 (native CRT sequence; fixed preview seed and cross-system draw order unverified)");
environment.set_lightning_effect(lightning_effect);
Ok(Some(DynamicEnvironment {
schedule,
diff --git a/crates/fparkan-fx/src/environment.rs b/crates/fparkan-fx/src/environment.rs
index b0f9d83b..1fc033ab 100644
--- a/crates/fparkan-fx/src/environment.rs
+++ b/crates/fparkan-fx/src/environment.rs
@@ -187,10 +187,8 @@ pub const LIGHTNING_QUAD_DIMENSIONS: [f32; 3] = [
];
const NATIVE_RANDOM_SCALE: f32 = 1.0 / 32_768.0;
-/// The CRT linear congruential generator used by Terrain.dll and Effect.dll.
-/// Both modules read and update the same process-wide state, so the
-/// environment system intentionally owns one stream and passes it through
-/// each emitter in update order.
+/// The CRT linear congruential sequence used by Terrain.dll's weather.
+/// The environment system passes one stream through each emitter in update order.
#[derive(Clone, Copy, Debug)]
struct NativeRng {
state: u32,
@@ -202,7 +200,10 @@ impl NativeRng {
}
fn next_u15(&mut self) -> u16 {
- self.state = self.state.wrapping_mul(0x343F_D).wrapping_add(0x269E_C);
+ self.state = self
+ .state
+ .wrapping_mul(0x0003_43FD)
+ .wrapping_add(0x0026_9EC3);
((self.state >> 16) & 0x7FFF) as u16
}
@@ -1483,9 +1484,8 @@ pub struct EnvironmentSystem {
time_seconds: f32,
time_millis: u64,
time_millis_fraction: f64,
- /// Terrain and Effect share the CRT `rand` state. Keep one stream for
- /// particle respawns, lightning scheduling, and lightning placement so
- /// the native call order remains observable across subsystems.
+ /// One stream for particle respawns, lightning scheduling and placement.
+ /// Native initialization and the other world consumers remain unaligned.
rng: NativeRng,
rain: PrecipitationEmitter,
snow: PrecipitationEmitter,
@@ -2531,6 +2531,39 @@ mod tests {
use super::*;
#[test]
+ fn weather_rng_matches_executed_gog_crt_vectors() {
+ // GOG Terrain.dll +0x5884F, including zero and wrapping initial states.
+ for (seed, expected, final_state) in [
+ (
+ 0,
+ [38, 7719, 21238, 2437, 8855, 11797, 8365, 32285],
+ 2115878600,
+ ),
+ (
+ 1,
+ [41, 18467, 6334, 26500, 19169, 15724, 11478, 29358],
+ 1924036713,
+ ),
+ (
+ 0x12345678,
+ [13289, 23359, 19469, 24737, 23446, 14229, 6193, 18180],
+ 3338983488,
+ ),
+ (
+ u32::MAX,
+ [35, 29739, 3374, 11141, 31308, 7870, 5253, 2445],
+ 2307720487,
+ ),
+ ] {
+ let mut rng = NativeRng::new(u64::from(seed));
+ for value in expected {
+ assert_eq!(rng.next_u15(), value, "seed {seed}");
+ }
+ assert_eq!(rng.state, final_state);
+ }
+ }
+
+ #[test]
fn active_rain_is_camera_local_and_uses_sky_material() {
let mut system = EnvironmentSystem::new(7);
let weather = WeatherInput {
@@ -2627,21 +2660,22 @@ mod tests {
rain: WeatherState::new(true, 0.01, [1.0; 4]),
..WeatherInput::clear()
};
- let initial = system.update(0.0, weather.clone(), camera);
- let initial_position = initial
- .primitives
- .iter()
- .find_map(|primitive| match primitive {
- EnvironmentPrimitive::Particle { position, .. } => Some(*position),
- _ => None,
- })
- .expect("initial rain particle");
+ let _initial = system.update(0.0, weather.clone(), camera);
+ // Keep this particle inside both volumes so turning does not respawn it.
+ let initial_position = [20.0, 30.0, 35.0];
+ system.rain.particles[0].position = initial_position;
let turned_camera = Camera::with_basis(
[10.0, 20.0, 30.0],
[0.0, 1.0, 0.0],
[-1.0, 0.0, 0.0],
[0.0, 0.0, 1.0],
);
+ assert!(system.rain.volume.bounds(camera).contains(initial_position));
+ assert!(system
+ .rain
+ .volume
+ .bounds(turned_camera)
+ .contains(initial_position));
let turned = system.update(0.0, weather.clone(), turned_camera);
let turned_position = turned
.primitives
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index a83cdce7..aad03948 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -6,6 +6,10 @@ authoring API без динамического подтверждения.
## Render state
+CRT-последовательность погоды сверена исполнением Terrain.dll; seed просмотра
+и порядок расхода с остальным миром пока не выровнены (`weather_rng_schedule_approx`).
+Точное совпадение дождя, снега и вспышек по кадрам этим не подтверждено.
+
Доказаны frame boundaries, world traversal, material resolve и крупные проходы.
Не доказаны символами точные имена renderer vtable slots, полный набор CShade
state transitions и окончательный порядок части transparent/FX/shadow subpasses.
diff --git a/docs/reference/atmosphere.md b/docs/reference/atmosphere.md
index f5a61f6f..03af2754 100644
--- a/docs/reference/atmosphere.md
+++ b/docs/reference/atmosphere.md
@@ -8,6 +8,29 @@
геометрию купола, динамические цвета вершин, небесные слои, положение
светил, туман и нижнюю границу освещения.
+## Случайные числа погоды
+
+Положение новых капель и снежинок, задержки и размещение молний используют
+CRT-последовательность Terrain.dll из [эталонной сборки](original-binaries.md).
+Функция RVA `0x5884F` обновляет 32-битное состояние по RVA `0x6EAE0`:
+
+```text
+state = (state × 214013 + 2531011) mod 2³²
+value = (state >> 16) & 32767
+unit = value / 32768
+```
+
+При начальном состоянии `1` первые значения равны `41, 18467, 6334, 26500`.
+32 результата и конечные состояния четырёх последовательностей, включая
+переполнение `u32`, сверены исполнением DLL и закреплены Rust-тестом.
+У слагаемого важны все разряды: потеря последнего меняет всю погоду,
+даже если новое распределение внешне тоже кажется случайным.
+
+Приложение пока начинает отдельный поток погоды с постоянного seed.
+Начальное состояние оригинала и общий порядок расхода с остальным миром
+не выровнены; это явно отмечено `weather_rng_schedule_approx`.
+Совпадение самой последовательности не доказывает совпадения кадров погоды.
+
## Игровые сутки и смена дня и ночи
Вызов `TypedAtmosphere::sample(real_seconds)` принимает секунды от начала
diff --git a/docs/tomes/05-render.md b/docs/tomes/05-render.md
index ba47db4e..203e5236 100644
--- a/docs/tomes/05-render.md
+++ b/docs/tomes/05-render.md
@@ -695,6 +695,14 @@ RNG для lightning, atmosphere phases и FX должен иметь стаби
Даже правильный средний интервал не даёт повторяемый кадр, если random values
запрашиваются в другой последовательности.
+Дождь, снег и молнии получают числа из CRT-генератора Terrain. Он умножает
+32-битное состояние на `214013` и прибавляет `2531011`. Биты 16–30 результата
+дают число от 0 до 32767. Переполнение здесь намеренное. Эта последовательность
+сверена вызовом DLL; её начальное состояние и общий порядок расхода в
+просмотре ещё приближённые. Поэтому правильный генератор восстанавливает
+само правило случайности, но ещё не привязывает каждую каплю и вспышку к
+тому же моменту оригинального игрового мира.
+
Согласованная модель sort phases:
```text