Phase 6: submarine and surface-ship physics

Add src/physics/submarine.py and apply it to hostile platforms:
- Ordered versus actual speed: the AI orders, the hull follows at its
  acceleration limit (saved speed_order); external speed overrides still
  set both.
- Hydroplane authority ~ v^2 (slow depth changes below ~4 kn).
- Emergency blow from a bounded HP-air store for a flooded boat; pressure
  hull fatigue beyond 0.9 x test depth and crush at 1.5 x test depth.
- Cavitation onset rising with depth; radiated source level ~40 log v
  (auxiliary-machinery floor), cavitation jump and launch/blow transients,
  used by every passive sonar path.
- Lurking boats hold station against the current.
- Surface ships: Nomoto-linear turning and speed loss in heavy seas by hull
  length; their radiated level follows speed.
Manual EN/DE and simulation-gaps updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
db9979andClaude Opus 5.5 committed 2026-09-23 16:29:56 +02:00
1 parent 7abc45f9f8
commit 8f7970059c
11 files changed
+434 -22

No files matched your search

+2
View File
@@ -73,6 +73,8 @@ Alle Werte sind die Standardwerte der aktuellen Spielversion. Eigene Schwierigke
U-Boote weichen nach einem gehörten Ping oder Torpedo 240 s aus, können einen Täuschkörper ausstoßen, lauern, schnorcheln (durch HFDF und ESM erfassbar) und pingen gelegentlich aus 15 sm oder weniger.
U-Boot-Physik: der Rumpf beschleunigt auf die befohlene Fahrt (kein Sofortsprint); Tiefenruder brauchen Fahrt (unter etwa 4 kn ändert sich die Tiefe nur langsam); das abgestrahlte Geräusch steigt je Verdopplung der Fahrt um etwa 12 dB und springt, wenn die Schraube kavitiert, wobei die Kavitationsfahrt mit der Tiefe steigt; ein Torpedoausstoß erzeugt 8 s lang ein Transientengeräusch; ein stark geflutetes Boot bläst einmal an und steigt schnell und laut auf; unter der Testtiefe ermüdet der Druckkörper, bei 1,5-facher Testtiefe wird er zerdrückt; ein lauerndes Boot hält seine Position gegen die Strömung. Überwasserschiffe verlieren bei schwerer See Höchstfahrt (kleine Schiffe mehr).
## Mission und Wertung {#ref-mission}
- Szenarien: 1 Patrouille, 2 Doppeljagd, 3 Nuklear-Abfang, 4 Zufall (eigene Schwierigkeit). Eigene Missionen starten aus dem Missionseditor (`F5` in dessen Browser).
+2
View File
@@ -73,6 +73,8 @@ All values are the defaults of the current game version. Custom difficulty and m
Submarines evade for 240 s after hearing a ping or a torpedo, may launch a decoy, lie in wait, snorkel (detectable by HFDF and ESM) and sometimes ping from 15 NM or less.
Submarine physics: the hull accelerates toward an ordered speed (no instant sprints); hydroplanes need speed (below about 4 kn depth changes are slow); radiated noise rises about 12 dB per doubling of speed and jumps when the screw cavitates, and the cavitation speed rises with depth; a torpedo launch makes an 8 s transient; a badly flooded boat blows ballast once and rises fast and loud; operating below test depth fatigues the hull, and 1.5 x test depth crushes it; a lurking boat holds its position against the current. Surface ships lose top speed in heavy seas (small ships more).
## Mission and scoring {#ref-mission}
- Scenarios: 1 Patrol, 2 Double hunt, 3 Nuclear intercept, 4 Random (custom difficulty). User missions start from the Mission Editor (`F5` in its browser).
+9 -9
View File
@@ -76,15 +76,15 @@ Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment.
| Gap | Current behaviour | Would need for realism |
|-----|-------------------|------------------------|
| ~~**No depth dynamics**~~ | **Partially fixed (2026-09).** `Sub._advance_depth()` now approaches `target_depth` with an acceleration-limited (inertial) rate instead of an instant full-rate clamp, for the EVADE/LAUER/PATROLLE states. `_update_surface_cycle`'s snorkel-cycle depth stepping deliberately stays linear (its analytic event-timing depends on it). Still open: no buoyancy/plane-angle model, no depth overshoot beyond the inertial ramp itself. | Buoyancy control; plane effectiveness at low speed |
| **No cavitation model on subs** | Cavitation tendency is a static acoustic parameter; no speed-dependent cavitation threshold | Propeller cavitation onset at critical RPM/speed; noise spike; loss of propulsive efficiency |
| **No pressure / hull limits** | `max_depth_m` is a hard clamp; no structural stress, no crush | Pressure-hull fatigue, emergency blows, maximum crush depth with margin |
| **Speed vs noise coupling is indirect** | Noise derived from `speed / max_speed` ratio + state modifier; no RPM or blade-rate physics | Shaft RPM → blade-pass frequency → cavitation onset; engine RPM for diesel; electrical motor hum |
| **No propeller-wake / bubble effects** | None | Propeller race affects local sonar performance and torpedo launch conditions |
| **Evasive manoeuvre is kinematic** | EVADE: turn at `2.5 × turn_rate`, speed up to `0.9 × max`; no dynamic limit | Real evasive depth change + hard turn; dynamic pressure on hull; possible cavitation from hard turn at speed |
| **LAUER is a speed brake, not a tactic** | Speed forced to 0.5–1 kn; no station-keeping, no drift | Station-keeping in current; drift modelling |
| ~~**No depth dynamics**~~ | **Closed (Phases W2 + 6).** Inertial depth changes; hydroplane authority ~ v^2 (ballast-only rate below ~4 kn); one emergency blow from a bounded HP-air store at 4 m/s. | — |
| ~~**No cavitation model on subs**~~ | **Closed (Phase 6).** Onset speed from the catalog (or tendency) rising with depth as sqrt(1 + z/10.3); cavitation adds 8 dB source level. | — |
| ~~**No pressure / hull limits**~~ | **Closed (Phase 6).** Fatigue accumulates beyond 0.9 x test depth (saved) and converts to damage; 1.5 x test depth crushes the hull. | — |
| ~~**Speed vs noise coupling is indirect**~~ | **Closed (Phase 6).** Source level ~40 log v relative to the patrol reference (subs 6 kn, ships their cruise speed), plus cavitation and launch/blow transients, in all passive sonar paths (own, dipping, buoys, NPC). | — |
| ~~**No propeller-wake / bubble effects**~~ | **Closed (Phases 2/6/8).** Own wake ring masks the hull array astern; submarine screw transients and cavitation raise source level; torpedo bubble trails in Phase 8. | — |
| ~~**Evasive manoeuvre is kinematic**~~ | **Closed (Phase 6).** Evasion speeds are reached at the hull's acceleration limit, deep dives are limited by plane authority, and a hard sprint cavitates and becomes loud. | — |
| ~~**LAUER is a speed brake, not a tactic**~~ | **Closed (Phase 6).** The lurking boat heads into the current at bare steerage way and holds station. | — |
| ~~**No current / drift**~~ | **Fixed (2026-09).** `World.current_vec(x, y)` provides a deterministic current field, already applied to ship/sub/surface ships (`world.py:217-224`), and now also to torpedoes (both classes) and the free-drift enemy decoy. | — |
| **Torpedo launch is instantaneous** | Torpedo appears at sub position with chosen course and depth; no tube-pressurisation, no water jet | Launch delay, initial depth offset, wire letout before free-running |
| ~~**Torpedo launch is instantaneous**~~ | **Closed (Phases W2 + 6).** Motor spool-up, launch depth, and a loud 8 s tube-discharge transient on the firing boat. | — |
| **No active sonar use by subs** | Subs only use passive detection (or legacy `snapshot_observation`) | Active ping capability with its own trade-offs (reveals position) |
| **No ESM/ESB use by subs** | ESM sensor exists in catalog but `legacy_observation_model` short-circuits it for most profiles | Full `PlatformSensorSuite` path for subs when `propulsor_type != "unknown"` |
| **No ASW coordination** | Each sub acts independently; no data-link between hostile subs | Friendly datalink (already exists in `PlatformSensorSuite` for "blue" side but not used for hostile subs) |
@@ -120,7 +120,7 @@ Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment.
| Gap | Current behaviour | Would need |
|-----|-------------------|------------|
| **No ship hydrodynamics** | Constant speed or linear approach; no drag, no trim | Same as frigate: speed-dependent resistance, turning at speed |
| ~~**No ship hydrodynamics**~~ | **Closed (Phase 6).** Speed lag from the catalog, Nomoto-linear turning, and added resistance in waves lowering attainable speed by hull length (small hulls lose more). | — |
| ~~**No radar horizon**~~ | **Fixed (2026-09).** Surface detection now uses `min(effective_range × aspect, radar_horizon_nm(RADAR_ANTENNA_HEIGHT_M, RADAR_SURFACE_TARGET_HEIGHT_M))` for both civilians and warships (`game.py`, `_update_air_picture`), the same formula already used for raiders. | — |
| **No countermeasures** | Warships do not deploy chaff/flare | ASM jamming, chaff, hard-kill CIWS on enemy ships |
| **No damage propagation** | Single scalar `damage`; one torpedo = 34 damage → 3 hits to sink | Compartment flooding, fire, loss of specific capabilities |
+19
View File
@@ -6720,6 +6720,11 @@ class Game:
torpedo_alerted=s.torpedo_alerted,
decoy_cd=s._decoy_cd,
active_ping_cd=s._active_ping_cd,
speed_order=s.speed_order,
blow_available=s.blow_available,
emergency_ascent=s.emergency_ascent,
transient_left=s.transient_left,
hull_fatigue=s.hull_fatigue,
turn_left=s.turn_left, turn_delta=s.turn_delta,
target_course=s.target_course,
target_depth=s.target_depth,
@@ -7333,6 +7338,12 @@ class Game:
s.torpedo_alerted = sd["torpedo_alerted"]
s._decoy_cd = sd["decoy_cd"]
s._active_ping_cd = sd["active_ping_cd"]
s.speed_order = sd["speed_order"]
s._last_actual_speed = s.speed
s.blow_available = sd["blow_available"]
s.emergency_ascent = sd["emergency_ascent"]
s.transient_left = sd["transient_left"]
s.hull_fatigue = sd["hull_fatigue"]
s.turn_left = sd["turn_left"]
s.turn_delta = sd["turn_delta"]
s.target_course = sd["target_course"]
@@ -8436,6 +8447,14 @@ class Game:
if not bounded(entry.get("active_ping_cd"), 0.0,
config.SUB_ACTIVE_PING_COOLDOWN_S):
return False
if (type(entry.get("blow_available")) is not bool
or type(entry.get("emergency_ascent")) is not bool
or (entry["emergency_ascent"]
and entry["blow_available"])
or not bounded(entry.get("transient_left"), 0.0, 60.0)
or not bounded(entry.get("hull_fatigue"), 0.0, 1.0)
or not bounded(entry.get("speed_order"), 0.0, 100.0)):
return False
endurance_profile = runtime_catalog.endurances.get(
f"endurance.{profile_key}")
endurance_state = entry.get("endurance")
+112 -2
View File
@@ -8,6 +8,7 @@ import math
import random
from src.core import config
from src.physics import submarine as sub_physics
from src.data import catalog
from src.data import fingerprint as fingerprint_mod
from src.sensors.platform import (
@@ -114,8 +115,16 @@ class Sub:
# W2: signed vertical rate (+ = descending), acceleration-limited so
# depth changes have inertia instead of snapping to the full rate.
self.depth_rate_mps = 0.0
# Physics state (saved): one emergency blow, blow in progress, loud
# transient timer (launch/blow) and pressure-hull fatigue (0..1).
self.blow_available = True
self.emergency_ascent = False
self.transient_left = 0.0
self.hull_fatigue = 0.0
self.speed = rng.uniform(self.stype.speed_min_kn,
min(self.stype.speed_kn, 8.0))
self.speed_order = self.speed
self._last_actual_speed = self.speed
self.state = "PATROLLE"
self.evac_left = 0.0
self.turn_left = rng.uniform(300.0, 900.0)
@@ -308,6 +317,9 @@ class Sub:
if self.weapon_battery is not None
else self.torpedoes_left - launched)
self.attack_left = self.attack_cooldown
# Tube discharge: a loud, short launch transient.
self.transient_left = max(self.transient_left,
sub_physics.LAUNCH_TRANSIENT_S)
def _maybe_active_ping(self, dt: float) -> bool:
"""W2: ein aggressives Boot mit frischem Kontakt riskiert selten einen
@@ -339,6 +351,42 @@ class Sub:
# --- Physik/KI ---
# --- physics: planes, hull stress, cavitation, source level ---------------
def _update_hull_stress(self, dt: float) -> None:
"""Pressure-hull fatigue below test depth; collapse beyond crush depth."""
test = self.stype.max_depth_m
if self.depth >= sub_physics.crush_depth_m(test):
self.damage = 100.0
self.hull_fatigue += sub_physics.fatigue_rate_per_s(self.depth, test) * dt
if self.hull_fatigue >= 1.0:
self.hull_fatigue -= 1.0
self.damage = min(100.0, self.damage + 20.0)
if self.damage >= 100.0 and self.state != "SINKING":
self.state = "SINKING"
self.sink_left = 20.0
def cavitation_onset_kn(self) -> float:
acoustic = self.stype.acoustic
onset = getattr(acoustic, "cavitation_speed_knots", None)
if onset is None:
tendency = getattr(acoustic, "cavitation_tendency", 0.5)
onset = self.stype.speed_kn * (1.0 - 0.5 * tendency)
return sub_physics.cavitation_speed_kn(onset, 0.0) if onset else 99.0
@property
def cavitating(self) -> bool:
return self.speed > sub_physics.cavitation_speed_kn(
self.cavitation_onset_kn(), self.depth)
def source_level_offset_db(self) -> float:
"""Radiated-level change from speed, cavitation and transients."""
level = sub_physics.source_speed_db(
self.speed, sub_physics.SUBMARINE_REFERENCE_SPEED_KN, self.cavitating)
if self.transient_left > 0.0:
level += sub_physics.LAUNCH_TRANSIENT_DB
return level
def _advance_depth(self, target_depth: float, max_rate: float, dt: float) -> None:
"""Acceleration-limited depth approach (closed-form, no overshoot).
@@ -355,6 +403,8 @@ class Sub:
_update_surface_cycle, which has its own independent, deliberately-
still-linear depth stepping (see there).
"""
# Hydroplane lift scales with dynamic pressure (v^2).
max_rate *= sub_physics.plane_authority(self.speed)
desired_rate = (max_rate if target_depth > self.depth
else -max_rate if target_depth < self.depth else 0.0)
accel = config.SUB_DEPTH_ACCEL_MPS2 * dt
@@ -370,10 +420,34 @@ class Sub:
self.depth_rate_mps = new_rate
def update(self, dt: float, observation, world) -> None:
"""dt in Simulationssekunden; bei 1x identisch zu Echtzeit."""
"""dt in Simulationssekunden; bei 1x identisch zu Echtzeit.
The AI below reads and writes ``self.speed`` as the *ordered* speed;
the hull follows it at its acceleration limit (surge) and everyone
outside the update sees the actual speed."""
self.pinged_this_tick = False
if self.sunk:
return
if self.speed != self._last_actual_speed:
# Set from outside (spawn, scenario, test): order and actual.
self.speed_order = self.speed
self._actual_speed = self.speed
self._surged = False
self.speed = self.speed_order
try:
self._update_inner(dt, observation, world)
finally:
if not self._surged:
self.speed_order = config.clamp(
self.speed, 0.0, self.motion.maximum_speed_kn)
self.speed = self._actual_speed
if self.state in ("SINKING", "SUNK"):
self.speed = self.speed_order = 0.0
self._last_actual_speed = self.speed
def _update_inner(self, dt: float, observation, world) -> None:
start_speed = self._actual_speed
self.transient_left = max(0.0, self.transient_left - dt)
depth_at = getattr(world, "depth_m", lambda x, y: 1000.0)
bottom = depth_at(self.x, self.y)
safe_depth = min(self.stype.max_depth_m, max(0.0, bottom - 25.0))
@@ -423,6 +497,16 @@ class Sub:
return
self.speed = config.clamp(self.speed, 0.0, self.motion.maximum_speed_kn)
self._update_hull_stress(dt)
if self.state == "SINKING":
return
if (self.blow_available and not self.emergency_ascent
and self.damage >= sub_physics.EMERGENCY_BLOW_DAMAGE
and self.depth > 30.0):
# Flooding: blow main ballast with the high-pressure air store.
self.blow_available = False
self.emergency_ascent = True
self.transient_left = max(self.transient_left, 20.0)
# Retain only a bounded local acoustic observation, never a live ship
# reference. Ping memory does not continuously refresh hidden motion.
@@ -514,7 +598,18 @@ class Sub:
self.evac_left -= dt
self.target_depth = min(thermo + 15.0, safe_depth)
self._advance_depth(self.target_depth, self.motion.depth_rate_m_s, dt)
self.speed = max(1.0, self.speed - .08 * dt)
# Station keeping: stem the current at bare steerage way instead
# of a fixed crawl, so the boat hovers over its ambush point.
current = getattr(world, "current_vec", None)
cu, cv = current(self.x, self.y) if current is not None else (0.0, 0.0)
drift = math.hypot(cu, cv)
if drift > 0.05:
self.target_course = math.degrees(math.atan2(-cu, cv)) % 360.0
diff = config.angle_diff_deg(self.target_course, self.course)
self.course = (self.course + config.clamp(
diff, -self.motion.turn_rate_deg_s * dt,
self.motion.turn_rate_deg_s * dt)) % 360.0
self.speed = min(2.0, drift)
if self.evac_left <= 0:
self.state = "PATROLLE"
self.speed = min(6.0, self.speed_for_state())
@@ -543,6 +638,21 @@ class Sub:
if self.stype.profile.requires_air and self.depth > 55.0:
self.rng.random()
if self.emergency_ascent:
self.depth = max(10.0, old_depth - sub_physics.EMERGENCY_BLOW_RATE_MPS * dt)
self.target_depth = self.depth
self.depth_rate_mps = -sub_physics.EMERGENCY_BLOW_RATE_MPS
if self.depth <= 10.0 + 1e-9:
self.emergency_ascent = False
self.depth_rate_mps = 0.0
# Surge: the ordered speed is reached at the hull's acceleration
# limit (propeller thrust against drag and mass), faster when slowing.
ordered = config.clamp(self.speed, 0.0, self.motion.maximum_speed_kn)
accel = self.motion.acceleration_kn_s * dt
self.speed = start_speed + config.clamp(ordered - start_speed,
-2.0 * accel, accel)
self.speed_order = ordered
self._surged = True
motion_dt = dt
if self.endurance is not None:
motion_dt = self.endurance.time_until_surface_operation(
+26 -5
View File
@@ -8,6 +8,7 @@ import math
import random
from src.core import config
from src.physics import submarine as sub_physics
from src.data import catalog
from src.data import fingerprint as fingerprint_mod
from src.sensors.platform import (
@@ -117,6 +118,19 @@ class SurfaceShip:
"""Propulsion damage caps top speed, mirroring Sub's degradation."""
return self.motion.maximum_speed_kn * (1.0 - 0.25 * self.damage / 100.0)
@property
def hull_length_m(self) -> float:
catalog = self.runtime_catalog
systems = catalog.profile_systems.get(self.signature_key)
reference = (catalog.references.get(systems.reference_key)
if systems is not None and systems.reference_key else None)
return float(reference.length_m) if reference and reference.length_m else 120.0
def source_level_offset_db(self) -> float:
"""Radiated level versus the catalog cruise speed (40 log v)."""
return sub_physics.source_speed_db(
self.speed, max(self.motion.cruise_speed_kn, 1.0))
@property
def radar_emitting(self) -> bool:
return not self.sunk and self.emitter
@@ -278,18 +292,25 @@ class SurfaceShip:
if offset:
self.target_course = course
break
# W2: Ruderwirkung skaliert mit Staudruck (~v^2), wie beim Spielerschiff.
speed_factor = config.clamp((self.speed / 10.0) ** 2, 0.0, 1.5)
# Nomoto steering as on the own ship: steady turn rate grows linearly
# with speed (constant turning circle), no turning without way on.
speed_factor = config.clamp(self.speed / 10.0, 0.0, 1.5)
diff = config.angle_diff_deg(self.target_course, self.course)
effective_rate = max_rate * speed_factor
self.course = (self.course + config.clamp(
diff, -effective_rate * dt, effective_rate * dt)) % 360.0
# W2: Schub/Widerstand-Gleichgewicht als Exponential-Verzug (geschlossene
# Form -> dt-unabhaengig, siehe Ship.update()).
if abs(self.target_speed - self.speed) <= 0.05:
self.speed = self.target_speed
# Added resistance in waves lowers the attainable speed.
sea_state = float(getattr(world, "effective_sea_state",
getattr(world, "sea_state", 0.0))) if world else 0.0
cap = self.speed_cap_kn * sub_physics.wave_speed_fraction(
sea_state, self.hull_length_m, self.hull_length_m / 8.0)
target = min(self.target_speed, cap)
if abs(target - self.speed) <= 0.05:
self.speed = target
else:
self.speed = self.target_speed + (self.speed - self.target_speed) \
self.speed = target + (self.speed - target) \
* math.exp(-dt / self.speed_tau_s)
self.speed = config.clamp(self.speed, 0.0, self.speed_cap_kn)
+86
View File
@@ -0,0 +1,86 @@
"""Submarine and hostile-hull physics helpers (pure functions).
* Hydroplanes produce lift proportional to dynamic pressure, so the
achievable depth-change rate falls with speed squared; below a few knots the
boat relies on slow trim/ballast changes.
* Propeller cavitation onset rises with the static pressure at the screw:
v_c(z) = v_c0 * sqrt(1 + z / 10.3 m).
* Radiated source level grows with speed (machinery/flow noise ~40 log v
below cavitation) and jumps when the screw cavitates.
* Operating below test depth accumulates pressure-hull fatigue; the crush
depth has a safety factor of 1.5.
* A bounded high-pressure-air store allows one emergency blow.
* Surface ships lose speed in waves (added resistance ~ Hs^2 B^2 / L,
relative to their own resistance at top speed).
"""
from __future__ import annotations
import math
PLANE_REFERENCE_KN = 4.0
PLANE_MIN_AUTHORITY = 0.25
CAVITATION_PRESSURE_HEAD_M = 10.3
SPEED_SOURCE_LAW_DB = 40.0
# Lower bound: auxiliary machinery (pumps, generators) keeps radiating when
# the boat hovers; the speed law only governs above that floor.
SOURCE_SPEED_DB_LIMITS = (-6.0, 18.0)
CAVITATION_JUMP_DB = 8.0
SUBMARINE_REFERENCE_SPEED_KN = 6.0
TEST_DEPTH_FATIGUE_START = 0.9
FATIGUE_PER_S_AT_TEST = 1.0 / 1800.0 # 30 min at 10 % beyond test depth
CRUSH_SAFETY_FACTOR = 1.5
EMERGENCY_BLOW_RATE_MPS = 4.0
EMERGENCY_BLOW_DAMAGE = 60.0 # damage level that triggers a blow
LAUNCH_TRANSIENT_S = 8.0
LAUNCH_TRANSIENT_DB = 12.0
def plane_authority(speed_kn: float) -> float:
"""Fraction of the design depth rate the hydroplanes can produce."""
return min(1.0, max(PLANE_MIN_AUTHORITY,
(max(speed_kn, 0.0) / PLANE_REFERENCE_KN) ** 2))
def cavitation_speed_kn(surface_onset_kn: float, depth_m: float) -> float:
return surface_onset_kn * math.sqrt(1.0 + max(depth_m, 0.0)
/ CAVITATION_PRESSURE_HEAD_M)
def source_speed_db(speed_kn: float, reference_kn: float,
cavitating: bool = False) -> float:
"""Source-level change relative to the reference operating speed."""
low, high = SOURCE_SPEED_DB_LIMITS
level = SPEED_SOURCE_LAW_DB * math.log10(
max(speed_kn, 1.0) / max(reference_kn, 1.0))
level = min(high, max(low, level))
return level + (CAVITATION_JUMP_DB if cavitating else 0.0)
def crush_depth_m(test_depth_m: float) -> float:
return test_depth_m * CRUSH_SAFETY_FACTOR
def fatigue_rate_per_s(depth_m: float, test_depth_m: float) -> float:
ratio = depth_m / max(test_depth_m, 1.0)
if ratio <= TEST_DEPTH_FATIGUE_START:
return 0.0
return FATIGUE_PER_S_AT_TEST * (ratio - TEST_DEPTH_FATIGUE_START) / 0.2
def wave_speed_fraction(sea_state: float, length_m: float, beam_m: float) -> float:
"""Top-speed fraction retained in waves (sustained-power equilibrium).
Added resistance scales with Hs^2 B^2 / L; relative to a hull's own
resistance at top speed (~ L^2 for similar forms) smaller ships lose
proportionally more."""
from src.physics.ship_dynamics import SEA_STATE_HS_M
index = max(0.0, min(6.0, sea_state))
low = int(index)
high = min(6, low + 1)
hs = SEA_STATE_HS_M[low] + (SEA_STATE_HS_M[high] - SEA_STATE_HS_M[low]) * (index - low)
length = max(length_m, 20.0)
beam = max(beam_m, length / 9.0)
relative = 0.015 * hs * hs * (beam / 14.0) ** 2 * (118.0 / length) ** 3
return 1.0 / math.sqrt(1.0 + relative)
+3 -1
View File
@@ -298,7 +298,9 @@ class PlatformSensorSuite:
candidate.y, target_depth, frequency)
terms = equation.passive_terms(
frequency_hz=frequency, distance_nm=distance,
target_bonus=1.0 + 0.8 * config.clamp(source_noise, 0.0, 1.0),
target_bonus=(1.0 + 0.8 * config.clamp(source_noise, 0.0, 1.0))
* (10.0 ** (candidate.source_level_offset_db() / 20.0)
if hasattr(candidate, "source_level_offset_db") else 1.0),
excess_path_loss_db=(ray if ray is not None else
result.best_path.loss_db
- 20.0 * math.log10(1.0 + distance)),
+11 -3
View File
@@ -93,6 +93,12 @@ DOPPLER_SIGMA_HZ = 0.02
DOPPLER_MIN_QUALITY = 0.3
def source_level_factor(tgt) -> float:
"""Amplitude factor of a target's speed/cavitation/transient source level."""
offset = getattr(tgt, "source_level_offset_db", None)
return 10.0 ** (offset() / 20.0) if offset is not None else 1.0
def doppler_factor(tgt, observer) -> float:
"""Received/emitted frequency ratio from the closing speed (knots)."""
dx, dy = observer.x - tgt.x, observer.y - tgt.y
@@ -953,7 +959,7 @@ class SonarSystem:
# (target bonus 1, reference sea state) becomes a self-noise level.
own_factor = frigate.passive_sonar_range_nm(
1.0, int(equation.REFERENCE_SEA_STATE)) / config.SONAR_PASSIVE_BASE_NM
target_bonus = 1.0 + 0.8 * (1.0 - tgt.quiet_factor())
target_bonus = (1.0 + 0.8 * (1.0 - tgt.quiet_factor())) * source_level_factor(tgt)
thermo = world.thermocline_depth_m(tgt.x, tgt.y)
sensor_depth = self.towed_depth_m if mode == "TOWED" else 5.0
same_layer = (sensor_depth < thermo) == (tgt.depth < thermo)
@@ -1038,7 +1044,8 @@ class SonarSystem:
continue
dx, dy = tgt.x - helicopter.x, tgt.y - helicopter.y
distance = math.hypot(dx, dy)
target_bonus = 1.0 + 0.8 * (1.0 - tgt.quiet_factor())
target_bonus = ((1.0 + 0.8 * (1.0 - tgt.quiet_factor()))
* source_level_factor(tgt))
sea_state = float(getattr(world, "effective_sea_state", world.sea_state))
midpoint_x = (helicopter.x + tgt.x) * .5
midpoint_y = (helicopter.y + tgt.y) * .5
@@ -1339,7 +1346,8 @@ class SonarSystem:
else 0.0)
terms = equation.passive_terms(
frequency_hz=frequency, distance_nm=dist,
target_bonus=1.0 + 0.8 * (1.0 - tgt.quiet_factor()),
target_bonus=(1.0 + 0.8 * (1.0 - tgt.quiet_factor()))
* source_level_factor(tgt),
excess_path_loss_db=ray,
absorption_db_per_km=equation.francois_garrison_db_per_km(
frequency, _surface_temperature(world)),
+7 -2
View File
@@ -328,7 +328,9 @@ def test_patrol_speed_resumes_when_descent_completes():
sub.update(.05, None, Ocean())
assert sub.endurance.phase == "SUBMERGED"
assert sub.speed == pytest.approx(min(6.0, sub.speed_for_state()))
# The patrol speed is ordered at once; the hull then accelerates to it.
assert sub.speed_order == pytest.approx(min(6.0, sub.speed_for_state()))
assert 0.0 <= sub.speed <= sub.speed_order
@pytest.mark.parametrize("state", ["PATROLLE", "EVADE", "LAUER"])
@@ -363,7 +365,10 @@ def test_subsecond_reserve_transition_has_stable_motion_and_stores(parts):
sub = Sub(100, 100, 60, 90, "diesel_alt", random.Random(1606))
sub.state = "EVADE"
sub.evac_left = 1000
sub.speed = 6
# Start at the evasion speed so the hull does not accelerate: this
# test is about reserve transitions at a steady speed.
sub.speed = max(6.0, min(sub.speed_for_state(),
max(10.0, sub.stype.speed_kn * .9)))
load_rate = sub.endurance.load_kw(
sub.speed, sub.motion.maximum_speed_kn) / 3600
reserve = (sub.endurance.profile.battery_capacity_kwh
+157
View File
@@ -0,0 +1,157 @@
"""Phase 6: submarine and surface-ship physics."""
import copy
import json
import math
import random
from types import SimpleNamespace
import pytest
from src.core.game import Game
from src.enemies.sub import Sub
from src.enemies.surface import SurfaceShip
from src.physics import submarine as sub_physics
class Ocean:
size_nm = 500.0
sea_state = 1
effective_sea_state = 1.0
def __init__(self, current=(0.0, 0.0)):
self._current = current
def depth_m(self, *args):
return 3000.0
def thermocline_depth_m(self, *args):
return 60.0
def on_land(self, *args):
return False
def land_blocks_line(self, *args):
return False
def sonar_path_blocked(self, *args):
return False
def current_vec(self, *args):
return self._current
def _sub(seed=1, depth=100.0):
sub = Sub(100.0, 100.0, depth, 90.0, "aip_modern", random.Random(seed))
sub.endurance = None
return sub
def test_planes_lose_authority_at_low_speed():
assert sub_physics.plane_authority(1.0) == sub_physics.PLANE_MIN_AUTHORITY
assert sub_physics.plane_authority(8.0) == 1.0
slow, fast = _sub(), _sub()
for sub, speed in ((slow, 1.0), (fast, 8.0)):
sub.speed = speed
sub.target_depth = 200.0
sub.state = "PATROLLE"
sub.turn_left = 1e6
for _ in range(100):
sub._advance_depth(200.0, sub.motion.depth_rate_m_s, 0.2)
assert fast.depth - 100.0 > 2.0 * (slow.depth - 100.0)
def test_hull_accelerates_toward_the_ordered_speed():
sub = _sub()
sub.speed = 0.0
sub.state = "EVADE"
sub.evac_left = 1000.0
sub.update(1.0, None, Ocean())
assert sub.speed_order > 5.0
assert sub.speed == pytest.approx(sub.motion.acceleration_kn_s * 1.0)
def test_cavitation_onset_rises_with_depth_and_speed_raises_source_level():
shallow, deep = _sub(depth=20.0), _sub(depth=250.0)
speed = sub_physics.cavitation_speed_kn(shallow.cavitation_onset_kn(), 20.0) + 0.5
shallow.speed = deep.speed = speed
assert shallow.cavitating and not deep.cavitating
slow = _sub()
slow.speed = 4.0
fast = _sub()
fast.speed = 12.0
assert fast.source_level_offset_db() - slow.source_level_offset_db() > 15.0
slow.transient_left = 5.0
assert slow.source_level_offset_db() > sub_physics.LAUNCH_TRANSIENT_DB - 8.0
def test_emergency_blow_brings_a_flooded_boat_up_once():
sub = _sub(depth=150.0)
sub.damage = 70.0
sub.state = "EVADE"
sub.evac_left = 1000.0
sub.update(1.0, None, Ocean())
assert sub.emergency_ascent and not sub.blow_available
shallowest = sub.depth
for _ in range(60):
sub.update(1.0, None, Ocean())
shallowest = min(shallowest, sub.depth)
assert shallowest == pytest.approx(10.0)
assert not sub.emergency_ascent and not sub.blow_available
def test_pressure_hull_fatigue_and_crush_depth():
sub = _sub(depth=100.0)
sub.depth = sub.stype.max_depth_m * 1.05
sub._update_hull_stress(600.0)
assert sub.hull_fatigue > 0.0
sub.depth = sub_physics.crush_depth_m(sub.stype.max_depth_m) + 1.0
sub._update_hull_stress(0.1)
assert sub.state == "SINKING"
def test_lurking_boat_holds_station_against_the_current():
world = Ocean(current=(1.0, 0.0))
sub = _sub()
sub.state = "LAUER"
sub.evac_left = 1e6
sub.speed = 0.5
start = (sub.x, sub.y)
for _ in range(1800):
sub.update(1.0, None, world)
drifted = math.hypot(sub.x - start[0], sub.y - start[1])
assert drifted < 0.2 # pure drift would be 0.5 NM
def test_surface_ship_loses_speed_in_heavy_seas():
calm_world, rough_world = Ocean(), Ocean()
rough_world.effective_sea_state = 6.0
speeds = []
for world in (calm_world, rough_world):
ship = SurfaceShip(100.0, 100.0, random.Random(3))
ship.target_speed = ship.speed_cap_kn
for _ in range(600):
ship._steer(1.0, 0.5, world)
speeds.append(ship.speed)
assert speeds[1] < 0.95 * speeds[0]
def test_physics_state_round_trips_and_is_validated():
game = Game(seed=6601, start_menu=False, audio_enabled=False)
sub = game.subs[0]
sub.blow_available = False
sub.emergency_ascent = True
sub.transient_left = 4.0
sub.hull_fatigue = 0.3
sub.speed_order = 7.5
state = json.loads(json.dumps(game.save_state()))
restored = Game(seed=1, start_menu=False, audio_enabled=False)
assert restored._load_save_data(copy.deepcopy(state))
twin = next(s for s in restored.subs if s.id == sub.id)
assert (twin.blow_available, twin.emergency_ascent, twin.transient_left,
twin.hull_fatigue, twin.speed_order) == (False, True, 4.0, 0.3, 7.5)
for field, value in (("hull_fatigue", 2.0), ("blow_available", 1),
("transient_left", -1.0)):
broken = copy.deepcopy(state)
broken["subs"][0][field] = value
assert not restored._load_save_data(broken)