From 6998cf0d8f09e03375c6ac86800a28429ff5bf38 Mon Sep 17 00:00:00 2001 From: db9979 Date: Sun, 27 Sep 2026 01:16:43 +0200 Subject: [PATCH] Core split 4b: display, operator commands and pictures out of game.py DrawMixin (frame, chrome, overlays, run), OperatorMixin (station commands shared by keys and Remote Crew) and PicturesMixin (OPZ/ELOKA pictures, plot layer, weather and SimLog) leave game.py at 700 lines of composition root. Tests patch module-level names where they are now looked up; Game keeps the re-exports tests import. Co-Authored-By: Claude Fable 5.1 --- src/core/game.py | 4413 +-------------------------- src/core/game_draw.py | 1256 ++++++++ src/core/game_operator.py | 1716 +++++++++++ src/core/game_pictures.py | 1486 +++++++++ tests/test_eco_display.py | 2 +- tests/test_game_integration.py | 13 +- tests/test_live_traffic.py | 13 +- tests/test_save_catalog_snapshot.py | 7 +- tests/test_web_host.py | 3 +- 9 files changed, 4496 insertions(+), 4413 deletions(-) create mode 100644 src/core/game_draw.py create mode 100644 src/core/game_operator.py create mode 100644 src/core/game_pictures.py diff --git a/src/core/game.py b/src/core/game.py index 64630273..ce0ea322 100644 --- a/src/core/game.py +++ b/src/core/game.py @@ -1,15 +1,12 @@ """Haupt-Game-Loop: Widescreen-Grid, Echtzeit, Szenarien und Multi-Slot-Save.""" import copy -import hashlib import math import os import threading -import time import weakref from collections import deque from contextlib import contextmanager -from dataclasses import replace import pygame @@ -17,103 +14,50 @@ from src.audio.engine import AudioEngine from src.audio.receiver import AcousticReceiver from src.commander.local import CommanderConsole from src.core import config -from src.core import plot as plot_geometry from src.core.plot import PlotLayer from src.core.autocrew import AutocrewController -from src.core.commands import STATION_PAGES, station_page_step -from src.core.debuglog import append_bounded_log -from src.core.i18n import (Translator, display_value, localized, localize, - message, raw_text, translation_scope) -from src.core.preferences import Preferences, save_preferences +from src.core.i18n import Translator, message +from src.core.preferences import Preferences from src.network.connectivity import ConnectivityMonitor from src.network.live_traffic import LiveTrafficManager -from src.core.help import get_global_help, get_help, get_sop, get_uboot_help -from src.core import manual from src.core.mission import Mission from src.core.station import Station from src.core import opfor -from src.core import uboot_local from src.core.limits import (MAX_AIR_PICTURE_TRACKS, MAX_DECOYS, MAX_ENEMY_TORPEDOES, MAX_OPZ_TRACK_LABELS, MAX_SAVED_ASMS, MAX_SAVED_ENTITIES, MAX_SAVED_ESSMS, MAX_SAVED_PLAYER_TORPEDOES, MAX_TRACK_DISPLAY_ID_LEN) from src.sensors.ais import AISReceiver -from src.sensors import visual as visual_physics -from src.sensors import lookout_id -from src.world import atmosphere as atmosphere_physics -from src.world import ocean as ocean_physics -from src.sonar import raytrace as sonar_raytrace from src.sonar import analysis_tools -from src.sonar import tma_operator from src.data.catalog import CATALOG from src.enemies.animal import Animal from src.enemies.civilian import CivilianShip -from src.enemies.decoy import Decoy from src.enemies.sub import Sub from src.enemies.surface import SurfaceShip -from src.nations.nations import reference_summary from src.sensors.tracks import TrackPicture -from src.sensors.fusion import OPZFusionPicture, OPZObservation, source_classification -from src.sensors.esm import ( - ESM_MAX_ANNOTATIONS, - ESMCorrelationEvidence, - ECM_TECHNIQUES, - ECMJammer, - ESMPicture, - analyze_signal, - correlate_observations, - estimated_range_nm, - filter_and_sort_tracks, - library_emitters, - rank_emitters) +from src.sensors.fusion import OPZFusionPicture +from src.sensors.esm import ECMJammer, ESMPicture from src.ship.damage import DamageModel from src.ship.ship import Ship -from src.sonar.sonar import Contact, SonarSystem, TowState +from src.sonar.sonar import SonarSystem from src.sonar.station import SonarStation, install_station_properties -from src.ui import layout -from src.ui import observations from src.ui.editor_widgets import TextField from src.ui.feedback import EventFeed -from src.ui.map_view import draw_map_view -from src.ui.splash_view import draw_splash -from src.ui.sonar_view import draw_sonar_view -from src.ui.weather_station import draw_weather_station -from src.ui import uboot_view -from src.ui.stations_view import ( - draw_autocrew_overview, - draw_bridge_view, - draw_damage_view, - draw_eloka_view, - draw_engine_view, - draw_opz_view, - draw_radio_view, - draw_helicopter_view) -from src.ui.stations_view import opz_ppi_rect -from src.ui.mission_editor import MissionEditor -from src.ui.contact_analyzer import ContactAnalyzer from src.ui import simlog_map -from src.ui.simlog_view import draw_simlog_view from src.ui.viewport import Viewport -from src.ui.weapons_view import draw_weapons_overlay, draw_weapons_panel -from src.air.asm import ESSM -from src.air import chaff as chaff_physics from src.air.helicopter import Helicopter -from src.air import helicopter as helicopter_physics from src.air.flights import FlightManager from src.world.world import World from src.world.coastline import Coastline -from src.weapons.torpedo import Torpedo -from src.weapons.asw import ( - ConsumableStore, - MAX_TOWED_DECOYS, - TowedAcousticDecoy, - WeaponBattery, - ownship_loadout) +from src.weapons.asw import ConsumableStore, WeaponBattery, ownship_loadout from src.weapons.air_defense import air_defense_loadout, make_softkill_store # Shared display/help constants and helpers (re-exported for tests/tools). from src.core.game_shared import ( # noqa: F401 HELP_MANUAL_PAGE, HELP_PAGE_COUNT, SONAR_BAND_PRESETS, TMA_ACCEPT_MIN_FIT, letterbox_layout, make_night_overlay, make_scanlines) +# Entity classes tests import from ``src.core.game`` (kept as re-exports). +from src.enemies.decoy import Decoy # noqa: F401 +from src.weapons.torpedo import EnemyTorpedo # noqa: F401 # Names tests and tools import from ``src.core.game`` (kept as re-exports). from src.core.save_schema import SAVE_ROOT_FIELDS # noqa: F401 from src.core.game_save import ( @@ -132,9 +76,12 @@ from src.core.game_sim import ( TORPEDO_WAKE_VISIBLE_DEPTH_M) from src.core.game_events import (EventMixin, _ECO_REFRESH_EVENTS) from src.core.mission_bridge import (MissionBridgeMixin) +from src.core.game_draw import (DrawMixin) +from src.core.game_operator import (OperatorMixin) +from src.core.game_pictures import (PicturesMixin) -class Game(MissionBridgeMixin, EventMixin, SimMixin, SaveMixin): +class Game(PicturesMixin, OperatorMixin, DrawMixin, MissionBridgeMixin, EventMixin, SimMixin, SaveMixin): # Options overlay rows in display order; the last two open sub-menus. _OPTION_ROWS = ("language", "fullscreen", "audio", "large_text", "tooltips", "simlog", "night_mode", "high_contrast", "frame_rate", @@ -285,16 +232,6 @@ class Game(MissionBridgeMixin, EventMixin, SimMixin, SaveMixin): self.splash_started_at = self._t self._splash_ping_cycle = -1 - def _apply_text_size(self) -> None: - layout.configure_for(self) - self.font = layout.font(18) - self.font_big = layout.font(28, bold=True) - # Menus get a larger baseline than in-game HUD text: more free - # space per screen, and no risk to the already-tuned station views - # that also read `self.font`/`self.font_big`. - self.menu_font = layout.font(21) - self.menu_font_big = layout.font(34, bold=True) - @property def radar_range_nm(self) -> float: return self.opz_range_nm @@ -740,34 +677,6 @@ class Game(MissionBridgeMixin, EventMixin, SimMixin, SaveMixin): tuple(self.difficulty[name] for name in config.DIFFICULTY_FIELD_ORDER), self.hq_intel_mode(), id(self.world), id(self.sonar)) if self.in_menu else None - def flash_banner_rect(self) -> pygame.Rect: - """Opaque, text-sized banner in the free right part of the top bar. - - It starts right of the status line, so it never prints over a map, - station tabs or chart labels; only a message too long for one line - grows downward (at most two lines). - """ - face = layout.font(layout.scaled_size(self.FLASH_TEXT_SIZE)) - left = max(config.SCREEN_W // 2, - getattr(self, "_top_status_right", 0) + 16) - max_w = config.SCREEN_W - 6 - left - lines = layout.wrap_text(localize(self.msg), face, max_w - 20) - lines = lines[:self.FLASH_MAX_LINES] or [""] - width = min(max_w, max(face.size(line)[0] for line in lines) + 20) - height = max(config.TOP_BAR_H - 4, - len(lines) * layout._line_height(face) + 6) - return pygame.Rect(config.SCREEN_W - 6 - width, 2, width, height) - - def _draw_flash_banner(self, surface) -> None: - # The banner covers what lies beneath it instead of printing over - # the map and the station tabs. - box = self.flash_banner_rect() - pygame.draw.rect(surface, config.COLOR_OVERLAY_BG, box) - pygame.draw.rect(surface, config.COLOR_WARN, box, 1) - layout.blit_block(surface, localize(self.msg), box.x + 10, box.y + 3, - box.w - 20, box.h - 6, config.COLOR_WARN, - size=self.FLASH_TEXT_SIZE, align="center", valign="center") - def flash(self, text: object, seconds: float = 3.0) -> None: if (getattr(self, "local_side", "frigate") == "uboot" and not getattr(self, "_uboot_ui", False)): @@ -786,946 +695,6 @@ class Game(MissionBridgeMixin, EventMixin, SimMixin, SaveMixin): self.flash(text, seconds) self.feed.add(self.world.format_time(), category, text) - def hq_msg(self, text: object) -> None: - """M13/W3: Teletype-Nachricht – Funkraum-Verkehr + Ereignis-Feed.""" - stamp = self.world.format_time() - self.messages.append((stamp, text)) - if len(self.messages) > 40: - self.messages.pop(0) - self.feed.add(stamp, "funk", text) - - def _navigation_order_live(self) -> bool: - # The simulation never pauses: menus and overlays own local input only, - # so crew orders stay live behind them. - return (self.running and not self.game_over - and not self.in_menu and not self.main_menu - and not self.splash_active - and self.input_mode in (None, "course", "speed")) - - def _set_course_order(self, course: float, station: str) -> str: - """Apply a validated shared helm order for one local station owner.""" - if type(course) not in (int, float): - return "invalid_value" - try: - valid = math.isfinite(course) and 0.0 <= course < 360.0 - except OverflowError: - valid = False - if not valid: - return "invalid_value" - if not self._navigation_order_live(): - return "phase_blocked" - if self.damage.station_down(station): - return f"{station}_down" - self.ship.target_course = course - self.feed.add(self.world.format_time(), "navigation", - message("runtime.numeric.course_feed", course=f"{course:03.0f}")) - return "ok" - - def order_course(self, course: float) -> str: - """Apply a Bridge course order and return a stable result code.""" - return self._set_course_order(course, "bridge") - - def set_engine_course(self, course: float) -> str: - """Set the common course controller from the machinery station.""" - return self._set_course_order(course, "engine") - - def order_speed(self, speed_kn: float) -> str: - """Apply a validated ahead-speed order and return a stable result code.""" - if type(speed_kn) not in (int, float): - return "invalid_value" - try: - valid = (math.isfinite(speed_kn) - and 0.0 <= speed_kn <= config.SHIP_SPEED_MAX_KN) - except OverflowError: - valid = False - if not valid: - return "invalid_value" - if not self._navigation_order_live(): - return "phase_blocked" - if self.ship.fuel_kg <= 0.0: - return "no_fuel" - self.ship.target_speed = speed_kn - self.ship.astern = False - self.ship.order_idx = min(range(len(config.TELEGRAPH_ORDERS)), - key=lambda i: abs(config.TELEGRAPH_ORDERS[i][1] - - speed_kn)) - self.feed.add(self.world.format_time(), "navigation", - message("runtime.numeric.speed_feed", speed=f"{speed_kn:.1f}")) - return "ok" - - def set_engine_telegraph(self, order: str): - if type(order) is not str: - return "invalid_value" - if self.damage.station_down("engine"): - return "engine_down" - if self.ship.fuel_kg <= 0.0: - return "no_fuel" - if order == "ASTERN": - self.ship.astern = True - self.ship.order_idx = 0 - self.ship.target_speed = config.ASTERN_SPEED_KN - else: - index = next((i for i, item in enumerate(config.TELEGRAPH_ORDERS) - if item[0] == order), None) - if index is None: - return "invalid_value" - self.ship.astern = False - self.ship.order_idx = index - self.ship.target_speed = config.TELEGRAPH_ORDERS[index][1] - return True - - def _cycle_engine_telegraph(self, delta: int): - orders = ("ASTERN", *(item[0] for item in config.TELEGRAPH_ORDERS)) - index = orders.index(self.ship.telegraph) - return self.set_engine_telegraph( - orders[config.clamp(index + delta, 0, len(orders) - 1)]) - - def set_engine_speed(self, speed_kn: float): - if self.damage.station_down("engine"): - return "engine_down" - return self.order_speed(speed_kn) - - def set_quiet_mode(self, enabled: bool): - if type(enabled) is not bool: - return "invalid_value" - if self.damage.station_down("engine"): - return "engine_down" - self.ship.quiet_mode = enabled - return True - - def assign_damage_team(self, team: int, compartment: str): - if type(team) is not int or type(compartment) is not str: - return "invalid_value" - if team not in self.damage.teams or compartment not in self.damage.compartments: - return "invalid_value" - if self.damage.ship_sunk: - return "not_ready" - if not self.damage.assign_team(team, compartment): - return "not_ready" - return True - - def unassign_damage_team(self, team: int, compartment: str): - if (type(team) is not int or type(compartment) is not str - or team not in self.damage.teams - or compartment not in self.damage.compartments): - return "invalid_value" - if self.damage.teams[team] != compartment: - return "stale_ref" - self.damage.unassign_team(team) - return True - - def set_sonar_listen_bearing(self, bearing: float): - if (type(bearing) not in (int, float) or not 0 <= bearing < 360 - or not math.isfinite(bearing)): - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - # Retuning keeps the listening stream running: the receiver reset is a - # sequence gap that _update_audio joins without a silent re-buffer. - self.sonar.set_listen_bearing(bearing) - return True - - def set_sonar_focus(self, contact): - if self._sonar_down(): - return "sonar_down" - if (not isinstance(contact, Contact) - or self.sonar.contacts.get(contact.target_id) is not contact): - return "stale_ref" - if not 0 <= self.sim_t - contact.last_seen <= 2.0: - return "stale_ref" - self.selected_contact = contact - self.sonar.set_listen_bearing(contact.bearing) - self.sonar.focus_locked = True - self.sonar._listen_target_id = contact.target_id - return True - - def clear_sonar_focus(self): - if self._sonar_down(): - return "sonar_down" - self.sonar.focus_locked = False - self.sonar._listen_target_id = None - return True - - def set_sonar_array_mode(self, mode: str): - if mode not in ("BOW", "TOWED") or type(mode) is not str: - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - self.sonar_mode = mode - return True - - def set_sonar_tas(self, deployed: bool): - if type(deployed) is not bool: - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - state = self.sonar.tow_status(self.sonar_observer.speed)["state"] - if state == "FAULT": - return "tas_fault" - is_deploying = state in ("DEPLOYING", "STREAMED") - if deployed == is_deploying: - return True - return True if self.sonar.toggle_tow(self.sonar_observer.speed) else "tas_fault" - - def set_sonar_tow_depth(self, depth_m: float): - if (type(depth_m) not in (int, float) - or not config.SONAR_TOWED_DEPTH_MIN_M <= depth_m - <= config.SONAR_TOWED_DEPTH_MAX_M or not math.isfinite(depth_m)): - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - if self.sonar.tow_state != TowState.STREAMED: - return "not_ready" - limit = max(config.SONAR_TOWED_DEPTH_MIN_M, - config.SONAR_TOWED_DEPTH_MAX_M - - self.sonar_observer.speed * config.SONAR_TOWED_SPEED_SHALLOW_M_PER_KN) - if depth_m > limit: - return "not_ready" - self.sonar.towed_depth_target_m = depth_m - return True - - def measure_sonar_bt(self): - if self._sonar_down(): - return "sonar_down" - return (True if self.sonar.measure_environment( - self.world, self.sonar_observer, self.sim_t) else "not_ready") - - def send_active_ping(self): - if self._opfor is not None and self._sonar_ctx is self._opfor.station: - return opfor.send_ping(self, self._opfor) - if self._sonar_down(): - return "sonar_down" - if (self.sonar_mode == "TOWED" - and not self.sonar.tow_status(self.ship.speed)["available"]): - return "not_ready" - if not self.sonar.fire_ping(): - return "not_ready" - self._remember_ping_pulse() - self._emit_sound("sonar_ping") - self.sonar.queue_ping(self.ship, self._sonar_targets(), self.world, - self.sim_t, self._sonar_range_factor(), - mode=self.sonar_mode) - return True - - def set_helicopter_dipping(self, deployed: bool): - if type(deployed) is not bool: - return "invalid_value" - if self.damage.station_down("flightdeck"): - return "flightdeck_down" - if not self.helo.airborne: - return "not_ready" - if deployed and not self.helicopter_weather()["dipping_safe"]: - return "weather_unsafe" - if not self.helo.set_dipping(deployed, self.world): - return "water_required" if deployed else "not_ready" - return True - - def set_helicopter_dip_depth(self, depth_m: float): - if (type(depth_m) not in (int, float) or isinstance(depth_m, bool) - or not math.isfinite(depth_m) - or not config.HELO_DIP_DEPTH_MIN_M <= depth_m - <= config.HELO_DIP_DEPTH_MAX_M): - return "invalid_value" - if (not self.helo.airborne - or self.helo.dip_state not in ("DEPLOYING", "DEPLOYED")): - return "not_ready" - return (True if self.helo.set_dip_depth(depth_m, self.world) - else "water_required") - - def send_helicopter_dipping_ping(self): - if self.damage.station_down("sonar"): - return "sonar_down" - if not self.helo.fire_dipping_ping(): - return "not_ready" - self._remember_ping_pulse() - self._emit_sound("sonar_ping") - self.sonar.queue_ping(self.helo, self._sonar_targets(), self.world, - self.sim_t, self._sonar_range_factor(), - mode="DIPPING") - return True - - def set_sonar_tma_enabled(self, enabled: bool): - if type(enabled) is not bool: - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - self.sonar.tma_enabled = enabled - return True - - def set_sonar_gain(self, gain_db: float): - if (type(gain_db) not in (int, float) or not -12 <= gain_db <= 24 - or not math.isfinite(gain_db)): - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - self.sonar.gain_db = gain_db - return True - - def set_sonar_audition_mode(self, mode: str): - if type(mode) is not str or mode not in ("BROADBAND", "FILTERED", "HETERODYNE"): - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - self.sonar.set_audition_mode(mode) - return True - - def set_sonar_band_preset(self, preset: str): - band = SONAR_BAND_PRESETS.get(preset) if type(preset) is str else None - if band is None: - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - self.sonar.band_low_hz, self.sonar.band_high_hz = band - return True - - def set_sonar_notch(self, enabled: bool): - if type(enabled) is not bool: - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - self.sonar.notch_enabled = enabled - return True - - def set_sonar_peak_hold(self, enabled: bool): - if type(enabled) is not bool: - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - self.sonar.peak_hold = enabled - return True - - def sonar_harmonic_candidates(self): - return tuple(sorted({float(hz) for hz, _ in list( - getattr(self.sonar.receiver, "peaks", []))[:6] - if type(hz) in (int, float) and math.isfinite(hz) - and 0 < float(hz) <= config.LOFAR_FMAX_HZ})) - - def set_sonar_harmonic(self, frequency_hz): - if self._sonar_down(): - return "sonar_down" - if frequency_hz is None: - self.sonar_harmonic_hz = None - return True - if (type(frequency_hz) not in (int, float) - or not 0 < frequency_hz <= config.LOFAR_FMAX_HZ - or not math.isfinite(frequency_hz)): - return "invalid_value" - # Any operator-chosen fundamental (the cursor), not only detected peaks. - self.sonar_harmonic_hz = float(frequency_hz) - return True - - def designate_sonar_target(self, contact): - if self._sonar_down(): - return "sonar_down" - if (not isinstance(contact, Contact) - or self.sonar.contacts.get(contact.target_id) is not contact - or not 0 <= self.sim_t - contact.last_seen - < config.SONAR_CONTACT_LOST_S): - return "stale_ref" - self.target = contact - return True - - def _feed_ping(self, tgt, contact) -> None: - """W1/W2: Ping-Echo-Feed inkl. Echolatenz (W3: Salzwasser-Schallfeld).""" - dist = tgt.distance_nm(self.ship) - 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 "", - "unknown") if getattr(tgt, "stype", None) else \ - ("Decoy?" if getattr(tgt, "kind", "") == "decoy" - else ("biological" if hasattr(tgt, "atype") else "vessel")) - self.feed.add(self.world.format_time(), "sonar", - message("runtime.ping.feed", contact=tgt.id, - bearing=f"{contact.bearing:4.0f}", - range=f"{contact.range_est:4.1f}", - latency=f"{latenz:3.1f}", - speed=f"{self.world.mean_sound_speed_m_s(mx, my):.0f}", - classification=klass)) - - # --- Display (M8): Letterbox-Scaling + Vollbild --- - - def toggle_fullscreen(self, persist: bool = True) -> None: - """Vollbild: (0,0)+FULLSCREEN = native Desktop-Größe (deckt Taskleiste - ab, keine schwarzen Balken). Zurück = 1280x720-Fenster.""" - self.fullscreen = not self.fullscreen - if self.fullscreen: - self.display = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) - else: - self.display = pygame.display.set_mode( - (config.SCREEN_W, config.SCREEN_H), pygame.RESIZABLE) - if persist: - from dataclasses import replace - self.preferences = replace(self.preferences, fullscreen=self.fullscreen) - try: - save_preferences(self.preferences) - except OSError: - pass - self.flash(message("event.fullscreen_on" if self.fullscreen - else "event.fullscreen_off"), 2.0) - - def _set_preference(self, name: str, value) -> None: - from dataclasses import replace - self.preferences = replace(self.preferences, **{name: value}) - if name == "language": - self.translator = Translator(value) - self.tr = self.translator.t - self.pinned_tooltip = None - self._tooltip_anchor = None - pygame.display.set_caption(self.tr("app.title")) - if self.editor is not None: - self.editor.tr = self.tr - self.flash(message("status.language_changed", - language=self.tr("option.language." + value)), 2.0) - elif name == "fullscreen" and bool(value) != self.fullscreen: - self.toggle_fullscreen(persist=False) - elif name == "audio": - self.audio.shutdown() - self.audio = AudioEngine(sample_rate=config.AUDIO_SAMPLE_RATE, - enabled=bool(value)) - self._audio_timer = 0.0 - self._sonar_audio_sequence = -1 - elif name in ("large_text", "high_contrast"): - self._apply_text_size() - elif name == "tooltips": - self.tooltips_enabled = bool(value) - self.pinned_tooltip = None - self._tooltip_anchor = None - try: - save_preferences(self.preferences) - except OSError: - self.flash(message("status.preferences_error"), 3.0) - - def _record_simlog(self, stamp: str, category: str, text) -> None: - """Simulationsprotokoll: alle Feed-Ereignisse, optionsgesteuert, begrenzt. - - Speichert das Rohtext (message-/RawText-Objekt); die Lokalisierung - erfolgt erst beim Commander-Publish (Sprache kann wechseln). - """ - if not self.preferences.simlog: - return - self._simlog_seq += 1 - self.simlog.append({ - "seq": self._simlog_seq, - "t": self.sim_t, - "stamp": stamp, - "cat": category, - "text": text, - }) - - def _record_simlog_state(self, dt: float) -> None: - """Periodischer Zustandssnapshot des kompletten Simulationshintergrunds. - - Rein lesend (kein RNG, keine Zustandsaenderung); Laeuft nur im - Simulationsfortschritt, nicht in Pause/Menue/Editor. - """ - if not self.preferences.simlog: - self._simlog_acc = 0.0 - return - self._simlog_acc += dt - if self._simlog_acc < config.SIMLOG_INTERVAL_S: - return - self._simlog_acc = 0.0 - self._simlog_seq += 1 - self.simlog.append({ - "seq": self._simlog_seq, - "t": self.sim_t, - "stamp": self.world.format_time(), - "cat": "state", - "text": "", - "data": self._simlog_state_data(), - }) - - def _simlog_state_data(self) -> dict: - """Kompakter, JSON-faechiger Zustand aller Einheiten, Waffen und Welt.""" - def r2(v): - return None if v is None else round(float(v), 2) - - def r1(v): - return None if v is None else round(float(v), 1) - - ship = self.ship - snap = { - "mission_t": r2(self.mission_time), - "result": self.mission_result, - "world": {"hour": r1(self.world.hour), - "sea_state": self.world.sea_state, - "night": self.world.is_night()}, - "ship": {"x": r2(ship.x), "y": r2(ship.y), - "course": r1(ship.course), "speed": r1(ship.speed), - "damage": r1(self.damage.total), - "sunk": self.damage.ship_sunk, - "stations": {k: self.damage.station_down(k) - for k in ("bridge", "sonar", "weapons", "opz", - "radio", "engine", "flightdeck")}}, - "weapons": {"torpedoes": self.torpedo_count, - "vls": self.vls_cells, "ciws": self.ciws_ammo, - "aa": self.aa_ammo, "chaff_cd": r2(self.chaff_cd)}, - "subs": [{"id": s.id, "x": r2(s.x), "y": r2(s.y), - "depth": r1(s.depth), "course": r1(s.course), - "speed": r1(s.speed), "state": s.state, - "torps": s.torpedoes_left, "sunk": s.sunk} - for s in self.subs], - "surfaces": ([{"id": w.id, "kind": "warship", - "name": getattr(w, "name", None), - "callsign": getattr(w, "callsign", None), - "mmsi": None, "imo": None, "ship_type": None, - "destination": None, "draught_m": None, - "length_m": None, "width_m": None, - "nav_status": None, "ais_heading": None, - "position_accuracy": None, "x": r2(w.x), - "y": r2(w.y), "course": r1(w.course), - "speed": r1(w.speed), "sunk": w.sunk, - "damage": r1(w.damage)} - for w in self.warships] - + [{"id": c.id, "kind": "civilian", - "name": getattr(c, "name", None), - "callsign": getattr(c, "callsign", None), - "mmsi": getattr(c, "live_mmsi", None), - "imo": getattr(c, "live_ais_details", {}).get("imo"), - "ship_type": getattr(c, "live_ais_details", {}).get("ship_type"), - "destination": getattr(c, "live_ais_details", {}).get("destination"), - "draught_m": getattr(c, "live_ais_details", {}).get("draught_m"), - "length_m": getattr(c, "live_ais_details", {}).get("length_m"), - "width_m": getattr(c, "live_ais_details", {}).get("width_m"), - "nav_status": getattr(c, "live_ais_details", {}).get("nav_status"), - "ais_heading": getattr(c, "live_ais_details", {}).get("heading"), - "position_accuracy": getattr(c, "live_ais_details", {}).get("position_accuracy"), - "x": r2(c.x), - "y": r2(c.y), "course": r1(c.course), - "speed": r1(c.speed), "sunk": c.sunk, - "damage": r1(c.damage)} - for c in self.civilians]), - "animals": [{"id": a.id, "x": r2(a.x), "y": r2(a.y), - "dead": a.dead} for a in self.animals], - "torpedoes": [{"id": t.id, "x": r2(t.x), "y": r2(t.y), - "depth": r1(t.depth), "course": r1(t.course), - "state": t.state, - "target": (t.target.id if t.target is not None - else None)} - for t in self.torpedoes], - "enemy_torpedoes": [{"id": t.id, "x": r2(t.x), "y": r2(t.y), - "depth": r1(t.depth), "course": r1(t.course), - "state": t.state} - for t in self.enemy_torpedoes], - "decoys": [{"id": d.id, "x": r2(d.x), "y": r2(d.y), - "depth": r1(d.depth), "life": r1(d.life), - "dead": d.dead} for d in self.decoys], - "asms": [{"seq": a.seq, "x": r2(a.x), "y": r2(a.y), - "course": r1(a.course), "state": a.state, - "jammer": a.jammer} for a in self.asms], - "essms": [{"seq": e.seq, "x": r2(e.x), "y": r2(e.y), - "course": r1(e.course), "state": e.state} - for e in self.essms], - "asrocs": [{"seq": a.seq, "x": r2(a.x), "y": r2(a.y), - "course": r1(a.course), "state": a.state} - for a in self.asrocs], - "nixies": [{"seq": n.seq, "x": r2(n.x), "y": r2(n.y), - "depth": r1(n.depth), "dead": n.dead} - for n in self.nixies], - "buoys": [{"seq": b.seq, "x": r2(b.x), "y": r2(b.y), - "battery_s": r1(b.battery_s), "active": b.active} - for b in self.buoys], - "helo": {"state": self.helo.state, "x": r2(self.helo.x), - "y": r2(self.helo.y), "airborne": self.helo.airborne}, - "flights": ([{"seq": f.seq, "kind": f.kind, "callsign": None, - "icao24": None, "x": r2(f.x), "y": r2(f.y), - "course": r1(f.course), "speed": r1(f.speed), - "alt_m": None} - for f in self.flights.flights] - + [{"seq": a.seq, "kind": "live", - "callsign": a.callsign, "icao24": a.icao24, - "x": r2(a.x), "y": r2(a.y), - "course": r1(a.course), "speed": r1(a.speed), - "alt_m": r1(a.altitude_m)} - for a in sorted(self.live_traffic.aircraft.values(), - key=lambda item: item.seq) - if not a.despawned]), - "raiders": [{"seq": r.seq, "x": r2(r.x), "y": r2(r.y), - "course": r1(r.course), "phase": r.phase.value, - "hp": r.hp, "pending_asm": r.pending_asm} - for r in self.raiders], - "radars": {"surface": self.surface_radar_on, - "air": self.air_radar_on}, - } - return snap - - def compose_frame(self) -> None: - """Virtuellen 1280x720-Canvas aufs Display bringen (M8/M9). - - FILL_SCREEN=True: Stretch auf die volle Fläche (keine schwarzen - Balken bei 16:9); False: aspect-correctes Letterbox. - """ - w, h = pygame.display.get_window_size() - if w <= 0 or h <= 0: - w, h = config.SCREEN_W, config.SCREEN_H - # Unter X11/XWayland ersetzt pygame die Display-Surface nach dem ersten - # Event-Pump/Resize durch ein neues Objekt; das gemerkte self.display - # ist dann 0x0 und der Blit scheitert mit "Surfaces must not be locked". - display = pygame.display.get_surface() - if display is None: - return - self.display = display - display.fill((0, 0, 0)) - if (w, h) == (config.SCREEN_W, config.SCREEN_H): - display.blit(self.screen, (0, 0)) - elif config.FILL_SCREEN: - display.blit(pygame.transform.scale(self.screen, (w, h)), (0, 0)) - else: - _, ox, oy, sw, sh = letterbox_layout(w, h) - display.blit( - pygame.transform.scale(self.screen, (sw, sh)), (ox, oy)) - pygame.display.flip() - - # --- Input --- - - def _cycle_sonar_mode(self) -> None: - self.set_sonar_array_mode("TOWED" if self.sonar_mode == "BOW" else "BOW") - self.flash(message("runtime.sonar_array.towed" if self.sonar_mode == "TOWED" - else "runtime.sonar_array.bow"), 1.5) - - def _handle_sonar_click(self, target) -> bool: - """Execute the sonar view's closed allowlist of non-critical actions.""" - if not isinstance(target, dict) or target.get("safe") is not True: - return False - action = target.get("action") - if action == "page_set": - value = target.get("value") - if type(value) is not int or not 0 <= value < len(STATION_PAGES[Station.SONAR]): - return False - self.sonar_page = value - elif action == "page": - self.sonar_page = station_page_step(Station.SONAR, self.sonar_page, 1) - elif action in ("contact", "echo", "contact_listen"): - contact_id = target.get("value") - contact = next((item for item in self.sonar.active_contacts() - if item.id == contact_id), None) - if contact is None: - return False - if action == "contact_listen": - if self.set_sonar_focus(contact) is not True: - return False - else: - self.selected_contact = contact - elif action == "listen_bearing": - value = target.get("value") - if (type(value) not in (int, float) or not math.isfinite(value) - or not 0 <= value < 360): - return False - self.set_sonar_listen_bearing(value) - self.flash(message("runtime.numeric.true_bearing", - bearing=f"{value:05.1f}"), 2.0) - elif action == "array": - self._cycle_sonar_mode() - elif action == "gain": - self._adjust_sonar_gain(3.0) - elif action == "band_filter": - self._cycle_sonar_band() - elif action == "notch": - self.set_sonar_notch(not self.sonar.notch_enabled) - self.flash(message("runtime.notch.on" if self.sonar.notch_enabled - else "runtime.notch.off"), 1.5) - elif action == "harmonic": - self._cycle_sonar_harmonic() - elif action == "tma_accept": - self._accept_tma_with_notice(self._tma_contact()) - elif action == "integration": - seconds = self.sonar_tools.cycle_integration() - self.flash(message("runtime.integration", seconds=seconds), 1.5) - elif action == "cursor": - pass # the cursor moves with Z/X; the segment is a readout - elif action == "peak": - self.set_sonar_peak_hold(not self.sonar.peak_hold) - self.flash(message("runtime.peak_hold.on" if self.sonar.peak_hold - else "runtime.peak_hold.off"), 1.5) - elif action == "audio": - self.sonar_audio_enabled = not self.sonar_audio_enabled - self._stop_sonar_audio() - self.flash(message("runtime.sonar_audio.on" if self.sonar_audio_enabled - else "runtime.sonar_audio.off")) - else: - return False - return True - - def _cycle_sonar_harmonic(self) -> None: - """K: mark the line under the operator cursor (LOFAR fundamental, - DEMON shaft then blade line); pressing again on the mark clears it.""" - page = "demon" if self.sonar_page == 2 else "lofar" - if self.mark_sonar_cursor(page) is not True: - return - tools = self.sonar_tools - if page == "demon": - key = ("runtime.demon.blade" if tools.blade_hz is not None - else "runtime.demon.shaft" if tools.shaft_hz is not None - else "runtime.demon.cleared") - self.flash(message(key, frequency=f"{tools.demon_cursor_hz:.1f}"), 1.5) - elif self.sonar_harmonic_hz is None: - self.flash(message("runtime.harmonic.cleared"), 1.5) - else: - self.flash(message("runtime.harmonic.selected", - frequency=f"{self.sonar_harmonic_hz:.1f}"), 1.5) - - def _tma_contact(self): - contact = self.selected_contact - if contact is None or contact.target_id not in self.sonar.contacts: - return None - return contact - - def _tma_points(self, contact): - track = self.sonar._tracks.get(getattr(contact, "target_id", None)) - return list(getattr(track, "pts", ())) - - def tma_hypothesis(self, contact): - hypothesis = self.tma_hypotheses.get(contact.target_id) - if hypothesis is None: - hypothesis = tma_operator.default_hypothesis(self._tma_points(contact)) - return hypothesis - - def set_tma_hypothesis(self, contact, course, speed_kn, range_nm): - if contact is None or contact.target_id not in self.sonar.contacts: - return "stale_ref" - if any(type(value) not in (int, float) or not math.isfinite(value) - for value in (course, speed_kn, range_nm)): - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - self.tma_hypotheses[contact.target_id] = tma_operator.Hypothesis( - float(course), float(speed_kn), float(range_nm)).clamped() - while len(self.tma_hypotheses) > 64: - self.tma_hypotheses.pop(next(iter(self.tma_hypotheses))) - return True - - def tma_evaluation(self, contact): - points = self._tma_points(contact) - return tma_operator.evaluate(points, self.tma_hypothesis(contact)) - - def accept_tma(self, contact): - """Write the operator's hypothesis as the contact's TMA fix.""" - if contact is None or contact.target_id not in self.sonar.contacts: - return "stale_ref" - if self._sonar_down(): - return "sonar_down" - points = self._tma_points(contact) - evaluation = tma_operator.evaluate(points, self.tma_hypothesis(contact)) - if evaluation is None: - return "not_ready" - if evaluation["observability"] < 0.5: - return "unobservable" - if evaluation["fit"] < TMA_ACCEPT_MIN_FIT: - return "poor_fit" - hypothesis = self.tma_hypothesis(contact) - position = tma_operator.position_at(points, hypothesis, self.sim_t) - contact.accept_operator_tma(position, hypothesis.course, - hypothesis.speed_kn, evaluation["quality"], - self.sim_t) - return True - - def copy_tma_proposal(self, contact): - """Training aid: start the hypothesis from the automatic solver.""" - if not self.operator_assist(): - return "not_available" - if contact is None: - return "stale_ref" - proposal = self.sonar.tma_proposals.get(contact.target_id) - points = self._tma_points(contact) - if proposal is None or not points: - return "not_ready" - # The proposal's position is at its newest bearing; its range from - # that observation point seeds the hypothesis range. - ref = points[-1] - return self.set_tma_hypothesis( - contact, proposal.course, proposal.speed, - math.hypot(proposal.pos[0] - ref.fx, proposal.pos[1] - ref.fy)) - - def _accept_tma_with_notice(self, contact) -> None: - result = self.accept_tma(contact) if contact is not None else "stale_ref" - if result is True: - self.flash(message("runtime.tma.accepted", contact=contact.id, - quality=f"{contact.tma_quality:.0%}"), 2.0) - elif result == "poor_fit": - self.flash(message("runtime.tma.poor_fit"), 2.0) - elif result == "unobservable": - self.flash(message("runtime.tma.unobservable"), 2.0) - else: - self.flash(message("runtime.tma.not_ready"), 2.0) - - def operator_assist(self) -> bool: - """Training aids (auto peaks, blade-rate/catalog ranking, ESM IDs) on?""" - return getattr(self.preferences, "operator_assist", "off") == "training" - - def set_sonar_cursor(self, page, frequency_hz): - if page not in ("lofar", "demon"): - return "invalid_value" - if (type(frequency_hz) not in (int, float) - or not math.isfinite(frequency_hz)): - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - value = analysis_tools.clamp_cursor(frequency_hz, page) - if page == "lofar": - self.sonar_tools.lofar_cursor_hz = value - else: - self.sonar_tools.demon_cursor_hz = value - return True - - def mark_sonar_cursor(self, page): - if page not in ("lofar", "demon"): - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - tools = self.sonar_tools - if page == "demon": - tools.mark_demon(tools.demon_cursor_hz) - return True - cursor = tools.lofar_cursor_hz - if (self.sonar_harmonic_hz is not None - and abs(self.sonar_harmonic_hz - cursor) < 1e-6): - return self.set_sonar_harmonic(None) - return self.set_sonar_harmonic(cursor) - - def set_sonar_integration(self, seconds): - if type(seconds) is not int or seconds not in analysis_tools.INTEGRATION_CHOICES_S: - return "invalid_value" - self.sonar_tools.integration_s = seconds - return True - - def set_sonar_vernier(self, enabled): - if type(enabled) is not bool: - return "invalid_value" - self.sonar_tools.vernier = enabled - return True - - def set_sonar_band(self, low_hz, high_hz): - """Free band-pass edges (low 0 = low-pass, high 300 = high-pass).""" - if (any(type(value) not in (int, float) or not math.isfinite(value) - for value in (low_hz, high_hz)) - or not 0.0 <= low_hz < high_hz <= config.LOFAR_FMAX_HZ): - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - self.sonar.band_low_hz, self.sonar.band_high_hz = float(low_hz), float(high_hz) - return True - - def set_tas_side(self, contact, action: str): - """Operator decision on a towed-only contact's array side. - - ``flip`` shows the other side (and reopens a confirmed choice); - ``confirm`` commits the shown side. Nothing is decided automatically. - """ - if contact is None or contact.target_id not in self.sonar.contacts: - return "stale_ref" - if action not in ("flip", "confirm"): - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - if action == "flip": - if not contact.towed_ambiguous: - if not contact.towed_resolved: - return "not_ambiguous" - contact.towed_ambiguous, contact.towed_resolved = True, False - contact.ambiguity_axis = self.sonar.tow_heading_deg - contact.towed_side = "PORT" if contact.towed_side == "STBD" else "STBD" - return True - if not contact.towed_ambiguous: - return "not_ambiguous" - contact.towed_ambiguous, contact.towed_resolved = False, True - contact.mirror_bearing = contact.ambiguity_axis = None - return True - - def set_sonar_demon_band(self, low_hz, high_hz): - if (low_hz, high_hz) not in analysis_tools.DEMON_BANDS_HZ: - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - self.sonar.receiver.demon_band_hz = (float(low_hz), float(high_hz)) - return True - - def set_sonar_heterodyne(self, frequency_hz): - if frequency_hz not in analysis_tools.HETERODYNE_OFFSETS_HZ: - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - self.sonar.heterodyne_hz = float(frequency_hz) - return True - - def set_sonar_operator_notch(self, frequency_hz): - if frequency_hz is not None and ( - type(frequency_hz) not in (int, float) or not math.isfinite(frequency_hz) - or not 0.0 < frequency_hz <= config.LOFAR_FMAX_HZ): - return "invalid_value" - if self._sonar_down(): - return "sonar_down" - self.sonar.operator_notch_hz = (None if frequency_hz is None - else float(frequency_hz)) - return True - - def _adjust_sonar_gain(self, delta: float) -> None: - self.set_sonar_gain(config.clamp(self.sonar.gain_db + delta, -12.0, 24.0)) - self.flash(message("runtime.sonar_gain", gain=f"{self.sonar.gain_db:+.0f}"), 1.2) - - def _cycle_sonar_display_palette(self) -> None: - palettes = ("green", "amber", "cyan") - current = (palettes.index(self.sonar_display_palette) - if self.sonar_display_palette in palettes else -1) - self.sonar_display_palette = palettes[(current + 1) % len(palettes)] - self.flash(message("runtime.sonar_palette", - palette=self.sonar_display_palette.upper()), 1.2) - - def _adjust_sonar_display_contrast(self, delta: float) -> None: - self.sonar_display_contrast = round(config.clamp( - self.sonar_display_contrast + delta, .5, 4.0), 1) - self.flash(message("runtime.sonar_contrast", - contrast=f"{self.sonar_display_contrast:.1f}"), 1.2) - - def _adjust_sonar_display_black(self, delta: float) -> None: - self.sonar_display_black = round(config.clamp( - self.sonar_display_black + delta, 0.0, .8), 2) - self.flash(message("runtime.sonar_black_level", - level=f"{self.sonar_display_black:.2f}"), 1.2) - - def _cycle_sonar_display_history(self) -> None: - depths = (.25, .5, 1.0) - current = next((index for index, value in enumerate(depths) - if abs(self.sonar_display_history - value) < 1e-6), -1) - self.sonar_display_history = depths[(current + 1) % len(depths)] - self.flash(message("runtime.sonar_history", - history=f"{self.sonar_display_history:.0%}"), 1.2) - - def _set_sonar_audition_mode(self, mode: str) -> None: - if self.set_sonar_audition_mode(mode) is not True: - return - key = {"BROADBAND": "runtime.listen.broadband", - "FILTERED": "runtime.listen.filtered", - "HETERODYNE": "runtime.listen.heterodyne"}[mode] - self.flash(message(key), 1.2) - - def sonar_audio_status(self) -> dict: - status = self.audio.availability_status() - locally_ready = (self.station is Station.SONAR and self.sonar_audio_enabled - and not self.damage.station_down("sonar")) - return dict(status, local_enabled=bool(self.sonar_audio_enabled), - mode=self.sonar.audition_mode, gain_db=self.sonar.gain_db, - band_hz=[self.sonar.band_low_hz, self.sonar.band_high_hz], - notch=bool(self.sonar.notch_enabled), volume=self.sonar_volume, - stale=bool(self.audio.sonar_stale), - audible=bool(status["global_enabled"] - and status["device_available"] and locally_ready)) - - def _cycle_sonar_band(self) -> None: - bands = tuple(SONAR_BAND_PRESETS.values()) - current = (self.sonar.band_low_hz, self.sonar.band_high_hz) - try: - index = bands.index(current) - except ValueError: - index = 0 - low, high = bands[(index + 1) % len(bands)] - preset = next(key for key, value in SONAR_BAND_PRESETS.items() - if value == (low, high)) - self.set_sonar_band_preset(preset) - self.flash(message("runtime.sonar_band", low=f"{low:.0f}", - high=f"{high:.0f}"), 1.5) - @property def radar_on(self) -> bool: """Kompatibilitaet fuer alte Aufrufer/Saves: beide Radare gemeinsam.""" @@ -1736,3360 +705,4 @@ class Game(MissionBridgeMixin, EventMixin, SimMixin, SaveMixin): self.surface_radar_on = bool(value) self.air_radar_on = bool(value) - def toggle_radar(self, domain: str = "surface") -> None: - enabled = not (self.air_radar_on if domain == "air" - else self.surface_radar_on) - if self.set_opz_radar(domain, enabled) is not True: - self.flash(message("runtime.opz.disabled")) - return - if domain == "air": - radar, active = "air", self.air_radar_on - else: - radar, active = "surface", self.surface_radar_on - suffix = "on" if active else "off" - self.hq_msg(message(f"runtime.emcon.{radar}.{suffix}.hq")) - self.flash(message(f"runtime.emcon.{radar}.{suffix}"), 2.0) - - def set_opz_radar(self, domain: str, enabled: bool): - """Set one OPZ radar from a validated local or remote station action.""" - if self.damage.station_down("opz"): - return "opz_down" - if domain not in ("surface", "air") or type(enabled) is not bool: - return "invalid_value" - setattr(self, f"{domain}_radar_on", enabled) - return True - - def set_opz_range(self, range_nm: float): - if self.damage.station_down("opz"): - return "opz_down" - if type(range_nm) not in (int, float) or range_nm not in config.RADAR_RANGE_SCALES_NM: - return "invalid_value" - self.opz_range_nm = float(range_nm) - return True - - def _cycle_lookout_range(self, delta: int) -> None: - """Bridge lookout page: step the display scale (presentation only).""" - scales = config.LOOKOUT_DISPLAY_RANGES_NM - current = getattr(self, "lookout_range_nm", 12.0) - index = min(range(len(scales)), key=lambda i: abs(scales[i] - current)) - self.lookout_range_nm = scales[max(0, min(len(scales) - 1, index + delta))] - self.flash(message("runtime.lookout.range", range=f"{self.lookout_range_nm:.0f}"), 1.5) - - def lookout_sightings(self) -> list: - """Current bridge-lookout tracks (measured bearing/range, visual label).""" - return [track for track in self.air_picture.tracks(self.sim_t) - if track.source == "LOOKOUT" and track.x is not None and track.y is not None] - - def _cycle_radar_range(self, delta: int) -> None: - scales = config.RADAR_RANGE_SCALES_NM - try: - index = scales.index(float(self.opz_range_nm)) - except ValueError: - index = len(scales) - 1 - index = max(0, min(len(scales) - 1, index + delta)) - if self.set_opz_range(scales[index]) is not True: - return - self.flash(message("runtime.radar.range", range=f"{self.opz_range_nm:.0f}"), 1.5) - - def radar_blip_view(self) -> list: - """Unmarked radar blips still glowing (measured positions only).""" - if not (self.surface_radar_on and not self.damage.station_down("opz")): - return [] - return [blip for blip in self.radar_blips - if 0.0 <= self.sim_t - blip["t"] < config.RADAR_BLIP_LIFE_S - and blip["target"] not in self._radar_marked] - - def mark_radar_blip(self, seq): - """OPZ: start a radar track from a blip (its measurement only).""" - if type(seq) is not int: - return "invalid_value" - blip = next((item for item in self.radar_blip_view() if item["seq"] == seq), None) - if blip is None: - return "stale_ref" - track_id = f"R-{blip['seq']}" - self._observe_mast(track_id, blip["target"], blip["bearing"], blip["range_nm"], - blip["observer_x"], blip["observer_y"], blip["error"]) - self.announce(message("runtime.opz.blip_marked", track=track_id), "opz", 2.0) - return True - - def _mark_newest_blip(self) -> None: - blips = self.radar_blip_view() - if not blips: - self.flash(message("runtime.opz.no_blip"), 1.5) - return - self.mark_radar_blip(blips[-1]["seq"]) - - def radar_sweep_bearing(self) -> float: - """Nautische Peilung: zunehmende Werte drehen Nord -> Ost rechtsherum.""" - return self.radar_scan_phase - - def toggle_helo(self) -> None: - if self.helo.airborne: - if self.return_helicopter() is True: - self.announce(message("runtime.helo.return"), "waffen") - else: - result = self.launch_helicopter() - if result == "flightdeck_down": - self.flash(message("runtime.helo.deck_down")) - return - if result == "weather_unsafe": - self.flash(message("runtime.helo.weather_unsafe")) - return - if result is not True: - self.flash(message("runtime.helo.lost")) - return - self.announce(message("runtime.helo.launch", torpedoes=self.helo.torps, - buoys=self.helo.buoys_left), "waffen", 3.0) - - def atmosphere(self) -> dict: - """Own-ship atmosphere (barometer, thermometer, wind, sky), derived - from the weather system; observation-safe (no future values).""" - world = self.world - weather = world.weather_values() - kind = world.weather_kind() - source_sea, target_sea, elapsed = world.weather_epoch() - pressure, tendency = atmosphere_physics.barometer( - self.seed, source_sea, target_sea, elapsed) - trend = atmosphere_physics.pressure_trend(tendency) - rain = weather["rain_intensity"] - wind = weather["wind_speed_kn"] - sst = world.ocean.sea_surface_temperature_c(world.hour) - cloud = atmosphere_physics.cloud_cover(kind, rain) - air = atmosphere_physics.air_temperature_c( - sst, world.ocean.day_of_year, world.hour, weather["wind_from_deg"], - wind, cloud) - precipitation = atmosphere_physics.precipitation(rain, air) - latitude = world.latitude_deg() - latitude = (atmosphere_physics.DEFAULT_LATITUDE_DEG if latitude is None - else latitude) - sun = atmosphere_physics.sun_elevation_deg( - latitude, world.ocean.day_of_year, world.hour) - lunar_age = self.lunar_age_days() - return dict( - weather=("snow" if precipitation == "snow" else kind), - precipitation=precipitation, rain_intensity=rain, - visibility_nm=weather["visibility_nm"], - sea_state=int(round(weather["sea_state"])), - wind_from_deg=weather["wind_from_deg"], wind_kn=wind, - gust_kn=atmosphere_physics.gust_kn(wind, weather["sea_state"]), - beaufort=atmosphere_physics.beaufort(wind), - pressure_hpa=pressure, pressure_tendency_hpa_3h=tendency, - pressure_trend=trend, - storm_warning=atmosphere_physics.storm_warning(pressure, trend), - air_temp_c=air, sea_temp_c=sst, cloud_cover=cloud, - ceiling_ft=atmosphere_physics.cloud_ceiling_ft( - kind, rain, weather["visibility_nm"]), - icing=atmosphere_physics.icing(air, precipitation, wind), - sun_elevation_deg=sun, - daylight=atmosphere_physics.daylight(sun), - moon_phase=atmosphere_physics.moon_phase(lunar_age), - moon_illumination=visual_physics.moon_illumination(lunar_age), - time=world.format_time()) - - def helicopter_weather(self) -> dict: - """Return one shared, observation-safe flight-weather decision.""" - weather = self.world.weather_values() - atmosphere = self.atmosphere() - relative = math.radians(config.angle_diff_deg( - weather["wind_from_deg"], self.ship.course)) - crosswind = abs(weather["wind_speed_kn"] * math.sin(relative)) - launch_safe = ( - weather["wind_speed_kn"] <= config.HELO_LAUNCH_WIND_MAX_KN - and crosswind <= config.HELO_LAUNCH_CROSSWIND_MAX_KN - and weather["visibility_nm"] >= config.HELO_LAUNCH_VISIBILITY_MIN_NM - and weather["sea_state"] <= config.HELO_LAUNCH_SEA_STATE_MAX) - gust = atmosphere["gust_kn"] - ceiling = atmosphere["ceiling_ft"] - icing = atmosphere["icing"] - launch_weather = (launch_safe - and gust <= config.HELO_LAUNCH_GUST_MAX_KN - and (ceiling is None or ceiling >= config.HELO_CEILING_MIN_FT) - and icing != "severe") - # Launch and recovery also need a deck-motion window (own ship). - deck_safe = helicopter_physics.deck_within_limits(self.ship.roll, self.ship.pitch) - launch_safe = launch_weather and deck_safe - dipping_safe = ( - weather["wind_speed_kn"] <= config.HELO_DIP_WIND_MAX_KN - and weather["visibility_nm"] >= config.HELO_DIP_VISIBILITY_MIN_NM - and weather["sea_state"] <= config.HELO_DIP_SEA_STATE_MAX - # Winch and cable ice up: no dipping in icing conditions. - and icing == "none") - # Flight-weather category: NO-GO outside the launch weather limits, - # LIMITED near a limit (80 %) or in light icing, else CLEAR. - margins = ( - weather["wind_speed_kn"] / config.HELO_LAUNCH_WIND_MAX_KN, - gust / config.HELO_LAUNCH_GUST_MAX_KN, - crosswind / config.HELO_LAUNCH_CROSSWIND_MAX_KN, - weather["sea_state"] / config.HELO_LAUNCH_SEA_STATE_MAX, - config.HELO_LAUNCH_VISIBILITY_MIN_NM / max(weather["visibility_nm"], 1e-3), - (0.0 if ceiling is None else config.HELO_CEILING_MIN_FT / max(ceiling, 1.0))) - status = ("no_go" if not launch_weather else - "limited" if icing != "none" or max(margins) >= 0.8 else "clear") - return dict(weather, crosswind_kn=crosswind, deck_safe=deck_safe, - launch_safe=launch_safe, dipping_safe=dipping_safe, - gust_kn=gust, ceiling_ft=ceiling, icing=icing, status=status) - - WEATHER_PROFILE_STALE_S = 1800.0 - WEATHER_PROFILE_STALE_NM = 10.0 - WEATHER_RAY_SOURCE_DEPTH_M = 5.0 # hull sonar - - def weather_station_data(self) -> dict: - """Observation-safe data for the weather & sonar analysis panel. - - Atmosphere and flight weather come from own-ship instruments. The - ocean profile - layer, sound-speed curve, shadow zone, SOFAR axis, - rays - exists only after the sonar has taken a bathythermograph - measurement, and is always that measurement (with its age), never - the modelled truth.""" - atmosphere = self.atmosphere() - flight = self.helicopter_weather() - effects = dict( - solar_heating=(atmosphere["daylight"] == "day" - and atmosphere["sun_elevation_deg"] >= 20.0 - and atmosphere["cloud_cover"] < 0.6), - wind_mixing=atmosphere["wind_kn"] >= ocean_physics.MLD_WIND_THRESHOLD_KN, - freshwater=atmosphere["precipitation"] != "none") - return dict( - atmosphere=atmosphere, effects=effects, - flight=dict( - status=flight["status"], launch_safe=flight["launch_safe"], - dipping_safe=flight["dipping_safe"], deck_safe=flight["deck_safe"], - wind_kn=flight["wind_speed_kn"], gust_kn=flight["gust_kn"], - crosswind_kn=flight["crosswind_kn"], - visibility_nm=flight["visibility_nm"], - ceiling_ft=flight["ceiling_ft"], icing=flight["icing"], - sea_state=int(round(flight["sea_state"])), - # A crewed boat's instruments never report the frigate's motion. - roll_deg=(self.ship.roll if self._sonar_ctx is self._frigate_sonar - else 0.0), - pitch_deg=(self.ship.pitch if self._sonar_ctx is self._frigate_sonar - else 0.0), - limits=dict( - wind_kn=config.HELO_LAUNCH_WIND_MAX_KN, - gust_kn=config.HELO_LAUNCH_GUST_MAX_KN, - crosswind_kn=config.HELO_LAUNCH_CROSSWIND_MAX_KN, - visibility_nm=config.HELO_LAUNCH_VISIBILITY_MIN_NM, - ceiling_ft=config.HELO_CEILING_MIN_FT, - sea_state=config.HELO_LAUNCH_SEA_STATE_MAX, - roll_deg=helicopter_physics.DECK_ROLL_LIMIT_DEG, - pitch_deg=helicopter_physics.DECK_PITCH_LIMIT_DEG)), - profile=self._weather_station_profile()) - - def _weather_station_profile(self) -> dict | None: - bt = self.sonar.bt_profile - if bt is None: - return None - age = max(0.0, self.sim_t - bt["t"]) - observer = self.sonar_observer - offset = math.hypot(observer.x - bt["x"], observer.y - bt["y"]) - # Wind of the measurement's sea-state band keeps the picture fixed - # for one measurement (a pure, cached function of it). - wind = ocean_physics.MLD_WIND_THRESHOLD_KN * bt["sea_state"] / 3.0 - picture = sonar_raytrace.ray_picture( - bt["depths_m"], bt["speeds_m_s"], bt["water_depth_m"], - self.WEATHER_RAY_SOURCE_DEPTH_M, self.world.seabed_at(bt["x"], bt["y"]), - wind, bt["thermocline_m"]) - dip = None - if (self._sonar_ctx is self._frigate_sonar and self.helo.airborne - and self.helo.dip_state != "STOWED"): - dip = ("below" if self.helo.dip_depth_m >= bt["thermocline_m"] - else "above") - return dict( - age_s=age, offset_nm=offset, - stale=(age > self.WEATHER_PROFILE_STALE_S - or offset > self.WEATHER_PROFILE_STALE_NM), - thermocline_m=bt["thermocline_m"], water_depth_m=bt["water_depth_m"], - depths_m=list(bt["depths_m"]), speeds_m_s=list(bt["speeds_m_s"]), - sofar_axis_m=ocean_physics.sofar_axis_m( - bt["depths_m"], bt["speeds_m_s"], bt["water_depth_m"]), - cz_bands_nm=[list(band) for band in bt["cz_bands_nm"]], - range_nm=picture["range_nm"], rays=picture["rays"], - depth_edges_m=picture["depth_edges_m"], shadow=picture["shadow"], - dip_relative_to_layer=dip) - - def launch_helicopter(self): - if self.damage.station_down("flightdeck"): - return "flightdeck_down" - if not self.helicopter_weather()["launch_safe"]: - return "weather_unsafe" - if self.helo.state != "HANGAR": - return "not_ready" - self.helo.launch(self.ship) - return True - - def return_helicopter(self): - if not self.helo.airborne: - return "not_ready" - self.helo.order_return() - return True - - def set_helicopter_waypoint(self, x: float, y: float): - if (type(x) not in (int, float) or type(y) not in (int, float) - or not 0 <= x <= self.world.size_nm - or not 0 <= y <= self.world.size_nm - or not math.isfinite(x) or not math.isfinite(y)): - return "invalid_value" - if self.helo.state == "VERLOREN": - return "not_ready" - self.helo.set_waypoint(x, y) - return True - - def _helo_waypoint_polar(self) -> tuple[float, float]: - if self.helo.waypoint_x is None or self.helo.waypoint_y is None: - return self.ship.course, 2.0 - dx = self.helo.waypoint_x - self.ship.x - dy = self.helo.waypoint_y - self.ship.y - return math.degrees(math.atan2(dx, -dy)) % 360.0, math.hypot(dx, dy) - - def _adjust_helo_waypoint(self, bearing_delta: float = 0.0, - range_delta: float = 0.0) -> None: - bearing, distance = self._helo_waypoint_polar() - bearing = (bearing + bearing_delta) % 360.0 - distance = config.clamp(distance + range_delta, 1.0, 30.0) - self.helo.set_waypoint( - self.ship.x + distance * math.sin(math.radians(bearing)), - self.ship.y - distance * math.cos(math.radians(bearing))) - self.flash(message("runtime.helo.waypoint", bearing=f"{bearing:03.0f}", - range=f"{distance:.0f}"), 1.5) - - def deploy_buoys(self) -> None: - result = self.deploy_helicopter_buoy() - if result == "not_ready": - self.flash(message("runtime.helo.not_airborne")) - return - if result == "water_required": - self.flash(message("runtime.helo.water_required")) - return - if result is True: - buoy = self.buoys[-1] - self.flash(message("runtime.buoy.deployed", buoy=buoy.seq)) - self.feed.add(self.world.format_time(), "sonar", - message("runtime.buoy.active", buoy=buoy.seq)) - else: - self.flash(message("event.no_buoys")) - - def deploy_helicopter_buoy(self): - if not self.helo.airborne: - return "not_ready" - if not self.helo.water_entry_clear(self.world): - return "water_required" - if self.helo.buoys_left <= 0: - return "no_buoys" - next_sequence = self.buoy_seq + 1 - buoy = self.helo.deploy_buoy(next_sequence, world=self.world, - mode=getattr(self, "helo_buoy_mode", "PASSIVE")) - if buoy is None: - return "not_ready" - self.buoy_seq = next_sequence - self.buoys.append(buoy) - if buoy.mode == "PASSIVE" and not self.helicopter_audio_ready(): - self.set_helicopter_listen_source(f"SB{buoy.seq}") - return True - - def set_helicopter_buoy_mode(self, mode: str): - if mode not in ("PASSIVE", "ACTIVE") or type(mode) is not str: - return "invalid_value" - self.helo_buoy_mode = mode - return True - - def set_helicopter_listen_source(self, source: str): - if source != "DIP": - if (type(source) is not str or not source.startswith("SB") - or not source[2:].isdigit() or len(source) > 5): - return "invalid_value" - seq = int(source[2:]) - if not any(b.seq == seq and b.active for b in self.buoys): - return "stale_ref" - if source != self.helo_listen_source: - self.helo_listen_source = source - self.helo_receiver.reset() - self.helo_audition.reset_audition_audio() - self.helo_spectra.clear() - self.helo_broadband_history.clear() - self.helo_demon_history.clear() - self._helo_receiver_timer = 0.0 - return True - - def set_helicopter_listen_bearing(self, bearing): - if bearing is not None and (type(bearing) not in (int, float) - or not math.isfinite(bearing) - or not 0 <= bearing < 360): - return "invalid_value" - self.helo_listen_bearing = bearing - return True - - def set_helicopter_audio_mode(self, mode: str): - if type(mode) is not str or not self.helo_audition.set_audition_mode(mode): - return "invalid_value" - return True - - def set_helicopter_audio_band(self, preset: str): - band = SONAR_BAND_PRESETS.get(preset) if type(preset) is str else None - if band is None: - return "invalid_value" - self.helo_audition.band_low_hz, self.helo_audition.band_high_hz = band - self.helo_audio_band = preset - return True - - def set_helicopter_audio_gain(self, gain_db): - if type(gain_db) not in (int, float) or not math.isfinite(gain_db) \ - or not -12 <= gain_db <= 24: - return "invalid_value" - self.helo_audition.gain_db = float(gain_db) - return True - - def set_helicopter_audio_notch(self, enabled): - if type(enabled) is not bool: - return "invalid_value" - self.helo_audition.notch_enabled = enabled - return True - - def helicopter_audio_ready(self) -> bool: - """The selected helicopter hydrophone must be in the water.""" - source = self.helo_listen_source - if source == "DIP": - return self.helo.dip_available and self.helo.dip_depth_m > 0.0 - if not source.startswith("SB") or not source[2:].isdigit(): - return False - seq = int(source[2:]) - return any(b.seq == seq and b.active and b.mode == "PASSIVE" - for b in self.buoys) - - def launch_helo_torpedo(self) -> None: - """Leichttorpedo vom HSP-5 (eigene Munition, nicht Fregatten-Rohre).""" - if (self.target is None - or self.sim_t - self.target.last_seen >= config.SONAR_CONTACT_LOST_S): - self.target = None - self.flash(message("runtime.target.invalid")) - return - self.launch_helicopter_torpedo_at(self.target, self.torpedo_depth) - - def launch_helicopter_torpedo_at(self, contact, depth_m: float): - """Release a helicopter torpedo against one explicit sonar observation.""" - if (contact is None or type(depth_m) not in (int, float) - or not math.isfinite(depth_m) or not 10 <= depth_m <= 300 - or self.sim_t - contact.last_seen >= config.SONAR_CONTACT_LOST_S): - self.flash(message("runtime.target.invalid")) - return "invalid_target" - blocked = self._target_affiliation_interlock(contact) - if blocked is not None: - self.flash(message("runtime.roe.blocked", - affiliation=display_value("affiliation", blocked, self.tr))) - return "roe_blocked" - if self.roe == "STD" and not self._contact_range_fresh(contact): - self.flash(message("runtime.target.not_located")) - return "not_located" - if self.weapon_classification(contact) != "U_BOOT": - self.flash(message("runtime.target.air_class")) - return "not_classified" - if not self.helo.airborne: - self.flash(message("runtime.helo.not_airborne")) - return "not_ready" - if self.helo.torps <= 0: - self.flash(message("runtime.helo_no_torpedoes")) - return "empty" - if not self.helo.water_entry_clear(self.world): - self.flash(message("runtime.helo.water_required")) - return "water_required" - tgt = self._find_target(contact.target_id) - lv = self.difficulty - range_nm = (contact.range_est if contact.range_est is not None - else config.ROE_FREE_LAUNCH_RANGE_NM) - use_fix = (self._contact_range_fresh(contact) - and contact.observed_x is not None - and contact.observed_y is not None) - datum = self.helo.release_datum_from_ship_observation( - self.ship, contact.bearing, range_nm, - bearing_uncertainty_deg=max(0.0, (1.0 - contact.quality) * 8.0), - range_uncertainty_nm=contact.range_sigma_nm or 0.0, - datum_x=contact.observed_x if use_fix else None, - datum_y=contact.observed_y if use_fix else None) - torp = self.helo.drop_torpedo( - tgt, depth_m, self.torpedo_seq + 1, - kill_dist_nm=lv["kill_dist_nm"], kill_depth_m=lv["kill_depth_m"], - guidance_x=datum.x_nm, guidance_y=datum.y_nm, world=self.world) - if torp is None: - return "not_ready" - self.torpedo_seq += 1 - self.torpedoes.append(torp) - self._emit_sound("water_entry") - self.flash(message("runtime.helo_torpedo.launched", - torpedo=self.torpedo_seq), 2.0) - self.feed.add(self.world.format_time(), "waffen", - message("runtime.helo_torpedo.feed", - torpedo=self.torpedo_seq, contact=contact.id)) - return True - - @staticmethod - def _missile_seq(track): - """Internal missile sequence behind an ``M-`` air track, else None. - - An ASM cue can also sit on an aircraft track; fire control resolves - the engaged weapon only through the missile's own track namespace. - """ - track_id = str(getattr(track, "track_id", "")) - suffix = track_id[2:] - return int(suffix) if track_id.startswith("M-") and suffix.isdigit() else None - - def _cycle_asm_track(self, delta: int) -> None: - n = len(self.asm_tracks()) - if n == 0: - self.asm_sel = 0 - return - self.asm_sel = (self.asm_sel + delta) % n - - def launch_essm(self) -> None: - tracks = self.asm_tracks() - track = tracks[min(self.asm_sel, len(tracks) - 1)] if tracks else None - self.launch_essm_at(track) - - def launch_essm_at(self, track): - """Launch against an explicit current positioned ASM observation.""" - profiles = self._air_defense_loadout - if self.damage.station_down("opz") or self.damage.station_degraded("opz"): - self.flash(message("runtime.opz.degraded")) - return "opz_degraded" - if self.vls_cells <= 0: - self.flash(message("runtime.vls.empty")) - return "empty" - if len(self.essms) >= profiles["vls"]["fire_channels"]: - self.flash(message("runtime.vls.empty")) - return "active_limit" - if not any(item is track for item in self.asm_tracks()): - self.flash(message("runtime.asm.none")) - return "invalid_target" - sam = profiles["sam"] - if track.range_nm is None or track.range_nm > sam["range_nm"]: - self.flash(message("runtime.asm.range", range=f"{sam['range_nm']:.0f}")) - return "out_of_range" - if (track.x is None or track.y is None or track.position_seen is None - or self.sim_t - track.position_seen - > sam["observation_max_age_s"]): - self.flash(message("runtime.asm.stale")) - return "stale_ref" - missile_seq = self._missile_seq(track) - tgt = next((a for a in self.asms if a.seq == missile_seq), None) - course = math.degrees(math.atan2(track.x - self.ship.x, - -(track.y - self.ship.y))) % 360.0 - self.essm_seq += 1 - self.essms.append(ESSM(self.ship.x, self.ship.y, course, tgt, - self.essm_seq, - guidance_x=track.x, guidance_y=track.y, - target_id=missile_seq, profile=sam)) - self.vls_cells -= 1 - self._emit_sound("missile_launch") - self.announce(message("runtime.essm.launched", cells=self.vls_cells), - "waffen", 2.0) - return True - - def launch_chaff(self) -> None: - tracks = self.asm_tracks() - track = tracks[min(self.asm_sel, len(tracks) - 1)] if tracks else None - self.launch_chaff_at(track) - - def launch_chaff_at(self, track): - """Deploy one softkill round against an explicit ASM observation.""" - if self.damage.station_down("opz"): - self.flash(message("runtime.chaff.disabled")) - return "opz_down" - if self.softkill_store.ready <= 0: - self.flash(message("runtime.chaff.cooldown", seconds=f"{self.chaff_cd:.0f}")) - return "not_ready" - if track is None or not any(item is track for item in self.asm_tracks()): - self.flash(message("runtime.chaff.none")) - return "invalid_target" - a = next((item for item in self.asms - if item.seq == self._missile_seq(track) - and item.state == "LAUF"), None) - profile = self._air_defense_loadout["softkill"] - if (a is not None and track.range_nm is not None - and track.position_seen is not None - and self.sim_t - track.position_seen <= self._air_defense_loadout[ - "sam"]["observation_max_age_s"] - and track.range_nm <= profile["range_nm"] - and self.softkill_store.fire()): - self.chaff_seq += 1 - threat = math.degrees(math.atan2(a.x - self.ship.x, - -(a.y - self.ship.y))) % 360.0 - cloud = chaff_physics.ChaffCloud( - self.chaff_seq, *chaff_physics.lay_position( - self.ship.x, self.ship.y, threat, self.chaff_seq)) - self.chaff_clouds = (self.chaff_clouds + [cloud])[ - -chaff_physics.MAX_CLOUDS:] - arrival = (math.hypot(a.x - cloud.x, a.y - cloud.y) - / max(config.kn_to_nm_per_s(a.speed_kn), 1e-9)) - broke = a.launch_chaff(self.rng_asm, profile, cloud_seq=cloud.seq, - arrival_s=arrival) - self.chaff_cd = min(self.softkill_store.loading, default=0.0) - self.announce(message("runtime.chaff.decoyed" if broke - else "runtime.chaff.jammed"), "waffen") - return True - else: - self.flash(message("runtime.chaff.none")) - return "stale_ref" - - def deploy_nixie(self) -> None: - """Deploy one finite towed acoustic countermeasure from own ship.""" - self.deploy_nixie_result() - - def deploy_nixie_result(self): - if len(self.nixies) >= MAX_TOWED_DECOYS: - self.flash(message("runtime.nixie.active")) - return "active_limit" - if not self.nixie_store.fire(): - self.flash(message("runtime.nixie.empty")) - return "empty" - definition = self._ownship_loadout["countermeasure"] - self.nixie_seq += 1 - self.nixies.append(TowedAcousticDecoy( - self.nixie_seq, self.ship, life_s=definition["active_life_s"], - tether_nm=definition["tether_nm"], depth_m=definition["depth_m"])) - self.announce(message("runtime.nixie.deployed", - count=self.nixie_store.remaining_total), "waffen") - return True - - def set_flak_authorized(self, authorized: bool): - """Fire-release gate for the AA gun; it never engages FLG raiders - while withheld, regardless of ammo/cooldown/range readiness.""" - if type(authorized) is not bool: - return "invalid_value" - if self.damage.station_down("weapons"): - return "weapons_down" - self.flak_authorized = authorized - return True - - def set_ciws_authorized(self, authorized: bool): - """Fire-release gate for CIWS; it never engages inbound ASMs while - withheld, regardless of ammo/cooldown/range readiness.""" - if type(authorized) is not bool: - return "invalid_value" - if self.damage.station_down("opz"): - return "opz_down" - self.ciws_authorized = authorized - return True - - def lookout_report_text(self, report: dict): - """Localizable report line: 'Bridge lookout: frigate bearing 040, 3.8 NM'.""" - return message("lookout.report", what=self.lookout_report_what(report), - bearing=f"{report['bearing']:03.0f}", - range=f"{report['range_nm']:.1f}") - - def lookout_report_what(self, report: dict): - if report["code"] is None: - return message(f"lookout.detect.{report['kind'].lower()}") - what = message(f"lookout.class.{report['code'].lower()}") - if report["type_name"]: - what = message("lookout.with_type", what=what, - type=raw_text(report["type_name"])) - return what - - def lookout_visual_what(self, label): - """What the lookout reported for a visual track label, or None.""" - _level, code, type_key = lookout_id.decode(label) - if code is None: - return None - return self.lookout_report_what(dict( - kind=None, code=code, type_name=self.lookout_type_name(type_key))) - - def lookout_type_name(self, type_key: str | None) -> str | None: - if type_key is None: - return None - profile = (self.runtime_catalog.surfaces.get(type_key) - or self.runtime_catalog.aircraft.get(type_key)) - return None if profile is None else str(profile.name) - - def radar_tracks(self) -> list: - """Compatibility view of the persistent surface/air picture.""" - tracks = [] - for t in self.air_picture.tracks(self.sim_t): - if "AIS" in t.source.upper(): - continue - derived_course, derived_speed = t.derived_motion() - tracks.append(dict( - kind=t.kind, track_id=t.track_id, target_id=t.target_id, - source=t.source, dist=t.range_nm, bearing=t.bearing, - x=t.x, y=t.y, - course=t.course if t.course is not None else derived_course, - speed_kn=derived_speed, - quality=t.display_quality(self.sim_t, self.air_picture.stale_s), - label=self.opz_track_label( - self._opz_observation_id("picture", t.track_id), - self._opz_observation_id("picture", t.track_id)[-6:]), - hostile=t.hostile, jamming=t.jamming, - age=t.age(self.sim_t), position_seen=t.position_seen, - bearing_uncertainty_deg=t.bearing_uncertainty_deg, - altitude_m=t.altitude_m, - visual=t.label if t.source == "LOOKOUT" else None)) - return tracks - - def _opz_observation_id(self, namespace: str, identity: object) -> str: - return "O-" + self._observation_key("opz-" + namespace, identity) - - def opz_track_label(self, observation_id: str, fallback: str) -> str: - """Return the one shared, operator-visible ID for an observation.""" - return self.opz_track_labels.get(observation_id, fallback) - - def contact_display_id(self, contact: Contact) -> str: - if self._sonar_ctx is not self._frigate_sonar: - # A crewed boat's contacts never carry frigate OPZ labels. - return f"K{contact.id:02d}" - observation_id = self._opz_observation_id("sonar", contact.target_id) - return self.opz_track_label(observation_id, f"K{contact.id:02d}") - - def set_opz_track_label(self, observation_id: str, label: str): - """Assign an OPZ-authored display ID without changing track identity.""" - if self.damage.station_down("opz"): - return "opz_down" - if (type(label) is not str or not 1 <= len(label) <= MAX_TRACK_DISPLAY_ID_LEN - or not label.isascii() - or any(not (char.isalnum() or char == "-") for char in label) - or not any(char.isalnum() for char in label)): - return "invalid_value" - current = {item.observation_id for item in self.opz_published_observations()} - if observation_id not in current: - return "stale_ref" - if (observation_id not in self.opz_track_labels - and len(self.opz_track_labels) >= MAX_OPZ_TRACK_LABELS): - del self.opz_track_labels[next(iter(self.opz_track_labels))] - self.opz_track_labels[observation_id] = label.upper() - return True - - def _detached_air_observations(self) -> list[OPZObservation]: - observations = [] - bindings = {} - for track in self.air_picture.tracks(self.sim_t): - # Sonar owns its release policy and detached report identity. Legacy - # save-backed mirrors are never consumed as OPZ source reports. - if track.source.startswith("SONAR") or "AIS" in track.source.upper(): - continue - observation_id = self._opz_observation_id("picture", track.track_id) - classification = (self.opz_fusion.classifications.get(observation_id) - if (track.source.startswith("RADAR") - or track.source == "HOJ") - else self.released_esm_labels().get(track.track_id) - if track.source == "ESM" else None) - kind = "UNKNOWN" if track.source == "ESM" else track.kind - derived_course, derived_speed = track.derived_motion() - observation = OPZObservation( - observation_id, track.source, kind, track.bearing, track.range_nm, - track.x, track.y, - track.course if track.course is not None else derived_course, - track.quality, track.last_seen, - self.opz_track_label(observation_id, observation_id[-6:]), classification, - track.bearing_uncertainty_deg, track.position_seen, track.jamming, - speed_kn=derived_speed, altitude_m=track.altitude_m, - visual=track.label if track.source == "LOOKOUT" else None) - observations.append(observation) - bindings[observation_id] = track - self._opz_source_bindings = bindings - return observations - - def _sonar_opz_observations(self, released_only: bool) -> list[OPZObservation]: - """Return detached Sonar reports without carrying contact identity.""" - observations = [] - for _, contact in sorted(self.sonar.contacts.items()): - if ((released_only and not contact.released_to_opz) - or not 0.0 <= self.sim_t - contact.last_seen - < config.SONAR_CONTACT_LOST_S): - continue - observation_id = self._opz_observation_id("sonar", contact.target_id) - fixes = tuple(fix for fix in contact.active_fixes(self.sim_t) - if fix["source"] not in ("DIPPING", "SONOBUOY")) - ship_passive_seen = (contact._bearing_filter_t - if contact._bearing_filter_t is not None - else contact.last_seen) - ship_passive_current = (contact.passive_bearing is not None - and 0 <= self.sim_t - ship_passive_seen - < config.SONAR_CONTACT_LOST_S) - if released_only and not ship_passive_current and not fixes: - continue - fix_by_source = {item["source"]: item for item in fixes} - fix = max(fixes, key=lambda item: (item["fixed_at"], item["source"])) \ - if fixes else None - x = fix["x"] if fix is not None else None - y = fix["y"] if fix is not None else None - observer_x = (contact.ship_observer_x - if ship_passive_current and contact.ship_observer_x is not None - else self.ship.x if ship_passive_current - else contact.observer_x) - observer_y = (contact.ship_observer_y - if ship_passive_current and contact.ship_observer_y is not None - else self.ship.y if ship_passive_current - else contact.observer_y) - bearing_uncertainty_deg = contact.bearing_uncertainty_deg - if x is not None and y is not None: - dx, dy = x - self.ship.x, y - self.ship.y - bearing = math.degrees(math.atan2(dx, -dy)) % 360.0 - range_nm = math.hypot(dx, dy) - source = "SONAR-" + fix["source"] - elif ship_passive_current: - bearing = contact.passive_bearing - range_nm = None - source = contact.passive_source - elif not released_only and contact.dip_bearing is not None: - bearing = contact.dip_bearing - range_nm = None - source = "SONAR-DIP-BRG" - observer_x, observer_y = contact.dip_observer_x, contact.dip_observer_y - bearing_uncertainty_deg = contact.dip_bearing_uncertainty_deg - else: - continue - course = contact.tma_course if "TMA" in fix_by_source else None - speed = contact.tma_speed if "TMA" in fix_by_source else None - depth = (contact.depth_est - if "PING" in fix_by_source or "DIPPING" in fix_by_source - else None) - observation = OPZObservation( - observation_id, source, "UNKNOWN", bearing, range_nm, x, y, course, - max(contact.quality, contact.confidence), - (fix["measured_at"] if fix is not None - else ship_passive_seen if ship_passive_current - else contact.last_seen), - self.opz_track_label(observation_id, f"K{contact.id:02d}"), (contact.player_class - if contact.player_class in config.PLAYER_CLASSES - else None), - bearing_uncertainty_deg, - fix["measured_at"] if fix is not None else None, - depth_m=depth, speed_kn=speed, - observer_x=observer_x, observer_y=observer_y, - released_to_opz=contact.released_to_opz) - observations.append(observation) - self._opz_source_bindings[observation_id] = contact - return observations - - def private_sonar_observations(self) -> tuple[OPZObservation, ...]: - """Fresh private acoustic reports for role-specific projections.""" - return tuple((*self._sonar_opz_observations(False), - *self._buoy_opz_observations(released_only=False))) - - def _helicopter_opz_observations(self) -> list[OPZObservation]: - """The helicopter's separately released, measured dip reports.""" - reports = [] - for _, contact in sorted(self.sonar.contacts.items()): - if not contact.dip_released_to_opz: - continue - passive = (contact.dip_bearing is not None - and contact.dip_last_seen is not None - and 0 <= self.sim_t - contact.dip_last_seen - < config.SONAR_CONTACT_LOST_S) - fixes = [fix for fix in contact.active_fixes(self.sim_t) - if fix["source"] == "DIPPING"] - fix = max(fixes, key=lambda item: item["fixed_at"]) if fixes else None - if not passive and fix is None: - continue - origin_x = contact.dip_observer_x if passive else contact.observer_x - origin_y = contact.dip_observer_y if passive else contact.observer_y - bearing = (contact.dip_bearing if passive else math.degrees( - math.atan2(fix["x"] - origin_x, -(fix["y"] - origin_y))) % 360.0) - range_nm = (None if passive else math.hypot( - fix["x"] - origin_x, fix["y"] - origin_y)) - observation_id = self._opz_observation_id("sonar-dip", contact.target_id) - reports.append(OPZObservation( - observation_id, - "SONAR-DIP-BRG" if passive else "SONAR-DIPPING", - "UNKNOWN", bearing, range_nm, - None if passive else fix["x"], - None if passive else fix["y"], None, - max(contact.quality, contact.confidence), - max(contact.dip_last_seen if passive else 0.0, - fix["measured_at"] if fix is not None else 0.0), - self.opz_track_label(observation_id, f"K{contact.id:02d} H"), - contact.player_class if contact.player_class in config.PLAYER_CLASSES - else None, - contact.dip_bearing_uncertainty_deg if passive else None, - fix["measured_at"] if not passive else None, - depth_m=fix["depth_m"] if not passive else None, - observer_x=origin_x, observer_y=origin_y, - released_to_opz=True)) - self._opz_source_bindings[observation_id] = contact - return reports - - def _buoy_opz_observations(self, released_only=True) -> list[OPZObservation]: - reports = [] - for _, contact in sorted(self.sonar.contacts.items()): - if released_only and (not contact.helo_qualified - or not contact.buoy_released_to_opz): - continue - for seq, row in sorted(contact.buoy_reports.items()): - if not 0 <= self.sim_t - row["measured_at"] < config.SONAR_CONTACT_LOST_S: - continue - observation_id = self._opz_observation_id( - f"sonar-buoy-{seq}", contact.target_id) - reports.append(OPZObservation( - observation_id, f"SONAR-BUOY-{seq:02d}-{row['mode']}", "UNKNOWN", - row["bearing"], row["range_nm"], row["x"], row["y"], - None, row["quality"], row["measured_at"], - self.opz_track_label(observation_id, f"B{seq:02d} K{contact.id:02d}"), - contact.player_class, row["bearing_uncertainty_deg"], - row["measured_at"] if row["x"] is not None else None, - observer_x=row["observer_x"], observer_y=row["observer_y"], - released_to_opz=bool(contact.helo_qualified - and contact.buoy_released_to_opz))) - self._opz_source_bindings[observation_id] = contact - return reports - - def opz_source_observations(self) -> tuple[OPZObservation, ...]: - if id(self.world) != self._opz_world_identity: - self.opz_fusion.clear() - self.opz_track_labels.clear() - self.opz_selected_track_id = None - self._opz_world_identity = id(self.world) - observations = self._detached_air_observations() - observations.extend(self._sonar_opz_observations(True)) - observations.extend(self._helicopter_opz_observations()) - observations.extend(self._buoy_opz_observations()) - return tuple(sorted(observations, key=lambda item: item.observation_id)) - - def opz_published_observations(self) -> tuple[OPZObservation, ...]: - """Shared OPZ picture, unaffected by host-local suppression.""" - observations = self.opz_source_observations() - self.opz_fusion.prune(observations) - fused = [self.opz_fusion.computed(item, observations, self.sim_t, - self.air_picture.stale_s) - for item in self.opz_fusion.fusions.values()] - fused = [replace(item, label=self.opz_track_label( - item.observation_id, item.label)) for item in fused if item is not None] - return tuple(sorted((*observations, *(item for item in fused if item is not None)), - key=lambda item: item.observation_id)) - - def asm_tracks(self) -> list: - return [t for t in self.air_picture.tracks(self.sim_t, ("ASM",)) - if t.source in ("RADAR", "RADAR-L", "HOJ", "DATALINK")] - - def opz_tracks(self) -> list: - """Host-visible OPZ reports, with local suppression applied.""" - observations = self.opz_source_observations() - visible = self.opz_fusion.visible(observations, self.sim_t, - self.air_picture.stale_s) - return [replace(item, label=self.opz_track_label( - item.observation_id, item.label)) for item in visible] - - def filtered_opz_tracks(self) -> list: - """Presentation-only OPZ register filter; never alters observations.""" - tracks = self.opz_tracks() - selected = getattr(self, "opz_contact_filter", "ALL") - if selected == "ALL": - return tracks - if selected in ("RADAR", "SONAR"): - return [track for track in tracks - if track.source.startswith(selected)] - if selected == "ESM": - return [track for track in tracks if track.source == "ESM"] - kind_domains = { - "AIS": "SURFACE", "SURFACE": "SURFACE", "SUB": "SUBSURFACE", - "TORP": "SUBSURFACE", "FLG": "AIR", "ASM": "AIR", - } - # Sonar reports carry no sensor domain; the operator's classification - # (an annotation, not truth) sorts them into the display filter. - class_domains = { - "U_BOOT": "SUBSURFACE", "TORPEDO": "SUBSURFACE", - "KAMPFSCHIFF": "SURFACE", "FAHRZEUG": "SURFACE", "FLUGZEUG": "AIR", - } - return [track for track in tracks - if kind_domains.get(track.kind, class_domains.get( - track.classification, "UNKNOWN")) == selected] - - def _cycle_opz_contact_filter(self) -> None: - filters = ("ALL", "RADAR", "SONAR", "ESM", "AIR", "SURFACE", - "SUBSURFACE") - current = getattr(self, "opz_contact_filter", "ALL") - index = filters.index(current) if current in filters else 0 - self.opz_contact_filter = filters[(index + 1) % len(filters)] - tracks = self.filtered_opz_tracks() - if not any(track.track_id == self.opz_selected_track_id - for track in tracks): - self.opz_selected_track_id = tracks[0].track_id if tracks else None - self.flash(message( - "runtime.cic.filter", - filter=display_value("contact_filter", self.opz_contact_filter, - self.tr)), 1.5) - - # --- Shared operator plot layer ---------------------------------------- - - PLOT_TOOL_KEYS = {pygame.K_m: "mark", pygame.K_r: "ruler", - pygame.K_b: "bearing", pygame.K_c: "circle", - pygame.K_d: "dr"} - PLOT_CURSOR_STEP_PX = 6 - PLOT_CURSOR_STEP_FAST_PX = 40 - PLOT_PICK_PX = 12 - - def _reset_plot_ui(self) -> None: - """Transient plot-mode state; the drawing itself lives in ``plot``.""" - self.plot_mode = False - self.plot_tool = "mark" - self.plot_cursor = (0.0, 0.0) - self.plot_anchor = None - self._plot_dr_pending = None - - # ``layer`` selects another crew's plot (the crewed submarine's own); - # by default the frigate crew's shared plot. - def plot_add(self, kind, x, y, label="", *, layer=None, **fields): - """Add one crew drawing at sim time now; returns its id or an error.""" - if kind not in plot_geometry.KINDS: - return "invalid_value" - target = self.plot if layer is None else layer - return target.add({"kind": kind, "label": label, - "t": float(self.sim_t), "x": x, "y": y, **fields}) - - def plot_remove(self, object_id, *, layer=None): - return True if (self.plot if layer is None else layer).remove(object_id) else "stale_ref" - - def plot_clear(self, *, layer=None): - (self.plot if layer is None else layer).clear() - return True - - def plot_relabel(self, object_id, label, *, layer=None): - if not plot_geometry.valid_label(label): - return "invalid_value" - return True if (self.plot if layer is None else layer).relabel(object_id, label) else "stale_ref" - - def _plot_view(self): - """The chart camera of the current station, or None without a chart.""" - if self.station is Station.OPZ: - self._configure_opz_map_view() - return self.opz_map_view - if self._map_station_visible(): - self.map_view.set_rect(config.MAP_RECT) - return self.map_view - return None - - def toggle_plot_mode(self): - if self.plot_mode: - self._reset_plot_ui() - self.flash(message("plot.flash.off"), 1.5) - return False - if self._plot_view() is None: - self.flash(message("plot.flash.no_chart"), 2.0) - return None - self._clear_station_input() - self.plot_mode = True - self.plot_anchor = None - self.plot_cursor = (self.ship.x, self.ship.y) - self.flash(message("plot.flash.on"), 2.0) - return True - - def _plot_flash_result(self, result) -> None: - if isinstance(result, str): - self.flash(message("plot.flash.full" if result == "full" - else "plot.flash.invalid"), 2.0) - else: - item = next((obj for obj in self.plot.objects if obj["id"] == result), None) - if item is not None: - self.flash(message("plot.flash.added", label=item["label"]), 1.5) - - def _plot_commit_point(self, x=None, y=None) -> None: - """Enter/click: place the cursor point for the active tool.""" - if x is not None: - self.plot_cursor = (x, y) - cx, cy = self.plot_cursor - tool = self.plot_tool - if tool == "mark": - self._plot_flash_result(self.plot_add("mark", cx, cy)) - return - if tool == "bearing": - brg, dist = plot_geometry.bearing_distance(self.ship.x, self.ship.y, cx, cy) - result = (self.plot_add("bearing", self.ship.x, self.ship.y, - bearing=round(brg, 1) % 360.0) - if dist > 0.0 else "invalid_value") - self._plot_flash_result(result) - return - if self.plot_anchor is None: - self.plot_anchor = (cx, cy) - self.flash(message("plot.flash.second_point"), 2.0) - return - ax, ay = self.plot_anchor - self.plot_anchor = None - brg, dist = plot_geometry.bearing_distance(ax, ay, cx, cy) - if tool == "ruler": - result = self.plot_add("ruler", ax, ay, x2=cx, y2=cy) - elif tool == "circle": - result = self.plot_add("circle", ax, ay, radius_nm=round(dist, 2)) - else: - if dist <= 0.0: - self._plot_flash_result("invalid_value") - return - self._plot_dr_pending = (ax, ay, round(brg, 1) % 360.0) - self._begin_numeric_input("plot_speed") - return - self._plot_flash_result(result) - - def selected_opz_track(self): - return next((track for track in self.opz_tracks() - if track.track_id == self.opz_selected_track_id), None) - - def designate_opz_track(self) -> None: - """Hand an observed CIC track to weapons without exposing world truth.""" - track = self.selected_opz_track() - if track is None: - self.flash(message("runtime.cic.none")) - return - result = self.designate_opz_observation(track.observation_id) - if result is not True: - ambiguous = (track.source == "FUSION" - and len(self._fusion_contacts(track)) > 1) - self.flash(message("runtime.cic.fusion_ambiguous" if ambiguous - else "runtime.cic.no_solution")) - return - self.selected_contact = self.target - self.flash(message("runtime.cic.designated", track=track.track_id)) - - def designate_opz_observation(self, observation_id: str): - if self.damage.station_down("opz"): - return "opz_down" - track = next((item for item in self.opz_published_observations() - if item.observation_id == observation_id), None) - if track is None: - return "stale_ref" - if track.source == "FUSION": - # A fusion hands over its sonar report only when that is unique. - contacts = self._fusion_contacts(track) - contact = contacts[0] if len(contacts) == 1 else None - else: - bound = self._opz_source_bindings.get(track.observation_id) - contact = (bound if isinstance(bound, Contact) else - next((c for c in self.sonar.contacts.values() - if getattr(bound, "target_id", None) == c.target_id), - None)) - if (contact is None or self.sonar.contacts.get(contact.target_id) is not contact - or not 0 <= self.sim_t - contact.last_seen - < config.SONAR_CONTACT_LOST_S): - return "no_solution" - self.target = contact - return True - - def _fusion_contacts(self, track) -> list: - """Distinct sonar contacts behind the member reports of one fusion.""" - contacts = [] - for member in getattr(track, "members", ()): - bound = self._opz_source_bindings.get(member) - if isinstance(bound, Contact) and not any( - item is bound for item in contacts): - contacts.append(bound) - return contacts - - def opz_affiliation(self, track_id: str) -> str: - if track_id not in self.opz_affiliations: - source_key = getattr(self._opz_source_bindings.get(track_id), - "track_id", None) - bound = self._opz_source_bindings.get(track_id) - if isinstance(bound, Contact): - legacy_key = f"U-{bound.target_id}" - if legacy_key in self.opz_affiliations: - track_id = legacy_key - if source_key in self.opz_affiliations: - track_id = source_key - else: - opaque = next((key for key, source in self._opz_source_bindings.items() - if getattr(source, "track_id", None) == track_id), None) - if opaque is not None: - track_id = opaque - value = self.opz_fusion.fusion_affiliations.get( - track_id, self.opz_affiliations.get(track_id, "UNKNOWN")) - return value if value in config.NATO_AFFILIATIONS else "UNKNOWN" - - def opz_source_classification(self, observation_id: str) -> str | None: - return source_classification(observation_id, - self.opz_published_observations()) - - def classify_sonar_contact(self, contact, classification): - if self._sonar_down(): - return "sonar_down" - if classification is not None and classification not in config.PLAYER_CLASSES: - return "invalid_value" - if (not isinstance(contact, Contact) - or self.sonar.contacts.get(contact.target_id) is not contact): - return "stale_ref" - if not 0 <= self.sim_t - contact.last_seen < config.SONAR_CONTACT_LOST_S: - return "stale_ref" - contact.player_class = classification - return True - - def release_sonar_contact(self, contact, released: bool, *, source="sonar"): - if type(released) is not bool: - return "invalid_value" - if source not in ("sonar", "helicopter", "buoy"): - return "invalid_value" - if self.damage.station_down("sonar"): - return "sonar_down" - if (not isinstance(contact, Contact) - or self.sonar.contacts.get(contact.target_id) is not contact - or not 0 <= self.sim_t - contact.last_seen - < config.SONAR_CONTACT_LOST_S): - return "stale_ref" - if source == "helicopter": - dip_current = (contact.dip_last_seen is not None - and 0 <= self.sim_t - contact.dip_last_seen - < config.SONAR_CONTACT_LOST_S) - dip_fix = any(fix["source"] == "DIPPING" - for fix in contact.active_fixes(self.sim_t)) - if not dip_current and not dip_fix: - return "stale_ref" - if released and not contact.helo_qualified: - return "not_qualified" - contact.dip_released_to_opz = released - elif source == "buoy": - if not any(0 <= self.sim_t - row["measured_at"] < config.SONAR_CONTACT_LOST_S - for row in contact.buoy_reports.values()): - return "stale_ref" - if released and not contact.helo_qualified: - return "not_qualified" - contact.buoy_released_to_opz = released - else: - contact.released_to_opz = released - return True - - def qualify_helicopter_contact(self, contact, qualified: bool): - if type(qualified) is not bool: - return "invalid_value" - if self.damage.station_down("sonar"): - return "sonar_down" - if (not isinstance(contact, Contact) - or self.sonar.contacts.get(contact.target_id) is not contact - or not 0 <= self.sim_t - contact.last_seen < config.SONAR_CONTACT_LOST_S): - return "stale_ref" - if not (any(0 <= self.sim_t - row["measured_at"] - < config.SONAR_CONTACT_LOST_S - for row in contact.buoy_reports.values()) - or contact.dip_last_seen is not None - and 0 <= self.sim_t - contact.dip_last_seen - < config.SONAR_CONTACT_LOST_S - or any(fix["source"] == "DIPPING" - for fix in contact.active_fixes(self.sim_t))): - return "stale_ref" - contact.helo_qualified = qualified - if not qualified: - contact.dip_released_to_opz = False - contact.buoy_released_to_opz = False - return True - - def classify_opz_observation(self, observation_id: str, classification): - if self.damage.station_down("opz"): - return "opz_down" - if classification is not None and classification not in config.PLAYER_CLASSES: - return "invalid_value" - track = next((item for item in self.opz_published_observations() - if item.observation_id == observation_id), None) - if track is None: - return "stale_ref" - if track.source.startswith("SONAR"): - # A sonar-origin contact is classified on the contact itself - # (shared with the Sonar/Helicopter stations), not in the OPZ - # fusion overlay used for radar-only tracks. - contact = self._opz_source_bindings.get(observation_id) - if (not isinstance(contact, Contact) - or self.sonar.contacts.get(contact.target_id) is not contact): - return "stale_ref" - return self.classify_sonar_contact(contact, classification) - if not (track.source.startswith("RADAR") - or track.source in ("HOJ", "FUSION")): - return "source_owned" - if classification is None: - self.opz_fusion.classifications.pop(observation_id, None) - else: - self.opz_fusion.classifications[observation_id] = classification - return True - - def affiliate_opz_observation(self, observation_id: str, affiliation: str): - if self.damage.station_down("opz"): - return "opz_down" - if affiliation not in config.NATO_AFFILIATIONS: - return "invalid_value" - track = next((item for item in self.opz_published_observations() - if item.observation_id == observation_id), None) - if track is None: - return "stale_ref" - destination = (self.opz_fusion.fusion_affiliations - if track.source == "FUSION" else self.opz_affiliations) - destination[observation_id] = affiliation - self._sync_live_engagement_hold(observation_id, track.track_id, affiliation) - return True - - def _live_aircraft_icao_for_track_id(self, track_id) -> str | None: - """Resolve an air-picture 'A-' track id to its live ADS-B icao24, - if that id happens to be bound to a real LiveAircraft rather than a - simulated Flight (both intentionally share the same id namespace).""" - if not isinstance(track_id, str) or not track_id.startswith("A-"): - return None - try: - seq = int(track_id[2:]) - except ValueError: - return None - return next((icao24 for icao24, aircraft in self.live_traffic.aircraft.items() - if aircraft.seq == seq), None) - - def _sync_live_engagement_hold(self, observation_id: str, display_id: str, - affiliation: str) -> None: - """Real ADS-B traffic is indistinguishable from a simulated contact, - so a manual HOSTILE call on it is a possible political incident, not - a weapons release. Any prior engagement confirmation is revoked here - and must be freshly re-affirmed (confirm_live_engagement) every time - the classification turns HOSTILE again.""" - bound = self._opz_source_bindings.get(observation_id) - icao24 = self._live_aircraft_icao_for_track_id(getattr(bound, "track_id", None)) - if icao24 is None: - return - self.live_engage_authorized.discard(icao24) - if affiliation == "HOSTILE": - self.live_engage_confirm_pending = icao24 - self.flash(message("runtime.cic.hostile_confirm_required", - track=display_id), 5.0) - self.feed.add(self.world.format_time(), "opz", - message("runtime.cic.hostile_confirm_required", - track=display_id)) - elif self.live_engage_confirm_pending == icao24: - self.live_engage_confirm_pending = None - - def live_engagement_pending_for_observation(self, observation_id: str) -> bool: - """Whether this OPZ observation is the live contact currently - awaiting an attack confirmation (see _sync_live_engagement_hold).""" - if self.live_engage_confirm_pending is None: - return False - bound = self._opz_source_bindings.get(observation_id) - icao24 = self._live_aircraft_icao_for_track_id(getattr(bound, "track_id", None)) - return icao24 == self.live_engage_confirm_pending - - def confirm_live_engagement(self) -> bool: - """OPZ 'Enter': explicit player affirmation to fire on the live, - real-world contact currently awaiting confirmation after being - classified HOSTILE. See _sync_live_engagement_hold.""" - icao24 = self.live_engage_confirm_pending - if icao24 is None or icao24 not in self.live_traffic.aircraft: - return False - self.live_engage_authorized.add(icao24) - self.live_engage_confirm_pending = None - self.flash(message("runtime.cic.hostile_confirmed"), 2.5) - self.feed.add(self.world.format_time(), "opz", - message("runtime.cic.hostile_confirmed")) - return True - - def create_opz_fusion(self, observation_ids): - if self.damage.station_down("opz"): - return "opz_down" - if (type(observation_ids) not in (list, tuple) - or not config.OPZ_FUSION_MEMBER_MIN <= len(observation_ids) - <= config.OPZ_FUSION_MEMBER_MAX - or len(set(observation_ids)) != len(observation_ids)): - return "invalid_value" - sources = self.opz_source_observations() - current = {item.observation_id for item in sources} - if any(key not in current for key in observation_ids): - return "stale_ref" - self.opz_fusion.marked = set(observation_ids) - fusion = self.opz_fusion.create(sources) - if fusion is None: - return "fusion_rejected" - self.opz_selected_track_id = fusion.fusion_id - return True - - def dissolve_opz_fusion(self, observation_id: str): - if self.damage.station_down("opz"): - return "opz_down" - if observation_id not in self.opz_fusion.fusions: - return "stale_ref" - self.opz_fusion.dissolve(observation_id) - if self.opz_selected_track_id == observation_id: - self.opz_selected_track_id = None - return True - - def _cycle_opz_track(self, delta: int) -> None: - tracks = self.filtered_opz_tracks() - if not tracks: - self.opz_selected_track_id = None - return - ids = [track.track_id for track in tracks] - try: - index = ids.index(self.opz_selected_track_id) - except ValueError: - index = -1 if delta > 0 else 0 - self.opz_selected_track_id = ids[(index + delta) % len(ids)] - - def _cycle_opz_affiliation(self) -> None: - track = self.selected_opz_track() - if track is None: - self.flash(message("runtime.cic.none_select")) - return - current = self.opz_affiliation(track.track_id) - order = config.NATO_AFFILIATIONS - value = order[(order.index(current) + 1) % len(order)] - if self.affiliate_opz_observation(track.track_id, value) is not True: - return - self.flash(message("runtime.cic.affiliation", track=track.track_id, - affiliation=display_value("affiliation", value, self.tr)), 2.0) - - def _cycle_opz_classification(self) -> None: - track = self.selected_opz_track() - if track is None: - self.flash(message("runtime.cic.none_select")) - return - if track.source.startswith("SONAR"): - contact = self._opz_source_bindings.get(track.observation_id) - if not isinstance(contact, Contact): - self.flash(message("runtime.cic.source_owned")) - return - current = contact.player_class - elif (track.source.startswith("RADAR") - or track.source in ("HOJ", "FUSION")): - current = self.opz_fusion.classifications.get(track.observation_id) - else: - self.flash(message("runtime.cic.source_owned")) - return - order = (None, *config.PLAYER_CLASSES) - value = order[(order.index(current) + 1) % len(order)] - self.classify_opz_observation(track.observation_id, value) - - def _toggle_opz_mark(self) -> None: - track = self.selected_opz_track() - if track is None or track.source == "FUSION": - return - if track.observation_id in self.opz_fusion.marked: - self.opz_fusion.marked.remove(track.observation_id) - else: - self.opz_fusion.marked.add(track.observation_id) - - def _create_opz_fusion(self) -> None: - result = self.create_opz_fusion(tuple(self.opz_fusion.marked)) - if result is not True: - self.flash(message("runtime.cic.fusion_rejected")) - - def _dissolve_opz_fusion(self) -> None: - if self.opz_selected_track_id: - self.dissolve_opz_fusion(self.opz_selected_track_id) - - def _toggle_opz_suppression(self) -> None: - track = self.selected_opz_track() - if track is None: - return - key = track.observation_id - if key in self.opz_fusion.suppressed: - self.opz_fusion.suppressed.remove(key) - else: - self.opz_fusion.suppressed.add(key) - - def eloka_tracks(self) -> tuple: - """Return detached passive intercepts in stable picture order.""" - return self.esm_picture.tracks(self.sim_t) - - def eloka_visible_tracks(self) -> tuple: - """Return the one filtered/sorted list used by ELOKA presentation.""" - return filter_and_sort_tracks( - self.eloka_tracks(), self.sim_t, self.eloka_display_analysis, - status=self.eloka_status_filter, - minimum_threat=self.eloka_threat_filter, - band=self.eloka_band_filter, - annotated_keys=self.eloka_annotations, - jamming_keys=(channel.track_key - for channel in self.ecm_jammer.channels)) - - def _reconcile_eloka_selection(self) -> None: - visible = self.eloka_visible_tracks() - keys = {track.track_key for track in visible} - if self.eloka_selected_track_key not in keys: - self.eloka_selected_track_key = (visible[0].track_key - if visible else None) - - def _cycle_eloka_filter(self, kind: str) -> None: - names = { - "status": ("eloka_status_filter", - ("OPERATIONAL", "LIVE", "MEMORY", "ALL")), - "threat": ("eloka_threat_filter", - ("ALL", "LOW", "MEDIUM", "HIGH", "CRITICAL")), - "band": ("eloka_band_filter", - ("ALL", "A_C", "D", "E_F", "G_H", "I_J", "K")), - } - attribute, values = names[kind] - current = getattr(self, attribute) - setattr(self, attribute, values[(values.index(current) + 1) % len(values)]) - self._reconcile_eloka_selection() - - def selected_eloka_track(self): - return next((track for track in self.eloka_tracks() - if track.track_key == self.eloka_selected_track_key), None) - - def _cycle_eloka_track(self, delta: int) -> None: - if self.damage.station_down("opz"): - return - tracks = self.eloka_visible_tracks() - if not tracks: - self.eloka_selected_track_key = None - return - keys = [track.track_key for track in tracks] - try: - index = keys.index(self.eloka_selected_track_key) - except ValueError: - index = -1 if delta > 0 else 0 - self.eloka_selected_track_key = keys[(index + delta) % len(keys)] - - def eloka_candidates(self, track=None) -> tuple: - if self.damage.station_down("opz"): - return () - track = track or self.selected_eloka_track() - return (() if track is None else - rank_emitters(track, self.runtime_catalog.emitters)) - - def eloka_display_candidates(self, track=None) -> tuple: - """Emitter choices shown to the operator: ranked with scores only as - a training aid; otherwise an unranked library range lookup.""" - if self.operator_assist(): - return self.eloka_candidates(track) - if self.damage.station_down("opz"): - return () - track = track or self.selected_eloka_track() - return (() if track is None else - library_emitters(track, self.runtime_catalog.emitters)) - - def eloka_display_analysis(self, track=None): - """Radar type/threat inferred from the catalog: training aid only.""" - return self.eloka_analysis(track) if self.operator_assist() else None - - def eloka_display_range(self, track): - return self.eloka_range_estimate(track) if self.operator_assist() else None - - ELOKA_ANALYSIS_CACHE_MAX = 256 - - def eloka_analysis(self, track=None): - track = track or self.selected_eloka_track() - if track is None: - return None - # The ranking depends only on the measured fingerprint and the - # immutable runtime catalog; memoize it (bounded, never saved). - emitters = self.runtime_catalog.emitters - if self.__dict__.get("_eloka_analysis_owner") is not emitters: - self._eloka_analysis_owner = emitters - self._eloka_analysis_cache = {} - key = (track.frequency_hz, track.prf_hz, track.modulation_code) - cache = self._eloka_analysis_cache - result = cache.get(key) - if result is None: - if len(cache) >= self.ELOKA_ANALYSIS_CACHE_MAX: - cache.clear() - result = cache[key] = analyze_signal(track, emitters) - return result - - def eloka_range_estimate(self, track=None) -> float | None: - """Range implied by the intercept's peak level, assuming the power - class of the best-ranked catalog hypothesis (never emitter truth).""" - track = track or self.selected_eloka_track() - analysis = self.eloka_analysis(track) - if analysis is None or not analysis.candidates or track.signal_db <= 0.0: - return None - emitter = self.runtime_catalog.emitters.get( - analysis.candidates[0].emitter_key) - return estimated_range_nm(track, getattr(emitter, "power_class", "medium")) - - def deploy_jamming(self, track, technique=None): - if self.damage.station_down("opz"): - return "opz_down" - if track is None or not any(item is track for item in self.eloka_tracks()): - return "stale_ref" - return self.ecm_jammer.deploy_jamming( - track, self.sim_t, technique=technique) - - def set_jamming_technique(self, track, technique: str): - if self.damage.station_down("opz"): - return "opz_down" - if track is None or not any(item is track for item in self.eloka_tracks()): - return "stale_ref" - return self.ecm_jammer.set_technique(track, technique, self.sim_t) - - def _cycle_jamming_technique(self, track) -> str | None: - if track is None: - return None - channel = next((item for item in self.ecm_jammer.channels - if item.track_key == track.track_key), None) - current = (channel.technique if channel is not None else - self.ecm_jammer.recommended_technique(track)) - index = ECM_TECHNIQUES.index(current) - technique = ECM_TECHNIQUES[(index + 1) % len(ECM_TECHNIQUES)] - return (technique if self.set_jamming_technique(track, technique) is True - else None) - - def set_jamming(self, track, enabled: bool): - if type(enabled) is not bool: - return "invalid" - active = (track is not None and any( - channel.track_key == track.track_key - for channel in self.ecm_jammer.channels)) - if active == enabled: - return True - return self.deploy_jamming(track) - - def set_ecm_auto(self, enabled: bool): - if type(enabled) is not bool: - return "invalid" - if self.damage.station_down("opz"): - return "opz_down" - self.ecm_jammer.auto_enabled = enabled - if not enabled: - self.ecm_jammer.channels = [channel for channel in - self.ecm_jammer.channels if not channel.automatic] - return True - - def eloka_annotation(self, track_key: str) -> str | None: - emitter_key = self.eloka_annotations.get(track_key) - emitter = self.runtime_catalog.emitters.get(emitter_key) - return emitter_key if emitter is not None and emitter.domain == "radar" else None - - def eloka_emitter_name(self, emitter_key: str | None) -> str | None: - """Display name of the platform owning an ESM emitter, or None.""" - if not isinstance(emitter_key, str): - return None - return self.runtime_catalog.emitter_name(emitter_key) - - def eloka_annotation_name(self, track_key: str) -> str | None: - """Operator annotation resolved to the owning platform's name.""" - return self.eloka_emitter_name(self.eloka_annotation(track_key)) - - def annotate_eloka_intercept(self, track, emitter_key: str): - if self.damage.station_down("opz"): - return "opz_down" - if not any(item is track for item in self.eloka_tracks()): - return "stale_ref" - candidates = {item.emitter_key for item in rank_emitters( - track, self.runtime_catalog.emitters, - maximum=len(self.runtime_catalog.emitters))} - if type(emitter_key) is not str or emitter_key not in candidates: - return "stale_ref" - previous = self.eloka_annotation(track.track_key) - if previous is not None and previous != emitter_key: - self._remove_released_esm(track.track_key, previous) - self.eloka_annotations[track.track_key] = emitter_key - while len(self.eloka_annotations) > ESM_MAX_ANNOTATIONS: - del self.eloka_annotations[min(self.eloka_annotations)] - self._publish_released_esm() - return True - - def clear_eloka_annotation(self, track): - if self.damage.station_down("opz"): - return "opz_down" - if not any(item is track for item in self.eloka_tracks()): - return "stale_ref" - previous = self.eloka_annotation(track.track_key) - self.eloka_annotations.pop(track.track_key, None) - if previous is not None: - self._remove_released_esm(track.track_key, previous) - self._publish_released_esm() - return True - - def _remove_released_esm(self, track_key: str, emitter_key: str) -> None: - identity = self._observation_key( - "esm-release", f"{track_key}:{emitter_key}") - self.air_picture._tracks.pop(f"E-{identity}", None) - - def _cycle_eloka_annotation(self) -> None: - if self.damage.station_down("opz"): - self.flash(message("runtime.eloka.disabled")) - return - track = self.selected_eloka_track() - if track is None: - self.flash(message("runtime.eloka.none_select")) - return - # Training: likeliest first. Otherwise the library range lookup in - # name order, so the first press does not reveal the best match. - choices = ([candidate.emitter_key for candidate in rank_emitters( - track, self.runtime_catalog.emitters, - maximum=len(self.runtime_catalog.emitters))] - if self.operator_assist() else sorted( - (candidate.emitter_key for candidate in library_emitters( - track, self.runtime_catalog.emitters, - maximum=len(self.runtime_catalog.emitters))), - key=lambda key: (str(self.eloka_emitter_name(key) or key), key))) - current = self.eloka_annotation(track.track_key) - index = choices.index(current) if current in choices else -1 - if index + 1 >= len(choices): - self.clear_eloka_annotation(track) - assignment = self.tr("common.unknown") - else: - key = choices[index + 1] - self.annotate_eloka_intercept(track, key) - assignment = self.eloka_emitter_name(key) or key - self.flash(message("runtime.eloka.annotation", - track=track.track_key, assignment=assignment), 2.0) - - def _publish_released_esm(self) -> None: - """Release only operator-classified, bearing-only ESM observations.""" - for track in self.eloka_tracks(): - emitter_key = self.eloka_annotation(track.track_key) - label = self.eloka_emitter_name(emitter_key) - if emitter_key is None or label is None: - continue - identity = self._observation_key( - "esm-release", f"{track.track_key}:{emitter_key}") - self.air_picture.observe( - track_id=f"E-{identity}", kind="UNKNOWN", target_id=0, - source="ESM", bearing=track.bearing, range_nm=None, - observer_x=track.observer_x, observer_y=track.observer_y, - course=None, quality=track.quality, now=track.last_seen, - label=label, hostile=False, - bearing_uncertainty_deg=track.bearing_uncertainty_deg) - - def released_esm_labels(self) -> dict[str, str]: - """Return detached operator-approved labels keyed by public track ID.""" - released = {} - for track in self.eloka_tracks(): - emitter_key = self.eloka_annotation(track.track_key) - label = self.eloka_emitter_name(emitter_key) - if emitter_key is not None and label is not None: - identity = self._observation_key( - "esm-release", f"{track.track_key}:{emitter_key}") - released[f"E-{identity}"] = label - return released - - def eloka_correlations(self, track=None) -> tuple: - """Compare ESM and public radar evidence without target identity.""" - if self.damage.station_down("opz"): - return () - track = track or self.selected_eloka_track() - if track is None: - return () - raw_evidence = [] - for observed in self.air_picture._tracks.values(): - if (not isinstance(observed.source, str) - or not observed.source.startswith("RADAR") - or "AIS" in observed.source.upper()): - continue - values = (observed.bearing, observed.last_seen) - optional = (observed.bearing_uncertainty_deg, observed.x, - observed.y, observed.position_seen) - if (not all(isinstance(value, (int, float)) - and not isinstance(value, bool) and math.isfinite(value) - for value in values) - or any(value is not None and ( - not isinstance(value, (int, float)) - or isinstance(value, bool) or not math.isfinite(value)) - for value in optional) - or (observed.x is None) != (observed.y is None) - or not 0.0 <= observed.bearing < 360.0): - continue - observed_at = (observed.position_seen if observed.x is not None - and observed.position_seen is not None - else observed.last_seen) - if not 0.0 <= observed_at <= self.sim_t \ - or self.sim_t - observed_at > 30.0: - continue - raw_evidence.append((observed.source, observed.bearing, - observed.bearing_uncertainty_deg, - observed.x, observed.y, observed_at)) - evidence = [] - evidence_order = lambda row: ( - row[0], row[1], -1.0 if row[2] is None else row[2], - 0 if row[3] is None else 1, - 0.0 if row[3] is None else row[3], - 0.0 if row[4] is None else row[4], row[5]) - used_keys = set() - for values in sorted(raw_evidence, key=evidence_order): - source, bearing, uncertainty, x, y, observed_at = values - digest = hashlib.blake2b(repr(values).encode("utf-8"), - digest_size=5).hexdigest().upper() - track_id = f"OBS-{digest}" - suffix = 2 - while track_id in used_keys: - track_id = f"OBS-{digest}-{suffix}" - suffix += 1 - used_keys.add(track_id) - evidence.append(ESMCorrelationEvidence( - track_id=track_id, source=source, bearing=bearing, - bearing_uncertainty_deg=uncertainty, x=x, y=y, - observed_at=observed_at)) - return correlate_observations(track, evidence, self.sim_t) - - def hfdf_bearings(self) -> list: - """Current and recently retained HFDF observations.""" - return self.radio_picture.tracks(self.sim_t, ("HF",)) - - def hfdf_display_id(self, report) -> str: - """Return the stable public identifier for an HFDF observation.""" - track_id = report if isinstance(report, str) else report.track_id - return "H-" + self._observation_key("hfdf-display", track_id)[-6:] - - def _cycle_hfdf(self, delta: int) -> None: - reports = self.hfdf_bearings() - self.radio_sel = 0 if not reports else (self.radio_sel + delta) % len(reports) - - @staticmethod - def _bearing_intersection(first: dict, second: dict): - """Intersect two nautical bearing rays; return None for weak geometry.""" - b1, b2 = math.radians(first["bearing"]), math.radians(second["bearing"]) - r = (math.sin(b1), -math.cos(b1)) - s = (math.sin(b2), -math.cos(b2)) - denom = r[0] * s[1] - r[1] * s[0] - if abs(denom) < math.sin(math.radians(12.0)): - return None - qx, qy = second["observer_x"] - first["observer_x"], \ - second["observer_y"] - first["observer_y"] - along_first = (qx * s[1] - qy * s[0]) / denom - along_second = (qx * r[1] - qy * r[0]) / denom - if along_first < 0.0 or along_second < 0.0: - return None - return (first["observer_x"] + along_first * r[0], - first["observer_y"] + along_first * r[1], abs(denom)) - - def capture_hfdf(self) -> None: - reports = self.hfdf_bearings() - if not reports: - self.flash(message("runtime.hfdf.none")) - return - report = reports[min(self.radio_sel, len(reports) - 1)] - self.capture_hfdf_report(report) - - def capture_hfdf_report(self, report): - if self.damage.station_down("radio"): - return "radio_down" - if not any(item is report for item in self.hfdf_bearings()): - return "stale_ref" - if report.age(self.sim_t) > config.RADAR_TRACK_STALE_S: - self.flash(message("runtime.hfdf.stale")) - return "stale_ref" - measurement = (report.measurement_history[-1] - if report.measurement_history else {}) - display_id = self.hfdf_display_id(report) - row = dict(track_id=report.track_id, label=display_id, - bearing=measurement.get("bearing", report.bearing), - observer_x=measurement.get("observer_x", self.ship.x), - observer_y=measurement.get("observer_y", self.ship.y), - t=measurement.get("t", report.last_seen)) - self.hfdf_log.append(row) - self.hfdf_log = self.hfdf_log[-20:] - previous = next((item for item in reversed(self.hfdf_log[:-1]) - if item["track_id"] == report.track_id - and 0 < row["t"] - item["t"] <= 300.0 - and math.hypot(item["observer_x"] - row["observer_x"], - item["observer_y"] - row["observer_y"]) >= 1.0), None) - if previous is None: - self.announce(message("runtime.hfdf.logged", label=display_id, - bearing=f"{report.bearing:05.1f}"), "funk") - return True - fix = self._bearing_intersection(previous, row) - if fix is None: - self.announce(message("runtime.hfdf.geometry"), "funk") - return True - x, y, geometry = fix - # Angular errors projected at the two measurement origins. This assumes - # a stationary emitter throughout the bounded observation span. - b1, b2 = math.radians(previous["bearing"]), math.radians(row["bearing"]) - # Sky-wave intercepts carry the larger ionospheric-tilt uncertainty. - sigma_rad = math.radians(report.bearing_uncertainty_deg - or config.HFDF_BEARING_ERR_DEG / math.sqrt(3.0)) - v1 = sigma_rad ** 2 * ((x - previous["observer_x"]) ** 2 - + (y - previous["observer_y"]) ** 2) - v2 = sigma_rad ** 2 * ((x - row["observer_x"]) ** 2 - + (y - row["observer_y"]) ** 2) - xx = (math.sin(b2) ** 2 * v1 + math.sin(b1) ** 2 * v2) / geometry ** 2 - yy = (math.cos(b2) ** 2 * v1 + math.cos(b1) ** 2 * v2) / geometry ** 2 - xy = -(math.sin(b2) * math.cos(b2) * v1 - + math.sin(b1) * math.cos(b1) * v2) / geometry ** 2 - self.hfdf_fixes[report.track_id] = dict( - label=display_id, x=x, y=y, - sigma_nm=math.sqrt(max(0.0, (xx + yy + math.hypot(xx - yy, 2 * xy)) / 2)), - covariance_nm2=(xx, xy, yy), - t=row["t"]) - dist = math.hypot(x - row["observer_x"], y - row["observer_y"]) - bearing = math.degrees(math.atan2( - x - row["observer_x"], -(y - row["observer_y"]))) % 360.0 - self.air_picture.observe( - track_id=f"H-{report.target_id}", kind="UNKNOWN", - target_id=report.target_id, source="HFDF-FIX", bearing=bearing, - range_nm=dist, observer_x=row["observer_x"], - observer_y=row["observer_y"], - course=None, quality=max(.25, geometry), now=row["t"], - label=display_id) - self.flash(message("runtime.hfdf.fix", label=display_id), 3.0) - self.feed.add(self.world.format_time(), "funk", - message("runtime.hfdf.feed", label=display_id)) - return True - - def set_target(self) -> None: - contacts = [c for c in self.sonar.active_contacts() - if self.sim_t - c.last_seen < config.SONAR_CONTACT_LOST_S] - if not contacts: - self.target = None - self.flash(message("runtime.contacts.none")) - return - if self.selected_contact in contacts: - best = self.selected_contact - else: - best = max(contacts, key=lambda c: c.confidence) - if self.designate_sonar_target(best) is not True: - return - self.flash(message("runtime.target.set", contact=best.id), 2.0) - - def torpedo_readiness(self) -> tuple[str, tuple]: - """Return an operator-readable fire-control state and color.""" - if (self.target is None - or self.sim_t - self.target.last_seen >= config.SONAR_CONTACT_LOST_S): - return "BLOCKIERT: KEIN ZIEL", config.COLOR_WARN - blocked = self._target_affiliation_interlock() - if blocked is not None: - return (f"BLOCKIERT: ZUGEHOERIGKEIT {blocked}", - config.COLOR_DANGER) - if not self._contact_range_fresh(self.target) and self.roe == "STD": - return "BLOCKIERT: KEINE ENTFERNUNG", config.COLOR_WARN - if self.weapon_classification(self.target) not in ("U_BOOT", "KAMPFSCHIFF"): - return ("BLOCKIERT: NICHT ALS U-BOOT/KAMPFSCHIFF KLASSIFIZIERT", - config.COLOR_WARN) - if self.torpedo_count <= 0: - return "BLOCKIERT: KEINE TORPEDOS", config.COLOR_DANGER - if self.player_torpedo_battery.ready_count <= 0: - return "BLOCKIERT: KEIN ROHR BEREIT", config.COLOR_WARN - if len([t for t in self.torpedoes if t.state == "RUN"]) >= \ - config.TORP_MAX_IN_AIR[config.TORP_DOCTRINE]: - return "BLOCKIERT: SALVENLIMIT", config.COLOR_WARN - if self.damage.station_down("weapons") or \ - self.damage.station_degraded("weapons"): - return "BLOCKIERT: WAFFENZENTRALE GESTOERT", config.COLOR_DANGER - return "FEUER FREI", config.COLOR_OK - - def _contact_affiliations(self, contact) -> list: - """Return every OPZ affiliation annotation bound to a sonar target.""" - if contact is None: - return [] - # Operator annotations outlive measurements. Aircraft/missile sequence - # IDs are a separate namespace and must not annotate a sonar target. - affiliations = [self.opz_affiliations.get( - f"{prefix}-{contact.target_id}", "UNKNOWN") - for prefix in ("U", "S")] - self.opz_source_observations() - affiliations.extend( - self.opz_affiliation(observation_id) - for observation_id, source in self._opz_source_bindings.items() - if (source is contact or getattr(source, "target_id", None) - == contact.target_id and str( - getattr(source, "track_id", "")).split("-", 1)[0] - in ("U", "S"))) - # An affiliation set on an OPZ fusion covers every sonar report in it. - affiliations.extend( - self.opz_fusion.fusion_affiliations[fusion.fusion_id] - for fusion in self._contact_fusions(contact) - if fusion.fusion_id in self.opz_fusion.fusion_affiliations) - return affiliations - - def _contact_fusions(self, contact) -> list: - """Intact OPZ fusions holding a report bound to this sonar contact. - - Read-only: a fusion counts only while all its member reports are - current (the condition ``OPZFusion.prune`` applies), so the result - never depends on whether a frame pruned the register first. - """ - if contact is None or not self.opz_fusion.fusions: - return [] - current = {item.observation_id for item in self.opz_source_observations()} - bindings = self._opz_source_bindings - return [fusion for _, fusion in sorted(self.opz_fusion.fusions.items()) - if set(fusion.members) <= current - and any(bindings.get(member) is contact - for member in fusion.members)] - - def weapon_classification(self, contact) -> str | None: - """Operator class that fire control uses for one sonar contact. - - The sonar contact's own class wins; otherwise the class the OPZ gave a - fusion holding this contact's report applies. - """ - if contact is None: - return None - if contact.player_class in config.PLAYER_CLASSES: - return contact.player_class - return next((self.opz_fusion.classifications[fusion.fusion_id] - for fusion in self._contact_fusions(contact) - if self.opz_fusion.classifications.get(fusion.fusion_id) - in config.PLAYER_CLASSES), None) - - def contact_affiliation(self, contact) -> str: - """Resolve one affiliation for a contact, FRIEND/NEUTRAL taking - precedence over HOSTILE so callers stay conservative by default.""" - affiliations = self._contact_affiliations(contact) - return next((value for value in ("FRIEND", "NEUTRAL", "HOSTILE") - if value in affiliations), "UNKNOWN") - - def _target_affiliation_interlock(self, contact=None): - """Return a protected OPZ affiliation for the assigned sonar target.""" - contact = self.target if contact is None else contact - if contact is None: - return None - affiliations = self._contact_affiliations(contact) - return next((value for value in ("FRIEND", "NEUTRAL") - if value in affiliations), None) - - def _contact_range_fresh(self, contact) -> bool: - if contact is None or contact.range_est is None: - return False - observed_at = (contact.range_seen if contact.range_seen is not None - else contact.last_seen) - return self.sim_t - observed_at <= config.SONAR_CONTACT_LOST_S - - # --- M9: Kontakt-Auswahl & manuelle Klassifizierung --- - - def _cycle_selected_contact(self, delta: int) -> None: - cs = sorted((c for c in self.sonar.contacts.values() - if self.sim_t - c.last_seen < config.SONAR_CONTACT_LOST_S), - key=lambda c: c.id) - if not cs: - self.selected_contact = None - return - try: - i = cs.index(self.selected_contact) - except ValueError: - i = -1 - self.selected_contact = cs[(i + delta) % len(cs)] - if self.sonar.focus_locked: - self.sonar.reset_listening_history() - - def _cycle_helo_contact(self, delta: int) -> None: - """W2: browse only what the helicopter's own dip has plotted - its - own active/passive picture, independent of the ship's sonar picture - - so the operator can select one and release it to CIC from here.""" - cs = sorted((c for c in self.sonar.contacts.values() - if (c.dip_last_seen is not None - and 0 <= self.sim_t - c.dip_last_seen - < config.SONAR_CONTACT_LOST_S) - or any(fix["source"] == "DIPPING" - for fix in c.active_fixes(self.sim_t)) - or any(0 <= self.sim_t - row["measured_at"] - < config.SONAR_CONTACT_LOST_S - for row in c.buoy_reports.values())), - key=lambda c: c.id) - if not cs: - self.selected_contact = None - self.flash(message("runtime.contact.none_selected")) - return - try: - i = cs.index(self.selected_contact) - except ValueError: - i = -1 - self.selected_contact = cs[(i + delta) % len(cs)] - - def _cycle_classification(self) -> None: - if self.selected_contact is None: - self.flash(message("runtime.contact.none_selected")) - return - if self.selected_contact.target_id not in self.sonar.contacts: - self.selected_contact = None - return - c = self.selected_contact - order = [None] + list(config.PLAYER_CLASSES) - value = order[(order.index(c.player_class) + 1) % len(order)] - if self.classify_sonar_contact(c, value) is not True: - return - self.flash(message("runtime.contact.classified", contact=c.id, - classification=display_value("classification", - c.player_class, self.tr)), 2.0) - - def _toggle_sonar_release(self) -> None: - contact = self.selected_contact - if contact is None: - self.flash(message("runtime.contact.none_selected")) - return - helicopter = self.station is Station.HELICOPTER - buoy = helicopter and self.helo_sensor_source == "BUOY" - released = not (contact.buoy_released_to_opz if buoy else - contact.dip_released_to_opz if helicopter - else contact.released_to_opz) - if self.release_sonar_contact(contact, released, - source="buoy" if buoy else - "helicopter" if helicopter else "sonar") is not True: - return - self.flash(message("runtime.sonar.release" if released - else "runtime.sonar.withdraw", - contact=contact.id), 2.0) - - def _find_target(self, target_id: int): - for s in self.subs: - if s.id == target_id: - return s - for a in self.animals: - if a.id == target_id: - return a - for d in self.decoys: - if d.id == target_id: - return d - for civilian in self.civilians: - if civilian.id == target_id: - return civilian - for w in self.warships: - if w.id == target_id: - return w - for t in self.enemy_torpedoes: - if t.id == target_id: - return t - return None - - def launch_torpedo(self) -> None: - if (self.target is None - or self.sim_t - self.target.last_seen >= config.SONAR_CONTACT_LOST_S): - self.target = None - self.flash(message("runtime.target.invalid")) - return - self.launch_torpedo_at(self.target, self.torpedo_depth) - - def launch_torpedo_at(self, contact, depth_m: float): - """Launch from ownship against one explicit sonar observation.""" - if (contact is None or type(depth_m) not in (int, float) - or not math.isfinite(depth_m) or not 10 <= depth_m <= 300 - or self.sim_t - contact.last_seen >= config.SONAR_CONTACT_LOST_S): - self.flash(message("runtime.target.invalid")) - return "invalid_target" - blocked = self._target_affiliation_interlock(contact) - if blocked is not None: - self.flash(message("runtime.roe.blocked", - affiliation=display_value("affiliation", blocked, self.tr))) - return "roe_blocked" - if self.roe == "STD": - if not self._contact_range_fresh(contact): - self.flash(message("runtime.target.not_located")) - return "not_located" - if self.weapon_classification(contact) not in ("U_BOOT", "KAMPFSCHIFF"): - self.flash(message("runtime.target.not_classified")) - return "not_classified" - else: - if self.weapon_classification(contact) not in ("U_BOOT", "KAMPFSCHIFF"): - self.flash(message("runtime.target.not_classified")) - return "not_classified" - active_torpedoes = len([t for t in self.torpedoes if t.state == "RUN"]) - salvo_limit = config.TORP_MAX_IN_AIR[config.TORP_DOCTRINE] - if active_torpedoes >= salvo_limit: - self.flash(message("runtime.salvo.limit", limit=salvo_limit)) - return "salvo_limit" - if self.torpedo_count <= 0: - self.flash(message("event.no_torpedoes")) - return "empty" - if self.player_torpedo_battery.ready_count <= 0: - self.flash(message("runtime.torpedo.no_tube")) - return "no_tube" - if self.damage.station_down("weapons"): - self.flash(message("runtime.weapons.down")) - return "weapons_down" - if self.damage.station_degraded("weapons"): - self.flash(message("runtime.weapons.degraded")) - return "weapons_degraded" - tgt = self._find_target(contact.target_id) - if (contact.observed_x is not None - and contact.observed_y is not None - and self._contact_range_fresh(contact)): - est_x, est_y = contact.observed_x, contact.observed_y - else: - range_nm = (contact.range_est if contact.range_est is not None - else config.ROE_FREE_LAUNCH_RANGE_NM) - est_x = self.ship.x + range_nm * math.sin(math.radians(contact.bearing)) - est_y = self.ship.y - range_nm * math.cos(math.radians(contact.bearing)) - course = math.degrees(math.atan2(est_x - self.ship.x, - -(est_y - self.ship.y))) % 360.0 - weapon_key = self.player_torpedo_battery.fire() - if weapon_key is None: - self.flash(message("runtime.torpedo.no_tube")) - return "no_tube" - self.torpedo_seq += 1 - weapon_definition = next( - item - for item in self._ownship_loadout["weapons"] - if item["key"] == weapon_key) - profile_key = weapon_definition["runtime_profile_key"] - profile = self.runtime_catalog.torpedoes[profile_key] - self.torpedoes.append(Torpedo(self.ship.x, self.ship.y, course, - depth_m, tgt, self.torpedo_seq, - kill_dist_nm=self.difficulty["kill_dist_nm"], - kill_depth_m=self.difficulty["kill_depth_m"], - guidance_x=est_x, guidance_y=est_y, - profile=profile, time_since_launch=0.0)) - self.torpedo_count = self.player_torpedo_battery.remaining_total - # W2: the launch transient itself is a loud, one-time acoustic event, - # audible passively much farther than a torpedo's own terminal seeker - # ever gets (TORP_HOME_RANGE_NM) - distinct concept, separate gate. - for sub in self.subs: - if (not sub.sunk and sub.state != "SINKING" - and math.hypot(self.ship.x - sub.x, self.ship.y - sub.y) - <= config.SUB_TORPEDO_ALERT_NM - and not self.world.sonar_path_blocked( - self.ship.x, self.ship.y, 5.0, - sub.x, sub.y, sub.depth)): - sub.alert_torpedo(source=(self.ship.x, self.ship.y)) - for warship in self.warships: - if (not warship.sunk and warship.doctrine == "surface_combatant" - and math.hypot(self.ship.x - warship.x, self.ship.y - warship.y) - <= config.SUB_TORPEDO_ALERT_NM - and not self.world.sonar_path_blocked( - self.ship.x, self.ship.y, 5.0, - warship.x, warship.y, warship.depth)): - bearing = math.degrees(math.atan2( - self.ship.x - warship.x, - -(self.ship.y - warship.y))) % 360.0 - warship.alert_torpedo(bearing) - if (warship.countermeasures_left > 0 and warship.side == "hostile" - and len(self.decoys) < MAX_DECOYS): - # Stream an acoustic decoy while turning away. - warship.countermeasures_left -= 1 - decoy_profile = self.runtime_catalog.decoys[ - self.runtime_catalog.runtime_bindings["submarine_decoy"]] - self.decoys.append(Decoy( - warship.x, warship.y, 10.0, self.rng_asw, decoy_profile, - self.runtime_catalog.acoustic_for(decoy_profile.key), - source_id=warship.id)) - self._emit_sound("torpedo_launch") - self.flash(message("runtime.torpedo.launched", torpedo=self.torpedo_seq), 2.0) - self.feed.add(self.world.format_time(), "waffen", - message("runtime.torpedo.feed", torpedo=self.torpedo_seq, - contact=contact.id)) - return True - - # --- Update --- - - def _make_analyzer(self) -> ContactAnalyzer: - """Read-only Kontakt-Katalog-Browser (Menue und In-Game, F8).""" - return ContactAnalyzer( - tr=self.tr, on_play_sample=self._play_unit_audio, - on_stop_sample=self.audio.stop_preview, - preview_active=self.audio.preview_playing) - - def _open_analyzer_in_game(self) -> None: - """TUA im laufenden Spiel: Simulation laeuft weiter, Esc kehrt ins Spiel zurueck. - - With a sonar contact selected, Enter assigns the browsed profile to - it (the operator's catalog comparison result).""" - self._clear_controls() - contact = self.selected_contact - if contact is None or contact.target_id not in self.sonar.contacts: - self.editor = self._make_analyzer() - return - analyzer = self._make_analyzer() - analyzer.on_assign = lambda key: self.assign_contact_profile(contact, key) - analyzer.assign_label = self.contact_display_id(contact) - analyzer.current_assignment = lambda: self.profile_name(contact.player_profile) - self.editor = analyzer - - def profile_name(self, key): - """Display name of a catalog profile (as listed in the analyser).""" - if key is None: - return None - names = self.__dict__.get("_profile_names") - if names is None: - from src.data.contact_analysis import project_contact_catalog - names = {row["key"]: str(row["name"]) - for row in project_contact_catalog()["profiles"]} - self._profile_names = names - return names.get(key, key) - - def assign_contact_profile(self, contact, profile_key): - """Operator annotation: this contact matches that catalog profile.""" - if contact is None or contact.target_id not in self.sonar.contacts: - return "stale_ref" - if profile_key is not None and ( - type(profile_key) is not str - or profile_key not in self.runtime_catalog.profile_systems): - return "invalid_value" - contact.player_profile = profile_key - if profile_key is None: - notice = message("runtime.profile.cleared", - contact=self.contact_display_id(contact)) - else: - notice = message("runtime.profile.assigned", - contact=self.contact_display_id(contact), - profile=raw_text(self.profile_name(profile_key))) - self._sonar_notice(notice, 2.0) - return True - - def _open_simlog_view(self) -> None: - """F4: Live-Protokoll-Ansicht; nur bei aktiver simlog-Option.""" - if not self.preferences.simlog: - self.flash(message("simlog.view_disabled"), 2.0) - return - self._clear_station_input() - self.simlog_view_open = True - self.simlog_view_scroll = 0 - self.simlog_view_map = False - - def _close_simlog_view(self) -> None: - self.simlog_view_open = False - self.simlog_view_scroll = 0 - self.simlog_view_map = False - self._clear_station_input() - - def _scroll_simlog_view(self, amount: int) -> None: - self.simlog_view_scroll = max(0, self.simlog_view_scroll + amount) - - def _reset_map_view(self) -> None: - """Standard-Karte: Detail-Zoom, Kamera folgt der Fregatte.""" - self.map_view.set_rect(config.MAP_RECT) - self.map_view.scale = config.MAP_ZOOM_DEFAULT_PX_PER_NM - self.map_view.cx = self.ship.x - self.map_view.cy = self.ship.y - self.map_view.clamp_center() - self.map_follow = True - self._configure_opz_map_view() - self.opz_map_view.scale = min(self.opz_map_view.rect[2], - self.opz_map_view.rect[3]) / ( - 2.0 * config.OPZ_MAP_DEFAULT_RADIUS_NM) - self.opz_map_view.cx = self.ship.x - self.opz_map_view.cy = self.ship.y - self.opz_map_view.clamp_center() - self.opz_map_follow = True - - def _configure_opz_map_view(self, chart=None) -> None: - chart = pygame.Rect(chart or opz_ppi_rect(config.OPZ_STATION_RECT)) - self.opz_map_view.world_size = self.world.size_nm - self.opz_map_view.set_rect(tuple(chart)) - self.opz_map_view.min_scale = min(chart.w, chart.h) / self.world.size_nm - self.opz_map_view.max_scale = max( - self.opz_map_view.min_scale, min(chart.w, chart.h) / ( - 2.0 * config.OPZ_MAP_MAX_ZOOM_RADIUS_NM)) - self.opz_map_view.scale = config.clamp( - self.opz_map_view.scale, self.opz_map_view.min_scale, - self.opz_map_view.max_scale) - - @localized - def draw_menu(self) -> None: - """W4: Szenario -> (Level bei s4) -> Briefing -> Start.""" - s = self.screen - s.fill(config.COLOR_BG) - cx = config.SCREEN_W // 2 - - def center(text: str, y: int, font=None, color=config.COLOR_TEXT) -> None: - f = font or self.menu_font - text = localize(text) - surf = f.render(text, True, color) - s.blit(surf, surf.get_rect(center=(cx, y))) - - center("U-JAGD – FREGATTE F-217", 100, self.menu_font_big) - - if self.main_menu: - labels = ("menu.new_game", "menu.load", "menu.mission_editor", - "menu.unit_editor", "menu.contact_analyzer", "option.title", - "menu.quit") - for i, key in enumerate(labels): - marker = "> " if i == self.main_menu_sel else " " - color = config.COLOR_TEXT if i == self.main_menu_sel else config.COLOR_TEXT_DIM - center(message("menu.choice", marker=marker, - label=self.tr(key).upper()), 185 + i * 47, color=color) - elif self.menu_screen == "side": - center(self.tr("menu.choose_side"), 170, color=config.COLOR_TEXT_DIM) - for i, side in enumerate(("frigate", "uboot")): - selected = i == self.menu_sel - center(message("menu.choice", marker="► " if selected else " ", - label=self.tr(f"menu.side.{side}")), - 250 + i * 90, self.menu_font_big if selected else None, - config.COLOR_TEXT if selected else config.COLOR_TEXT_DIM) - layout.blit_line(s, f"menu.side.{side}.note", (cx - 420, 285 + i * 90, 840, 26), - config.COLOR_TEXT_DIM, size=18, align="center") - center(self.tr("menu.side_hint"), 470, color=config.COLOR_TEXT_DIM) - elif self.menu_screen == "scenario": - center(self.tr("menu.choose_scenario"), - 150, color=config.COLOR_TEXT_DIM) - scenario_names = {"s1_patrouille": "patrol", "s2_doppeljagd": "double", - "s3_abfang": "intercept", "s4_zufall": "random"} - for i, key in enumerate(config.SCENARIO_ORDER): - sc = config.SCENARIOS[key] - marker = "► " if i == self.menu_sel else " " - col = config.COLOR_TEXT if i == self.menu_sel \ - else config.COLOR_TEXT_DIM - lv = self.tr("menu.difficulty_fixed" if sc["difficulty"] is not None - else "menu.difficulty_custom") - title = self.tr("scenario." + scenario_names[key] + ".title") - center(message("menu.scenario_choice", index=i + 1, - marker=marker, title=title, level=lv), - 240 + i * 40, color=col) - elif self.menu_screen == "difficulty": - center(self.tr("menu.choose_difficulty"), - 150, color=config.COLOR_TEXT_DIM) - row_h = 26 - for i, name in enumerate(config.DIFFICULTY_FIELD_ORDER): - kind, _low, _high, _step, _default = config.DIFFICULTY_FIELDS[name] - marker = "► " if i == self.menu_sel else " " - col = config.COLOR_TEXT if i == self.menu_sel \ - else config.COLOR_TEXT_DIM - value = self.menu_difficulty[name] - value_text = (str(value) if kind is int - else f"{value:.3f}".rstrip("0").rstrip(".")) - center(message("menu.difficulty_choice", marker=marker, - label=self.tr("difficulty." + name), - value=value_text), - 190 + i * row_h, color=col) - i = len(config.DIFFICULTY_FIELD_ORDER) - selected = i == self.menu_sel - center(message("menu.difficulty_choice", - marker="► " if selected else " ", - label=self.tr("menu.hq_intel"), - value=self.tr("menu.hq_intel." + self.hq_intel_mode_menu())), - 190 + i * row_h, - color=config.COLOR_TEXT if selected else config.COLOR_TEXT_DIM) - else: # briefing - sc = config.SCENARIOS[self.scenario_key] - scenario_key = {"s1_patrouille": "patrol", "s2_doppeljagd": "double", - "s3_abfang": "intercept", "s4_zufall": "random"}[self.scenario_key] - center(self.tr("scenario." + scenario_key + ".title"), 170, - self.menu_font_big, config.COLOR_WARN) - layout.blit_block(s, self.tr("scenario." + scenario_key + ".brief"), - cx - 420, 210, 840, 180, - color=config.COLOR_TEXT, size=20) - if sc["win_text"]: - center(message("menu.goal_value", - goal=self.tr("scenario." + scenario_key + ".win")), - 420, color=config.COLOR_OK) - if sc["lose_text"]: - center(message("menu.loss_value", - loss=self.tr("scenario." + scenario_key + ".lose")), 448, - color=config.COLOR_DANGER) - center(self.tr("menu.start_hint"), 520, - color=config.COLOR_TEXT_DIM) - center(message("menu.local_side", side=message( - "menu.local_side.uboot" if self.local_side == "uboot" - else "menu.local_side.frigate")), 556, - color=config.COLOR_WARN if self.local_side == "uboot" - else config.COLOR_TEXT_DIM) - - if self.world_mode in ("procedural", "real_fixed"): - from src.world.real_coast import sector_for_seed - sector, _ = sector_for_seed(self.seed) - world_label = sector["name"] - if self.world_mode == "real_fixed": - center(self.tr("menu.real_fixed_hint", sector=sector["id"]), - config.SCREEN_H - 95, color=config.COLOR_TEXT_DIM) - else: - world_label = self.tr("menu.fixed_chart") - center(self.tr("menu.world_status", world=world_label, seed=self.seed), - config.SCREEN_H - 68, color=config.COLOR_OK) - center(self.tr("menu.seed_fullscreen", seed=self.seed, - action=self.tr("menu.windowed" if self.fullscreen - else "menu.fullscreen")), - config.SCREEN_H - 40, color=config.COLOR_TEXT_DIM) - - # --- W0: Draw-Grid --- - - @property - def _station_overlay_open(self) -> bool: - """A full-station overlay (F3 autocrew, 0 weather) replaces the station.""" - return self.autocrew_overview_open or self.weather_station_open - - @localized - def _eco_display_active(self) -> bool: - """Solo browser is live: the uConsole shows a cheap status screen. - - Pure display decision; it never touches simulation state, saves or input. - """ - return (self.running and not self.splash_active and self.editor is None - and not self.simlog_view_open and not self.in_menu - and not self.main_menu and not self.administration_open - and not self.game_over and not self._station_overlay_open - and self.commander.eco_display_ready(self)) - - def _skip_eco_frame(self) -> bool: - """True while the last eco frame is still current (draw and blit skipped).""" - if not self._eco_display_active(): - self._eco_drawn_at = float("-inf") - return False - if self._t - self._eco_drawn_at < config.ECO_REDRAW_S: - return True - self._eco_drawn_at = self._t - return False - - @localized - def draw_eco_display(self) -> None: - s = self.screen - panel = pygame.Rect(240, 90, 800, 360) - layout.panel(s, panel) - x, w = panel.x + 24, panel.w - 48 - layout.blit_line(s, "eco.title", (x, panel.y + 16, w, 36), - config.COLOR_WARN, size=28, align="center") - layout.blit_block(s, "eco.subtitle", x, panel.y + 66, w, 66, - config.COLOR_TEXT, size=20, align="center", valign="center") - address = getattr(self.commander, "address", None) - if address is not None: - url = raw_text(f"http://{address[0]}:{address[1]}/") - proxy = getattr(self.commander, "public_origin", None) - layout.blit_line(s, message("commander.local.url_proxy", url=url, - proxy=raw_text(proxy + "/")) - if proxy else message("commander.local.url", url=url), - (x, panel.y + 150, w, 32), config.COLOR_TEXT, size=22, align="center") - layout.blit_line(s, message( - "eco.state.running", time=raw_text(self.world.format_time())), - (x, panel.y + 200, w, 32), config.COLOR_OK, - size=24, align="center") - layout.blit_line(s, "eco.hint", (x, panel.bottom - 56, w, 30), - config.COLOR_TEXT_DIM, size=16, align="center") - - def draw(self) -> None: - # One translation scope for the whole frame: text drawn directly here - # (flash banner, overlays) must follow the game language, not the - # process-wide default translator. - with layout.bottom_panel_regions(self.bottom_panel_mode()), \ - translation_scope(self.tr): - self._draw() - - def _draw(self) -> None: - self._apply_text_size() - s = self.screen - eco = self._eco_display_active() - s.fill(config.COLOR_BG) - if self.splash_active: - draw_splash(s, self._t - self.splash_started_at, self.tr) - elif self.editor is not None: - self.editor.draw(s) - if isinstance(self.editor, MissionEditor) and self.editor.mode == "browser": - hint = self.font.render(localize("F5: start selected runtime-compatible mission"), - True, config.COLOR_OK) - s.blit(hint, (config.SCREEN_W - hint.get_width() - 20, - config.SCREEN_H - 68)) - elif self.simlog_view_open: - draw_simlog_view(self) - elif self.in_menu: - self.draw_menu() - elif self.local_side == "uboot": - uboot_view.draw(self) - elif eco: - self.draw_top_bar() - self.draw_eco_display() - self.draw_bottom_panel() - else: - self.draw_top_bar() - map_station = (not self._station_overlay_open - and self._map_station_visible()) - previous_rect = config.STATION_RECT - try: - config.STATION_RECT = (config.STATION_PANEL_RECT if map_station else - # The weather panel takes the whole - # screen below the top bar. - config.OPZ_STATION_RECT - if self.weather_station_open - or (self.station is Station.OPZ - and not self._station_overlay_open) else - config.FULL_STATION_RECT) - if self.autocrew_overview_open: - with layout.clip_to(s, config.STATION_RECT): - draw_autocrew_overview(self) - elif self.weather_station_open: - with layout.clip_to(s, config.STATION_RECT): - draw_weather_station(self) - elif map_station: - draw_map_view(self) - if self.station is Station.WEAPONS: - draw_weapons_overlay(self) - if not self._station_overlay_open: - with layout.clip_to(s, config.STATION_RECT): - if self.station is Station.SONAR: - draw_sonar_view(self) - elif self.station is Station.WEAPONS: - draw_weapons_panel(self) - elif self.station is Station.DAMAGE: - draw_damage_view(self) - elif self.station is Station.OPZ: - draw_opz_view(self) - elif self.station is Station.RADIO: - draw_radio_view(self) - elif self.station is Station.ENGINE: - draw_engine_view(self) - elif self.station is Station.HELICOPTER: - draw_helicopter_view(self) - elif self.station is Station.ELOKA: - draw_eloka_view(self) - else: - draw_bridge_view(self) - if (self.station is not Station.OPZ and not self.weather_station_open - and not self.feed_overlay_open): - self.draw_bottom_panel() - if self.feed_overlay_open: - self.draw_feed_overlay() - self.draw_navigation_input() - if self.game_over: - self.draw_end_panel() - finally: - config.STATION_RECT = previous_rect - if self.quit_confirm: - self.draw_quit_overlay() - elif self.help_open: - self.draw_help_overlay() - elif self.nations_open: - self.draw_nations_overlay() - elif self.save_ui is not None: - self.draw_save_ui() - elif self.options_open: - self.draw_options_overlay() - elif self.live_traffic_open: - self.draw_live_traffic_overlay() - elif self.commander_open: - self.commander.draw(self) - self.commander.draw_confirm(self) - if self.msg and self._t < self.msg_until: - self._draw_flash_banner(s) - if (not self.in_menu and not self.splash_active and self.editor is None - and not self.simlog_view_open and not self._station_overlay_open - and self.tooltips_enabled and not eco - and self.local_side != "uboot" - and not self.administration_open and not self.game_over): - canvas = self._window_to_canvas(pygame.mouse.get_pos()) - payload = self.pinned_tooltip or self.tooltip_at(canvas) - anchor = self._tooltip_anchor if self.pinned_tooltip else canvas - if payload is not None and anchor is not None: - layout.draw_tooltip(s, payload, anchor, - (0, 0, config.SCREEN_W, config.SCREEN_H)) - if self._scanlines is not None: - s.blit(self._scanlines, (0, 0)) - if self.preferences.night_mode: - s.blit(self._night_overlay, (0, 0), special_flags=pygame.BLEND_MULT) - - @localized - def draw_navigation_input(self) -> None: - """Show the active numeric command without hiding the simulation.""" - if self.input_mode is None: - return - label = self.tr("input." + self.input_mode) - rect = pygame.Rect(280, 88, 720, 70) - pygame.draw.rect(self.screen, config.COLOR_OVERLAY_BG, rect) - pygame.draw.rect(self.screen, config.COLOR_WARN, rect, 2) - layout.blit_line(self.screen, self.tr("input.value", label=label, - value=self.input_buffer), - (rect.x + 14, rect.y + 8, rect.w - 28, 26), - config.COLOR_TEXT, size=20) - layout.blit_line(self.screen, self.tr("input.hint"), - (rect.x + 14, rect.y + 38, rect.w - 28, 22), - config.COLOR_TEXT_DIM, size=14) - - @localized - def top_bar_scenario(self) -> str: - """Mission title shown in the top status bar.""" - if self.custom_mission_definition is not None: - return localize(self.mission_name_display()) - return self.tr("scenario." + {"s1_patrouille": "patrol", "s2_doppeljagd": "double", - "s3_abfang": "intercept", "s4_zufall": "random"} - [self.scenario_key] + ".title") - - def draw_top_bar(self) -> None: - layout.configure_for(self) - s = self.screen - pygame.draw.rect(s, config.COLOR_PANEL_BG, (0, 0, config.SCREEN_W, config.TOP_BAR_H)) - pygame.draw.line(s, config.COLOR_SONAR_RING, - (0, config.TOP_BAR_H - 1), - (config.SCREEN_W, config.TOP_BAR_H - 1), 1) - station = display_value("station", self.station.name, self.tr).upper() - scenario = self.top_bar_scenario() - txt = self.tr("top.status", station=station, scenario=scenario, - time=self.world.format_time(), speed=f"{self.ship.speed:4.1f}", - course=f"{self.ship.course:4.0f}") - layout.blit_line(s, txt, (10, 4, config.SCREEN_W - 20, - config.TOP_BAR_H - 8), - config.COLOR_TEXT, size=18) - self._top_status_right = 10 + layout.font(layout.scaled_size(18)).size( - localize(txt))[0] - - def draw_bottom_panel(self, entries=None, rows=None, heading="feed.heading", - ticker_keys=None, ticker_hint="ticker.hint") -> None: - """Event feed and telemetry: docked band or one status ticker. - - ``entries``/``rows`` replace the frigate's feed and telemetry (the - crewed submarine's own log and readings use the same band). - """ - if self.bottom_panel_mode() == "ticker": - self.draw_status_ticker(entries, rows, ticker_keys, ticker_hint) - else: - self.draw_bottom_feed(entries, heading) - self.draw_bottom_telemetry(rows) - - def _feed_lines(self, width: int, face, entries=None) -> list: - """Wrap feed entries (oldest first) into (text, colour, is_first) rows. - - Entries wrap onto continuation lines under the text column; nothing - is ever cut off with an ellipsis. - """ - rows = [] - for entry in self.feed.entries if entries is None else entries: - prefix = f"[{entry.stamp}] {entry.tag():4s} " - indent = face.size(prefix)[0] - wrapped = layout.wrap_text(localize(entry.text), face, - max(40, width - indent)) or [""] - rows.append((prefix, wrapped[0], entry.color(), indent)) - rows.extend(("", line, entry.color(), indent) for line in wrapped[1:]) - return rows - - def _blit_feed_rows(self, rect, rows, scroll: int = 0) -> None: - """Draw wrapped feed rows bottom-up (newest at the bottom).""" - face = layout.font(16) - pitch = layout._line_height(face) - visible = max(1, rect.h // pitch) - end = max(0, len(rows) - scroll) - shown = rows[max(0, end - visible):end] - y = rect.bottom - len(shown) * pitch - with layout.clip_to(self.screen, rect): - for prefix, text, color, indent in shown: - if prefix: - layout.blit_line(self.screen, raw_text(prefix), - (rect.x, y, indent, pitch), - config.COLOR_TEXT_DIM, size=16) - layout.blit_line(self.screen, raw_text(text), - (rect.x + indent, y, rect.w - indent, pitch), - color, size=16) - y += pitch - - @localized - def draw_bottom_feed(self, entries=None, heading="feed.heading") -> None: - s = self.screen - x, y, w, h = config.FEED_RECT - pygame.draw.rect(s, config.COLOR_FEED_BG, (x, y, w, h)) - pygame.draw.rect(s, config.COLOR_SONAR_RING, (x, y, w, h), 1) - layout.blit_line(s, heading, (x + 8, y + 3, w - 16, 20), - config.COLOR_TEXT_DIM, size=16) - body = pygame.Rect(x + 8, y + 25, w - 16, h - 29) - face = layout.font(16) - self._blit_feed_rows(body, self._feed_lines(body.w, face, entries)) - - @localized - def draw_bottom_telemetry(self, rows=None) -> None: - s = self.screen - x, y, w, h = config.TELEMETRY_RECT - pygame.draw.rect(s, config.COLOR_FEED_BG, (x, y, w, h)) - pygame.draw.rect(s, config.COLOR_SONAR_RING, (x, y, w, h), 1) - layout.blit_line(s, "panel.telemetry", (x + 8, y + 3, w - 16, 20), - config.COLOR_TEXT_DIM, size=16) - self._blit_telemetry_rows(pygame.Rect(x + 8, y + 25, w - 16, h - 29), - short=True, rows=rows) - - def _blit_telemetry_rows(self, rect, short: bool, rows=None) -> None: - face = layout.font(16) - rows = observations.telemetry_rows(self) if rows is None else rows - pitch = max(layout._line_height(face), rect.h // max(1, len(rows))) - labels = [localize(observations.telemetry_label(key, short)) - for key, *_rest in rows] - label_w = max(face.size(label)[0] for label in labels) + 10 - colors = {"ok": config.COLOR_TEXT, "warn": config.COLOR_WARN, - "danger": config.COLOR_DANGER} - for index, ((_key, value, level, _compact), label) in enumerate(zip(rows, labels)): - y = rect.y + index * pitch - layout.blit_line(self.screen, raw_text(label), (rect.x, y, label_w, pitch), - config.COLOR_TEXT_DIM, size=16) - layout.blit_line(self.screen, value, (rect.x + label_w, y, - rect.w - label_w, pitch), - colors[level], size=16) - - def _ticker_telemetry_text(self, width: int | None = None, rows=None, - keys=None) -> str: - """Compact telemetry for the ticker, most important readings first. - - Readings that do not fit are left out whole (never clipped); the - F11 overlay always shows all of them. - """ - parts = [] - keys = observations.TICKER_KEYS if keys is None else keys - rows = observations.telemetry_rows(self) if rows is None else rows - for key, _value, _level, compact in rows: - if key in keys: - label = observations.telemetry_label(key, short=True) - parts.append(f"{localize(label)} {localize(compact)}") - face = layout.font(16) - while width is not None and len(parts) > 1 and face.size( - " \u00b7 ".join(parts))[0] > width: - parts.pop() - return " \u00b7 ".join(parts) - - @localized - def draw_status_ticker(self, entries=None, rows=None, keys=None, - hint_key="ticker.hint") -> None: - """One 22 px strip: newest event (scrolls if long) + key telemetry.""" - s = self.screen - rect = layout.ticker_rect() - pygame.draw.rect(s, config.COLOR_FEED_BG, rect) - pygame.draw.line(s, config.COLOR_SONAR_RING, rect.topleft, rect.topright, 1) - face = layout.font(16) - rows = observations.telemetry_rows(self) if rows is None else rows - telemetry = self._ticker_telemetry_text(int(rect.w * .6) - 16, rows, keys) - level = ("danger" if any(row[2] == "danger" for row in rows) - else "warn" if any(row[2] == "warn" for row in rows) else "ok") - colors = {"ok": config.COLOR_TEXT, "warn": config.COLOR_WARN, - "danger": config.COLOR_DANGER} - tele_w = face.size(telemetry)[0] + 16 - tele_rect = pygame.Rect(rect.right - tele_w, rect.y + 2, tele_w - 8, rect.h - 2) - layout.blit_line(s, raw_text(telemetry), tele_rect, colors[level], - size=16, align="right") - hint = localize(hint_key) if hint_key else "" - hint_w = face.size(hint)[0] + 12 if hint else 0 - if hint: - layout.blit_line(s, raw_text(hint), (rect.x + 6, rect.y + 2, hint_w, rect.h - 2), - config.COLOR_TEXT_DIM, size=16) - feed_rect = pygame.Rect(rect.x + 6 + hint_w, rect.y + 2, - tele_rect.x - 12 - (rect.x + 6 + hint_w), rect.h - 2) - latest = self.feed.recent(1) if entries is None else list(entries)[-1:] - if not latest or feed_rect.w <= 20: - return - entry = latest[0] - text = f"[{entry.stamp}] {entry.tag()} {localize(entry.text)}" - width = face.size(text)[0] - with layout.clip_to(s, feed_rect): - if width <= feed_rect.w: - layout.blit_line(s, raw_text(text), feed_rect, entry.color(), size=16) - else: - # Marquee instead of an ellipsis: the full line stays readable. - gap = 60 - offset = int(self._t * config.TICKER_SCROLL_PX_S) % (width + gap) - surface = layout.font(16).render(text, True, entry.color()) - s.blit(surface, (feed_rect.x - offset, feed_rect.y)) - s.blit(surface, (feed_rect.x - offset + width + gap, feed_rect.y)) - - def feed_overlay_rect(self) -> pygame.Rect: - return pygame.Rect(0, config.SCREEN_H - 330, config.SCREEN_W, 330) - - @localized - def draw_feed_overlay(self) -> None: - """F11: full event history and telemetry over the station (display only).""" - s = self.screen - rect = self.feed_overlay_rect() - shade = pygame.Surface(rect.size, pygame.SRCALPHA) - shade.fill((*config.COLOR_FEED_BG, 238)) - s.blit(shade, rect.topleft) - pygame.draw.rect(s, config.COLOR_WARN, rect, 1) - tele_w = 360 - feed = pygame.Rect(rect.x + 10, rect.y + 30, rect.w - tele_w - 30, rect.h - 40) - tele = pygame.Rect(rect.right - tele_w - 10, rect.y + 30, tele_w, rect.h - 40) - face = layout.font(16) - rows = self._feed_lines(feed.w, face) - visible = max(1, feed.h // layout._line_height(face)) - self.feed_overlay_scroll = max(0, min(self.feed_overlay_scroll, - len(rows) - visible)) - layout.blit_line(s, message("feed.overlay.title", - shown=min(len(rows), visible), total=len(rows)), - (rect.x + 10, rect.y + 5, feed.w, 22), config.COLOR_WARN, - size=16) - layout.blit_line(s, "panel.telemetry", (tele.x, rect.y + 5, tele.w, 22), - config.COLOR_WARN, size=16) - self._blit_feed_rows(feed, rows, self.feed_overlay_scroll) - pygame.draw.line(s, config.COLOR_SONAR_RING, (tele.x - 10, feed.y), - (tele.x - 10, feed.bottom), 1) - self._blit_telemetry_rows(pygame.Rect(tele.x, tele.y, tele.w, 7 * 26), - short=False) - layout.blit_block(s, "feed.overlay.hint", tele.x, tele.bottom - 44, tele.w, - 44, config.COLOR_TEXT_DIM, size=16) - - def _help_lines(self) -> tuple[list[str], int]: - """Wrap before scrolling so every line remains reachable at either size.""" - layout.configure_for(self) - intro, keys, params, tactics = get_help(self.station, self.tr) - face = layout.font(18) - visible = max(1, 500 // layout._line_height(face)) - if self.help_page == HELP_MANUAL_PAGE: - chapter = manual.CHAPTERS[self.help_manual_chapter % len(manual.CHAPTERS)] - blocks = manual.chapter_blocks(chapter, manual.manual_language(self.tr)) - width = max(20, 960 // max(1, face.size("M")[0])) - # Leading blanks survive word wrapping only as no-break spaces. - lines = [line[:len(line) - len(line.lstrip(" "))].replace(" ", "\u00a0") - + line.lstrip(" ") for line in manual.text_lines(blocks, width)] - return lines, visible - if self.help_page == 0: - title, bindings = get_global_help(self.tr) - text = title + "\n\n" + "\n".join(f"{k:<18} {a}" for k, a in bindings) - elif self.help_page == 1 and self.local_side == "uboot": - title, bindings = get_uboot_help(self.tr) - text = title + "\n\n" + "\n".join(f"{k:<18} {a}" for k, a in bindings) - elif self.help_page == 1: - sop = get_sop(self.station, self.tr) - text = (intro + "\n\n" + "\n".join(f"{k:<18} {a}" for k, a in keys) - + "\n\n" + self.tr("help.sop.title") + "\n" - + "\n".join(f"{n}. {step}" for n, step in enumerate(sop, 1))) - else: - text = self.tr("help.sensors_tactics") + "\n\n" + "\n\n".join(params + tactics) - return layout.wrap_text(text, face, 960), visible - - @localized - def draw_help_overlay(self) -> None: - layout.configure_for(self) - s = self.screen - dim = pygame.Surface((config.SCREEN_W, config.SCREEN_H), pygame.SRCALPHA) - dim.fill((0, 0, 0, 170)) - s.blit(dim, (0, 0)) - bw, bh = 1000, 620 - bx = (config.SCREEN_W - bw) // 2 - by = (config.SCREEN_H - bh) // 2 - pygame.draw.rect(s, config.COLOR_PANEL_BG, (bx, by, bw, bh)) - pygame.draw.rect(s, config.COLOR_SONAR_RING, (bx, by, bw, bh), 2) - help_title = self.tr("help.title", station=display_value( - "station", self.station.name, self.tr).upper()) - layout.blit_line(s, help_title, (bx + 18, by + 10, bw - 36, 40), - config.COLOR_TEXT, size=30) - x = bx + 20 - w = bw - 40 - y = by + 52 - lines, visible = self._help_lines() - scroll = min(getattr(self, "help_scroll", 0), max(0, len(lines) - visible)) - body = "\n".join(lines[scroll:scroll + visible]) - if self.help_page == HELP_MANUAL_PAGE: - body = raw_text(body) - hint = self.tr("help.manual.hint", - chapter=self.help_manual_chapter % len(manual.CHAPTERS) + 1, - chapters=len(manual.CHAPTERS), first=scroll + 1, - last=min(len(lines), scroll + visible), total=len(lines)) - else: - hint = self.tr("control.help.scroll_hint", page=self.help_page + 1, - pages=HELP_PAGE_COUNT, first=scroll + 1, - last=min(len(lines), scroll + visible), total=len(lines)) - layout.blit_block(s, body, x, y, w, 500, config.COLOR_TEXT, size=18, min_size=18) - layout.blit_block(s, hint, x, by + bh - 62, w, 54, config.COLOR_TEXT_DIM, size=16) - - @localized - def draw_nations_overlay(self) -> None: - s = self.screen - dim = pygame.Surface((config.SCREEN_W, config.SCREEN_H), pygame.SRCALPHA) - dim.fill((0, 0, 0, 160)) - s.blit(dim, (0, 0)) - bw, bh = 1100, 620 - bx = (config.SCREEN_W - bw) // 2 - by = (config.SCREEN_H - bh) // 2 - pygame.draw.rect(s, config.COLOR_PANEL_BG, (bx, by, bw, bh)) - pygame.draw.rect(s, config.COLOR_SONAR_RING, (bx, by, bw, bh), 2) - layout.blit_line(s, "panel.nations", (bx + 18, by + 12, bw - 36, 38), - config.COLOR_TEXT, size=30) - summary = getattr(self, "_nations_summary", None) - if summary is None: - summary = reference_summary(self.world.coast, self.runtime_catalog) - self._nations_summary = summary - legacy_country_names = { - "HANSE": "nations.country.hanse", - "BOREN": "nations.country.boren", - "SKANDIA": "nations.country.skandia", - } - countries = ", ".join(self.tr(legacy_country_names[c]) - if c in legacy_country_names else c - for c in summary["countries"]) or self.tr("nations.none") - cards = ( - ("nations.area", self.tr("nations.countries", countries=countries) - + "\n\n" + self.tr("nations.reference_note"), config.COLOR_FLIGHT), - ("nations.friendly", "\n".join(summary["friendly"]), config.COLOR_OK), - ("nations.hostile", self.tr("nations.subs", count=len(summary["hostile_subs"])) - + "\n" + ", ".join(summary["hostile_subs"]) - + "\n\n" + self.tr("nations.surfaces", count=len(summary["hostile_surfaces"])) - + "\n" + ", ".join(summary["hostile_surfaces"]), config.COLOR_DANGER), - ("nations.other", self.tr("nations.neutral_military", count=summary["neutral_military"]) - + "\n\n" + self.tr("nations.civilian", count=summary["civilian"]) - + "\n\n" + self.tr("nations.catalog_hint"), config.COLOR_CONTACT_ZIVIL), - ) - cw, ch = 520, 260 - for i, (title, body, color) in enumerate(cards): - cx = bx + 18 + (i % 2) * (cw + 14) - cyy = by + 52 + (i // 2) * (ch + 12) - pygame.draw.rect(s, config.COLOR_PANEL_BG, (cx, cyy, cw, ch)) - pygame.draw.rect(s, color, (cx, cyy, cw, ch), 1) - layout.blit_line(s, title, (cx + 12, cyy + 8, cw - 24, 36), color, size=24) - layout.blit_block(s, body, cx + 12, cyy + 50, cw - 24, ch - 58, - color=config.COLOR_TEXT, size=18) - layout.blit_line(s, "nations.close", (bx + bw - 160, by + bh - 30, 140, 24), - config.COLOR_TEXT_DIM, size=16, align="right") - - @localized - def draw_save_ui(self) -> None: - s = self.screen - mode = self.tr("common.save" if self.save_ui == "save" else "common.load").upper() - dim = pygame.Surface((config.SCREEN_W, config.SCREEN_H), pygame.SRCALPHA) - dim.fill((0, 0, 0, 150)) - s.blit(dim, (0, 0)) - bw, bh = 660, 380 - bx = (config.SCREEN_W - bw) // 2 - by = (config.SCREEN_H - bh) // 2 - pygame.draw.rect(s, config.COLOR_PANEL_BG, (bx, by, bw, bh)) - pygame.draw.rect(s, config.COLOR_SONAR_RING, (bx, by, bw, bh), 2) - layout.blit_line(s, self.tr("save.title", mode=mode), - (bx + 18, by + 14, bw - 36, 34), config.COLOR_TEXT, size=22) - ly = by + 70 - for slot in range(1, 6): - info = self.save_info[slot - 1] if len(self.save_info) == 5 else "--" - selected = slot == self.save_slot - col = config.COLOR_WARN if selected else config.COLOR_TEXT_DIM - layout.blit_line(s, message("save.slot", marker=">" if selected else " ", - slot=slot, info=localize(info)), - (bx + 24, ly, bw - 48, 32), col, size=19) - ly += 42 - hint = "save.live" - if self.save_confirm: - hint = ("save.overwrite" if self.save_ui == "save" - else "save.replace") - layout.blit_line(s, hint, (bx + 18, by + bh - 54, bw - 36, 34), - config.COLOR_WARN, size=18) - - @localized - def draw_end_panel(self) -> None: - """M8: Endpanel mit Score-Bruchrechnung und Hinweisen.""" - s = self.screen - dim = pygame.Surface((config.SCREEN_W, config.SCREEN_H), pygame.SRCALPHA) - dim.fill((0, 0, 0, 140)) - s.blit(dim, (0, 0)) - w, h = 700, 340 - x = (config.SCREEN_W - w) // 2 - y = (config.SCREEN_H - h) // 2 - pygame.draw.rect(s, (12, 26, 18), (x, y, w, h)) - pygame.draw.rect(s, config.COLOR_TEXT_DIM, (x, y, w, h), 2) - col = config.COLOR_OK if self.mission_result == "SIEG" else config.COLOR_DANGER - result = self.tr("end.victory" if self.mission_result == "SIEG" - else "end.defeat") - lines = [ - (message("end.result", result=result, - reason=localize(self.result_reason)), col, True), - ("", config.COLOR_TEXT, False), - (message("end.score_value", score=self.score), config.COLOR_TEXT, True), - (message("end.mission_level", mission=self.mission_name_display(), - level=self.mission_level_display()), - config.COLOR_TEXT_DIM, False), - (message("end.time_remaining", - remaining=self.mission.format_remaining(self.mission_time)) - if (self.mission_result == "SIEG" - or self.mission_time < self.mission.time_limit_s) - else "end.expired", - config.COLOR_TEXT_DIM, False), - ("", config.COLOR_TEXT, False), - ("end.restart", config.COLOR_TEXT_DIM, False), - ] - ly = y + 44 - for text, c, big in lines: - if not text: - ly += 16 - continue - size = 26 if big else 20 - height = 36 if big else 26 - layout.blit_line(s, text, (x + 16, ly, w - 32, height), c, - size=size, align="center") - ly += 42 if big else 30 - - @staticmethod - def _options_row_rects(): - return tuple(pygame.Rect(292, 118 + index * 40, 696, 36) - for index in range(max(len(page) for page in Game._OPTION_PAGES))) - - @staticmethod - def _options_page_rects(): - """Clickable page tabs left and right of the options title.""" - return tuple(pygame.Rect(292 + index * 590, 70, 106, 36) - for index in range(len(Game._OPTION_PAGES))) - - def _option_rows(self) -> tuple: - page = self.options_page if 0 <= self.options_page < len(self._OPTION_PAGES) else 0 - return self._OPTION_PAGES[page] - - def _set_options_page(self, page: int) -> None: - self.options_page = page % len(self._OPTION_PAGES) - self.options_sel = 0 - - def local_side_locked(self) -> bool: - """The uConsole's side is chosen outside a mission only.""" - return not self.in_menu - - def _toggle_local_side(self) -> None: - if not self.local_side_locked(): - uboot_local.toggle_side(self) - - @localized - def draw_options_overlay(self) -> None: - # Panel/row geometry is sized so the footer hint always starts below - # the last row with margin, never overlapping it (was previously a - # fixed y=612 footer colliding with row 9's box at y=620-662). - rect = pygame.Rect(260, 40, 760, 660) - pygame.draw.rect(self.screen, config.COLOR_OVERLAY_BG, rect) - pygame.draw.rect(self.screen, config.COLOR_WARN, rect, 2) - layout.blit_line(self.screen, "option.title", (292, 64, 696, 48), - config.COLOR_WARN, size=32, align="center") - for page, tab in enumerate(self._options_page_rects()): - active = page == self.options_page - pygame.draw.rect(self.screen, config.COLOR_WARN if active - else config.COLOR_TEXT_DIM, tab, 1) - layout.blit_line(self.screen, message("option.page", page=page + 1, - pages=len(self._OPTION_PAGES)), - tab.inflate(-8, -4), config.COLOR_WARN if active - else config.COLOR_TEXT_DIM, size=18, align="center") - if self._option_rows() is self._OPTION_ROWS_SETUP: - self._draw_options_setup_page() - return - values = ( - self.tr("option.language") + ": " + self.tr("option.language." + self.preferences.language), - self.tr("option.fullscreen") + ": " + self.tr("common.on" if self.preferences.fullscreen else "common.off"), - self.tr("option.audio") + ": " + self.tr("common.on" if self.audio.available else "common.off"), - self.tr("option.large_text") + ": " + self.tr("common.on" if self.preferences.large_text else "common.off"), - self.tr("option.tooltips") + ": " - + self.tr("common.on" if self.tooltips_enabled else "common.off"), - self.tr("option.simlog") + ": " - + self.tr("common.on" if self.preferences.simlog else "common.off"), - self.tr("option.night_mode") + ": " - + self.tr("common.on" if self.preferences.night_mode else "common.off"), - self.tr("option.high_contrast") + ": " - + self.tr("common.on" if self.preferences.high_contrast else "common.off"), - self.tr("option.frame_rate", fps=self.frame_rate()), - self.tr("option.bottom_panel") + ": " - + self.tr("option.bottom_panel." + self.bottom_panel_mode()), - self.tr("option.operator_assist") + ": " - + self.tr("option.operator_assist." + ("training" if self.operator_assist() - else "off")), - self.tr("option.live_traffic"), - self.tr("commander.local.option"), - ) - for index, (value, row) in enumerate(zip(values, self._options_row_rects())): - color = config.COLOR_TEXT if index == self.options_sel else config.COLOR_TEXT_DIM - prefix = "> " if index == self.options_sel else " " - layout.blit_line(self.screen, raw_text(prefix + value), row, color, size=20) - layout.blit_block(self.screen, - "commander.local.options_hint", - 292, 650, 696, 46, config.COLOR_TEXT_DIM, size=18, - align="center") - - def _draw_options_setup_page(self) -> None: - row = self._options_row_rects()[0] - locked = self.local_side_locked() - value = (self.tr("option.local_side") + ": " - + self.tr("option.local_side." + self.local_side)) - selected = self.options_sel == 0 - color = (config.COLOR_TEXT_DIM if locked or not selected else config.COLOR_TEXT) - layout.blit_line(self.screen, raw_text(("> " if selected else " ") + value), - row, color, size=20) - layout.blit_block(self.screen, "option.local_side.help", - row.x + 24, row.bottom + 10, row.w - 24, 150, - config.COLOR_TEXT_DIM, size=18) - if locked: - layout.blit_block(self.screen, "option.local_side.locked", - row.x + 24, row.bottom + 170, row.w - 24, 50, - config.COLOR_WARN, size=18) - layout.blit_block(self.screen, - "commander.local.options_hint", - 292, 650, 696, 46, config.COLOR_TEXT_DIM, size=18, - align="center") - - @staticmethod - def _live_traffic_row_rects(): - return tuple(pygame.Rect(292, 150 + index * 84, 696, 44) for index in range(5)) - - @staticmethod - def _mask_credential(value: str) -> str: - value = (value or "").strip() - if not value: - return "-" - return f"...{value[-4:]}" if len(value) > 4 else "*" * len(value) - - @localized - def draw_live_traffic_overlay(self) -> None: - rect = pygame.Rect(260, 40, 760, 660) - pygame.draw.rect(self.screen, config.COLOR_OVERLAY_BG, rect) - pygame.draw.rect(self.screen, config.COLOR_WARN, rect, 2) - layout.blit_line(self.screen, "live_traffic.title", (292, 64, 696, 48), - config.COLOR_WARN, size=32, align="center") - online = self.connectivity.online - status_key = ("live_traffic.online" if online - else "live_traffic.offline" if online is False - else "live_traffic.checking") - layout.blit_line(self.screen, status_key, (292, 108, 696, 28), - config.COLOR_TEXT_DIM, size=16, align="center") - rows = self._live_traffic_row_rects() - names = self._LIVE_TRAFFIC_ROWS - toggle_labels = ( - self.tr("live_traffic.ais_toggle") + ": " - + self.tr("common.on" if self.preferences.live_ais_enabled else "common.off"), - self.tr("live_traffic.adsb_toggle") + ": " - + self.tr("common.on" if self.preferences.live_adsb_enabled else "common.off"), - ) - for index in range(2): - color = (config.COLOR_TEXT if index == self.live_traffic_sel - else config.COLOR_TEXT_DIM) - if not getattr(self.preferences, names[index]) \ - and not self._live_traffic_can_enable(names[index]): - color = config.COLOR_TEXT_DIM - prefix = "> " if index == self.live_traffic_sel else " " - layout.blit_line(self.screen, raw_text(prefix + toggle_labels[index]), - rows[index], color, size=20) - for index, key in ((2, "aisstream_api_key"), (3, "opensky_credentials")): - color = config.COLOR_TEXT if index == self.live_traffic_sel else config.COLOR_TEXT_DIM - prefix = "> " if index == self.live_traffic_sel else " " - label = self.tr("live_traffic.aisstream_key" if key == "aisstream_api_key" - else "live_traffic.opensky_key") - row = rows[index] - layout.blit_line(self.screen, raw_text(prefix + label), - (row.x, row.y, row.w, 22), color, size=18) - field_rect = pygame.Rect(row.x, row.y + 24, row.w, 30) - if self.live_traffic_field is not None and self.live_traffic_field_name == key: - self.live_traffic_field.draw(self.screen, field_rect, focused=True) - else: - layout.blit_line(self.screen, - raw_text(self._mask_credential(getattr(self.preferences, key))), - field_rect, config.COLOR_TEXT_DIM, size=16) - test_row = rows[4] - color = config.COLOR_TEXT if self.live_traffic_sel == 4 else config.COLOR_TEXT_DIM - prefix = "> " if self.live_traffic_sel == 4 else " " - layout.blit_line(self.screen, raw_text(prefix + self.tr("live_traffic.test_action")), - (test_row.x, test_row.y, test_row.w, 22), color, size=18) - status_line = self.tr("live_traffic.test_result", - ais=self._live_traffic_test_label("ais"), - adsb=self._live_traffic_test_label("adsb")) - layout.blit_line(self.screen, raw_text(status_line), - (test_row.x, test_row.y + 24, test_row.w, 24), - config.COLOR_TEXT_DIM, size=16) - layout.blit_block(self.screen, - "live_traffic.hint", - 292, 636, 696, 58, config.COLOR_TEXT_DIM, size=16, - align="center") - - def _live_traffic_test_label(self, side: str) -> str: - status, reason = self.live_traffic_test_result.get(side, ("idle", None)) - if status == "running": - return self.tr("live_traffic.test_running") - if status == "no_key": - return self.tr("live_traffic.test_no_key") - if status == "ok": - return self.tr("live_traffic.test_ok") - if status == "error": - return self.tr("live_traffic.test_error", reason=(reason or "?")[:80]) - return self.tr("live_traffic.test_idle") - - @localized - def draw_quit_overlay(self) -> None: - """Require an explicit confirmation before leaving a live mission.""" - s = self.screen - dim = pygame.Surface((config.SCREEN_W, config.SCREEN_H), pygame.SRCALPHA) - dim.fill((0, 0, 0, 155)) - s.blit(dim, (0, 0)) - choices = (("quit.menu", "common.exit") if self.in_menu else - ("quit.game", "quit.save", "quit.main_menu", "quit.no_save")) - rect = pygame.Rect(260, 185 - 20 * (len(choices) - 3), - 760, 330 + 40 * (len(choices) - 3)) - pygame.draw.rect(s, config.COLOR_PANEL_BG, rect) - pygame.draw.rect(s, config.COLOR_WARN, rect, 2) - layout.blit_line(s, "quit.title", (rect.x + 20, rect.y + 22, - rect.w - 40, 36), config.COLOR_WARN, size=28) - layout.blit_line(s, "quit.warning", - (rect.x + 20, rect.y + 74, rect.w - 40, 26), - config.COLOR_TEXT, size=16) - for index, label in enumerate(choices): - selected = index == self.quit_selection - layout.blit_line(s, message("menu.choice", - marker="> " if selected else " ", - label=self.tr(label)), - (rect.x + 20, rect.y + 124 + index * 40, rect.w - 40, 32), - config.COLOR_WARN if selected else config.COLOR_TEXT, - size=22) - layout.blit_line(s, "control.quit_hint", - (rect.x + 20, rect.bottom - 44, rect.w - 40, 28), - config.COLOR_TEXT_DIM, size=18) - - # --- Main loop --- - - def _perf_debug_log(self, wall_dt: float) -> None: - """Optional 1 Hz diagnostics line, enabled via U_JAGD_PERF_DEBUG=1. - - Appends bounded per-frame-average phase timings (physics substeps, - audio publish, Remote Crew pump, draw/compose) to perf_debug.log - inside the save directory, for on-device (uConsole) CPU diagnosis. - Purely measures wall time already spent in existing calls; never - alters simulation timing, input, or rendering. No-op unless enabled. - """ - if not self._perf_debug_enabled: - return - try: - wall_dt = float(wall_dt) - except (TypeError, ValueError, OverflowError): - return - if not math.isfinite(wall_dt) or wall_dt <= 0.0: - return - self._perf_frames += 1 - self._perf_frame_max_s = max(self._perf_frame_max_s, wall_dt) - self._perf_debug_due += wall_dt - if self._perf_debug_due < 1.0: - return - self._perf_debug_due %= 1.0 - frames = self._perf_frames - line = ("t={t:.1f} fps={fps} substeps_avg={sub:.2f} sim_ms={sim:.2f} " - "audio_ms={audio:.2f} commander_ms={cmd:.2f} " - "commander_max_ms={cmdmax:.1f} events_ms={events:.2f} " - "traffic_ms={traffic:.2f} " - "draw_ms={draw:.2f} frame_max_ms={fmax:.1f} " - "sim_lag_ms={lag:.1f} sim_dropped_ms={drop:.1f}\n").format( - t=time.monotonic(), fps=frames, sub=self._perf_substeps / frames, - fmax=1000 * self._perf_frame_max_s, lag=1000 * self._sim_debt_s, - drop=1000 * self._sim_dropped_s, - sim=1000 * self._perf_sim_s / frames, - audio=1000 * self._perf_audio_s / frames, - cmd=1000 * self._perf_commander_s / frames, - cmdmax=1000 * self._perf_commander_max_s, - events=1000 * self._perf_events_s / frames, - traffic=1000 * self._perf_traffic_s / frames, - draw=1000 * self._perf_draw_s / frames) - append_bounded_log(config.SAVE_DIR, "perf_debug.log", line, - config.PERF_DEBUG_LOG_MAX_BYTES) - self._perf_frames = 0 - self._perf_sim_s = 0.0 - self._perf_substeps = 0 - self._perf_audio_s = 0.0 - self._perf_commander_s = 0.0 - self._perf_commander_max_s = 0.0 - self._perf_events_s = 0.0 - self._perf_traffic_s = 0.0 - self._perf_draw_s = 0.0 - self._perf_frame_max_s = 0.0 - - def _frame_dt(self, wall_dt: float) -> float: - """Simulation seconds for this frame from wall time and bounded debt. - - A frame never advances more than SIM_FRAME_DT_MAX, but the remainder of - a slow frame is caught up over the next frames, so simulation time (and - the sonar audio produced in it) keeps pace with wall-clock playback. - Debt above SIM_CATCHUP_MAX_S is dropped. After a pause, menu, overlay, - load or world reset the first frame is only clamped, never caught up. - """ - try: - wall_dt = float(wall_dt) - except (TypeError, ValueError, OverflowError): - wall_dt = 0.0 - if not math.isfinite(wall_dt) or wall_dt < 0.0: - wall_dt = 0.0 - if self._frame_clock_reset: - self._frame_clock_reset = False - self._sim_debt_s = 0.0 - return min(wall_dt, config.SIM_FRAME_DT_MAX) - debt = self._sim_debt_s + wall_dt - if debt > config.SIM_CATCHUP_MAX_S: - self._sim_dropped_s += debt - config.SIM_CATCHUP_MAX_S - debt = config.SIM_CATCHUP_MAX_S - dt = min(debt, config.SIM_FRAME_DT_MAX) - self._sim_debt_s = debt - dt - return dt - - def frame_rate(self) -> int: - """Active frame-rate cap from the saved preference.""" - value = getattr(self.preferences, "frame_rate", config.FPS_DEFAULT) - return value if value in config.FPS_CHOICES else config.FPS_DEFAULT - - def run(self) -> None: - try: - while self.running: - if self.auto_quit is not None: - self.auto_quit -= 1 - if self.auto_quit <= 0: - self.running = False - wall_dt = self.clock.tick(self.frame_rate()) / 1000.0 - dt = self._frame_dt(wall_dt) - self._t += dt - events_started = (time.perf_counter() - if self._perf_debug_enabled else None) - for e in pygame.event.get(): - if not self.web_mode: - self.handle_event(e) - if e.type in _ECO_REFRESH_EVENTS: - self._eco_drawn_at = float("-inf") - if events_started is not None: - self._perf_events_s += time.perf_counter() - events_started - commander_started = (time.perf_counter() - if self._perf_debug_enabled else None) - self.commander.pump(self) - if commander_started is not None: - now = time.perf_counter() - self._perf_commander_s += now - commander_started - self._perf_commander_max_s = max( - self._perf_commander_max_s, now - commander_started) - commander_started = now - self.live_traffic.pump(self) - if commander_started is not None: - self._perf_traffic_s += time.perf_counter() - commander_started - self.update(dt, audio_dt=wall_dt) - self._perf_debug_log(wall_dt) - if self.web_mode: - continue - if self._skip_eco_frame(): - continue - draw_started = time.perf_counter() if self._perf_debug_enabled else None - self.draw() - self.compose_frame() - if draw_started is not None: - self._perf_draw_s += time.perf_counter() - draw_started - finally: - try: - self.commander.stop() - finally: - try: - self.connectivity.stop() - self.live_traffic.stop() - finally: - self.audio.shutdown() - pygame.quit() - - install_station_properties(Game) diff --git a/src/core/game_draw.py b/src/core/game_draw.py new file mode 100644 index 00000000..5ac806fd --- /dev/null +++ b/src/core/game_draw.py @@ -0,0 +1,1256 @@ +"""Rendering and the main loop of the game: frame composition, the station +chrome (top bar, bottom panel, ticker), overlays (help, nations, save, end +panel, options, live traffic, quit), display preferences and the real-time +frame clock (``Game`` mixin). + +Verbatim moves from ``game.py`` (plan 1.3, phase 2, step 4b).""" + +import math +import time + +import pygame + +from src.audio.engine import AudioEngine +from src.core import config +from src.core.debuglog import append_bounded_log +from src.core.i18n import (Translator, display_value, localized, localize, + message, raw_text, translation_scope) +from src.core.preferences import save_preferences +from src.core.help import get_global_help, get_help, get_sop, get_uboot_help +from src.core import manual +from src.core.station import Station +from src.core import uboot_local +from src.nations.nations import reference_summary +from src.ui import layout +from src.ui import observations +from src.ui.map_view import draw_map_view +from src.ui.splash_view import draw_splash +from src.ui.sonar_view import draw_sonar_view +from src.ui.weather_station import draw_weather_station +from src.ui import uboot_view +from src.ui.stations_view import ( + draw_autocrew_overview, + draw_bridge_view, + draw_damage_view, + draw_eloka_view, + draw_engine_view, + draw_opz_view, + draw_radio_view, + draw_helicopter_view) +from src.ui.stations_view import opz_ppi_rect +from src.ui.mission_editor import MissionEditor +from src.ui.simlog_view import draw_simlog_view +from src.ui.weapons_view import draw_weapons_overlay, draw_weapons_panel +# Shared display/help constants and helpers (re-exported for tests/tools). +from src.core.game_shared import HELP_MANUAL_PAGE, HELP_PAGE_COUNT, letterbox_layout +# Names tests and tools import from ``src.core.game`` (kept as re-exports). +from src.core.game_events import _ECO_REFRESH_EVENTS + + +class DrawMixin: + """Display half of ``Game``: ``draw``, the overlays and ``run``.""" + + def flash_banner_rect(self) -> pygame.Rect: + """Opaque, text-sized banner in the free right part of the top bar. + + It starts right of the status line, so it never prints over a map, + station tabs or chart labels; only a message too long for one line + grows downward (at most two lines). + """ + face = layout.font(layout.scaled_size(self.FLASH_TEXT_SIZE)) + left = max(config.SCREEN_W // 2, + getattr(self, "_top_status_right", 0) + 16) + max_w = config.SCREEN_W - 6 - left + lines = layout.wrap_text(localize(self.msg), face, max_w - 20) + lines = lines[:self.FLASH_MAX_LINES] or [""] + width = min(max_w, max(face.size(line)[0] for line in lines) + 20) + height = max(config.TOP_BAR_H - 4, + len(lines) * layout._line_height(face) + 6) + return pygame.Rect(config.SCREEN_W - 6 - width, 2, width, height) + + def _draw_flash_banner(self, surface) -> None: + # The banner covers what lies beneath it instead of printing over + # the map and the station tabs. + box = self.flash_banner_rect() + pygame.draw.rect(surface, config.COLOR_OVERLAY_BG, box) + pygame.draw.rect(surface, config.COLOR_WARN, box, 1) + layout.blit_block(surface, localize(self.msg), box.x + 10, box.y + 3, + box.w - 20, box.h - 6, config.COLOR_WARN, + size=self.FLASH_TEXT_SIZE, align="center", valign="center") + + def compose_frame(self) -> None: + """Virtuellen 1280x720-Canvas aufs Display bringen (M8/M9). + + FILL_SCREEN=True: Stretch auf die volle Fläche (keine schwarzen + Balken bei 16:9); False: aspect-correctes Letterbox. + """ + w, h = pygame.display.get_window_size() + if w <= 0 or h <= 0: + w, h = config.SCREEN_W, config.SCREEN_H + # Unter X11/XWayland ersetzt pygame die Display-Surface nach dem ersten + # Event-Pump/Resize durch ein neues Objekt; das gemerkte self.display + # ist dann 0x0 und der Blit scheitert mit "Surfaces must not be locked". + display = pygame.display.get_surface() + if display is None: + return + self.display = display + display.fill((0, 0, 0)) + if (w, h) == (config.SCREEN_W, config.SCREEN_H): + display.blit(self.screen, (0, 0)) + elif config.FILL_SCREEN: + display.blit(pygame.transform.scale(self.screen, (w, h)), (0, 0)) + else: + _, ox, oy, sw, sh = letterbox_layout(w, h) + display.blit( + pygame.transform.scale(self.screen, (sw, sh)), (ox, oy)) + pygame.display.flip() + + # --- Input --- + + @localized + def draw_menu(self) -> None: + """W4: Szenario -> (Level bei s4) -> Briefing -> Start.""" + s = self.screen + s.fill(config.COLOR_BG) + cx = config.SCREEN_W // 2 + + def center(text: str, y: int, font=None, color=config.COLOR_TEXT) -> None: + f = font or self.menu_font + text = localize(text) + surf = f.render(text, True, color) + s.blit(surf, surf.get_rect(center=(cx, y))) + + center("U-JAGD – FREGATTE F-217", 100, self.menu_font_big) + + if self.main_menu: + labels = ("menu.new_game", "menu.load", "menu.mission_editor", + "menu.unit_editor", "menu.contact_analyzer", "option.title", + "menu.quit") + for i, key in enumerate(labels): + marker = "> " if i == self.main_menu_sel else " " + color = config.COLOR_TEXT if i == self.main_menu_sel else config.COLOR_TEXT_DIM + center(message("menu.choice", marker=marker, + label=self.tr(key).upper()), 185 + i * 47, color=color) + elif self.menu_screen == "side": + center(self.tr("menu.choose_side"), 170, color=config.COLOR_TEXT_DIM) + for i, side in enumerate(("frigate", "uboot")): + selected = i == self.menu_sel + center(message("menu.choice", marker="► " if selected else " ", + label=self.tr(f"menu.side.{side}")), + 250 + i * 90, self.menu_font_big if selected else None, + config.COLOR_TEXT if selected else config.COLOR_TEXT_DIM) + layout.blit_line(s, f"menu.side.{side}.note", (cx - 420, 285 + i * 90, 840, 26), + config.COLOR_TEXT_DIM, size=18, align="center") + center(self.tr("menu.side_hint"), 470, color=config.COLOR_TEXT_DIM) + elif self.menu_screen == "scenario": + center(self.tr("menu.choose_scenario"), + 150, color=config.COLOR_TEXT_DIM) + scenario_names = {"s1_patrouille": "patrol", "s2_doppeljagd": "double", + "s3_abfang": "intercept", "s4_zufall": "random"} + for i, key in enumerate(config.SCENARIO_ORDER): + sc = config.SCENARIOS[key] + marker = "► " if i == self.menu_sel else " " + col = config.COLOR_TEXT if i == self.menu_sel \ + else config.COLOR_TEXT_DIM + lv = self.tr("menu.difficulty_fixed" if sc["difficulty"] is not None + else "menu.difficulty_custom") + title = self.tr("scenario." + scenario_names[key] + ".title") + center(message("menu.scenario_choice", index=i + 1, + marker=marker, title=title, level=lv), + 240 + i * 40, color=col) + elif self.menu_screen == "difficulty": + center(self.tr("menu.choose_difficulty"), + 150, color=config.COLOR_TEXT_DIM) + row_h = 26 + for i, name in enumerate(config.DIFFICULTY_FIELD_ORDER): + kind, _low, _high, _step, _default = config.DIFFICULTY_FIELDS[name] + marker = "► " if i == self.menu_sel else " " + col = config.COLOR_TEXT if i == self.menu_sel \ + else config.COLOR_TEXT_DIM + value = self.menu_difficulty[name] + value_text = (str(value) if kind is int + else f"{value:.3f}".rstrip("0").rstrip(".")) + center(message("menu.difficulty_choice", marker=marker, + label=self.tr("difficulty." + name), + value=value_text), + 190 + i * row_h, color=col) + i = len(config.DIFFICULTY_FIELD_ORDER) + selected = i == self.menu_sel + center(message("menu.difficulty_choice", + marker="► " if selected else " ", + label=self.tr("menu.hq_intel"), + value=self.tr("menu.hq_intel." + self.hq_intel_mode_menu())), + 190 + i * row_h, + color=config.COLOR_TEXT if selected else config.COLOR_TEXT_DIM) + else: # briefing + sc = config.SCENARIOS[self.scenario_key] + scenario_key = {"s1_patrouille": "patrol", "s2_doppeljagd": "double", + "s3_abfang": "intercept", "s4_zufall": "random"}[self.scenario_key] + center(self.tr("scenario." + scenario_key + ".title"), 170, + self.menu_font_big, config.COLOR_WARN) + layout.blit_block(s, self.tr("scenario." + scenario_key + ".brief"), + cx - 420, 210, 840, 180, + color=config.COLOR_TEXT, size=20) + if sc["win_text"]: + center(message("menu.goal_value", + goal=self.tr("scenario." + scenario_key + ".win")), + 420, color=config.COLOR_OK) + if sc["lose_text"]: + center(message("menu.loss_value", + loss=self.tr("scenario." + scenario_key + ".lose")), 448, + color=config.COLOR_DANGER) + center(self.tr("menu.start_hint"), 520, + color=config.COLOR_TEXT_DIM) + center(message("menu.local_side", side=message( + "menu.local_side.uboot" if self.local_side == "uboot" + else "menu.local_side.frigate")), 556, + color=config.COLOR_WARN if self.local_side == "uboot" + else config.COLOR_TEXT_DIM) + + if self.world_mode in ("procedural", "real_fixed"): + from src.world.real_coast import sector_for_seed + sector, _ = sector_for_seed(self.seed) + world_label = sector["name"] + if self.world_mode == "real_fixed": + center(self.tr("menu.real_fixed_hint", sector=sector["id"]), + config.SCREEN_H - 95, color=config.COLOR_TEXT_DIM) + else: + world_label = self.tr("menu.fixed_chart") + center(self.tr("menu.world_status", world=world_label, seed=self.seed), + config.SCREEN_H - 68, color=config.COLOR_OK) + center(self.tr("menu.seed_fullscreen", seed=self.seed, + action=self.tr("menu.windowed" if self.fullscreen + else "menu.fullscreen")), + config.SCREEN_H - 40, color=config.COLOR_TEXT_DIM) + + # --- W0: Draw-Grid --- + + @property + def _station_overlay_open(self) -> bool: + """A full-station overlay (F3 autocrew, 0 weather) replaces the station.""" + return self.autocrew_overview_open or self.weather_station_open + + @localized + def _eco_display_active(self) -> bool: + """Solo browser is live: the uConsole shows a cheap status screen. + + Pure display decision; it never touches simulation state, saves or input. + """ + return (self.running and not self.splash_active and self.editor is None + and not self.simlog_view_open and not self.in_menu + and not self.main_menu and not self.administration_open + and not self.game_over and not self._station_overlay_open + and self.commander.eco_display_ready(self)) + + def _skip_eco_frame(self) -> bool: + """True while the last eco frame is still current (draw and blit skipped).""" + if not self._eco_display_active(): + self._eco_drawn_at = float("-inf") + return False + if self._t - self._eco_drawn_at < config.ECO_REDRAW_S: + return True + self._eco_drawn_at = self._t + return False + + @localized + def draw_eco_display(self) -> None: + s = self.screen + panel = pygame.Rect(240, 90, 800, 360) + layout.panel(s, panel) + x, w = panel.x + 24, panel.w - 48 + layout.blit_line(s, "eco.title", (x, panel.y + 16, w, 36), + config.COLOR_WARN, size=28, align="center") + layout.blit_block(s, "eco.subtitle", x, panel.y + 66, w, 66, + config.COLOR_TEXT, size=20, align="center", valign="center") + address = getattr(self.commander, "address", None) + if address is not None: + url = raw_text(f"http://{address[0]}:{address[1]}/") + proxy = getattr(self.commander, "public_origin", None) + layout.blit_line(s, message("commander.local.url_proxy", url=url, + proxy=raw_text(proxy + "/")) + if proxy else message("commander.local.url", url=url), + (x, panel.y + 150, w, 32), config.COLOR_TEXT, size=22, align="center") + layout.blit_line(s, message( + "eco.state.running", time=raw_text(self.world.format_time())), + (x, panel.y + 200, w, 32), config.COLOR_OK, + size=24, align="center") + layout.blit_line(s, "eco.hint", (x, panel.bottom - 56, w, 30), + config.COLOR_TEXT_DIM, size=16, align="center") + + def draw(self) -> None: + # One translation scope for the whole frame: text drawn directly here + # (flash banner, overlays) must follow the game language, not the + # process-wide default translator. + with layout.bottom_panel_regions(self.bottom_panel_mode()), \ + translation_scope(self.tr): + self._draw() + + def _draw(self) -> None: + self._apply_text_size() + s = self.screen + eco = self._eco_display_active() + s.fill(config.COLOR_BG) + if self.splash_active: + draw_splash(s, self._t - self.splash_started_at, self.tr) + elif self.editor is not None: + self.editor.draw(s) + if isinstance(self.editor, MissionEditor) and self.editor.mode == "browser": + hint = self.font.render(localize("F5: start selected runtime-compatible mission"), + True, config.COLOR_OK) + s.blit(hint, (config.SCREEN_W - hint.get_width() - 20, + config.SCREEN_H - 68)) + elif self.simlog_view_open: + draw_simlog_view(self) + elif self.in_menu: + self.draw_menu() + elif self.local_side == "uboot": + uboot_view.draw(self) + elif eco: + self.draw_top_bar() + self.draw_eco_display() + self.draw_bottom_panel() + else: + self.draw_top_bar() + map_station = (not self._station_overlay_open + and self._map_station_visible()) + previous_rect = config.STATION_RECT + try: + config.STATION_RECT = (config.STATION_PANEL_RECT if map_station else + # The weather panel takes the whole + # screen below the top bar. + config.OPZ_STATION_RECT + if self.weather_station_open + or (self.station is Station.OPZ + and not self._station_overlay_open) else + config.FULL_STATION_RECT) + if self.autocrew_overview_open: + with layout.clip_to(s, config.STATION_RECT): + draw_autocrew_overview(self) + elif self.weather_station_open: + with layout.clip_to(s, config.STATION_RECT): + draw_weather_station(self) + elif map_station: + draw_map_view(self) + if self.station is Station.WEAPONS: + draw_weapons_overlay(self) + if not self._station_overlay_open: + with layout.clip_to(s, config.STATION_RECT): + if self.station is Station.SONAR: + draw_sonar_view(self) + elif self.station is Station.WEAPONS: + draw_weapons_panel(self) + elif self.station is Station.DAMAGE: + draw_damage_view(self) + elif self.station is Station.OPZ: + draw_opz_view(self) + elif self.station is Station.RADIO: + draw_radio_view(self) + elif self.station is Station.ENGINE: + draw_engine_view(self) + elif self.station is Station.HELICOPTER: + draw_helicopter_view(self) + elif self.station is Station.ELOKA: + draw_eloka_view(self) + else: + draw_bridge_view(self) + if (self.station is not Station.OPZ and not self.weather_station_open + and not self.feed_overlay_open): + self.draw_bottom_panel() + if self.feed_overlay_open: + self.draw_feed_overlay() + self.draw_navigation_input() + if self.game_over: + self.draw_end_panel() + finally: + config.STATION_RECT = previous_rect + if self.quit_confirm: + self.draw_quit_overlay() + elif self.help_open: + self.draw_help_overlay() + elif self.nations_open: + self.draw_nations_overlay() + elif self.save_ui is not None: + self.draw_save_ui() + elif self.options_open: + self.draw_options_overlay() + elif self.live_traffic_open: + self.draw_live_traffic_overlay() + elif self.commander_open: + self.commander.draw(self) + self.commander.draw_confirm(self) + if self.msg and self._t < self.msg_until: + self._draw_flash_banner(s) + if (not self.in_menu and not self.splash_active and self.editor is None + and not self.simlog_view_open and not self._station_overlay_open + and self.tooltips_enabled and not eco + and self.local_side != "uboot" + and not self.administration_open and not self.game_over): + canvas = self._window_to_canvas(pygame.mouse.get_pos()) + payload = self.pinned_tooltip or self.tooltip_at(canvas) + anchor = self._tooltip_anchor if self.pinned_tooltip else canvas + if payload is not None and anchor is not None: + layout.draw_tooltip(s, payload, anchor, + (0, 0, config.SCREEN_W, config.SCREEN_H)) + if self._scanlines is not None: + s.blit(self._scanlines, (0, 0)) + if self.preferences.night_mode: + s.blit(self._night_overlay, (0, 0), special_flags=pygame.BLEND_MULT) + + @localized + def draw_navigation_input(self) -> None: + """Show the active numeric command without hiding the simulation.""" + if self.input_mode is None: + return + label = self.tr("input." + self.input_mode) + rect = pygame.Rect(280, 88, 720, 70) + pygame.draw.rect(self.screen, config.COLOR_OVERLAY_BG, rect) + pygame.draw.rect(self.screen, config.COLOR_WARN, rect, 2) + layout.blit_line(self.screen, self.tr("input.value", label=label, + value=self.input_buffer), + (rect.x + 14, rect.y + 8, rect.w - 28, 26), + config.COLOR_TEXT, size=20) + layout.blit_line(self.screen, self.tr("input.hint"), + (rect.x + 14, rect.y + 38, rect.w - 28, 22), + config.COLOR_TEXT_DIM, size=14) + + @localized + def top_bar_scenario(self) -> str: + """Mission title shown in the top status bar.""" + if self.custom_mission_definition is not None: + return localize(self.mission_name_display()) + return self.tr("scenario." + {"s1_patrouille": "patrol", "s2_doppeljagd": "double", + "s3_abfang": "intercept", "s4_zufall": "random"} + [self.scenario_key] + ".title") + + def draw_top_bar(self) -> None: + layout.configure_for(self) + s = self.screen + pygame.draw.rect(s, config.COLOR_PANEL_BG, (0, 0, config.SCREEN_W, config.TOP_BAR_H)) + pygame.draw.line(s, config.COLOR_SONAR_RING, + (0, config.TOP_BAR_H - 1), + (config.SCREEN_W, config.TOP_BAR_H - 1), 1) + station = display_value("station", self.station.name, self.tr).upper() + scenario = self.top_bar_scenario() + txt = self.tr("top.status", station=station, scenario=scenario, + time=self.world.format_time(), speed=f"{self.ship.speed:4.1f}", + course=f"{self.ship.course:4.0f}") + layout.blit_line(s, txt, (10, 4, config.SCREEN_W - 20, + config.TOP_BAR_H - 8), + config.COLOR_TEXT, size=18) + self._top_status_right = 10 + layout.font(layout.scaled_size(18)).size( + localize(txt))[0] + + def draw_bottom_panel(self, entries=None, rows=None, heading="feed.heading", + ticker_keys=None, ticker_hint="ticker.hint") -> None: + """Event feed and telemetry: docked band or one status ticker. + + ``entries``/``rows`` replace the frigate's feed and telemetry (the + crewed submarine's own log and readings use the same band). + """ + if self.bottom_panel_mode() == "ticker": + self.draw_status_ticker(entries, rows, ticker_keys, ticker_hint) + else: + self.draw_bottom_feed(entries, heading) + self.draw_bottom_telemetry(rows) + + def _feed_lines(self, width: int, face, entries=None) -> list: + """Wrap feed entries (oldest first) into (text, colour, is_first) rows. + + Entries wrap onto continuation lines under the text column; nothing + is ever cut off with an ellipsis. + """ + rows = [] + for entry in self.feed.entries if entries is None else entries: + prefix = f"[{entry.stamp}] {entry.tag():4s} " + indent = face.size(prefix)[0] + wrapped = layout.wrap_text(localize(entry.text), face, + max(40, width - indent)) or [""] + rows.append((prefix, wrapped[0], entry.color(), indent)) + rows.extend(("", line, entry.color(), indent) for line in wrapped[1:]) + return rows + + def _blit_feed_rows(self, rect, rows, scroll: int = 0) -> None: + """Draw wrapped feed rows bottom-up (newest at the bottom).""" + face = layout.font(16) + pitch = layout._line_height(face) + visible = max(1, rect.h // pitch) + end = max(0, len(rows) - scroll) + shown = rows[max(0, end - visible):end] + y = rect.bottom - len(shown) * pitch + with layout.clip_to(self.screen, rect): + for prefix, text, color, indent in shown: + if prefix: + layout.blit_line(self.screen, raw_text(prefix), + (rect.x, y, indent, pitch), + config.COLOR_TEXT_DIM, size=16) + layout.blit_line(self.screen, raw_text(text), + (rect.x + indent, y, rect.w - indent, pitch), + color, size=16) + y += pitch + + @localized + def draw_bottom_feed(self, entries=None, heading="feed.heading") -> None: + s = self.screen + x, y, w, h = config.FEED_RECT + pygame.draw.rect(s, config.COLOR_FEED_BG, (x, y, w, h)) + pygame.draw.rect(s, config.COLOR_SONAR_RING, (x, y, w, h), 1) + layout.blit_line(s, heading, (x + 8, y + 3, w - 16, 20), + config.COLOR_TEXT_DIM, size=16) + body = pygame.Rect(x + 8, y + 25, w - 16, h - 29) + face = layout.font(16) + self._blit_feed_rows(body, self._feed_lines(body.w, face, entries)) + + @localized + def draw_bottom_telemetry(self, rows=None) -> None: + s = self.screen + x, y, w, h = config.TELEMETRY_RECT + pygame.draw.rect(s, config.COLOR_FEED_BG, (x, y, w, h)) + pygame.draw.rect(s, config.COLOR_SONAR_RING, (x, y, w, h), 1) + layout.blit_line(s, "panel.telemetry", (x + 8, y + 3, w - 16, 20), + config.COLOR_TEXT_DIM, size=16) + self._blit_telemetry_rows(pygame.Rect(x + 8, y + 25, w - 16, h - 29), + short=True, rows=rows) + + def _blit_telemetry_rows(self, rect, short: bool, rows=None) -> None: + face = layout.font(16) + rows = observations.telemetry_rows(self) if rows is None else rows + pitch = max(layout._line_height(face), rect.h // max(1, len(rows))) + labels = [localize(observations.telemetry_label(key, short)) + for key, *_rest in rows] + label_w = max(face.size(label)[0] for label in labels) + 10 + colors = {"ok": config.COLOR_TEXT, "warn": config.COLOR_WARN, + "danger": config.COLOR_DANGER} + for index, ((_key, value, level, _compact), label) in enumerate(zip(rows, labels)): + y = rect.y + index * pitch + layout.blit_line(self.screen, raw_text(label), (rect.x, y, label_w, pitch), + config.COLOR_TEXT_DIM, size=16) + layout.blit_line(self.screen, value, (rect.x + label_w, y, + rect.w - label_w, pitch), + colors[level], size=16) + + def _ticker_telemetry_text(self, width: int | None = None, rows=None, + keys=None) -> str: + """Compact telemetry for the ticker, most important readings first. + + Readings that do not fit are left out whole (never clipped); the + F11 overlay always shows all of them. + """ + parts = [] + keys = observations.TICKER_KEYS if keys is None else keys + rows = observations.telemetry_rows(self) if rows is None else rows + for key, _value, _level, compact in rows: + if key in keys: + label = observations.telemetry_label(key, short=True) + parts.append(f"{localize(label)} {localize(compact)}") + face = layout.font(16) + while width is not None and len(parts) > 1 and face.size( + " \u00b7 ".join(parts))[0] > width: + parts.pop() + return " \u00b7 ".join(parts) + + @localized + def draw_status_ticker(self, entries=None, rows=None, keys=None, + hint_key="ticker.hint") -> None: + """One 22 px strip: newest event (scrolls if long) + key telemetry.""" + s = self.screen + rect = layout.ticker_rect() + pygame.draw.rect(s, config.COLOR_FEED_BG, rect) + pygame.draw.line(s, config.COLOR_SONAR_RING, rect.topleft, rect.topright, 1) + face = layout.font(16) + rows = observations.telemetry_rows(self) if rows is None else rows + telemetry = self._ticker_telemetry_text(int(rect.w * .6) - 16, rows, keys) + level = ("danger" if any(row[2] == "danger" for row in rows) + else "warn" if any(row[2] == "warn" for row in rows) else "ok") + colors = {"ok": config.COLOR_TEXT, "warn": config.COLOR_WARN, + "danger": config.COLOR_DANGER} + tele_w = face.size(telemetry)[0] + 16 + tele_rect = pygame.Rect(rect.right - tele_w, rect.y + 2, tele_w - 8, rect.h - 2) + layout.blit_line(s, raw_text(telemetry), tele_rect, colors[level], + size=16, align="right") + hint = localize(hint_key) if hint_key else "" + hint_w = face.size(hint)[0] + 12 if hint else 0 + if hint: + layout.blit_line(s, raw_text(hint), (rect.x + 6, rect.y + 2, hint_w, rect.h - 2), + config.COLOR_TEXT_DIM, size=16) + feed_rect = pygame.Rect(rect.x + 6 + hint_w, rect.y + 2, + tele_rect.x - 12 - (rect.x + 6 + hint_w), rect.h - 2) + latest = self.feed.recent(1) if entries is None else list(entries)[-1:] + if not latest or feed_rect.w <= 20: + return + entry = latest[0] + text = f"[{entry.stamp}] {entry.tag()} {localize(entry.text)}" + width = face.size(text)[0] + with layout.clip_to(s, feed_rect): + if width <= feed_rect.w: + layout.blit_line(s, raw_text(text), feed_rect, entry.color(), size=16) + else: + # Marquee instead of an ellipsis: the full line stays readable. + gap = 60 + offset = int(self._t * config.TICKER_SCROLL_PX_S) % (width + gap) + surface = layout.font(16).render(text, True, entry.color()) + s.blit(surface, (feed_rect.x - offset, feed_rect.y)) + s.blit(surface, (feed_rect.x - offset + width + gap, feed_rect.y)) + + def feed_overlay_rect(self) -> pygame.Rect: + return pygame.Rect(0, config.SCREEN_H - 330, config.SCREEN_W, 330) + + @localized + def draw_feed_overlay(self) -> None: + """F11: full event history and telemetry over the station (display only).""" + s = self.screen + rect = self.feed_overlay_rect() + shade = pygame.Surface(rect.size, pygame.SRCALPHA) + shade.fill((*config.COLOR_FEED_BG, 238)) + s.blit(shade, rect.topleft) + pygame.draw.rect(s, config.COLOR_WARN, rect, 1) + tele_w = 360 + feed = pygame.Rect(rect.x + 10, rect.y + 30, rect.w - tele_w - 30, rect.h - 40) + tele = pygame.Rect(rect.right - tele_w - 10, rect.y + 30, tele_w, rect.h - 40) + face = layout.font(16) + rows = self._feed_lines(feed.w, face) + visible = max(1, feed.h // layout._line_height(face)) + self.feed_overlay_scroll = max(0, min(self.feed_overlay_scroll, + len(rows) - visible)) + layout.blit_line(s, message("feed.overlay.title", + shown=min(len(rows), visible), total=len(rows)), + (rect.x + 10, rect.y + 5, feed.w, 22), config.COLOR_WARN, + size=16) + layout.blit_line(s, "panel.telemetry", (tele.x, rect.y + 5, tele.w, 22), + config.COLOR_WARN, size=16) + self._blit_feed_rows(feed, rows, self.feed_overlay_scroll) + pygame.draw.line(s, config.COLOR_SONAR_RING, (tele.x - 10, feed.y), + (tele.x - 10, feed.bottom), 1) + self._blit_telemetry_rows(pygame.Rect(tele.x, tele.y, tele.w, 7 * 26), + short=False) + layout.blit_block(s, "feed.overlay.hint", tele.x, tele.bottom - 44, tele.w, + 44, config.COLOR_TEXT_DIM, size=16) + + def _help_lines(self) -> tuple[list[str], int]: + """Wrap before scrolling so every line remains reachable at either size.""" + layout.configure_for(self) + intro, keys, params, tactics = get_help(self.station, self.tr) + face = layout.font(18) + visible = max(1, 500 // layout._line_height(face)) + if self.help_page == HELP_MANUAL_PAGE: + chapter = manual.CHAPTERS[self.help_manual_chapter % len(manual.CHAPTERS)] + blocks = manual.chapter_blocks(chapter, manual.manual_language(self.tr)) + width = max(20, 960 // max(1, face.size("M")[0])) + # Leading blanks survive word wrapping only as no-break spaces. + lines = [line[:len(line) - len(line.lstrip(" "))].replace(" ", "\u00a0") + + line.lstrip(" ") for line in manual.text_lines(blocks, width)] + return lines, visible + if self.help_page == 0: + title, bindings = get_global_help(self.tr) + text = title + "\n\n" + "\n".join(f"{k:<18} {a}" for k, a in bindings) + elif self.help_page == 1 and self.local_side == "uboot": + title, bindings = get_uboot_help(self.tr) + text = title + "\n\n" + "\n".join(f"{k:<18} {a}" for k, a in bindings) + elif self.help_page == 1: + sop = get_sop(self.station, self.tr) + text = (intro + "\n\n" + "\n".join(f"{k:<18} {a}" for k, a in keys) + + "\n\n" + self.tr("help.sop.title") + "\n" + + "\n".join(f"{n}. {step}" for n, step in enumerate(sop, 1))) + else: + text = self.tr("help.sensors_tactics") + "\n\n" + "\n\n".join(params + tactics) + return layout.wrap_text(text, face, 960), visible + + @localized + def draw_help_overlay(self) -> None: + layout.configure_for(self) + s = self.screen + dim = pygame.Surface((config.SCREEN_W, config.SCREEN_H), pygame.SRCALPHA) + dim.fill((0, 0, 0, 170)) + s.blit(dim, (0, 0)) + bw, bh = 1000, 620 + bx = (config.SCREEN_W - bw) // 2 + by = (config.SCREEN_H - bh) // 2 + pygame.draw.rect(s, config.COLOR_PANEL_BG, (bx, by, bw, bh)) + pygame.draw.rect(s, config.COLOR_SONAR_RING, (bx, by, bw, bh), 2) + help_title = self.tr("help.title", station=display_value( + "station", self.station.name, self.tr).upper()) + layout.blit_line(s, help_title, (bx + 18, by + 10, bw - 36, 40), + config.COLOR_TEXT, size=30) + x = bx + 20 + w = bw - 40 + y = by + 52 + lines, visible = self._help_lines() + scroll = min(getattr(self, "help_scroll", 0), max(0, len(lines) - visible)) + body = "\n".join(lines[scroll:scroll + visible]) + if self.help_page == HELP_MANUAL_PAGE: + body = raw_text(body) + hint = self.tr("help.manual.hint", + chapter=self.help_manual_chapter % len(manual.CHAPTERS) + 1, + chapters=len(manual.CHAPTERS), first=scroll + 1, + last=min(len(lines), scroll + visible), total=len(lines)) + else: + hint = self.tr("control.help.scroll_hint", page=self.help_page + 1, + pages=HELP_PAGE_COUNT, first=scroll + 1, + last=min(len(lines), scroll + visible), total=len(lines)) + layout.blit_block(s, body, x, y, w, 500, config.COLOR_TEXT, size=18, min_size=18) + layout.blit_block(s, hint, x, by + bh - 62, w, 54, config.COLOR_TEXT_DIM, size=16) + + @localized + def draw_nations_overlay(self) -> None: + s = self.screen + dim = pygame.Surface((config.SCREEN_W, config.SCREEN_H), pygame.SRCALPHA) + dim.fill((0, 0, 0, 160)) + s.blit(dim, (0, 0)) + bw, bh = 1100, 620 + bx = (config.SCREEN_W - bw) // 2 + by = (config.SCREEN_H - bh) // 2 + pygame.draw.rect(s, config.COLOR_PANEL_BG, (bx, by, bw, bh)) + pygame.draw.rect(s, config.COLOR_SONAR_RING, (bx, by, bw, bh), 2) + layout.blit_line(s, "panel.nations", (bx + 18, by + 12, bw - 36, 38), + config.COLOR_TEXT, size=30) + summary = getattr(self, "_nations_summary", None) + if summary is None: + summary = reference_summary(self.world.coast, self.runtime_catalog) + self._nations_summary = summary + legacy_country_names = { + "HANSE": "nations.country.hanse", + "BOREN": "nations.country.boren", + "SKANDIA": "nations.country.skandia", + } + countries = ", ".join(self.tr(legacy_country_names[c]) + if c in legacy_country_names else c + for c in summary["countries"]) or self.tr("nations.none") + cards = ( + ("nations.area", self.tr("nations.countries", countries=countries) + + "\n\n" + self.tr("nations.reference_note"), config.COLOR_FLIGHT), + ("nations.friendly", "\n".join(summary["friendly"]), config.COLOR_OK), + ("nations.hostile", self.tr("nations.subs", count=len(summary["hostile_subs"])) + + "\n" + ", ".join(summary["hostile_subs"]) + + "\n\n" + self.tr("nations.surfaces", count=len(summary["hostile_surfaces"])) + + "\n" + ", ".join(summary["hostile_surfaces"]), config.COLOR_DANGER), + ("nations.other", self.tr("nations.neutral_military", count=summary["neutral_military"]) + + "\n\n" + self.tr("nations.civilian", count=summary["civilian"]) + + "\n\n" + self.tr("nations.catalog_hint"), config.COLOR_CONTACT_ZIVIL), + ) + cw, ch = 520, 260 + for i, (title, body, color) in enumerate(cards): + cx = bx + 18 + (i % 2) * (cw + 14) + cyy = by + 52 + (i // 2) * (ch + 12) + pygame.draw.rect(s, config.COLOR_PANEL_BG, (cx, cyy, cw, ch)) + pygame.draw.rect(s, color, (cx, cyy, cw, ch), 1) + layout.blit_line(s, title, (cx + 12, cyy + 8, cw - 24, 36), color, size=24) + layout.blit_block(s, body, cx + 12, cyy + 50, cw - 24, ch - 58, + color=config.COLOR_TEXT, size=18) + layout.blit_line(s, "nations.close", (bx + bw - 160, by + bh - 30, 140, 24), + config.COLOR_TEXT_DIM, size=16, align="right") + + @localized + def draw_save_ui(self) -> None: + s = self.screen + mode = self.tr("common.save" if self.save_ui == "save" else "common.load").upper() + dim = pygame.Surface((config.SCREEN_W, config.SCREEN_H), pygame.SRCALPHA) + dim.fill((0, 0, 0, 150)) + s.blit(dim, (0, 0)) + bw, bh = 660, 380 + bx = (config.SCREEN_W - bw) // 2 + by = (config.SCREEN_H - bh) // 2 + pygame.draw.rect(s, config.COLOR_PANEL_BG, (bx, by, bw, bh)) + pygame.draw.rect(s, config.COLOR_SONAR_RING, (bx, by, bw, bh), 2) + layout.blit_line(s, self.tr("save.title", mode=mode), + (bx + 18, by + 14, bw - 36, 34), config.COLOR_TEXT, size=22) + ly = by + 70 + for slot in range(1, 6): + info = self.save_info[slot - 1] if len(self.save_info) == 5 else "--" + selected = slot == self.save_slot + col = config.COLOR_WARN if selected else config.COLOR_TEXT_DIM + layout.blit_line(s, message("save.slot", marker=">" if selected else " ", + slot=slot, info=localize(info)), + (bx + 24, ly, bw - 48, 32), col, size=19) + ly += 42 + hint = "save.live" + if self.save_confirm: + hint = ("save.overwrite" if self.save_ui == "save" + else "save.replace") + layout.blit_line(s, hint, (bx + 18, by + bh - 54, bw - 36, 34), + config.COLOR_WARN, size=18) + + @localized + def draw_end_panel(self) -> None: + """M8: Endpanel mit Score-Bruchrechnung und Hinweisen.""" + s = self.screen + dim = pygame.Surface((config.SCREEN_W, config.SCREEN_H), pygame.SRCALPHA) + dim.fill((0, 0, 0, 140)) + s.blit(dim, (0, 0)) + w, h = 700, 340 + x = (config.SCREEN_W - w) // 2 + y = (config.SCREEN_H - h) // 2 + pygame.draw.rect(s, (12, 26, 18), (x, y, w, h)) + pygame.draw.rect(s, config.COLOR_TEXT_DIM, (x, y, w, h), 2) + col = config.COLOR_OK if self.mission_result == "SIEG" else config.COLOR_DANGER + result = self.tr("end.victory" if self.mission_result == "SIEG" + else "end.defeat") + lines = [ + (message("end.result", result=result, + reason=localize(self.result_reason)), col, True), + ("", config.COLOR_TEXT, False), + (message("end.score_value", score=self.score), config.COLOR_TEXT, True), + (message("end.mission_level", mission=self.mission_name_display(), + level=self.mission_level_display()), + config.COLOR_TEXT_DIM, False), + (message("end.time_remaining", + remaining=self.mission.format_remaining(self.mission_time)) + if (self.mission_result == "SIEG" + or self.mission_time < self.mission.time_limit_s) + else "end.expired", + config.COLOR_TEXT_DIM, False), + ("", config.COLOR_TEXT, False), + ("end.restart", config.COLOR_TEXT_DIM, False), + ] + ly = y + 44 + for text, c, big in lines: + if not text: + ly += 16 + continue + size = 26 if big else 20 + height = 36 if big else 26 + layout.blit_line(s, text, (x + 16, ly, w - 32, height), c, + size=size, align="center") + ly += 42 if big else 30 + + @classmethod + def _options_row_rects(cls): + return tuple(pygame.Rect(292, 118 + index * 40, 696, 36) + for index in range(max(len(page) for page in cls._OPTION_PAGES))) + + @classmethod + def _options_page_rects(cls): + """Clickable page tabs left and right of the options title.""" + return tuple(pygame.Rect(292 + index * 590, 70, 106, 36) + for index in range(len(cls._OPTION_PAGES))) + + def _option_rows(self) -> tuple: + page = self.options_page if 0 <= self.options_page < len(self._OPTION_PAGES) else 0 + return self._OPTION_PAGES[page] + + def _set_options_page(self, page: int) -> None: + self.options_page = page % len(self._OPTION_PAGES) + self.options_sel = 0 + + def local_side_locked(self) -> bool: + """The uConsole's side is chosen outside a mission only.""" + return not self.in_menu + + def _toggle_local_side(self) -> None: + if not self.local_side_locked(): + uboot_local.toggle_side(self) + + @localized + def draw_options_overlay(self) -> None: + # Panel/row geometry is sized so the footer hint always starts below + # the last row with margin, never overlapping it (was previously a + # fixed y=612 footer colliding with row 9's box at y=620-662). + rect = pygame.Rect(260, 40, 760, 660) + pygame.draw.rect(self.screen, config.COLOR_OVERLAY_BG, rect) + pygame.draw.rect(self.screen, config.COLOR_WARN, rect, 2) + layout.blit_line(self.screen, "option.title", (292, 64, 696, 48), + config.COLOR_WARN, size=32, align="center") + for page, tab in enumerate(self._options_page_rects()): + active = page == self.options_page + pygame.draw.rect(self.screen, config.COLOR_WARN if active + else config.COLOR_TEXT_DIM, tab, 1) + layout.blit_line(self.screen, message("option.page", page=page + 1, + pages=len(self._OPTION_PAGES)), + tab.inflate(-8, -4), config.COLOR_WARN if active + else config.COLOR_TEXT_DIM, size=18, align="center") + if self._option_rows() is self._OPTION_ROWS_SETUP: + self._draw_options_setup_page() + return + values = ( + self.tr("option.language") + ": " + self.tr("option.language." + self.preferences.language), + self.tr("option.fullscreen") + ": " + self.tr("common.on" if self.preferences.fullscreen else "common.off"), + self.tr("option.audio") + ": " + self.tr("common.on" if self.audio.available else "common.off"), + self.tr("option.large_text") + ": " + self.tr("common.on" if self.preferences.large_text else "common.off"), + self.tr("option.tooltips") + ": " + + self.tr("common.on" if self.tooltips_enabled else "common.off"), + self.tr("option.simlog") + ": " + + self.tr("common.on" if self.preferences.simlog else "common.off"), + self.tr("option.night_mode") + ": " + + self.tr("common.on" if self.preferences.night_mode else "common.off"), + self.tr("option.high_contrast") + ": " + + self.tr("common.on" if self.preferences.high_contrast else "common.off"), + self.tr("option.frame_rate", fps=self.frame_rate()), + self.tr("option.bottom_panel") + ": " + + self.tr("option.bottom_panel." + self.bottom_panel_mode()), + self.tr("option.operator_assist") + ": " + + self.tr("option.operator_assist." + ("training" if self.operator_assist() + else "off")), + self.tr("option.live_traffic"), + self.tr("commander.local.option"), + ) + for index, (value, row) in enumerate(zip(values, self._options_row_rects())): + color = config.COLOR_TEXT if index == self.options_sel else config.COLOR_TEXT_DIM + prefix = "> " if index == self.options_sel else " " + layout.blit_line(self.screen, raw_text(prefix + value), row, color, size=20) + layout.blit_block(self.screen, + "commander.local.options_hint", + 292, 650, 696, 46, config.COLOR_TEXT_DIM, size=18, + align="center") + + def _draw_options_setup_page(self) -> None: + row = self._options_row_rects()[0] + locked = self.local_side_locked() + value = (self.tr("option.local_side") + ": " + + self.tr("option.local_side." + self.local_side)) + selected = self.options_sel == 0 + color = (config.COLOR_TEXT_DIM if locked or not selected else config.COLOR_TEXT) + layout.blit_line(self.screen, raw_text(("> " if selected else " ") + value), + row, color, size=20) + layout.blit_block(self.screen, "option.local_side.help", + row.x + 24, row.bottom + 10, row.w - 24, 150, + config.COLOR_TEXT_DIM, size=18) + if locked: + layout.blit_block(self.screen, "option.local_side.locked", + row.x + 24, row.bottom + 170, row.w - 24, 50, + config.COLOR_WARN, size=18) + layout.blit_block(self.screen, + "commander.local.options_hint", + 292, 650, 696, 46, config.COLOR_TEXT_DIM, size=18, + align="center") + + @staticmethod + def _live_traffic_row_rects(): + return tuple(pygame.Rect(292, 150 + index * 84, 696, 44) for index in range(5)) + + @staticmethod + def _mask_credential(value: str) -> str: + value = (value or "").strip() + if not value: + return "-" + return f"...{value[-4:]}" if len(value) > 4 else "*" * len(value) + + @localized + def draw_live_traffic_overlay(self) -> None: + rect = pygame.Rect(260, 40, 760, 660) + pygame.draw.rect(self.screen, config.COLOR_OVERLAY_BG, rect) + pygame.draw.rect(self.screen, config.COLOR_WARN, rect, 2) + layout.blit_line(self.screen, "live_traffic.title", (292, 64, 696, 48), + config.COLOR_WARN, size=32, align="center") + online = self.connectivity.online + status_key = ("live_traffic.online" if online + else "live_traffic.offline" if online is False + else "live_traffic.checking") + layout.blit_line(self.screen, status_key, (292, 108, 696, 28), + config.COLOR_TEXT_DIM, size=16, align="center") + rows = self._live_traffic_row_rects() + names = self._LIVE_TRAFFIC_ROWS + toggle_labels = ( + self.tr("live_traffic.ais_toggle") + ": " + + self.tr("common.on" if self.preferences.live_ais_enabled else "common.off"), + self.tr("live_traffic.adsb_toggle") + ": " + + self.tr("common.on" if self.preferences.live_adsb_enabled else "common.off"), + ) + for index in range(2): + color = (config.COLOR_TEXT if index == self.live_traffic_sel + else config.COLOR_TEXT_DIM) + if not getattr(self.preferences, names[index]) \ + and not self._live_traffic_can_enable(names[index]): + color = config.COLOR_TEXT_DIM + prefix = "> " if index == self.live_traffic_sel else " " + layout.blit_line(self.screen, raw_text(prefix + toggle_labels[index]), + rows[index], color, size=20) + for index, key in ((2, "aisstream_api_key"), (3, "opensky_credentials")): + color = config.COLOR_TEXT if index == self.live_traffic_sel else config.COLOR_TEXT_DIM + prefix = "> " if index == self.live_traffic_sel else " " + label = self.tr("live_traffic.aisstream_key" if key == "aisstream_api_key" + else "live_traffic.opensky_key") + row = rows[index] + layout.blit_line(self.screen, raw_text(prefix + label), + (row.x, row.y, row.w, 22), color, size=18) + field_rect = pygame.Rect(row.x, row.y + 24, row.w, 30) + if self.live_traffic_field is not None and self.live_traffic_field_name == key: + self.live_traffic_field.draw(self.screen, field_rect, focused=True) + else: + layout.blit_line(self.screen, + raw_text(self._mask_credential(getattr(self.preferences, key))), + field_rect, config.COLOR_TEXT_DIM, size=16) + test_row = rows[4] + color = config.COLOR_TEXT if self.live_traffic_sel == 4 else config.COLOR_TEXT_DIM + prefix = "> " if self.live_traffic_sel == 4 else " " + layout.blit_line(self.screen, raw_text(prefix + self.tr("live_traffic.test_action")), + (test_row.x, test_row.y, test_row.w, 22), color, size=18) + status_line = self.tr("live_traffic.test_result", + ais=self._live_traffic_test_label("ais"), + adsb=self._live_traffic_test_label("adsb")) + layout.blit_line(self.screen, raw_text(status_line), + (test_row.x, test_row.y + 24, test_row.w, 24), + config.COLOR_TEXT_DIM, size=16) + layout.blit_block(self.screen, + "live_traffic.hint", + 292, 636, 696, 58, config.COLOR_TEXT_DIM, size=16, + align="center") + + def _live_traffic_test_label(self, side: str) -> str: + status, reason = self.live_traffic_test_result.get(side, ("idle", None)) + if status == "running": + return self.tr("live_traffic.test_running") + if status == "no_key": + return self.tr("live_traffic.test_no_key") + if status == "ok": + return self.tr("live_traffic.test_ok") + if status == "error": + return self.tr("live_traffic.test_error", reason=(reason or "?")[:80]) + return self.tr("live_traffic.test_idle") + + @localized + def draw_quit_overlay(self) -> None: + """Require an explicit confirmation before leaving a live mission.""" + s = self.screen + dim = pygame.Surface((config.SCREEN_W, config.SCREEN_H), pygame.SRCALPHA) + dim.fill((0, 0, 0, 155)) + s.blit(dim, (0, 0)) + choices = (("quit.menu", "common.exit") if self.in_menu else + ("quit.game", "quit.save", "quit.main_menu", "quit.no_save")) + rect = pygame.Rect(260, 185 - 20 * (len(choices) - 3), + 760, 330 + 40 * (len(choices) - 3)) + pygame.draw.rect(s, config.COLOR_PANEL_BG, rect) + pygame.draw.rect(s, config.COLOR_WARN, rect, 2) + layout.blit_line(s, "quit.title", (rect.x + 20, rect.y + 22, + rect.w - 40, 36), config.COLOR_WARN, size=28) + layout.blit_line(s, "quit.warning", + (rect.x + 20, rect.y + 74, rect.w - 40, 26), + config.COLOR_TEXT, size=16) + for index, label in enumerate(choices): + selected = index == self.quit_selection + layout.blit_line(s, message("menu.choice", + marker="> " if selected else " ", + label=self.tr(label)), + (rect.x + 20, rect.y + 124 + index * 40, rect.w - 40, 32), + config.COLOR_WARN if selected else config.COLOR_TEXT, + size=22) + layout.blit_line(s, "control.quit_hint", + (rect.x + 20, rect.bottom - 44, rect.w - 40, 28), + config.COLOR_TEXT_DIM, size=18) + + # --- Main loop --- + + def _perf_debug_log(self, wall_dt: float) -> None: + """Optional 1 Hz diagnostics line, enabled via U_JAGD_PERF_DEBUG=1. + + Appends bounded per-frame-average phase timings (physics substeps, + audio publish, Remote Crew pump, draw/compose) to perf_debug.log + inside the save directory, for on-device (uConsole) CPU diagnosis. + Purely measures wall time already spent in existing calls; never + alters simulation timing, input, or rendering. No-op unless enabled. + """ + if not self._perf_debug_enabled: + return + try: + wall_dt = float(wall_dt) + except (TypeError, ValueError, OverflowError): + return + if not math.isfinite(wall_dt) or wall_dt <= 0.0: + return + self._perf_frames += 1 + self._perf_frame_max_s = max(self._perf_frame_max_s, wall_dt) + self._perf_debug_due += wall_dt + if self._perf_debug_due < 1.0: + return + self._perf_debug_due %= 1.0 + frames = self._perf_frames + line = ("t={t:.1f} fps={fps} substeps_avg={sub:.2f} sim_ms={sim:.2f} " + "audio_ms={audio:.2f} commander_ms={cmd:.2f} " + "commander_max_ms={cmdmax:.1f} events_ms={events:.2f} " + "traffic_ms={traffic:.2f} " + "draw_ms={draw:.2f} frame_max_ms={fmax:.1f} " + "sim_lag_ms={lag:.1f} sim_dropped_ms={drop:.1f}\n").format( + t=time.monotonic(), fps=frames, sub=self._perf_substeps / frames, + fmax=1000 * self._perf_frame_max_s, lag=1000 * self._sim_debt_s, + drop=1000 * self._sim_dropped_s, + sim=1000 * self._perf_sim_s / frames, + audio=1000 * self._perf_audio_s / frames, + cmd=1000 * self._perf_commander_s / frames, + cmdmax=1000 * self._perf_commander_max_s, + events=1000 * self._perf_events_s / frames, + traffic=1000 * self._perf_traffic_s / frames, + draw=1000 * self._perf_draw_s / frames) + append_bounded_log(config.SAVE_DIR, "perf_debug.log", line, + config.PERF_DEBUG_LOG_MAX_BYTES) + self._perf_frames = 0 + self._perf_sim_s = 0.0 + self._perf_substeps = 0 + self._perf_audio_s = 0.0 + self._perf_commander_s = 0.0 + self._perf_commander_max_s = 0.0 + self._perf_events_s = 0.0 + self._perf_traffic_s = 0.0 + self._perf_draw_s = 0.0 + self._perf_frame_max_s = 0.0 + + def _frame_dt(self, wall_dt: float) -> float: + """Simulation seconds for this frame from wall time and bounded debt. + + A frame never advances more than SIM_FRAME_DT_MAX, but the remainder of + a slow frame is caught up over the next frames, so simulation time (and + the sonar audio produced in it) keeps pace with wall-clock playback. + Debt above SIM_CATCHUP_MAX_S is dropped. After a pause, menu, overlay, + load or world reset the first frame is only clamped, never caught up. + """ + try: + wall_dt = float(wall_dt) + except (TypeError, ValueError, OverflowError): + wall_dt = 0.0 + if not math.isfinite(wall_dt) or wall_dt < 0.0: + wall_dt = 0.0 + if self._frame_clock_reset: + self._frame_clock_reset = False + self._sim_debt_s = 0.0 + return min(wall_dt, config.SIM_FRAME_DT_MAX) + debt = self._sim_debt_s + wall_dt + if debt > config.SIM_CATCHUP_MAX_S: + self._sim_dropped_s += debt - config.SIM_CATCHUP_MAX_S + debt = config.SIM_CATCHUP_MAX_S + dt = min(debt, config.SIM_FRAME_DT_MAX) + self._sim_debt_s = debt - dt + return dt + + def frame_rate(self) -> int: + """Active frame-rate cap from the saved preference.""" + value = getattr(self.preferences, "frame_rate", config.FPS_DEFAULT) + return value if value in config.FPS_CHOICES else config.FPS_DEFAULT + + def run(self) -> None: + try: + while self.running: + if self.auto_quit is not None: + self.auto_quit -= 1 + if self.auto_quit <= 0: + self.running = False + wall_dt = self.clock.tick(self.frame_rate()) / 1000.0 + dt = self._frame_dt(wall_dt) + self._t += dt + events_started = (time.perf_counter() + if self._perf_debug_enabled else None) + for e in pygame.event.get(): + if not self.web_mode: + self.handle_event(e) + if e.type in _ECO_REFRESH_EVENTS: + self._eco_drawn_at = float("-inf") + if events_started is not None: + self._perf_events_s += time.perf_counter() - events_started + commander_started = (time.perf_counter() + if self._perf_debug_enabled else None) + self.commander.pump(self) + if commander_started is not None: + now = time.perf_counter() + self._perf_commander_s += now - commander_started + self._perf_commander_max_s = max( + self._perf_commander_max_s, now - commander_started) + commander_started = now + self.live_traffic.pump(self) + if commander_started is not None: + self._perf_traffic_s += time.perf_counter() - commander_started + self.update(dt, audio_dt=wall_dt) + self._perf_debug_log(wall_dt) + if self.web_mode: + continue + if self._skip_eco_frame(): + continue + draw_started = time.perf_counter() if self._perf_debug_enabled else None + self.draw() + self.compose_frame() + if draw_started is not None: + self._perf_draw_s += time.perf_counter() - draw_started + finally: + try: + self.commander.stop() + finally: + try: + self.connectivity.stop() + self.live_traffic.stop() + finally: + self.audio.shutdown() + pygame.quit() + + def _apply_text_size(self) -> None: + layout.configure_for(self) + self.font = layout.font(18) + self.font_big = layout.font(28, bold=True) + # Menus get a larger baseline than in-game HUD text: more free + # space per screen, and no risk to the already-tuned station views + # that also read `self.font`/`self.font_big`. + self.menu_font = layout.font(21) + self.menu_font_big = layout.font(34, bold=True) + + def toggle_fullscreen(self, persist: bool = True) -> None: + """Vollbild: (0,0)+FULLSCREEN = native Desktop-Größe (deckt Taskleiste + ab, keine schwarzen Balken). Zurück = 1280x720-Fenster.""" + self.fullscreen = not self.fullscreen + if self.fullscreen: + self.display = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) + else: + self.display = pygame.display.set_mode( + (config.SCREEN_W, config.SCREEN_H), pygame.RESIZABLE) + if persist: + from dataclasses import replace + self.preferences = replace(self.preferences, fullscreen=self.fullscreen) + try: + save_preferences(self.preferences) + except OSError: + pass + self.flash(message("event.fullscreen_on" if self.fullscreen + else "event.fullscreen_off"), 2.0) + + def _set_preference(self, name: str, value) -> None: + from dataclasses import replace + self.preferences = replace(self.preferences, **{name: value}) + if name == "language": + self.translator = Translator(value) + self.tr = self.translator.t + self.pinned_tooltip = None + self._tooltip_anchor = None + pygame.display.set_caption(self.tr("app.title")) + if self.editor is not None: + self.editor.tr = self.tr + self.flash(message("status.language_changed", + language=self.tr("option.language." + value)), 2.0) + elif name == "fullscreen" and bool(value) != self.fullscreen: + self.toggle_fullscreen(persist=False) + elif name == "audio": + self.audio.shutdown() + self.audio = AudioEngine(sample_rate=config.AUDIO_SAMPLE_RATE, + enabled=bool(value)) + self._audio_timer = 0.0 + self._sonar_audio_sequence = -1 + elif name in ("large_text", "high_contrast"): + self._apply_text_size() + elif name == "tooltips": + self.tooltips_enabled = bool(value) + self.pinned_tooltip = None + self._tooltip_anchor = None + try: + save_preferences(self.preferences) + except OSError: + self.flash(message("status.preferences_error"), 3.0) + + def _reset_map_view(self) -> None: + """Standard-Karte: Detail-Zoom, Kamera folgt der Fregatte.""" + self.map_view.set_rect(config.MAP_RECT) + self.map_view.scale = config.MAP_ZOOM_DEFAULT_PX_PER_NM + self.map_view.cx = self.ship.x + self.map_view.cy = self.ship.y + self.map_view.clamp_center() + self.map_follow = True + self._configure_opz_map_view() + self.opz_map_view.scale = min(self.opz_map_view.rect[2], + self.opz_map_view.rect[3]) / ( + 2.0 * config.OPZ_MAP_DEFAULT_RADIUS_NM) + self.opz_map_view.cx = self.ship.x + self.opz_map_view.cy = self.ship.y + self.opz_map_view.clamp_center() + self.opz_map_follow = True + + def _configure_opz_map_view(self, chart=None) -> None: + chart = pygame.Rect(chart or opz_ppi_rect(config.OPZ_STATION_RECT)) + self.opz_map_view.world_size = self.world.size_nm + self.opz_map_view.set_rect(tuple(chart)) + self.opz_map_view.min_scale = min(chart.w, chart.h) / self.world.size_nm + self.opz_map_view.max_scale = max( + self.opz_map_view.min_scale, min(chart.w, chart.h) / ( + 2.0 * config.OPZ_MAP_MAX_ZOOM_RADIUS_NM)) + self.opz_map_view.scale = config.clamp( + self.opz_map_view.scale, self.opz_map_view.min_scale, + self.opz_map_view.max_scale) diff --git a/src/core/game_operator.py b/src/core/game_operator.py new file mode 100644 index 00000000..245805fb --- /dev/null +++ b/src/core/game_operator.py @@ -0,0 +1,1716 @@ +"""Operator commands of the frigate's stations: navigation and plant orders, +sonar and TMA controls, radar, helicopter, weapons and radio actions. Local +keys and Remote Crew commands both end here and pass the same checks +(``Game`` mixin). + +Verbatim moves from ``game.py`` (plan 1.3, phase 2, step 4b).""" + +import math + + +from src.core import config +from src.core.commands import STATION_PAGES, station_page_step +from src.core.i18n import display_value, message, raw_text +from src.core.station import Station +from src.core import opfor +from src.core.limits import MAX_DECOYS +from src.sonar import analysis_tools +from src.sonar import tma_operator +from src.enemies.decoy import Decoy +from src.sonar.sonar import Contact, TowState +from src.ui.contact_analyzer import ContactAnalyzer +from src.air.asm import ESSM +from src.air import chaff as chaff_physics +from src.weapons.torpedo import Torpedo +from src.weapons.asw import MAX_TOWED_DECOYS, TowedAcousticDecoy +# Shared display/help constants and helpers (re-exported for tests/tools). +from src.core.game_shared import SONAR_BAND_PRESETS, TMA_ACCEPT_MIN_FIT +# Names tests and tools import from ``src.core.game`` (kept as re-exports). + + +class OperatorMixin: + """Command half of ``Game``: every station action shared by keys and browsers.""" + + def _navigation_order_live(self) -> bool: + # The simulation never pauses: menus and overlays own local input only, + # so crew orders stay live behind them. + return (self.running and not self.game_over + and not self.in_menu and not self.main_menu + and not self.splash_active + and self.input_mode in (None, "course", "speed")) + + def _set_course_order(self, course: float, station: str) -> str: + """Apply a validated shared helm order for one local station owner.""" + if type(course) not in (int, float): + return "invalid_value" + try: + valid = math.isfinite(course) and 0.0 <= course < 360.0 + except OverflowError: + valid = False + if not valid: + return "invalid_value" + if not self._navigation_order_live(): + return "phase_blocked" + if self.damage.station_down(station): + return f"{station}_down" + self.ship.target_course = course + self.feed.add(self.world.format_time(), "navigation", + message("runtime.numeric.course_feed", course=f"{course:03.0f}")) + return "ok" + + def order_course(self, course: float) -> str: + """Apply a Bridge course order and return a stable result code.""" + return self._set_course_order(course, "bridge") + + def set_engine_course(self, course: float) -> str: + """Set the common course controller from the machinery station.""" + return self._set_course_order(course, "engine") + + def order_speed(self, speed_kn: float) -> str: + """Apply a validated ahead-speed order and return a stable result code.""" + if type(speed_kn) not in (int, float): + return "invalid_value" + try: + valid = (math.isfinite(speed_kn) + and 0.0 <= speed_kn <= config.SHIP_SPEED_MAX_KN) + except OverflowError: + valid = False + if not valid: + return "invalid_value" + if not self._navigation_order_live(): + return "phase_blocked" + if self.ship.fuel_kg <= 0.0: + return "no_fuel" + self.ship.target_speed = speed_kn + self.ship.astern = False + self.ship.order_idx = min(range(len(config.TELEGRAPH_ORDERS)), + key=lambda i: abs(config.TELEGRAPH_ORDERS[i][1] + - speed_kn)) + self.feed.add(self.world.format_time(), "navigation", + message("runtime.numeric.speed_feed", speed=f"{speed_kn:.1f}")) + return "ok" + + def set_engine_telegraph(self, order: str): + if type(order) is not str: + return "invalid_value" + if self.damage.station_down("engine"): + return "engine_down" + if self.ship.fuel_kg <= 0.0: + return "no_fuel" + if order == "ASTERN": + self.ship.astern = True + self.ship.order_idx = 0 + self.ship.target_speed = config.ASTERN_SPEED_KN + else: + index = next((i for i, item in enumerate(config.TELEGRAPH_ORDERS) + if item[0] == order), None) + if index is None: + return "invalid_value" + self.ship.astern = False + self.ship.order_idx = index + self.ship.target_speed = config.TELEGRAPH_ORDERS[index][1] + return True + + def _cycle_engine_telegraph(self, delta: int): + orders = ("ASTERN", *(item[0] for item in config.TELEGRAPH_ORDERS)) + index = orders.index(self.ship.telegraph) + return self.set_engine_telegraph( + orders[config.clamp(index + delta, 0, len(orders) - 1)]) + + def set_engine_speed(self, speed_kn: float): + if self.damage.station_down("engine"): + return "engine_down" + return self.order_speed(speed_kn) + + def set_quiet_mode(self, enabled: bool): + if type(enabled) is not bool: + return "invalid_value" + if self.damage.station_down("engine"): + return "engine_down" + self.ship.quiet_mode = enabled + return True + + def assign_damage_team(self, team: int, compartment: str): + if type(team) is not int or type(compartment) is not str: + return "invalid_value" + if team not in self.damage.teams or compartment not in self.damage.compartments: + return "invalid_value" + if self.damage.ship_sunk: + return "not_ready" + if not self.damage.assign_team(team, compartment): + return "not_ready" + return True + + def unassign_damage_team(self, team: int, compartment: str): + if (type(team) is not int or type(compartment) is not str + or team not in self.damage.teams + or compartment not in self.damage.compartments): + return "invalid_value" + if self.damage.teams[team] != compartment: + return "stale_ref" + self.damage.unassign_team(team) + return True + + def set_sonar_listen_bearing(self, bearing: float): + if (type(bearing) not in (int, float) or not 0 <= bearing < 360 + or not math.isfinite(bearing)): + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + # Retuning keeps the listening stream running: the receiver reset is a + # sequence gap that _update_audio joins without a silent re-buffer. + self.sonar.set_listen_bearing(bearing) + return True + + def set_sonar_focus(self, contact): + if self._sonar_down(): + return "sonar_down" + if (not isinstance(contact, Contact) + or self.sonar.contacts.get(contact.target_id) is not contact): + return "stale_ref" + if not 0 <= self.sim_t - contact.last_seen <= 2.0: + return "stale_ref" + self.selected_contact = contact + self.sonar.set_listen_bearing(contact.bearing) + self.sonar.focus_locked = True + self.sonar._listen_target_id = contact.target_id + return True + + def clear_sonar_focus(self): + if self._sonar_down(): + return "sonar_down" + self.sonar.focus_locked = False + self.sonar._listen_target_id = None + return True + + def set_sonar_array_mode(self, mode: str): + if mode not in ("BOW", "TOWED") or type(mode) is not str: + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + self.sonar_mode = mode + return True + + def set_sonar_tas(self, deployed: bool): + if type(deployed) is not bool: + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + state = self.sonar.tow_status(self.sonar_observer.speed)["state"] + if state == "FAULT": + return "tas_fault" + is_deploying = state in ("DEPLOYING", "STREAMED") + if deployed == is_deploying: + return True + return True if self.sonar.toggle_tow(self.sonar_observer.speed) else "tas_fault" + + def set_sonar_tow_depth(self, depth_m: float): + if (type(depth_m) not in (int, float) + or not config.SONAR_TOWED_DEPTH_MIN_M <= depth_m + <= config.SONAR_TOWED_DEPTH_MAX_M or not math.isfinite(depth_m)): + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + if self.sonar.tow_state != TowState.STREAMED: + return "not_ready" + limit = max(config.SONAR_TOWED_DEPTH_MIN_M, + config.SONAR_TOWED_DEPTH_MAX_M + - self.sonar_observer.speed * config.SONAR_TOWED_SPEED_SHALLOW_M_PER_KN) + if depth_m > limit: + return "not_ready" + self.sonar.towed_depth_target_m = depth_m + return True + + def measure_sonar_bt(self): + if self._sonar_down(): + return "sonar_down" + return (True if self.sonar.measure_environment( + self.world, self.sonar_observer, self.sim_t) else "not_ready") + + def send_active_ping(self): + if self._opfor is not None and self._sonar_ctx is self._opfor.station: + return opfor.send_ping(self, self._opfor) + if self._sonar_down(): + return "sonar_down" + if (self.sonar_mode == "TOWED" + and not self.sonar.tow_status(self.ship.speed)["available"]): + return "not_ready" + if not self.sonar.fire_ping(): + return "not_ready" + self._remember_ping_pulse() + self._emit_sound("sonar_ping") + self.sonar.queue_ping(self.ship, self._sonar_targets(), self.world, + self.sim_t, self._sonar_range_factor(), + mode=self.sonar_mode) + return True + + def set_helicopter_dipping(self, deployed: bool): + if type(deployed) is not bool: + return "invalid_value" + if self.damage.station_down("flightdeck"): + return "flightdeck_down" + if not self.helo.airborne: + return "not_ready" + if deployed and not self.helicopter_weather()["dipping_safe"]: + return "weather_unsafe" + if not self.helo.set_dipping(deployed, self.world): + return "water_required" if deployed else "not_ready" + return True + + def set_helicopter_dip_depth(self, depth_m: float): + if (type(depth_m) not in (int, float) or isinstance(depth_m, bool) + or not math.isfinite(depth_m) + or not config.HELO_DIP_DEPTH_MIN_M <= depth_m + <= config.HELO_DIP_DEPTH_MAX_M): + return "invalid_value" + if (not self.helo.airborne + or self.helo.dip_state not in ("DEPLOYING", "DEPLOYED")): + return "not_ready" + return (True if self.helo.set_dip_depth(depth_m, self.world) + else "water_required") + + def send_helicopter_dipping_ping(self): + if self.damage.station_down("sonar"): + return "sonar_down" + if not self.helo.fire_dipping_ping(): + return "not_ready" + self._remember_ping_pulse() + self._emit_sound("sonar_ping") + self.sonar.queue_ping(self.helo, self._sonar_targets(), self.world, + self.sim_t, self._sonar_range_factor(), + mode="DIPPING") + return True + + def set_sonar_tma_enabled(self, enabled: bool): + if type(enabled) is not bool: + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + self.sonar.tma_enabled = enabled + return True + + def set_sonar_gain(self, gain_db: float): + if (type(gain_db) not in (int, float) or not -12 <= gain_db <= 24 + or not math.isfinite(gain_db)): + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + self.sonar.gain_db = gain_db + return True + + def set_sonar_audition_mode(self, mode: str): + if type(mode) is not str or mode not in ("BROADBAND", "FILTERED", "HETERODYNE"): + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + self.sonar.set_audition_mode(mode) + return True + + def set_sonar_band_preset(self, preset: str): + band = SONAR_BAND_PRESETS.get(preset) if type(preset) is str else None + if band is None: + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + self.sonar.band_low_hz, self.sonar.band_high_hz = band + return True + + def set_sonar_notch(self, enabled: bool): + if type(enabled) is not bool: + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + self.sonar.notch_enabled = enabled + return True + + def set_sonar_peak_hold(self, enabled: bool): + if type(enabled) is not bool: + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + self.sonar.peak_hold = enabled + return True + + def sonar_harmonic_candidates(self): + return tuple(sorted({float(hz) for hz, _ in list( + getattr(self.sonar.receiver, "peaks", []))[:6] + if type(hz) in (int, float) and math.isfinite(hz) + and 0 < float(hz) <= config.LOFAR_FMAX_HZ})) + + def set_sonar_harmonic(self, frequency_hz): + if self._sonar_down(): + return "sonar_down" + if frequency_hz is None: + self.sonar_harmonic_hz = None + return True + if (type(frequency_hz) not in (int, float) + or not 0 < frequency_hz <= config.LOFAR_FMAX_HZ + or not math.isfinite(frequency_hz)): + return "invalid_value" + # Any operator-chosen fundamental (the cursor), not only detected peaks. + self.sonar_harmonic_hz = float(frequency_hz) + return True + + def designate_sonar_target(self, contact): + if self._sonar_down(): + return "sonar_down" + if (not isinstance(contact, Contact) + or self.sonar.contacts.get(contact.target_id) is not contact + or not 0 <= self.sim_t - contact.last_seen + < config.SONAR_CONTACT_LOST_S): + return "stale_ref" + self.target = contact + return True + + def _feed_ping(self, tgt, contact) -> None: + """W1/W2: Ping-Echo-Feed inkl. Echolatenz (W3: Salzwasser-Schallfeld).""" + dist = tgt.distance_nm(self.ship) + 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 "", + "unknown") if getattr(tgt, "stype", None) else \ + ("Decoy?" if getattr(tgt, "kind", "") == "decoy" + else ("biological" if hasattr(tgt, "atype") else "vessel")) + self.feed.add(self.world.format_time(), "sonar", + message("runtime.ping.feed", contact=tgt.id, + bearing=f"{contact.bearing:4.0f}", + range=f"{contact.range_est:4.1f}", + latency=f"{latenz:3.1f}", + speed=f"{self.world.mean_sound_speed_m_s(mx, my):.0f}", + classification=klass)) + + # --- Display (M8): Letterbox-Scaling + Vollbild --- + + def _cycle_sonar_mode(self) -> None: + self.set_sonar_array_mode("TOWED" if self.sonar_mode == "BOW" else "BOW") + self.flash(message("runtime.sonar_array.towed" if self.sonar_mode == "TOWED" + else "runtime.sonar_array.bow"), 1.5) + + def _handle_sonar_click(self, target) -> bool: + """Execute the sonar view's closed allowlist of non-critical actions.""" + if not isinstance(target, dict) or target.get("safe") is not True: + return False + action = target.get("action") + if action == "page_set": + value = target.get("value") + if type(value) is not int or not 0 <= value < len(STATION_PAGES[Station.SONAR]): + return False + self.sonar_page = value + elif action == "page": + self.sonar_page = station_page_step(Station.SONAR, self.sonar_page, 1) + elif action in ("contact", "echo", "contact_listen"): + contact_id = target.get("value") + contact = next((item for item in self.sonar.active_contacts() + if item.id == contact_id), None) + if contact is None: + return False + if action == "contact_listen": + if self.set_sonar_focus(contact) is not True: + return False + else: + self.selected_contact = contact + elif action == "listen_bearing": + value = target.get("value") + if (type(value) not in (int, float) or not math.isfinite(value) + or not 0 <= value < 360): + return False + self.set_sonar_listen_bearing(value) + self.flash(message("runtime.numeric.true_bearing", + bearing=f"{value:05.1f}"), 2.0) + elif action == "array": + self._cycle_sonar_mode() + elif action == "gain": + self._adjust_sonar_gain(3.0) + elif action == "band_filter": + self._cycle_sonar_band() + elif action == "notch": + self.set_sonar_notch(not self.sonar.notch_enabled) + self.flash(message("runtime.notch.on" if self.sonar.notch_enabled + else "runtime.notch.off"), 1.5) + elif action == "harmonic": + self._cycle_sonar_harmonic() + elif action == "tma_accept": + self._accept_tma_with_notice(self._tma_contact()) + elif action == "integration": + seconds = self.sonar_tools.cycle_integration() + self.flash(message("runtime.integration", seconds=seconds), 1.5) + elif action == "cursor": + pass # the cursor moves with Z/X; the segment is a readout + elif action == "peak": + self.set_sonar_peak_hold(not self.sonar.peak_hold) + self.flash(message("runtime.peak_hold.on" if self.sonar.peak_hold + else "runtime.peak_hold.off"), 1.5) + elif action == "audio": + self.sonar_audio_enabled = not self.sonar_audio_enabled + self._stop_sonar_audio() + self.flash(message("runtime.sonar_audio.on" if self.sonar_audio_enabled + else "runtime.sonar_audio.off")) + else: + return False + return True + + def _cycle_sonar_harmonic(self) -> None: + """K: mark the line under the operator cursor (LOFAR fundamental, + DEMON shaft then blade line); pressing again on the mark clears it.""" + page = "demon" if self.sonar_page == 2 else "lofar" + if self.mark_sonar_cursor(page) is not True: + return + tools = self.sonar_tools + if page == "demon": + key = ("runtime.demon.blade" if tools.blade_hz is not None + else "runtime.demon.shaft" if tools.shaft_hz is not None + else "runtime.demon.cleared") + self.flash(message(key, frequency=f"{tools.demon_cursor_hz:.1f}"), 1.5) + elif self.sonar_harmonic_hz is None: + self.flash(message("runtime.harmonic.cleared"), 1.5) + else: + self.flash(message("runtime.harmonic.selected", + frequency=f"{self.sonar_harmonic_hz:.1f}"), 1.5) + + def _tma_contact(self): + contact = self.selected_contact + if contact is None or contact.target_id not in self.sonar.contacts: + return None + return contact + + def _tma_points(self, contact): + track = self.sonar._tracks.get(getattr(contact, "target_id", None)) + return list(getattr(track, "pts", ())) + + def tma_hypothesis(self, contact): + hypothesis = self.tma_hypotheses.get(contact.target_id) + if hypothesis is None: + hypothesis = tma_operator.default_hypothesis(self._tma_points(contact)) + return hypothesis + + def set_tma_hypothesis(self, contact, course, speed_kn, range_nm): + if contact is None or contact.target_id not in self.sonar.contacts: + return "stale_ref" + if any(type(value) not in (int, float) or not math.isfinite(value) + for value in (course, speed_kn, range_nm)): + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + self.tma_hypotheses[contact.target_id] = tma_operator.Hypothesis( + float(course), float(speed_kn), float(range_nm)).clamped() + while len(self.tma_hypotheses) > 64: + self.tma_hypotheses.pop(next(iter(self.tma_hypotheses))) + return True + + def tma_evaluation(self, contact): + points = self._tma_points(contact) + return tma_operator.evaluate(points, self.tma_hypothesis(contact)) + + def accept_tma(self, contact): + """Write the operator's hypothesis as the contact's TMA fix.""" + if contact is None or contact.target_id not in self.sonar.contacts: + return "stale_ref" + if self._sonar_down(): + return "sonar_down" + points = self._tma_points(contact) + evaluation = tma_operator.evaluate(points, self.tma_hypothesis(contact)) + if evaluation is None: + return "not_ready" + if evaluation["observability"] < 0.5: + return "unobservable" + if evaluation["fit"] < TMA_ACCEPT_MIN_FIT: + return "poor_fit" + hypothesis = self.tma_hypothesis(contact) + position = tma_operator.position_at(points, hypothesis, self.sim_t) + contact.accept_operator_tma(position, hypothesis.course, + hypothesis.speed_kn, evaluation["quality"], + self.sim_t) + return True + + def copy_tma_proposal(self, contact): + """Training aid: start the hypothesis from the automatic solver.""" + if not self.operator_assist(): + return "not_available" + if contact is None: + return "stale_ref" + proposal = self.sonar.tma_proposals.get(contact.target_id) + points = self._tma_points(contact) + if proposal is None or not points: + return "not_ready" + # The proposal's position is at its newest bearing; its range from + # that observation point seeds the hypothesis range. + ref = points[-1] + return self.set_tma_hypothesis( + contact, proposal.course, proposal.speed, + math.hypot(proposal.pos[0] - ref.fx, proposal.pos[1] - ref.fy)) + + def _accept_tma_with_notice(self, contact) -> None: + result = self.accept_tma(contact) if contact is not None else "stale_ref" + if result is True: + self.flash(message("runtime.tma.accepted", contact=contact.id, + quality=f"{contact.tma_quality:.0%}"), 2.0) + elif result == "poor_fit": + self.flash(message("runtime.tma.poor_fit"), 2.0) + elif result == "unobservable": + self.flash(message("runtime.tma.unobservable"), 2.0) + else: + self.flash(message("runtime.tma.not_ready"), 2.0) + + def operator_assist(self) -> bool: + """Training aids (auto peaks, blade-rate/catalog ranking, ESM IDs) on?""" + return getattr(self.preferences, "operator_assist", "off") == "training" + + def set_sonar_cursor(self, page, frequency_hz): + if page not in ("lofar", "demon"): + return "invalid_value" + if (type(frequency_hz) not in (int, float) + or not math.isfinite(frequency_hz)): + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + value = analysis_tools.clamp_cursor(frequency_hz, page) + if page == "lofar": + self.sonar_tools.lofar_cursor_hz = value + else: + self.sonar_tools.demon_cursor_hz = value + return True + + def mark_sonar_cursor(self, page): + if page not in ("lofar", "demon"): + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + tools = self.sonar_tools + if page == "demon": + tools.mark_demon(tools.demon_cursor_hz) + return True + cursor = tools.lofar_cursor_hz + if (self.sonar_harmonic_hz is not None + and abs(self.sonar_harmonic_hz - cursor) < 1e-6): + return self.set_sonar_harmonic(None) + return self.set_sonar_harmonic(cursor) + + def set_sonar_integration(self, seconds): + if type(seconds) is not int or seconds not in analysis_tools.INTEGRATION_CHOICES_S: + return "invalid_value" + self.sonar_tools.integration_s = seconds + return True + + def set_sonar_vernier(self, enabled): + if type(enabled) is not bool: + return "invalid_value" + self.sonar_tools.vernier = enabled + return True + + def set_sonar_band(self, low_hz, high_hz): + """Free band-pass edges (low 0 = low-pass, high 300 = high-pass).""" + if (any(type(value) not in (int, float) or not math.isfinite(value) + for value in (low_hz, high_hz)) + or not 0.0 <= low_hz < high_hz <= config.LOFAR_FMAX_HZ): + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + self.sonar.band_low_hz, self.sonar.band_high_hz = float(low_hz), float(high_hz) + return True + + def set_tas_side(self, contact, action: str): + """Operator decision on a towed-only contact's array side. + + ``flip`` shows the other side (and reopens a confirmed choice); + ``confirm`` commits the shown side. Nothing is decided automatically. + """ + if contact is None or contact.target_id not in self.sonar.contacts: + return "stale_ref" + if action not in ("flip", "confirm"): + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + if action == "flip": + if not contact.towed_ambiguous: + if not contact.towed_resolved: + return "not_ambiguous" + contact.towed_ambiguous, contact.towed_resolved = True, False + contact.ambiguity_axis = self.sonar.tow_heading_deg + contact.towed_side = "PORT" if contact.towed_side == "STBD" else "STBD" + return True + if not contact.towed_ambiguous: + return "not_ambiguous" + contact.towed_ambiguous, contact.towed_resolved = False, True + contact.mirror_bearing = contact.ambiguity_axis = None + return True + + def set_sonar_demon_band(self, low_hz, high_hz): + if (low_hz, high_hz) not in analysis_tools.DEMON_BANDS_HZ: + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + self.sonar.receiver.demon_band_hz = (float(low_hz), float(high_hz)) + return True + + def set_sonar_heterodyne(self, frequency_hz): + if frequency_hz not in analysis_tools.HETERODYNE_OFFSETS_HZ: + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + self.sonar.heterodyne_hz = float(frequency_hz) + return True + + def set_sonar_operator_notch(self, frequency_hz): + if frequency_hz is not None and ( + type(frequency_hz) not in (int, float) or not math.isfinite(frequency_hz) + or not 0.0 < frequency_hz <= config.LOFAR_FMAX_HZ): + return "invalid_value" + if self._sonar_down(): + return "sonar_down" + self.sonar.operator_notch_hz = (None if frequency_hz is None + else float(frequency_hz)) + return True + + def _adjust_sonar_gain(self, delta: float) -> None: + self.set_sonar_gain(config.clamp(self.sonar.gain_db + delta, -12.0, 24.0)) + self.flash(message("runtime.sonar_gain", gain=f"{self.sonar.gain_db:+.0f}"), 1.2) + + def _cycle_sonar_display_palette(self) -> None: + palettes = ("green", "amber", "cyan") + current = (palettes.index(self.sonar_display_palette) + if self.sonar_display_palette in palettes else -1) + self.sonar_display_palette = palettes[(current + 1) % len(palettes)] + self.flash(message("runtime.sonar_palette", + palette=self.sonar_display_palette.upper()), 1.2) + + def _adjust_sonar_display_contrast(self, delta: float) -> None: + self.sonar_display_contrast = round(config.clamp( + self.sonar_display_contrast + delta, .5, 4.0), 1) + self.flash(message("runtime.sonar_contrast", + contrast=f"{self.sonar_display_contrast:.1f}"), 1.2) + + def _adjust_sonar_display_black(self, delta: float) -> None: + self.sonar_display_black = round(config.clamp( + self.sonar_display_black + delta, 0.0, .8), 2) + self.flash(message("runtime.sonar_black_level", + level=f"{self.sonar_display_black:.2f}"), 1.2) + + def _cycle_sonar_display_history(self) -> None: + depths = (.25, .5, 1.0) + current = next((index for index, value in enumerate(depths) + if abs(self.sonar_display_history - value) < 1e-6), -1) + self.sonar_display_history = depths[(current + 1) % len(depths)] + self.flash(message("runtime.sonar_history", + history=f"{self.sonar_display_history:.0%}"), 1.2) + + def _set_sonar_audition_mode(self, mode: str) -> None: + if self.set_sonar_audition_mode(mode) is not True: + return + key = {"BROADBAND": "runtime.listen.broadband", + "FILTERED": "runtime.listen.filtered", + "HETERODYNE": "runtime.listen.heterodyne"}[mode] + self.flash(message(key), 1.2) + + def sonar_audio_status(self) -> dict: + status = self.audio.availability_status() + locally_ready = (self.station is Station.SONAR and self.sonar_audio_enabled + and not self.damage.station_down("sonar")) + return dict(status, local_enabled=bool(self.sonar_audio_enabled), + mode=self.sonar.audition_mode, gain_db=self.sonar.gain_db, + band_hz=[self.sonar.band_low_hz, self.sonar.band_high_hz], + notch=bool(self.sonar.notch_enabled), volume=self.sonar_volume, + stale=bool(self.audio.sonar_stale), + audible=bool(status["global_enabled"] + and status["device_available"] and locally_ready)) + + def _cycle_sonar_band(self) -> None: + bands = tuple(SONAR_BAND_PRESETS.values()) + current = (self.sonar.band_low_hz, self.sonar.band_high_hz) + try: + index = bands.index(current) + except ValueError: + index = 0 + low, high = bands[(index + 1) % len(bands)] + preset = next(key for key, value in SONAR_BAND_PRESETS.items() + if value == (low, high)) + self.set_sonar_band_preset(preset) + self.flash(message("runtime.sonar_band", low=f"{low:.0f}", + high=f"{high:.0f}"), 1.5) + + def toggle_radar(self, domain: str = "surface") -> None: + enabled = not (self.air_radar_on if domain == "air" + else self.surface_radar_on) + if self.set_opz_radar(domain, enabled) is not True: + self.flash(message("runtime.opz.disabled")) + return + if domain == "air": + radar, active = "air", self.air_radar_on + else: + radar, active = "surface", self.surface_radar_on + suffix = "on" if active else "off" + self.hq_msg(message(f"runtime.emcon.{radar}.{suffix}.hq")) + self.flash(message(f"runtime.emcon.{radar}.{suffix}"), 2.0) + + def set_opz_radar(self, domain: str, enabled: bool): + """Set one OPZ radar from a validated local or remote station action.""" + if self.damage.station_down("opz"): + return "opz_down" + if domain not in ("surface", "air") or type(enabled) is not bool: + return "invalid_value" + setattr(self, f"{domain}_radar_on", enabled) + return True + + def set_opz_range(self, range_nm: float): + if self.damage.station_down("opz"): + return "opz_down" + if type(range_nm) not in (int, float) or range_nm not in config.RADAR_RANGE_SCALES_NM: + return "invalid_value" + self.opz_range_nm = float(range_nm) + return True + + def _cycle_lookout_range(self, delta: int) -> None: + """Bridge lookout page: step the display scale (presentation only).""" + scales = config.LOOKOUT_DISPLAY_RANGES_NM + current = getattr(self, "lookout_range_nm", 12.0) + index = min(range(len(scales)), key=lambda i: abs(scales[i] - current)) + self.lookout_range_nm = scales[max(0, min(len(scales) - 1, index + delta))] + self.flash(message("runtime.lookout.range", range=f"{self.lookout_range_nm:.0f}"), 1.5) + + def lookout_sightings(self) -> list: + """Current bridge-lookout tracks (measured bearing/range, visual label).""" + return [track for track in self.air_picture.tracks(self.sim_t) + if track.source == "LOOKOUT" and track.x is not None and track.y is not None] + + def _cycle_radar_range(self, delta: int) -> None: + scales = config.RADAR_RANGE_SCALES_NM + try: + index = scales.index(float(self.opz_range_nm)) + except ValueError: + index = len(scales) - 1 + index = max(0, min(len(scales) - 1, index + delta)) + if self.set_opz_range(scales[index]) is not True: + return + self.flash(message("runtime.radar.range", range=f"{self.opz_range_nm:.0f}"), 1.5) + + def radar_blip_view(self) -> list: + """Unmarked radar blips still glowing (measured positions only).""" + if not (self.surface_radar_on and not self.damage.station_down("opz")): + return [] + return [blip for blip in self.radar_blips + if 0.0 <= self.sim_t - blip["t"] < config.RADAR_BLIP_LIFE_S + and blip["target"] not in self._radar_marked] + + def mark_radar_blip(self, seq): + """OPZ: start a radar track from a blip (its measurement only).""" + if type(seq) is not int: + return "invalid_value" + blip = next((item for item in self.radar_blip_view() if item["seq"] == seq), None) + if blip is None: + return "stale_ref" + track_id = f"R-{blip['seq']}" + self._observe_mast(track_id, blip["target"], blip["bearing"], blip["range_nm"], + blip["observer_x"], blip["observer_y"], blip["error"]) + self.announce(message("runtime.opz.blip_marked", track=track_id), "opz", 2.0) + return True + + def _mark_newest_blip(self) -> None: + blips = self.radar_blip_view() + if not blips: + self.flash(message("runtime.opz.no_blip"), 1.5) + return + self.mark_radar_blip(blips[-1]["seq"]) + + def radar_sweep_bearing(self) -> float: + """Nautische Peilung: zunehmende Werte drehen Nord -> Ost rechtsherum.""" + return self.radar_scan_phase + + def toggle_helo(self) -> None: + if self.helo.airborne: + if self.return_helicopter() is True: + self.announce(message("runtime.helo.return"), "waffen") + else: + result = self.launch_helicopter() + if result == "flightdeck_down": + self.flash(message("runtime.helo.deck_down")) + return + if result == "weather_unsafe": + self.flash(message("runtime.helo.weather_unsafe")) + return + if result is not True: + self.flash(message("runtime.helo.lost")) + return + self.announce(message("runtime.helo.launch", torpedoes=self.helo.torps, + buoys=self.helo.buoys_left), "waffen", 3.0) + + def launch_helicopter(self): + if self.damage.station_down("flightdeck"): + return "flightdeck_down" + if not self.helicopter_weather()["launch_safe"]: + return "weather_unsafe" + if self.helo.state != "HANGAR": + return "not_ready" + self.helo.launch(self.ship) + return True + + def return_helicopter(self): + if not self.helo.airborne: + return "not_ready" + self.helo.order_return() + return True + + def set_helicopter_waypoint(self, x: float, y: float): + if (type(x) not in (int, float) or type(y) not in (int, float) + or not 0 <= x <= self.world.size_nm + or not 0 <= y <= self.world.size_nm + or not math.isfinite(x) or not math.isfinite(y)): + return "invalid_value" + if self.helo.state == "VERLOREN": + return "not_ready" + self.helo.set_waypoint(x, y) + return True + + def _helo_waypoint_polar(self) -> tuple[float, float]: + if self.helo.waypoint_x is None or self.helo.waypoint_y is None: + return self.ship.course, 2.0 + dx = self.helo.waypoint_x - self.ship.x + dy = self.helo.waypoint_y - self.ship.y + return math.degrees(math.atan2(dx, -dy)) % 360.0, math.hypot(dx, dy) + + def _adjust_helo_waypoint(self, bearing_delta: float = 0.0, + range_delta: float = 0.0) -> None: + bearing, distance = self._helo_waypoint_polar() + bearing = (bearing + bearing_delta) % 360.0 + distance = config.clamp(distance + range_delta, 1.0, 30.0) + self.helo.set_waypoint( + self.ship.x + distance * math.sin(math.radians(bearing)), + self.ship.y - distance * math.cos(math.radians(bearing))) + self.flash(message("runtime.helo.waypoint", bearing=f"{bearing:03.0f}", + range=f"{distance:.0f}"), 1.5) + + def deploy_buoys(self) -> None: + result = self.deploy_helicopter_buoy() + if result == "not_ready": + self.flash(message("runtime.helo.not_airborne")) + return + if result == "water_required": + self.flash(message("runtime.helo.water_required")) + return + if result is True: + buoy = self.buoys[-1] + self.flash(message("runtime.buoy.deployed", buoy=buoy.seq)) + self.feed.add(self.world.format_time(), "sonar", + message("runtime.buoy.active", buoy=buoy.seq)) + else: + self.flash(message("event.no_buoys")) + + def deploy_helicopter_buoy(self): + if not self.helo.airborne: + return "not_ready" + if not self.helo.water_entry_clear(self.world): + return "water_required" + if self.helo.buoys_left <= 0: + return "no_buoys" + next_sequence = self.buoy_seq + 1 + buoy = self.helo.deploy_buoy(next_sequence, world=self.world, + mode=getattr(self, "helo_buoy_mode", "PASSIVE")) + if buoy is None: + return "not_ready" + self.buoy_seq = next_sequence + self.buoys.append(buoy) + if buoy.mode == "PASSIVE" and not self.helicopter_audio_ready(): + self.set_helicopter_listen_source(f"SB{buoy.seq}") + return True + + def set_helicopter_buoy_mode(self, mode: str): + if mode not in ("PASSIVE", "ACTIVE") or type(mode) is not str: + return "invalid_value" + self.helo_buoy_mode = mode + return True + + def set_helicopter_listen_source(self, source: str): + if source != "DIP": + if (type(source) is not str or not source.startswith("SB") + or not source[2:].isdigit() or len(source) > 5): + return "invalid_value" + seq = int(source[2:]) + if not any(b.seq == seq and b.active for b in self.buoys): + return "stale_ref" + if source != self.helo_listen_source: + self.helo_listen_source = source + self.helo_receiver.reset() + self.helo_audition.reset_audition_audio() + self.helo_spectra.clear() + self.helo_broadband_history.clear() + self.helo_demon_history.clear() + self._helo_receiver_timer = 0.0 + return True + + def set_helicopter_listen_bearing(self, bearing): + if bearing is not None and (type(bearing) not in (int, float) + or not math.isfinite(bearing) + or not 0 <= bearing < 360): + return "invalid_value" + self.helo_listen_bearing = bearing + return True + + def set_helicopter_audio_mode(self, mode: str): + if type(mode) is not str or not self.helo_audition.set_audition_mode(mode): + return "invalid_value" + return True + + def set_helicopter_audio_band(self, preset: str): + band = SONAR_BAND_PRESETS.get(preset) if type(preset) is str else None + if band is None: + return "invalid_value" + self.helo_audition.band_low_hz, self.helo_audition.band_high_hz = band + self.helo_audio_band = preset + return True + + def set_helicopter_audio_gain(self, gain_db): + if type(gain_db) not in (int, float) or not math.isfinite(gain_db) \ + or not -12 <= gain_db <= 24: + return "invalid_value" + self.helo_audition.gain_db = float(gain_db) + return True + + def set_helicopter_audio_notch(self, enabled): + if type(enabled) is not bool: + return "invalid_value" + self.helo_audition.notch_enabled = enabled + return True + + def helicopter_audio_ready(self) -> bool: + """The selected helicopter hydrophone must be in the water.""" + source = self.helo_listen_source + if source == "DIP": + return self.helo.dip_available and self.helo.dip_depth_m > 0.0 + if not source.startswith("SB") or not source[2:].isdigit(): + return False + seq = int(source[2:]) + return any(b.seq == seq and b.active and b.mode == "PASSIVE" + for b in self.buoys) + + def launch_helo_torpedo(self) -> None: + """Leichttorpedo vom HSP-5 (eigene Munition, nicht Fregatten-Rohre).""" + if (self.target is None + or self.sim_t - self.target.last_seen >= config.SONAR_CONTACT_LOST_S): + self.target = None + self.flash(message("runtime.target.invalid")) + return + self.launch_helicopter_torpedo_at(self.target, self.torpedo_depth) + + def launch_helicopter_torpedo_at(self, contact, depth_m: float): + """Release a helicopter torpedo against one explicit sonar observation.""" + if (contact is None or type(depth_m) not in (int, float) + or not math.isfinite(depth_m) or not 10 <= depth_m <= 300 + or self.sim_t - contact.last_seen >= config.SONAR_CONTACT_LOST_S): + self.flash(message("runtime.target.invalid")) + return "invalid_target" + blocked = self._target_affiliation_interlock(contact) + if blocked is not None: + self.flash(message("runtime.roe.blocked", + affiliation=display_value("affiliation", blocked, self.tr))) + return "roe_blocked" + if self.roe == "STD" and not self._contact_range_fresh(contact): + self.flash(message("runtime.target.not_located")) + return "not_located" + if self.weapon_classification(contact) != "U_BOOT": + self.flash(message("runtime.target.air_class")) + return "not_classified" + if not self.helo.airborne: + self.flash(message("runtime.helo.not_airborne")) + return "not_ready" + if self.helo.torps <= 0: + self.flash(message("runtime.helo_no_torpedoes")) + return "empty" + if not self.helo.water_entry_clear(self.world): + self.flash(message("runtime.helo.water_required")) + return "water_required" + tgt = self._find_target(contact.target_id) + lv = self.difficulty + range_nm = (contact.range_est if contact.range_est is not None + else config.ROE_FREE_LAUNCH_RANGE_NM) + use_fix = (self._contact_range_fresh(contact) + and contact.observed_x is not None + and contact.observed_y is not None) + datum = self.helo.release_datum_from_ship_observation( + self.ship, contact.bearing, range_nm, + bearing_uncertainty_deg=max(0.0, (1.0 - contact.quality) * 8.0), + range_uncertainty_nm=contact.range_sigma_nm or 0.0, + datum_x=contact.observed_x if use_fix else None, + datum_y=contact.observed_y if use_fix else None) + torp = self.helo.drop_torpedo( + tgt, depth_m, self.torpedo_seq + 1, + kill_dist_nm=lv["kill_dist_nm"], kill_depth_m=lv["kill_depth_m"], + guidance_x=datum.x_nm, guidance_y=datum.y_nm, world=self.world) + if torp is None: + return "not_ready" + self.torpedo_seq += 1 + self.torpedoes.append(torp) + self._emit_sound("water_entry") + self.flash(message("runtime.helo_torpedo.launched", + torpedo=self.torpedo_seq), 2.0) + self.feed.add(self.world.format_time(), "waffen", + message("runtime.helo_torpedo.feed", + torpedo=self.torpedo_seq, contact=contact.id)) + return True + + @staticmethod + def _missile_seq(track): + """Internal missile sequence behind an ``M-`` air track, else None. + + An ASM cue can also sit on an aircraft track; fire control resolves + the engaged weapon only through the missile's own track namespace. + """ + track_id = str(getattr(track, "track_id", "")) + suffix = track_id[2:] + return int(suffix) if track_id.startswith("M-") and suffix.isdigit() else None + + def _cycle_asm_track(self, delta: int) -> None: + n = len(self.asm_tracks()) + if n == 0: + self.asm_sel = 0 + return + self.asm_sel = (self.asm_sel + delta) % n + + def launch_essm(self) -> None: + tracks = self.asm_tracks() + track = tracks[min(self.asm_sel, len(tracks) - 1)] if tracks else None + self.launch_essm_at(track) + + def launch_essm_at(self, track): + """Launch against an explicit current positioned ASM observation.""" + profiles = self._air_defense_loadout + if self.damage.station_down("opz") or self.damage.station_degraded("opz"): + self.flash(message("runtime.opz.degraded")) + return "opz_degraded" + if self.vls_cells <= 0: + self.flash(message("runtime.vls.empty")) + return "empty" + if len(self.essms) >= profiles["vls"]["fire_channels"]: + self.flash(message("runtime.vls.empty")) + return "active_limit" + if not any(item is track for item in self.asm_tracks()): + self.flash(message("runtime.asm.none")) + return "invalid_target" + sam = profiles["sam"] + if track.range_nm is None or track.range_nm > sam["range_nm"]: + self.flash(message("runtime.asm.range", range=f"{sam['range_nm']:.0f}")) + return "out_of_range" + if (track.x is None or track.y is None or track.position_seen is None + or self.sim_t - track.position_seen + > sam["observation_max_age_s"]): + self.flash(message("runtime.asm.stale")) + return "stale_ref" + missile_seq = self._missile_seq(track) + tgt = next((a for a in self.asms if a.seq == missile_seq), None) + course = math.degrees(math.atan2(track.x - self.ship.x, + -(track.y - self.ship.y))) % 360.0 + self.essm_seq += 1 + self.essms.append(ESSM(self.ship.x, self.ship.y, course, tgt, + self.essm_seq, + guidance_x=track.x, guidance_y=track.y, + target_id=missile_seq, profile=sam)) + self.vls_cells -= 1 + self._emit_sound("missile_launch") + self.announce(message("runtime.essm.launched", cells=self.vls_cells), + "waffen", 2.0) + return True + + def launch_chaff(self) -> None: + tracks = self.asm_tracks() + track = tracks[min(self.asm_sel, len(tracks) - 1)] if tracks else None + self.launch_chaff_at(track) + + def launch_chaff_at(self, track): + """Deploy one softkill round against an explicit ASM observation.""" + if self.damage.station_down("opz"): + self.flash(message("runtime.chaff.disabled")) + return "opz_down" + if self.softkill_store.ready <= 0: + self.flash(message("runtime.chaff.cooldown", seconds=f"{self.chaff_cd:.0f}")) + return "not_ready" + if track is None or not any(item is track for item in self.asm_tracks()): + self.flash(message("runtime.chaff.none")) + return "invalid_target" + a = next((item for item in self.asms + if item.seq == self._missile_seq(track) + and item.state == "LAUF"), None) + profile = self._air_defense_loadout["softkill"] + if (a is not None and track.range_nm is not None + and track.position_seen is not None + and self.sim_t - track.position_seen <= self._air_defense_loadout[ + "sam"]["observation_max_age_s"] + and track.range_nm <= profile["range_nm"] + and self.softkill_store.fire()): + self.chaff_seq += 1 + threat = math.degrees(math.atan2(a.x - self.ship.x, + -(a.y - self.ship.y))) % 360.0 + cloud = chaff_physics.ChaffCloud( + self.chaff_seq, *chaff_physics.lay_position( + self.ship.x, self.ship.y, threat, self.chaff_seq)) + self.chaff_clouds = (self.chaff_clouds + [cloud])[ + -chaff_physics.MAX_CLOUDS:] + arrival = (math.hypot(a.x - cloud.x, a.y - cloud.y) + / max(config.kn_to_nm_per_s(a.speed_kn), 1e-9)) + broke = a.launch_chaff(self.rng_asm, profile, cloud_seq=cloud.seq, + arrival_s=arrival) + self.chaff_cd = min(self.softkill_store.loading, default=0.0) + self.announce(message("runtime.chaff.decoyed" if broke + else "runtime.chaff.jammed"), "waffen") + return True + else: + self.flash(message("runtime.chaff.none")) + return "stale_ref" + + def deploy_nixie(self) -> None: + """Deploy one finite towed acoustic countermeasure from own ship.""" + self.deploy_nixie_result() + + def deploy_nixie_result(self): + if len(self.nixies) >= MAX_TOWED_DECOYS: + self.flash(message("runtime.nixie.active")) + return "active_limit" + if not self.nixie_store.fire(): + self.flash(message("runtime.nixie.empty")) + return "empty" + definition = self._ownship_loadout["countermeasure"] + self.nixie_seq += 1 + self.nixies.append(TowedAcousticDecoy( + self.nixie_seq, self.ship, life_s=definition["active_life_s"], + tether_nm=definition["tether_nm"], depth_m=definition["depth_m"])) + self.announce(message("runtime.nixie.deployed", + count=self.nixie_store.remaining_total), "waffen") + return True + + def set_flak_authorized(self, authorized: bool): + """Fire-release gate for the AA gun; it never engages FLG raiders + while withheld, regardless of ammo/cooldown/range readiness.""" + if type(authorized) is not bool: + return "invalid_value" + if self.damage.station_down("weapons"): + return "weapons_down" + self.flak_authorized = authorized + return True + + def set_ciws_authorized(self, authorized: bool): + """Fire-release gate for CIWS; it never engages inbound ASMs while + withheld, regardless of ammo/cooldown/range readiness.""" + if type(authorized) is not bool: + return "invalid_value" + if self.damage.station_down("opz"): + return "opz_down" + self.ciws_authorized = authorized + return True + + def set_target(self) -> None: + contacts = [c for c in self.sonar.active_contacts() + if self.sim_t - c.last_seen < config.SONAR_CONTACT_LOST_S] + if not contacts: + self.target = None + self.flash(message("runtime.contacts.none")) + return + if self.selected_contact in contacts: + best = self.selected_contact + else: + best = max(contacts, key=lambda c: c.confidence) + if self.designate_sonar_target(best) is not True: + return + self.flash(message("runtime.target.set", contact=best.id), 2.0) + + def torpedo_readiness(self) -> tuple[str, tuple]: + """Return an operator-readable fire-control state and color.""" + if (self.target is None + or self.sim_t - self.target.last_seen >= config.SONAR_CONTACT_LOST_S): + return "BLOCKIERT: KEIN ZIEL", config.COLOR_WARN + blocked = self._target_affiliation_interlock() + if blocked is not None: + return (f"BLOCKIERT: ZUGEHOERIGKEIT {blocked}", + config.COLOR_DANGER) + if not self._contact_range_fresh(self.target) and self.roe == "STD": + return "BLOCKIERT: KEINE ENTFERNUNG", config.COLOR_WARN + if self.weapon_classification(self.target) not in ("U_BOOT", "KAMPFSCHIFF"): + return ("BLOCKIERT: NICHT ALS U-BOOT/KAMPFSCHIFF KLASSIFIZIERT", + config.COLOR_WARN) + if self.torpedo_count <= 0: + return "BLOCKIERT: KEINE TORPEDOS", config.COLOR_DANGER + if self.player_torpedo_battery.ready_count <= 0: + return "BLOCKIERT: KEIN ROHR BEREIT", config.COLOR_WARN + if len([t for t in self.torpedoes if t.state == "RUN"]) >= \ + config.TORP_MAX_IN_AIR[config.TORP_DOCTRINE]: + return "BLOCKIERT: SALVENLIMIT", config.COLOR_WARN + if self.damage.station_down("weapons") or \ + self.damage.station_degraded("weapons"): + return "BLOCKIERT: WAFFENZENTRALE GESTOERT", config.COLOR_DANGER + return "FEUER FREI", config.COLOR_OK + + def _contact_affiliations(self, contact) -> list: + """Return every OPZ affiliation annotation bound to a sonar target.""" + if contact is None: + return [] + # Operator annotations outlive measurements. Aircraft/missile sequence + # IDs are a separate namespace and must not annotate a sonar target. + affiliations = [self.opz_affiliations.get( + f"{prefix}-{contact.target_id}", "UNKNOWN") + for prefix in ("U", "S")] + self.opz_source_observations() + affiliations.extend( + self.opz_affiliation(observation_id) + for observation_id, source in self._opz_source_bindings.items() + if (source is contact or getattr(source, "target_id", None) + == contact.target_id and str( + getattr(source, "track_id", "")).split("-", 1)[0] + in ("U", "S"))) + # An affiliation set on an OPZ fusion covers every sonar report in it. + affiliations.extend( + self.opz_fusion.fusion_affiliations[fusion.fusion_id] + for fusion in self._contact_fusions(contact) + if fusion.fusion_id in self.opz_fusion.fusion_affiliations) + return affiliations + + def _contact_fusions(self, contact) -> list: + """Intact OPZ fusions holding a report bound to this sonar contact. + + Read-only: a fusion counts only while all its member reports are + current (the condition ``OPZFusion.prune`` applies), so the result + never depends on whether a frame pruned the register first. + """ + if contact is None or not self.opz_fusion.fusions: + return [] + current = {item.observation_id for item in self.opz_source_observations()} + bindings = self._opz_source_bindings + return [fusion for _, fusion in sorted(self.opz_fusion.fusions.items()) + if set(fusion.members) <= current + and any(bindings.get(member) is contact + for member in fusion.members)] + + def weapon_classification(self, contact) -> str | None: + """Operator class that fire control uses for one sonar contact. + + The sonar contact's own class wins; otherwise the class the OPZ gave a + fusion holding this contact's report applies. + """ + if contact is None: + return None + if contact.player_class in config.PLAYER_CLASSES: + return contact.player_class + return next((self.opz_fusion.classifications[fusion.fusion_id] + for fusion in self._contact_fusions(contact) + if self.opz_fusion.classifications.get(fusion.fusion_id) + in config.PLAYER_CLASSES), None) + + def contact_affiliation(self, contact) -> str: + """Resolve one affiliation for a contact, FRIEND/NEUTRAL taking + precedence over HOSTILE so callers stay conservative by default.""" + affiliations = self._contact_affiliations(contact) + return next((value for value in ("FRIEND", "NEUTRAL", "HOSTILE") + if value in affiliations), "UNKNOWN") + + def _target_affiliation_interlock(self, contact=None): + """Return a protected OPZ affiliation for the assigned sonar target.""" + contact = self.target if contact is None else contact + if contact is None: + return None + affiliations = self._contact_affiliations(contact) + return next((value for value in ("FRIEND", "NEUTRAL") + if value in affiliations), None) + + def _contact_range_fresh(self, contact) -> bool: + if contact is None or contact.range_est is None: + return False + observed_at = (contact.range_seen if contact.range_seen is not None + else contact.last_seen) + return self.sim_t - observed_at <= config.SONAR_CONTACT_LOST_S + + # --- M9: Kontakt-Auswahl & manuelle Klassifizierung --- + + def _cycle_selected_contact(self, delta: int) -> None: + cs = sorted((c for c in self.sonar.contacts.values() + if self.sim_t - c.last_seen < config.SONAR_CONTACT_LOST_S), + key=lambda c: c.id) + if not cs: + self.selected_contact = None + return + try: + i = cs.index(self.selected_contact) + except ValueError: + i = -1 + self.selected_contact = cs[(i + delta) % len(cs)] + if self.sonar.focus_locked: + self.sonar.reset_listening_history() + + def _cycle_helo_contact(self, delta: int) -> None: + """W2: browse only what the helicopter's own dip has plotted - its + own active/passive picture, independent of the ship's sonar picture - + so the operator can select one and release it to CIC from here.""" + cs = sorted((c for c in self.sonar.contacts.values() + if (c.dip_last_seen is not None + and 0 <= self.sim_t - c.dip_last_seen + < config.SONAR_CONTACT_LOST_S) + or any(fix["source"] == "DIPPING" + for fix in c.active_fixes(self.sim_t)) + or any(0 <= self.sim_t - row["measured_at"] + < config.SONAR_CONTACT_LOST_S + for row in c.buoy_reports.values())), + key=lambda c: c.id) + if not cs: + self.selected_contact = None + self.flash(message("runtime.contact.none_selected")) + return + try: + i = cs.index(self.selected_contact) + except ValueError: + i = -1 + self.selected_contact = cs[(i + delta) % len(cs)] + + def _cycle_classification(self) -> None: + if self.selected_contact is None: + self.flash(message("runtime.contact.none_selected")) + return + if self.selected_contact.target_id not in self.sonar.contacts: + self.selected_contact = None + return + c = self.selected_contact + order = [None] + list(config.PLAYER_CLASSES) + value = order[(order.index(c.player_class) + 1) % len(order)] + if self.classify_sonar_contact(c, value) is not True: + return + self.flash(message("runtime.contact.classified", contact=c.id, + classification=display_value("classification", + c.player_class, self.tr)), 2.0) + + def _toggle_sonar_release(self) -> None: + contact = self.selected_contact + if contact is None: + self.flash(message("runtime.contact.none_selected")) + return + helicopter = self.station is Station.HELICOPTER + buoy = helicopter and self.helo_sensor_source == "BUOY" + released = not (contact.buoy_released_to_opz if buoy else + contact.dip_released_to_opz if helicopter + else contact.released_to_opz) + if self.release_sonar_contact(contact, released, + source="buoy" if buoy else + "helicopter" if helicopter else "sonar") is not True: + return + self.flash(message("runtime.sonar.release" if released + else "runtime.sonar.withdraw", + contact=contact.id), 2.0) + + def _find_target(self, target_id: int): + for s in self.subs: + if s.id == target_id: + return s + for a in self.animals: + if a.id == target_id: + return a + for d in self.decoys: + if d.id == target_id: + return d + for civilian in self.civilians: + if civilian.id == target_id: + return civilian + for w in self.warships: + if w.id == target_id: + return w + for t in self.enemy_torpedoes: + if t.id == target_id: + return t + return None + + def launch_torpedo(self) -> None: + if (self.target is None + or self.sim_t - self.target.last_seen >= config.SONAR_CONTACT_LOST_S): + self.target = None + self.flash(message("runtime.target.invalid")) + return + self.launch_torpedo_at(self.target, self.torpedo_depth) + + def launch_torpedo_at(self, contact, depth_m: float): + """Launch from ownship against one explicit sonar observation.""" + if (contact is None or type(depth_m) not in (int, float) + or not math.isfinite(depth_m) or not 10 <= depth_m <= 300 + or self.sim_t - contact.last_seen >= config.SONAR_CONTACT_LOST_S): + self.flash(message("runtime.target.invalid")) + return "invalid_target" + blocked = self._target_affiliation_interlock(contact) + if blocked is not None: + self.flash(message("runtime.roe.blocked", + affiliation=display_value("affiliation", blocked, self.tr))) + return "roe_blocked" + if self.roe == "STD": + if not self._contact_range_fresh(contact): + self.flash(message("runtime.target.not_located")) + return "not_located" + if self.weapon_classification(contact) not in ("U_BOOT", "KAMPFSCHIFF"): + self.flash(message("runtime.target.not_classified")) + return "not_classified" + else: + if self.weapon_classification(contact) not in ("U_BOOT", "KAMPFSCHIFF"): + self.flash(message("runtime.target.not_classified")) + return "not_classified" + active_torpedoes = len([t for t in self.torpedoes if t.state == "RUN"]) + salvo_limit = config.TORP_MAX_IN_AIR[config.TORP_DOCTRINE] + if active_torpedoes >= salvo_limit: + self.flash(message("runtime.salvo.limit", limit=salvo_limit)) + return "salvo_limit" + if self.torpedo_count <= 0: + self.flash(message("event.no_torpedoes")) + return "empty" + if self.player_torpedo_battery.ready_count <= 0: + self.flash(message("runtime.torpedo.no_tube")) + return "no_tube" + if self.damage.station_down("weapons"): + self.flash(message("runtime.weapons.down")) + return "weapons_down" + if self.damage.station_degraded("weapons"): + self.flash(message("runtime.weapons.degraded")) + return "weapons_degraded" + tgt = self._find_target(contact.target_id) + if (contact.observed_x is not None + and contact.observed_y is not None + and self._contact_range_fresh(contact)): + est_x, est_y = contact.observed_x, contact.observed_y + else: + range_nm = (contact.range_est if contact.range_est is not None + else config.ROE_FREE_LAUNCH_RANGE_NM) + est_x = self.ship.x + range_nm * math.sin(math.radians(contact.bearing)) + est_y = self.ship.y - range_nm * math.cos(math.radians(contact.bearing)) + course = math.degrees(math.atan2(est_x - self.ship.x, + -(est_y - self.ship.y))) % 360.0 + weapon_key = self.player_torpedo_battery.fire() + if weapon_key is None: + self.flash(message("runtime.torpedo.no_tube")) + return "no_tube" + self.torpedo_seq += 1 + weapon_definition = next( + item + for item in self._ownship_loadout["weapons"] + if item["key"] == weapon_key) + profile_key = weapon_definition["runtime_profile_key"] + profile = self.runtime_catalog.torpedoes[profile_key] + self.torpedoes.append(Torpedo(self.ship.x, self.ship.y, course, + depth_m, tgt, self.torpedo_seq, + kill_dist_nm=self.difficulty["kill_dist_nm"], + kill_depth_m=self.difficulty["kill_depth_m"], + guidance_x=est_x, guidance_y=est_y, + profile=profile, time_since_launch=0.0)) + self.torpedo_count = self.player_torpedo_battery.remaining_total + # W2: the launch transient itself is a loud, one-time acoustic event, + # audible passively much farther than a torpedo's own terminal seeker + # ever gets (TORP_HOME_RANGE_NM) - distinct concept, separate gate. + for sub in self.subs: + if (not sub.sunk and sub.state != "SINKING" + and math.hypot(self.ship.x - sub.x, self.ship.y - sub.y) + <= config.SUB_TORPEDO_ALERT_NM + and not self.world.sonar_path_blocked( + self.ship.x, self.ship.y, 5.0, + sub.x, sub.y, sub.depth)): + sub.alert_torpedo(source=(self.ship.x, self.ship.y)) + for warship in self.warships: + if (not warship.sunk and warship.doctrine == "surface_combatant" + and math.hypot(self.ship.x - warship.x, self.ship.y - warship.y) + <= config.SUB_TORPEDO_ALERT_NM + and not self.world.sonar_path_blocked( + self.ship.x, self.ship.y, 5.0, + warship.x, warship.y, warship.depth)): + bearing = math.degrees(math.atan2( + self.ship.x - warship.x, + -(self.ship.y - warship.y))) % 360.0 + warship.alert_torpedo(bearing) + if (warship.countermeasures_left > 0 and warship.side == "hostile" + and len(self.decoys) < MAX_DECOYS): + # Stream an acoustic decoy while turning away. + warship.countermeasures_left -= 1 + decoy_profile = self.runtime_catalog.decoys[ + self.runtime_catalog.runtime_bindings["submarine_decoy"]] + self.decoys.append(Decoy( + warship.x, warship.y, 10.0, self.rng_asw, decoy_profile, + self.runtime_catalog.acoustic_for(decoy_profile.key), + source_id=warship.id)) + self._emit_sound("torpedo_launch") + self.flash(message("runtime.torpedo.launched", torpedo=self.torpedo_seq), 2.0) + self.feed.add(self.world.format_time(), "waffen", + message("runtime.torpedo.feed", torpedo=self.torpedo_seq, + contact=contact.id)) + return True + + # --- Update --- + + def hq_msg(self, text: object) -> None: + """M13/W3: Teletype-Nachricht – Funkraum-Verkehr + Ereignis-Feed.""" + stamp = self.world.format_time() + self.messages.append((stamp, text)) + if len(self.messages) > 40: + self.messages.pop(0) + self.feed.add(stamp, "funk", text) + + def assign_contact_profile(self, contact, profile_key): + """Operator annotation: this contact matches that catalog profile.""" + if contact is None or contact.target_id not in self.sonar.contacts: + return "stale_ref" + if profile_key is not None and ( + type(profile_key) is not str + or profile_key not in self.runtime_catalog.profile_systems): + return "invalid_value" + contact.player_profile = profile_key + if profile_key is None: + notice = message("runtime.profile.cleared", + contact=self.contact_display_id(contact)) + else: + notice = message("runtime.profile.assigned", + contact=self.contact_display_id(contact), + profile=raw_text(self.profile_name(profile_key))) + self._sonar_notice(notice, 2.0) + return True + + def profile_name(self, key): + """Display name of a catalog profile (as listed in the analyser).""" + if key is None: + return None + names = self.__dict__.get("_profile_names") + if names is None: + from src.data.contact_analysis import project_contact_catalog + names = {row["key"]: str(row["name"]) + for row in project_contact_catalog()["profiles"]} + self._profile_names = names + return names.get(key, key) + + def _make_analyzer(self) -> ContactAnalyzer: + """Read-only Kontakt-Katalog-Browser (Menue und In-Game, F8).""" + return ContactAnalyzer( + tr=self.tr, on_play_sample=self._play_unit_audio, + on_stop_sample=self.audio.stop_preview, + preview_active=self.audio.preview_playing) + + def _open_analyzer_in_game(self) -> None: + """TUA im laufenden Spiel: Simulation laeuft weiter, Esc kehrt ins Spiel zurueck. + + With a sonar contact selected, Enter assigns the browsed profile to + it (the operator's catalog comparison result).""" + self._clear_controls() + contact = self.selected_contact + if contact is None or contact.target_id not in self.sonar.contacts: + self.editor = self._make_analyzer() + return + analyzer = self._make_analyzer() + analyzer.on_assign = lambda key: self.assign_contact_profile(contact, key) + analyzer.assign_label = self.contact_display_id(contact) + analyzer.current_assignment = lambda: self.profile_name(contact.player_profile) + self.editor = analyzer + + def _open_simlog_view(self) -> None: + """F4: Live-Protokoll-Ansicht; nur bei aktiver simlog-Option.""" + if not self.preferences.simlog: + self.flash(message("simlog.view_disabled"), 2.0) + return + self._clear_station_input() + self.simlog_view_open = True + self.simlog_view_scroll = 0 + self.simlog_view_map = False + + def _close_simlog_view(self) -> None: + self.simlog_view_open = False + self.simlog_view_scroll = 0 + self.simlog_view_map = False + self._clear_station_input() + + def _scroll_simlog_view(self, amount: int) -> None: + self.simlog_view_scroll = max(0, self.simlog_view_scroll + amount) + + def capture_hfdf(self) -> None: + reports = self.hfdf_bearings() + if not reports: + self.flash(message("runtime.hfdf.none")) + return + report = reports[min(self.radio_sel, len(reports) - 1)] + self.capture_hfdf_report(report) + + def capture_hfdf_report(self, report): + if self.damage.station_down("radio"): + return "radio_down" + if not any(item is report for item in self.hfdf_bearings()): + return "stale_ref" + if report.age(self.sim_t) > config.RADAR_TRACK_STALE_S: + self.flash(message("runtime.hfdf.stale")) + return "stale_ref" + measurement = (report.measurement_history[-1] + if report.measurement_history else {}) + display_id = self.hfdf_display_id(report) + row = dict(track_id=report.track_id, label=display_id, + bearing=measurement.get("bearing", report.bearing), + observer_x=measurement.get("observer_x", self.ship.x), + observer_y=measurement.get("observer_y", self.ship.y), + t=measurement.get("t", report.last_seen)) + self.hfdf_log.append(row) + self.hfdf_log = self.hfdf_log[-20:] + previous = next((item for item in reversed(self.hfdf_log[:-1]) + if item["track_id"] == report.track_id + and 0 < row["t"] - item["t"] <= 300.0 + and math.hypot(item["observer_x"] - row["observer_x"], + item["observer_y"] - row["observer_y"]) >= 1.0), None) + if previous is None: + self.announce(message("runtime.hfdf.logged", label=display_id, + bearing=f"{report.bearing:05.1f}"), "funk") + return True + fix = self._bearing_intersection(previous, row) + if fix is None: + self.announce(message("runtime.hfdf.geometry"), "funk") + return True + x, y, geometry = fix + # Angular errors projected at the two measurement origins. This assumes + # a stationary emitter throughout the bounded observation span. + b1, b2 = math.radians(previous["bearing"]), math.radians(row["bearing"]) + # Sky-wave intercepts carry the larger ionospheric-tilt uncertainty. + sigma_rad = math.radians(report.bearing_uncertainty_deg + or config.HFDF_BEARING_ERR_DEG / math.sqrt(3.0)) + v1 = sigma_rad ** 2 * ((x - previous["observer_x"]) ** 2 + + (y - previous["observer_y"]) ** 2) + v2 = sigma_rad ** 2 * ((x - row["observer_x"]) ** 2 + + (y - row["observer_y"]) ** 2) + xx = (math.sin(b2) ** 2 * v1 + math.sin(b1) ** 2 * v2) / geometry ** 2 + yy = (math.cos(b2) ** 2 * v1 + math.cos(b1) ** 2 * v2) / geometry ** 2 + xy = -(math.sin(b2) * math.cos(b2) * v1 + + math.sin(b1) * math.cos(b1) * v2) / geometry ** 2 + self.hfdf_fixes[report.track_id] = dict( + label=display_id, x=x, y=y, + sigma_nm=math.sqrt(max(0.0, (xx + yy + math.hypot(xx - yy, 2 * xy)) / 2)), + covariance_nm2=(xx, xy, yy), + t=row["t"]) + dist = math.hypot(x - row["observer_x"], y - row["observer_y"]) + bearing = math.degrees(math.atan2( + x - row["observer_x"], -(y - row["observer_y"]))) % 360.0 + self.air_picture.observe( + track_id=f"H-{report.target_id}", kind="UNKNOWN", + target_id=report.target_id, source="HFDF-FIX", bearing=bearing, + range_nm=dist, observer_x=row["observer_x"], + observer_y=row["observer_y"], + course=None, quality=max(.25, geometry), now=row["t"], + label=display_id) + self.flash(message("runtime.hfdf.fix", label=display_id), 3.0) + self.feed.add(self.world.format_time(), "funk", + message("runtime.hfdf.feed", label=display_id)) + return True + + def _cycle_hfdf(self, delta: int) -> None: + reports = self.hfdf_bearings() + self.radio_sel = 0 if not reports else (self.radio_sel + delta) % len(reports) + + @staticmethod + def _bearing_intersection(first: dict, second: dict): + """Intersect two nautical bearing rays; return None for weak geometry.""" + b1, b2 = math.radians(first["bearing"]), math.radians(second["bearing"]) + r = (math.sin(b1), -math.cos(b1)) + s = (math.sin(b2), -math.cos(b2)) + denom = r[0] * s[1] - r[1] * s[0] + if abs(denom) < math.sin(math.radians(12.0)): + return None + qx, qy = second["observer_x"] - first["observer_x"], \ + second["observer_y"] - first["observer_y"] + along_first = (qx * s[1] - qy * s[0]) / denom + along_second = (qx * r[1] - qy * r[0]) / denom + if along_first < 0.0 or along_second < 0.0: + return None + return (first["observer_x"] + along_first * r[0], + first["observer_y"] + along_first * r[1], abs(denom)) + + def hfdf_bearings(self) -> list: + """Current and recently retained HFDF observations.""" + return self.radio_picture.tracks(self.sim_t, ("HF",)) + + def hfdf_display_id(self, report) -> str: + """Return the stable public identifier for an HFDF observation.""" + track_id = report if isinstance(report, str) else report.track_id + return "H-" + self._observation_key("hfdf-display", track_id)[-6:] diff --git a/src/core/game_pictures.py b/src/core/game_pictures.py new file mode 100644 index 00000000..8c144698 --- /dev/null +++ b/src/core/game_pictures.py @@ -0,0 +1,1486 @@ +"""The operator-facing pictures of the game: OPZ observations, tracks, fusion +and affiliation, the shared plot layer, ELOKA analysis, weather and lookout +reports, and the SimLog history (``Game`` mixin). Views consume these; none +of them discovers hidden entity state. + +Verbatim moves from ``game.py`` (plan 1.3, phase 2, step 4b).""" + +import hashlib +import math +from dataclasses import replace + +import pygame + +from src.core import config +from src.core import plot as plot_geometry +from src.core.i18n import display_value, message, raw_text +from src.core.station import Station +from src.core.limits import MAX_OPZ_TRACK_LABELS, MAX_TRACK_DISPLAY_ID_LEN +from src.sensors import visual as visual_physics +from src.sensors import lookout_id +from src.world import atmosphere as atmosphere_physics +from src.world import ocean as ocean_physics +from src.sonar import raytrace as sonar_raytrace +from src.sensors.fusion import OPZObservation, source_classification +from src.sensors.esm import ( + ESM_MAX_ANNOTATIONS, + ESMCorrelationEvidence, + ECM_TECHNIQUES, + analyze_signal, + correlate_observations, + estimated_range_nm, + filter_and_sort_tracks, + library_emitters, + rank_emitters) +from src.sonar.sonar import Contact +from src.air import helicopter as helicopter_physics +# Shared display/help constants and helpers (re-exported for tests/tools). +# Names tests and tools import from ``src.core.game`` (kept as re-exports). + + +class PicturesMixin: + """Picture half of ``Game``: what the stations and browsers are shown.""" + + def radar_tracks(self) -> list: + """Compatibility view of the persistent surface/air picture.""" + tracks = [] + for t in self.air_picture.tracks(self.sim_t): + if "AIS" in t.source.upper(): + continue + derived_course, derived_speed = t.derived_motion() + tracks.append(dict( + kind=t.kind, track_id=t.track_id, target_id=t.target_id, + source=t.source, dist=t.range_nm, bearing=t.bearing, + x=t.x, y=t.y, + course=t.course if t.course is not None else derived_course, + speed_kn=derived_speed, + quality=t.display_quality(self.sim_t, self.air_picture.stale_s), + label=self.opz_track_label( + self._opz_observation_id("picture", t.track_id), + self._opz_observation_id("picture", t.track_id)[-6:]), + hostile=t.hostile, jamming=t.jamming, + age=t.age(self.sim_t), position_seen=t.position_seen, + bearing_uncertainty_deg=t.bearing_uncertainty_deg, + altitude_m=t.altitude_m, + visual=t.label if t.source == "LOOKOUT" else None)) + return tracks + + def _opz_observation_id(self, namespace: str, identity: object) -> str: + return "O-" + self._observation_key("opz-" + namespace, identity) + + def opz_track_label(self, observation_id: str, fallback: str) -> str: + """Return the one shared, operator-visible ID for an observation.""" + return self.opz_track_labels.get(observation_id, fallback) + + def contact_display_id(self, contact: Contact) -> str: + if self._sonar_ctx is not self._frigate_sonar: + # A crewed boat's contacts never carry frigate OPZ labels. + return f"K{contact.id:02d}" + observation_id = self._opz_observation_id("sonar", contact.target_id) + return self.opz_track_label(observation_id, f"K{contact.id:02d}") + + def set_opz_track_label(self, observation_id: str, label: str): + """Assign an OPZ-authored display ID without changing track identity.""" + if self.damage.station_down("opz"): + return "opz_down" + if (type(label) is not str or not 1 <= len(label) <= MAX_TRACK_DISPLAY_ID_LEN + or not label.isascii() + or any(not (char.isalnum() or char == "-") for char in label) + or not any(char.isalnum() for char in label)): + return "invalid_value" + current = {item.observation_id for item in self.opz_published_observations()} + if observation_id not in current: + return "stale_ref" + if (observation_id not in self.opz_track_labels + and len(self.opz_track_labels) >= MAX_OPZ_TRACK_LABELS): + del self.opz_track_labels[next(iter(self.opz_track_labels))] + self.opz_track_labels[observation_id] = label.upper() + return True + + def _detached_air_observations(self) -> list[OPZObservation]: + observations = [] + bindings = {} + for track in self.air_picture.tracks(self.sim_t): + # Sonar owns its release policy and detached report identity. Legacy + # save-backed mirrors are never consumed as OPZ source reports. + if track.source.startswith("SONAR") or "AIS" in track.source.upper(): + continue + observation_id = self._opz_observation_id("picture", track.track_id) + classification = (self.opz_fusion.classifications.get(observation_id) + if (track.source.startswith("RADAR") + or track.source == "HOJ") + else self.released_esm_labels().get(track.track_id) + if track.source == "ESM" else None) + kind = "UNKNOWN" if track.source == "ESM" else track.kind + derived_course, derived_speed = track.derived_motion() + observation = OPZObservation( + observation_id, track.source, kind, track.bearing, track.range_nm, + track.x, track.y, + track.course if track.course is not None else derived_course, + track.quality, track.last_seen, + self.opz_track_label(observation_id, observation_id[-6:]), classification, + track.bearing_uncertainty_deg, track.position_seen, track.jamming, + speed_kn=derived_speed, altitude_m=track.altitude_m, + visual=track.label if track.source == "LOOKOUT" else None) + observations.append(observation) + bindings[observation_id] = track + self._opz_source_bindings = bindings + return observations + + def _sonar_opz_observations(self, released_only: bool) -> list[OPZObservation]: + """Return detached Sonar reports without carrying contact identity.""" + observations = [] + for _, contact in sorted(self.sonar.contacts.items()): + if ((released_only and not contact.released_to_opz) + or not 0.0 <= self.sim_t - contact.last_seen + < config.SONAR_CONTACT_LOST_S): + continue + observation_id = self._opz_observation_id("sonar", contact.target_id) + fixes = tuple(fix for fix in contact.active_fixes(self.sim_t) + if fix["source"] not in ("DIPPING", "SONOBUOY")) + ship_passive_seen = (contact._bearing_filter_t + if contact._bearing_filter_t is not None + else contact.last_seen) + ship_passive_current = (contact.passive_bearing is not None + and 0 <= self.sim_t - ship_passive_seen + < config.SONAR_CONTACT_LOST_S) + if released_only and not ship_passive_current and not fixes: + continue + fix_by_source = {item["source"]: item for item in fixes} + fix = max(fixes, key=lambda item: (item["fixed_at"], item["source"])) \ + if fixes else None + x = fix["x"] if fix is not None else None + y = fix["y"] if fix is not None else None + observer_x = (contact.ship_observer_x + if ship_passive_current and contact.ship_observer_x is not None + else self.ship.x if ship_passive_current + else contact.observer_x) + observer_y = (contact.ship_observer_y + if ship_passive_current and contact.ship_observer_y is not None + else self.ship.y if ship_passive_current + else contact.observer_y) + bearing_uncertainty_deg = contact.bearing_uncertainty_deg + if x is not None and y is not None: + dx, dy = x - self.ship.x, y - self.ship.y + bearing = math.degrees(math.atan2(dx, -dy)) % 360.0 + range_nm = math.hypot(dx, dy) + source = "SONAR-" + fix["source"] + elif ship_passive_current: + bearing = contact.passive_bearing + range_nm = None + source = contact.passive_source + elif not released_only and contact.dip_bearing is not None: + bearing = contact.dip_bearing + range_nm = None + source = "SONAR-DIP-BRG" + observer_x, observer_y = contact.dip_observer_x, contact.dip_observer_y + bearing_uncertainty_deg = contact.dip_bearing_uncertainty_deg + else: + continue + course = contact.tma_course if "TMA" in fix_by_source else None + speed = contact.tma_speed if "TMA" in fix_by_source else None + depth = (contact.depth_est + if "PING" in fix_by_source or "DIPPING" in fix_by_source + else None) + observation = OPZObservation( + observation_id, source, "UNKNOWN", bearing, range_nm, x, y, course, + max(contact.quality, contact.confidence), + (fix["measured_at"] if fix is not None + else ship_passive_seen if ship_passive_current + else contact.last_seen), + self.opz_track_label(observation_id, f"K{contact.id:02d}"), (contact.player_class + if contact.player_class in config.PLAYER_CLASSES + else None), + bearing_uncertainty_deg, + fix["measured_at"] if fix is not None else None, + depth_m=depth, speed_kn=speed, + observer_x=observer_x, observer_y=observer_y, + released_to_opz=contact.released_to_opz) + observations.append(observation) + self._opz_source_bindings[observation_id] = contact + return observations + + def private_sonar_observations(self) -> tuple[OPZObservation, ...]: + """Fresh private acoustic reports for role-specific projections.""" + return tuple((*self._sonar_opz_observations(False), + *self._buoy_opz_observations(released_only=False))) + + def _helicopter_opz_observations(self) -> list[OPZObservation]: + """The helicopter's separately released, measured dip reports.""" + reports = [] + for _, contact in sorted(self.sonar.contacts.items()): + if not contact.dip_released_to_opz: + continue + passive = (contact.dip_bearing is not None + and contact.dip_last_seen is not None + and 0 <= self.sim_t - contact.dip_last_seen + < config.SONAR_CONTACT_LOST_S) + fixes = [fix for fix in contact.active_fixes(self.sim_t) + if fix["source"] == "DIPPING"] + fix = max(fixes, key=lambda item: item["fixed_at"]) if fixes else None + if not passive and fix is None: + continue + origin_x = contact.dip_observer_x if passive else contact.observer_x + origin_y = contact.dip_observer_y if passive else contact.observer_y + bearing = (contact.dip_bearing if passive else math.degrees( + math.atan2(fix["x"] - origin_x, -(fix["y"] - origin_y))) % 360.0) + range_nm = (None if passive else math.hypot( + fix["x"] - origin_x, fix["y"] - origin_y)) + observation_id = self._opz_observation_id("sonar-dip", contact.target_id) + reports.append(OPZObservation( + observation_id, + "SONAR-DIP-BRG" if passive else "SONAR-DIPPING", + "UNKNOWN", bearing, range_nm, + None if passive else fix["x"], + None if passive else fix["y"], None, + max(contact.quality, contact.confidence), + max(contact.dip_last_seen if passive else 0.0, + fix["measured_at"] if fix is not None else 0.0), + self.opz_track_label(observation_id, f"K{contact.id:02d} H"), + contact.player_class if contact.player_class in config.PLAYER_CLASSES + else None, + contact.dip_bearing_uncertainty_deg if passive else None, + fix["measured_at"] if not passive else None, + depth_m=fix["depth_m"] if not passive else None, + observer_x=origin_x, observer_y=origin_y, + released_to_opz=True)) + self._opz_source_bindings[observation_id] = contact + return reports + + def _buoy_opz_observations(self, released_only=True) -> list[OPZObservation]: + reports = [] + for _, contact in sorted(self.sonar.contacts.items()): + if released_only and (not contact.helo_qualified + or not contact.buoy_released_to_opz): + continue + for seq, row in sorted(contact.buoy_reports.items()): + if not 0 <= self.sim_t - row["measured_at"] < config.SONAR_CONTACT_LOST_S: + continue + observation_id = self._opz_observation_id( + f"sonar-buoy-{seq}", contact.target_id) + reports.append(OPZObservation( + observation_id, f"SONAR-BUOY-{seq:02d}-{row['mode']}", "UNKNOWN", + row["bearing"], row["range_nm"], row["x"], row["y"], + None, row["quality"], row["measured_at"], + self.opz_track_label(observation_id, f"B{seq:02d} K{contact.id:02d}"), + contact.player_class, row["bearing_uncertainty_deg"], + row["measured_at"] if row["x"] is not None else None, + observer_x=row["observer_x"], observer_y=row["observer_y"], + released_to_opz=bool(contact.helo_qualified + and contact.buoy_released_to_opz))) + self._opz_source_bindings[observation_id] = contact + return reports + + def opz_source_observations(self) -> tuple[OPZObservation, ...]: + if id(self.world) != self._opz_world_identity: + self.opz_fusion.clear() + self.opz_track_labels.clear() + self.opz_selected_track_id = None + self._opz_world_identity = id(self.world) + observations = self._detached_air_observations() + observations.extend(self._sonar_opz_observations(True)) + observations.extend(self._helicopter_opz_observations()) + observations.extend(self._buoy_opz_observations()) + return tuple(sorted(observations, key=lambda item: item.observation_id)) + + def opz_published_observations(self) -> tuple[OPZObservation, ...]: + """Shared OPZ picture, unaffected by host-local suppression.""" + observations = self.opz_source_observations() + self.opz_fusion.prune(observations) + fused = [self.opz_fusion.computed(item, observations, self.sim_t, + self.air_picture.stale_s) + for item in self.opz_fusion.fusions.values()] + fused = [replace(item, label=self.opz_track_label( + item.observation_id, item.label)) for item in fused if item is not None] + return tuple(sorted((*observations, *(item for item in fused if item is not None)), + key=lambda item: item.observation_id)) + + def asm_tracks(self) -> list: + return [t for t in self.air_picture.tracks(self.sim_t, ("ASM",)) + if t.source in ("RADAR", "RADAR-L", "HOJ", "DATALINK")] + + def opz_tracks(self) -> list: + """Host-visible OPZ reports, with local suppression applied.""" + observations = self.opz_source_observations() + visible = self.opz_fusion.visible(observations, self.sim_t, + self.air_picture.stale_s) + return [replace(item, label=self.opz_track_label( + item.observation_id, item.label)) for item in visible] + + def filtered_opz_tracks(self) -> list: + """Presentation-only OPZ register filter; never alters observations.""" + tracks = self.opz_tracks() + selected = getattr(self, "opz_contact_filter", "ALL") + if selected == "ALL": + return tracks + if selected in ("RADAR", "SONAR"): + return [track for track in tracks + if track.source.startswith(selected)] + if selected == "ESM": + return [track for track in tracks if track.source == "ESM"] + kind_domains = { + "AIS": "SURFACE", "SURFACE": "SURFACE", "SUB": "SUBSURFACE", + "TORP": "SUBSURFACE", "FLG": "AIR", "ASM": "AIR", + } + # Sonar reports carry no sensor domain; the operator's classification + # (an annotation, not truth) sorts them into the display filter. + class_domains = { + "U_BOOT": "SUBSURFACE", "TORPEDO": "SUBSURFACE", + "KAMPFSCHIFF": "SURFACE", "FAHRZEUG": "SURFACE", "FLUGZEUG": "AIR", + } + return [track for track in tracks + if kind_domains.get(track.kind, class_domains.get( + track.classification, "UNKNOWN")) == selected] + + def _cycle_opz_contact_filter(self) -> None: + filters = ("ALL", "RADAR", "SONAR", "ESM", "AIR", "SURFACE", + "SUBSURFACE") + current = getattr(self, "opz_contact_filter", "ALL") + index = filters.index(current) if current in filters else 0 + self.opz_contact_filter = filters[(index + 1) % len(filters)] + tracks = self.filtered_opz_tracks() + if not any(track.track_id == self.opz_selected_track_id + for track in tracks): + self.opz_selected_track_id = tracks[0].track_id if tracks else None + self.flash(message( + "runtime.cic.filter", + filter=display_value("contact_filter", self.opz_contact_filter, + self.tr)), 1.5) + + # --- Shared operator plot layer ---------------------------------------- + + PLOT_TOOL_KEYS = {pygame.K_m: "mark", pygame.K_r: "ruler", + pygame.K_b: "bearing", pygame.K_c: "circle", + pygame.K_d: "dr"} + PLOT_CURSOR_STEP_PX = 6 + PLOT_CURSOR_STEP_FAST_PX = 40 + PLOT_PICK_PX = 12 + + def _reset_plot_ui(self) -> None: + """Transient plot-mode state; the drawing itself lives in ``plot``.""" + self.plot_mode = False + self.plot_tool = "mark" + self.plot_cursor = (0.0, 0.0) + self.plot_anchor = None + self._plot_dr_pending = None + + # ``layer`` selects another crew's plot (the crewed submarine's own); + # by default the frigate crew's shared plot. + def plot_add(self, kind, x, y, label="", *, layer=None, **fields): + """Add one crew drawing at sim time now; returns its id or an error.""" + if kind not in plot_geometry.KINDS: + return "invalid_value" + target = self.plot if layer is None else layer + return target.add({"kind": kind, "label": label, + "t": float(self.sim_t), "x": x, "y": y, **fields}) + + def plot_remove(self, object_id, *, layer=None): + return True if (self.plot if layer is None else layer).remove(object_id) else "stale_ref" + + def plot_clear(self, *, layer=None): + (self.plot if layer is None else layer).clear() + return True + + def plot_relabel(self, object_id, label, *, layer=None): + if not plot_geometry.valid_label(label): + return "invalid_value" + return True if (self.plot if layer is None else layer).relabel(object_id, label) else "stale_ref" + + def _plot_view(self): + """The chart camera of the current station, or None without a chart.""" + if self.station is Station.OPZ: + self._configure_opz_map_view() + return self.opz_map_view + if self._map_station_visible(): + self.map_view.set_rect(config.MAP_RECT) + return self.map_view + return None + + def toggle_plot_mode(self): + if self.plot_mode: + self._reset_plot_ui() + self.flash(message("plot.flash.off"), 1.5) + return False + if self._plot_view() is None: + self.flash(message("plot.flash.no_chart"), 2.0) + return None + self._clear_station_input() + self.plot_mode = True + self.plot_anchor = None + self.plot_cursor = (self.ship.x, self.ship.y) + self.flash(message("plot.flash.on"), 2.0) + return True + + def _plot_flash_result(self, result) -> None: + if isinstance(result, str): + self.flash(message("plot.flash.full" if result == "full" + else "plot.flash.invalid"), 2.0) + else: + item = next((obj for obj in self.plot.objects if obj["id"] == result), None) + if item is not None: + self.flash(message("plot.flash.added", label=item["label"]), 1.5) + + def _plot_commit_point(self, x=None, y=None) -> None: + """Enter/click: place the cursor point for the active tool.""" + if x is not None: + self.plot_cursor = (x, y) + cx, cy = self.plot_cursor + tool = self.plot_tool + if tool == "mark": + self._plot_flash_result(self.plot_add("mark", cx, cy)) + return + if tool == "bearing": + brg, dist = plot_geometry.bearing_distance(self.ship.x, self.ship.y, cx, cy) + result = (self.plot_add("bearing", self.ship.x, self.ship.y, + bearing=round(brg, 1) % 360.0) + if dist > 0.0 else "invalid_value") + self._plot_flash_result(result) + return + if self.plot_anchor is None: + self.plot_anchor = (cx, cy) + self.flash(message("plot.flash.second_point"), 2.0) + return + ax, ay = self.plot_anchor + self.plot_anchor = None + brg, dist = plot_geometry.bearing_distance(ax, ay, cx, cy) + if tool == "ruler": + result = self.plot_add("ruler", ax, ay, x2=cx, y2=cy) + elif tool == "circle": + result = self.plot_add("circle", ax, ay, radius_nm=round(dist, 2)) + else: + if dist <= 0.0: + self._plot_flash_result("invalid_value") + return + self._plot_dr_pending = (ax, ay, round(brg, 1) % 360.0) + self._begin_numeric_input("plot_speed") + return + self._plot_flash_result(result) + + def selected_opz_track(self): + return next((track for track in self.opz_tracks() + if track.track_id == self.opz_selected_track_id), None) + + def designate_opz_track(self) -> None: + """Hand an observed CIC track to weapons without exposing world truth.""" + track = self.selected_opz_track() + if track is None: + self.flash(message("runtime.cic.none")) + return + result = self.designate_opz_observation(track.observation_id) + if result is not True: + ambiguous = (track.source == "FUSION" + and len(self._fusion_contacts(track)) > 1) + self.flash(message("runtime.cic.fusion_ambiguous" if ambiguous + else "runtime.cic.no_solution")) + return + self.selected_contact = self.target + self.flash(message("runtime.cic.designated", track=track.track_id)) + + def designate_opz_observation(self, observation_id: str): + if self.damage.station_down("opz"): + return "opz_down" + track = next((item for item in self.opz_published_observations() + if item.observation_id == observation_id), None) + if track is None: + return "stale_ref" + if track.source == "FUSION": + # A fusion hands over its sonar report only when that is unique. + contacts = self._fusion_contacts(track) + contact = contacts[0] if len(contacts) == 1 else None + else: + bound = self._opz_source_bindings.get(track.observation_id) + contact = (bound if isinstance(bound, Contact) else + next((c for c in self.sonar.contacts.values() + if getattr(bound, "target_id", None) == c.target_id), + None)) + if (contact is None or self.sonar.contacts.get(contact.target_id) is not contact + or not 0 <= self.sim_t - contact.last_seen + < config.SONAR_CONTACT_LOST_S): + return "no_solution" + self.target = contact + return True + + def _fusion_contacts(self, track) -> list: + """Distinct sonar contacts behind the member reports of one fusion.""" + contacts = [] + for member in getattr(track, "members", ()): + bound = self._opz_source_bindings.get(member) + if isinstance(bound, Contact) and not any( + item is bound for item in contacts): + contacts.append(bound) + return contacts + + def opz_affiliation(self, track_id: str) -> str: + if track_id not in self.opz_affiliations: + source_key = getattr(self._opz_source_bindings.get(track_id), + "track_id", None) + bound = self._opz_source_bindings.get(track_id) + if isinstance(bound, Contact): + legacy_key = f"U-{bound.target_id}" + if legacy_key in self.opz_affiliations: + track_id = legacy_key + if source_key in self.opz_affiliations: + track_id = source_key + else: + opaque = next((key for key, source in self._opz_source_bindings.items() + if getattr(source, "track_id", None) == track_id), None) + if opaque is not None: + track_id = opaque + value = self.opz_fusion.fusion_affiliations.get( + track_id, self.opz_affiliations.get(track_id, "UNKNOWN")) + return value if value in config.NATO_AFFILIATIONS else "UNKNOWN" + + def opz_source_classification(self, observation_id: str) -> str | None: + return source_classification(observation_id, + self.opz_published_observations()) + + def classify_sonar_contact(self, contact, classification): + if self._sonar_down(): + return "sonar_down" + if classification is not None and classification not in config.PLAYER_CLASSES: + return "invalid_value" + if (not isinstance(contact, Contact) + or self.sonar.contacts.get(contact.target_id) is not contact): + return "stale_ref" + if not 0 <= self.sim_t - contact.last_seen < config.SONAR_CONTACT_LOST_S: + return "stale_ref" + contact.player_class = classification + return True + + def release_sonar_contact(self, contact, released: bool, *, source="sonar"): + if type(released) is not bool: + return "invalid_value" + if source not in ("sonar", "helicopter", "buoy"): + return "invalid_value" + if self.damage.station_down("sonar"): + return "sonar_down" + if (not isinstance(contact, Contact) + or self.sonar.contacts.get(contact.target_id) is not contact + or not 0 <= self.sim_t - contact.last_seen + < config.SONAR_CONTACT_LOST_S): + return "stale_ref" + if source == "helicopter": + dip_current = (contact.dip_last_seen is not None + and 0 <= self.sim_t - contact.dip_last_seen + < config.SONAR_CONTACT_LOST_S) + dip_fix = any(fix["source"] == "DIPPING" + for fix in contact.active_fixes(self.sim_t)) + if not dip_current and not dip_fix: + return "stale_ref" + if released and not contact.helo_qualified: + return "not_qualified" + contact.dip_released_to_opz = released + elif source == "buoy": + if not any(0 <= self.sim_t - row["measured_at"] < config.SONAR_CONTACT_LOST_S + for row in contact.buoy_reports.values()): + return "stale_ref" + if released and not contact.helo_qualified: + return "not_qualified" + contact.buoy_released_to_opz = released + else: + contact.released_to_opz = released + return True + + def qualify_helicopter_contact(self, contact, qualified: bool): + if type(qualified) is not bool: + return "invalid_value" + if self.damage.station_down("sonar"): + return "sonar_down" + if (not isinstance(contact, Contact) + or self.sonar.contacts.get(contact.target_id) is not contact + or not 0 <= self.sim_t - contact.last_seen < config.SONAR_CONTACT_LOST_S): + return "stale_ref" + if not (any(0 <= self.sim_t - row["measured_at"] + < config.SONAR_CONTACT_LOST_S + for row in contact.buoy_reports.values()) + or contact.dip_last_seen is not None + and 0 <= self.sim_t - contact.dip_last_seen + < config.SONAR_CONTACT_LOST_S + or any(fix["source"] == "DIPPING" + for fix in contact.active_fixes(self.sim_t))): + return "stale_ref" + contact.helo_qualified = qualified + if not qualified: + contact.dip_released_to_opz = False + contact.buoy_released_to_opz = False + return True + + def classify_opz_observation(self, observation_id: str, classification): + if self.damage.station_down("opz"): + return "opz_down" + if classification is not None and classification not in config.PLAYER_CLASSES: + return "invalid_value" + track = next((item for item in self.opz_published_observations() + if item.observation_id == observation_id), None) + if track is None: + return "stale_ref" + if track.source.startswith("SONAR"): + # A sonar-origin contact is classified on the contact itself + # (shared with the Sonar/Helicopter stations), not in the OPZ + # fusion overlay used for radar-only tracks. + contact = self._opz_source_bindings.get(observation_id) + if (not isinstance(contact, Contact) + or self.sonar.contacts.get(contact.target_id) is not contact): + return "stale_ref" + return self.classify_sonar_contact(contact, classification) + if not (track.source.startswith("RADAR") + or track.source in ("HOJ", "FUSION")): + return "source_owned" + if classification is None: + self.opz_fusion.classifications.pop(observation_id, None) + else: + self.opz_fusion.classifications[observation_id] = classification + return True + + def affiliate_opz_observation(self, observation_id: str, affiliation: str): + if self.damage.station_down("opz"): + return "opz_down" + if affiliation not in config.NATO_AFFILIATIONS: + return "invalid_value" + track = next((item for item in self.opz_published_observations() + if item.observation_id == observation_id), None) + if track is None: + return "stale_ref" + destination = (self.opz_fusion.fusion_affiliations + if track.source == "FUSION" else self.opz_affiliations) + destination[observation_id] = affiliation + self._sync_live_engagement_hold(observation_id, track.track_id, affiliation) + return True + + def _live_aircraft_icao_for_track_id(self, track_id) -> str | None: + """Resolve an air-picture 'A-' track id to its live ADS-B icao24, + if that id happens to be bound to a real LiveAircraft rather than a + simulated Flight (both intentionally share the same id namespace).""" + if not isinstance(track_id, str) or not track_id.startswith("A-"): + return None + try: + seq = int(track_id[2:]) + except ValueError: + return None + return next((icao24 for icao24, aircraft in self.live_traffic.aircraft.items() + if aircraft.seq == seq), None) + + def _sync_live_engagement_hold(self, observation_id: str, display_id: str, + affiliation: str) -> None: + """Real ADS-B traffic is indistinguishable from a simulated contact, + so a manual HOSTILE call on it is a possible political incident, not + a weapons release. Any prior engagement confirmation is revoked here + and must be freshly re-affirmed (confirm_live_engagement) every time + the classification turns HOSTILE again.""" + bound = self._opz_source_bindings.get(observation_id) + icao24 = self._live_aircraft_icao_for_track_id(getattr(bound, "track_id", None)) + if icao24 is None: + return + self.live_engage_authorized.discard(icao24) + if affiliation == "HOSTILE": + self.live_engage_confirm_pending = icao24 + self.flash(message("runtime.cic.hostile_confirm_required", + track=display_id), 5.0) + self.feed.add(self.world.format_time(), "opz", + message("runtime.cic.hostile_confirm_required", + track=display_id)) + elif self.live_engage_confirm_pending == icao24: + self.live_engage_confirm_pending = None + + def live_engagement_pending_for_observation(self, observation_id: str) -> bool: + """Whether this OPZ observation is the live contact currently + awaiting an attack confirmation (see _sync_live_engagement_hold).""" + if self.live_engage_confirm_pending is None: + return False + bound = self._opz_source_bindings.get(observation_id) + icao24 = self._live_aircraft_icao_for_track_id(getattr(bound, "track_id", None)) + return icao24 == self.live_engage_confirm_pending + + def confirm_live_engagement(self) -> bool: + """OPZ 'Enter': explicit player affirmation to fire on the live, + real-world contact currently awaiting confirmation after being + classified HOSTILE. See _sync_live_engagement_hold.""" + icao24 = self.live_engage_confirm_pending + if icao24 is None or icao24 not in self.live_traffic.aircraft: + return False + self.live_engage_authorized.add(icao24) + self.live_engage_confirm_pending = None + self.flash(message("runtime.cic.hostile_confirmed"), 2.5) + self.feed.add(self.world.format_time(), "opz", + message("runtime.cic.hostile_confirmed")) + return True + + def create_opz_fusion(self, observation_ids): + if self.damage.station_down("opz"): + return "opz_down" + if (type(observation_ids) not in (list, tuple) + or not config.OPZ_FUSION_MEMBER_MIN <= len(observation_ids) + <= config.OPZ_FUSION_MEMBER_MAX + or len(set(observation_ids)) != len(observation_ids)): + return "invalid_value" + sources = self.opz_source_observations() + current = {item.observation_id for item in sources} + if any(key not in current for key in observation_ids): + return "stale_ref" + self.opz_fusion.marked = set(observation_ids) + fusion = self.opz_fusion.create(sources) + if fusion is None: + return "fusion_rejected" + self.opz_selected_track_id = fusion.fusion_id + return True + + def dissolve_opz_fusion(self, observation_id: str): + if self.damage.station_down("opz"): + return "opz_down" + if observation_id not in self.opz_fusion.fusions: + return "stale_ref" + self.opz_fusion.dissolve(observation_id) + if self.opz_selected_track_id == observation_id: + self.opz_selected_track_id = None + return True + + def _cycle_opz_track(self, delta: int) -> None: + tracks = self.filtered_opz_tracks() + if not tracks: + self.opz_selected_track_id = None + return + ids = [track.track_id for track in tracks] + try: + index = ids.index(self.opz_selected_track_id) + except ValueError: + index = -1 if delta > 0 else 0 + self.opz_selected_track_id = ids[(index + delta) % len(ids)] + + def _cycle_opz_affiliation(self) -> None: + track = self.selected_opz_track() + if track is None: + self.flash(message("runtime.cic.none_select")) + return + current = self.opz_affiliation(track.track_id) + order = config.NATO_AFFILIATIONS + value = order[(order.index(current) + 1) % len(order)] + if self.affiliate_opz_observation(track.track_id, value) is not True: + return + self.flash(message("runtime.cic.affiliation", track=track.track_id, + affiliation=display_value("affiliation", value, self.tr)), 2.0) + + def _cycle_opz_classification(self) -> None: + track = self.selected_opz_track() + if track is None: + self.flash(message("runtime.cic.none_select")) + return + if track.source.startswith("SONAR"): + contact = self._opz_source_bindings.get(track.observation_id) + if not isinstance(contact, Contact): + self.flash(message("runtime.cic.source_owned")) + return + current = contact.player_class + elif (track.source.startswith("RADAR") + or track.source in ("HOJ", "FUSION")): + current = self.opz_fusion.classifications.get(track.observation_id) + else: + self.flash(message("runtime.cic.source_owned")) + return + order = (None, *config.PLAYER_CLASSES) + value = order[(order.index(current) + 1) % len(order)] + self.classify_opz_observation(track.observation_id, value) + + def _toggle_opz_mark(self) -> None: + track = self.selected_opz_track() + if track is None or track.source == "FUSION": + return + if track.observation_id in self.opz_fusion.marked: + self.opz_fusion.marked.remove(track.observation_id) + else: + self.opz_fusion.marked.add(track.observation_id) + + def _create_opz_fusion(self) -> None: + result = self.create_opz_fusion(tuple(self.opz_fusion.marked)) + if result is not True: + self.flash(message("runtime.cic.fusion_rejected")) + + def _dissolve_opz_fusion(self) -> None: + if self.opz_selected_track_id: + self.dissolve_opz_fusion(self.opz_selected_track_id) + + def _toggle_opz_suppression(self) -> None: + track = self.selected_opz_track() + if track is None: + return + key = track.observation_id + if key in self.opz_fusion.suppressed: + self.opz_fusion.suppressed.remove(key) + else: + self.opz_fusion.suppressed.add(key) + + def eloka_tracks(self) -> tuple: + """Return detached passive intercepts in stable picture order.""" + return self.esm_picture.tracks(self.sim_t) + + def eloka_visible_tracks(self) -> tuple: + """Return the one filtered/sorted list used by ELOKA presentation.""" + return filter_and_sort_tracks( + self.eloka_tracks(), self.sim_t, self.eloka_display_analysis, + status=self.eloka_status_filter, + minimum_threat=self.eloka_threat_filter, + band=self.eloka_band_filter, + annotated_keys=self.eloka_annotations, + jamming_keys=(channel.track_key + for channel in self.ecm_jammer.channels)) + + def _reconcile_eloka_selection(self) -> None: + visible = self.eloka_visible_tracks() + keys = {track.track_key for track in visible} + if self.eloka_selected_track_key not in keys: + self.eloka_selected_track_key = (visible[0].track_key + if visible else None) + + def _cycle_eloka_filter(self, kind: str) -> None: + names = { + "status": ("eloka_status_filter", + ("OPERATIONAL", "LIVE", "MEMORY", "ALL")), + "threat": ("eloka_threat_filter", + ("ALL", "LOW", "MEDIUM", "HIGH", "CRITICAL")), + "band": ("eloka_band_filter", + ("ALL", "A_C", "D", "E_F", "G_H", "I_J", "K")), + } + attribute, values = names[kind] + current = getattr(self, attribute) + setattr(self, attribute, values[(values.index(current) + 1) % len(values)]) + self._reconcile_eloka_selection() + + def selected_eloka_track(self): + return next((track for track in self.eloka_tracks() + if track.track_key == self.eloka_selected_track_key), None) + + def _cycle_eloka_track(self, delta: int) -> None: + if self.damage.station_down("opz"): + return + tracks = self.eloka_visible_tracks() + if not tracks: + self.eloka_selected_track_key = None + return + keys = [track.track_key for track in tracks] + try: + index = keys.index(self.eloka_selected_track_key) + except ValueError: + index = -1 if delta > 0 else 0 + self.eloka_selected_track_key = keys[(index + delta) % len(keys)] + + def eloka_candidates(self, track=None) -> tuple: + if self.damage.station_down("opz"): + return () + track = track or self.selected_eloka_track() + return (() if track is None else + rank_emitters(track, self.runtime_catalog.emitters)) + + def eloka_display_candidates(self, track=None) -> tuple: + """Emitter choices shown to the operator: ranked with scores only as + a training aid; otherwise an unranked library range lookup.""" + if self.operator_assist(): + return self.eloka_candidates(track) + if self.damage.station_down("opz"): + return () + track = track or self.selected_eloka_track() + return (() if track is None else + library_emitters(track, self.runtime_catalog.emitters)) + + def eloka_display_analysis(self, track=None): + """Radar type/threat inferred from the catalog: training aid only.""" + return self.eloka_analysis(track) if self.operator_assist() else None + + def eloka_display_range(self, track): + return self.eloka_range_estimate(track) if self.operator_assist() else None + + ELOKA_ANALYSIS_CACHE_MAX = 256 + + def eloka_analysis(self, track=None): + track = track or self.selected_eloka_track() + if track is None: + return None + # The ranking depends only on the measured fingerprint and the + # immutable runtime catalog; memoize it (bounded, never saved). + emitters = self.runtime_catalog.emitters + if self.__dict__.get("_eloka_analysis_owner") is not emitters: + self._eloka_analysis_owner = emitters + self._eloka_analysis_cache = {} + key = (track.frequency_hz, track.prf_hz, track.modulation_code) + cache = self._eloka_analysis_cache + result = cache.get(key) + if result is None: + if len(cache) >= self.ELOKA_ANALYSIS_CACHE_MAX: + cache.clear() + result = cache[key] = analyze_signal(track, emitters) + return result + + def eloka_range_estimate(self, track=None) -> float | None: + """Range implied by the intercept's peak level, assuming the power + class of the best-ranked catalog hypothesis (never emitter truth).""" + track = track or self.selected_eloka_track() + analysis = self.eloka_analysis(track) + if analysis is None or not analysis.candidates or track.signal_db <= 0.0: + return None + emitter = self.runtime_catalog.emitters.get( + analysis.candidates[0].emitter_key) + return estimated_range_nm(track, getattr(emitter, "power_class", "medium")) + + def deploy_jamming(self, track, technique=None): + if self.damage.station_down("opz"): + return "opz_down" + if track is None or not any(item is track for item in self.eloka_tracks()): + return "stale_ref" + return self.ecm_jammer.deploy_jamming( + track, self.sim_t, technique=technique) + + def set_jamming_technique(self, track, technique: str): + if self.damage.station_down("opz"): + return "opz_down" + if track is None or not any(item is track for item in self.eloka_tracks()): + return "stale_ref" + return self.ecm_jammer.set_technique(track, technique, self.sim_t) + + def _cycle_jamming_technique(self, track) -> str | None: + if track is None: + return None + channel = next((item for item in self.ecm_jammer.channels + if item.track_key == track.track_key), None) + current = (channel.technique if channel is not None else + self.ecm_jammer.recommended_technique(track)) + index = ECM_TECHNIQUES.index(current) + technique = ECM_TECHNIQUES[(index + 1) % len(ECM_TECHNIQUES)] + return (technique if self.set_jamming_technique(track, technique) is True + else None) + + def set_jamming(self, track, enabled: bool): + if type(enabled) is not bool: + return "invalid" + active = (track is not None and any( + channel.track_key == track.track_key + for channel in self.ecm_jammer.channels)) + if active == enabled: + return True + return self.deploy_jamming(track) + + def set_ecm_auto(self, enabled: bool): + if type(enabled) is not bool: + return "invalid" + if self.damage.station_down("opz"): + return "opz_down" + self.ecm_jammer.auto_enabled = enabled + if not enabled: + self.ecm_jammer.channels = [channel for channel in + self.ecm_jammer.channels if not channel.automatic] + return True + + def eloka_annotation(self, track_key: str) -> str | None: + emitter_key = self.eloka_annotations.get(track_key) + emitter = self.runtime_catalog.emitters.get(emitter_key) + return emitter_key if emitter is not None and emitter.domain == "radar" else None + + def eloka_emitter_name(self, emitter_key: str | None) -> str | None: + """Display name of the platform owning an ESM emitter, or None.""" + if not isinstance(emitter_key, str): + return None + return self.runtime_catalog.emitter_name(emitter_key) + + def eloka_annotation_name(self, track_key: str) -> str | None: + """Operator annotation resolved to the owning platform's name.""" + return self.eloka_emitter_name(self.eloka_annotation(track_key)) + + def annotate_eloka_intercept(self, track, emitter_key: str): + if self.damage.station_down("opz"): + return "opz_down" + if not any(item is track for item in self.eloka_tracks()): + return "stale_ref" + candidates = {item.emitter_key for item in rank_emitters( + track, self.runtime_catalog.emitters, + maximum=len(self.runtime_catalog.emitters))} + if type(emitter_key) is not str or emitter_key not in candidates: + return "stale_ref" + previous = self.eloka_annotation(track.track_key) + if previous is not None and previous != emitter_key: + self._remove_released_esm(track.track_key, previous) + self.eloka_annotations[track.track_key] = emitter_key + while len(self.eloka_annotations) > ESM_MAX_ANNOTATIONS: + del self.eloka_annotations[min(self.eloka_annotations)] + self._publish_released_esm() + return True + + def clear_eloka_annotation(self, track): + if self.damage.station_down("opz"): + return "opz_down" + if not any(item is track for item in self.eloka_tracks()): + return "stale_ref" + previous = self.eloka_annotation(track.track_key) + self.eloka_annotations.pop(track.track_key, None) + if previous is not None: + self._remove_released_esm(track.track_key, previous) + self._publish_released_esm() + return True + + def _remove_released_esm(self, track_key: str, emitter_key: str) -> None: + identity = self._observation_key( + "esm-release", f"{track_key}:{emitter_key}") + self.air_picture._tracks.pop(f"E-{identity}", None) + + def _cycle_eloka_annotation(self) -> None: + if self.damage.station_down("opz"): + self.flash(message("runtime.eloka.disabled")) + return + track = self.selected_eloka_track() + if track is None: + self.flash(message("runtime.eloka.none_select")) + return + # Training: likeliest first. Otherwise the library range lookup in + # name order, so the first press does not reveal the best match. + choices = ([candidate.emitter_key for candidate in rank_emitters( + track, self.runtime_catalog.emitters, + maximum=len(self.runtime_catalog.emitters))] + if self.operator_assist() else sorted( + (candidate.emitter_key for candidate in library_emitters( + track, self.runtime_catalog.emitters, + maximum=len(self.runtime_catalog.emitters))), + key=lambda key: (str(self.eloka_emitter_name(key) or key), key))) + current = self.eloka_annotation(track.track_key) + index = choices.index(current) if current in choices else -1 + if index + 1 >= len(choices): + self.clear_eloka_annotation(track) + assignment = self.tr("common.unknown") + else: + key = choices[index + 1] + self.annotate_eloka_intercept(track, key) + assignment = self.eloka_emitter_name(key) or key + self.flash(message("runtime.eloka.annotation", + track=track.track_key, assignment=assignment), 2.0) + + def _publish_released_esm(self) -> None: + """Release only operator-classified, bearing-only ESM observations.""" + for track in self.eloka_tracks(): + emitter_key = self.eloka_annotation(track.track_key) + label = self.eloka_emitter_name(emitter_key) + if emitter_key is None or label is None: + continue + identity = self._observation_key( + "esm-release", f"{track.track_key}:{emitter_key}") + self.air_picture.observe( + track_id=f"E-{identity}", kind="UNKNOWN", target_id=0, + source="ESM", bearing=track.bearing, range_nm=None, + observer_x=track.observer_x, observer_y=track.observer_y, + course=None, quality=track.quality, now=track.last_seen, + label=label, hostile=False, + bearing_uncertainty_deg=track.bearing_uncertainty_deg) + + def released_esm_labels(self) -> dict[str, str]: + """Return detached operator-approved labels keyed by public track ID.""" + released = {} + for track in self.eloka_tracks(): + emitter_key = self.eloka_annotation(track.track_key) + label = self.eloka_emitter_name(emitter_key) + if emitter_key is not None and label is not None: + identity = self._observation_key( + "esm-release", f"{track.track_key}:{emitter_key}") + released[f"E-{identity}"] = label + return released + + def eloka_correlations(self, track=None) -> tuple: + """Compare ESM and public radar evidence without target identity.""" + if self.damage.station_down("opz"): + return () + track = track or self.selected_eloka_track() + if track is None: + return () + raw_evidence = [] + for observed in self.air_picture._tracks.values(): + if (not isinstance(observed.source, str) + or not observed.source.startswith("RADAR") + or "AIS" in observed.source.upper()): + continue + values = (observed.bearing, observed.last_seen) + optional = (observed.bearing_uncertainty_deg, observed.x, + observed.y, observed.position_seen) + if (not all(isinstance(value, (int, float)) + and not isinstance(value, bool) and math.isfinite(value) + for value in values) + or any(value is not None and ( + not isinstance(value, (int, float)) + or isinstance(value, bool) or not math.isfinite(value)) + for value in optional) + or (observed.x is None) != (observed.y is None) + or not 0.0 <= observed.bearing < 360.0): + continue + observed_at = (observed.position_seen if observed.x is not None + and observed.position_seen is not None + else observed.last_seen) + if not 0.0 <= observed_at <= self.sim_t \ + or self.sim_t - observed_at > 30.0: + continue + raw_evidence.append((observed.source, observed.bearing, + observed.bearing_uncertainty_deg, + observed.x, observed.y, observed_at)) + evidence = [] + evidence_order = lambda row: ( + row[0], row[1], -1.0 if row[2] is None else row[2], + 0 if row[3] is None else 1, + 0.0 if row[3] is None else row[3], + 0.0 if row[4] is None else row[4], row[5]) + used_keys = set() + for values in sorted(raw_evidence, key=evidence_order): + source, bearing, uncertainty, x, y, observed_at = values + digest = hashlib.blake2b(repr(values).encode("utf-8"), + digest_size=5).hexdigest().upper() + track_id = f"OBS-{digest}" + suffix = 2 + while track_id in used_keys: + track_id = f"OBS-{digest}-{suffix}" + suffix += 1 + used_keys.add(track_id) + evidence.append(ESMCorrelationEvidence( + track_id=track_id, source=source, bearing=bearing, + bearing_uncertainty_deg=uncertainty, x=x, y=y, + observed_at=observed_at)) + return correlate_observations(track, evidence, self.sim_t) + + def atmosphere(self) -> dict: + """Own-ship atmosphere (barometer, thermometer, wind, sky), derived + from the weather system; observation-safe (no future values).""" + world = self.world + weather = world.weather_values() + kind = world.weather_kind() + source_sea, target_sea, elapsed = world.weather_epoch() + pressure, tendency = atmosphere_physics.barometer( + self.seed, source_sea, target_sea, elapsed) + trend = atmosphere_physics.pressure_trend(tendency) + rain = weather["rain_intensity"] + wind = weather["wind_speed_kn"] + sst = world.ocean.sea_surface_temperature_c(world.hour) + cloud = atmosphere_physics.cloud_cover(kind, rain) + air = atmosphere_physics.air_temperature_c( + sst, world.ocean.day_of_year, world.hour, weather["wind_from_deg"], + wind, cloud) + precipitation = atmosphere_physics.precipitation(rain, air) + latitude = world.latitude_deg() + latitude = (atmosphere_physics.DEFAULT_LATITUDE_DEG if latitude is None + else latitude) + sun = atmosphere_physics.sun_elevation_deg( + latitude, world.ocean.day_of_year, world.hour) + lunar_age = self.lunar_age_days() + return dict( + weather=("snow" if precipitation == "snow" else kind), + precipitation=precipitation, rain_intensity=rain, + visibility_nm=weather["visibility_nm"], + sea_state=int(round(weather["sea_state"])), + wind_from_deg=weather["wind_from_deg"], wind_kn=wind, + gust_kn=atmosphere_physics.gust_kn(wind, weather["sea_state"]), + beaufort=atmosphere_physics.beaufort(wind), + pressure_hpa=pressure, pressure_tendency_hpa_3h=tendency, + pressure_trend=trend, + storm_warning=atmosphere_physics.storm_warning(pressure, trend), + air_temp_c=air, sea_temp_c=sst, cloud_cover=cloud, + ceiling_ft=atmosphere_physics.cloud_ceiling_ft( + kind, rain, weather["visibility_nm"]), + icing=atmosphere_physics.icing(air, precipitation, wind), + sun_elevation_deg=sun, + daylight=atmosphere_physics.daylight(sun), + moon_phase=atmosphere_physics.moon_phase(lunar_age), + moon_illumination=visual_physics.moon_illumination(lunar_age), + time=world.format_time()) + + def helicopter_weather(self) -> dict: + """Return one shared, observation-safe flight-weather decision.""" + weather = self.world.weather_values() + atmosphere = self.atmosphere() + relative = math.radians(config.angle_diff_deg( + weather["wind_from_deg"], self.ship.course)) + crosswind = abs(weather["wind_speed_kn"] * math.sin(relative)) + launch_safe = ( + weather["wind_speed_kn"] <= config.HELO_LAUNCH_WIND_MAX_KN + and crosswind <= config.HELO_LAUNCH_CROSSWIND_MAX_KN + and weather["visibility_nm"] >= config.HELO_LAUNCH_VISIBILITY_MIN_NM + and weather["sea_state"] <= config.HELO_LAUNCH_SEA_STATE_MAX) + gust = atmosphere["gust_kn"] + ceiling = atmosphere["ceiling_ft"] + icing = atmosphere["icing"] + launch_weather = (launch_safe + and gust <= config.HELO_LAUNCH_GUST_MAX_KN + and (ceiling is None or ceiling >= config.HELO_CEILING_MIN_FT) + and icing != "severe") + # Launch and recovery also need a deck-motion window (own ship). + deck_safe = helicopter_physics.deck_within_limits(self.ship.roll, self.ship.pitch) + launch_safe = launch_weather and deck_safe + dipping_safe = ( + weather["wind_speed_kn"] <= config.HELO_DIP_WIND_MAX_KN + and weather["visibility_nm"] >= config.HELO_DIP_VISIBILITY_MIN_NM + and weather["sea_state"] <= config.HELO_DIP_SEA_STATE_MAX + # Winch and cable ice up: no dipping in icing conditions. + and icing == "none") + # Flight-weather category: NO-GO outside the launch weather limits, + # LIMITED near a limit (80 %) or in light icing, else CLEAR. + margins = ( + weather["wind_speed_kn"] / config.HELO_LAUNCH_WIND_MAX_KN, + gust / config.HELO_LAUNCH_GUST_MAX_KN, + crosswind / config.HELO_LAUNCH_CROSSWIND_MAX_KN, + weather["sea_state"] / config.HELO_LAUNCH_SEA_STATE_MAX, + config.HELO_LAUNCH_VISIBILITY_MIN_NM / max(weather["visibility_nm"], 1e-3), + (0.0 if ceiling is None else config.HELO_CEILING_MIN_FT / max(ceiling, 1.0))) + status = ("no_go" if not launch_weather else + "limited" if icing != "none" or max(margins) >= 0.8 else "clear") + return dict(weather, crosswind_kn=crosswind, deck_safe=deck_safe, + launch_safe=launch_safe, dipping_safe=dipping_safe, + gust_kn=gust, ceiling_ft=ceiling, icing=icing, status=status) + + WEATHER_PROFILE_STALE_S = 1800.0 + WEATHER_PROFILE_STALE_NM = 10.0 + WEATHER_RAY_SOURCE_DEPTH_M = 5.0 # hull sonar + + def weather_station_data(self) -> dict: + """Observation-safe data for the weather & sonar analysis panel. + + Atmosphere and flight weather come from own-ship instruments. The + ocean profile - layer, sound-speed curve, shadow zone, SOFAR axis, + rays - exists only after the sonar has taken a bathythermograph + measurement, and is always that measurement (with its age), never + the modelled truth.""" + atmosphere = self.atmosphere() + flight = self.helicopter_weather() + effects = dict( + solar_heating=(atmosphere["daylight"] == "day" + and atmosphere["sun_elevation_deg"] >= 20.0 + and atmosphere["cloud_cover"] < 0.6), + wind_mixing=atmosphere["wind_kn"] >= ocean_physics.MLD_WIND_THRESHOLD_KN, + freshwater=atmosphere["precipitation"] != "none") + return dict( + atmosphere=atmosphere, effects=effects, + flight=dict( + status=flight["status"], launch_safe=flight["launch_safe"], + dipping_safe=flight["dipping_safe"], deck_safe=flight["deck_safe"], + wind_kn=flight["wind_speed_kn"], gust_kn=flight["gust_kn"], + crosswind_kn=flight["crosswind_kn"], + visibility_nm=flight["visibility_nm"], + ceiling_ft=flight["ceiling_ft"], icing=flight["icing"], + sea_state=int(round(flight["sea_state"])), + # A crewed boat's instruments never report the frigate's motion. + roll_deg=(self.ship.roll if self._sonar_ctx is self._frigate_sonar + else 0.0), + pitch_deg=(self.ship.pitch if self._sonar_ctx is self._frigate_sonar + else 0.0), + limits=dict( + wind_kn=config.HELO_LAUNCH_WIND_MAX_KN, + gust_kn=config.HELO_LAUNCH_GUST_MAX_KN, + crosswind_kn=config.HELO_LAUNCH_CROSSWIND_MAX_KN, + visibility_nm=config.HELO_LAUNCH_VISIBILITY_MIN_NM, + ceiling_ft=config.HELO_CEILING_MIN_FT, + sea_state=config.HELO_LAUNCH_SEA_STATE_MAX, + roll_deg=helicopter_physics.DECK_ROLL_LIMIT_DEG, + pitch_deg=helicopter_physics.DECK_PITCH_LIMIT_DEG)), + profile=self._weather_station_profile()) + + def _weather_station_profile(self) -> dict | None: + bt = self.sonar.bt_profile + if bt is None: + return None + age = max(0.0, self.sim_t - bt["t"]) + observer = self.sonar_observer + offset = math.hypot(observer.x - bt["x"], observer.y - bt["y"]) + # Wind of the measurement's sea-state band keeps the picture fixed + # for one measurement (a pure, cached function of it). + wind = ocean_physics.MLD_WIND_THRESHOLD_KN * bt["sea_state"] / 3.0 + picture = sonar_raytrace.ray_picture( + bt["depths_m"], bt["speeds_m_s"], bt["water_depth_m"], + self.WEATHER_RAY_SOURCE_DEPTH_M, self.world.seabed_at(bt["x"], bt["y"]), + wind, bt["thermocline_m"]) + dip = None + if (self._sonar_ctx is self._frigate_sonar and self.helo.airborne + and self.helo.dip_state != "STOWED"): + dip = ("below" if self.helo.dip_depth_m >= bt["thermocline_m"] + else "above") + return dict( + age_s=age, offset_nm=offset, + stale=(age > self.WEATHER_PROFILE_STALE_S + or offset > self.WEATHER_PROFILE_STALE_NM), + thermocline_m=bt["thermocline_m"], water_depth_m=bt["water_depth_m"], + depths_m=list(bt["depths_m"]), speeds_m_s=list(bt["speeds_m_s"]), + sofar_axis_m=ocean_physics.sofar_axis_m( + bt["depths_m"], bt["speeds_m_s"], bt["water_depth_m"]), + cz_bands_nm=[list(band) for band in bt["cz_bands_nm"]], + range_nm=picture["range_nm"], rays=picture["rays"], + depth_edges_m=picture["depth_edges_m"], shadow=picture["shadow"], + dip_relative_to_layer=dip) + + def lookout_report_text(self, report: dict): + """Localizable report line: 'Bridge lookout: frigate bearing 040, 3.8 NM'.""" + return message("lookout.report", what=self.lookout_report_what(report), + bearing=f"{report['bearing']:03.0f}", + range=f"{report['range_nm']:.1f}") + + def lookout_report_what(self, report: dict): + if report["code"] is None: + return message(f"lookout.detect.{report['kind'].lower()}") + what = message(f"lookout.class.{report['code'].lower()}") + if report["type_name"]: + what = message("lookout.with_type", what=what, + type=raw_text(report["type_name"])) + return what + + def lookout_visual_what(self, label): + """What the lookout reported for a visual track label, or None.""" + _level, code, type_key = lookout_id.decode(label) + if code is None: + return None + return self.lookout_report_what(dict( + kind=None, code=code, type_name=self.lookout_type_name(type_key))) + + def lookout_type_name(self, type_key: str | None) -> str | None: + if type_key is None: + return None + profile = (self.runtime_catalog.surfaces.get(type_key) + or self.runtime_catalog.aircraft.get(type_key)) + return None if profile is None else str(profile.name) + + def _record_simlog(self, stamp: str, category: str, text) -> None: + """Simulationsprotokoll: alle Feed-Ereignisse, optionsgesteuert, begrenzt. + + Speichert das Rohtext (message-/RawText-Objekt); die Lokalisierung + erfolgt erst beim Commander-Publish (Sprache kann wechseln). + """ + if not self.preferences.simlog: + return + self._simlog_seq += 1 + self.simlog.append({ + "seq": self._simlog_seq, + "t": self.sim_t, + "stamp": stamp, + "cat": category, + "text": text, + }) + + def _record_simlog_state(self, dt: float) -> None: + """Periodischer Zustandssnapshot des kompletten Simulationshintergrunds. + + Rein lesend (kein RNG, keine Zustandsaenderung); Laeuft nur im + Simulationsfortschritt, nicht in Pause/Menue/Editor. + """ + if not self.preferences.simlog: + self._simlog_acc = 0.0 + return + self._simlog_acc += dt + if self._simlog_acc < config.SIMLOG_INTERVAL_S: + return + self._simlog_acc = 0.0 + self._simlog_seq += 1 + self.simlog.append({ + "seq": self._simlog_seq, + "t": self.sim_t, + "stamp": self.world.format_time(), + "cat": "state", + "text": "", + "data": self._simlog_state_data(), + }) + + def _simlog_state_data(self) -> dict: + """Kompakter, JSON-faechiger Zustand aller Einheiten, Waffen und Welt.""" + def r2(v): + return None if v is None else round(float(v), 2) + + def r1(v): + return None if v is None else round(float(v), 1) + + ship = self.ship + snap = { + "mission_t": r2(self.mission_time), + "result": self.mission_result, + "world": {"hour": r1(self.world.hour), + "sea_state": self.world.sea_state, + "night": self.world.is_night()}, + "ship": {"x": r2(ship.x), "y": r2(ship.y), + "course": r1(ship.course), "speed": r1(ship.speed), + "damage": r1(self.damage.total), + "sunk": self.damage.ship_sunk, + "stations": {k: self.damage.station_down(k) + for k in ("bridge", "sonar", "weapons", "opz", + "radio", "engine", "flightdeck")}}, + "weapons": {"torpedoes": self.torpedo_count, + "vls": self.vls_cells, "ciws": self.ciws_ammo, + "aa": self.aa_ammo, "chaff_cd": r2(self.chaff_cd)}, + "subs": [{"id": s.id, "x": r2(s.x), "y": r2(s.y), + "depth": r1(s.depth), "course": r1(s.course), + "speed": r1(s.speed), "state": s.state, + "torps": s.torpedoes_left, "sunk": s.sunk} + for s in self.subs], + "surfaces": ([{"id": w.id, "kind": "warship", + "name": getattr(w, "name", None), + "callsign": getattr(w, "callsign", None), + "mmsi": None, "imo": None, "ship_type": None, + "destination": None, "draught_m": None, + "length_m": None, "width_m": None, + "nav_status": None, "ais_heading": None, + "position_accuracy": None, "x": r2(w.x), + "y": r2(w.y), "course": r1(w.course), + "speed": r1(w.speed), "sunk": w.sunk, + "damage": r1(w.damage)} + for w in self.warships] + + [{"id": c.id, "kind": "civilian", + "name": getattr(c, "name", None), + "callsign": getattr(c, "callsign", None), + "mmsi": getattr(c, "live_mmsi", None), + "imo": getattr(c, "live_ais_details", {}).get("imo"), + "ship_type": getattr(c, "live_ais_details", {}).get("ship_type"), + "destination": getattr(c, "live_ais_details", {}).get("destination"), + "draught_m": getattr(c, "live_ais_details", {}).get("draught_m"), + "length_m": getattr(c, "live_ais_details", {}).get("length_m"), + "width_m": getattr(c, "live_ais_details", {}).get("width_m"), + "nav_status": getattr(c, "live_ais_details", {}).get("nav_status"), + "ais_heading": getattr(c, "live_ais_details", {}).get("heading"), + "position_accuracy": getattr(c, "live_ais_details", {}).get("position_accuracy"), + "x": r2(c.x), + "y": r2(c.y), "course": r1(c.course), + "speed": r1(c.speed), "sunk": c.sunk, + "damage": r1(c.damage)} + for c in self.civilians]), + "animals": [{"id": a.id, "x": r2(a.x), "y": r2(a.y), + "dead": a.dead} for a in self.animals], + "torpedoes": [{"id": t.id, "x": r2(t.x), "y": r2(t.y), + "depth": r1(t.depth), "course": r1(t.course), + "state": t.state, + "target": (t.target.id if t.target is not None + else None)} + for t in self.torpedoes], + "enemy_torpedoes": [{"id": t.id, "x": r2(t.x), "y": r2(t.y), + "depth": r1(t.depth), "course": r1(t.course), + "state": t.state} + for t in self.enemy_torpedoes], + "decoys": [{"id": d.id, "x": r2(d.x), "y": r2(d.y), + "depth": r1(d.depth), "life": r1(d.life), + "dead": d.dead} for d in self.decoys], + "asms": [{"seq": a.seq, "x": r2(a.x), "y": r2(a.y), + "course": r1(a.course), "state": a.state, + "jammer": a.jammer} for a in self.asms], + "essms": [{"seq": e.seq, "x": r2(e.x), "y": r2(e.y), + "course": r1(e.course), "state": e.state} + for e in self.essms], + "asrocs": [{"seq": a.seq, "x": r2(a.x), "y": r2(a.y), + "course": r1(a.course), "state": a.state} + for a in self.asrocs], + "nixies": [{"seq": n.seq, "x": r2(n.x), "y": r2(n.y), + "depth": r1(n.depth), "dead": n.dead} + for n in self.nixies], + "buoys": [{"seq": b.seq, "x": r2(b.x), "y": r2(b.y), + "battery_s": r1(b.battery_s), "active": b.active} + for b in self.buoys], + "helo": {"state": self.helo.state, "x": r2(self.helo.x), + "y": r2(self.helo.y), "airborne": self.helo.airborne}, + "flights": ([{"seq": f.seq, "kind": f.kind, "callsign": None, + "icao24": None, "x": r2(f.x), "y": r2(f.y), + "course": r1(f.course), "speed": r1(f.speed), + "alt_m": None} + for f in self.flights.flights] + + [{"seq": a.seq, "kind": "live", + "callsign": a.callsign, "icao24": a.icao24, + "x": r2(a.x), "y": r2(a.y), + "course": r1(a.course), "speed": r1(a.speed), + "alt_m": r1(a.altitude_m)} + for a in sorted(self.live_traffic.aircraft.values(), + key=lambda item: item.seq) + if not a.despawned]), + "raiders": [{"seq": r.seq, "x": r2(r.x), "y": r2(r.y), + "course": r1(r.course), "phase": r.phase.value, + "hp": r.hp, "pending_asm": r.pending_asm} + for r in self.raiders], + "radars": {"surface": self.surface_radar_on, + "air": self.air_radar_on}, + } + return snap diff --git a/tests/test_eco_display.py b/tests/test_eco_display.py index 808e0300..80b8a1c5 100644 --- a/tests/test_eco_display.py +++ b/tests/test_eco_display.py @@ -69,7 +69,7 @@ def test_eco_display_replaces_the_station_views_while_the_browser_is_live( raise AssertionError("full station view drawn in eco mode") for name in ("draw_map_view", "draw_bridge_view", "draw_sonar_view"): - monkeypatch.setattr("src.core.game." + name, forbidden) + monkeypatch.setattr("src.core.game_draw." + name, forbidden) calls = [] monkeypatch.setattr(Game, "draw_eco_display", lambda self: calls.append(self.station)) diff --git a/tests/test_game_integration.py b/tests/test_game_integration.py index b38910f4..3685565a 100644 --- a/tests/test_game_integration.py +++ b/tests/test_game_integration.py @@ -7,6 +7,7 @@ import pygame import pytest import src.core.game as game_module +from src.core import game_draw from src.core import config from src.core.game import Game from src.core.station import Station @@ -201,8 +202,12 @@ def test_audio_replacement_and_run_shutdown_old_engines(monkeypatch): initial = game.audio monkeypatch.setattr(initial, "shutdown", Mock(wraps=initial.shutdown)) replacement = Mock(available=False) - monkeypatch.setattr(game_module, "AudioEngine", Mock(return_value=replacement)) - monkeypatch.setattr(game_module, "save_preferences", Mock()) + # The engine is constructed by the display half (game_draw); the same + # factory mock is visible through both modules. + factory = Mock(return_value=replacement) + monkeypatch.setattr(game_module, "AudioEngine", factory) + monkeypatch.setattr(game_draw, "AudioEngine", factory) + monkeypatch.setattr(game_draw, "save_preferences", Mock()) game._set_preference("audio", True) old = game_module.AudioEngine.return_value assert game.audio is old @@ -226,7 +231,7 @@ def test_options_apply_global_tooltip_preference_and_language_state(monkeypatch) game = Game(seed=82, audio_enabled=False, preferences=Preferences(language="en", tooltips=True)) save = Mock() - monkeypatch.setattr(game_module, "save_preferences", save) + monkeypatch.setattr(game_draw, "save_preferences", save) game.pinned_tooltip = {"title": "old", "lines": []} game._set_preference("tooltips", False) assert not game.tooltips_enabled and not game.preferences.tooltips @@ -273,7 +278,7 @@ def test_runtime_notices_are_structured_for_bt_listening_and_launches(monkeypatc def test_runtime_language_switch_retranslates_feeds_and_keeps_legacy_strings(monkeypatch): game = Game(seed=87, audio_enabled=False, preferences=Preferences(language="en")) - monkeypatch.setattr(game_module, "save_preferences", Mock()) + monkeypatch.setattr(game_draw, "save_preferences", Mock()) structured = message("runtime.helo.return") game.feed.add("12:00", "mission", structured) game.feed.add("12:01", "mission", "Saved") diff --git a/tests/test_live_traffic.py b/tests/test_live_traffic.py index dd9ee915..75f7f129 100644 --- a/tests/test_live_traffic.py +++ b/tests/test_live_traffic.py @@ -6,6 +6,7 @@ from types import SimpleNamespace import pytest import src.core.game as game_module +from src.core import game_events from src.core.game import Game from src.core.preferences import Preferences from src.data.catalog import CATALOG @@ -535,9 +536,9 @@ def game(): def test_live_traffic_api_test_reports_ok_and_error(game, monkeypatch): """The options-menu 'API test' row runs both probes in a background thread and stores per-side (status, reason) tuples the overlay reads.""" - monkeypatch.setattr(game_module, "ais_test_connection", + monkeypatch.setattr(game_events, "ais_test_connection", lambda api_key, bbox: (True, None)) - monkeypatch.setattr(game_module, "adsb_test_connection", + monkeypatch.setattr(game_events, "adsb_test_connection", lambda credentials, bbox: (False, "boom")) game._set_preference("aisstream_api_key", "some-key") @@ -554,9 +555,9 @@ def test_live_traffic_api_test_reports_ok_and_error(game, monkeypatch): def test_live_traffic_api_test_skips_ais_without_key(game, monkeypatch): called = [] monkeypatch.setattr( - game_module, "ais_test_connection", + game_events, "ais_test_connection", lambda api_key, bbox: called.append(api_key) or (True, None)) - monkeypatch.setattr(game_module, "adsb_test_connection", + monkeypatch.setattr(game_events, "adsb_test_connection", lambda credentials, bbox: (True, None)) assert game.preferences.aisstream_api_key == "" @@ -569,9 +570,9 @@ def test_live_traffic_api_test_skips_ais_without_key(game, monkeypatch): def test_live_traffic_test_row_is_reachable_via_navigation(game, monkeypatch): - monkeypatch.setattr(game_module, "ais_test_connection", + monkeypatch.setattr(game_events, "ais_test_connection", lambda api_key, bbox: (True, None)) - monkeypatch.setattr(game_module, "adsb_test_connection", + monkeypatch.setattr(game_events, "adsb_test_connection", lambda credentials, bbox: (True, None)) game._open_administration("live_traffic") assert game.live_traffic_open diff --git a/tests/test_save_catalog_snapshot.py b/tests/test_save_catalog_snapshot.py index 73c1ed39..647afcea 100644 --- a/tests/test_save_catalog_snapshot.py +++ b/tests/test_save_catalog_snapshot.py @@ -7,6 +7,7 @@ import random import pytest import src.core.game as game_module +from src.core import game_events, game_save, save_validate from src.air.flights import Flight from src.core.game import Game from src.data import catalog @@ -121,6 +122,8 @@ def test_snapshot_remains_authoritative_after_packaged_defaults_change(monkeypat original = copy.deepcopy(state["catalog_snapshot"]) changed_package = _changed_catalog(original) monkeypatch.setattr(game_module, "CATALOG", changed_package) + monkeypatch.setattr(save_validate, "CATALOG", changed_package) + monkeypatch.setattr(game_events, "CATALOG", changed_package) game.load_state(state) @@ -161,7 +164,7 @@ def test_save_reader_rejects_oversize_before_json_parse(tmp_path, monkeypatch): game = Game(seed=2411, start_menu=False) path = tmp_path / "oversize.json" path.write_bytes(b" " * 129) - monkeypatch.setattr(game_module, "MAX_SAVE_DOCUMENT_BYTES", 128) + monkeypatch.setattr(game_save, "MAX_SAVE_DOCUMENT_BYTES", 128) assert not game.load_game(str(path)) @@ -270,6 +273,8 @@ def test_changed_package_split_run_keeps_snapshot_continuation(monkeypatch): control.load_state(copy.deepcopy(state)) changed_package = _changed_catalog(state["catalog_snapshot"]) monkeypatch.setattr(game_module, "CATALOG", changed_package) + monkeypatch.setattr(save_validate, "CATALOG", changed_package) + monkeypatch.setattr(game_events, "CATALOG", changed_package) restored = Game(seed=1, start_menu=False) restored.load_state(copy.deepcopy(state)) diff --git a/tests/test_web_host.py b/tests/test_web_host.py index c9637d8b..dbb29d7f 100644 --- a/tests/test_web_host.py +++ b/tests/test_web_host.py @@ -14,6 +14,7 @@ from src.commander.local import CommanderConsole from src.core import config from src.core.game import Game from src.core import game as game_module +from src.core import game_draw import pygame @@ -221,7 +222,7 @@ def test_host_password_file_is_private_and_reset_is_local(tmp_path): def test_web_host_publishes_game_without_local_display_work(tmp_path, monkeypatch): monkeypatch.setattr(config, "SAVE_DIR", str(tmp_path)) - monkeypatch.setattr(game_module, "save_preferences", lambda prefs: tmp_path / "settings.json") + monkeypatch.setattr(game_draw, "save_preferences", lambda prefs: tmp_path / "settings.json") game = Game(seed=31, start_menu=True, fullscreen=False, audio_enabled=False, language="en", web_mode=True) game.world_mode = "fixed"