Phase 1: time-varying ocean environment

Add src/world/ocean.py and wire it into World:
- Tides (M2 + S2, seeded amplitude/phase, spatial gradient, Green's-law
  shoaling); depth_m/physical_depth_m are chart datum + tide, so grounding
  and submarine safe depth follow the tide. charted_depth_m keeps the datum.
- Mixed-layer depth with diurnal heating (zero 24 h mean), wind-mixing
  deepening (saved exact relaxation) and three internal-wave components.
- Seasonal/diurnal SST, thermocline temperature profile and the Mackenzie
  sound-speed equation; the bathythermograph and ping echo latency use it.
- Wind-driven surface drift (3 %, 20 deg right) added to current_vec.
- Seeded sediment grid with Rayleigh bottom-loss parameters, and up to 64
  wrecks/submerged rocks (rocks shoal depth, never above 15 m).
- Save v12 world block gains the ocean clock and wind-mixing state.
- HQ weather bulletin reports tide and water temperature; manual EN/DE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
db9979andClaude Opus 5.5 committed 2026-09-23 13:41:37 +02:00
1 parent bd9260ba09
commit d666b1b46f
17 files changed
+586 -30

No files matched your search

+1 -1
View File
@@ -1965,7 +1965,7 @@
"editor.runtime_unsupported": "Mission verwendet Felder, die zur Laufzeit nicht unterstuetzt werden",
"runtime.hq.roe": "HQ: ROE {roe} \u2013 erst pingen + klassifizieren, dann schie\u00dfen.",
"runtime.hq.weather": "HQ: Wetter: See {sea_state}, Wind aus {wind_from} Grad mit {wind_speed} kn, Regen {rain}, Sicht {visibility} NM.",
"runtime.hq.profile": "HQ: See {sea_state}, Wind aus {wind_from} Grad mit {wind_speed} kn, Regen {rain}, Sicht {visibility} NM, Thermokline {depth} m.",
"runtime.hq.profile": "HQ: See {sea_state}, Wind aus {wind_from} Grad mit {wind_speed} kn, Regen {rain}, Sicht {visibility} NM, Thermokline {depth} m, Gezeit {tide} m, Wasser {sst} °C.",
"runtime.hq.threat_underwater": "HQ: Erste Aufklaerung meldet moegliche Unterwasseraktivitaet bei Peilung {bearing} Grad, etwa {range} NM von der Startposition. Position unbestaetigt; Suche in diesem Sektor beginnen.",
"runtime.hq.threat_surface": "HQ: Erste Aufklaerung meldet moegliche feindliche Oberflaechenaktivitaet bei Peilung {bearing} Grad, etwa {range} NM von der Startposition. Position unbestaetigt; diesen Sektor untersuchen.",
"runtime.hq.threat_unknown": "HQ: Keine verlaessliche anfaengliche Bedrohungsposition verfuegbar. Zugewiesenen Missionssektor patrouillieren und Lagebild mit Bordsensoren aufbauen.",
+1 -1
View File
@@ -1965,7 +1965,7 @@
"editor.runtime_unsupported": "Mission uses fields not supported by the runtime",
"runtime.hq.roe": "HQ: ROE {roe} - ping and classify before firing.",
"runtime.hq.weather": "HQ: Weather: sea {sea_state}, wind from {wind_from} deg at {wind_speed} kn, rain {rain}, visibility {visibility} NM.",
"runtime.hq.profile": "HQ: Sea {sea_state}, wind from {wind_from} deg at {wind_speed} kn, rain {rain}, visibility {visibility} NM, thermocline {depth} m.",
"runtime.hq.profile": "HQ: Sea {sea_state}, wind from {wind_from} deg at {wind_speed} kn, rain {rain}, visibility {visibility} NM, thermocline {depth} m, tide {tide} m, water {sst} °C.",
"runtime.hq.threat_underwater": "HQ: Initial intelligence reports possible underwater activity near bearing {bearing} deg, approximately {range} NM from your start position. Position unconfirmed; begin the search in that sector.",
"runtime.hq.threat_surface": "HQ: Initial intelligence reports possible hostile surface activity near bearing {bearing} deg, approximately {range} NM from your start position. Position unconfirmed; investigate that sector.",
"runtime.hq.threat_unknown": "HQ: No reliable initial threat position is available. Patrol the assigned mission sector and develop the picture with onboard sensors.",
+2
View File
@@ -53,6 +53,8 @@ Gefechtslage:
- Sprint und Drift: mit FULL an eine neue Position, dann auf 4-6 kn gehen und horchen.
- Starke einseitige Flutung bewirkt Krängung und einen stetigen Drehzug; mit Ruder ausgleichen.
- Das Schiff kann nicht auf Land fahren (es wird zurückgeschoben), aber Flachwasser begrenzt die Tauchtiefe des Helikoptersonars (10 m Bodenabstand).
- Die Wassertiefe folgt der Gezeit (halbtägig, etwa 12,4 h, im Flachwasser bis zu einigen Metern). Eine Passage, die bei Hochwasser sicher ist, kann bei Niedrigwasser zur Grundberührung führen; das HQ-Wetterbulletin meldet die aktuelle Gezeit am Schiff.
- Wind treibt das Oberflächenwasser: etwa 3 % der Windgeschwindigkeit, 20 Grad rechts von der Windrichtung, zusätzlich zur ständigen Meeresströmung.
## Nicht modelliert {#bridge-limits}
+2
View File
@@ -53,6 +53,8 @@ Combat situation:
- Sprint-and-drift: sprint at FULL to a new position, then slow to 4-6 kn and listen.
- Heavy flooding on one side gives a list and a steady yaw pull; correct with rudder.
- The ship cannot run aground onto land; it is pushed back, but shallow water limits the helicopter dipping depth (10 m bottom clearance).
- Water depth follows the tide (semi-diurnal, about 12.4 h, up to a few metres in shallow water). A passage that is safe at high water can ground the hull at low water; the HQ weather bulletin reports the current tide at the ship.
- Wind pushes the surface water: about 3 % of the wind speed, 20 degrees to the right of downwind, on top of the steady ocean current.
## Not modelled {#bridge-limits}
+1 -1
View File
@@ -62,7 +62,7 @@ Die Anzeige zeigt gemessene Modulation, keine sichere Identität. Die Analysefen
### TMA, Umwelt und Aktiv {#sonar-tma-env}
- **TMA** löst Entfernung, Kurs und Fahrt aus einer Peilungsreihe des fokussierten Kontakts. Nötig sind mindestens 4 Peilungen über 180 s und eine eigene Kursänderung von mindestens 6 Grad; die Entfernung gilt ab Qualität 0,35. Tiefe schätzt TMA nicht.
- **UMWELT / FUSION** zeigt den Bathythermographen (`E`, 60 s Abklingzeit): gemessene Schichttiefe, Schallgeschwindigkeitsprofil und Konvergenzzonen, dazu den Vergleich HMS/TAS. Peilungen innerhalb 5 Grad bestätigen sich; ab 9 Grad Abweichung wird ein möglicher Geisterkontakt markiert.
- **UMWELT / FUSION** zeigt den Bathythermographen (`E`, 60 s Abklingzeit): gemessene Schichttiefe, Schallgeschwindigkeitsprofil und Konvergenzzonen, dazu den Vergleich HMS/TAS. Peilungen innerhalb 5 Grad bestätigen sich; ab 9 Grad Abweichung wird ein möglicher Geisterkontakt markiert. Die Schicht ist nicht fest: Nachmittagssonne macht sie flacher (etwa 8 m), starker Wind mischt sie über Stunden tiefer, und interne Wellen verschieben sie um einige Meter. Den BT nach einigen Stunden oder einem Wetterwechsel wiederholen. Das gemessene Profil ist die echte temperaturabhängige Schallgeschwindigkeit (Mackenzie-Gleichung) und fällt deshalb unterhalb der Schicht ab.
- **ACTIVE** listet die Echos der letzten 120 s: Peilung, Entfernung (+/-0,18 sm) und Tiefe (+/-12 m). Ein Ping-Fix veraltet nach 120 s.
## Bugsonar und Schleppsonar {#sonar-arrays}
+1 -1
View File
@@ -61,7 +61,7 @@ The display shows measured modulation, not certain identity. The analysis window
### TMA, environment and active {#sonar-tma-env}
- **TMA** solves range, course and speed from a bearing series of the focused contact. It needs at least 4 bearings over 180 s and an own course change of at least 6 degrees; range is trusted from quality 0.35. It does not estimate depth.
- **UMWELT / FUSION** shows the bathythermograph (`E`, 60 s cooldown): measured layer depth, sound-speed profile and convergence-zone bands, plus the HMS/TAS comparison. Bearings within 5 degrees confirm each other; 9 degrees or more apart are flagged as a possible ghost contact.
- **UMWELT / FUSION** shows the bathythermograph (`E`, 60 s cooldown): measured layer depth, sound-speed profile and convergence-zone bands, plus the HMS/TAS comparison. Bearings within 5 degrees confirm each other; 9 degrees or more apart are flagged as a possible ghost contact. The layer is not fixed: afternoon sun makes it shallower (about 8 m), strong wind mixes it deeper over hours, and internal waves move it a few metres. Repeat the BT after a few hours or a weather change. The measured profile is the real temperature-driven sound speed (Mackenzie equation), so it drops below the layer.
- **ACTIVE** lists echoes of the last 120 s: bearing, range (+/-0.18 NM) and depth (+/-12 m). A ping fix ages out after 120 s.
## Hull sonar versus towed array {#sonar-arrays}
+11
View File
@@ -52,6 +52,17 @@ Alle Werte sind die Standardwerte der aktuellen Spielversion. Eigene Schwierigke
| TAS-Tiefe | 20-260 m, minus 4 m je Knoten |
| Schaden | 9 Abteilungen, 3 Trupps; sinkt bei 60 % mittlerer Flutung |
## Umwelt {#ref-environment}
| Vorgang | Modell |
|---|---|
| Gezeit | M2 (12,42 h) + S2 (12 h), 0,4-1,4 m Amplitude, im Flachwasser größer |
| Deckschicht | jahreszeitliche Grundtiefe; nachmittags etwa 8 m flacher; vertieft sich bei Wind über 12 kn; interne Wellen +/-6 m |
| Schallgeschwindigkeit | Mackenzie-Gleichung aus dem Temperaturprofil (Oberfläche 8-18 Grad C je nach Jahreszeit) |
| Strömung | festes Feld bis 1 kn plus 3 % des Windes, 20 Grad rechts der Windrichtung |
| Meeresboden | Fels, Kies, Sand, Schluff oder Schlick; beeinflusst die Bodenreflexion |
| Hindernisse | bis zu 64 kartierte Wracks und Unterwasserfelsen (Spitzen mindestens 15 m tief) |
## Gegnerische U-Boote {#ref-subs}
| Klasse | Leisheit | Max. Tiefe | Torpedos |
+11
View File
@@ -52,6 +52,17 @@ All values are the defaults of the current game version. Custom difficulty and m
| TAS depth | 20-260 m, minus 4 m per knot |
| Damage | 9 compartments, 3 teams; sinks at 60 % mean flooding |
## Environment {#ref-environment}
| Process | Model |
|---|---|
| Tide | M2 (12.42 h) + S2 (12 h), 0.4-1.4 m amplitude, larger in shallow water |
| Surface layer | seasonal base depth; about 8 m shallower in the afternoon; deepens in wind above 12 kn; internal waves +/-6 m |
| Sound speed | Mackenzie equation from the temperature profile (sea surface 8-18 deg C by season) |
| Current | steady field up to 1 kn plus 3 % of the wind, 20 deg right of downwind |
| Seabed | rock, gravel, sand, silt or mud; affects bottom reflection |
| Hazards | up to 64 charted wrecks and submerged rocks (tops at least 15 m deep) |
## Opposing submarines {#ref-subs}
| Class | Quietness | Max depth | Torpedoes |
+7 -7
View File
@@ -366,13 +366,13 @@ Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment.
| Gap | Current behaviour | Would need |
|-----|-------------------|------------|
| **No ocean currents** | None; all entities move by own propulsion only | Current field (speed/direction) affecting drift of all floating objects, torpedoes, buoys |
| **No tides** | Water depth is static | Tidal variation affecting under-keel clearance, buoy depth, thermocline |
| **No thermocline dynamics** | Thermocline depth is static per grid cell | Diurnal warming/cooling; frontal structure; internal waves |
| **No wind/current interaction** | Wind is independent of surface drift | Wind-driven surface current (3% rule); affects sonar surface path |
| **No seasonal / diurnal sound-speed variation** | Sound speed is fixed by depth only | SST variation → sound-speed changes; diurnal thermocline deepening |
| **Seabed composition** | Only depth; no sediment type | Bottom type affects sonar reflection (hard vs soft), torpedo ground effect, ASW channel |
| **No underwater geography beyond depth** | No rocks, reefs, shipwrecks, cable routes | Sonar clutter from fixed underwater objects; navigation hazards |
| ~~**No ocean currents**~~ | **Closed.** Static seeded current field (`World.current_vec`) applied to ship, subs, surface ships, torpedoes and decoys; Phase 1 adds the wind-driven component. | — |
| ~~**No tides**~~ | **Closed (Phase 1).** `src/world/ocean.py`: M2 + S2 constituents, seeded amplitude/phase and a spatial phase gradient, Green's-law shoaling. `World.depth_m`/`physical_depth_m` = chart datum + tide, so grounding and sub safe depth follow the tide. | — |
| ~~**No thermocline dynamics**~~ | **Closed (Phase 1).** Mixed-layer depth = seasonal cell base + diurnal heating (-8 m at 15:00, zero 24-h mean) + wind-mixing deepening (saved first-order relaxation, fast deepening / slow restratification) + three internal-wave components. | — |
| ~~**No wind/current interaction**~~ | **Closed (Phase 1).** 3 % of wind speed, deflected 20 deg to the right of downwind, added to `current_vec`. | — |
| ~~**No seasonal / diurnal sound-speed variation**~~ | **Closed (Phase 1).** Seeded season, SST with seasonal and diurnal terms, exponential thermocline temperature profile and the Mackenzie (1981) equation. Used by the bathythermograph and ping echo latency; the ray tracer (Phase 4) samples the same profile. | — |
| ~~**Seabed composition**~~ | **Closed (Phase 1 model).** Seeded 12x12 sediment grid (rock/gravel/sand/silt/mud) from depth and slope with Hamilton-style geoacoustic parameters and a Rayleigh fluid-fluid bottom-loss function; consumed by the sonar equation (Phase 3) and ray tracer (Phase 4). | — |
| ~~**No underwater geography beyond depth**~~ | **Closed (Phase 1 model).** Up to 64 seeded wrecks and submerged rocks. Rocks shoal `depth_m` (tops at least 15 m, a hazard to submarines and weapons, never to surface keels); wrecks become active-sonar clutter in Phase 3. | — |
---
+12 -6
View File
@@ -36,6 +36,7 @@ from src.core.mission_definition import static_preview, validate_mission
from src.core.station import Station
from src.core.version import SAVE_SCHEMA, SAVE_VERSION
from src.sensors.ais import AISReceiver
from src.world.ocean import OceanEnvironment
from src.core.save_schema import (
COMPARTMENT_FIELDS, COMPARTMENT_STATES, DAMAGE_FIELDS, RNG_STREAMS,
SAVE_ROOT_FIELDS, SHIP_FIELDS, WORLD_FIELDS)
@@ -75,7 +76,6 @@ from src.sensors.platform import (
)
from src.ship.damage import DamageModel
from src.ship.ship import Ship
from src.sonar import propagation
from src.sonar.sonar import Contact, SonarSystem, TowState
from src.sonar.tma import BearingPoint, BearingTrack
from src.ui import layout
@@ -1409,7 +1409,8 @@ class Game:
def _feed_ping(self, tgt, contact) -> None:
"""W1/W2: Ping-Echo-Feed inkl. Echolatenz (W3: Salzwasser-Schallfeld)."""
dist = tgt.distance_nm(self.ship)
latenz = self.world.echo_delay_s(dist)
mx, my = (self.ship.x + tgt.x) * .5, (self.ship.y + tgt.y) * .5
latenz = self.world.echo_delay_s(dist, mx, my)
klass = {"diesel_alt": "Diesel", "aip_modern": "AIP",
"ssn": "Nuclear propulsion?"}.get(
getattr(tgt, "stype", None) and tgt.stype.key or "",
@@ -1421,7 +1422,7 @@ class Game:
bearing=f"{contact.bearing:4.0f}",
range=f"{contact.range_est:4.1f}",
latency=f"{latenz:3.1f}",
speed=f"{config.SOUND_SPEED_M_S:.0f}",
speed=f"{self.world.mean_sound_speed_m_s(mx, my):.0f}",
classification=klass))
# --- Display (M8): Letterbox-Scaling + Vollbild ---
@@ -6391,6 +6392,8 @@ class Game:
self.hq_msg(message(
"runtime.hq.profile", sea_state=f"{weather['sea_state']:.1f}",
depth=f"{self.world.thermocline_depth_m(self.ship.x, self.ship.y):.0f}",
tide=f"{self.world.tide_m(self.ship.x, self.ship.y):+.1f}",
sst=f"{self.world.ocean.sea_surface_temperature_c(self.world.hour):.1f}",
wind_from=f"{weather['wind_from_deg']:.0f}",
wind_speed=f"{weather['wind_speed_kn']:.0f}",
rain=f"{weather['rain_intensity']:.0%}",
@@ -6596,6 +6599,7 @@ class Game:
"world": dict(hour=self.world.hour,
sea_state=self.world.sea_state,
weather_shift_timer=self.world.weather_shift_timer,
ocean=self.world.ocean.serialize(),
mode=self.world_mode,
generator=("natural-earth-v1"
if self.world_mode in ("procedural", "real_fixed")
@@ -7022,6 +7026,7 @@ class Game:
self.world.hour = w["hour"]
self.world.sea_state = w["sea_state"]
self.world.weather_shift_timer = w["weather_shift_timer"]
self.world.ocean.restore(w["ocean"])
self.seed = seed
self.sonar = SonarSystem(
seed=seed, acoustic_profiles=self.runtime_catalog.acoustic_profiles)
@@ -8843,10 +8848,13 @@ class Game:
or not 0 <= world["sea_state"] <= 6
or not bounded(world["weather_shift_timer"], 0.0,
config.WEATHER_SHIFT_PERIOD_S)
or not OceanEnvironment.valid_state(world["ocean"])
or not Coastline.valid_snapshot(world["coast"])):
return False
validation_coast = Coastline.from_dict(world["coast"])
validation_world = World(seed=data["seed"], coast=validation_coast)
validation_world.hour = world["hour"]
validation_world.ocean.restore(world["ocean"])
validation_hull = HullSpec(**hull)
if grounding["latched"]:
saved_contact = GroundingContact(**contact)
@@ -8912,9 +8920,7 @@ class Game:
expected_depths = [maximum * index / 20 for index in range(21)]
if (any(abs(depth - expected) > 1e-9
for depth, expected in zip(depths, expected_depths))
or any(abs(speed - propagation.synthetic_sound_speed_m_s(
depth, thermocline)) > .150000001
for depth, speed in zip(depths, speeds))):
or any(not 1400.0 <= speed <= 1600.0 for speed in speeds)):
return False
contacts = sonar.get("contacts", {})
if not isinstance(contacts, dict):
+1
View File
@@ -38,6 +38,7 @@ SHIP_FIELDS = frozenset({
WORLD_FIELDS = frozenset({
"hour", "sea_state", "weather_shift_timer", "mode", "generator", "coast",
"ocean",
})
DAMAGE_FIELDS = frozenset({"repair_mult", "compartments", "teams"})
+16 -2
View File
@@ -33,6 +33,14 @@ def snr_db(passive_range_nm: float, dist_nm: float) -> float:
/ max(dist_nm, 1e-6))
def _echo_delay(world, distance_nm: float, frigate, target) -> float:
"""Two-way echo latency with the modelled sound speed on the path."""
if hasattr(world, "mean_sound_speed_m_s"):
return world.echo_delay_s(distance_nm, (frigate.x + target.x) * .5,
(frigate.y + target.y) * .5)
return world.echo_delay_s(distance_nm)
def _target_acoustic_signature(tgt):
"""Best-effort TargetSignature lookup across the different contact types."""
for attr in ("acoustic", "stype", "profile"):
@@ -580,8 +588,13 @@ class SonarSystem:
max_depth = min(water_depth, 400.0)
depths = np.linspace(0.0, max_depth, 21)
speeds = []
true_speed = getattr(world, "sound_speed_m_s", None)
for depth in depths:
speed = propagation.synthetic_sound_speed_m_s(depth, measured_thermo)
# The probe measures the real modelled temperature profile
# (Mackenzie sound speed) with a small sensor noise.
speed = (true_speed(float(depth), frigate.x, frigate.y)
if true_speed is not None else
propagation.synthetic_sound_speed_m_s(depth, measured_thermo))
speeds.append(speed + self.rng.uniform(-.15, .15))
self.bt_profile = dict(t=t, x=frigate.x, y=frigate.y,
thermocline_m=measured_thermo,
@@ -776,7 +789,8 @@ class SonarSystem:
"frigate": frigate,
"world": world,
"sent_at": t_real,
"ready_at": t_real + world.echo_delay_s(distance),
"ready_at": t_real + _echo_delay(world, distance,
frigate, target),
"range_factor": range_factor,
"mode": mode,
"snapshot": snapshot,
+307
View File
@@ -0,0 +1,307 @@
"""Time-varying ocean environment: tides, mixed layer, temperature/sound
speed, wind drift, seabed sediment and charted underwater hazards.
Everything here is a deterministic function of the world seed, the
bathymetry, the saved environment clock and one saved relaxation state (the
wind-mixing deepening of the surface layer). The values are a game model of
real ocean processes; they are not claims about any real sea area.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from src.core import detrand
# --- tides -----------------------------------------------------------------
M2_PERIOD_S = 12.4206012 * 3600.0
S2_PERIOD_S = 12.0 * 3600.0
S2_TO_M2_RATIO = 0.46
TIDE_M2_AMPLITUDE_RANGE_M = (0.4, 1.4)
# Green's law shoaling a ~ h^-1/4, relative to the deep reference, bounded.
TIDE_REFERENCE_DEPTH_M = 400.0
TIDE_SHOALING_LIMITS = (0.6, 2.2)
# Spatial phase gradient of the tidal wave across the sector (rad per NM).
TIDE_PHASE_GRADIENT_MAX = 0.004
# --- mixed layer -----------------------------------------------------------
MLD_DIURNAL_AMPLITUDE_M = 8.0 # shallowest in the afternoon
MLD_DIURNAL_PEAK_HOUR = 15.0
MLD_WIND_THRESHOLD_KN = 12.0
MLD_WIND_DEEPENING_M_PER_KN = 1.2
MLD_DEEPEN_TAU_S = 2.0 * 3600.0 # storms mix down quickly
MLD_RESTRATIFY_TAU_S = 12.0 * 3600.0
MLD_WIND_MIX_MAX_M = 60.0
INTERNAL_WAVES = 3
INTERNAL_WAVE_AMPLITUDE_M = 2.0 # per component
MLD_MIN_M = 10.0
MLD_MAX_M = 250.0
# --- temperature / sound speed -----------------------------------------------
SALINITY_PSU = 35.0
DEEP_TEMPERATURE_C = 4.0
THERMOCLINE_SCALE_M = 150.0
SST_MEAN_C = 13.0
SST_SEASONAL_AMPLITUDE_C = 5.0
SST_WARMEST_DAY = 225
SST_DIURNAL_AMPLITUDE_C = 0.5
# --- wind drift --------------------------------------------------------------
WIND_DRIFT_FACTOR = 0.03
WIND_DRIFT_DEFLECTION_DEG = 20.0 # to the right (northern hemisphere)
# --- seabed ------------------------------------------------------------------
SEABED_GRID = 12
# Hamilton-style geoacoustic classes: density ratio, sound-speed ratio,
# attenuation (dB/wavelength), Lambert backscatter coefficient mu (dB).
SEDIMENTS = {
"rock": (2.50, 2.50, 0.10, -17.0),
"gravel": (2.00, 1.35, 0.80, -22.0),
"sand": (1.95, 1.15, 0.85, -27.0),
"silt": (1.70, 1.05, 1.00, -32.0),
"mud": (1.45, 0.99, 0.20, -37.0),
}
SEDIMENT_ORDER = ("rock", "gravel", "sand", "silt", "mud")
# --- hazards -----------------------------------------------------------------
MAX_HAZARDS = 64
ROCK_RADIUS_NM = 0.08
ROCK_MIN_TOP_M = 15.0
@dataclass(frozen=True, slots=True)
class Hazard:
kind: str # "wreck" | "rock"
x_nm: float
y_nm: float
top_depth_m: float # depth of the highest point below the surface
length_m: float
def mackenzie_sound_speed(temperature_c: float, salinity_psu: float,
depth_m: float) -> float:
"""Mackenzie (1981) nine-term sound speed in sea water (m/s)."""
t, s, d = temperature_c, salinity_psu, depth_m
return (1448.96 + 4.591 * t - 5.304e-2 * t * t + 2.374e-4 * t ** 3
+ 1.340 * (s - 35.0) + 1.630e-2 * d + 1.675e-7 * d * d
- 1.025e-2 * t * (s - 35.0) - 7.139e-13 * t * d ** 3)
def rayleigh_bottom_loss_db(sediment: str, grazing_deg: float) -> float:
"""Plane-wave fluid-fluid reflection loss at a sediment interface (dB)."""
rho, nu, attenuation, _mu = SEDIMENTS[sediment]
theta = math.radians(max(0.01, min(90.0, grazing_deg)))
cos_t, sin_t = math.cos(theta), math.sin(theta)
# R = (m sin t - sqrt(n^2 - cos^2 t)) / (m sin t + sqrt(n^2 - cos^2 t))
# with m = rho2/rho1 and n = c1/c2; below the critical grazing angle
# (cos t > n) the reflection is total.
n = 1.0 / nu
radicand = n * n - cos_t * cos_t
if radicand <= 0.0:
loss = 0.0
else:
root = math.sqrt(radicand)
r = abs((rho * sin_t - root) / (rho * sin_t + root))
loss = -20.0 * math.log10(max(r, 1e-6))
# Sediment absorption adds a small grazing-dependent loss.
return loss + 0.35 * attenuation * math.sin(theta)
class OceanEnvironment:
"""Deterministic ocean model attached to one ``World``."""
def __init__(self, seed: int, size_nm: float, charted_depth):
self.seed = int(seed)
self.size_nm = float(size_nm)
self.clock_s = 0.0
self.wind_mix_m = 0.0
low, high = TIDE_M2_AMPLITUDE_RANGE_M
self.m2_amplitude_m = detrand.uniform(low, high, seed, "tide-m2-amp")
self.m2_phase = detrand.phase(seed, "tide-m2-phase")
self.s2_phase = detrand.phase(seed, "tide-s2-phase")
grad = TIDE_PHASE_GRADIENT_MAX
self.tide_kx = detrand.uniform(-grad, grad, seed, "tide-kx")
self.tide_ky = detrand.uniform(-grad, grad, seed, "tide-ky")
self.day_of_year = 1 + int(detrand.u01(seed, "season") * 365.0)
self._waves = []
for index in range(INTERNAL_WAVES):
period = detrand.uniform(1200.0, 3600.0, seed, "iw-period", index)
wavelength = detrand.uniform(2.0, 8.0, seed, "iw-length", index)
heading = detrand.phase(seed, "iw-heading", index)
k = 2.0 * math.pi / wavelength
self._waves.append((k * math.sin(heading), -k * math.cos(heading),
2.0 * math.pi / period,
detrand.phase(seed, "iw-phase", index)))
self._sediment = self._build_sediment(charted_depth)
self.hazards = self._build_hazards(charted_depth)
# Bucket rocks by 1-NM cell so depth queries stay O(1).
self._rock_cells: dict[tuple[int, int], list[Hazard]] = {}
for hazard in self.hazards:
if hazard.kind == "rock":
cell = (int(hazard.x_nm), int(hazard.y_nm))
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
self._rock_cells.setdefault(
(cell[0] + dx, cell[1] + dy), []).append(hazard)
# --- construction -------------------------------------------------------
def _build_sediment(self, charted_depth) -> list[list[str]]:
n = SEABED_GRID
step = self.size_nm / (n - 1)
grid = []
for row in range(n):
line = []
for col in range(n):
x, y = col * step, row * step
depth = max(1.0, charted_depth(x, y))
slope = 0.0
for dx, dy in ((step * .5, 0.0), (0.0, step * .5)):
a = charted_depth(min(self.size_nm, x + dx),
min(self.size_nm, y + dy))
b = charted_depth(max(0.0, x - dx), max(0.0, y - dy))
slope = max(slope, abs(a - b) / max(step, 1e-6))
# Steep and shallow ground is coarse; deep, flat basins
# collect fine sediment. A seeded jitter breaks up bands.
score = (math.log10(depth) * 1.2 - min(2.0, slope / 40.0)
+ detrand.uniform(-0.5, 0.5, self.seed, "sed", row, col))
index = int(max(0, min(len(SEDIMENT_ORDER) - 1, score - 1.0)))
line.append(SEDIMENT_ORDER[index])
grid.append(line)
return grid
def _build_hazards(self, charted_depth) -> tuple[Hazard, ...]:
hazards = []
attempts = 0
while len(hazards) < MAX_HAZARDS and attempts < MAX_HAZARDS * 4:
attempts += 1
x = detrand.uniform(0.02, 0.98, self.seed, "hz-x", attempts) * self.size_nm
y = detrand.uniform(0.02, 0.98, self.seed, "hz-y", attempts) * self.size_nm
depth = charted_depth(x, y)
if depth <= 5.0:
continue
is_rock = 30.0 < depth < 150.0 and detrand.u01(
self.seed, "hz-kind", attempts) < 0.35
if is_rock:
# Submerged pinnacles: a hazard to submarines and weapons,
# never shallower than surface-ship keel clearance.
top = depth * detrand.uniform(0.4, 0.9, self.seed, "hz-top",
attempts)
hazards.append(Hazard("rock", x, y, max(ROCK_MIN_TOP_M, top),
60.0))
else:
length = detrand.uniform(40.0, 180.0, self.seed, "hz-len", attempts)
hazards.append(Hazard("wreck", x, y, max(1.0, depth - 12.0),
length))
return tuple(hazards)
# --- tides ----------------------------------------------------------------
def tide_m(self, x_nm: float, y_nm: float, charted_depth_m: float) -> float:
spatial = self.tide_kx * x_nm + self.tide_ky * y_nm
t = self.clock_s
base = (self.m2_amplitude_m * math.cos(
2.0 * math.pi * t / M2_PERIOD_S + self.m2_phase + spatial)
+ S2_TO_M2_RATIO * self.m2_amplitude_m * math.cos(
2.0 * math.pi * t / S2_PERIOD_S + self.s2_phase + spatial))
depth = max(1.0, charted_depth_m)
low, high = TIDE_SHOALING_LIMITS
shoal = min(high, max(low, (TIDE_REFERENCE_DEPTH_M / depth) ** 0.25))
return base * shoal
# --- mixed layer ------------------------------------------------------------
def wind_mix_target_m(self, wind_kn: float) -> float:
return min(MLD_WIND_MIX_MAX_M, max(
0.0, (wind_kn - MLD_WIND_THRESHOLD_KN) * MLD_WIND_DEEPENING_M_PER_KN))
def update(self, dt: float, wind_kn: float) -> None:
if dt <= 0.0:
return
self.clock_s += dt
target = self.wind_mix_target_m(wind_kn)
tau = (MLD_DEEPEN_TAU_S if target > self.wind_mix_m
else MLD_RESTRATIFY_TAU_S)
# Exact first-order relaxation, independent of step size.
self.wind_mix_m = target + (self.wind_mix_m - target) * math.exp(-dt / tau)
def mixed_layer_depth_m(self, base_m: float, hour: float,
x_nm: float, y_nm: float) -> float:
diurnal = -MLD_DIURNAL_AMPLITUDE_M * math.cos(
2.0 * math.pi * (hour - MLD_DIURNAL_PEAK_HOUR) / 24.0)
waves = sum(INTERNAL_WAVE_AMPLITUDE_M * math.sin(
kx * x_nm + ky * y_nm - omega * self.clock_s + phase)
for kx, ky, omega, phase in self._waves)
return min(MLD_MAX_M, max(MLD_MIN_M,
base_m + diurnal + self.wind_mix_m + waves))
# --- temperature / sound speed ------------------------------------------------
def sea_surface_temperature_c(self, hour: float) -> float:
seasonal = SST_SEASONAL_AMPLITUDE_C * math.cos(
2.0 * math.pi * (self.day_of_year - SST_WARMEST_DAY) / 365.0)
diurnal = SST_DIURNAL_AMPLITUDE_C * math.cos(
2.0 * math.pi * (hour - MLD_DIURNAL_PEAK_HOUR) / 24.0)
return SST_MEAN_C + seasonal + diurnal
def temperature_c(self, depth_m: float, mld_m: float, sst_c: float) -> float:
if depth_m <= mld_m:
# Nearly isothermal surface layer.
return sst_c - 0.002 * depth_m
surface = sst_c - 0.002 * mld_m
return DEEP_TEMPERATURE_C + (surface - DEEP_TEMPERATURE_C) * math.exp(
-(depth_m - mld_m) / THERMOCLINE_SCALE_M)
def sound_speed_m_s(self, depth_m: float, mld_m: float, hour: float) -> float:
sst = self.sea_surface_temperature_c(hour)
return mackenzie_sound_speed(self.temperature_c(depth_m, mld_m, sst),
SALINITY_PSU, depth_m)
# --- wind drift -------------------------------------------------------------
@staticmethod
def wind_drift_kn(wind_from_deg: float, wind_kn: float) -> tuple[float, float]:
"""Surface drift (u east, v north) = 3 % of wind, 20 deg to the right."""
towards = math.radians((wind_from_deg + 180.0
+ WIND_DRIFT_DEFLECTION_DEG) % 360.0)
speed = WIND_DRIFT_FACTOR * max(0.0, wind_kn)
return speed * math.sin(towards), speed * math.cos(towards)
# --- seabed ----------------------------------------------------------------
def sediment_at(self, x_nm: float, y_nm: float) -> str:
n = SEABED_GRID
step = self.size_nm / (n - 1)
col = int(round(min(max(x_nm, 0.0), self.size_nm) / step))
row = int(round(min(max(y_nm, 0.0), self.size_nm) / step))
return self._sediment[min(n - 1, row)][min(n - 1, col)]
def rock_top_depth_m(self, x_nm: float, y_nm: float) -> float | None:
"""Shallowest charted rock top covering this point, if any."""
best = None
for hazard in self._rock_cells.get((int(x_nm), int(y_nm)), ()):
if math.hypot(hazard.x_nm - x_nm, hazard.y_nm - y_nm) <= ROCK_RADIUS_NM:
if best is None or hazard.top_depth_m < best:
best = hazard.top_depth_m
return best
# --- persistence -------------------------------------------------------------
def serialize(self) -> dict:
return {"clock_s": self.clock_s, "wind_mix_m": self.wind_mix_m}
@staticmethod
def valid_state(state) -> bool:
if not isinstance(state, dict) or set(state) != {"clock_s", "wind_mix_m"}:
return False
for key, high in (("clock_s", 1e12), ("wind_mix_m", MLD_WIND_MIX_MAX_M)):
value = state[key]
if (not isinstance(value, (int, float)) or isinstance(value, bool)
or not math.isfinite(value) or not 0.0 <= value <= high):
return False
return True
def restore(self, state: dict) -> None:
self.clock_s = float(state["clock_s"])
self.wind_mix_m = float(state["wind_mix_m"])
+59 -8
View File
@@ -6,6 +6,7 @@ import random
from src.core import config
from src.world.coastline import Coastline
from src.world.ocean import OceanEnvironment
from src.world.grounding import (DEFAULT_HULL_SPEC, grounding_contact,
hull_is_safe, swept_grounding)
@@ -50,6 +51,10 @@ class World:
for _ in range(grid_n)]
self._current_v = [[current_rng.uniform(-1.0, 1.0) for _ in range(grid_n)]
for _ in range(grid_n)]
# Physics upgrade: time-varying ocean (tides, mixed layer, sound
# speed, wind drift, seabed, hazards). Built from stateless seeded
# draws, so no existing RNG sequence moves.
self.ocean = OceanEnvironment(seed, self.size_nm, self.charted_depth_m)
@staticmethod
def _weather_endpoint(rng_state, sea_state: int) -> dict:
@@ -172,15 +177,35 @@ class World:
d = field[y1][x1]
return (a * (1 - tx) + b * tx) * (1 - ty) + (c * (1 - tx) + d * tx) * ty
def depth_m(self, x_nm: float, y_nm: float) -> float:
def charted_depth_m(self, x_nm: float, y_nm: float) -> float:
"""Chart datum depth: bathymetry without tide or hazards."""
if self.coast.has_bathymetry:
return self.coast.depth_m(x_nm, y_nm)
return self._cell(x_nm, y_nm, self._depth)
def _actual(self, charted: float, x_nm: float, y_nm: float) -> float:
if charted <= 0.0:
return charted
depth = charted + self.ocean.tide_m(x_nm, y_nm, charted)
rock = self.ocean.rock_top_depth_m(x_nm, y_nm)
if rock is not None:
depth = min(depth, rock)
return max(0.0, depth)
def tide_m(self, x_nm: float, y_nm: float) -> float:
"""Current tidal height above chart datum at this position."""
return self.ocean.tide_m(x_nm, y_nm, self.charted_depth_m(x_nm, y_nm))
def depth_m(self, x_nm: float, y_nm: float) -> float:
"""Actual water depth now: chart datum + tide, shoaled by rocks."""
return self._actual(self.charted_depth_m(x_nm, y_nm), x_nm, y_nm)
def physical_depth_m(self, x_nm: float, y_nm: float) -> float:
if self.coast.has_bathymetry:
return self.coast.physical_depth_m(x_nm, y_nm)
return self._cell(x_nm, y_nm, self._depth)
charted = self.coast.physical_depth_m(x_nm, y_nm)
else:
charted = self._cell(x_nm, y_nm, self._depth)
return self._actual(charted, x_nm, y_nm)
def grounding_contact(self, x_nm, y_nm, course_deg,
hull=DEFAULT_HULL_SPEC):
@@ -211,9 +236,20 @@ class World:
raise ValueError("no hull-safe start found")
def thermocline_depth_m(self, x_nm: float, y_nm: float) -> float:
measured = self._cell(x_nm, y_nm, self._thermo)
"""Mixed-layer depth now: seasonal base, diurnal heating, wind
mixing and internal waves; capped above the bottom."""
base = self._cell(x_nm, y_nm, self._thermo)
measured = self.ocean.mixed_layer_depth_m(base, self.hour, x_nm, y_nm)
return min(measured, max(10.0, self.depth_m(x_nm, y_nm) - 20.0))
def sound_speed_m_s(self, depth_m: float, x_nm: float, y_nm: float) -> float:
"""Mackenzie sound speed from the modelled temperature profile."""
return self.ocean.sound_speed_m_s(
depth_m, self.thermocline_depth_m(x_nm, y_nm), self.hour)
def seabed_at(self, x_nm: float, y_nm: float) -> str:
return self.ocean.sediment_at(x_nm, y_nm)
def current_vec(self, x_nm: float, y_nm: float) -> tuple[float, float]:
"""W2: Meeresstroemung in kn (u=Ost/+x, v=Nord/-y - Positionskonvention).
@@ -222,7 +258,9 @@ class World:
Thermokline)."""
u = self._cell(x_nm, y_nm, self._current_u) * config.CURRENT_MAX_KN
v = self._cell(x_nm, y_nm, self._current_v) * config.CURRENT_MAX_KN
return u, v
# Wind-driven surface drift (3 % of wind, deflected to the right).
du, dv = self.ocean.wind_drift_kn(self.wind_from_deg, self.wind_speed_kn)
return u + du, v + dv
# --- W3: Land / Küsten ---
@@ -251,9 +289,21 @@ class World:
# --- W2: Schallfeld ---
def echo_delay_s(self, dist_nm: float) -> float:
"""Echolatenz eines Pings: 2*R / Schallgeschwindigkeit (Salzwasser)."""
return (dist_nm * 1852.0 * 2.0) / config.SOUND_SPEED_M_S
def echo_delay_s(self, dist_nm: float, x_nm: float | None = None,
y_nm: float | None = None) -> float:
"""Echolatenz eines Pings: 2*R / Schallgeschwindigkeit (Salzwasser).
With a position, the modelled mean sound speed of the upper 200 m
at that point is used; without one, the nominal constant."""
speed = (config.SOUND_SPEED_M_S if x_nm is None or y_nm is None
else self.mean_sound_speed_m_s(x_nm, y_nm))
return (dist_nm * 1852.0 * 2.0) / speed
def mean_sound_speed_m_s(self, x_nm: float, y_nm: float) -> float:
depth = max(10.0, min(200.0, self.depth_m(x_nm, y_nm)))
samples = [self.sound_speed_m_s(depth * (i + 0.5) / 4.0, x_nm, y_nm)
for i in range(4)]
return sum(samples) / len(samples)
# --- Wetter / Tageszyklus ---
@@ -261,6 +311,7 @@ class World:
# Eine Simulationssekunde ist bei 1x eine reale Sekunde.
self.hour = (self.hour + dt * config.GAME_TIME_PER_SEC / 60.0) % 24.0
self.weather_shift_timer += dt
self.ocean.update(dt, self.wind_speed_kn)
while self.weather_shift_timer >= config.WEATHER_SHIFT_PERIOD_S:
self.weather_shift_timer -= config.WEATHER_SHIFT_PERIOD_S
d = self.rng.choice([-1, 0, 0, 1])
+3 -2
View File
@@ -105,7 +105,8 @@ def test_damage_zone_biases_expected_compartment():
def test_active_ping_echo_is_delayed_by_sound_travel_time():
world = World(seed=3)
frigate = Ship(250.0, 250.0, speed_kn=4.0)
sub = Sub(265.0, 250.0, 60.0, 180.0, "diesel_alt", random.Random(3))
# Shallow target: stays in the surface layer whatever the diurnal layer.
sub = Sub(265.0, 250.0, 30.0, 180.0, "diesel_alt", random.Random(3))
sonar = SonarSystem(seed=3)
sonar.queue_ping(frigate, [sub], world, 0.0)
assert sub.state == "EVADE"
@@ -185,7 +186,7 @@ def test_ship_fuel_survives_save_load():
def test_focused_sonar_track_exposes_signature_analysis():
world = World(seed=6)
frigate = Ship(250.0, 250.0, speed_kn=4.0)
sub = Sub(255.0, 250.0, 60.0, 180.0, "diesel_alt", random.Random(6))
sub = Sub(255.0, 250.0, 30.0, 180.0, "diesel_alt", random.Random(6))
sonar = SonarSystem(seed=6)
sonar.set_listen_bearing(90.0)
sonar.update(1.0, 1.0, frigate, [sub], world, focus_tgt=sub)
+147
View File
@@ -0,0 +1,147 @@
"""Phase 1: time-varying ocean environment (tides, mixed layer, sound speed,
wind drift, seabed, hazards) and its persistence."""
import copy
import json
import math
import pytest
from src.core.game import Game
from src.world import ocean as ocean_mod
from src.world.grounding import DEFAULT_HULL_SPEC
from src.world.world import World
def test_mackenzie_reference_values():
assert ocean_mod.mackenzie_sound_speed(10.0, 35.0, 0.0) == pytest.approx(
1489.8, abs=0.2)
assert ocean_mod.mackenzie_sound_speed(4.0, 35.0, 1000.0) == pytest.approx(
1483.0, abs=0.3)
def test_tide_is_semidiurnal_bounded_and_shoals_in_shallow_water():
world = World(seed=11)
ocean = world.ocean
heights = []
for step in range(0, 25 * 60):
ocean.clock_s = step * 60.0
heights.append(ocean.tide_m(100.0, 100.0, 400.0))
amplitude = ocean.m2_amplitude_m * (1 + ocean_mod.S2_TO_M2_RATIO)
assert max(heights) <= amplitude + 1e-9 and min(heights) >= -amplitude - 1e-9
assert max(heights) - min(heights) > 0.5 * ocean.m2_amplitude_m
# Two high waters per lunar day.
peaks = sum(1 for i in range(1, len(heights) - 1)
if heights[i - 1] < heights[i] >= heights[i + 1])
assert peaks in (2, 3)
ocean.clock_s = 3 * 3600.0
deep = abs(ocean.tide_m(100.0, 100.0, 2000.0))
shallow = abs(ocean.tide_m(100.0, 100.0, 20.0))
assert shallow > deep
def test_actual_depth_follows_tide_and_can_ground_a_ship():
world = World(seed=12)
ocean = world.ocean
ocean.m2_amplitude_m = 1.4
# Find a charted spot where the hull fits at high water only.
hull = DEFAULT_HULL_SPEC
spot = None
for x in range(2, 500, 1):
for y in range(2, 500, 1):
charted = world.coast.physical_depth_m(x, y)
if hull.minimum_depth_m - 0.4 < charted < hull.minimum_depth_m + 0.4:
spot = (float(x), float(y))
break
if spot:
break
assert spot is not None
safe_states = set()
for step in range(0, 13 * 60, 10):
ocean.clock_s = step * 60.0
depth = world.physical_depth_m(*spot)
assert depth == pytest.approx(
world.coast.physical_depth_m(*spot) + ocean.tide_m(
*spot, world.coast.physical_depth_m(*spot)), abs=1e-6)
safe_states.add(depth >= hull.minimum_depth_m)
assert safe_states == {True, False}
def test_mixed_layer_diurnal_mean_matches_base_and_wind_deepens():
world = World(seed=13)
ocean = world.ocean
base = world._cell(200.0, 200.0, world._thermo)
samples = []
for step in range(24 * 12):
ocean.clock_s = step * 300.0
samples.append(ocean.mixed_layer_depth_m(base, step / 12.0, 200.0, 200.0))
assert sum(samples) / len(samples) == pytest.approx(base, abs=2.0)
assert max(samples) - min(samples) >= ocean_mod.MLD_DIURNAL_AMPLITUDE_M
one = ocean_mod.OceanEnvironment(13, 500.0, lambda x, y: 500.0)
many = ocean_mod.OceanEnvironment(13, 500.0, lambda x, y: 500.0)
one.update(3600.0, 40.0)
for _ in range(3600):
many.update(1.0, 40.0)
assert one.wind_mix_m == pytest.approx(many.wind_mix_m, rel=1e-9)
assert one.wind_mix_m > 10.0
one.update(24 * 3600.0, 5.0)
assert one.wind_mix_m < 5.0
def test_sound_speed_profile_has_isothermal_layer_and_deep_minimum():
world = World(seed=14)
mld = world.thermocline_depth_m(250.0, 250.0)
near = world.sound_speed_m_s(mld * 0.5, 250.0, 250.0)
top = world.sound_speed_m_s(1.0, 250.0, 250.0)
below = world.sound_speed_m_s(mld + 150.0, 250.0, 250.0)
assert near >= top - 0.2 # pressure term: slight increase in layer
assert below < near # thermocline: speed drops below the layer
assert 1450.0 < world.mean_sound_speed_m_s(250.0, 250.0) < 1530.0
def test_wind_drift_is_three_percent_and_deflected_right():
u, v = ocean_mod.OceanEnvironment.wind_drift_kn(0.0, 20.0) # from north
assert math.hypot(u, v) == pytest.approx(0.6)
# Blowing towards south (180) deflected 20 degrees right -> 200 degrees.
assert math.degrees(math.atan2(u, v)) % 360.0 == pytest.approx(200.0)
def test_seabed_and_hazards_are_seeded_bounded_and_rocks_shoal():
first, second = World(seed=15), World(seed=15)
assert first.ocean._sediment == second.ocean._sediment
assert first.ocean.hazards == second.ocean.hazards
kinds = {cell for row in first.ocean._sediment for cell in row}
assert kinds <= set(ocean_mod.SEDIMENTS)
assert len(first.ocean.hazards) <= ocean_mod.MAX_HAZARDS
rocks = [h for h in first.ocean.hazards if h.kind == "rock"]
assert all(h.top_depth_m >= ocean_mod.ROCK_MIN_TOP_M for h in rocks)
for rock in rocks:
assert first.depth_m(rock.x_nm, rock.y_nm) <= rock.top_depth_m + 1e-9
assert World(seed=16).ocean.hazards != first.ocean.hazards
@pytest.mark.parametrize("sediment", sorted(ocean_mod.SEDIMENTS))
def test_rayleigh_bottom_loss_is_finite_and_rock_reflects_best(sediment):
loss = ocean_mod.rayleigh_bottom_loss_db(sediment, 20.0)
assert 0.0 <= loss < 40.0
assert ocean_mod.rayleigh_bottom_loss_db("rock", 20.0) <= loss + 1e-9
def test_ocean_state_round_trips_and_rejects_malformed():
game = Game(seed=1501, start_menu=False, audio_enabled=False)
for _ in range(200):
game.update(0.5)
state = json.loads(json.dumps(game.save_state()))
assert state["world"]["ocean"]["clock_s"] > 0.0
restored = Game(seed=1, start_menu=False, audio_enabled=False)
assert restored._load_save_data(copy.deepcopy(state))
assert restored.world.thermocline_depth_m(123.0, 321.0) == \
game.world.thermocline_depth_m(123.0, 321.0)
assert restored.world.depth_m(123.0, 321.0) == game.world.depth_m(123.0, 321.0)
for mutation in (lambda o: o.update(clock_s=-1.0),
lambda o: o.update(wind_mix_m=1e6),
lambda o: o.pop("clock_s"),
lambda o: o.update(extra=0)):
broken = copy.deepcopy(state)
mutation(broken["world"]["ocean"])
assert not restored._load_save_data(broken)
+4 -1
View File
@@ -139,7 +139,10 @@ def test_bathymetry_is_seeded_and_deepens_away_from_coast():
assert coast.depth_m(*land_point) == 0.0
world = World(seed=44)
assert world.depth_m(250.0, 250.0) == coast.depth_m(250.0, 250.0)
assert world.charted_depth_m(250.0, 250.0) == coast.depth_m(250.0, 250.0)
# Actual depth is chart datum plus the current tide.
assert world.depth_m(250.0, 250.0) == pytest.approx(
coast.depth_m(250.0, 250.0) + world.tide_m(250.0, 250.0))
def test_legacy_load_remains_fixed(tmp_path):