Compare commits

..

135 Commits

Author SHA1 Message Date
chexit 9e0cec13f2 Add battle timeline markers and incremental web map updates (#153)
build / mod (push) Successful in 30m14s
2026-12-02 11:54:02 +03:00
chexit 906159b17f Add the AirDef tablet web panel and battle archive (#153) 2026-12-02 00:46:18 +03:00
chexit dfb306edd7 Record unit decisions and show their replay moments (#153) 2026-12-02 00:01:03 +03:00
chexit b882dc3c2b Open the unit card from the visible model (#153) 2026-12-01 23:43:14 +03:00
chexit 5e3907aa99 Keep battle reviews reachable and tied to the recorded outcome (#148, #153) 2026-12-01 23:03:40 +03:00
chexit bf558c024e Add a command post and shared unit cards (#153) 2026-12-01 22:55:45 +03:00
chexit 7e6d9d8b9a Add village defense campaign and breakthrough reports
Co-Authored-By: Codex <noreply@openai.com>
2026-11-26 01:12:38 +03:00
chexit aa842d8a1f Fix raid gameplay, finite ammunition and truck routing
Check launch terrain, reserve ballistic targets for marked objectives, tune in-game reach and fallback fire, and support bounded terrain work on supply routes.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-25 18:53:17 +03:00
chexit 61c4fa5cee Pin the HD light masks and record RTX 3060 benchmarks (#147)
build / mod (push) Failing after 18s
Measure matching DLSS and native TAAU modes on Windows before and after the renderer changes. On the 480-light graphics fixture, the masks improve 37.0 to 41.6 FPS with DLSS. The same candidate reaches about 58 FPS with TAAU in fullscreen.

Verified the GPU output on the RTX 3060 with a static capture, 36 HD tests including shader translation, and the separate Metal TAAU test.
2026-11-24 19:40:42 +03:00
chexit aaf72ef171 Fix HD benchmark reporting and record renderer A/B results (#147)
build / mod (push) Failing after 17s
Resolve benchmark input paths before switching to the disposable game home and report startup failures without a missing screenshot traceback. Capture the executable hash and keep report environment metadata limited to benchmark settings.

Record the earlier light and smoke measurements and the repeated idle A/B runs. Verified with 18 Python benchmark tests, 36 Horizon HD tests, the Metal TAAU smoke test, and the real idle launch and error paths.
2026-11-24 18:24:00 +03:00
chexit 4b8fef6d8a Point horizon at the HD light-tile and smoke-skip fixes (#147)
build / mod (push) Failing after 10s
The engine's kimi-work-124 moves b4c68a78b..4215e8999:

- The light tiles keep the whole screen's lights in one global list instead
  of a copy per tile, and the tile lists no longer overflow into "every
  light on every pixel". In a raid the render phase of the window thread was
  27-83 ms of CPU a frame on an M5 at 1440p (tile_lists 21-25% of the thread
  in a sample); it is 5-13 ms now.
- The fog's march skips the steps that stay inside an empty brick of the
  smoke grid: about -11% of the GPU time where a raid's replay still has
  smoke, nothing where it has none.

Neither changes the picture: on one paused frame of a recorded raid, with
and without each (the smoke-skip and light-tiles diagnostics), the pixels
that do not depend on the wall clock are the same to the frame-to-frame
flicker of one level. The water is not compared: it moves with the clock.

Not explained: in the early windows of a replay some frames take 100-230 ms
with 45-55 ms of GPU and 20-30 ms of CPU. The engine before the fixes shows
it too.
2026-11-24 17:09:08 +03:00
chexit 9b8ef1bcc8 CI: keep the per-push job inside the runner's disk (#102)
build / mod (push) Failing after 9s
Run 140, the first green build since 2 November, knocked Gitea's database
over: from 19:42:52 UTC, right after the mod test binaries were written,
the API answered 500 and 401 and ssh said 'the database system is in
recovery mode' until 19:53:28, eighteen seconds after the job had ended and
its workspace was gone. The tests themselves are innocent (ground_oom peaks
at 113 MiB RSS); what the job leaves behind is not. rustup installed stable
and then the pinned 1.99.1 on top of it (about 1.1 GB), and the debug test
targets of the core and of the mod (669 MB for the mod alone) stayed on
disk through the release build. The runner shares that disk with Gitea and
its database; on 6 November release.yml found 1 GB free there.

The job now installs only the channel pinned in rust-toolchain.toml, deletes
each test target directory once its step is done, and refuses to start with
less than 4 GB free, with the same ::error:: wording as release.yml, after
printing df and free into the log. Both test suites stay complete.

Not verified on the server (no access there). The log now shows the free
space at the start, so the next run confirms or corrects the diagnosis.
2026-11-23 23:08:04 +03:00
chexit d9431468c1 gen_models --check: compare PNGs by their pixels, not their bytes (#92)
build / mod (push) Has been cancelled
With Pillow installable again, build.yml failed one step later: on the Linux
runner 171 generated PNGs (every item icon) differed from the committed
files. Their pixels are identical (sha256 of the decoded rasters matches
the macOS ones byte for byte); only the deflate stream differs, because the
zlib inside the Pillow wheel is built per platform and Python version. The
manifest's byte hashes are not portable, so the check could only pass where
the assets had been generated.

--check now treats a PNG whose bytes differ as unchanged when it decodes to
the same mode, size and pixels, and only while the file still matches its
manifest row: a hand-edited file stays a conflict. Writing (a run without
--check) and the manifest stay byte-exact.

Verified: a copy of airdef-mod with all 175 manifest PNGs re-encoded
(stored blocks) and the manifest rows updated passes --check; the real tree
still reports no differences; tools/test_gen_assets.py OK (13 tests, two
new: a re-encoded icon is accepted and then rewritten by a real run, another
picture and a hand-edited icon are still reported).
2026-11-23 22:31:21 +03:00
chexit 5ac72287f4 CI: let pip install the pinned Pillow into the externally managed runner Python (#102)
build / mod (push) Failing after 39s
Since 2 November build.yml has failed before its first test: gen_models.py
--check needs Pillow, and python3 -m pip install --user refuses the system
Python of the catthehacker/ubuntu:act-latest image (PEP 668,
externally-managed-environment). The job container is disposable, so
--break-system-packages with --user is safe here.

No step order or limit changes; the checkout, fork and Rust steps already
passed and are untouched.
2026-11-23 21:56:22 +03:00
chexit 6616d58a3e Resolution Scale: 100% is DLAA (1:1), monotonic; docs + test-dlss.bat
build / mod (push) Failing after 33s
Point horizon at b4c68a78b (the slider is monotonic: 100% renders 1:1 DLAA,
80% no longer renders larger than 100%). Update the scale docs and pin
test-dlss.bat to HORIZON_HD_SCALE=0.67 for the upscaling A/B (empty would now
be DLAA at the slider's 100%).

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-22 12:24:27 +03:00
chexit b8049674bb engine: the Resolution Scale slider drives HD render scale (DLSS included)
build / mod (push) Failing after 33s
Pin horizon to 4e441de6a (agent/resolution-scale): hd::scale_override used
to pin the HD world at 2/3 whenever DLSS was enabled and its SDK open, so
the Resolution Scale slider (50-200%) was ignored — pixel-identical image
and unchanged FPS at every step. Now the slider drives the world target and
the DLSS render size live, no restart: film quality, then HORIZON_HD_SCALE,
then the slider; with DLSS the render scale caps at the output (100% keeps
the 2/3 auto ratio, above 100% renders at the output — supersampling is
native TAAU's with DLSS off), without DLSS the slider applies as-is
including above 1. The jitter and motion globals match the new size on the
very frame it changes; the NGX context is kept while the render size fits
its dynamic-resolution range, and the histories reset on every scale
change. The #143 motion/jitter contract (MVJittered, render-pixel jitter,
MV scale [1,1]) is intact.

Verified on Mac (M5/Metal, no DLSS device): lib suite 1243 passed, new GPU
test the_world_target_follows_the_resolution_slider (50/100/200% target
sizes + live resize + hd_scale precedence), taau_gpu_smoke_still_surface_ab,
non-dlss build, and a Windows-gnu cross-check of the dlss-gated code against
the NGX v310.9.1 headers. DLSS evaluation awaits RTX.

Docs: DLSS-TESTING.md documents the scale semantic, the live-update
mechanism and the RTX verification checklist (slider changes the DLSS
render size + FPS, no shaking regression, context reuse, fallback logs);
HD-RENDERER.md's scale references follow the slider.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-22 12:05:45 +03:00
chexit 24f3485ebb save: assemble the air section with write! instead of += &format!
build / mod (push) Failing after 30s
Sim::air_text built the save text with `head += &format!(...)` per contact
and `line += &format!(...)` per relief run, and Drone::air_line did the same
for a route point. Each of those allocated a temporary String and re-copied
the whole growing buffer, so the cost was quadratic in the section's size.
The head is not covered by the fits check (only the drone/queue body is): up
to 8 relief grids of 40k run-length tokens each plus 4096 contact lines. On a
heavy raid the autosave's tick therefore exhausted its 300M fuel while
formatting — the crash was in Sim::air_text.

Format directly into the buffer now (std::fmt::Write, push_str, push), which
grows it amortized with no per-token temporary. Nothing else changes: the
format, every MAX_* bound and the byte-budget logic are untouched.

The output is byte-identical: the same air_text over a relief-heavy raid
state and over the 600-drone byte-bound state hashes and measures the same
before and after (64a1787d37047447, 894 and 747942 bytes).
2026-11-21 18:46:19 +03:00
chexit 5737b47dc5 record: thin track points on the caller's grid; extreme-load test; re-pin the stale budget stats
build / mod (push) Failing after 59s
The points budget first gated on (recording tick - first) % step, but a strike
carrier's samples fall on its flight-age grid, offset from the recording's
ticks — the gate skipped them (physical_strike_track_keeps_muzzle... failed).
Count the sampling calls per track instead (Track::due): at STEP it pushes
every call exactly as before, and the thinning doubles the interval without
touching the track's phase. Track::points_len exposes the count for diagnostics.

tests/ground_oom.rs gains the continuous extreme load (eight overlapping
40-Oreshnik waves, 1118 objects airborne at once — well past the crash's >200):
peak 26.3 MiB steady + 5.5 MiB rehash transient, the flight tracks thin to
step 16 (91k points, 2.3 MiB) under their 2 MiB budget, the journal and poses
stay within theirs, and the fight still resolves (157 intercepts). The radar
picture itself (11.5 MiB at 1118 airborne) scales with the sky — it is the
simulation's state, not a cache, and is ~3 MiB at the crash's >200 load.

The WASM budget fixture's final /airdef stats pin was stale at the base commit
already: it was measured on engine 8e711f969, and the base pins acfb379aa,
whose host answers shift the two late Smart raids (417/2463, 7 in the air).
Verified identical on the pristine base and on this branch — the memory bounds
do not move that fight; the tick-2102 checkpoint (184/325/2011) is unchanged.
Re-pinned to the measured string and updated BUDGET_ASSERTED_SHA256 so the
raid/snapshot assertions stay active. test-budgets: 283 steps ok, tick fuel
max 184.7M/300M, 0 failures.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 17:57:51 +03:00
chexit dc87c0b98a sim: bound the ground cache and the recording under the 64 MiB WASM budget
The fullscreen-map OOM (rust_oom in hashbrown reserve_rehash under
Ground::answer during a large raid): the mod's whole state shares one
64 MiB linear memory, and three consumers grew without an effective bound.

Measured on a native replica of the crash load (tests/ground_oom.rs: 64
complexes, six all-sides Oreshnik raids plus a smart raid over 10000 ticks,
304 objects airborne at once, a wide map query walk; render answers exactly
as the WASM host gives them): peak 45.5 MiB steady + 21.9 MiB rehash
transient = 67 MiB, over the cap. The bulk: kept replays 23.2 MiB (the scene
journal 4.6 MiB each, filled with per-radar track transitions), Ground.known
10.9 MiB (277k columns; the old sweep only ran above 300k and kept everything
younger than 2000 ticks, so a wide query pattern grew it without bound and
the next rehash doubled the table), the live recording 7.5 MiB, radar tracks
3.2 MiB.

Bounds, derived from the 64 MiB budget (Sim::memory reports each consumer):
- Ground.known: KNOWN_MAX 100_000 columns (~2.7 MiB steady, ~8.2 MiB through
  a rehash at 24 B + control byte per entry, 7/8 load). Over the cap the
  oldest answers go down to three quarters (a sweep is not every tick),
  ordered by (age, column) so the sweep is deterministic; heights past
  SWEEP_AGE go with them. Evicted columns are asked again when next needed —
  the cache is reconstructible, no target, frequency or precision is cut.
- Scene journal: MAX_SCENE_EVENTS 65_536 -> 24_576 (~1.7 MiB), and the track
  transitions (acquire/handoff/lock/lost — they grow with systems x contacts,
  the journal's bulk under a large raid) get their own 8_192 budget; beyond
  it the later ones are not recorded. Launches, fires and outcomes keep the
  rest of the journal; chains() already tolerates missing steps.
- Flight track points: MAX_TRACK_POINTS 2 MiB per recording; over it every
  other point is kept and the ticks between points double (Track::step, the
  #142 decimation pattern for the systems' poses). Replay readers use the
  track's own step.

Replica peak after: 24.5 MiB steady + 5.5 MiB transient = 30 MiB, under the
48 MiB headroom target; the fight resolves (376 intercepts, sky clears) and
the same seed replays the same ordered trace. The saturation checkpoint is
untouched (314 / 2022 / 184): its cache stays under the cap.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 17:55:54 +03:00
chexit 4dbe103f5b sim: account where the mod's memory goes (Sim::memory, per-cache bytes)
The fullscreen-map OOM (Ground::answer rehash under a large raid) needs a
measured breakdown, not a guess: Sim::memory estimates each consumer's
allocated capacity (hashbrown tables with their control bytes, vec capacities,
BTreeMap nodes) — Ground.known, WorldCache.secs and rays, the sim vectors and
radar tracks, the recording and kept replays, Intel/recon, routes, sites,
strikes, the raid plan. MemoryReport::rehash_headroom names the transient a
rehash adds (old + new table of the biggest map). Ground::known_len exposes the
column count the budget tests guard.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 17:55:54 +03:00
chexit dca35dc9a2 Point horizon at the 512 MiB mod-memory cap; re-baseline the budget final stats
build / mod (push) Failing after 30s
The larger memory cap shifts the heavy scenario's final stats slightly
(417/2463, fewer pending sections); deterministic across runs, fuel
failures still 0. The tick-2102 checkpoint is unchanged.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 17:53:20 +03:00
chexit 3a992e7369 Point horizon at the DLSS temporal-stability fix; document the RTX checks
build / mod (push) Failing after 31s
Engine agent/dlss-temporal-stability (a791e8439 -> acfb379aa):
- f536fa958 DLSS: declare the jittered motion vectors (MVJittered). The create flags left
  MVJittered unset, so NGX applied the jitter offset on top of the already-jittered motion
  buffer — the camera jitter counted twice, the severe shaking. Contract verified against the
  DLSS Programming Guide (31 March 2026) §3.6.1-3.6.3/§3.7.3/§3.8.1, nvsdk_ngx_defs.h and
  Streamline's dlssEntry.cpp (pixel-space vectors take MV.Scale 1.0; the {1/w,1/h} advice is
  Streamline's own constant, scaled back by its plugin).
- 26ee82398 Native TAA: a reactive mask for water (its own depth, binding 7; less history where
  the waves/glint animate fastest, faded to 96 blocks) + the wind-motion contract test.
- acfb379aa Wind-blown leaves and plants carry their own motion vectors (previous frame's wind
  time/strength in Globals.hd_motion.zw, terrain.wgsl wind_offset_at).

Verified on Mac (no RTX): horizon-client --lib 1242 passed / 0 failed; taau_gpu_smoke on Metal
(fixed decode at the spatial filter's error floor, phase spread 0.0029 vs legacy 0.0156); naga
validation + HLSL translation of every HD shader and terrain/entity; frame/global layouts;
deterministic jitter/reprojection fixtures; non-dlss binary build; clippy clean on the touched
files. NGX evaluation itself awaits RTX — docs/DLSS-TESTING.md has the verification steps and
three fallback variants (jitter sign/axes, Streamline-style scale, non-jittered conversion pass).

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 16:56:38 +03:00
chexit f7ec0a3373 Docs: battery variants deploy by remote or command, not the removed N-menu page
build / mod (push) Failing after 30s
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 16:48:01 +03:00
chexit 4d7815834d Give each battery variant its own placeable remote
build / mod (push) Failing after 28s
Every catalog variant now has a `airdef:deploy_<id>` remote in `give` and
in the hotbar: deploy_radar_search, deploy_radar_track, deploy_radar_height,
deploy_s400_launcher and deploy_s500_launcher. The variant rows carry their
remote item in the generated catalog, and the inventory appends them after
the existing remotes so no ordinary remote changes slot.

Placing a remote now resolves the item back to its (kind, mode, role)
configuration and settles the system, the same path `/airdef deploy <key>`
already used. The base remotes keep deploying the ordinary integrated,
multifunction system; the radar remotes place Search/Engagement/Height
profiles, so radar_track gets fire authority and the others do not.

The N menu's battery-deploy page is removed entirely (button, page and its
handlers); variants remain available through `/airdef deploy` and now the
remotes. Items, icons (aliased to the unit silhouettes), lang entries and
generated assets are regenerated from the content catalog.

Checks: gen_catalog.py --check, gen_models.py --check, test_gen_assets (11),
airdef-mod lib 115 + integration suites, airdef-core 327, cargo build.
2026-11-21 16:44:23 +03:00
chexit b735458dd8 Point horizon at the DLSS colour filterable-texture fix (#124)
build / mod (push) Failing after 29s
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 16:08:53 +03:00
chexit 74baf8b4e2 Document the libclang auto-install
build / mod (push) Failing after 29s
The zero-step Windows+RTX toolchain now also covers libclang: LLVM is no
longer a build prerequisite, the detected or downloaded directory is
passed as LIBCLANG_PATH, and the cache layout gains
.horizon-cache/libclang/<version>/. Manual override (winget install
LLVM.LLVM + LIBCLANG_PATH) and the Unable to find libclang troubleshooting
note remain.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:55:14 +03:00
chexit 67e8a19e2b Auto-install libclang for bindgen on Windows + NVIDIA RTX
The DLSS build failed on Windows at dlss_wgpu's bindgen step: libclang.dll
is neither in the DLSS SDK nor in the Vulkan headers. It is now part of the
same zero-manual toolchain.

Detection first, download last: an explicit LIBCLANG_PATH (directory with
libclang.dll or clang.dll) wins and disables auto-install; otherwise PATH,
Program Files\LLVM\bin (both Program Files roots) and LLVM shipped with
Visual Studio (vswhere -find VC\Tools\Llvm\x64\bin\libclang.dll) are
checked, then the cache.

When nothing is found, the NuGet package libclang.runtime.win-x64 is
downloaded (~34 MB, version from the flat-container index with pinned
23.1.5 fallback) and only runtimes/win-x64/native/libclang.dll (~89 MB) is
extracted to .horizon-cache/libclang/<version>/ behind the existing
staging + airdef-install.json marker pattern. The resolved directory is
passed to cargo as LIBCLANG_PATH.

libclang is resolved only when the DLSS SDK and Vulkan headers are already
available, so a missing SDK never triggers a useless download. Any
detection/download/extract failure warns and degrades to mods/TAAU, and
non-Windows/non-RTX still returns before any network access.

Tests cover PATH/Program Files/vswhere detection, explicit precedence,
numeric NuGet version choice and fallback, selective extraction and marker,
cache hit, damaged cache reinstall, package without the DLL, plan env
wiring and failure to mods-only.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:55:12 +03:00
chexit e61b2e8f64 Cover mixed explicit-env and auto-download DLSS resolution
build / mod (push) Failing after 29s
A valid DLSS_SDK must not block the Vulkan header auto-download, and vice
versa; assert that only the missing component is fetched.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:44:12 +03:00
chexit 97d97eb37c Keep a broken DLSS cache directory from failing the build
Scanning .horizon-cache/dlss-sdk is best-effort: a permissions error or a
missing directory now means "nothing cached" and the normal install path
runs, instead of an exception escaping before the mods fallback.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:43:48 +03:00
chexit 84e9d6ab60 Document the zero-step DLSS toolchain install
The quick-start build section no longer asks for an NVIDIA DLSS SDK or a
LunarG Vulkan SDK: `airdef.py all` downloads only the headers, static libs
and nvngx_dlss.dll it needs, caches them under .horizon-cache with a
version marker, and copies the fresh DLL beside horizon-client.exe. Keeps
the explicit DLSS_SDK/VULKAN_SDK override, the offline/failure fallback to
mods with native TAAU, and the remaining LLVM/clang build prerequisite.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:40:00 +03:00
chexit 88757d05f8 Auto-install the DLSS toolchain on Windows + NVIDIA RTX
`airdef.py game` no longer needs manual SDK setup. On Windows with an RTX
adapter, when neither DLSS_SDK nor VULKAN_SDK is set, it downloads only the
files dlss_wgpu reads:

- NVIDIA/DLSS at the newest stable v310.9.x tag (GitHub API; pinned v310.9.1
  when the API fails): include/*.h, both x64 static libs and the runtime
  rel/nvngx_dlss.dll (~67 MB once), laid out under
  .horizon-cache/dlss-sdk/<tag>/ exactly as valid_dlss_sdk expects.
- KhronosGroup/Vulkan-Headers include/ under
  .horizon-cache/vulkan-headers/<tag>/Include/, since build.rs uses headers
  only and links no Vulkan library.

The resolved roots are passed to cargo as DLSS_SDK/VULKAN_SDK, and after a
successful dlss build the fresh nvngx_dlss.dll is copied beside the built
horizon-client.exe. Explicit DLSS_SDK/VULKAN_SDK (and the sdk argument)
keep priority and disable auto-download for that component. Any network or
layout failure warns and falls back to --features mods/native TAAU instead
of failing the build; non-Windows and non-RTX take the old mods path with
no network access.

valid_dlss_sdk now looks for the real nvsdk_ngx*.h names instead of the
nonexistent nvngx*.h glob, so a genuine SDK (and the downloaded cache) is
recognised at all.

Tests cover tag selection and fallback, selective layout + marker cache
hit, damaged/partial caches, streamed download and truncation, Vulkan
Include layout, plan env wiring, explicit-env precedence, failure to mods,
and DLL placement beside the client.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:39:56 +03:00
chexit 8d716eccaf Point the DLSS build hint at the mod settings toggle
build / mod (push) Failing after 30s
The build auto-detect hint still said HORIZON_DLSS=1 enables the backend;
the player-facing control is now the mod settings toggle (default on),
with HORIZON_DLSS=1|0 as an override.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:08:03 +03:00
chexit e85e7a18d0 DLSS on/off toggle in the mod settings, persisted per world
The More page (N → Огонь, ремонт, эффекты…) gains a DLSS row next to
Акустика. Default on: a world without a saved choice leaves the engine's
own default (on where supported). The row reads render.dlss-status (API
level 33): with a DLSS device it toggles live; without one it says
«недоступен», and an on-request is kept and applied at the next launch —
a graceful no-op, never an error. The request is saved in the world's
layout (`dlss true|false`, older saves load unchanged) and re-applied on
world load; the engine persists it in horizon-graphics.txt for the next
start's device opening. /airdef capabilities reports the DLSS state too.

Graphics-only: no resolution control (the player's own Horizon settings
stay in charge) and no sim changes. Engine gitlink → b2cc11c45
(agent/dlss-toggle): the dlss graphics setting, the live evaluation gate,
the dlss control command and the level-33 SDK imports.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:06:25 +03:00
chexit 11238c4a03 Add dlss to the game build on Windows + NVIDIA RTX with the SDK
build / mod (push) Failing after 29s
tools/airdef.py game always built with --features mods, so an RTX user had
to run the manual cargo line from docs/DLSS-TESTING.md. The feature string
now comes from dlss_build_features(): dlss is added only when the OS is
Windows, a Win32_VideoController name has both NVIDIA and RTX, the DLSS SDK
has include/nvngx*.h and lib/Windows_x86_64/x64 (DLSS_SDK, a repo DLSS/ dir
or %ProgramFiles%\NVIDIA\DLSS), and VULKAN_SDK has Include/vulkan/vulkan.h
(dlss_wgpu's build script needs both SDKs). Otherwise the build stays
mods-only; on Windows + RTX without the SDK it prints how to get v310.9.1
instead of failing. GPU/SDK probe errors mean "no DLSS" and never abort the
build; the HORIZON_DLSS runtime switch is untouched.

Tests: tools/test_airdef_build.py covers non-Windows, no RTX, missing DLSS
SDK, missing Vulkan SDK, the full toolchain, a failed GPU probe, the SDK
layout check and the feature string reaching cargo. python3 tools/airdef.py
game still builds mods-only on macOS (fresh target dir: 3m11s, exit 0).

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 14:21:20 +03:00
chexit d8d9913770 Issue #126 point 4: same-tick A/B parity and timing record
build / mod (push) Failing after 29s
The temporary in-session shader switch (harness build, reverted) renders the
same frozen tick with both effects.wgsl versions: old-vs-new differs by at
most 1-2/255, no pixel over 5/255, and no more than two frames of the same
shader differ. Frame time is below the in-game noise floor on M5 (32
screen-filling late-life fireballs: +0.37 ms median, sigma 3.6). Includes
the hd_bench polygon_noon run and test counts.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 13:51:13 +03:00
chexit 8fb849f195 Skip the fireball raymarch when its fade is zero (#126 point 4)
In the HD smoke path fade = 1 - smoothstep(0.08, 0.28, k) is exactly 0
from k = 0.28: every step's density is zero, absorb is 0, so the march
adds no light and leaves transmittance alone while still sampling fbm
and shading the volume. Wrap the loop in an `if fade > 0.0` guard; the
glow after it is untouched (heat is still live there) and is itself
skipped once its heat is spent. Density, steps, sampling and lighting
are unchanged.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 13:51:13 +03:00
chexit 1a82742744 CPU timeline profile of the battle frame (#147 step 3.1, #126 D/E)
build / mod (push) Failing after 28s
Measure-first profile naming the culprit with data; no worker implemented
(step 3.2 is out of scope). docs/measurements/issue-147-cpu-profile/: README +
report-server.json (default server-thread path) + report-inframe.json
(--in-frame control), M5/Metal 2560x1440 HD, same-recording battle with
overlapping raids + explosions + dense smoke, each run serialized under the
shared flock /tmp/airdef-bench.lock (earlier concurrent runs discarded).

Instrumentation: host per-tick tick_mods spans (ground/world/snapshot/wasm/
models/output/total, HORIZON_MOD_CPU_PROFILE=1, attributed by tick+frame),
mod Sim::step phase timing via an adapter-injected monotonic clock
(game.monotonic-nanos, API level 32; airdef-core stays SDK-free), raid_bench
--scheduler + per-frame span/frame correlation + mod phase delta.

Findings: on the default path the battle frame is GPU-bound (GPU avg 73.7ms ~
frame p95 88ms; 127/128 frames >33ms); the mod path is ~2.5ms/tick, per-frame
p99 7.7ms, 0 frames >25ms, host world answers <0.1ms, model prep ~0.05ms; the
872ms CPU spike is a render/GPU hitch (mod 2.15ms). In-frame is CPU-bound
(CPU p99 175ms); the mod path reaches >25ms in 27 frames, and step_drones
dominates Sim::step (52%, max 47ms/tick), A* only 15%. The schedulers' mod
peaks do not coincide; only the render-dominated catch-up spike is common.

Recommendation: a pure A* route worker and a world-snapshot worker are NOT
justified (A* leads only the tiny default-path mod; world answers never lead).
Default-path peaks are GPU -> steps 1-2 (GPU/geometry) apply, a CPU worker
would not help. If targeting in-frame CPU, the unit is the whole Sim::step
(Wasmtime on its own thread), not a route worker — still not implemented.

Harness fix (engine gitlink 48eff0fcb): control-socket chat/chat-log now reach
the client mod on the server-thread path (chat-box parity), enabling the
required default-path battle measurement; sim rules untouched.

Tests: airdef-core 326 passed/0 failed/8 ignored; airdef-mod 113+1+2+5 passed
incl. same_seed_same_result and combat_trace_is_deterministic;
tools/test_raid_bench.py 11 passed; horizon-mods suite + wasm ABI test ok.

Engine: d073783f5 (spans + clock) + 48eff0fcb (chat harness) on
agent/126-cpu-profile. Parent: 92c058f60 (profiler + driver) + this commit.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 13:35:32 +03:00
chexit 92c058f606 Sim::step phase timing and the CPU-profile bench driver (#147 step 3.1)
Mod side: Sim::step times plan_step, adapt, step_drones, step_moves,
update_sight, step_sams and record, plus the whole step and its untimed
remainder, through sim::profile. The simulation stays SDK-independent (also
built as airdef-core): the adapter installs the host monotonic clock
(game.monotonic-nanos) in init, native tests use std::time::Instant. The
counters are fixed-size, per-thread, read no randomness and change no
decision; /airdef stats reports them as PROFILE chat lines, reset per world.

Driver: raid_bench gains --scheduler in-frame|server-thread (the two
single-player paths, measured separately), HORIZON_MOD_CPU_PROFILE=1, the
per-tick mod-path spans joined to the frame trace (per-frame totals, >25/33 ms
counts, what the worst CPU frames carry), and the mod phase profile read at
idle and battle end with the battle delta. report.json carries mod_cpu,
mod_cpu_ticks, mod_phases_* and the derived correlation. Tests for the new
helpers.

Engine gitlink: mod-path CPU spans + game.monotonic-nanos (API level 32).

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 12:29:22 +03:00
chexit c08b737296 Reproducible raid/replay render bench and #147 instancing measurements
build / mod (push) Failing after 32s
tools/raid_bench.py (+ tests): the #147 step-0 driver replaces the #126
scratch script. One battle at fixed ticks (waves inside resident terrain —
far waves stall at the unknown-chunk edge and no fight happens), fingerprint
chat lines at control ticks, then the raid's own recording replayed. Both
render paths are benched on the SAME recording in ONE process via the
engine's diagnostic `model-instancing off|on` toggle (cross-process battles
diverge in event timing: 16 vs 32 kills at one control tick), pairs in
alternating order; idle cold/warm, mid-battle window, reload (F3+T), replay
seek, away-camera checks, and static off/on stills for pixel parity
(hd_bench motion-mask methodology). report.json carries gitlinks, device,
mod_models counters, CPU/GPU p50/p95/p99/max, raw frame times, >25/33 ms
frame counts, guest fuel and streaming queues.

Engine gitlink: one mass mod-model group GPU-instanced (retained mesh per
pack generation, current/previous pose/id/light instance stream shared by
main, motion and shadow passes, per-vertex fallback to parity, runtime
diagnostic toggle, stats raw + guest fuel reporting).

Measurements: docs/measurements/issue-147-instancing/ (M5/Metal, 2560x1440;
RTX 3060 pending). docs/REPO-MAP.md and docs/ENGINE.md pin updated.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 11:39:43 +03:00
chexit 32748b116c Smart v2 on top of #146: one public picture, mark prices, bounded refresh, bearing window (#149)
build / mod (push) Failing after 30s
Re-applied the genuinely new #149 features onto kimi-work, REUSING the already-integrated
#146 infrastructure (KnowledgeSnapshot { tick, contacts, marks }, knowledge_now(),
Plan.knowledge, RouteJob.known, versioned price_grid_known and restore). No #146 scaffolding
is duplicated: one snapshot per order, prices over known.tick, versioned restore are kept
exactly as they were. The only additive change to KnowledgeSnapshot is observations().

New #149 layer:
- observe::Observation + observe::merge: Contact and Mark become one public hint, matched by
  public features only (area overlap + exact category); coarse Unknown/contradicting marks stay
  separate, the contact's kind/fix are never rewritten, recon.truth and real ids are not used.
  One Observation::rank scale replaces the two ranks in radar_strikes, choose_target and the
  adaptive picks (kimi-work's slice signatures kept).
- price_grid_known prices marks: a trusted launcher/gun/jammer mark prices its published
  category envelope weighted by confidence (Confirmed x1, Probable x0.5); a radar mark feeds
  the network belief; a mark matched to a contact is priced once through the contact; a
  doubtful mark prices nothing.
- Bounded refresh of the unreleased portion: ew::Refresh with absolute deadline
  REFRESH_WINDOW=600; step_refresh re-aims queued Plan/Sead drones once on a report (typed
  Intent::Refresh, SEAD priority) within SWITCH_CAP and assignment budgets; no report never
  delays a launch.
- Bearing window: Intel.outcomes bounded VecDeque (48 entries, 12000-tick window); best_bearing
  adapts exploration share by typed BearingReason (few/stale/conditions-changed/exploiting);
  conditions are a fingerprint of the public picture, never hidden state. bearing_report() and
  bearing/refresh_*/observations fields in EnemyPictureReport. Legacy fixed share kept.
- examples/smart_bench runner (simple/current/candidate, seeds 1/7/42, open/hills/config-change/
  recon-lost, JSON+lines); Sim::smart_legacy reproduces current Smart; harness::run_with_hook.
  Light modes and bounded jobs unchanged; policy reads no health/charges/hidden switches/positions.

Tests: smart_tests + observe::tests (metamorphic hidden-layout, public dedup, marks in prices,
one version per order in both modes, bounded refresh fires-once/never-pauses, bearing window and
reasons, durable window + Intent::Refresh). The relief-version regression fixture's wall is
widened in z so it crosses any east-west route after the candidate's assignment-order change.
cargo test passes: airdef-core 326 lib + 8 scenarios; airdef-mod 113 lib + core_boundary + 5 scenarios.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 10:57:04 +03:00
chexit b796a439df Restore the saturated intercept count by uncueing the embedded radar (#145)
build / mod (push) Failing after 31s
The heavy WASM scenario (wasm_flat_budget, 64 integrated complexes vs two
`airdef wave oreshnik 40 2600`) lost intercepts at the tick-2102 checkpoint:
522 (main) -> 302 (#133) -> 243 (#134). Decomposed by A/B on one fixture, one
host (2bcce64), one SDK, each slice built from its own commit:

- 522 -> 302 (#133): Track.vel became an estimate from noisy measured places
  (it was the target's true velocity); the forecast, the aim lead and the
  interceptor's launch Fix all read it. Forcing the class estimate to Unknown
  leaves the count unchanged (native 296 ~= 294), so class/roles is not the
  cause. The pre-#133 522 used the target's true velocity, which the #133
  contract "class and speed only from measurements" forbids; this portion is
  the intentional cost of honest measurement-only tracks and is kept.

- 302 -> 243 (#134): the network cue was extended from the separate engagement
  radar to every fire-quality radar, including each weapon's embedded radar.
  Cueing every relayed contact each tick flooded the embedded fire control with
  one-tick plots whose noisy velocity degraded guidance. Restricting the cue
  back to separate radars recovers the whole drop: 243 -> 325.

- own_fire_within / FIRE_QUALITY / channels are NOT causes here: relaxing the
  own-fire gate or the channel limit each changed nothing (243 -> 243). Embedded
  radars always measure Fire plots of quality >= 64 and have no channel limit.

- #140 does not affect this loadout, by fact: the fixture deploys no separate
  radar, so every profile is embedded with channels = 0; the channel-age bug
  binds only where a profile has channels, and the channels-off A/B was flat.

Fix: the cue looks only through a separate fire-quality radar
(sam.kind == SamKind::Radar); the embedded radar keeps its beam/revisit/lock
acquisition as before #134. All radar profiles, channel limits, own-fire
authority and the measurement-only class/speed contract are preserved; no
target truth is injected.

Measured after the fix (WASM, fuel budget 300M/tick): checkpoint 325 intercepts
/ 2011 hits, fuel max 118M; final (tick 3302, two late Smart raids) 385 / 2472,
fuel max 176M; zero fuel failures. The first late raid reports the #135 recon
flight ("Разведка противника: впереди налёта высланы разведчики"); the second
is silent (recon budget spent) — the fixture now expects exactly that instead
of the stale empty chat that stopped the scenario.

Tests:
- airdef-mod/tests/saturation.rs: deterministic native replica of the checkpoint
  (same sim, host block tracer) asserting the restored count and a regression
  threshold, plus the #140 loadout fact (no separate radar, channels = 0).
- Sim::launch_audit (why.rs): on-demand tolerance diagnostic counting why each
  (system, drone) pair holds fire — no track / stale / no authority / role /
  doctrine / reach / claimed / not ready / not aimed / terrain / ready.
- sensor_tests: a network plot cues a separate fire radar but not the embedded one.
- wasm_flat_budget baselines re-measured with provenance comments; the asserted
  fixture SHA in tools/airdef.py updated.

Verification: `python3 tools/airdef.py test-budgets` passes both stages and the
two late raids (283 steps, fuel failures = 0). airdef-core 292 + 8, mod lib 104,
mod scenarios 5, saturation 2 — all green. A/B record:
docs/measurements/issue-145-intercept-regression.json.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>

Integration note (shipped engine 8e711f969): the tick-2102 checkpoint baseline is
unchanged and passes on the shipped engine (325 intercepts / 2011 hits). The final
stats baseline was re-measured on the shipped engine with #146 integrated (one
knowledge snapshot per Smart order changes the two late raids): 414 / 2463, world
8885 sections / 420671 rays / 3442845 cells. The asserted fixture SHA in
tools/airdef.py was updated to match. python3 tools/airdef.py test-budgets passes
all 283 steps with zero fuel failures (tick max 184608537 / 300000000).
2026-11-21 10:32:11 +03:00
chexit c76f620642 Point horizon at the TAAU motion-buffer jitter fix (#143)
build / mod (push) Failing after 28s
Engine a3045b61b: the motion buffer's coordinate contract is explicit and
decoded per history grid — native TAAU's stable history no longer receives
the two frames' jitter difference (a still surface reads the same output
pixel on every phase), 1:1 TAA keeps the correction its jittered history
needs, and the NGX input and flags are untouched for separate verification
on the DLSS path (#137). Numerical reprojection tests on all jitter phases
plus an ignored GPU A/B smoke on the real fs_taau.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 10:09:12 +03:00
chexit 63ebd4ac6c Plan one Smart order on one knowledge snapshot (#146)
build / mod (push) Failing after 25s
order_raid read one picture and one list of recon marks for the whole
order, but the Plan kept neither: plan_step priced each kind's first
route on whatever picture_of_defences() held at the tick the budget
reached that kind, so one raid could hold several versions of the map
at once. A retarget job carried its version's contacts, yet
price_grid_known aged them at self.tick, so two jobs of one version
reached on different ticks could disagree about a contact's own sensor.

KnowledgeSnapshot fixes the observation tick together with the contacts
and marks read at it. The plan stores the order's snapshot and passes it
explicitly to price_grid_on/price_grid_known; radar_strikes takes the
order's marks instead of re-reading the recon memory. A retarget job
shares its adaptive tick's snapshot and prices age at the snapshot's
tick, never at the current one: current time still cancels a stale job
(prune_air, job_live), separately from the version's own arithmetic, and
an explicitly new retarget gets a new snapshot and may use a fresh
report. The save rebuilds each version's snapshot from the contacts and
the marks reported by it; the section format is unchanged. Nothing here
reads the force: only published kinds and the contacts' own observations.

SDK-free regressions: a Smart order of two kinds whose land answers
starve while a visible contact is disclosed mid-wait keeps every kind's
targets and routes on the order's snapshot (and differs from an order
that knew the contact from the start); two jobs of one version worked
out across the emission-belief boundary price the same world, a new
version with a fresh report believes again, and a new version without
one does not.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:54:47 +03:00
chexit f2bc8550f5 Tie a radar's refine/fire channel to its own plot's freshness (#140)
build / mod (push) Failing after 28s
A station counted any own plot, however old, as a busy refine/fire
channel: a network heartbeat kept a stale contact's track fresh, so two
long-expired own fire plots still held both channels of the engagement
radar and a new contact nearby got only a coarse search plot, even with
the search radar running.

Channel occupancy now follows the station's own tracking.
Track::holds_channel requires an own (never relayed) refine/fire plot no
older than the station's track_ttl — three missed turns, the same value
that already bounds a contact without a fresh measurement. The planner
counts channels with the same Sam::own_channels_used(now) the panel,
monitor, map and "why" views read, so the UI and the allocation cannot
disagree about a stale channel. A stale channel frees for a new contact
without the network's survey track being removed; the hard per-profile
limit and the own measurement's provenance are unchanged, and a relayed
plot still never holds a channel.

Test: two contacts take both channels at the station, then leave its
reach while the search radar beside them keeps relaying them; a third
contact arrives nearby and gets its own fire channel (the test fails on
the old counting), and the relayed survey tracks of the old contacts
stay.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:53:43 +03:00
chexit 5f00a2a16b Read replay events by their time ranges, not the whole journal (#150)
The replay's sounds, the raid map's counts and the struck objects now read
the recording's event and scene journals by time instead of every pass over
the whole journal: partition points over the journals (with a stable time
index built at close only when a journal is out of order), the map's kill
and hit prefix indices, each object's first hit, and marker/time-line paths
that stop at the map's shape cap. Blasts, smoke, debris and the fire replay
read bounded windows back from the moment.

The sets, order and names stay exactly as they were: tests compare every
reader against the full journal filter, including tied times, out-of-order
journals and arbitrary forward and back seeks. The replay_bench example
measures a 10-minute raid with nearly full journals (playback, reverse seek,
pause, MP4); its result is docs/measurements/issue-150-replay-ranges.json.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:52:20 +03:00
chexit 7f52c40d99 Bump horizon to the DLSS command-order and history fix (#137)
build / mod (push) Failing after 21s
Engine 1cadd6338: the DLSS frame now submits world+linearize -> NGX ->
delinearize -> film/tonemap/UI/capture/present in one queue.submit with no
CPU sync, so the final frame, screenshot and export read the current
resolved frame instead of the previous one. Native TAA history readiness
is tracked separately from NGX, so the first fallback frame after DLSS
does not blend a stale or empty native history; a cut/resize clears both.

HD-RENDERER.md records the corrected order and the history separation.

Real-RTX acceptance (docs/DLSS-TESTING.md) is still pending: no RTX is
available here, so this is verified by the ordering/history unit tests and
the native horizon-client + horizon-mods suites, not a DLSS GPU capture.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:45:20 +03:00
chexit 8afe691301 Add typed battle reasons and short engagement chains (#148)
build / mod (push) Failing after 32s
A battery's "why" now starts with one typed reason shared by the monitor,
the HUD and the chat: only observation, waiting for a track, busy channels,
no ammunition, or ready. It carries the age and the station of the mark it
is about, and `/airdef why <n> source` moves the monitor to that station.
The reason is computed from the same predicates the launch decision uses,
and the detailed decision settles it, so a headline cannot promise or deny
a shot the simulation does not take.

The after-action review builds 4-5 measured steps per contact from the
recording's scene journal and events: mark, handoff, lock, launch, outcome.
The menu lists them per battery with a filter and opens a replay frame on
a click (the outcome clip, else the map held at the launch or mark);
`/airdef chains [battery]` prints the same list. Missing transitions stay
missing and marked as no launch, never guessed, and the normal HUD still
shows only the battery's own picture.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:42:10 +03:00
chexit bd2d8f4fed Release an unreachable optical contact and serve ready posts fairly (#138)
build / mod (push) Failing after 22s
An automatic optical contact is kept only within the optics' own reach and let go after a few failed probes. It stays out of the next picks for a while, so a visible alternative can be tried without constant switching; unknown world geometry gets a longer, still bounded wait. A player's command still waits for its contact and says so in the status line.

Ready posts are now served oldest-probe first through a simulation-wide probe sequence, so posts whose phases coincide all advance under the unchanged CHECKS_PER_TICK budget.

Tests: an out-of-range contact with a visible alternative, a blocked contact with a visible alternative, five same-phase posts, the bounded unknown-geometry wait, and the manual pin's status and out-of-reach behaviour.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:27:02 +03:00
chexit 41ab52e802 Keep replay transitions through the SAM pose decimation (#142)
build / mod (push) Failing after 36s
Sampling slowed by the pose budget skipped whole short stages: the six-tick
tube cover opening, the ejection and the radar switch fell between samples,
and thinning then halved already recorded transitions along with poses.

Poses still share the adaptive sam_step grid and the unchanged 32768-key
budget, but the recording is now sampled every tick for facts: a discrete
change (spent_cells, cap_cell, radar_on, mode, role) and every frame of the
cover's own movement are kept on the tick they happen, with the stage's start
backdated one tick so the opening still spans exactly OPEN_TICKS. These keys
carry an event mark and decimation halves poses only, keeping events, the
first and the last key.

Events get their own explicit 4096-key budget instead of raising the pose
budget: when it runs out the oldest stop being critical and thin as poses
while the newest stay exact.

Test: 64 turning radars plus an S-400 at sam_step 16, ejection on tick 4103
(cover 0.8333333 a tick before, spent cell on the ejection tick), a cancelled
opening and a radar switch off the pose grid, all surviving further thinning;
a 64-radar chattering recording stays exactly at the event budget with the
newest switch exact.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:23:41 +03:00
chexit 433e1500e2 Do not treat a cooling jammer as an active emitter (#139)
build / mod (push) Failing after 37s
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:20:46 +03:00
chexit 01765027b1 Fix the recon picture's wrecks and its emission sources (#139)
build / mod (push) Failing after 29s
A look no longer reports a wreck as a lead: a first look at one makes no
mark, and one the picture already held is radioed home as destroyed and
takes its mark out of the picture. A hidden kill still never rewrites a
mark, so the old assessment stands until its age runs out.

The channel now follows actual work, not a switch: a radar emits only
while radar_up, a jammer only while its transmitter is on the air. A
silent, packed, failed or destroyed station is just a unit the flyby saw.

A pending wreck observation is durable; older saves without its flag read
as before, every look being of a unit alive when it was seen.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:12:35 +03:00
chexit 24b8cce11b Update the WASM contract for radars configured at deployment (#144)
build / mod (push) Failing after 1m21s
The real-.hmod scenario still expected the pre-#134 role switch to
retune radar 4 and return its role as feedback. After #134 the profile
is chosen at deployment and dispatch refuses the old syntax, so step 14
failed with no feedback.

Both stale checks now expect the intended refusal, naming
deploy radar_search|radar_track|radar_height and on/off. The deployed
station is not transformed back for the test.

Verified with python3 tools/airdef.py test-wasm on the pinned host
2bcce64236 and the real airdef.hmod: 30 steps pass.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 08:57:53 +03:00
chexit 502d94c528 Spend the world overlay's marker budget on targets in frame (#141)
The overlay clipped the network's tracks to the nearest 64 by distance
before projecting them, and the truth and interceptor layers the same way.
A crowd behind the camera filled the budget, so a raid could show nothing
even with a target right in front of the player; the native reproduction
(one contact ahead, 64 behind) came out with zero markers and a header
saying all 65 were out of frame.

Now visibility comes before the draw budget. Each layer orders its
candidates nearest first, projects at most MAX_SCAN = 4 x MAX_MARKERS of
them (bounded work, no sort of the whole picture beyond that prefix), skips
those the frame does not hold without spending a marker, and draws the
nearest MAX_MARKERS visible ones. Each layer keeps its own draw budget, so
the interceptors and the truth markers cannot crowd out the network's.

The header separates the two ways a target stays unmarked: "за кадром"
(behind the camera or past an edge) and "сверх бюджета" (past the scan or
draw budget), alongside "в кадре".

Regression tests: 64 behind plus one ahead for the network, truth and
interceptor layers; a mixed crowd proving the nearest visible keep the
markers and the farthest is budget-capped, not offscreen; the projection
count bounded by MAX_SCAN; every case stays inside the HUD's 1024 shapes.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 08:57:53 +03:00
chexit a983177d34 Draw a held-key world overlay of targets through the drawn camera (#132)
build / mod (push) Failing after 59s
Holding C draws square markers over the targets the player can see, each
with the class the radars estimated and the distance; an unidentified
track stays a "?", never the target's type. Stale forecast tracks fade
orange and say their age, the player's own interceptors wear small yellow
squares, and the sandbox truth mode adds white markers of the real drones
apart from the network's estimates. Letting the key go clears the HUD.

The markers project through the camera of the last drawn frame
(render.project, API 31), so they sit on the world as it is drawn and
follow the view frame by frame; the overlay stays off under a replay, the
grid J, the monitor K and the map M, which own the screen themselves. A
full raid stays inside the HUD's 1024-shape budget, keeping the nearest
markers and counting the rest behind the camera or past the edges.

Bump the engine pin to 2bcce6423 (API 31, render.project) and name API 31
in the capabilities diagnostic to match.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 00:39:17 +03:00
chexit 795b1b2fcf Merge recon flights and partial reports into the classified radar picture (#135)
build / mod (push) Failing after 1m5s
Co-Authored-By: Kimi Code <noreply@moonshot.ai>

# Conflicts:
#	airdef-mod/src/sim/mod.rs
2026-11-21 00:07:39 +03:00
chexit c4e002ed8b Add the recon UI and diagnostic layer to the smart enemy (#135)
The core recon flights and partial reports (9d8f3da57) had no player-facing
or diagnostic consumer: enemy_picture().recon/recon_sorties were read only by
core tests. This adds the missing layer on top, without touching the mechanics,
models or textures.

- Map: a tracked recon aircraft is a recognisable yellow hollow diamond with a
  "разведчик" label, a role line in the selection panel and a filter legend; in
  the sandbox truth mode it gets an amber marker of its own.
- Battle UI: the summary panel and the map show the flight's coarse phase
  (разведка → донесение → завершение) only while the player's network actually
  holds a recon aircraft — what the visible aircraft are doing, not what the
  enemy learned. The truth mode adds a recon count line.
- Diagnostics and after-action review: /airdef recon and the menu page
  "Разведка противника (разбор)" (from Main and Replays) list the enemy's marks
  best-first with the reason each outranks the rest — priority = freshness×4 +
  quality×3 + observed role (recon::priority_parts, cross-checked against
  Mark::priority by a test) — plus the sortie phases and the drones aimed at a
  mark. The omniscient enemy picture is never shown in the normal HUD; it is
  explicit debug/review only.

recon_view reads only the current report types (EnemyPictureReport, ReconReport,
ReconSortieReport); the sim side only widens visibility and adds priority_parts
and the is_recon_drone/recon_status read helpers. Tests: recon_view, panel,
command tree, priority_parts cross-check. README and IMPLEMENTATION-STATUS updated.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:59:45 +03:00
chexit 12a706fb67 Refine the network track's class from the optical look (#136)
build / mod (push) Failing after 1m25s
- ClassEst::step_optical: the shared estimate's rule for one passive look —
  an unsure look (over OPTICAL_CLASS_MAX_UNCERTAINTY) names nothing, a sure
  one names a class, firms an agreeing probable, replaces a contrary guess
- Track::refine_class_optical: the minimal common method — class only; the
  plot, age, source, quality and own fire rights stay untouched
- Sim::apply_optical_classes: the explicit adapter, fed by each observation
  made this tick through OpticalObservation::estimate; a relay of the
  refined track carries the class as it was and gains nothing from it
- the post still holds no track, emits nothing and authorizes no shot;
  the refined class reaches the existing #133 track UI through the picture
- tests: network refinement, unsure look, relay/stale look add no
  confidence, equal observables refine equal classes, the step rules

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:55:28 +03:00
chexit 8550de16f8 Finish the optical post's network cue and edge cases (#136)
- a radar's fresh track reaches a post as a cue only: it points the head
  but never enters the post's tracks, seen or own set
- a searching post's sector follows the turning head, not the fixed base
  heading; switching contacts drops the old contact's picture
- dead and blinded posts spend no probe budget and never observe
- the icon alias is part of the generator, so the placeholder item uses
  the radar texture without a duplicate PNG or a hand-written asset
- part diagnostics read "Опт" for a passive post's sensor
- tests: cue wiring, turning sector, contact switch, dead post, graphics
  preset; generator alias

Cherry-picked from 3697a1764aec7a7bdc6311918453dd51e26ecabf onto the
#132/#133/#134 base: the cue-wiring test's track literal now carries the
shared class/source/product/quality contract instead of a DroneKind.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:38:32 +03:00
chexit 245aceb434 Add recon flights and partial reports to the smart enemy (#135)
A smart raid may send a small, bounded flight of unarmed Gerbera aircraft
ahead of its strike. They fly physically through zones round the marked
objectives (and revisit a doubtful mark when nothing is unchecked), look
at units inside a zone, and radio home an area, a public category, the
channel, age and quality only after a delay and only while the aircraft
is alive. A sortie lost before its report sends nothing; marks already
delivered stay, and the picture remembers them across raids.

The planner now reads recon marks as well as disclosure contacts. A mark
carries a synthetic id, an area, a category and a radar role only once a
second independent look refines it -- never a real id, SamKind, exact
point, health, magazine or link. Aims are chosen by observed role,
freshness and quality; a fresh modest mark can outrank a stale doubtful
big one, and a hidden unit is in neither list. In-flight recon aims keep
their old area: hidden moves, re-roles and damage do not rewrite a mark.

Bounded assignments, the route-job queue, the original wave objectives
and the no-eternal-pause rule are preserved. Recon aircraft take ids from
their own range, do not spend the strike's combat RNG and are not part of
the strike's replay. Save/load keeps marks, sorties, pending reports and
checked zones. No new models, textures or weapons.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:36:00 +03:00
chexit e5ee15a2ca Add passive optical observation post (#136)
- new Optical unit kind with its own catalog row and deploy item
- bounded one-contact line-of-sight checks against land and blocks
- day/night reach and hold timing; obstacle and unknown geometry block sight
- independent class observation with source, time and uncertainty, never DroneKind
- map/monitor/panel statuses and a line to the selected contact
- tests: day/night, wall/unknown, ageing, no kind leak, bounded work, passivity

Cherry-picked from 3ae21123964a9d3234bb2b3efc9ff926d64fc77d onto the
#132/#133/#134 base: the cue test's track literal now carries the shared
class/source/product/quality contract instead of a DroneKind.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:33:32 +03:00
chexit 53fbeced22 Cover radar profiles over a ridge (#134)
build / mod (push) Failing after 28s
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:13:38 +03:00
chexit e1b09f696f Give the two-raid scenario room for the last contact (#134)
The maximum menu raid keeps a supersonic contact in the air past 5000 ticks under the new fire-authority rules; the recording closes only when the sky is clear. Run the scenario to 8000 ticks, still well inside its 20-minute cap, and keep the replay assertion.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:13:32 +03:00
chexit 858735a4c6 Implement the first full radar-profile slice (#134)
Give the separate radar three real profiles over SamKind::Radar and the
typed catalog variants:

- radar_search: coarse, slow, long-range search plots; no fire authority.
- radar_height: raised mast, local refinement of low plots; no fire authority.
- radar_track: local search, fast revisit, two refined/fire channels.
- radar_multi remains the compatible universal profile, not best everywhere.

Tracks now carry the measuring station, product (search/refine/fire), and
quality (separate from identification), and keep the station's own plot when a
fresher network relay replaces the published position. A relay never refreshes
the measurement or authorizes a launch. Ordinary launches need the battery's
own confirmed fire plot; launcher-only batteries use a supporting radar's own
plot, and the existing heavy far shot keeps its cue-radar exception.

Per-tick refinement/fire work is bounded by profile channels and local search
radius. Off, damage, network and save/replay behavior are preserved: new saves
write the stable profile ID, old role-only lines migrate, and embedded SAM
radars keep their own fire authority. The deploy menu, status lines, map,
monitor, radar scope and /airdef why explain the profile, source, age, quality,
channels and refusal reason.

Models/textures are untouched: all profiles reuse the existing radar
silhouette (the separate art zone remains for its owner).

Tests: profile single/pair/full scenarios and duplicate station, channels,
relay source/age/quality, Off/damage, save migration, replay, embedded and
Multifunction radars, catalog/generator checks, airdef-mod suites, core lib
(non-balance on one thread; the four active balance tests in release) and core
scenarios.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:11:12 +03:00
chexit ac7521936d Estimate a track's class from its measurements, not from the target (#133)
build / mod (push) Failing after 1m18s
A radar track is what the network measured, and it never carried the
target's own answers: the tactical Track loses `kind: DroneKind` and the
true velocity, and gains what the measurements say instead.

- Track now holds a ClassEst (unknown / probable / firm) plus an observed
  velocity: none from the first blip, then the change of the measured
  places between real measurements, smoothed so one noisy pair does not
  flap the class. The classifier's bands sit between the game's speed
  clusters (Class::of_speed); a new contrary measurement replaces the
  hypothesis, an agreeing one firms it.
- The class estimate is separate from track confirmation (Track::ident):
  a track can be confirmed with its type still unknown. The estimate
  grows only on real measurements — a forecast and a relayed copy add
  nothing — and it travels with the measurement it grew from, ageing
  with the track and gone when the track drops.
- Roles, last chance, the reserve and the interceptor count read the
  estimate, never the target's class. Explicit policy for the unknown:
  an unidentified track stays a candidate under the general rules (and
  the system with no roles holds its fire at everything); the map, the
  monitor, the summary panel and /airdef why read the same estimate and
  name the reason — «Трек подтверждён · тип не определён», «вероятно
  крылатая ракета». The exact model stays in the sandbox's truth mode.
- A gun or a launcher lets go of a target that classified out of the
  roles since it was taken; a first blip no longer rules a contact out
  as a threat to guarded objects (it has no measured course yet).

Old saves and replays are untouched (tracks are derived, not persisted);
the simulation stays deterministic (the classifier is pure arithmetic on
the measurement noise). The doctrine/first-blip/last-chance tests gained
classified tracks where the contract provably changed; new tests cover
the classifier's steps, kind-independent estimates, first-blip blindness,
and relays and forecasts adding no confidence.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 22:55:36 +03:00
chexit 95739c95b1 Finish radar truth HUD layout and document target modes (#132)
build / mod (push) Failing after 33s
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 22:08:46 +03:00
chexit d302204649 Make map and radar targets legible with an honest hover (#132)
- mini radar: class-shaped blips that merge into one with a count
- map: larger track markers and trails, hover card with distance, type,
  status, target and interception
- explicit network vs sandbox truth: true drones, routes and aims drawn
  apart from the network tracks, with their own trails

Co-Authored-By: Kimi Code <noreply@kimi.com>
2026-11-20 22:08:46 +03:00
chexit 1e2d5dd0c0 Record #126 first stage: retained mod-model meshes, measured
build / mod (push) Failing after 55s
Engine a861c1ed2 (kimi-work-124), based on ed751714e: mod-model faces resolved once per pack generation, frames only transform and light them; motion #124 from the same faces; counters and span; reload/unload invalidate the cache. HD-RENDERER status + section, and docs/measurements/issue-126-first-stage with the A/B method and numbers (M5/Metal, Polygon raid: entity_geometry CPU 5.71 -> 1.57 ms avg, prepare 23.5 -> 7.05 ms; static scene pixel-identical; reload/unload smoke). Not GPU instancing; 5600X/3060 acceptance pending. Issue #126 stays open.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 21:46:46 +03:00
chexit 80d0cc9c43 Add native wgpu ray-query capability probe (#125)
build / mod (push) Failing after 1m21s
Stage 1 of #125: prove or disprove real hardware ray-tracing support without
touching the client renderer. The probe pins the same wgpu 30.0.1 stack as the
engine, including its vendored third_party/wgpu-hal patch, builds one BLAS/TLAS
and traces a 16x16 ray-query compute frame, checking every ray against a CPU
point-in-triangle expectation.

Verified on macOS aarch64, Apple M5 / Metal: BLAS/TLAS and the ray-query
pipeline build, 32 hits and 224 misses all match, exit 0. RT_PROBE_BACKEND=gl
reports no RT adapter and exits 2; RT_PROBE_NO_OPTIN=1 shows request_device
rejects EXPERIMENTAL_RAY_QUERY without the experimental opt-in and exits 2.

tools/rt-probe/target/ is ignored; the probe is a standalone workspace and is
not wired into the game build.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 21:34:07 +03:00
chexit c59bfe9e54 Catalog typed battery variants (#91)
The battery deploy pieces (s400_launcher, s500_launcher, radar_search/
track/height) were described three times: the menu table and the
configuration match in lib.rs, and a chained id list in commands.rs. One
catalog decision instead: catalog/content.json gains a variants section
(mode/role reuse the existing SamMode/RadarRole save keys), gen_catalog.py
generates catalog::UnitVariant rows, and the loader rejects duplicates,
unknown kinds/modes and id collisions with kinds or items. The battery
menu, its click handler and the deploy completion read the generated
table; the historical row order and labels are unchanged.

No variant carries its own balance: per-variant ammo profiles stay open
pending a confirmed profile and an explicitly labelled game abstraction
(PAC-3 note on #91), so no new specs, no new matches and no save/replay
change - a variant is only a deploy key over the same kind.

Checks: gen_catalog.py --check and gen_models.py --check clean, the
python catalog/asset and sound tests pass, airdef-core 234 unit + 8
scenarios, airdef-mod 69 unit + 1 boundary + 5 scenarios (save/load and
state round trips included), zero failures.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 21:34:07 +03:00
chexit 306af49744 Move battery status text to the presentation adapter
Sam::status, Comps::describe/worst and Sam::parts_text formatted
player-facing Russian in the simulation. The adapter now owns that
text: battery_view::sam_status for the panel and map, why_view::parts
and why_view::worst for the monitor and the status line. The core keeps
the data and gains only the accessors the adapter needs
(preparing_cell, public cells/reload_time/magazine/gun facts).

Texts are unchanged; the adapter tests pin the existing strings.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 21:34:07 +03:00
chexit 60f1bf0fd8 Record the Windows DLSS acceptance build and remaining runtime check
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-16 13:00:39 +03:00
chexit e194971867 Document Visual C++ runtime needed by the DLSS test build
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-16 12:56:32 +03:00
chexit 7ae0c5bbba Add Windows DLSS A/B test launchers and acceptance guide (#124)
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-16 12:55:10 +03:00
chexit 217e3ac886 Add feature-gated DLSS SR proof of concept (#124)
Advance to engine ed751714e. Document the optional SDK build, ordered color conversion/submission, native fallback and the remaining MSVC-link and RTX-runtime acceptance.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 22:10:32 +03:00
chexit f33b799551 Record previous-frame motion for mod models (#124)
Advance to engine 7a73e8d26: separate previous-position streams and a depth-read-only motion pass for mod models, with matching alpha cutouts and a debug view.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 21:06:02 +03:00
chexit d8cb98a964 Keep radar target blips above the player arrow
Draw the player marker before network tracks so a close blip is not hidden. Add a shape-order regression and verify a live raid with truth disabled.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 18:25:33 +03:00
chexit e59c49e3bf Blend HD shadow cascade filters at the near boundary
Advance to engine 17382445a and document the six-block near/far transition verified on the forest aerial view.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 18:04:24 +03:00
chexit 9664783b17 Add dense motion foundation for temporal upscaling (#124)
Advance to engine c962cd472. Document the render-pixel current-to-previous contract, native TAA/TAAU consumer and the remaining DLSS/object-motion/linear-HDR work.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 17:49:23 +03:00
chexit 3db1b73d64 Reuse oversized renderer staging buffers (#130)
Advance the engine to 94b572cd2, backporting upstream f7b77fbc8 with its GPU growth/readback regression. Keep API30 unchanged.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 17:27:17 +03:00
chexit 367c7f4ac3 Bound recorded SAM poses under the WASM memory cap (#122)
Thin old SAM keyframes in place, reduce allocation capacity and adapt later sampling when a recording exceeds its fixed pose budget. Preserve recent poses and cover the full ten-minute window in native and real WASM stress tests.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 17:21:48 +03:00
chexit e7934a1ebb Give the enemy a structured intent and a durable route queue (#127)
build / mod (push) Failing after 22s
release / windows (push) Failing after 2s
Stage 2 of #127. A smart drone now carries why it is aimed where it is
(Intent: plan, sead, react, replace) apart from the aim bookkeeping
(unit, since, switches, confidence). Assignments are throttled per
adaptive tick and per contact, a fresh disclosure replaces an aim only
after a hold, within a switch cap and when the change is worth a new
route, and a killed aim is replaced as a separate, lower-priority
decision. The queue is bounded and taken by priority (plan > sead >
react > replace); unknown land is no longer free in a replanned route.

The autosave now carries the air state: the drones in flight, the launch
queue, every pending job with its id, aim, unit, version, priority,
intent and relief version, the contacts the jobs were chosen from and
the relief snapshots they plan over. The format is a versioned `air 1`
section; older saves read as before, scenarios do not carry the sky,
stale, ghost and duplicate jobs are cancelled on load, and the section is
bounded (512 drones, 512 route points, 4096 contacts, 8 reliefs, 900 KB).
A periodic save waits while a raid is only being planned.

enemy_picture() now explains targets and pending jobs (aims, aimed_by,
pending_jobs, reason, work_per_tick) in English, and intel_bench records
the queue and intent evidence next to completion, losses and failures.
2026-11-06 18:36:20 +03:00
chexit 8fc10c07a1 Give the enemy a last-observation picture and observed-capability pricing (#127) 2026-11-06 18:00:08 +03:00
chexit 0b645d77e9 Normalize #129 measurements and pair the cold-launch capture
build / mod (push) Failing after 22s
Write both measurement CSVs with LF instead of CRLF so the range no longer
fails `git diff --check` on trailing whitespace; the parsed data is unchanged.

Add a matched before/after capture: one copied world, scenario and seed, the
same client/director and the same export command. The baseline hmod is built
from dc36d67 and the final one from the #129 code. Both launch shots start at
frame 94; the first centre illumination is frame 101 (0.233 s) before and
frame 121 (0.900 s) after, against the 0.25/1.00 s cold rules. Raw probe,
hashes and the measurement method are in issue-129-pair.json. The two MP4s
in docs are CRF26 storage copies; the CRF16 originals stay in the scratch
homes.

These are replay exports, not live footage. The capturing agent still has no
image input, so composition is left for human review; the frames before the
launch are not pixel-identical because these are two live sessions.

Co-Authored-By: Kimi Code <noreply@kimi.com>
2026-11-06 13:35:35 +03:00
chexit 56093b3a55 Record the #129 balance and the cold-launch capture
The stage contract and profiles are in 4b013fb. This commit adds the
measured balance (the #120 grid on identical seeds and the 12-seed raid),
the replay/export video with four stills, and updates the user and handoff
documentation. The visual files are provided for human review; the agent
that captured them has no image input and checked only the encoded
parameters, shot boundaries and the first large plume.

Co-Authored-By: Kimi Code <noreply@kimi.com>
2026-11-06 13:35:35 +03:00
chexit 1261c30724 Stage the cold launch and spool every interceptor's motor (#129)
The interceptor's launch is one sequence: the cap opens, the round is
thrown out unlit and slows under linear gas drag (`cold` ticks), the motor
lights where it has reached, it turns with a growing rate while thrust
spools up (`boost` ticks), and full guidance starts only at `cold + boost`.
A rail launch lights at once but spools over the same `boost` ticks; the
electric P1-SUN has no rocket spool or plume.

S-400/500 now hold the unlit ejection for 20/24 ticks (1.00/1.20 s at
20 Hz); IRIS-T/Tor keep shorter 8-tick throws. Ignition, its sound, flame
and recorded MotorIgnition event all use the missile's current position.
The RM48U strike follows the same 20-tick choreography, counts the throw
in its flight time and starts its recorded smoke at ignition.

Maximum speed, turn, accel, pk and every collision rule are unchanged.

Co-Authored-By: Kimi Code <noreply@kimi.com>
2026-11-06 13:35:35 +03:00
chexit a592ece6e3 fixup! Keep unfinished retarget routes in a bounded job queue (#127)
build / mod (push) Failing after 22s
The planner caches were keyed by (kind, relief Arc pointer, start, aim): two jobs with the same relief but different known-units snapshots could reuse each other's price grid and route. Key relief sampling by its Arc pointer but key prices and routes by the whole knowledge version: adaptive tick plus the known-units and relief Arc pointers. Regression creates two same-start, same-aim jobs on one relief with different known snapshots and checks their routes differ, while a third job of one version still reuses the route cache. Core release, adapter and WASM contract pass.
2026-11-06 12:57:36 +03:00
chexit a47812aadd fixup! Keep unfinished retarget routes in a bounded job queue (#127)
The relief snapshot was still global: a smart plan finishing while a retarget job waited could replace Sim::known_relief, so the pending route was planned on the newer map. RouteJob now carries Arc<KnownRelief> for its knowledge version; Sim::known_relief keeps the same Arc only to seed new jobs. retarget_relief reads the job's snapshot, and relief sampling, price grids and route caches are keyed by that version. The new regression makes a job wait, swaps the global relief for another grid with a wall, and checks the pending route and sample stay those of the original version; outside its grid is Unknown. Core release, adapter and WASM contract pass.
2026-11-06 12:57:36 +03:00
chexit 6f7b041c8b Keep unfinished retarget routes in a bounded job queue (#127)
A mass retarget used to clear every selected drone's route before the planner's per-tick work ran out: the rest flew straight for ever. Route jobs now carry the drone id, new aim, target unit, knowledge version and the intel snapshot, stay in a FIFO across ticks and are drained under the same WORK_PER_TICK. An old safe route is kept until its replacement is ready; a cancelled job falls back to a straight run. Jobs are replaced in place per drone, cancelled when the drone or unit is gone, and retarget routes reuse the original plan's known relief. An in-flight drone no longer turns to a unit behind its turning circle. Core release tests, adapter tests and the real WASM contract pass.
2026-11-06 12:57:36 +03:00
chexit dc36d67eb7 Unblock supply trucks from an impossible RM48U return (#128)
build / mod (push) Failing after 21s
step_supply sent every free truck into the return branch whenever any
S-400 had a pending ground_return, even when that return could not
proceed (the system moving, damaged, reloading or preparing, its round
already claimed by another truck, the route marked unreachable, or no
depot with room). The branch then found no target, cleared the job and
stopped the truck, so independent typed supply requests starved.

The return now keeps its priority only while it is executable: a
carrier holding a reserved round looks for a depot with room in reach,
an empty one for a system ready to hand a round over. Otherwise the
claim stays untouched and only real RM48U demand (a requesting system
with depot stock, or ground rounds aboard for one) pulls the truck
into the typed supply branch; without such demand it holds its watch
exactly as before. Redirecting a reserved round to a waiting request
clears return_cargo once the last one leaves the truck, and a stale
return_cargo with an empty hold no longer sends the truck to a depot
handover it cannot complete.

Regressions: three sim tests (moving claimant, pickup claimed by
another truck with damaged/save-restore phases, unreachable route) and
one full-drive lib test with a mid-flight state round trip; the rounds
are conserved in every phase and the actual return completes once the
claimant is back. All three sim tests fail on the old code.

Checks: core release 200 passed/8 ignored + 8 scenarios; adapter
67 unit + 1 boundary + 5 scenarios; real WASM test-wasm 30 steps.
2026-11-06 11:11:59 +03:00
chexit d45629ae29 Fix the UI-event fuel trap on a second large raid order
build / mod (push) Failing after 22s
The Windows log for #122 showed the mod stopping in the UI event
(fuel budget 1e9, remaining 0) with known_units <- order_raid <-
launch_wave <- ui_select: order_raid recomputed the planner snapshot
known_units() for every drone, and the snapshot itself rescanned the
whole force and the dedup list per intel entry. A second big Smart
order cost drones x intel-log x force-size inside one event.

Reproduced in actual WASM with measured per-callback fuel through the
exact ui_select(BTN_LAUNCH) handler (diagnostic guest, trigger.patch):
before, a 111-drone second order at revealed=13172/known=144 exhausted
exactly 1e9 and stopped the mod (an 11-drone order at the same state:
247805865); after, the same scenario passes with max command fuel
32946177/1e9, failures=0, and /stats at tick 2602 byte-identical.
A stacked single-point layout dies to one warhead (known=0, cheap
order), so the scenario deploys spread clusters with a moved player.

Fix: one known_units snapshot per order_raid passed to radar_strikes
and choose_target; known_units is a single O(log + force) set pass;
price_grid_on reuses its snapshot. Emitter/network targeting and
carrier choice semantics are unchanged (native equivalence test
against the former predicate; WASM checkpoint counters equal).
Limits unchanged; HD/recording untouched; wave size unrestricted.

Committed regressions: native snapshot-equivalence and
second-smart-order tests; the heavy WASM fixture now orders two Smart
raids through the wave screen's launch function (airdef preset +
airdef raid) with EW and a combat intel log, four accepted orders
asserted; the light contract covers preset and the empty-wave refusal.

Core release 195 + 8 scenarios; adapter 65 + 1 boundary + 5 scenarios;
light WASM 30 steps; heavy WASM 283 steps (tick max 182413686/300M,
command max 6939810/1e9, failures 0). Windows GUI acceptance remains
external and is not claimed.

Co-Authored-By: Kimi Code (Moonshot AI) <noreply@moonshot.cn>
2026-11-06 10:29:36 +03:00
chexit 61aaa0bf35 Record the Metal/offscreen camera picture acceptance
build / mod (push) Failing after 22s
The final engine 6a53a626c with the API30 AirDef build was run in the
real game (macOS, Apple M5, Metal, --offscreen, a clean HORIZON_HOME and
copied test worlds), not only in the sandbox: the monitor and the film's
main view report ready with the picture actually drawn (screenshots show
the panel and picture area, not a registered target), an empty set-views
drops the request, a world change bumps the generation and clears it, and
AirDef's next submission prepares the camera again in the new world.

Fixes nothing: no defect showed. It also records what the run does not
prove (a human visual check, Windows/other GPUs, two runs with the same
local id on the GPU, a mod reload on the GPU), the per-tick
set-views/set-main-view ordering that can honestly read awaiting-frame
between tick and note (not flicker), and that a title trip back into the
same world keeps the request because the generation is per world.

Co-Authored-By: Kimi Code <noreply@moonshot.cn>
2026-11-04 21:10:34 +03:00
chexit 9217f9a5cc Report camera readiness in /airdef capabilities
Pin the engine at 6a53a626c (API 30) and show render.camera-status: the
calling run's set-views cameras, whether the last noted frame was a world
frame, the request's world generation, each camera's reason and the run's
own main-view selection. As the other lines, this is a host milestone:
availability, request, preparation and why, not a GPU frame or a visible
picture. A unit test pins the line: readiness stays per camera and apart
from the run's main-view selection.

docs/ENGINE.md, the 4 November continuation and the status table now say
what prepared means (a picture encoded into the camera's target, or a
world frame drawn from it as this run's screen view, only for the run
whose selection the screen used), the per-run/per-world resets, and what
remains: GPU acceptance.

Verified: python3 tools/airdef.py check (gitlink, packer, mod needs 30,
fork 30, game 30); test-wasm 27 steps; airdef-mod 65 unit, 1 boundary and
5 scenarios; python3 -m unittest discover -s tools 28 tests.

Co-Authored-By: Kimi Code <noreply@moonshot.cn>
2026-11-04 21:08:23 +03:00
chexit 46d2274c8d Measure the #120 balance grid across batteries, ranges and target classes
Wider same-seed sampling of the finite-burn/coast change: baseline 2689d93
(pre-#120) against the current tree, 6 variants x 8 seeds of a 46-drone raid
(batt10/20/50, near200, far1500, hills20). Harness-only: Result carries the
tally's fuse/expired/orphaned/energy_lost counts and a new ignored
sim::balance::issue_120_grid test; no simulation parameters changed.

Findings: kills are equal or up and leaks equal or down in every variant;
fuse misses drop (far1500 70 -> 38 over 8 seeds); hills terrain losses fall
(scrubbed 6 -> 2). MotorEnergyLost never fires in the 48 scenarios and
expired stays <= 1: coast ends before drag reaches the 25% guidance
threshold. Leaks stay concentrated in the ballistic/fast classes
(Iskander/Kinzhal/Kh22/Zircon). No confirmed defect, so no tuning.

Full airdef-core suite: 193 + 8 passed, 0 failed (baseline side 169 + 4).

Co-Authored-By: Kimi Code <noreply@moonshot.cn>
2026-11-04 21:03:01 +03:00
chexit 325119b726 refactor: validate specs without a per-kind name list
The armed/support check in load_specs named the ten armed kinds, so a new
unit type would still have required a code edit and repeated the coupling
#91 is removing. Drop it: optional missile/gun rows are still validated
generically, and the existing kind-coverage check against content.json
already ties specs to the catalog.

validate_specs now takes the document, content identities and sound
events, and a test shows a hypothetical unit kind is accepted from a
specs row plus its content entry alone. No data or balance changes.

Verified: gen_catalog --check fresh, test_gen_assets 10 tests, core
release 195 passed + 8 scenarios (7 ignored), adapter 64 unit +
1 boundary + 5 scenarios, WASM contract 27 steps.
2026-11-04 21:00:35 +03:00
chexit 0937ac9e05 fix: keep the P1-SUN motor voice at its played 1.6 pitch
The old engine_voice returned early for flame == 0 with
(DRONE_LANCET, 0.8, 1.6), so the later `P1sun => 1.7` match arm was
unreachable. The catalog migration mistook that arm for the played value
and stored 1.7, which changed the interceptor drone's flight sound.
specs.json is back to 1.6 and specs_generated.rs is regenerated.

Adds missile_engine_voices_keep_their_played_values, pinning P1-SUN to
(DRONE_LANCET, 0.8, 1.6) and M48N6 to (MISSILE_FLIGHT, 1.0, 0.88).

The continuation and handoff text now describe the early return instead
of the dead arm, and tools/airdef_assets/catalog.py gets its final
newline back.

Verified: gen_catalog --check and test_gen_assets, core release
195 passed + 8 scenarios (7 ignored), adapter 64 unit + 1 boundary +
5 scenarios, WASM contract 27 steps.
2026-11-04 21:00:35 +03:00
chexit ead87343d2 feat: generate simulation numeric profiles from catalog/specs.json
catalog/specs.json is now the single copy of the numeric rows for
DroneSpec, MissileSpec and SamSpec: speed, guidance, warheads, models'
parts, RCS, seekers, launch and motor sounds, mount drives, gravity,
the Oreshnik split height and logistics limits, plus the named part
sets. tools/gen_catalog.py generates airdef-mod/src/sim/specs_generated.rs
(included by mod.rs, so the mod and airdef-core compile the same rows)
and unit_specs_generated.rs (included by units.rs). The hand-written
spec matches are gone; DroneKind::spec, MissileKind::spec and
SamKind::spec read the generated constants.

load_specs validates the schema, sound references, kind coverage against
content.json, named-part references and unused rows. gen_catalog.py
--check already runs in the CI generated-assets step, so a JSON/Rust
drift fails the build.

Every value was compared with the literals at 632061d field by field.
The only mismatch was the P1-SUN motor voice pitch in JSON (1.6 instead
of the actual 1.7, the flame == 0 branch in voices.rs); the JSON was
corrected and behaviour is unchanged. Save keys, raid order, RNG and
gameplay traces are untouched.

Verified: core release 194 passed + 8 scenarios (7 ignored), adapter
64 unit + 1 boundary + 5 scenarios, WASM contract 27 steps, catalog and
model generators fresh, asset/sound/model-bound/report tests pass.
2026-11-04 21:00:35 +03:00
chexit abf3d76fdb docs: record the real MP4 acoustics check (#96)
Pairs of the same replay exported with acoustics on and off on the
scratch world (no HORIZON_NO_AUDIO): acoustics and capture ownership
both ready. The open field has no reverb send by design, so it shows
occlusion/air absorption only; the stone court's on-track is quieter
and darker, and its residual after a gain fit is low-passed and
stereo-decorrelated, i.e. the wet path. A clean reverb tail/RT60 in a
real MP4, echoes alone and listening remain open. No code changes.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-04 20:52:11 +03:00
chexit e6a7000440 docs: record the engine cleanup for failed film takes
Engine 60cc7b11d removes a failed or cancelled take's video, raw sound
and log, carries the log's last lines in the error, and only creates
<name>.mp4 after a successful finish. A real failing encoder on the
scratch world left no temporaries and kept the earlier film byte for
byte; successful audio and no-audio control films still verified.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-04 20:19:51 +03:00
chexit cec7257ea1 Pin the engine that frees a failed film take's files
horizon 60cc7b11d (on top of 57f8b2853, API 29) removes a failed or
cancelled take's video, raw sound and log, carries the log's last lines
in the error, and only creates <name>.mp4 after a successful finish.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-04 20:17:52 +03:00
chexit 503e6e29af Fix dynamic model lighting and document GPU comparison (#123)
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-04 17:53:10 +03:00
chexit 675967ce42 End the show when its world closes and verify the MP4 lifecycle (#89)
A frame hook ends an active film or export when the world is gone. The game
stops ticking at the title screen but keeps rendering, so an export used to
keep recording the title with its playback clock frozen (a sec=10 request
produced 3898 frames) and went on after re-entering the world. Session
cleanup runs once with WorldChange and cancels the capture.

Real short exports on a scratch home and world (pin 57f8b2853, API 29,
Metal): h264+AAC both 2.07 s with non-silent audio, reported frames equal
ffprobe nb_frames; cancel, SDK refusal, encoder failure and restart all
leave no capture running; 1920x1080 works. The engine still leaves
*.audio.raw and *.ffmpeg.log behind on an encoder error (game/film.rs).

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-04 17:44:28 +03:00
chexit 632061d2ad docs: archive clean API29 WASM fuel acceptance
build / mod (push) Failing after 20s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:23:22 +03:00
chexit 56339b076e docs: hand off catalog, model, API29 and acoustics continuation
build / mod (push) Failing after 20s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:21:29 +03:00
chexit c1a595b773 feat: expose light and sound processing diagnostics with isolated cameras
build / mod (push) Failing after 21s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:19:06 +03:00
chexit 914f723d1f Verify aircraft models as lit mod instances
build / mod (push) Failing after 20s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:16:47 +03:00
chexit d45d59df9f build: pin source-manager processing handshake
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:12:53 +03:00
chexit cfae0c1253 Refine cruise silhouette and document model comparisons
build / mod (push) Failing after 19s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:09:14 +03:00
chexit 53669887dd Refine Lancet silhouette with swept X wings
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:09:14 +03:00
chexit 4c7c887917 build: pin point-light handshake and mass acoustics fixture
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:09:14 +03:00
chexit daa9ed7cbc Use catalog sound identifiers throughout runtime
build / mod (push) Failing after 19s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:01:19 +03:00
chexit 1553976484 Share sound identifiers and metadata with resource generation
build / mod (push) Failing after 18s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 15:59:18 +03:00
chexit 0c870c10d5 Represent damage diagnostics as typed reasons
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 15:59:18 +03:00
chexit eea1b3692e Share aircraft and item catalog with asset generation
build / mod (push) Failing after 20s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 15:55:45 +03:00
chexit cb73cb7ccc Move world cache report to presentation adapter
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 15:55:45 +03:00
chexit 375fdf2d80 Separate battery status from player-facing text
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 15:55:45 +03:00
chexit 63aefc7621 test: record measured callback fuel in budget reports
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 15:55:45 +03:00
chexit d410e2c92d docs: archive the reproduced fuel failure and bounded cache fix
build / mod (push) Failing after 18s
Preserve the diagnostic trigger, scenario, before/after logs and scope of equivalent counters. Update ground strike guidance, Windows acceptance status and profiler semantics.

Co-authored-by: Codex <codex@openai.com>
2026-11-03 11:39:23 +03:00
chexit ab737e7390 test: verify empty nearby depot feedback in WASM
build / mod (push) Failing after 18s
Co-authored-by: Codex <codex@openai.com>
2026-11-03 11:34:02 +03:00
chexit 3b470ddc8a build: pin optional per-callback WASM fuel profiling
The opt-in test CLI reports measured guest fuel separately from host and GPU costs; runtime limits remain unchanged.

Co-authored-by: Codex <codex@openai.com>
2026-11-03 11:34:02 +03:00
chexit cbd6067e8f fix: explain empty strike stock and ground attack prerequisites
build / mod (push) Failing after 19s
Show typed depot cargo separately, identify an empty nearby depot, and document loading, reconnaissance, two ID namespaces and reverse pickup.

Co-authored-by: Codex <codex@openai.com>
2026-11-03 11:26:52 +03:00
chexit cc48302b36 Exercise two maximum menu raids with terrain replies
Co-authored-by: Codex <codex@openai.com>
2026-11-03 11:26:52 +03:00
chexit 1f28f8361f Bound height cache invalidation per explosion
Co-authored-by: Codex <codex@openai.com>
2026-11-03 11:23:47 +03:00
chexit 10f24b5df8 docs: record verified overlap stress and unresolved Windows report
build / mod (push) Failing after 19s
Keep the corrected historical coverage claim, archive the real flat-world WASM run, explain trap diagnostics and the small HD trail density change.

Co-authored-by: Codex <codex@openai.com>
2026-11-03 10:54:57 +03:00
chexit 293236490b test: freeze the exact budget fixture used by the runtime
build / mod (push) Failing after 17s
Derive synthetic terrain metadata from the fixture and copy the same bytes that were hashed before building.

Co-authored-by: Codex <codex@openai.com>
2026-11-03 10:49:21 +03:00
chexit bf8551e1a8 Run flat terrain scenario in budget report
Co-authored-by: Codex <codex@openai.com>
2026-11-03 10:43:01 +03:00
chexit 3afebae6bd Cover HD grid during overlapping raids
Co-authored-by: Codex <codex@openai.com>
2026-11-03 10:43:01 +03:00
chexit 326817db9a Add overlapping raids budget scenario with flat terrain
Co-authored-by: Codex <codex@openai.com>
2026-11-03 10:43:01 +03:00
chexit 8f5603847e test: pin real render-query fixtures and correct raid coverage claims
build / mod (push) Failing after 18s
Archive the original budget report as insufficient proof of overlapping raids. Pin callback/fuel diagnostics and an opt-in flat render world that services actual guest queries.

Co-authored-by: Codex <codex@openai.com>
2026-11-03 10:36:45 +03:00
chexit bd091e60df Exercise overlapping Oreshnik splits and recording
Co-authored-by: Codex <codex@openai.com>
2026-11-03 10:36:42 +03:00
chexit 296a64ffaa Exercise overlapping menu raids on answered terrain
Co-authored-by: Codex <codex@openai.com>
2026-11-03 10:34:31 +03:00
chexit a41a4d17cf Verify sequential raid requests in budget scenario 2026-11-03 10:32:31 +03:00
chexit 692ae77af7 Slightly densify missile smoke trails
build / mod (push) Failing after 18s
Co-authored-by: Codex <codex@openai.com>
2026-11-03 10:25:56 +03:00
chexit 19c53fda4c docs: record API27 readiness and reverse logistics verification
build / mod (push) Failing after 19s
Document capability milestones, budget limits versus measurements, real-game no-audio observations, reverse pickup reservation and the Windows stale-URL fix.

Co-authored-by: Codex <codex@openai.com>
2026-11-03 10:22:53 +03:00
chexit aab3e784b8 build: reuse the pinned engine target cache for its packer
build / mod (push) Failing after 18s
Co-authored-by: Codex <codex@openai.com>
2026-11-03 00:27:02 +03:00
chexit 8d5d0d1dd7 Test WASM budget report failure paths
Co-authored-by: Codex <codex@openai.com>
2026-11-03 00:25:28 +03:00
223 changed files with 96145 additions and 2395 deletions
+21 -2
View File
@@ -1,6 +1,8 @@
# На каждый пуш: только мод (.hmod, один для всех ОС) и релиз build-<номер> с ним.
# Раннер живёт на одной машине с Gitea и другими сервисами (2 ядра, 4 ГБ): сборка мода лёгкая —
# один поток компиляции, низший приоритет, без системных пакетов и без кэша target.
# Диск у раннера тоже общий с базой Gitea: 23.11.2026, дойдя до тестов, джоба уронила базу до конца прогона.
# Поэтому один закреплённый тулчейн вместо stable поверх него и без каталогов target тестов к моменту сборки мода.
# Игра-форк здесь не собирается: только по тегу версии (release.yml, Windows) и вручную (game.yml Linux, desktop.yml macOS).
name: build
@@ -22,9 +24,19 @@ jobs:
- uses: actions/checkout@v4
with:
submodules: recursive
# Не начинать, когда места мало: иначе сборка займёт диск до конца, а база Gitea на нём падает.
- name: Ресурсы раннера
run: |
df -h / | tail -1
free -m | sed -n '1,2p'
FREE=$(df --output=avail -BM / | tail -1 | tr -dc 0-9)
if [ "$FREE" -lt 4000 ]; then echo "::error::на сервере свободно ${FREE} МБ, нужно хотя бы 4000"; exit 1; fi
# Только закреплённый тулчейн из rust-toolchain.toml: stable ставился раньше и лежал мёртвым грузом.
- name: Rust
run: |
curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --target wasm32-unknown-unknown
CHANNEL=$(sed -n 's/^channel = "\(.*\)"$/\1/p' rust-toolchain.toml)
if [ -z "$CHANNEL" ]; then echo "::error::rust-toolchain.toml: не прочитан channel"; exit 1; fi
curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain "$CHANNEL" --target wasm32-unknown-unknown
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
# Без actions/cache: кэш-сервер раннера из контейнеров задач недоступен — восстановление
# падало по таймауту, а сохранение вешало «Complete job» на пару минут. Инструмент собирается заново.
@@ -32,21 +44,28 @@ jobs:
run: nice -n 19 python3 tools/airdef.py fork
- name: Проверка закреплённого checkout
run: python3 -m unittest discover -s tools -p test_engine_checkout.py
# Системный Python образа — externally managed (PEP 668): без --break-system-packages pip отказывает,
# и тесты со сборкой ниже вообще не запускаются. Контейнер задачи одноразовый, так что --user безопасен.
- name: Проверка generated assets
run: |
python3 -m pip install --user -r tools/requirements.txt
python3 -m pip install --user --break-system-packages -r tools/requirements.txt
python3 tools/gen_catalog.py --check
python3 -m unittest discover -s tools -p test_sound_catalog.py
python3 tools/gen_models.py --check
python3 -m unittest discover -s tools -p test_model_bounds.py
# После тестов их каталог target не нужен (модуль собирается под wasm заново), а на диске его место.
- name: Тесты ядра без SDK
working-directory: airdef-core
run: |
HOST=$(rustc -vV | sed -n 's/^host: //p')
nice -n 19 cargo test --target "$HOST"
rm -rf target
- name: Тесты мода
working-directory: airdef-mod
run: |
HOST=$(rustc -vV | sed -n 's/^host: //p')
nice -n 19 cargo test --target "$HOST"
rm -rf target
- name: Мод
run: nice -n 19 python3 tools/airdef.py mod
- name: Релиз
+1
View File
@@ -2,6 +2,7 @@ run-home/
.horizon-cache/
airdef-mod/target/
airdef-core/target/
tools/rt-probe/target/
__pycache__/
/out/
.DS_Store
+149 -40
View File
@@ -30,6 +30,14 @@ python3 tools/airdef.py all # получить закреплённый дв
python3 tools/airdef.py play # запустить (аргументы игры — после: --world "Имя мира")
```
`all` синхронизирует URL сабмодуля из `.gitmodules`, включая обновление со старого upstream.
Продолжение 4 ноября: [модели, границы ядра, общий каталог, API29 и массовая акустика](docs/CONTINUATION-2026-11-04.md).
Диагностика в игре: `/airdef capabilities` показывает доступность API, принятие запроса и
подготовку дыма, акустики и захвата именно этого мода. Подготовка не означает готовый GPU-кадр или MP4.
Для разработчика: `python3 tools/airdef.py test-wasm` — лёгкий ABI-тест;
`python3 tools/airdef.py test-budgets` — отдельный тяжёлый сценарий с JSON-отчётом.
Для разработки: `./install.sh` перегенерирует модели (`tools/gen_models.py`, нужен Pillow) и звуки
(`tools/gen_sounds.py`, нужны numpy и ffmpeg), собирает и ставит мод. Сгенерированные файлы лежат в репозитории,
так что для обычной сборки нужен только Rust.
@@ -52,27 +60,44 @@ CI: `.gitea/workflows/build.yml` на каждый пуш собирает то
| Развернуть Patriot / Гепард / Панцирь-С1 / С-400 / С-500 | ставит комплекс на блок под прицелом, носом по взгляду |
| Свернуть ПВО | убирает ближайший комплекс у точки под прицелом |
**Командный пункт:** клавиша **N** или `/airdef menu`. В нём список комплексов: выбери комплекс и включай или выключай классы целей
(дроны, реактивные дроны, крылатые, сверхзвуковые, баллистика), есть сброс по умолчанию. Там же кнопки «Командный
пункт» (сетка), «Налёт…» и «Огонь, ремонт, эффекты…» (огонь ПВО, ремонт всех, эффекты, разрушения).
**Меню AirDef:** клавиша **N** или `/airdef menu`. В разделе «Классы целей» можно включить или выключить
классы для каждого типа комплекса и сбросить их по умолчанию. В меню также открываются командный пункт,
налёты, повторы и настройки.
**Налёт (меню N → «Налёт: состав и запуск…»):** на первой странице состав — клик по типу листает число
(0, 1, 2, 3, 4, 6, 8, 10, 15, 20, 30, 40); на второй — готовый вариант («Рой Шахедов», «Массированный удар»,
«Баллистика», «Гиперзвук», «Орешник с прикрытием», «Подавление ПВО»), откуда (один сектор, два, со всех сторон,
волнами по типам), дальность старта, цели и **ПУСК**. Цели:
- *только объекты* — всё летит по отмеченным объектам (или по игроку, если их нет);
- *объекты и ПВО* — треть ударных средств бьёт по случайным комплексам;
- *объекты и ПВО* — часть ударных аппаратов бьёт по случайным комплексам. Баллистика летит по отмеченным объектам;
- *умный противник* — планировщик использует наблюдённые контакты и последние известные позиции комплексов: ведёт дроны и крылатые ракеты
маршрутами в обход зон поражения, низко, за рельефом и через мёртвые зоны; «Герберы» прилетают на 15 с раньше,
чтобы оттянуть ракеты; «Ланцеты» идут по Гепардам и Панцирям, Х-22/Циркон и часть баллистики — по дальнобойным
комплексам; на наблюдённые РЛС дальнего обнаружения выделяются 2–3 быстрых ударника (Х-22, Циркон, Искандер, Кинжал, затем Х-101,
Герань-3, Ланцет, Шахед; не больше четверти налёта); всё остальное стартует со сдвигом так, чтобы прилететь одновременно.
чтобы оттянуть ракеты. На технику вместе с наблюдёнными РЛС выделяется до четверти большого налёта.
Баллистика и остальная ударная группа идут по отмеченным объектам. В режиме волн группы прибывают с интервалами.
После налёта приходит отчёт: сколько сбито и прорвалось, ракет ПВО потрачено, комплексов потеряно, урон объектам.
**Оборона деревни** доступна из меню N или через `/airdef scenario village normal`
(`easy` и `hard` меняют бюджет и состав волн). Встаньте в деревне и выберите сложность.
Если целей ещё нет, мод отметит три точки по высотам местности рядом с игроком.
Можно заранее отметить ровно три целых объекта самостоятельно. По порядку отметок это штаб, лазарет и укрытие.
Расставьте технику и выберите «Начать оборону» или `/airdef scenario village start`.
Стоимость техники показывает `/airdef scenario village prices`. Через пять секунд начинается первая из трёх волн.
В паузах по 30 секунд можно тратить остаток бюджета. Боезапас, урон и запас складов сохраняются между волнами.
Для победы нужны уцелевший штаб и минимум 65 баллов. Целые объекты дают 50, 30 и 20 баллов соответственно,
повреждённые дают долю от этих значений. При потере всех трёх объектов сценарий заканчивается досрочно.
Сценарий можно остановить командой `/airdef scenario village stop`.
Она оставляет расстановку и уже начатый налёт в мире.
**Разбор прорывов** доступен из меню деревни, из меню повторов или командой `/airdef breaches [страница]`.
В истории текущего сеанса остаются последние 128 попаданий. Видны время первого замера РЛС, число запущенных
перехватчиков и состояние ближайших комплексов в момент перед ударом. После перезахода часть данных по
уже летящим аппаратам может быть неизвестна.
**Обнаружение.** РЛС видит цель не дальше, чем позволяют:
- её размер: дальность растёт как корень четвёртой степени из ЭПР — Х-101 и Ланцет видно примерно вдвое ближе, чем Х-22;
- радиогоризонт: низколетящую цель видно поздно (Шахед на 25 м — с ~250 м, баллистику — издалека);
- радиогоризонт: низколетящие цели обнаруживаются ближе, чем цели на большой высоте;
- рельеф и лес: за холмом цель не видна (каждый комплекс строит свой горизонт по 48 лучам; рельеф известен в
прогруженных чанках);
- вблизи (24 м) видно всё.
@@ -82,10 +107,13 @@ CI: `.gitea/workflows/build.yml` на каждый пуш собирает то
**Сохранение.** Комплексы, объекты, их повреждения и настройки сохраняются отдельно для каждого мира (и для каждого
сервера); уничтоженный комплекс остаётся остовом и после перезахода, пока его не отремонтируют.
Налёт в воздухе тоже сохраняется: дроны, очередь их запуска и незавершённые задания на маршрут
восстанавливаются, и перезаход не обрывает перенацеливание. Ракеты-перехватчики в воздухе и площадки
запуска не сохраняются; сценарий — стартовое состояние и налёт не несёт.
**Сеть ПВО.** Единицы обмениваются измеренными треками в пределах игровой связи; повреждение связи
сокращает её дальность. Можно поставить несколько С-400/С-500 без собственной РЛС и общие радары
поиска, сопровождения и мачтового обзора: N → «Разместить элементы батареи…».
поиска, сопровождения и мачтового обзора — отдельными пультами (`/airdef give` выдаёт `deploy_radar_search`, `deploy_radar_track`, `deploy_radar_height`) или командой `/airdef deploy radar_search|radar_track|radar_height`.
Поисковый радар даёт подсказку; огневой должен сам измерить цель, прежде чем разрешить пуск.
Старая сборная конфигурация сохранена. [Команды, источники и ограничения](docs/BATTERIES-AND-COLD-LAUNCH.md).
P1-SUN также использует чужие данные. Пушкам (Гепард,
@@ -96,17 +124,24 @@ P1-SUN также использует чужие данные. Пушкам (Г
не заменяет обязательное собственное сопровождение. Выключение не стирает старые сведения противника:
он продолжает использовать последнюю наблюдённую позицию, а пуски и РЭБ могут снова раскрыть технику.
**Логистика.** Пока нет ни одного склада, магазины пополняются сами, как раньше. Как только поставлен склад,
боекомплект считается: комплекс без ракет пишет «ЖДЁТ БК»; в 60 м от склада он перезаряжается прямо с него, а
**Логистика.** Боекомплект конечный с момента размещения техники. Комплекс с пустым боекомплектом показывает
«ЖДЁТ БК». В 60 блоках от склада он перезаряжается прямо с него, а
дальние обслуживают **ТЗМ**: заправляются на складе (2 перезарядки), сами едут к ждущим комплексам, ближайшим
первым, и возвращаются. Запас склада — 30 перезарядок, он виден в сводке. Склад и ТЗМ детонируют всем грузом.
первым, и возвращаются. ТЗМ ищет проезд с любой стороны получателя. Если объезда нет, машина может
уложить короткий мост или пандус из булыжника и расчистить до двух слоёв мягкого грунта. Строительство
требует разрешения на команды изменения мира. Запас склада — 30 перезарядок, он виден в сводке.
Склад и ТЗМ детонируют всем грузом.
Ударная **RM48U у С-400** — отдельный условный игровой боеприпас, который делит четыре ячейки
с ракетами ПВО. `/airdef ground-stock <склад> <количество>` задаёт конечный начальный запас
sandbox-сценария, `/airdef ground-load <С-400>` загружает одну ракету рядом со складом либо
создаёт заявку на доставку ТЗМ. Груз едет физически; снятая ракета ПВО возвращается на склад.
Заявка и груз сохраняются в пути. `/airdef ground-unload <С-400>` выгружает ракету у склада.
Заявка и груз сохраняются в пути. `/airdef ground-unload <С-400>` выгружает ракету у склада,
а вдали создаёт заявку на обратный вывоз ТЗМ. Одна ракета резервируется от пуска до забора;
`/airdef ground-cancel <С-400>` отменяет ещё ожидающую доставку или вывоз.
После забора ракета находится в машине и едет на склад. Отмена заявки не возвращает уже вывезенный груз в ПУ.
Без склада этот ударный боеприпас сам не появляется. Бук и остальные комплексы такого профиля пока не имеют.
Порядок подготовки, разведка и номера двух списков: [как ударить по ПУ](docs/GROUND-STRIKES.md).
**Перемещение.** **Пульт перемещения**: навестись на технику (выбрать), затем на точку на земле — она
сворачивается (С-400 и другие с вертикальным пуском дольше, Гепард и Панцирь быстро), едет по рельефу и
@@ -120,8 +155,11 @@ sandbox-сценария, `/airdef ground-load <С-400>` загружает од
**Умный противник учится.** Он запоминает, откуда его налёты сбивали, а откуда они прорывались, и следующий
налёт ведёт с лучшего направления; помнит комплексы, выдавшие себя пуском, и станции РЭБ, и во время налёта
перенацеливает ещё не взлетевшие Ланцеты и Шахеды на них; если цель-комплекс уничтожен, дроны идут к
следующему известному. Дроны под обстрелом прижимаются к земле.
может перенацелить часть ещё не взлетевших аппаратов. Удары по технике занимают до четверти большого
налёта. Баллистика на всех этапах сохраняет отмеченный объект. Если цель-комплекс уничтожена, выделенные
на удар по технике аппараты могут выбрать другой известный комплекс. Маршруты к новым целям достраиваются по бюджету планировщика в следующих тиках:
необработанное задание не теряется, старый безопасный участок остаётся до готовности нового, а дрон без
маршрута летит прямо только до ближайшего бюджета. Дроны под обстрелом прижимаются к земле.
**Ночь.** Исправные пушки с собственным свежим радарным сопровождением не теряют точность из-за темноты.
Цели освещают **прожекторы** (луч ведёт ближайшую
@@ -137,7 +175,11 @@ sandbox-сценария, `/airdef ground-load <С-400>` загружает од
тонмаппинг (ванильный диапазон не трогается, сжимается только то, что ярче). Источники передаются движку новым
API мода `render.set-lights` (до 512, плавно интерполируются), режим — `render.set-lighting`.
**Сетка J** после сбития ещё 3,5 с держит камеру на сбитой цели, и комплекс в это время не пропадает из сетки.
В HD дымовые следы ракет немного уплотнены; число сегментов и время появления/выгорания сохранены.
Это относится к ракетам ПВО, RM48U, крылатым, сверхзвуковым и баллистическим средствам;
дым пожаров и слабая дымка винтовых дронов остались прежними.
**Сетка камер** после сбития ещё 3,5 с держит камеру на сбитой цели, и комплекс в это время не пропадает из сетки.
**Повреждения.** Взрыв рядом с комплексом повреждает его: он хуже поворачивается, хуже видит и попадает,
дымит, ниже 35% горит. Уничтоженный остаётся горящим остовом, его боекомплект детонирует: чем больше ракет
@@ -156,10 +198,39 @@ API мода `render.set-lights` (до 512, плавно интерполиру
- камера комплекса: настоящий вид мира из точки комплекса (второй рендер форка), с зумом на цель — тепловизор
при сопровождении, в поиске днём цвет, ночью ПНВ; рамка захвата, дальность, высота, скорость и пеленг.
**Командный пункт ПВО (сетка):** клавиша **J** (или `/airdef grid`, или кнопка в меню N) — на весь экран сетка
до 8 комплексов: у каждого состояние, РЛС, живая камера, прочность и боекомплект. Если комплексов больше, показываются
самые занятые (стреляют, держат захват, сопровождают, горят), раз в 2 секунды; комплекс с монитора K — всегда.
Повторное J закрывает.
**Командный пункт ПВО:** клавиша **J** или строка «Командный пункт» в меню **N** открывает прокручиваемый список
всей развёрнутой техники. Кнопка фильтра перебирает роли и состояния. Для поиска по названию или номеру используйте
`/airdef post Панцирь` или `/airdef post 12`. Нажатие на строку открывает карточку. В ней видны текущая причина,
отметка и её источник. Из карточки можно открыть карту, камеру, историю решений и закрепить технику.
История показывает отказы на проверке, фактические выстрелы и известные исходы с отметкой, которая была у комплекса
на тот момент. По записи завершившегося налёта можно открыть соответствующий кадр повтора.
История живёт вместе с повторами текущей игровой сессии. В ней доступны последние 128 записей выбранного комплекса.
Та же карточка доступна с выбранного маркера на карте **M** и по **I** при открытом мониторе **K**.
В мире от первого лица наведите прицел на видимую часть техники на расстоянии до 24 блоков и нажмите **I**.
Если между прицелом и моделью есть блок, карточка по наведению не откроется.
**Веб-пульт для планшета:** живая карта, карточки техники, архив налётов и запуск сценариев с отдельным доступом
оператора. Запуск на ПК командой `python3 tools/airdef.py web`. [Подключение планшета и режимы доступа](docs/WEB-PANEL.md).
**Сетка камер** открывается отдельной кнопкой в списке или командой `/airdef grid`. В ней до восьми живых
камер со статусом, РЛС, прочностью и боекомплектом. Камеры подбираются по активности каждые две секунды.
Закреплённый комплекс получает приоритет, а при отсутствии закрепления приоритет у выбранного на мониторе K.
**Тактическая карта:** клавиша **M** открывает общую карту. Цели обозначены крупными отметками с классом,
курсом и измеренной траекторией; наведение мыши показывает дистанцию, тип, состояние трека и перехват.
По умолчанию доступны только данные сети РЛС. **T** переключает явно подписанный режим «Истина» для
песочницы: в нём белые рамки показывают даже незамеченные аппараты, а жёлтый пунктир — их цель и будущий
маршрут. Этот режим не меняет боевую логику.
**Обзор целей поверх мира:** удерживай **C** — вокруг видимых целей появляются квадратные метки с краткой
строкой: класс, который оценили РЛС (неопознанная цель — «?», без утечки типа), и дистанция; устаревший
трек-прогноз оранжевый и помечен возрастом. Свои перехватчики — маленькие жёлтые квадраты. Это данные сети
РЛС, как на радаре и карте; в режиме «Истина» (`/airdef truth on`, T на карте) добавляются белые рамки
реальных дронов с их настоящим типом — отдельно от сетевых оценок, чтобы видеть расхождение. Отпустил
клавишу — метки исчезли. Метки достаются ближайшим из видимых целей: цель за камерой или за краем
экрана бюджет кадра не тратит, а заголовок показывает, сколько целей в кадре, сколько за кадром и сколько
не поместилось в бюджет. Метки проектируются через камеру последнего отрисованного кадра (`render.project`,
API 31 форка) и следуют за взглядом покадрово; поверх повтора, сетки камер, монитора K и карты M обзор не рисуется.
**Повторы.** Каждый налёт записывается сам: с первой цели в небе до момента, когда небо 5 с чисто
(хранятся 3 последних). Меню N → «Повторы…» или клавиша **R**:
@@ -169,7 +240,12 @@ API мода `render.set-lights` (до 512, плавно интерполиру
целью, потом за перехватчиком (или смотрит из пушки, со стороны на прилёт), в момент сбития время замедляется;
- **полный повтор** — весь налёт, камера-режиссёр сама выбирает, за чем следить; колесо — перемотка, стрелки — скорость;
- **лучшие моменты** — нарезка до 8 самых интересных событий (перехват баллистики и гиперзвука, поражения
объектов, потерянные комплексы, разделение «Орешника») с титрами и замедлением; колесо листает моменты.
объектов, потерянные комплексы, разделение «Орешника») с титрами и замедлением; колесо листает моменты;
- **цепочки боя** — меню N → «Повторы…» → «Цепочки боя»: по каждому контакту короткая строка
«отметка → передача → захват → пуск → исход» с записанными шагами и их временем. Можно отобрать
цепочки по комплексу, прорывы и контакты без записи пуска. В длинном списке можно листать страницы.
Нажатие на строку открывает клип исхода или карту налёта на моменте пуска или отметки.
Текстовый список открывается командой `/airdef chains [номер батареи]`.
Повтор идёт на весь экран с леттербоксом; звук слышен так, как его слышала бы камера. Управление (подсказка
показывается в начале, после нажатия и на паузе): **← →** — перемотка на 5 с (в нарезке — соседний момент),
@@ -179,7 +255,7 @@ API мода `render.set-lights` (до 512, плавно интерполиру
Чтобы в повторах и камерах комплексов была видна земля далеко от игрока, мод включает дальний ландшафт
(48 чанков, упрощённый); выключается в меню N → «Огонь, ремонт, эффекты…» → «Дальний ландшафт».
Клавиши N, K, J, R и U можно переназначить в «Настройки → Моды».
Клавиши N, K, J, I, R, U и C (обзор целей, удержание) можно переназначить в «Настройки → Моды».
Команды:
- `/airdef wave <тип> [кол-во] [дальность]` — налёт на ближайшую цель. Дальность старта — от 60 до 4000 блоков (в меню: 200–4000); землю для площадок, которой нет в загруженных чанках, игра подгружает сама (API 22, `render.load-chunks`, пока идёт поиск), а где подгрузить нельзя (сервер) или нет пригодного места, дроны всё равно стартуют: «за картой», с высоты полёта на заказанной дальности, без площадки. Типы: `shahed`, `geran3`, `lancet`, `gerbera`, `kh101`, `kalibr`, `kh22`, `zircon`, `iskander`, `kinzhal`, `oreshnik` и `mix` (комбинированный удар двумя секторами: «Герберы», шахеды, Герани-3, Х-101, «Калибры», Х-22, Циркон, «Искандер», «Кинжал», при 30+ — «Орешник»);
@@ -191,10 +267,22 @@ API мода `render.set-lights` (до 512, плавно интерполиру
- `/airdef lastchance <on|off>` — «последний шанс»: комплекс стреляет и по классу вне ролей, если цель вот-вот попадёт (по умолчанию вкл; сохраняется);
- `/airdef sites` — известные пусковые площадки (ПУ). РЛС с прямой видимостью может заметить сам пуск и получить неточную позицию; несколько наблюдённых пусков уточняют её. Обнаруженный позже дрон даёт только слабое предположение об обратном курсе: скрытые координаты площадки и время невидимого старта не используются. Повторные треки одного полёта не создают ложную точность.
- `/airdef strike <номер ПУ>` — ручной удар по разведанной площадке из готового физического С-400 с отдельно загруженной RM48U (игровой профиль, #118). Четыре ячейки делятся с боезапасом ПВО; приказ резервирует носитель и ячейку, открывает крышку и списывает одну ударную ракету при выбросе. Выбирается готовый комплекс с наибольшим остатком RM48U, затем ближайший к цели. Есть открытие ТПК, выброс, отложенное включение двигателя и разгон, ограниченная игровая траектория, столкновения и запись пуска. Несуществующее «ПВО площадки» не перехватывает ракету по броску вероятности.
- `/airdef ground-stock <номер склада> <количество>` — задать начальный запас RM48U для sandbox-сценария (по умолчанию 0, сам не пополняется). `/airdef ground-load <номер С-400>` — у живого склада в пределах 60 блоков загрузить одну RM48U, сохранив снятую ракету ПВО на складе; `/airdef ground-unload <номер С-400>` — вернуть её и восстановить снятую ракету ПВО, если она осталась. Запас сохраняется с миром. Автоматическая доставка RM48U через ТЗМ пока не реализована. Совместимость профиля основана на [публикации ГУР](https://gur.gov.ua/content/warsanctions-hur-mo-rozkryvaie-budovu-komponentnu-bazu-ta-pidpryiemstva-kooperatsii-z-vyrobnytstva-udarnykh-raket-rm48u.html); это сообщение ведомства, не независимая сертификация. Дальность, форма полёта и оформление условны для Minecraft.
- `/airdef deploy s400_launcher` и `s500_launcher` — отдельные пусковые без своей РЛС; `radar_search`, `radar_track`, `radar_height` — обзорная, сопровождающая и мачтовая игровые РЛС. Они также доступны через меню N → «Разместить элементы батареи…». `/airdef battery` показывает состав и связь; `/airdef battery <номер> integrated|launcher` меняет конфигурацию, `/airdef radar <номер> multi|search|engagement|height` — роль отдельной РЛС. Обзорная РЛС передаёт подсказки; станция сопровождения должна сама получить свежее измерение, чтобы разрешить пуск. Старые С-400/С-500 сохраняют упрощённую сборную конфигурацию. [Устройство игровой батареи и пуска](docs/BATTERIES-AND-COLD-LAUNCH.md).
- `/airdef ground-stock <номер склада> <количество>` — задать остаток RM48U для sandbox-сценария (по умолчанию 0). `/airdef ground-load <номер С-400>` загружает одну ракету у склада либо заказывает ТЗМ; `ground-unload` возвращает её у склада либо заказывает вывоз; `ground-cancel` отменяет ожидающую заявку. Доставка и обратный вывоз через ТЗМ реализованы, запас и груз сохраняются. [Пошаговый пример](docs/GROUND-STRIKES.md). Совместимость профиля основана на [публикации ГУР](https://gur.gov.ua/content/warsanctions-hur-mo-rozkryvaie-budovu-komponentnu-bazu-ta-pidpryiemstva-kooperatsii-z-vyrobnytstva-udarnykh-raket-rm48u.html); это сообщение ведомства, не независимая сертификация. Дальность, форма полёта и оформление условны для Minecraft.
- `/airdef deploy s400_launcher` и `s500_launcher` — отдельные пусковые без своей РЛС; `radar_search`, `radar_track`, `radar_height` — три разные игровые РЛС с устойчивыми профилями в каталоге. Они также выдаются отдельными пультами (`/airdef give`) и ставятся на блок как обычные пульты. `/airdef battery` показывает состав, профиль, цикл, продукты измерения и связь; `/airdef battery <номер> integrated|launcher` меняет конфигурацию. Профиль РЛС задаётся при размещении и не переключается на ходу: `radar <номер> on|off` сохраняется. Обзорная станция даёт редкие грубые отметки и область поиска; мачтовая уточняет низкие контакты над рельефом; сопровождения ищет локально, ведёт ограниченное число точных треков и только её собственное подтверждённое измерение разрешает пуск. Сеть передаёт источник, возраст и качество, но повторная пересылка не освежает измерение. Старые С-400/С-500 сохраняют сборную конфигурацию, старые роли РЛС при загрузке сопоставляются с профилями. [Устройство игровой батареи и пуска](docs/BATTERIES-AND-COLD-LAUNCH.md).
- `/airdef roles` — показать, по каким классам целей работает каждый комплекс; `/airdef roles <patriot|gepard|pantsir|s400|s500|all> <классы|default>` — задать (классы через запятую: `drone`, `jet`, `cruise`, `supersonic`, `ballistic` или `all`), например `/airdef roles s400 cruise,ballistic`;
- `/airdef doctrine` — доктрины комплексов (#47; в меню N: «Доктрины…»): `/airdef doctrine <номер|all> reserve <K>` — держать K ракет для срочных целей (баллистика или до удара меньше 12 с); `salvo eco|normal|heavy` — сколько перехватчиков на цель (только базовые / как обычно / на один больше); `sector <центр°> <полуширина°>` или `sector off` — сектор ответственности (0° — север); `guard <объект№>[,<№>]` или `guard off` — стрелять только по тому, что идёт на охраняемые объекты (отметка: `/airdef target here`). По умолчанию ограничений нет; последний шанс сильнее доктрины; `/airdef why <номер>` называет, какая настройка остановила или разрешила пуск; сохраняется с миром и сценариями. Карта охраны и пробелов в ней — вместе с картой (#48).
- `/airdef why <номер>` — почему комплекс стреляет или нет. Сразу под строкой состояния — одна typed-причина:
«есть только обзор», «ждёт сопровождения», «каналы заняты», «нет боезапаса» или «готов к пуску», вместе с возрастом и
источником отметки (своя РЛС или сеть, РЛС №N). «Есть только обзор» — на картине лишь поисковая или
сетевая отметка, своё подтверждённое измерение пуск не разрешает; «ждёт сопровождения» — своя РЛС ещё
уточняет контакт или пусковая ждёт огневой трек поддерживающей РЛС; «каналы заняты» — все каналы
сопровождения заняты другими контактами; «нет боезапаса» — нет ракет и снарядов или идёт перезарядка.
`/airdef why <номер> source` переводит монитор K на станцию, которая поставила отметку. Подробные
проверки (роли, доктрина, дальность, наведение) идут ниже и не расходятся с этой причиной. В обычном
HUD — только картина самой батареи: класс по оценке, без истинного типа и скрытых данных.
- `/airdef chains [номер батареи]` — короткие цепочки последнего налёта: «отметка → передача → захват →
пуск → исход» с временем шагов; без номера — все батареи. Строка кликабельна в меню N → «Повторы…» →
«Цепочки боя» и открывает кадр повтора.
- `/airdef deploy <patriot|gepard|pantsir|s400|s500>` — поставить комплекс в 8 блоках перед собой;
- `/airdef hold on|off` — запретить или разрешить ПВО огонь, удобно для съёмки ударов;
- `/airdef damage on|off` — разрушать ли ландшафт взрывами (через TNT, нужны читы);
@@ -202,10 +290,23 @@ API мода `render.set-lights` (до 512, плавно интерполиру
- `/airdef clear` — убрать дроны и ракеты;
- `/airdef targets clear` — снять все цели;
- `/airdef stats` — сводка.
- `/airdef recon` — debug/послебоевой разбор разведки противника (#135): отметки его картины best-first с причиной приоритета (`свежесть×4 + качество×3 + наблюдаемая роль`), фазы вылетов и дроны, нацеленные на отметку. То же — страница «Разведка противника (разбор)» в меню N. Всеведущая картина противника в обычный HUD не выводится.
Интерфейс:
- **сверху справа — сводка:** тревога, цели по типам, ближайшая угроза (дальность, высота, скорость), перехватчики в воздухе, по каждому комплексу боезапас или перезарядка, его текущая цель и число сбитых, итоговый счёт;
- **снизу справа — радар на 500 м** со сканирующим лучом. Отметки гаснут после прохода луча. Красное — цели (с хвостом по курсу), жёлтое — ракеты, синее — ПВО с кругами дальности, крест — цели удара.
- **сверху справа — сводка:** тревога, цели по типам, ближайшая угроза (дальность, высота, скорость), перехватчики в воздухе, по каждому комплексу боезапас или перезарядка, его текущая цель и число сбитых, итоговый счёт; если сеть держит разведчиков противника — их число и фаза вылета (разведка/донесение/завершение);
- **снизу справа — радар на 500 м** со сканирующим лучом. Отметки гаснут после прохода луча. Красное — цели: форма значка различает дрон, самолёт, крылатую, сверхзвуковую и баллистическую ракету, хвост показывает курс, а близкие отметки объединяются с числом; жёлтое — ракеты, синее — ПВО с кругами дальности, крест — цели удара. Разведчик противника в картине сети — жёлтый полый ромб с подписью «разведчик».
**Разведка противника (#135).** Налёт с целью «умный противник» перед ударом высылает небольшой бюджет
невооружённых разведчиков: они физически проходят игровые зоны вокруг отмеченных целей и передают домой
только область, грубую категорию, канал (пролёт/излучение/РЭБ/пуск) и возраст — не точную точку, тип,
прочность и боезапас. Сбитый до донесения разведчик ничего не передаёт; уже переданное противник помнит
между налётами, а скрытый переезд или выключение не переписывают старую отметку. На карте сети разведчик —
узнаваемый жёлтый ромб с подписью «разведчик» (в sandbox-режиме `/airdef truth on` — янтарная метка и
счётчик отметок), в сводке и на карте видна фаза вылета: разведка → донесение → завершение. Что противник
запомнил и почему выбирает цель, показывает `/airdef recon` и страница «Разведка противника (разбор)» в меню
N (есть и в «Повторы…»): отметки best-first с разбором приоритета (свежесть, качество, наблюдаемая роль) и
дроны, нацеленные на отметку. Это явный debug/послебоевой разбор — всеведущая картина противника в обычный
HUD не выводится. Простые пресеты налёта фазу разведки не получают.
Комплексы ПВО и цели сохраняются между сессиями.
@@ -231,20 +332,22 @@ API мода `render.set-lights` (до 512, плавно интерполиру
| ПВО | Вооружение | Дальность |
|---|---|---|
| Patriot | 4 × PAC-3, пусковая разворачивается на цель | 10–450 |
| Гепард | 2 × 35 мм, башня и стволы со слежением и упреждением, 160 очередей | 135 (слежение с 195) |
| Панцирь-С1 | 12 × 57Э6 и 2 × 30 мм; модуль поворачивается, пакеты и стволы поднимаются | ракеты 25–225, пушки 90 |
| С-400 | 4 × 48Н6, вертикальный холодный старт, РЛС обзора на прицепе | 30–720 |
| С-500 | 2 × 77Н6, холодный старт, самые быстрые ракеты | 40–1050 |
| Patriot | 4 × PAC-3, пусковая разворачивается на цель | 10–950 |
| Гепард | 2 × 35 мм, башня и стволы со слежением и упреждением, 160 очередей | 180 (слежение с 260) |
| Панцирь-С1 | 12 × 57Э6 и 2 × 30 мм; модуль поворачивается, пакеты и стволы поднимаются | ракеты 25–330, пушки 125 |
| С-400 | 4 × 48Н6, вертикальный холодный старт, РЛС обзора на прицепе | 30–1300 |
| С-500 | 2 × 77Н6, холодный старт, самые быстрые ракеты | 40–1850 |
| IRIS-T SLM | 8 ракет, вертикальный пуск, быстрые и манёвренные | 15–600 |
| NASAMS | 6 × AMRAAM, наводимая пусковая на прицепе | 10–450 |
| Бук-М2 | 4 × 9М317 на направляющих, башня с РЛС подсвета | 20–675 |
| Тор-М2 | 8 × 9М338 вертикально из башни, быстрая реакция против дронов | 8–240 |
| Тор-М2 | 8 × 9М338 вертикально из башни, быстрая реакция против дронов | 8–350 |
| P1-SUN | 8 дронов-перехватчиков против Шахедов и Герань; своей РЛС нет — стреляет по данным сети | 5–675 |
Обслуживающая техника (тоже пультами или `/airdef deploy <ключ>`): **РЛС дальнего обнаружения** (`radar`,
видит на 2,5 км с высокой мачты, хуже прячутся за рельефом), **склад боеприпасов** (`depot`), **ТЗМ** (`tzm`),
**станция РЭБ** (`ew`), **прожектор** (`light`). Новые комплексы: `irist`, `nasams`, `buk`, `tor`, `p1sun`.
базовая дальность обзора 3800 блоков до поправок на класс цели, высоту и рельеф), **склад боеприпасов** (`depot`), **ТЗМ** (`tzm`),
**станция РЭБ** (`ew`), **прожектор** (`light`), **оптический пост** (`optical`: пассивно уточняет широкий класс
контакта по прямой видимости и передаёт уточнение в класс уже известного сетевого трека — без своего трека,
свежести и права на пуск; не излучает и не ведёт огневой трек). Новые комплексы: `irist`, `nasams`, `buk`, `tor`, `p1sun`.
**Согласование огня.** Комплексы делят цели между собой: на обычную цель идёт одна ракета, на баллистическую две; чем ближе цель к своей точке попадания,
тем больше перехватчиков разрешено на неё сразу (за ~12 с до удара ещё один, за ~5 с — ещё один). Комплекс, у которого кончились ракеты
@@ -252,14 +355,17 @@ API мода `render.set-lights` (до 512, плавно интерполиру
«Герберы» выглядят для них как настоящие. Геометрия встречи проверяется по движению обоих объектов
за тик, а остаточный шанс учитывает фактическую скорость перехватчика.
**Энергетика перехватчика.** После холодного выброса ракета разгоняется, но двигатель работает
конечное игровое время. После выгорания ракета летит по инерции, теряет скорость и манёвренность;
при недостаточной скорости сопровождение срывается. Факел, звук двигателя и новый дым прекращаются
при выгорании и в live, и в повторе; уже созданный дым продолжает рассеиваться.
**Энергетика перехватчика.** Сначала ракета выходит из ТПК без двигателя: у С-400 это 1,0 с,
у С-500 — 1,2 с; только потом в её текущей точке зажигается факел, и тяга плавно нарастает.
После выброса ракета разгоняется, но двигатель работает конечное игровое время. После выгорания
ракета летит по инерции, теряет скорость и манёвренность; при недостаточной скорости сопровождение
срывается. Факел, звук двигателя и новый дым прекращаются при выгорании и в live, и в повторе;
уже созданный дым продолжает рассеиваться. У ракет с горячим (рельсовым) пуском тяга тоже
нарастает плавно, но холодного выброса нет; электрический P1-SUN не получает ракетную струю.
**Последний шанс** (`/airdef lastchance on|off`, по умолчанию вкл). Комплекс стреляет и по классу целей вне своих ролей
(С-400, С-500 и Patriot по умолчанию не бьют дроны), если цель долетит до своей точки меньше чем за 10 с и на ней ещё нет
ничьего перехватчика. Комплексу с пустыми ролями (огонь запрещён) это не касается. `/airdef why` пишет «последний шанс».
(С-400, С-500 и Patriot по умолчанию не бьют дроны), если цель долетит до своей точки меньше чем за 6 с, на ней ещё нет
ничьего перехватчика и готовый комплекс меньшей дальности не успевает её обстрелять. Комплексу с пустыми ролями (огонь запрещён) это не касается. `/airdef why` пишет «последний шанс».
**Дальний пуск по РЛС.** С-400, С-500 и Patriot могут стрелять дальше своей дальности (до 1,6×) по цели, которую держит
свежим треком РЛС дальнего обнаружения в радиусе связи: не чаще раза в 15 с, при не менее чем половине боезапаса, только по
@@ -343,6 +449,9 @@ run-home/ тестовая игровая папка (для пров
## Известные ограничения
- Для [#122](https://gitea.maoniao.team/chexit/airdef/issues/122) воспроизведено и исправлено исчерпание fuel при массовых взрывах:
каждый взрыв больше не обходит всю карту высот. Проверка на конкретном Windows-компьютере ещё нужна;
прирост FPS этим исправлением не обещается.
- Мод клиентский: дроны и ПВО видит только тот, у кого он стоит. Мультиплеер не поддерживается.
- Окно Horizon на macOS не рисует кадры, пока оно перекрыто другими окнами (это поведение движка).
- Шейдер работает, только если не включён шейдер-пак Horizon (они взаимоисключающие).
+2
View File
@@ -9,5 +9,7 @@ glam = "0.30"
[features]
test-fixtures = []
# Counts the events the by-time journal readers hand out (the `replay_bench` example).
bench-counters = []
[workspace]
+8
View File
@@ -0,0 +1,8 @@
//! The enemy-picture bench (#127) without building the Horizon SDK.
extern crate airdef_core as airdef;
#[path = "../../airdef-mod/examples/intel_bench.rs"]
mod bench;
fn main() {
bench::main();
}
+131
View File
@@ -35,3 +35,134 @@ fn same_seed_same_result() {
let b = harness::run(&harness::logistics());
assert_eq!((a.ticks_run, a.launched, a.kills, a.hits, a.fired, a.ground_queries), (b.ticks_run, b.launched, b.kills, b.hits, b.fired, b.ground_queries));
}
#[test]
fn overlapping_mass_strikes_on_flat_world() {
use airdef::sim::{Aim, Approach, DroneKind as D, Ground, Out, RaidOrder, Sam, Sim};
use glam::DVec3;
let sc = harness::big_smart();
let terrain = harness::Terrain::Flat(70);
let mut sim = Sim::new(sc.seed);
sim.damage = false;
for unit in &sc.units {
let id = sim.id();
sim.sams.push(Sam::new(id, unit.kind, DVec3::new(unit.pos.x, 70.0, unit.pos.z), unit.heading));
}
sim.targets = vec![DVec3::new(0.0, 70.0, 0.0)];
sim.target_health = vec![100.0];
// Exact composition of the menu's "Массированный удар" preset.
let order = RaidOrder { kinds: vec![(D::Gerbera, 8), (D::Shahed, 12), (D::Geran3, 4), (D::Kh101, 4), (D::Kalibr, 4), (D::Kh22, 2), (D::Iskander, 2)], approach: Approach::AllSides, aim: Aim::Smart, dist: 4000.0 };
let mut ground = Ground::default();
let mut pending = Vec::new();
let mut out = Out::default();
let targets = sim.targets.clone();
assert_eq!(sim.order_raid(&order, &targets, &mut out), 36);
let mut second = false;
let mut peak = 0;
for now in 1..=12000 {
if !second && !sim.planning() {
assert_eq!(sim.order_raid(&order, &targets, &mut out), 36);
second = true;
}
ground.answer(std::mem::take(&mut pending), now);
out = Out::default();
sim.step(&mut ground, None, &mut out);
let wanted = ground.take_wanted();
pending = wanted.into_iter().map(|(x, z)| (x, z, 70)).collect();
let sections = ground.world.take_wanted(now);
ground.world.serve(&terrain, sections, now);
peak = peak.max(sim.drones.iter().filter(|d| d.alive()).count());
assert!(sim.drones.iter().all(|d| d.pos.is_finite() && d.vel.is_finite()));
if sim.launched >= 72 && peak > 36 { break; }
}
eprintln!("overlapping mass strikes: launched {}, peak airborne {peak}", sim.launched);
assert!(second && sim.launched >= 72, "second raid failed to launch; launched {}", sim.launched);
assert!(peak > 36, "raids never overlapped; peak {peak}");
}
#[test]
fn overlapping_oreshnik_splits_are_recorded() {
use airdef::sim::{Aim, Approach, DroneKind, Ground, Out, RaidOrder, Sim};
use glam::DVec3;
let mut sim = Sim::new(1);
sim.damage = false;
let targets = vec![DVec3::new(0.0, 70.0, 0.0)];
sim.targets = targets.clone();
sim.target_health = vec![100.0];
let order = RaidOrder { kinds: vec![(DroneKind::Oreshnik, 40)], approach: Approach::Sector, aim: Aim::Objects, dist: 2600.0 };
let terrain = harness::Terrain::Flat(70);
let mut ground = Ground::default();
let mut pending = Vec::new();
let mut out = Out::default();
assert_eq!(sim.order_raid(&order, &targets, &mut out), 40);
let mut second = false;
let mut peak = 0;
let mut peak_subs = 0;
for now in 1..=10000 {
if !second && !sim.planning() {
assert_eq!(sim.order_raid(&order, &targets, &mut out), 40);
second = true;
}
ground.answer(std::mem::take(&mut pending), now);
out = Out::default();
sim.step(&mut ground, None, &mut out);
pending = ground.take_wanted().into_iter().map(|(x, z)| (x, z, 70)).collect();
let sections = ground.world.take_wanted(now);
ground.world.serve(&terrain, sections, now);
peak = peak.max(sim.drones.iter().filter(|d| d.alive()).count());
peak_subs = peak_subs.max(sim.drones.iter().filter(|d| d.alive() && d.kind == DroneKind::OreshnikSub).count());
assert!(sim.drones.iter().all(|d| d.pos.is_finite() && d.vel.is_finite()));
if second && sim.launched >= 80 && !sim.replays.is_empty() { break; }
}
eprintln!("overlapping oreshnik: launched {}, peak airborne {peak}, peak submunitions {peak_subs}, replays {}", sim.launched, sim.replays.len());
assert_eq!(sim.launched, 2880);
assert!(peak_subs > 36, "expected many simultaneous submunitions");
assert!(!sim.replays.is_empty(), "recording did not finish");
}
#[test]
fn two_maximum_menu_raids_with_answered_flat_terrain() {
use airdef::sim::{Aim, Approach, Ground, Out, RaidOrder, Sam, Sim, catalog::RAID_KINDS};
use glam::DVec3;
let sc = harness::big_smart();
let terrain = harness::Terrain::Flat(70);
let mut sim = Sim::new(sc.seed);
for unit in &sc.units {
let id = sim.id();
sim.sams.push(Sam::new(id, unit.kind, DVec3::new(unit.pos.x, 70.0, unit.pos.z), unit.heading));
}
let targets = vec![DVec3::new(0.0, 70.0, 0.0)];
sim.targets = targets.clone();
sim.target_health = vec![100.0];
// The maximum selectable by the menu: 40 for each raid kind.
let order = RaidOrder { kinds: RAID_KINDS.iter().copied().map(|kind| (kind, 40)).collect(), approach: Approach::AllSides, aim: Aim::Smart, dist: 300.0 };
let expected = RAID_KINDS.len() as u32 * 40;
let mut ground = Ground::default();
let mut pending = Vec::new();
let mut out = Out::default();
assert_eq!(sim.order_raid(&order, &targets, &mut out), expected);
let mut second = false;
let mut overlap = false;
let mut peak = 0;
// Two maximum menu raids can keep the last supersonic contact in the air past
// 5000 ticks under the radar profiles; the recording closes once the sky is clear.
for now in 1..=8000 {
if !second && !sim.planning() {
overlap = !sim.queue.is_empty() || sim.drones.iter().any(|d| d.alive());
assert_eq!(sim.order_raid(&order, &targets, &mut out), expected);
second = true;
}
ground.answer(std::mem::take(&mut pending), now);
out = Out::default();
sim.step(&mut ground, None, &mut out);
pending = ground.take_wanted().into_iter().map(|(x, z)| (x, z, 70)).collect();
let sections = ground.world.take_wanted(now);
ground.world.serve(&terrain, sections, now);
peak = peak.max(sim.drones.iter().filter(|d| d.alive()).count());
assert!(sim.drones.iter().all(|d| d.pos.is_finite() && d.vel.is_finite()));
if second && sim.launched >= expected * 2 && !sim.replays.is_empty() { break; }
}
eprintln!("max menu raids: requested {}, launched {}, peak {peak}, replays {}", expected * 2, sim.launched, sim.replays.len());
assert!(second && overlap && sim.launched >= expected * 2 && peak > 40);
assert!(!sim.replays.is_empty(), "raid recording did not finish");
}
+197
View File
@@ -2,13 +2,22 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "airdef"
version = "0.2.0"
dependencies = [
"airdef-core",
"glam",
"horizon-assets",
"horizon-mod-sdk",
"horizon-mods",
"serde_json",
]
[[package]]
@@ -24,18 +33,75 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
dependencies = [
"derive_arbitrary",
]
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "bumpalo"
version = "3.20.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "crc32fast"
version = "1.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
dependencies = [
"cfg-if",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
[[package]]
name = "derive_arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "flate2"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]]
name = "foldhash"
version = "0.2.0"
@@ -63,6 +129,22 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "horizon-assets"
version = "0.1.0"
dependencies = [
"horizon-core",
"serde",
"serde_json",
]
[[package]]
name = "horizon-core"
version = "0.1.0"
dependencies = [
"libm",
]
[[package]]
name = "horizon-mod-sdk"
version = "0.1.0"
@@ -70,6 +152,17 @@ dependencies = [
"wit-bindgen",
]
[[package]]
name = "horizon-mods"
version = "0.1.0"
dependencies = [
"log",
"serde",
"serde_json",
"toml",
"zip",
]
[[package]]
name = "id-arena"
version = "2.3.0"
@@ -100,6 +193,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "log"
version = "0.4.34"
@@ -112,6 +211,16 @@ version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "prettyplease"
version = "0.2.37"
@@ -153,6 +262,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
@@ -188,6 +298,21 @@ dependencies = [
"zmij",
]
[[package]]
name = "serde_spanned"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
dependencies = [
"serde_core",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "syn"
version = "2.0.119"
@@ -210,6 +335,45 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "toml"
version = "1.2.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
name = "toml_datetime"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_parser"
version = "1.1.6+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31"
dependencies = [
"winnow",
]
[[package]]
name = "toml_writer"
version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]]
name = "unicode-ident"
version = "1.0.27"
@@ -250,6 +414,12 @@ dependencies = [
"semver",
]
[[package]]
name = "winnow"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
[[package]]
name = "wit-bindgen"
version = "0.60.0"
@@ -339,8 +509,35 @@ dependencies = [
"wasmparser",
]
[[package]]
name = "zip"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744"
dependencies = [
"arbitrary",
"crc32fast",
"crossbeam-utils",
"flate2",
"indexmap",
"memchr",
"zopfli",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
+11
View File
@@ -8,13 +8,24 @@ description = "AirDef: long-range drones and air defence for the AirDef fork of
[lib]
crate-type = ["cdylib", "rlib"]
[features]
# Counts the events the by-time readers hand out (the `replay_bench` example); off in the mod build.
bench-counters = ["airdef-core/bench-counters"]
[dependencies]
airdef-core = { path = "../airdef-core" }
horizon-mod-sdk = { path = "../horizon/crates/horizon-mod-sdk" }
glam = "0.30"
serde_json = "1"
[build-dependencies]
horizon-assets = { path = "../horizon/crates/horizon-assets" }
[dev-dependencies]
airdef-core = { path = "../airdef-core", features = ["test-fixtures"] }
# The host's own block tracer, so the saturation replica answers render rays exactly as the
# WASM test host does (no runtime: just `world_query`).
horizon-mods = { path = "../horizon/crates/horizon-mods", default-features = false }
[profile.release]
opt-level = "s"
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "airdef:item/deploy_optical"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "airdef:item/deploy_radar_height"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "airdef:item/deploy_radar_search"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "airdef:item/deploy_radar_track"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "airdef:item/deploy_s400_launcher"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "airdef:item/deploy_s500_launcher"
}
}
+6
View File
@@ -123,6 +123,12 @@
"item.airdef.deploy_tzm": "Развернуть ТЗМ",
"item.airdef.deploy_ew": "Развернуть станцию РЭБ",
"item.airdef.deploy_light": "Развернуть прожектор",
"item.airdef.deploy_optical": "Развернуть оптический пост",
"item.airdef.deploy_s400_launcher": "Развернуть С-400 (пусковая)",
"item.airdef.deploy_s500_launcher": "Развернуть С-500 (пусковая)",
"item.airdef.deploy_radar_search": "Развернуть РЛС обзора",
"item.airdef.deploy_radar_track": "Развернуть РЛС сопровождения",
"item.airdef.deploy_radar_height": "Развернуть мачтовую РЛС",
"item.airdef.mover": "Пульт перемещения",
"item.airdef.flare_gun": "Осветительная ракета",
"item.airdef.remover": "Свернуть ПВО",
+6
View File
@@ -123,6 +123,12 @@
"item.airdef.deploy_tzm": "Развернуть ТЗМ",
"item.airdef.deploy_ew": "Развернуть станцию РЭБ",
"item.airdef.deploy_light": "Развернуть прожектор",
"item.airdef.deploy_optical": "Развернуть оптический пост",
"item.airdef.deploy_s400_launcher": "Развернуть С-400 (пусковая)",
"item.airdef.deploy_s500_launcher": "Развернуть С-500 (пусковая)",
"item.airdef.deploy_radar_search": "Развернуть РЛС обзора",
"item.airdef.deploy_radar_track": "Развернуть РЛС сопровождения",
"item.airdef.deploy_radar_height": "Развернуть мачтовую РЛС",
"item.airdef.mover": "Пульт перемещения",
"item.airdef.flare_gun": "Осветительная ракета",
"item.airdef.remover": "Свернуть ПВО",
+598 -54
View File
@@ -741,8 +741,8 @@
2.0
],
"to": [
22.0,
7.6,
13.55,
7.5,
11.0
],
"faces": {
@@ -750,8 +750,8 @@
"uv": [
0,
0,
11.5,
0.6999999999999993
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
@@ -759,8 +759,8 @@
"uv": [
0,
0,
11.5,
0.6999999999999993
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
@@ -769,7 +769,7 @@
0,
0,
9.0,
0.6999999999999993
0.5999999999999996
],
"texture": "#kh101"
},
@@ -778,7 +778,7 @@
0,
0,
9.0,
0.6999999999999993
0.5999999999999996
],
"texture": "#kh101"
},
@@ -786,7 +786,7 @@
"uv": [
0,
0,
11.5,
3.0500000000000007,
9.0
],
"texture": "#kh101"
@@ -795,7 +795,7 @@
"uv": [
0,
0,
11.5,
3.0500000000000007,
9.0
],
"texture": "#kh101_belly"
@@ -804,13 +804,13 @@
},
{
"from": [
-6.0,
2.4499999999999993,
6.9,
2.0
],
"to": [
5.5,
7.6,
7.5,
11.0
],
"faces": {
@@ -818,8 +818,8 @@
"uv": [
0,
0,
11.5,
0.6999999999999993
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
@@ -827,8 +827,8 @@
"uv": [
0,
0,
11.5,
0.6999999999999993
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
@@ -837,7 +837,7 @@
0,
0,
9.0,
0.6999999999999993
0.5999999999999996
],
"texture": "#kh101"
},
@@ -846,7 +846,7 @@
0,
0,
9.0,
0.6999999999999993
0.5999999999999996
],
"texture": "#kh101"
},
@@ -854,7 +854,7 @@
"uv": [
0,
0,
11.5,
3.0500000000000007,
9.0
],
"texture": "#kh101"
@@ -863,7 +863,7 @@
"uv": [
0,
0,
11.5,
3.0500000000000007,
9.0
],
"texture": "#kh101_belly"
@@ -872,22 +872,22 @@
},
{
"from": [
22.0,
13.5,
6.9,
5.0
2.65
],
"to": [
28.5,
7.4,
11.0
16.55,
7.5,
10.88
],
"faces": {
"north": {
"uv": [
0,
0,
6.5,
0.5
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
@@ -895,8 +895,8 @@
"uv": [
0,
0,
6.5,
0.5
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
@@ -904,8 +904,8 @@
"uv": [
0,
0,
6.0,
0.5
8.23,
0.5999999999999996
],
"texture": "#kh101"
},
@@ -913,8 +913,8 @@
"uv": [
0,
0,
6.0,
0.5
8.23,
0.5999999999999996
],
"texture": "#kh101"
},
@@ -922,8 +922,8 @@
"uv": [
0,
0,
6.5,
6.0
3.0500000000000007,
8.23
],
"texture": "#kh101"
},
@@ -931,8 +931,552 @@
"uv": [
0,
0,
6.5,
6.0
3.0500000000000007,
8.23
],
"texture": "#kh101_belly"
}
}
},
{
"from": [
-0.5500000000000007,
6.9,
2.65
],
"to": [
2.5,
7.5,
10.88
],
"faces": {
"north": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"south": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"east": {
"uv": [
0,
0,
8.23,
0.5999999999999996
],
"texture": "#kh101"
},
"west": {
"uv": [
0,
0,
8.23,
0.5999999999999996
],
"texture": "#kh101"
},
"up": {
"uv": [
0,
0,
3.0500000000000007,
8.23
],
"texture": "#kh101"
},
"down": {
"uv": [
0,
0,
3.0500000000000007,
8.23
],
"texture": "#kh101_belly"
}
}
},
{
"from": [
16.5,
6.9,
3.3
],
"to": [
19.55,
7.5,
10.76
],
"faces": {
"north": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"south": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"east": {
"uv": [
0,
0,
7.46,
0.5999999999999996
],
"texture": "#kh101"
},
"west": {
"uv": [
0,
0,
7.46,
0.5999999999999996
],
"texture": "#kh101"
},
"up": {
"uv": [
0,
0,
3.0500000000000007,
7.46
],
"texture": "#kh101"
},
"down": {
"uv": [
0,
0,
3.0500000000000007,
7.46
],
"texture": "#kh101_belly"
}
}
},
{
"from": [
-3.5500000000000007,
6.9,
3.3
],
"to": [
-0.5,
7.5,
10.76
],
"faces": {
"north": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"south": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"east": {
"uv": [
0,
0,
7.46,
0.5999999999999996
],
"texture": "#kh101"
},
"west": {
"uv": [
0,
0,
7.46,
0.5999999999999996
],
"texture": "#kh101"
},
"up": {
"uv": [
0,
0,
3.0500000000000007,
7.46
],
"texture": "#kh101"
},
"down": {
"uv": [
0,
0,
3.0500000000000007,
7.46
],
"texture": "#kh101_belly"
}
}
},
{
"from": [
19.5,
6.9,
3.95
],
"to": [
22.55,
7.5,
10.64
],
"faces": {
"north": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"south": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"east": {
"uv": [
0,
0,
6.69,
0.5999999999999996
],
"texture": "#kh101"
},
"west": {
"uv": [
0,
0,
6.69,
0.5999999999999996
],
"texture": "#kh101"
},
"up": {
"uv": [
0,
0,
3.0500000000000007,
6.69
],
"texture": "#kh101"
},
"down": {
"uv": [
0,
0,
3.0500000000000007,
6.69
],
"texture": "#kh101_belly"
}
}
},
{
"from": [
-6.550000000000001,
6.9,
3.95
],
"to": [
-3.5,
7.5,
10.64
],
"faces": {
"north": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"south": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"east": {
"uv": [
0,
0,
6.69,
0.5999999999999996
],
"texture": "#kh101"
},
"west": {
"uv": [
0,
0,
6.69,
0.5999999999999996
],
"texture": "#kh101"
},
"up": {
"uv": [
0,
0,
3.0500000000000007,
6.69
],
"texture": "#kh101"
},
"down": {
"uv": [
0,
0,
3.0500000000000007,
6.69
],
"texture": "#kh101_belly"
}
}
},
{
"from": [
22.5,
6.9,
4.6
],
"to": [
25.55,
7.5,
10.52
],
"faces": {
"north": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"south": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"east": {
"uv": [
0,
0,
5.92,
0.5999999999999996
],
"texture": "#kh101"
},
"west": {
"uv": [
0,
0,
5.92,
0.5999999999999996
],
"texture": "#kh101"
},
"up": {
"uv": [
0,
0,
3.0500000000000007,
5.92
],
"texture": "#kh101"
},
"down": {
"uv": [
0,
0,
3.0500000000000007,
5.92
],
"texture": "#kh101_belly"
}
}
},
{
"from": [
-9.55,
6.9,
4.6
],
"to": [
-6.5,
7.5,
10.52
],
"faces": {
"north": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"south": {
"uv": [
0,
0,
3.0500000000000007,
0.5999999999999996
],
"texture": "#kh101"
},
"east": {
"uv": [
0,
0,
5.92,
0.5999999999999996
],
"texture": "#kh101"
},
"west": {
"uv": [
0,
0,
5.92,
0.5999999999999996
],
"texture": "#kh101"
},
"up": {
"uv": [
0,
0,
3.0500000000000007,
5.92
],
"texture": "#kh101"
},
"down": {
"uv": [
0,
0,
3.0500000000000007,
5.92
],
"texture": "#kh101_belly"
}
}
},
{
"from": [
25.5,
6.9,
5.25
],
"to": [
28.5,
7.5,
10.4
],
"faces": {
"north": {
"uv": [
0,
0,
3.0,
0.5999999999999996
],
"texture": "#kh101"
},
"south": {
"uv": [
0,
0,
3.0,
0.5999999999999996
],
"texture": "#kh101"
},
"east": {
"uv": [
0,
0,
5.15,
0.5999999999999996
],
"texture": "#kh101"
},
"west": {
"uv": [
0,
0,
5.15,
0.5999999999999996
],
"texture": "#kh101"
},
"up": {
"uv": [
0,
0,
3.0,
5.15
],
"texture": "#kh101"
},
"down": {
"uv": [
0,
0,
3.0,
5.15
],
"texture": "#kh101_belly"
}
@@ -942,20 +1486,20 @@
"from": [
-12.5,
6.9,
5.0
5.25
],
"to": [
-6.0,
7.4,
11.0
-9.5,
7.5,
10.4
],
"faces": {
"north": {
"uv": [
0,
0,
6.5,
0.5
3.0,
0.5999999999999996
],
"texture": "#kh101"
},
@@ -963,8 +1507,8 @@
"uv": [
0,
0,
6.5,
0.5
3.0,
0.5999999999999996
],
"texture": "#kh101"
},
@@ -972,8 +1516,8 @@
"uv": [
0,
0,
6.0,
0.5
5.15,
0.5999999999999996
],
"texture": "#kh101"
},
@@ -981,8 +1525,8 @@
"uv": [
0,
0,
6.0,
0.5
5.15,
0.5999999999999996
],
"texture": "#kh101"
},
@@ -990,8 +1534,8 @@
"uv": [
0,
0,
6.5,
6.0
3.0,
5.15
],
"texture": "#kh101"
},
@@ -999,8 +1543,8 @@
"uv": [
0,
0,
6.5,
6.0
3.0,
5.15
],
"texture": "#kh101_belly"
}
@@ -1551,4 +2095,4 @@
}
}
]
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "airdef:item/deploy_radar"
}
}
@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "airdef:item/deploy_radar"
}
}
@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "airdef:item/deploy_radar"
}
}
@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "airdef:item/deploy_radar"
}
}
@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "airdef:item/deploy_s400"
}
}
@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "airdef:item/deploy_s500"
}
}
+65
View File
@@ -0,0 +1,65 @@
use horizon_assets::{
bake::{BlockModelTransform, bake_block_model},
model::CuboidModel,
resolve::ModelLibrary,
};
use std::{collections::BTreeMap, env, fmt::Write, fs, path::PathBuf};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let models = PathBuf::from("assets/airdef/models/block");
println!("cargo:rerun-if-changed={}", models.display());
let output = PathBuf::from(env::var_os("OUT_DIR").expect("Cargo sets OUT_DIR"));
let mut decoded = BTreeMap::new();
for entry in fs::read_dir(models)? {
let path = entry?.path();
if path.extension().is_some_and(|ext| ext == "json") {
let name = path
.file_stem()
.and_then(|s| s.to_str())
.expect("UTF-8 model name");
let model = CuboidModel::from_json(&fs::read_to_string(&path)?)
.unwrap_or_else(|e| panic!("{}: {e}", path.display()));
decoded.insert(format!("airdef:block/{name}"), model);
}
}
// Use the same cuboid baker as the client so element rotations, omitted faces and
// model coordinates match. Include only positions, with offsets for the local AABBs.
let names: Vec<_> = decoded.keys().cloned().collect();
let library = ModelLibrary::new(decoded)?;
let transform = BlockModelTransform::new([0; 3], false);
let mut bytes = Vec::new();
let mut table = String::from("&[\n");
for name in names {
let model = library.resolve(&name)?;
let faces = bake_block_model(&model, transform)?;
if faces.is_empty() {
continue;
}
let start = bytes.len();
let mut min = [f32::INFINITY; 3];
let mut max = [f32::NEG_INFINITY; 3];
for face in faces {
for position in face.positions {
for (i, coordinate) in position.into_iter().enumerate() {
let centred = coordinate - 0.5;
min[i] = min[i].min(centred);
max[i] = max[i].max(centred);
bytes.extend_from_slice(&centred.to_le_bytes());
}
}
}
let id = name.replace(":block/", ":");
let extent = std::array::from_fn::<_, 3, _>(|i| min[i].abs().max(max[i].abs()));
let radius = extent.iter().map(|value| value * value).sum::<f32>().sqrt();
writeln!(
table,
" ({id:?}, Mesh {{ min: {min:?}, max: {max:?}, radius: {radius:?}, start: {start}, end: {} }}),",
bytes.len()
)?;
}
table.push_str("]\n");
fs::write(output.join("inspect-meshes.rs"), table)?;
fs::write(output.join("inspect-faces.bin"), bytes)?;
Ok(())
}
@@ -0,0 +1,4 @@
{
"template": "minecraft:stick",
"max_stack_size": 1
}
@@ -0,0 +1,4 @@
{
"template": "minecraft:stick",
"max_stack_size": 1
}
@@ -0,0 +1,4 @@
{
"template": "minecraft:stick",
"max_stack_size": 1
}
@@ -0,0 +1,4 @@
{
"template": "minecraft:stick",
"max_stack_size": 1
}
@@ -0,0 +1,4 @@
{
"template": "minecraft:stick",
"max_stack_size": 1
}
@@ -0,0 +1,4 @@
{
"template": "minecraft:stick",
"max_stack_size": 1
}
+57
View File
@@ -0,0 +1,57 @@
//! Enemy-picture outcomes on fixed seeds (#127): what changed for the raids, measured.
//!
//! Runs the standard scenarios over a fixed seed set and prints one JSON object with the
//! completion, losses and failure reasons of every run — the before/after comparison of the
//! honest EnemyPicture is judged on these, not on "it got smarter".
//!
//! cargo run --release --example intel_bench
#[path = "sim_run/harness.rs"]
mod harness;
use harness::{big_smart, ew_adaptive, logistics, Scenario};
fn esc(s: &str) -> String {
s.chars().flat_map(|c| match c {
'"' => "\\\"".chars().collect::<Vec<_>>(),
'\\' => "\\\\".chars().collect::<Vec<_>>(),
c => vec![c],
}).collect()
}
fn run(sc: &Scenario) -> String {
let r = harness::run(sc);
format!(
"{{\"scenario\":\"{}\",\"seed\":{},\"ticks_run\":{},\"raids_ordered\":{},\"raids_ended\":{},\"all_ended\":{},\"launched\":{},\"kills\":{},\"hits\":{},\"crashes\":{},\"sams_lost\":{},\"fired\":{},\"retargets_max\":{},\"air_bytes\":{},\"switches_max\":{},\"intents\":\"{}\",\"failures\":\"{}\"}}",
esc(&r.name),
r.seed,
r.ticks_run,
r.raids_ordered,
r.raids_ended,
r.all_ended,
r.launched,
r.kills,
r.hits,
r.crashes,
r.sams_lost,
r.fired,
r.retargets_max,
r.air_bytes,
r.switches_max,
esc(&r.intents),
esc(&r.failures),
)
}
pub fn main() {
let scenarios: Vec<fn() -> Scenario> = vec![big_smart, logistics, ew_adaptive];
let seeds = [1u64, 7, 42];
let mut rows = Vec::new();
for make in &scenarios {
for &seed in &seeds {
let mut sc = make();
sc.seed = seed;
rows.push(run(&sc));
}
}
println!("[{}]", rows.join(",\n"));
}
+261
View File
@@ -0,0 +1,261 @@
//! Replay hot-path benchmark (#150): a 10-minute raid with its journals almost full.
//!
//! Plays the recording the ways a player does — ordinary playback, reverse seeks, a pause and
//! an MP4 export (the director's film) — and reports the CPU per frame (p50/p95/p99) and the
//! events the by-time readers handed out. Run it with the counters built in:
//!
//! cargo run --release --example replay_bench --features bench-counters
//!
//! Without `bench-counters` the scanned-events numbers read 0. Native timings compare runs on
//! one machine; they say nothing about the WASM build or the GPU.
use airdef::film::{Film, Which};
use airdef::replay::{Control, Mode, Player};
use airdef::sim::record::{Event, EventKind, Recording, SceneEvent, SceneJournal, SceneKind, StrikeResult, What};
use airdef::sim::{DroneKind, Ground, MissileKind, Out, SamKind, Sim};
use glam::DVec3;
use std::time::{Duration, Instant};
/// The longest recording, ticks (10 minutes at 20 a second).
const TICKS: u32 = 12_000;
/// The event journal's cap, and the scene journal's (`MAX_SCENE_EVENTS`), nearly reached.
const EVENTS: usize = 64_000;
const SCENE: usize = 65_000;
/// Frames measured per mode (20 a second, half a minute of playback; a film frame is 0.05 s).
const FRAMES: usize = 600;
const LISTENER: DVec3 = DVec3::new(0.0, 70.0, 0.0);
/// A 10-minute raid's recording: 200 flights, a nearly full event journal and scene journal,
/// the objects, systems, tracks and the fires — the journal a busy raid leaves.
fn recording() -> Recording {
let mut rec = Recording::blank(TICKS);
rec.number = 1;
rec.len = TICKS;
rec.origin = DVec3::ZERO;
rec.sams = (0..8).map(|i| (10 + i, SamKind::S400, DVec3::new(i as f64 * 120.0, 64.0, 400.0))).collect();
rec.objects = (0..8).map(|i| DVec3::new(i as f64 * 90.0, 70.0, 0.0)).collect();
// 200 flights, each a few hundred ticks of the raid (a point every 2 ticks): the map and
// the ghosts draw them, the sounds read their launches.
for k in 0..200u32 {
let first = k * 55 % (TICKS - 700);
let last = first + 600;
let what = match k % 4 {
0 => What::Drone(DroneKind::Geran3),
1 => What::Drone(DroneKind::Shahed),
2 => What::Missile(MissileKind::M48n6, 10 + k % 8),
_ => What::Strike,
};
rec.straight(1000 + k, what, first, last, DVec3::new(-2000.0, 100.0, k as f64 * 5.0), DVec3::new(500.0, 70.0, k as f64 * 5.0));
}
// The events: interceptions, hits, losses and splits spread through the raid.
rec.events = (0..EVENTS)
.map(|i| {
let at = (i as u64 * u64::from(TICKS) / EVENTS as u64) as u32;
let drone = 1000 + (i as u32 * 7 % 200);
let pos = DVec3::new((i % 40) as f64 * 10.0, 95.0, (i % 17) as f64 * 12.0);
let kind = match i % 10 {
0 | 1 => EventKind::Kill { drone, kind: DroneKind::Geran3, sam: 10, sam_kind: SamKind::S400, sam_index: 0, missile: None, outcome: Default::default() },
2 | 3 => EventKind::Hit { drone, kind: DroneKind::Geran3, power: (i % 5) as u32, object: Some(i % 8), sam: None },
4 | 5 => EventKind::Crash { drone, kind: DroneKind::Geran3, power: (i % 5) as u32 },
6 => EventKind::SamLost { sam: 10 + (i % 8) as u32, kind: SamKind::S400, index: i % 8 },
7 => EventKind::Split { drone },
_ => EventKind::Strike { site: 1, result: StrikeResult::Destroyed },
};
Event { at, pos, kind }
})
.collect();
// The scene journal: launches and ignitions (the exact sounds), track changes and fires.
let mut scene = SceneJournal::default();
for i in 0..SCENE {
let at = (i as u64 * u64::from(TICKS) / SCENE as u64) as u32;
let missile = 5000 + (i as u32 % 300);
let pos = DVec3::new((i % 30) as f64 * 8.0, 66.0, 300.0);
let kind = match i % 100 {
// Fires are a small share of a raid's transitions (hundreds over ten minutes).
0 => SceneKind::FireStarted { fire: (i / 100) as u32, age: 0, life: 4000, size: 1.0, quiet: false, shown: true, water: Some(false) },
1 => SceneKind::FireEnded { fire: (i / 100) as u32 },
2 | 3 => SceneKind::MissileLaunch { missile, sam: 10, target: 2000, kind: MissileKind::M48n6, sound: "airdef:launch.s400", pitch: 1.0 },
4 | 5 => SceneKind::MotorIgnition { missile, kind: MissileKind::M48n6, sound: Some("airdef:launch.s400") },
6 => SceneKind::MotorBurnout { missile, kind: MissileKind::M48n6 },
7 => SceneKind::MotorEnergyLost { missile, kind: MissileKind::M48n6, speed: 4.0 },
8 | 9 => SceneKind::TrackAcquired { sam: 10, target: 2000 + (i as u32 % 200), ever_own: true },
_ => SceneKind::TrackLost { sam: 10, target: 2000 + (i as u32 % 200) },
};
scene.fixture_push(SceneEvent { at, pos, kind });
}
rec.scene = Some(scene);
rec.close();
rec
}
/// Answers the ground queries the replays make with a flat 70-block land, as the game would.
fn settle(ground: &mut Ground, now: u64) {
let wanted = ground.take_wanted();
if !wanted.is_empty() {
ground.answer(wanted.into_iter().map(|(x, z)| (x, z, 70)).collect(), now);
}
}
fn percentile(sorted: &[Duration], p: f64) -> f64 {
if sorted.is_empty() {
return 0.0;
}
let i = (((sorted.len() - 1) as f64) * p).round() as usize;
sorted[i].as_secs_f64() * 1e6
}
struct Measured {
mode: &'static str,
frames: usize,
scanned: u64,
cpu: Vec<Duration>,
}
impl Measured {
fn cpu_p(&self, p: f64) -> f64 {
let mut sorted = self.cpu.clone();
sorted.sort_unstable();
percentile(&sorted, p)
}
fn json(&self, rec: &Recording, sim: &Sim) -> String {
let events_bytes = rec.events.capacity() * std::mem::size_of::<Event>();
let scene_events = rec.scene.as_ref().map_or(0, |s| s.events().len());
let scene_bytes = scene_events * std::mem::size_of::<SceneEvent>();
let index_bytes: usize = sim.replays.iter().map(Recording::index_bytes).sum();
format!(
"{{\"mode\":\"{}\",\"frames\":{},\"journal_events\":{},\"journal_scene\":{},\
\"scanned_events\":{},\"scanned_per_frame\":{:.1},\"full_pass_events\":{},\
\"p50_us\":{:.1},\"p95_us\":{:.1},\"p99_us\":{:.1},\"max_us\":{:.1},\
\"events_bytes\":{},\"scene_bytes\":{},\"index_bytes\":{}}}",
self.mode,
self.frames,
rec.events.len(),
scene_events,
self.scanned,
self.scanned as f64 / self.frames.max(1) as f64,
// One whole-journal pass per frame: what the readers did before the ranges (#150).
(rec.events.len() + scene_events) as u64 * self.frames as u64,
self.cpu_p(0.50),
self.cpu_p(0.95),
self.cpu_p(0.99),
self.cpu.iter().copied().max().unwrap_or_default().as_secs_f64() * 1e6,
events_bytes,
scene_bytes,
index_bytes,
)
}
}
/// Steps the replay's clock to `t` the way the wheel does (5 s a press), so the seek resets the
/// sound cursor and the shot as a player's would.
fn seek_to(p: &mut Player, rec: &Recording, t: f64) {
for _ in 0..((t.max(0.0) / 100.0) as usize) {
p.control(Control::Forward, rec);
}
}
fn sim_with(rec: Recording) -> (Sim, u64) {
let mut sim = Sim::new(1);
sim.replays.push(rec);
(sim, 1)
}
/// Ordinary playback from a moment near the end of the raid, time running at ×2.
fn playback() -> Measured {
let (sim, mut tick) = sim_with(recording());
let rec = &sim.replays[0];
let mut p = Player::new(1, Mode::Full, &sim);
seek_to(&mut p, rec, rec.len as f64 - 1_200.0);
let mut ground = Ground::default();
let mut out = Out::default();
let _ = airdef::sim::record::scanned_events();
let mut cpu = Vec::with_capacity(FRAMES);
for _ in 0..FRAMES {
let started = Instant::now();
p.tick(&sim, &mut ground, LISTENER, &mut out);
settle(&mut ground, tick);
tick += 1;
cpu.push(started.elapsed());
out = Out::default();
}
Measured { mode: "playback", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
}
/// Reverse seeks: five seconds back every frame, then a frame of playback.
fn reverse_seek() -> Measured {
let (sim, mut tick) = sim_with(recording());
let rec = &sim.replays[0];
let mut p = Player::new(1, Mode::Full, &sim);
seek_to(&mut p, rec, rec.len as f64 - 200.0);
let mut ground = Ground::default();
let mut out = Out::default();
let _ = airdef::sim::record::scanned_events();
let mut cpu = Vec::with_capacity(FRAMES);
for _ in 0..FRAMES {
let started = Instant::now();
p.control(Control::Back, rec);
p.tick(&sim, &mut ground, LISTENER, &mut out);
settle(&mut ground, tick);
tick += 1;
cpu.push(started.elapsed());
out = Out::default();
}
Measured { mode: "reverse_seek", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
}
/// A pause held while frames keep coming (the HUD and the ghosts stay, nothing sounds).
fn paused() -> Measured {
let (sim, mut tick) = sim_with(recording());
let rec = &sim.replays[0];
let mut p = Player::new(1, Mode::Full, &sim);
seek_to(&mut p, rec, rec.len as f64 * 0.75);
p.control(Control::Pause, rec);
let mut ground = Ground::default();
let mut out = Out::default();
let _ = airdef::sim::record::scanned_events();
let mut cpu = Vec::with_capacity(FRAMES);
for _ in 0..FRAMES {
let started = Instant::now();
p.tick(&sim, &mut ground, LISTENER, &mut out);
settle(&mut ground, tick);
tick += 1;
cpu.push(started.elapsed());
out = Out::default();
}
Measured { mode: "pause", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
}
/// An MP4 export: the director's film, its frames prepared and drawn as the game records them.
fn mp4() -> Measured {
let (sim, mut tick) = sim_with(recording());
let rec = &sim.replays[0];
let film = Film::build(rec, Which::Best).expect("the raid has moments to film");
let mut p = Player::new(1, Mode::Film(Box::new(film)), &sim);
p.wait = true;
p.clean = true;
let mut ground = Ground::default();
let mut out = Out::default();
let _ = airdef::sim::record::scanned_events();
let mut cpu = Vec::with_capacity(FRAMES);
for _ in 0..FRAMES {
let started = Instant::now();
p.tick(&sim, &mut ground, LISTENER, &mut out);
settle(&mut ground, tick);
tick += 1;
cpu.push(started.elapsed());
out = Out::default();
}
Measured { mode: "mp4", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
}
pub fn main() {
let (playback, reverse_seek, paused, mp4) = (playback(), reverse_seek(), paused(), mp4());
let (sim, _) = sim_with(recording());
let rec = &sim.replays[0];
if !airdef::sim::record::scan_counters() {
eprintln!("replay_bench: scanned events read 0; rerun with --features bench-counters");
}
let rows = [playback.json(rec, &sim), reverse_seek.json(rec, &sim), paused.json(rec, &sim), mp4.json(rec, &sim)];
println!("[");
println!("{}", rows.join(",\n"));
println!("]");
}
+78 -1
View File
@@ -5,6 +5,8 @@
//! Native timings say nothing about the WASM build or the GPU; use them to compare runs of the
//! same machine.
#![allow(dead_code)]
#[path = "../../src/world_view.rs"]
mod world_view;
use airdef::sim::{Aim, Approach, DroneKind, Ground, Out, RaidOrder, Sam, SamKind, Sim};
use glam::DVec3;
use std::collections::HashMap;
@@ -70,6 +72,9 @@ pub struct Scenario {
pub ew: bool,
/// Ticks a truck on a job may stand still before it counts as stuck.
pub stuck_after: u64,
/// The smart enemy runs the legacy picks (#149's comparison runner): separate hint lists,
/// the lifetime bearing tally, no mark pricing and no refresh of the unreleased portion.
pub legacy: bool,
}
impl Scenario {
@@ -85,6 +90,7 @@ impl Scenario {
stop_at_end: true,
ew: false,
stuck_after: 600,
legacy: false,
}
}
pub fn unit(&mut self, kind: SamKind, x: f64, z: f64) -> &mut Unit {
@@ -126,6 +132,37 @@ pub struct Report {
pub raids_ordered: usize,
pub raids_ended: usize,
pub all_ended: bool,
/// Systems the defence lost (destroyed units at the end).
pub sams_lost: u32,
/// The most retarget route jobs waiting at once (#127).
pub retargets_max: usize,
/// The largest air section a save would have taken, in bytes (#127).
pub air_bytes: usize,
/// The aims every drone ended with, by intent: "plan:1,sead:2,react:3,replace:0".
pub intents: String,
/// The most aim switches one drone went through.
pub switches_max: u16,
/// Smart drones seen over the run (#149's comparison).
pub smart_seen: u32,
/// The share of them whose last aim was a live public hint when last seen (#149).
pub useful_share: f64,
/// Distinct aim units over the smart drones seen, per drone (#149).
pub diversity: f64,
/// The share of smart drones switched twice or more (#149's jitter).
pub jittery_share: f64,
/// The bearing picker's last typed reason (#149).
pub bearing_reason: String,
/// Aims the bounded refresh re-chose (#149).
pub refresh_applied: u32,
}
/// The last intent every smart drone of the run was seen carrying, as `name:count`.
fn intent_counts(seen: &HashMap<u32, &'static str>) -> String {
let mut counts = std::collections::BTreeMap::new();
for name in seen.values() {
*counts.entry(*name).or_insert(0usize) += 1;
}
["plan", "sead", "react", "replace", "refresh"].iter().map(|k| format!("{k}:{}", counts.get(*k).copied().unwrap_or(0))).collect::<Vec<_>>().join(",")
}
fn finite(v: DVec3) -> bool {
@@ -133,7 +170,14 @@ fn finite(v: DVec3) -> bool {
}
pub fn run(sc: &Scenario) -> Report {
run_with_hook(sc, &mut |_, _| {})
}
/// The same, with a hook called after every tick (#149's comparison runner): a scenario may
/// change the defence between waves or shoot a recon flight down before its report.
pub fn run_with_hook(sc: &Scenario, hook: &mut dyn FnMut(u64, &mut Sim)) -> Report {
let mut sim = Sim::new(sc.seed);
sim.smart_legacy = sc.legacy;
sim.damage = false; // explosions would change the land the height function describes
for u in &sc.units {
let id = sim.id();
@@ -160,6 +204,10 @@ pub fn run(sc: &Scenario) -> Report {
let mut ended = vec![false; sc.raids.len()];
// truck id -> (last position, ticks standing while busy)
let mut standing: HashMap<u32, (DVec3, u64)> = HashMap::new();
// drone id -> the last structured intent it carried (#127).
let mut intents_seen: HashMap<u32, &'static str> = HashMap::new();
// drone id -> (last aim unit, whether the picture held it live then, switches) (#149).
let mut decisions: HashMap<u32, (u32, bool, u16)> = HashMap::new();
let mut out = Out::default();
for now in 1..=sc.ticks {
// Raids come in order: one is ordered once the previous one has been sent.
@@ -182,6 +230,7 @@ pub fn run(sc: &Scenario) -> Report {
ground.world.serve(&sc.terrain, sections, now);
let dt = t.elapsed();
times.push(dt);
hook(now, &mut sim);
if planning {
r.planning += dt;
r.planning_ticks += 1;
@@ -192,6 +241,20 @@ pub fn run(sc: &Scenario) -> Report {
pending = wanted.into_iter().map(|(x, z)| (x, z, sc.terrain.height(x, z))).collect();
}
r.ticks_run = now;
r.retargets_max = r.retargets_max.max(sim.retargets_len());
r.switches_max = sim.drones.iter().chain(sim.queue.iter().map(|(_, d)| d)).map(|d| d.aim_switches()).max().unwrap_or(0).max(r.switches_max);
for d in sim.drones.iter().chain(sim.queue.iter().map(|(_, d)| d)) {
if d.alive() && d.smart() {
intents_seen.insert(d.id, d.intent().name());
let unit = d.aim_unit();
decisions.insert(d.id, (unit, unit != 0 && sim.known_live(unit), d.aim_switches()));
}
}
// The air section a save would take, sampled when the sky is fullest (writing it every tick
// would distort the timings the bench measures).
if sim.drones.len() > r.air_bytes {
r.air_bytes = sim.air_text().map_or(0, |t| t.len());
}
// NaN check on everything with a position.
let bad = sim.drones.iter().filter(|d| !finite(d.pos) || !finite(d.vel)).count()
+ sim.missiles.iter().filter(|m| !finite(m.pos)).count()
@@ -225,15 +288,29 @@ pub fn run(sc: &Scenario) -> Report {
}
}
r.launched = sim.launched;
r.sams_lost = sim.sams.iter().filter(|s| !s.alive()).count() as u32;
r.kills = sim.kills;
r.hits = sim.hits;
r.fired = sim.sams.iter().map(|s| s.fired).sum();
r.raids_ordered = ordered.iter().filter(|o| **o).count();
r.world = ground.world.text();
r.world = world_view::text(&ground.world);
r.crashes = sim.crashes;
r.failures = sim.tally.text();
r.raids_ended = ended.iter().filter(|o| **o).count();
r.all_ended = r.raids_ended == sc.raids.len();
r.intents = intent_counts(&intents_seen);
r.smart_seen = decisions.len() as u32;
if !decisions.is_empty() {
let n = decisions.len() as f64;
r.useful_share = decisions.values().filter(|(_, live, _)| *live).count() as f64 / n;
let mut units: Vec<u32> = decisions.values().map(|(u, _, _)| *u).collect();
units.sort_unstable();
units.dedup();
r.diversity = units.len() as f64 / n;
r.jittery_share = decisions.values().filter(|(_, _, s)| *s >= 2).count() as f64 / n;
}
r.bearing_reason = sim.bearing_report().reason.name().to_string();
r.refresh_applied = sim.refresh_applied();
r.tick_total = times.iter().sum();
times.sort();
if !times.is_empty() {
+187
View File
@@ -0,0 +1,187 @@
//! Smart v2 comparison runner (#149): the simple mode, the current (legacy) Smart and the
//! candidate, on fixed seeds and one scenario set — open map, hills, a configuration changed
//! between waves, and a recon flight shot down before its report.
//!
//! It prints one JSON array of rows: the share of useful decisions (a smart drone whose last
//! aim was a live public hint), the diversity of aims, the reasons (intents) on the review,
//! the share of jittery drones (two switches or more), the bearing picker's typed reason, the
//! refresh count, and the CPU/worst-job figures. The goal is interesting counterplay and clear
//! mistakes, not a maximised hit count — read the reasons and the jitter beside the losses.
//!
//! cargo run --release --example smart_bench
#[path = "sim_run/harness.rs"]
mod harness;
use airdef::sim::{Aim, Approach, DroneKind, Sam, SamKind, Sim};
use glam::DVec3;
use harness::{Report, Scenario, Terrain};
#[derive(Clone, Copy, PartialEq)]
enum Mode {
Simple,
Current,
Candidate,
}
impl Mode {
fn name(self) -> &'static str {
match self {
Mode::Simple => "simple",
Mode::Current => "current",
Mode::Candidate => "candidate",
}
}
fn apply(self, sc: &mut Scenario) {
sc.legacy = self == Mode::Current;
let aim = match self {
Mode::Simple => Aim::ObjectsAndSams,
_ => Aim::Smart,
};
for raid in &mut sc.raids {
raid.aim = aim;
}
}
}
fn esc(s: &str) -> String {
s.chars().flat_map(|c| match c {
'"' => "\\\"".chars().collect::<Vec<_>>(),
'\\' => "\\\\".chars().collect::<Vec<_>>(),
c => vec![c],
}).collect()
}
fn row(sc: &str, mode: Mode, r: &Report) -> String {
format!(
"{{\"scenario\":\"{}\",\"mode\":\"{}\",\"seed\":{},\"ticks\":{},\"all_ended\":{},\"launched\":{},\"kills\":{},\"hits\":{},\"fired\":{},\"sams_lost\":{},\"smart_seen\":{},\"useful_share\":{:.3},\"diversity\":{:.3},\"jittery_share\":{:.3},\"intents\":\"{}\",\"bearing_reason\":\"{}\",\"refresh_applied\":{},\"switches_max\":{},\"retargets_max\":{},\"tick_p95_ms\":{:.3},\"tick_max_ms\":{:.3},\"planning_ms\":{:.1},\"air_bytes\":{}}}",
esc(sc),
mode.name(),
r.seed,
r.ticks_run,
r.all_ended,
r.launched,
r.kills,
r.hits,
r.fired,
r.sams_lost,
r.smart_seen,
r.useful_share,
r.diversity,
r.jittery_share,
esc(&r.intents),
esc(&r.bearing_reason),
r.refresh_applied,
r.switches_max,
r.retargets_max,
r.tick_p95.as_secs_f64() * 1000.0,
r.tick_max.as_secs_f64() * 1000.0,
r.planning.as_secs_f64() * 1000.0,
r.air_bytes,
)
}
/// An open map: a ring of systems on flat land, one combined strike.
fn open() -> Scenario {
let mut sc = Scenario::new("open");
sc.terrain = Terrain::Flat(70);
for i in 0..18 {
let a = i as f64 * 2.399_963;
let r = 120.0 + (i as f64 / 18.0) * 320.0;
let kind = [SamKind::Radar, SamKind::S400, SamKind::Pantsir, SamKind::Ew, SamKind::Tor][i % 5];
sc.unit(kind, a.sin() * r, a.cos() * r).heading = a;
}
sc.raids.push(harness::RaidSpec {
kinds: vec![(DroneKind::Gerbera, 6), (DroneKind::Shahed, 10), (DroneKind::Kh101, 3), (DroneKind::Kh22, 2), (DroneKind::Lancet, 3)],
approach: Approach::AllSides,
aim: Aim::Smart,
dist: 500.0,
at: 1,
});
sc.ticks = 20 * 60 * 6;
sc
}
/// Hills: the standard big smart scenario's terrain and force.
fn hills() -> Scenario {
let mut sc = harness::big_smart();
sc.name = "hills".into();
sc.ticks = 20 * 60 * 6;
sc
}
/// Two waves with the defence changed between them: a radar moves unobserved, the EW stations
/// switch on, and a fresh battery appears. The second wave's picture must earn what it knows.
fn config_change() -> Scenario {
let mut sc = open();
sc.name = "config-change".into();
sc.raids.push(harness::RaidSpec {
kinds: vec![(DroneKind::Shahed, 8), (DroneKind::Geran3, 4), (DroneKind::Kh22, 2), (DroneKind::Iskander, 2)],
approach: Approach::TwoSectors,
aim: Aim::Smart,
dist: 600.0,
at: 4200,
});
sc.ticks = 20 * 60 * 10;
sc
}
/// A recon flight shot down before its report: the strike must fly on the picture it had, and
/// the bounded refresh must never hold the raid waiting for a report that will not come.
fn recon_lost() -> Scenario {
let mut sc = open();
sc.name = "recon-lost".into();
sc.ticks = 20 * 60 * 6;
sc
}
pub fn main() {
let seeds = [1u64, 7, 42];
let scenarios: [(&str, fn() -> Scenario); 4] = [("open", open), ("hills", hills), ("config-change", config_change), ("recon-lost", recon_lost)];
let modes = [Mode::Simple, Mode::Current, Mode::Candidate];
let mut rows = Vec::new();
for (name, make) in scenarios {
for mode in modes {
for &seed in &seeds {
let r = run(mode, name, make, seed);
rows.push(row(name, mode, &r));
eprintln!("{name} {} seed {seed}: useful {:.2} diversity {:.2} jitter {:.2} kills {} hits {} reasons {} bearing {} refresh {}", mode.name(), r.useful_share, r.diversity, r.jittery_share, r.kills, r.hits, r.intents, r.bearing_reason, r.refresh_applied);
}
}
}
println!("[{}]", rows.join(",\n"));
}
fn run(mode: Mode, name: &str, make: fn() -> Scenario, seed: u64) -> Report {
let mut sc = make();
sc.seed = seed;
mode.apply(&mut sc);
match name {
"config-change" => {
let mut changed = false;
harness::run_with_hook(&sc, &mut |now, sim: &mut Sim| {
if !changed && now >= 3600 && !sim.planning() {
changed = true;
if let Some(radar) = sim.sams.iter_mut().find(|s| s.kind == SamKind::Radar) {
radar.pos += DVec3::new(300.0, 0.0, -200.0);
}
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Pantsir, DVec3::new(-200.0, 70.0, 250.0), 0.0));
sim.set_ew(true);
}
})
}
"recon-lost" => {
let mut killed = false;
harness::run_with_hook(&sc, &mut |now, sim: &mut Sim| {
if !killed && now >= 120 {
let recon: Vec<u32> = sim.drones.iter().filter(|d| sim.is_recon_drone(d.id)).map(|d| d.id).collect();
if !recon.is_empty() {
sim.drones.retain(|d| !recon.contains(&d.id));
killed = true;
}
}
})
}
_ => harness::run(&sc),
}
}
+22 -4
View File
@@ -114,12 +114,18 @@ b50fe5804cbbe10df992ebbc7e095a32ce8b73fc35159fa19889640681e408e9 assets/airdef/
0c9c5ee3fc87e2dc6d716bdb0bb5f30d3b265268bfd5083462b4861a8da65f0f assets/airdef/items/deploy_irist.json
09e46a6c4b59f66c24060ac627e6a287bf6797c7b1e32a9ec6c9d9662fdc3de3 assets/airdef/items/deploy_light.json
6983561b3558aee16662aa83d2d9af760fb6236cc7dbe79ba20802f8a2ff15b9 assets/airdef/items/deploy_nasams.json
e39c555ff197ed6c7c8fdfab924b7a609b5d111a905ca599a75a7b1270448fcc assets/airdef/items/deploy_optical.json
d8ac6a9258e2fc2e0791bbce18a3a07a72e471fbc72b6be7b5ca545c53f8d633 assets/airdef/items/deploy_p1sun.json
e2353c70f6e5053864ab2fdf51df886d72c03e5c34db84fef8f3fff9c84a7ae4 assets/airdef/items/deploy_pantsir.json
68dd9b1382b2dd6ad23d0f507a8cfcdcfa18ef5c4203e69c61f6ade9cfbf238e assets/airdef/items/deploy_patriot.json
d93b6bf77de4aed1f1955e76353661729f06445788ad7a6654ed6af1a67fc48d assets/airdef/items/deploy_radar.json
84306c42dd25300f1cef69c83e3211ccc921fa606046157295a4ca3e3d568a0a assets/airdef/items/deploy_radar_height.json
28f6b71116bdc911e70d2382807c86edff40adae44acd256f798360dc60bd572 assets/airdef/items/deploy_radar_search.json
0e470cfa2a13383fadb74336c5333449f4079659d9d83596dcfcf2d592521a4c assets/airdef/items/deploy_radar_track.json
0b9445f3b54a9e958da0b9bd4243a41d85fc8f12b5c4e56bbc070edb8f1bf618 assets/airdef/items/deploy_s400.json
77355fc96ed50feb117bc6e7f7f70e9559bc69174a7a84afe7e3121db65efbfd assets/airdef/items/deploy_s400_launcher.json
dd7478f447d87dcad42e1a7e6dcb5fae555c832e933a3722022d0e10e2de011e assets/airdef/items/deploy_s500.json
47dabb117d3e6fb44005f4be8c2be2b6c4f8d7e06ff5ed2d426ac1e58e6408ce assets/airdef/items/deploy_s500_launcher.json
14e9a20dcddee5a6262ef624783900576dac2bd16e5079e731cf6115f13c76ec assets/airdef/items/deploy_tor.json
d4ff57f630ca92bf52ba228d8c6fd5292928b685d6bb5a9c9b9dc0c3d586fc2e assets/airdef/items/deploy_tzm.json
044fc626ad99ff8be6db0800f96dc743fc80606d813bd59abad531396bf9d8ce assets/airdef/items/designator.json
@@ -136,8 +142,8 @@ b4d98a938486d49db28c6c7a608ca3b6ab0c9c3eac266ecf12c7dd931cc28f93 assets/airdef/
489799dcb5b441e9d4be8bfb3d73a6ebd5fdf2b5ee614b62f38b85bb2fbfad75 assets/airdef/items/launch_zircon.json
6b6da5887aa8d9bc987b2c181c243bc2afdd5846a869818f699b59204e559929 assets/airdef/items/mover.json
177f7535e4c52ed975d6f737c2b2acb7741b7a928955c8899aced85211443bbf assets/airdef/items/remover.json
cede33ba58f61891a8afe42e1f4311cb293ca93f4d7eb3a57636caff17317a4d assets/airdef/lang/en_us.json
cede33ba58f61891a8afe42e1f4311cb293ca93f4d7eb3a57636caff17317a4d assets/airdef/lang/ru_ru.json
ddfba1d8e940c870b43268a5d8ebae130a4061f2f734a750df4bfd54452c8012 assets/airdef/lang/en_us.json
ddfba1d8e940c870b43268a5d8ebae130a4061f2f734a750df4bfd54452c8012 assets/airdef/lang/ru_ru.json
b9b5b5bec33a77e944552c225ee2f526ab9820fa8fca4b3ccf311f2a325925ee assets/airdef/models/block/amraam_missile.json
c54e6b24ab69e9d9a2dbbbc63fe2ac60fa37735bf644500ddd5c3de0b91908cf assets/airdef/models/block/barge.json
a4198ff647de5866919f9b82a3d53e6486fc56cc9f175f7907951d063a6f4526 assets/airdef/models/block/beam.json
@@ -173,10 +179,10 @@ e6cb3f578b875d3683d2a027f1ac34226b56c4db410fecc6479e2683485b8c3e assets/airdef/
449284669a58d71ae2de7e68cd7cf18ae21fec70ceb3124cd24fb4a09fc49909 assets/airdef/models/block/irist_tubes_burnt.json
be87037b84cd45b2c53d7fde6653f51769e782eea1b8586383afcfababf19ab6 assets/airdef/models/block/iskander.json
98d488ca797fb3d0193957b8a93a82f48376a89f8e091032e6365d1845016a90 assets/airdef/models/block/kalibr.json
be9eb1389e169a76732f16e604499260b147b524b4c929d2a4e77b580a032fb7 assets/airdef/models/block/kh101.json
20deb68dbba6eb64b7c51685497110ef7d1d3bf0aa7e7167c558e0a8e842e759 assets/airdef/models/block/kh101.json
ea7c9af888f1285502b2ca51114f226573311be6fb90b8d449b9f75cfbb6b885 assets/airdef/models/block/kh22.json
7b73015e33d85d4cef31660ef874ba8dcd6e07ae3a95416d0ead1d325bd0cb6c assets/airdef/models/block/kinzhal.json
911e55de28058e1723a61d15de80676789e57ab15bfc09fd75757cc85095fbcb assets/airdef/models/block/lancet.json
69135e90a1a7fb21d9f47b1854c5a3648e296136c2375acd9db5a48b0ad40887 assets/airdef/models/block/lancet.json
15c9884ce51311cf4b9b9d106e142e33d72c5ba18dc9236c5b51da01232f8e44 assets/airdef/models/block/launch_ramp.json
159fa5e3b6a096a1872dec2a550bfa30575d57519654a860607e20dab8f35f53 assets/airdef/models/block/launcher_truck.json
2069198ba24a932816f504fb52f53dc4bc740cacaf45637698a17d9175da851c assets/airdef/models/block/m48n6.json
@@ -254,12 +260,18 @@ a5d0450da8d6757b9b45f86e6b36977894dd9e3e1278c3668b99a8acab36f399 assets/airdef/
e80ee81085241b9712e024bbef73ef744ef5493eebb88770f4912d8aae138fe6 assets/airdef/models/item/deploy_irist.json
637b9bfe426ee50045f8fcbfd4f25dfbc1d819ce36dedbd60abdac63c274f088 assets/airdef/models/item/deploy_light.json
3398844e90203f97ee73e35619684c775d1856c8ca3399b5ed682786170d9327 assets/airdef/models/item/deploy_nasams.json
332f9de8c88658a562748fc7a6de7ec37847273ac0cd0733e23c0dff4b44418c assets/airdef/models/item/deploy_optical.json
76019c05d070cf1141cdf95b744b3d6198ab99469dba1f88a6903de1de303bde assets/airdef/models/item/deploy_p1sun.json
8b1af688bc83be5a8065673bca7054deee86ca425f0bfd1fb4ffb491844e90bf assets/airdef/models/item/deploy_pantsir.json
d0091d809816350c648e532a90ae59a3c5c9b94f837b2a46b5695e7f985a00f9 assets/airdef/models/item/deploy_patriot.json
332f9de8c88658a562748fc7a6de7ec37847273ac0cd0733e23c0dff4b44418c assets/airdef/models/item/deploy_radar.json
332f9de8c88658a562748fc7a6de7ec37847273ac0cd0733e23c0dff4b44418c assets/airdef/models/item/deploy_radar_height.json
332f9de8c88658a562748fc7a6de7ec37847273ac0cd0733e23c0dff4b44418c assets/airdef/models/item/deploy_radar_search.json
332f9de8c88658a562748fc7a6de7ec37847273ac0cd0733e23c0dff4b44418c assets/airdef/models/item/deploy_radar_track.json
9ee1dfa7d2c2587c85a8f73554962a02a06f1969a9a56c56110162dd93db7301 assets/airdef/models/item/deploy_s400.json
9ee1dfa7d2c2587c85a8f73554962a02a06f1969a9a56c56110162dd93db7301 assets/airdef/models/item/deploy_s400_launcher.json
55f1dae5cd7f0126533825c9da3ed3ee316e74d4be8f9bb217a3ebc6f827d24d assets/airdef/models/item/deploy_s500.json
55f1dae5cd7f0126533825c9da3ed3ee316e74d4be8f9bb217a3ebc6f827d24d assets/airdef/models/item/deploy_s500_launcher.json
aca5ea765ca0d84ed12444bf433c024b57d6ea9b9b7cf06449dfbd6892a66ae6 assets/airdef/models/item/deploy_tor.json
67912cc711c2f1514e6e2f8f17aa340fa9a99534fbbaeb2b8e319aa6ef80f38d assets/airdef/models/item/deploy_tzm.json
d0976d990130c6398f4adf5d3086e9cf50e5a2adbec081e4682e810af368c332 assets/airdef/models/item/designator.json
@@ -567,12 +579,18 @@ cc0877f40434365b45b03429222926aa0cf135e504017311be53263fd27c5f8f data/airdef/ho
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_irist.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_light.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_nasams.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_optical.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_p1sun.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_pantsir.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_patriot.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_radar.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_radar_height.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_radar_search.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_radar_track.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_s400.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_s400_launcher.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_s500.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_s500_launcher.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_tor.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_tzm.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/designator.json
+26 -19
View File
@@ -209,26 +209,33 @@ fn post(uv: vec2<f32>, pixel: vec2<f32>) -> vec4<f32> {
let on_screen = radius / max(length(centre), 1.0);
let steps = i32(clamp(on_screen * 40.0, 6.0, 14.0));
let ds = (t1 - t0) / f32(steps);
for (var s = 0; s < steps; s++) {
if trans < 0.02 { break; }
let p = dir * (t0 + (f32(s) + 0.5) * ds);
let local = (p - centre) / radius;
let r = length(local);
let n = fbm(local * 2.4 + seed + vec3<f32>(0.0, -age * 0.06, age * 0.02));
let shape = smoothstep(1.0, 0.25, r + (n - 0.5) * 1.1);
if shape <= 0.0 { continue; }
let density = shape * (1.2 + n * 2.0) * fade;
let absorb = 1.0 - exp(-density * ds * 1.4 / max(radius * 0.25, 0.5));
// Hot inside, soot outside; smoke lit from above by the sky.
let core = heat * (1.0 - r) * (0.6 + n);
let smoke = vec3<f32>(0.10, 0.095, 0.09) * (0.5 + 0.8 * sun * (0.5 + local.y * 0.5));
let c = mix(smoke, fire(core * 1.6), clamp(core * 2.2, 0.0, 1.0));
lit += trans * absorb * c;
trans *= 1.0 - absorb;
// At zero fade every step's density is zero: absorb is 0, so the march adds no light and
// leaves the transmittance alone. Skip it (the HD smoke path fades out by k = 0.28) instead
// of sampling the noise and shading a volume that cannot be seen.
if fade > 0.0 {
for (var s = 0; s < steps; s++) {
if trans < 0.02 { break; }
let p = dir * (t0 + (f32(s) + 0.5) * ds);
let local = (p - centre) / radius;
let r = length(local);
let n = fbm(local * 2.4 + seed + vec3<f32>(0.0, -age * 0.06, age * 0.02));
let shape = smoothstep(1.0, 0.25, r + (n - 0.5) * 1.1);
if shape <= 0.0 { continue; }
let density = shape * (1.2 + n * 2.0) * fade;
let absorb = 1.0 - exp(-density * ds * 1.4 / max(radius * 0.25, 0.5));
// Hot inside, soot outside; smoke lit from above by the sky.
let core = heat * (1.0 - r) * (0.6 + n);
let smoke = vec3<f32>(0.10, 0.095, 0.09) * (0.5 + 0.8 * sun * (0.5 + local.y * 0.5));
let c = mix(smoke, fire(core * 1.6), clamp(core * 2.2, 0.0, 1.0));
lit += trans * absorb * c;
trans *= 1.0 - absorb;
}
}
// Light thrown round by the fire (zero once its heat is spent).
if heat > 0.0 {
let d = length(centre);
glow += vec3<f32>(1.0, 0.5, 0.15) * heat * heat * size * 0.05 / (1.0 + d * 0.03);
}
// Light thrown round by the fire.
let d = length(centre);
glow += vec3<f32>(1.0, 0.5, 0.15) * heat * heat * size * 0.05 / (1.0 + d * 0.03);
}
color = color * trans + lit;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+213
View File
@@ -0,0 +1,213 @@
//! Player-facing labels for battery configuration and status.
use crate::sim::battery::{BatteryStatus, RadarProfile, SamMode};
use crate::sim::{Sam, SamKind};
/// One profile's functions in a line the player can read.
pub fn radar_profile_line(profile: RadarProfile) -> String {
let channels = if profile.channels == 0 { "без каналов уточнения".to_string() } else { format!("каналы {}", profile.channels) };
format!(
"{} [{}]: {}, оборот {:.1} с, {}, локальный поиск {}; развёртывание: {}",
profile.name,
profile.id,
profile.products_text(),
profile.cycle as f64 / 20.0,
channels,
if profile.local >= 1.0 { "во всей дальности".to_string() } else { format!("{:.0}% дальности", profile.local * 100.0) },
profile.deployment,
)
}
pub fn status(status: BatteryStatus) -> String {
match status {
BatteryStatus::Radar { index, role, emitting, operational } => {
let profile = role.profile();
format!(
"№{} РЛС: {}; излучение {}, {}",
index + 1,
radar_profile_line(profile),
if emitting { "вкл" } else { "выкл" },
if operational { "работает" } else { "нет связи или РЛС не работает" }
)
}
BatteryStatus::Launcher { index, kind, mode, linked } => format!(
"№{} {}: {}{}", index + 1, kind.name(), mode.key(),
if mode == SamMode::LauncherOnly {
if linked { ", РЛС связана" } else { ", нет связанной РЛС сопровождения" }
} else { "" }
),
}
}
/// One system's line in the summary panel and on the map.
pub fn sam_status(sam: &Sam, now: u64) -> String {
let spec = sam.kind.spec();
let mut text = spec.name.to_string();
if !sam.alive() {
return text + " УНИЧТОЖЕН";
}
if sam.moving() {
return text + " " + &sam.state.name().to_lowercase();
}
match sam.kind {
SamKind::Depot => return format!("{text}: {} перезарядок, RM48U {}, снятых ПВО {}", sam.cargo, sam.ground_stock, sam.air_48n6_stock),
SamKind::Tzm => return format!(
"{text}: на борту {}/2, RM48U {}, снятых ПВО {}{}",
sam.cargo,
sam.ground_stock,
sam.air_48n6_stock,
if sam.return_cargo { ", везёт RM48U на склад" } else if sam.job().is_some() { ", в пути" } else { "" }
),
SamKind::Ew => {
let state = if sam.ew_on { "ГЛУШИТ" } else if sam.ew_lock { "остывает" } else { "готова" };
return format!("{text}: {state}, нагрев {:.0}%", sam.heat * 100.0);
}
SamKind::Radar => {
let broken = if sam.comps.whole() { String::new() } else { format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind)) };
let profile = sam.radar_profile();
let channels = if profile.channels == 0 {
"без уточнения".to_string()
} else {
format!("каналы {}/{}", sam.own_channels_used(now), profile.channels)
};
return format!("{text} «{}»: {}; целей {}{broken}, {channels}", profile.name, profile.products_text(), sam.own.len());
}
SamKind::Light => return format!("{text}{}", if sam.target.is_some() { ": в луче цель" } else { "" }),
SamKind::Optical => {
let mut t = format!("{text}: {}", sam.optical.status_text());
if sam.health < 1.0 {
t += &format!(" ({:.0}%)", sam.health * 100.0);
}
if !sam.comps.whole() {
t += &format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind));
}
return t;
}
_ => {}
}
if let Some(cell) = sam.preparing_cell() {
text += &format!(" · открытие ТПК №{}", cell + 1);
}
if sam.empty && sam.missiles == 0 {
text += " ЖДЁТ БК";
}
if sam.health < 1.0 {
text += &format!(" ({:.0}%)", sam.health * 100.0);
}
if !sam.comps.whole() {
text += &format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind));
}
if sam.reloading > 0 {
text += &format!(" перезарядка {}с", sam.reloading.div_ceil(20));
} else {
if let Some(magazine) = sam.kind.missile_magazine() {
if sam.kind == SamKind::S400 {
text += &format!(" ПВО {} · RM48U {} / {} ячеек", sam.missiles, sam.ground_rounds, sam.cells());
if sam.ground_return { text += " · ожидает вывоза RM48U"; }
} else {
text += &format!(" ракеты {}/{}", sam.missiles, magazine);
}
}
if sam.kind.has_gun() {
text += &format!(" очереди {}", sam.bursts);
}
}
text
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::battery::RadarRole;
use crate::sim::{Part, Sam, SamKind, SamState};
use glam::DVec3;
#[test]
fn renders_system_status_in_existing_format() {
let mut s400 = Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0);
s400.missiles = 1;
s400.ground_rounds = 2;
assert_eq!(sam_status(&s400, 0), "С-400 ПВО 1 · RM48U 2 / 4 ячеек");
s400.ground_return = true;
assert_eq!(sam_status(&s400, 0), "С-400 ПВО 1 · RM48U 2 / 4 ячеек · ожидает вывоза RM48U");
let mut pantsir = Sam::new(2, SamKind::Pantsir, DVec3::ZERO, 0.0);
pantsir.missiles = 7;
pantsir.bursts = 100;
assert_eq!(sam_status(&pantsir, 0), "Панцирь-С1 ракеты 7/12 очереди 100");
let mut worn = Sam::new(3, SamKind::Patriot, DVec3::ZERO, 0.0);
worn.health = 0.5;
worn.comps.0[Part::Sensor as usize] = 0.4;
worn.reloading = 21;
assert_eq!(sam_status(&worn, 0), "Patriot (50%) [РЛС 40%] перезарядка 2с");
}
#[test]
fn renders_special_system_lines_in_existing_format() {
let mut radar = Sam::new(4, SamKind::Radar, DVec3::ZERO, 0.0);
radar.own.push(7);
radar.comps.0[Part::Sensor as usize] = 0.0;
assert_eq!(sam_status(&radar, 0), "РЛС дальнего обнаружения «многофункциональная»: обзор, уточнение, пуск; целей 1 [РЛС отказ], каналы 0/3");
let mut depot = Sam::new(5, SamKind::Depot, DVec3::ZERO, 0.0);
depot.cargo = 2;
depot.ground_stock = 3;
depot.air_48n6_stock = 1;
assert_eq!(sam_status(&depot, 0), "Склад боеприпасов: 2 перезарядок, RM48U 3, снятых ПВО 1");
let mut tzm = Sam::new(6, SamKind::Tzm, DVec3::ZERO, 0.0);
tzm.cargo = 1;
tzm.return_cargo = true;
assert_eq!(sam_status(&tzm, 0), "ТЗМ: на борту 1/2, RM48U 0, снятых ПВО 0, везёт RM48U на склад");
let mut ew = Sam::new(7, SamKind::Ew, DVec3::ZERO, 0.0);
ew.ew_on = true;
ew.heat = 0.5;
assert_eq!(sam_status(&ew, 0), "Станция РЭБ: ГЛУШИТ, нагрев 50%");
let mut light = Sam::new(8, SamKind::Light, DVec3::ZERO, 0.0);
light.target = Some(1);
assert_eq!(sam_status(&light, 0), "Прожектор: в луче цель");
let optical = Sam::new(9, SamKind::Optical, DVec3::ZERO, 0.0);
assert_eq!(sam_status(&optical, 0), "Оптический пост: ищет");
}
#[test]
fn renders_moving_and_destroyed_systems_in_existing_format() {
let mut moving = Sam::new(9, SamKind::S400, DVec3::ZERO, 0.0);
moving.state = SamState::Moving;
assert_eq!(sam_status(&moving, 0), "С-400 на марше");
let mut dead = Sam::new(10, SamKind::S400, DVec3::ZERO, 0.0);
dead.health = 0.0;
assert_eq!(sam_status(&dead, 0), "С-400 УНИЧТОЖЕН");
}
#[test]
fn profiles_explain_their_different_functions() {
for role in [RadarRole::Search, RadarRole::Height, RadarRole::Engagement, RadarRole::Multifunction] {
let text = radar_profile_line(role.profile());
assert!(text.contains(role.profile().id));
assert!(text.contains(&format!("оборот {:.1} с", role.profile().cycle as f64 / 20.0)));
}
assert!(radar_profile_line(RadarRole::Search.profile()).contains("без каналов"));
assert!(radar_profile_line(RadarRole::Engagement.profile()).contains("каналы 2"));
assert!(radar_profile_line(RadarRole::Height.profile()).contains("уточнение"));
}
#[test]
fn renders_battery_status_in_existing_format() {
assert_eq!(
status(BatteryStatus::Radar { index: 0, role: RadarRole::Search, emitting: false, operational: false }),
"№1 РЛС: дальнего обзора [radar_search]: обзор, оборот 8.5 с, без каналов уточнения, локальный поиск во всей дальности; развёртывание: крупная стационарная антенна; излучение выкл, нет связи или РЛС не работает"
);
assert_eq!(
status(BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: true, operational: true }),
"№2 РЛС: сопровождения [radar_track]: обзор, уточнение, пуск, оборот 3.5 с, каналы 2, локальный поиск 12% дальности; развёртывание: мобильная панель; излучение вкл, работает"
);
assert_eq!(status(BatteryStatus::Launcher { index: 2, kind: SamKind::S400, mode: SamMode::LauncherOnly, linked: true }), "№3 С-400: launcher, РЛС связана");
assert_eq!(status(BatteryStatus::Launcher { index: 3, kind: SamKind::S500, mode: SamMode::LauncherOnly, linked: false }), "№4 С-500: launcher, нет связанной РЛС сопровождения");
assert_eq!(status(BatteryStatus::Launcher { index: 4, kind: SamKind::S400, mode: SamMode::Integrated, linked: false }), "№5 С-400: integrated");
}
}
+99 -1
View File
@@ -59,10 +59,43 @@ fn line(
format!("{name}: API={available}, включено={enabled}, запрос={accepted}, подготовлено={prepared}, поколение={generation}, {why}")
}
fn camera_line(s: &render::CameraState) -> String {
let cameras: Vec<String> = s
.cameras
.iter()
.map(|c| {
let why = match c.reason {
render::CameraReason::AwaitingFrame => "awaiting-frame",
render::CameraReason::Ready => "ready",
};
format!("{}:{}", c.id, why)
})
.collect();
let main = match s.main_view {
Some(id) => id.to_string(),
None => "нет".into(),
};
format!(
"Камеры: API={}, включено={}, запрос={}, подготовлено={}, поколение={}, {}, main={}, [{}]",
s.available,
s.enabled,
s.request_accepted,
s.prepared,
s.generation,
reason(s.reason),
main,
cameras.join("; ")
)
}
pub fn diagnostics() -> String {
let smoke = render::smoke_status();
let acoustic = acoustics();
let capture = render::capture_owner_status();
let lights = render::point_lights_status();
let sources = render::sound_sources_status();
let cameras = render::camera_status();
let dlss = render::dlss_status();
let smoke_reason = match smoke.reason {
render::SmokeReason::AwaitingFrame => "awaiting-frame",
render::SmokeReason::Disabled => "disabled",
@@ -70,7 +103,7 @@ pub fn diagnostics() -> String {
render::SmokeReason::Ready => "ready",
};
[
"Возможности движка (API 27; подготовка не означает готовый GPU-кадр или файл):".into(),
"Возможности движка (API 33; подготовка не означает готовый GPU-кадр, слышимый звук или файл):".into(),
line(
"Дым",
smoke.generation,
@@ -89,6 +122,25 @@ pub fn diagnostics() -> String {
acoustic.prepared,
reason(acoustic.reason),
),
line(
"Точечный свет",
lights.generation,
lights.available,
lights.enabled,
lights.request_accepted,
lights.prepared,
reason(lights.reason),
),
line(
"Постоянные звуки",
sources.generation,
sources.available,
sources.enabled,
sources.request_accepted,
sources.prepared,
reason(sources.reason),
),
camera_line(&cameras),
line(
"Захват этого мода",
capture.generation,
@@ -98,6 +150,10 @@ pub fn diagnostics() -> String {
capture.prepared,
reason(capture.reason),
),
format!(
"DLSS: устройство={}, включено={} (выкл — родной TAAU; вкл без устройства — при следующем запуске)",
dlss.available, dlss.enabled
),
]
.join("\n")
}
@@ -144,4 +200,46 @@ mod tests {
s.reason = CapabilityReason::Failed;
assert!(capture_problem(&s).is_some());
}
fn camera(id: u32, prepared: bool) -> render::CameraReadiness {
render::CameraReadiness {
id,
request_accepted: true,
prepared,
reason: if prepared {
render::CameraReason::Ready
} else {
render::CameraReason::AwaitingFrame
},
}
}
#[test]
fn the_camera_line_separates_readiness_from_the_screens_selection() {
let line = camera_line(&render::CameraState {
generation: 5,
available: true,
enabled: true,
request_accepted: true,
prepared: true,
reason: CapabilityReason::Ready,
cameras: vec![camera(7, true), camera(8, false)],
main_view: Some(7),
});
assert_eq!(
line,
"Камеры: API=true, включено=true, запрос=true, подготовлено=true, поколение=5, \
ready, main=7, [7:ready; 8:awaiting-frame]"
);
// No accepted submission: no cameras, no main view, and the reason says so.
let line = camera_line(&render::CameraState {
generation: 5,
available: true,
enabled: false,
request_accepted: false,
prepared: false,
reason: CapabilityReason::NotRequested,
cameras: Vec::new(),
main_view: None,
});
assert!(line.ends_with("not-requested, main=нет, []"), "{line}");
}
}
+14 -12
View File
@@ -2,15 +2,17 @@
//! tail; from afar the muffled report and a late boom), and the camera's reaction (a brief
//! exposure and bloom punch). Everything is a function of the blast, its distance and its age, so
//! a replay hears and sees the same as the live raid did, from the replay's camera.
use crate::sim::catalog::sound;
/// The power (0 air burst .. 4 ballistic) of a blast sound event, if it is one.
pub fn blast_power(event: &str) -> Option<usize> {
Some(match event {
"airdef:blast.air" => 0,
"airdef:blast.medium" => 1,
"airdef:blast.big" => 2,
"airdef:blast.heavy" => 3,
"airdef:blast.huge" => 4,
sound::BLAST_AIR => 0,
sound::BLAST_MEDIUM => 1,
sound::BLAST_BIG => 2,
sound::BLAST_HEAVY => 3,
sound::BLAST_HUGE => 4,
_ => return None,
})
}
@@ -34,7 +36,7 @@ pub const FULL: usize = 3;
/// nearest of its tick.
pub fn layers(power: usize, dist: f64, far: f64, gain: f32, pitch: f32, rank: usize) -> Vec<Layer> {
let g = gain.clamp(0.3, 2.0);
let own = ["airdef:blast.air", "airdef:blast.medium", "airdef:blast.big", "airdef:blast.heavy", "airdef:blast.huge"][power.min(4)];
let own = [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][power.min(4)];
let layer = |name: &str, volume: f32, pitch: f32, delay: u64| Layer { name: name.to_string(), volume, pitch, delay };
let far_away = dist > far;
let suffix = if far_away { "_far" } else { "" };
@@ -45,22 +47,22 @@ pub fn layers(power: usize, dist: f64, far: f64, gain: f32, pitch: f32, rank: us
// The muffled report, then a deep boom that arrives late.
return vec![
layer(&format!("{own}_far"), g, pitch, 0),
layer("airdef:blast.big_far", 0.7 * g, pitch * 0.6, 10 + 2 * power as u64),
layer(sound::BLAST_BIG_FAR, 0.7 * g, pitch * 0.6, 10 + 2 * power as u64),
];
}
let tail = (0.45 + 0.08 * power as f32) * g;
if power == 0 {
// An air burst has no body of its own: the crack, the thump, the roll.
vec![
layer("airdef:blast.air", g, pitch * 1.12, 0),
layer("airdef:blast.big", 0.85 * g, pitch * 0.66, 2),
layer("airdef:blast.huge", tail, pitch * 0.5, 7),
layer(sound::BLAST_AIR, g, pitch * 1.12, 0),
layer(sound::BLAST_BIG, 0.85 * g, pitch * 0.66, 2),
layer(sound::BLAST_HUGE, tail, pitch * 0.5, 7),
]
} else {
vec![
layer(own, g, pitch, 0),
layer("airdef:blast.air", 0.7 * g, pitch * 1.15, 0),
layer("airdef:blast.huge", tail, pitch * 0.5, 7),
layer(sound::BLAST_AIR, 0.7 * g, pitch * 1.15, 0),
layer(sound::BLAST_HUGE, tail, pitch * 0.5, 7),
]
}
}
+39 -8
View File
@@ -14,7 +14,7 @@ fn on_off() -> Value {
/// `/airdef ...` as `lib.rs` accepts it.
pub fn tree() -> Tree {
let wave_kinds: Vec<&str> = DroneKind::ALL.iter().map(|k| k.spec().key).chain(["mix"]).collect();
let deploy_kinds: Vec<&str> = SamKind::ALL.iter().map(|k| k.key()).chain(["s400_launcher", "s500_launcher", "radar_search", "radar_track", "radar_height"]).collect();
let deploy_kinds: Vec<&str> = SamKind::ALL.iter().map(|k| k.key()).chain(crate::sim::catalog::VARIANTS.iter().map(|v| v.id)).collect();
let armed: Vec<&str> = SamKind::ARMED.iter().map(|k| k.key()).chain(["all"]).collect();
let toggle = |word: &str| Node::lit(word).then(Node::arg("on/off", on_off()).runs());
Tree::new("airdef").runs().with([
@@ -56,8 +56,15 @@ pub fn tree() -> Tree {
),
Node::lit("list").runs(),
Node::lit("delete").then(Node::arg("имя", Value::names(SCENARIOS)).runs()),
Node::lit("village").runs().then(
Node::arg("режим", Value::choice(["easy", "normal", "hard", "start", "status", "prices", "stop"])).runs(),
),
]),
Node::lit("why").runs().then(Node::arg("номер", Value::int_from(1)).runs()),
Node::lit("breaches").runs().then(Node::arg("страница", Value::int_from(1)).runs()),
Node::lit("why").runs().then(
Node::arg("номер", Value::int_from(1)).runs().then(Node::lit("source").runs()),
),
Node::lit("chains").runs().then(Node::arg("батарея", Value::int_from(1)).runs()),
Node::lit("raid").runs(),
Node::lit("sites").runs(),
Node::lit("ground-stock").then(Node::arg("склад", Value::int_from(1)).then(Node::arg("количество", Value::int_from(0)).runs())),
@@ -73,7 +80,7 @@ pub fn tree() -> Tree {
Node::lit("target").then(Node::lit("here").runs()),
Node::lit("give").runs(),
Node::lit("battery").runs().then(Node::arg("номер", Value::int_from(1)).then(Node::arg("режим", Value::choice(["integrated", "launcher"])).runs())),
Node::lit("radar").then(Node::arg("номер", Value::int_from(1)).then(Node::arg("роль", Value::choice(["on", "off", "multi", "search", "engagement", "height"])).runs())),
Node::lit("radar").then(Node::arg("номер", Value::int_from(1)).then(Node::arg("режим", Value::Word(vec!["on".into(), "off".into()])).runs())),
Node::lit("deploy").then(Node::arg("комплекс", Value::choice(deploy_kinds)).runs()),
Node::lit("wave").then(
Node::arg("тип", Value::choice(wave_kinds)).runs().then(
@@ -106,6 +113,16 @@ pub fn tree() -> Tree {
Node::lit("guard").with([Node::lit("off").runs(), Node::arg("объекты", Value::word()).runs()]),
Node::lit("reset").runs(),
])),
Node::lit("recon").runs(),
Node::lit("post").runs().then(Node::arg("поиск", Value::word()).runs()),
Node::lit("panel").with([
Node::lit("snapshot").then(Node::arg("запрос", Value::word()).then(
Node::arg("ракурс", Value::choice(["public", "debug"])).then(Node::arg("позиция", Value::word()).runs())
)),
Node::lit("launch").then(Node::arg("запрос", Value::word()).then(
Node::arg("сессия", Value::word()).then(Node::arg("сценарий", Value::word()).runs())
)),
]),
Node::lit("stats").runs(),
])
}
@@ -162,12 +179,13 @@ mod tests {
#[test]
fn every_branch_of_the_handler_parses() {
for line in [
"", "menu", "capabilities", "monitor", "grid", "give", "raid", "repair", "import", "flare", "clear", "stats", "roles",
"", "menu", "capabilities", "monitor", "grid", "post", "post Панцирь", "post 82", "give", "raid", "repair", "import", "flare", "clear", "stats", "recon", "roles",
"replay", "replay map", "replay full", "replay reel", "replay film", "replay film best", "replay film all",
"replay film 3", "replay export", "replay export mine", "replay export best", "replay export all", "replay export 3",
"replay export mine all fps=30 size=1280x720 crf=18 sec=12.5 noaudio", "replay export fps=60", "replay stop",
"scenario save a", "scenario save a fresh", "scenario load a", "scenario load a force", "scenario list",
"scenario delete a", "why", "why 2", "ew on", "ew off", "move 4", "target here", "targets clear",
"scenario delete a", "scenario village", "scenario village hard", "scenario village start",
"breaches", "breaches 2", "why", "why 2", "why 2 source", "chains", "chains 2", "ew on", "ew off", "move 4", "target here", "targets clear",
"sites", "strike 3", "battery", "battery 1 launcher", "battery 1 integrated", "radar 2 on", "radar 2 off", "radar 2 engagement", "radar 2 search", "deploy s400_launcher", "deploy s500_launcher", "deploy radar_search", "deploy radar_track", "deploy radar_height", "deploy patriot", "deploy light", "deploy s400", "wave mix", "wave shahed", "wave shahed 20", "wave kh101 80 800", "wave shahed 20 4000",
"wave oreshnik 1 60", "damage on", "damage off", "truth on", "shader hd", "shader off", "shader on", "hold on", "lastchance on", "lastchance off",
"roles all default", "doctrine", "doctrine 1 reserve 4", "doctrine all salvo eco", "doctrine 2 sector 90 45", "doctrine 2 sector off", "doctrine 1 guard 1,2", "doctrine 1 reset", "roles patriot drone,jet", "roles pantsir all", "roles tor ballistic",
@@ -241,14 +259,15 @@ mod tests {
fn completion_offers_the_next_word_only() {
let top = complete("", &[]);
for w in ["menu", "monitor", "grid", "replay", "scenario", "why", "raid", "repair", "import", "ew", "flare", "move",
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel"] {
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "recon", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel", "chains"] {
assert!(top.contains(&w.to_string()), "{w} in {top:?}");
}
assert_eq!(top.len(), 35);
assert!(top.contains(&"post".to_string()));
assert_eq!(top.len(), 40);
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
assert_eq!(complete("replay film ", &[]), ["all", "best"]);
assert_eq!(complete("scenario ", &[]), ["delete", "list", "load", "save"]);
assert_eq!(complete("scenario ", &[]), ["delete", "list", "load", "save", "village"]);
assert_eq!(complete("wave ", &[]).len(), 14);
assert!(complete("wave s", &[]).contains(&"shahed".to_string()));
assert_eq!(complete("shader ", &[]), ["hd", "off", "on"]);
@@ -258,6 +277,18 @@ mod tests {
assert!(complete("wave nothing ", &[]).is_empty());
}
/// A station's profile is fixed at deployment: completion offers only emission, while an
/// old role word still reaches the handler's explanation instead of a bare parse error.
#[test]
fn radar_completion_offers_emission_only() {
let words = complete("radar 1 ", &[]);
assert_eq!(words.len(), 2, "{words:?}");
assert!(words.contains(&"on".to_string()) && words.contains(&"off".to_string()));
for old in ["multi", "search", "engagement", "height"] {
assert!(tree().parse(&format!("radar 1 {old}")).is_ok(), "`{old}` should reach the handler");
}
}
/// The names follow the data: after a save the new name is offered, after a delete it is gone.
#[test]
fn scenario_names_follow_a_save_and_a_delete() {
+8 -6
View File
@@ -9,6 +9,8 @@
//! for a tick or two (a step the simulation skipped) does not stop the sound; a *cut* (a replay
//! seek, a new shot) stops every engine and starts them again under new ids, so nothing glides
//! across the jump.
use crate::sim::catalog::sound;
use glam::DVec3;
use std::collections::{BTreeMap, BTreeSet};
@@ -52,12 +54,12 @@ pub enum Op {
/// engine_sounds_has_no_hole` finds them (after the fade-in, before the sound begins to die).
pub fn steady_part(event: &str) -> (f32, f32) {
match event {
"airdef:drone.shahed" => (0.2, 2.2),
"airdef:drone.geran3" => (0.2, 2.0),
"airdef:drone.lancet" => (0.2, 1.4),
"airdef:drone.cruise" => (0.2, 2.6),
"airdef:drone.rocket" => (0.2, 2.6),
"airdef:missile.flight" => (0.2, 2.2),
sound::DRONE_SHAHED => (0.2, 2.2),
sound::DRONE_GERAN3 => (0.2, 2.0),
sound::DRONE_LANCET => (0.2, 1.4),
sound::DRONE_CRUISE => (0.2, 2.6),
sound::DRONE_ROCKET => (0.2, 2.6),
sound::MISSILE_FLIGHT => (0.2, 2.2),
_ => (0.0, 0.0),
}
}
+229
View File
@@ -0,0 +1,229 @@
//! Picking nearby AirDef models against the same block ray the client uses for its crosshair.
use crate::sim::Model;
use glam::{DVec3, Vec3};
use horizon_mod_sdk::render::{FillShape, Point, Rect, Shape, TextShape};
pub const REACH: f32 = 24.0;
const FACE_BYTES: usize = 4 * 3 * size_of::<f32>();
const FACES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/inspect-faces.bin"));
const MESHES: &[(&str, Mesh)] = include!(concat!(env!("OUT_DIR"), "/inspect-meshes.rs"));
struct Mesh {
min: [f32; 3],
max: [f32; 3],
radius: f32,
start: usize,
end: usize,
}
pub struct Ray {
origin: DVec3,
direction: DVec3,
limit: f64,
}
impl Ray {
pub fn from_view(eye: DVec3, direction: DVec3, terrain: Option<DVec3>) -> Self {
let mut origin = eye;
let mut limit = f64::from(REACH);
if let Some(point) = terrain {
let horizontal = DVec3::new(direction.x, 0.0, direction.z);
let distance = if horizontal.length_squared() > 1e-8 {
// Feet and eye share X/Z. Recover the actual eye height from the host
// ray when it hit a block (the eye lowers while crouching or swimming).
let t = (point - eye).dot(horizontal) / horizontal.length_squared();
origin.y = point.y - direction.y * t;
t
} else {
(point - eye).dot(direction)
};
limit = distance.clamp(0.0, limit);
}
Self {
origin,
direction,
limit,
}
}
fn hits_bounds(&self, min: DVec3, max: DVec3) -> bool {
let (mut near, mut far) = (0.0f64, self.limit);
for i in 0..3 {
if self.direction[i].abs() < 1e-10 {
if self.origin[i] < min[i] || self.origin[i] > max[i] {
return false;
}
} else {
let a = (min[i] - self.origin[i]) / self.direction[i];
let b = (max[i] - self.origin[i]) / self.direction[i];
near = near.max(a.min(b));
far = far.min(a.max(b));
if near > far {
return false;
}
}
}
near < self.limit
}
fn triangle(&self, a: DVec3, b: DVec3, c: DVec3) -> Option<f64> {
let ab = b - a;
let ac = c - a;
let p = self.direction.cross(ac);
let determinant = ab.dot(p);
if determinant.abs() < 1e-10 {
return None;
}
let t = self.origin - a;
let u = t.dot(p) / determinant;
let q = t.cross(ab);
let v = self.direction.dot(q) / determinant;
let distance = ac.dot(q) / determinant;
(u >= 0.0 && v >= 0.0 && u + v <= 1.0 && distance >= 0.0 && distance < self.limit)
.then_some(distance)
}
}
/// Return the object that owns the closest visible face, including its rotated moving parts.
pub fn pick(
mut ray: Ray,
models: &[Model],
mut is_unit_model: impl FnMut(&Model) -> bool,
) -> Option<u32> {
let mut picked = None;
for model in models {
if model.glow || model.scale <= 0.0 {
continue;
}
let Ok(i) = MESHES.binary_search_by_key(&model.name, |(name, _)| *name) else {
continue;
};
let mesh = &MESHES[i].1;
let scale = f64::from(model.scale);
let reach = ray.limit + scale * f64::from(mesh.radius);
if model.at.distance_squared(ray.origin) > reach * reach || !is_unit_model(model) {
continue;
}
let unrotate = model.rotation.conjugate();
let mut local = Ray {
origin: unrotate * (ray.origin - model.at) / scale,
direction: unrotate * ray.direction / scale,
limit: ray.limit,
};
if !local.hits_bounds(
Vec3::from_array(mesh.min).as_dvec3(),
Vec3::from_array(mesh.max).as_dvec3(),
) {
continue;
}
for face in FACES[mesh.start..mesh.end].chunks_exact(FACE_BYTES) {
let [a, b, c, d] = std::array::from_fn(|vertex| {
DVec3::from_array(std::array::from_fn(|axis| {
let start = (vertex * 3 + axis) * size_of::<f32>();
let value = f32::from_le_bytes(
face[start..start + size_of::<f32>()].try_into().unwrap(),
);
f64::from(value)
}))
});
if let Some(hit) = local.triangle(a, b, c).or_else(|| local.triangle(a, c, d)) {
local.limit = hit;
picked = Some(model.object_id());
}
}
ray.limit = local.limit;
}
picked
}
pub fn hint(size: (f32, f32), text_width: f32, label: String) -> [Shape; 2] {
let (x, y) = (size.0 / 2.0, size.1 / 2.0 + 14.0);
[
Shape::Fill(FillShape {
rect: Rect {
x: x - text_width / 2.0 - 4.0,
y: y - 2.0,
w: text_width + 8.0,
h: 12.0,
},
color: 0xA0101518,
}),
Shape::Text(TextShape {
text: label,
at: Point { x, y },
color: 0xFFF0F4FA,
centered: true,
shadow: true,
}),
]
}
#[cfg(test)]
mod tests {
use super::*;
use glam::DQuat;
fn radar(id: u32, at: DVec3) -> Model {
Model {
id,
name: "airdef:radar_truck",
at,
rotation: DQuat::from_rotation_y(0.4),
scale: 1.0,
glow: false,
}
}
#[test]
fn takes_the_closest_model_face_only_in_front_of_the_terrain() {
let eye = DVec3::new(0.0, 0.25, 0.0);
let models = [radar(16, 10.0 * DVec3::Z), radar(33, 6.0 * DVec3::Z)];
assert_eq!(
pick(Ray::from_view(eye, DVec3::Z, None), &models, |_| true),
Some(32)
);
let wall = Some(DVec3::new(0.0, 0.25, 3.0));
assert_eq!(
pick(Ray::from_view(eye, DVec3::Z, wall), &models, |_| true),
None
);
let wall_between_units = Some(DVec3::new(0.0, 0.25, 8.0));
assert_eq!(
pick(
Ray::from_view(eye, DVec3::Z, wall_between_units),
&models,
|_| true
),
Some(32)
);
assert_eq!(
pick(Ray::from_view(eye, DVec3::Z, None), &models, |m| m.id == 16),
Some(16)
);
}
#[test]
fn a_higher_visible_part_is_pickable_above_a_wall() {
let body = radar(16, 8.0 * DVec3::Z);
let antenna = Model {
name: "airdef:radar_panel",
..radar(18, DVec3::new(0.0, 1.8, 8.0))
};
let low_eye = DVec3::new(0.0, 0.25, 0.0);
let wall = Some(DVec3::new(0.0, 0.25, 3.0));
let high_eye = DVec3::new(0.0, 1.8, 0.0);
assert_eq!(
pick(Ray::from_view(high_eye, DVec3::Z, None), &[body], |_| true),
None
);
let models = [radar(16, 8.0 * DVec3::Z), antenna];
assert_eq!(
pick(Ray::from_view(low_eye, DVec3::Z, wall), &models, |_| true),
None
);
assert_eq!(
pick(Ray::from_view(high_eye, DVec3::Z, None), &models, |_| true),
Some(16)
);
}
}
+56 -1
View File
@@ -31,6 +31,9 @@ pub struct SamRec {
pub air_48n6_stock: u32,
pub mode: sim::battery::SamMode,
pub radar_role: sim::battery::RadarRole,
/// The stable profile ID when the file names one (new saves); old files
/// have only the role key, which migrates to the matching profile.
pub radar_profile: Option<sim::battery::RadarProfile>,
pub spent_cells: u8,
pub radar_on: bool,
}
@@ -45,6 +48,9 @@ pub struct Layout {
pub wave: Option<Vec<String>>,
pub far: Option<bool>,
pub acoustics: Option<bool>,
/// The player's DLSS request; absent in older saves (the engine's own
/// default applies: on where supported).
pub dlss: Option<bool>,
pub effects: Option<(bool, bool)>,
pub roles: Vec<(SamKind, u8)>,
/// Fire doctrines by the system's place in the file (#47).
@@ -147,10 +153,20 @@ impl Layout {
let radar_on = l.flag(29, "излучение РЛС")?.unwrap_or(true);
let ground_return = l.flag(30, "заявка на вывоз RM48U")?.unwrap_or(false);
let return_cargo = l.flag(31, "возвращаемый груз RM48U")?.unwrap_or(false);
let radar_profile = match l.w.get(32) {
None => None,
Some(v) => Some(sim::battery::RadarProfile::from_id(v).ok_or_else(|| l.bad("профиль РЛС", "radar_multi, radar_search, radar_track или radar_height"))?),
};
if (ground_return && (kind != SamKind::S400 || ground_request || ground_rounds == 0)) || (return_cargo && (kind != SamKind::Tzm || ground_stock == 0)) { return Err(l.bad("возврат RM48U", "несовместимое состояние")); }
if radar_role != sim::battery::RadarRole::Multifunction && kind != SamKind::Radar {
return Err(l.bad("роль РЛС", "роль поддерживается только отдельной РЛС"));
}
if let Some(profile) = radar_profile {
if kind != SamKind::Radar { return Err(l.bad("профиль РЛС", "профиль поддерживается только отдельной РЛС")); }
if profile.role() != radar_role { return Err(l.bad("профиль РЛС", "профиль и роль не совпадают")); }
}
// An old line has only the role: it migrates to the matching profile.
let radar_profile = radar_profile.or((kind == SamKind::Radar).then(|| sim::battery::RadarProfile::of(radar_role)));
if mode == sim::battery::SamMode::LauncherOnly && !matches!(kind, SamKind::S400 | SamKind::S500) {
return Err(l.bad("режим", "пусковая поддерживается только С-400 и С-500"));
}
@@ -160,7 +176,7 @@ impl Layout {
if let Some((m, _, _, _)) = ammo && m + ground_rounds > 4 && kind == SamKind::S400 {
return Err(l.bad("боезапас", "больше четырёх ячеек"));
}
out.sams.push(SamRec { kind, pos, heading, roles, health, cargo, ammo, dest, comps, ground_rounds, ground_stock, air_48n6_stock, mode, radar_role, spent_cells, ground_request, radar_on, ground_return, return_cargo });
out.sams.push(SamRec { kind, pos, heading, roles, health, cargo, ammo, dest, comps, ground_rounds, ground_stock, air_48n6_stock, mode, radar_role, radar_profile, spent_cells, ground_request, radar_on, ground_return, return_cargo });
}
"target" => {
if out.targets.len() >= MAX_UNITS {
@@ -175,6 +191,7 @@ impl Layout {
"strikes" => out.strikes = Some((l.need(1, "запас", 0.0, COUNT)? as u32, l.num(2, "до следующей", 0.0, COUNT)?.map_or(0, |v| v as u32))),
"far" => out.far = l.flag(1, "значение")?,
"acoustics" => out.acoustics = l.flag(1, "значение")?,
"dlss" => out.dlss = l.flag(1, "значение")?,
"effects" => out.effects = Some((l.flag(1, "шейдер")?.unwrap_or(true), l.flag(2, "HD")?.unwrap_or(false))),
"seed" => {
let v = l.w.get(1).ok_or_else(|| l.bad("значение", "строка оборвана"))?;
@@ -220,6 +237,7 @@ mod tests {
assert_eq!(l.sams[0].mode, sim::battery::SamMode::LauncherOnly);
assert_eq!(l.sams[0].spent_cells, 5);
assert_eq!(l.sams[1].radar_role, sim::battery::RadarRole::Engagement);
assert_eq!(l.sams[1].radar_profile, Some(sim::battery::RadarProfile::ENGAGEMENT), "an old role-only line migrates");
assert!(!Layout::parse(&data.replace("launcher multi 5", "launcher multi 5 0 false")).unwrap().sams[0].radar_on);
assert!(Layout::parse(&data.replace("launcher multi 5", "launcher multi 5 0 nope")).is_err());
assert!(Layout::parse(&data.replace("engagement", "invalid")).is_err());
@@ -230,6 +248,13 @@ mod tests {
SamKind::Patriot.key()
}
#[test]
fn an_optical_post_loads_by_its_catalog_key() {
let l = Layout::parse("sam optical 10 70 20 0.5\n").unwrap();
assert_eq!(l.sams[0].kind, SamKind::Optical);
assert_eq!(l.sams[0].mode, sim::battery::SamMode::Integrated);
}
// #86: the issue's file, and the other ways a saved state can be wrong: refused whole, with the line
#[test]
fn a_damaged_state_is_refused_as_a_whole_with_its_line_and_field() {
@@ -258,6 +283,36 @@ mod tests {
assert!(Layout::parse(&many).is_err(), "no limit on the number of objects");
}
#[test]
fn the_dlss_request_round_trips_and_old_saves_keep_the_engine_default() {
assert_eq!(Layout::parse("dlss false\n").unwrap().dlss, Some(false));
assert_eq!(Layout::parse("dlss true\n").unwrap().dlss, Some(true));
assert!(Layout::parse("dlss maybe\n").is_err());
// Older saves have no line: the engine's own default (on) applies.
assert_eq!(Layout::parse("damage true\n").unwrap().dlss, None);
}
#[test]
fn radar_profile_ids_round_trip_and_old_roles_map_to_them() {
let old = "sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated search";
let l = Layout::parse(old).unwrap();
assert_eq!(l.sams[0].radar_role, sim::battery::RadarRole::Search);
assert_eq!(l.sams[0].radar_profile, Some(sim::battery::RadarProfile::SEARCH));
let new = "sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated engagement 0 0 true false false radar_track";
let l = Layout::parse(new).unwrap();
assert_eq!(l.sams[0].radar_profile, Some(sim::battery::RadarProfile::ENGAGEMENT));
assert_eq!(l.sams[0].radar_role, sim::battery::RadarRole::Engagement);
assert_eq!(
Layout::parse("sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated multi 0 0 true false false radar_multi").unwrap().sams[0].radar_profile,
Some(sim::battery::RadarProfile::MULTI)
);
// A profile and the legacy role must agree; a profile on a non-radar is refused.
assert!(Layout::parse(&new.replace("engagement 0", "search 0")).is_err());
assert!(Layout::parse(&new.replace("sam radar", "sam s400").replace("engagement", "multi")).is_err());
assert!(Layout::parse(&new.replace("radar_track", "radar_unknown")).is_err());
assert_eq!(sim::battery::RadarProfile::from_id("multi"), Some(sim::battery::RadarProfile::MULTI));
}
// #86: files made by older builds (no ammunition, no parts, no destination marks) and unknown lines still load
#[test]
fn older_valid_saves_still_load() {
+1139 -143
View File
File diff suppressed because it is too large Load Diff
+653 -81
View File
File diff suppressed because it is too large Load Diff
+85 -27
View File
@@ -1,9 +1,9 @@
//! The air-defence monitor: a system's state, its radar's picture round it
//! and its camera (a real view of the world from the system, the game
//! renders it) locked on its target. K shows one system at a time, J all of
//! them in a grid.
//! renders it) locked on its target. K shows one system at a time. The
//! command post can also open a grid of up to eight cameras.
use crate::panel::distance;
use crate::sim::{Sam, SamState, Sim, heading_of, roles_text};
use crate::sim::{ClassEst, OpticalState, Sam, SamKind, SamState, Sim, heading_of, roles_text};
use glam::DVec3;
use horizon_mod_sdk::render::{self, CameraView, FillShape, Point, QuadShape, Rect, Shape, TextShape, ViewShape};
@@ -21,7 +21,7 @@ fn quad(a: (f32, f32), b: (f32, f32), c: (f32, f32), d: (f32, f32), color: u32)
}
/// `t` cut to `w` GUI pixels, with an ellipsis.
fn fit(t: String, w: f32) -> String {
pub(crate) fn fit(t: String, w: f32) -> String {
if render::text_width(&t) <= w {
return t;
}
@@ -91,12 +91,23 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
s.push(fill(x, y, w, h, 0xC0080C0A));
s.push(fill(x, y, w, 12.0, 0xE0142018));
let state = sam.state;
let optical = sam.kind == SamKind::Optical;
let lock = matches!(state, SamState::Lock | SamState::Launch | SamState::Fire);
let blink = lock && (tick / 4) % 2 == 0;
let label = state.name();
let label = if optical { sam.optical.state().name() } else { state.name() };
let color = if optical {
match sam.optical.state() {
OpticalState::Observing => 0xFF60FF80,
OpticalState::Holding => 0xFF9FE0FF,
OpticalState::NoSight => 0xFFFFA040,
OpticalState::Searching => 0xFFE0E0E0,
}
} else {
state.color()
};
let lw = render::text_width(label);
s.push(text(fit(format!("№{} {}", index + 1, spec.name), w - lw - 12.0), x + 3.0, y + 2.0, 0xFF9FE0FF));
s.push(text(label, x + w - 3.0 - lw, y + 2.0, argb(state.color(), if blink { 0x80 } else { 0xFF })));
s.push(text(label, x + w - 3.0 - lw, y + 2.0, argb(color, if blink { 0x80 } else { 0xFF })));
// The radar, at the left: round the system, north up.
let rr = ((h - 28.0) / 2.0).min(w * 0.2).max(10.0);
@@ -114,9 +125,13 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
}
// A system that only fires (no radar) has no reach: a radar's sensor
// range stands in, and nothing is divided by zero.
let reach = match sam.kind.range() {
r if r > 0.0 => r,
_ => spec.sensor,
let reach = if optical {
crate::sim::OPTICAL_RANGE
} else {
match sam.kind.range() {
r if r > 0.0 => r,
_ => spec.sensor,
}
};
let scale = if reach > 0.0 { rr as f64 / (reach * 1.25) } else { 0.0 };
// The beam is the radar's real one: targets are measured as it passes them.
@@ -146,13 +161,17 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
seen += 1;
let k = scale as f32;
let (bx, by) = (rx + rel.x as f32 * k, ry + rel.z as f32 * k);
let allowed = sam.roles & d.kind.spec().class.bit() != 0;
// By the class the track was estimated (#133): the unknown are candidates too, shown in
// their own colour — the explicit policy — never the target's own class. No roles means
// holding fire, and that greys out the unknown as well.
let color = if Some(d.id) == target.map(|t| t.id) {
0xFFFFE040
} else if allowed {
0xFFFF4040
} else {
} else if !tr.class.in_roles(sam.roles) {
0xFF808080
} else if tr.class == ClassEst::Unknown {
0xFFFFA040
} else {
0xFFFF4040
};
if tr.forecast(tick) {
s.push(fill(bx - 1.5, by - 1.5, 3.0, 1.0, color));
@@ -164,14 +183,30 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
}
}
s.push(fill(rx - 1.5, ry - 1.5, 3.0, 3.0, 0xFF40A0FF));
let radar_text = if spec.sensor <= 0.0 {
let radar_text = if optical {
format!("ОПТИКА · {}", sam.optical.state().name())
} else if spec.sensor <= 0.0 {
format!("сеть · {seen}")
} else if radar_up {
format!("РЛС {} · {}", distance(reach), seen)
let profile = sam.radar_profile();
let channels = if profile.channels == 0 { String::new() } else { format!(" · {}/{}", sam.own_channels_used(tick), profile.channels) };
format!("{} · {} · {}{channels}", profile.name, distance(reach), seen)
} else {
"РЛС ОТКАЗ".to_string()
};
s.push(text(fit(radar_text, rr * 2.0 + 4.0), x + 4.0, y + h - 10.0, if spec.sensor > 0.0 && !radar_up { 0xFFFF5040 } else { 0xFF80FF90 }));
let radar_color = if optical {
match sam.optical.state() {
OpticalState::Observing => 0xFF60FF80,
OpticalState::Holding => 0xFF9FE0FF,
OpticalState::NoSight => 0xFFFFA040,
OpticalState::Searching => 0xFFB0B0B0,
}
} else if spec.sensor > 0.0 && !radar_up {
0xFFFF5040
} else {
0xFF80FF90
};
s.push(text(fit(radar_text, rr * 2.0 + 4.0), x + 4.0, y + h - 10.0, radar_color));
// Its health under the radar: a bar, red when it is low.
if sam.alive() && sam.health < 1.0 {
@@ -209,7 +244,7 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
// Worn or failed parts, over the picture: orange, red when one has failed.
if !sam.comps.whole() {
let failed = crate::sim::Part::ALL.iter().any(|p| sam.part_state(*p) == crate::sim::PartState::Failed);
s.push(text(fit(sam.parts_text(), cw * 0.55), cx + 3.0, cy + 3.0, if failed { 0xFFFF4040 } else { 0xFFFFB030 }));
s.push(text(fit(crate::why_view::parts(&sam.comps, sam.kind), cw * 0.55), cx + 3.0, cy + 3.0, if failed { 0xFFFF4040 } else { 0xFFFFB030 }));
}
// Crosshair.
s.push(fill(cx + cw / 2.0 - 0.5, cy + 3.0, 1.0, ch * 0.18, 0x90FFFFFF));
@@ -217,6 +252,21 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
s.push(fill(cx + 3.0, cy + ch / 2.0 - 0.5, cw * 0.18, 1.0, 0x90FFFFFF));
s.push(fill(cx + cw * 0.82 - 3.0, cy + ch / 2.0 - 0.5, cw * 0.18, 1.0, 0x90FFFFFF));
match target {
Some(_) if optical => {
// The optical post's picture: its own class observation, never the true model name.
let (color, info) = match sam.optical.state() {
OpticalState::Observing => (0xFF60FF80, sam.optical.status_text()),
OpticalState::Holding => (0xFF9FE0FF, sam.optical.status_text()),
OpticalState::NoSight => (0xFFFFA040, sam.optical.status_text()),
OpticalState::Searching => (0xFFB0B0B0, sam.optical.status_text()),
};
let (bw, bh) = (cw * 0.3, ch * 0.34);
brackets(s, cx + cw / 2.0 - bw / 2.0, cy + ch / 2.0 - bh / 2.0, bw, bh, 6.0, color);
if ch > 50.0 {
s.push(text(fit(info.clone(), cw - 6.0), cx + 3.0, cy + ch - 20.0, color));
}
s.push(text(fit(info, cw - 6.0), cx + 3.0, cy + ch - 10.0, 0xFFC0FFC0));
}
Some(t) => {
let color = if lock { if blink { 0xFFFF3030 } else { 0xFFFF8080 } } else { 0xFFFFE060 };
let (bw, bh) = (cw * 0.3, ch * 0.34);
@@ -233,9 +283,12 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
let rel = at - sam.pos;
let bearing = (heading_of(rel).to_degrees() + 180.0).rem_euclid(360.0);
if ch > 50.0 {
s.push(text(fit(t.kind.spec().name.into(), cw - 6.0), cx + 3.0, cy + ch - 20.0, 0xFFFFFFFF));
// What the system knows it by: the estimated class; the sandbox's truth names the model.
let name = if sim.truth { t.kind.spec().name.to_string() } else { track.map_or_else(|| "тип не определён".into(), |tr| tr.class.name()) };
s.push(text(fit(name, cw - 6.0), cx + 3.0, cy + ch - 20.0, 0xFFFFFFFF));
}
let mut info = format!("{} в{:.0} {:.0}км/ч", distance(rel.length()), at.y - sam.pos.y, t.vel.length() * 72.0);
// The speed its own measurements showed, never the target's own figures.
let mut info = format!("{} в{:.0} {:.0}км/ч", distance(rel.length()), at.y - sam.pos.y, track.map_or(0.0, |tr| tr.vel.length()) * 72.0);
if let Some(tr) = track {
if tr.forecast(tick) {
info += &format!(" прогноз {:.1}с", tr.age(tick) as f64 / 20.0);
@@ -248,19 +301,24 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
}
s.push(text(fit(info, cw - 6.0), cx + 3.0, cy + ch - 10.0, 0xFFC0FFC0));
}
None if optical => s.push(text(fit(sam.optical.status_text(), cw - 6.0), cx + 3.0, cy + ch - 10.0, 0xFFB0B0B0)),
None => s.push(text("ПОИСК", cx + 3.0, cy + ch - 10.0, 0xFF80FF90)),
}
// What it carries and does.
let mut line = String::new();
if !matches!(sam.kind, crate::sim::SamKind::Gepard) {
line += &format!("Р{} ", sam.missiles);
if sam.kind == crate::sim::SamKind::S400 { line += &format!("У{} ", sam.ground_rounds); }
if optical {
line = sam.optical.status_text();
} else {
if !matches!(sam.kind, SamKind::Gepard) {
line += &format!("Р{} ", sam.missiles);
if sam.kind == SamKind::S400 { line += &format!("У{} ", sam.ground_rounds); }
}
if crate::sim::catalog::unit(sam.kind).has_gun() {
line += &format!("Оч{} ", sam.bursts);
}
line += &format!("сб.{} [{}]", sam.kills, roles_text(sam.roles));
}
if crate::sim::catalog::unit(sam.kind).has_gun() {
line += &format!("Оч{} ", sam.bursts);
}
line += &format!("сб.{} [{}]", sam.kills, roles_text(sam.roles));
s.push(text(fit(line, cw), cx, y + h - 10.0, 0xFF9FE0FF));
}
@@ -273,7 +331,7 @@ pub fn draw(sim: &Sim, index: usize) -> Vec<Shape> {
s.push(fill(4.0, 156.0, 300.0, 4.0 + 10.0 * checks.len() as f32, 0xA0080C0A));
for (k, c) in checks.iter().enumerate() {
let color = if c.ok { 0xFF80FF90 } else { 0xFFFF9060 };
s.push(text(fit(format!("{} {}", if c.ok { "+" } else { "-" }, c.text), 294.0), 7.0, 158.0 + 10.0 * k as f32, color));
s.push(text(fit(format!("{} {}", if c.ok { "+" } else { "-" }, crate::why_view::reason(&c.reason)), 294.0), 7.0, 158.0 + 10.0 * k as f32, color));
}
s
}
+448
View File
@@ -0,0 +1,448 @@
//! The world overlay (#132): while the player holds the overlay key, square markers over the
//! targets they can see, each with a short line — the class the radars estimated (#133) and the
//! distance. The picture is the network's, as the radar and the map read it; the sandbox's truth
//! mode adds white markers of the real drones, labelled with their actual type, apart from the
//! network's. The player's own interceptors wear small yellow squares, as the radar shows them.
//! Letting the key go hides everything. The markers are projected through the camera the last
//! drawn frame used (`render.project`, API 31), so they sit on the world as it is drawn.
//! Visibility comes before the draw budget (#141): each layer projects at most a bounded number
//! of its nearest candidates, keeps the markers of the nearest visible ones, and counts a target
//! that leaves the frame without spending a slot.
use crate::panel::distance;
use crate::sim::{ClassEst, Sim, Track};
use glam::DVec3;
use horizon_mod_sdk::render::{FillShape, Point, Rect, Shape, TextShape};
/// The most markers of one picture (the network's, the truth's and the interceptors' each): a full
/// raid still fits the HUD's 1024 shapes — a marker is four sides and a label.
const MAX_MARKERS: usize = 64;
/// The most candidates of one layer the frame looks at: the nearest ones by distance. The draw
/// budget is spent on what is in frame, but the projection work stays bounded — a crowd the frame
/// does not hold cannot buy an unbounded scan, and what the scan never reaches counts as past the
/// budget rather than out of the frame.
const MAX_SCAN: usize = 4 * MAX_MARKERS;
/// A marker's side thickness, pixels.
const LINE: f32 = 1.0;
/// A label line's height (the HUD font with its shadow).
const LH: f32 = 9.0;
/// The half-size a marker clamps to, near and far.
const HALF_MIN: f32 = 5.0;
const HALF_MAX: f32 = 16.0;
const RED: u32 = 0xFF4040;
const ORANGE: u32 = 0xFFB040;
const WHITE: u32 = 0xFFFFFFFF;
const GREEN: u32 = 0xFF80FF90;
const YELLOW: u32 = 0xFFFFE070;
/// The interceptors' own colour (the radar's missile dot).
const MISSILE: u32 = 0xFFE060;
/// An interceptor's marker half-size: small, it is not a target.
const MISSILE_HALF: f32 = 3.0;
fn pt(x: f32, y: f32) -> Point {
Point { x, y }
}
fn text(t: String, x: f32, y: f32, color: u32, centered: bool) -> Shape {
Shape::Text(TextShape { text: t, at: pt(x, y), color, centered, shadow: true })
}
/// 0xAARRGGBB with this alpha (0..1).
fn alpha(rgb: u32, a: f64) -> u32 {
((a.clamp(0.0, 1.0) * 255.0) as u32) << 24 | (rgb & 0xFFFFFF)
}
/// A square outline around a screen point: four thin fills, the world's marker.
fn square_outline(x: f32, y: f32, half: f32, color: u32) -> Vec<Shape> {
let (w, h) = (half * 2.0, LINE);
vec![
Shape::Fill(FillShape { rect: Rect { x: x - half, y: y - half, w, h }, color }),
Shape::Fill(FillShape { rect: Rect { x: x - half, y: y + half - LINE, w, h }, color }),
Shape::Fill(FillShape { rect: Rect { x: x - half, y: y - half, w: h, h: w }, color }),
Shape::Fill(FillShape { rect: Rect { x: x + half - LINE, y: y - half, w: h, h: w }, color }),
]
}
/// A marker's half-size by the distance: near targets read bigger, far ones stay legible.
fn half(dist: f64) -> f32 {
(700.0 / dist.max(1.0)).clamp(HALF_MIN as f64, HALF_MAX as f64) as f32
}
/// The short line under a network marker: the estimated class's mark (#133) and the distance to
/// the forecast place; a forecast says how old it is. An unidentified track gets a `?`, never the
/// target's type.
fn track_label(t: &Track, now: u64, player: DVec3) -> String {
let mark = match t.class {
ClassEst::Unknown => "?",
c => c.mark(),
};
let mut s = format!("{mark} {}", distance(t.est(now).distance(player)));
if t.forecast(now) {
s += &format!(" ~{}с", t.age(now) / 20);
}
s
}
/// Where a marker's label sits: under the square, or over it when the bottom edge is close.
fn label_y(y: f32, half: f32, gui_h: f32, above: bool) -> f32 {
if above {
if y - half - LH - 2.0 >= 0.0 { y - half - LH - 2.0 } else { y + half + 2.0 }
} else if y + half + LH + 2.0 <= gui_h {
y + half + 2.0
} else {
y - half - LH - 2.0
}
}
/// What one layer shows this frame: the markers to draw (the nearest visible candidates), how
/// many of the scanned candidates left the frame, and how many the budgets left out.
struct Pick<T> {
marks: Vec<(T, Point, f32)>,
offscreen: usize,
capped: usize,
}
/// The markers one layer gets this frame. The candidates are ordered nearest the player first and
/// at most [`MAX_SCAN`] of them are projected; a candidate the frame does not hold (behind the
/// camera or past an edge) is counted and its slot stays free for the next, so the nearest
/// [`MAX_MARKERS`] visible candidates are drawn. Work stays bounded by the scan, not the picture.
fn pick<T: Copy>(
items: impl Iterator<Item = T>,
at: impl Fn(T) -> DVec3,
half_at: impl Fn(T) -> f32,
player: DVec3,
gui: (f32, f32),
project: &impl Fn(DVec3) -> Option<Point>,
) -> Pick<T> {
let near = |a: &T, b: &T| at(*a).distance(player).total_cmp(&at(*b).distance(player));
let mut items: Vec<T> = items.collect();
let total = items.len();
// Only the nearest candidates are ever projected: no sort of the whole picture is needed.
if items.len() > MAX_SCAN {
items.select_nth_unstable_by(MAX_SCAN, near);
items.truncate(MAX_SCAN);
}
items.sort_by(near);
let mut marks = Vec::new();
let mut offscreen = 0usize;
for it in items {
if marks.len() >= MAX_MARKERS {
break;
}
let h = half_at(it);
match project(at(it)) {
Some(p) if p.x >= h && p.x <= gui.0 - h && p.y >= h && p.y <= gui.1 - h => marks.push((it, p, h)),
_ => offscreen += 1,
}
}
Pick { capped: total - marks.len() - offscreen, marks, offscreen }
}
/// The overlay's shapes for this frame. `project` is the game's `render.project` (the last drawn
/// frame's camera); a point behind the camera projects to None, a point off the screen still
/// projects past its edges — both are counted, not drawn. Drawn only while the key is held.
pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) -> Option<Point>) -> Vec<Shape> {
let mut s = Vec::new();
if gui.0 <= 0.0 || gui.1 <= 0.0 {
return s;
}
let pic = sim.air_picture();
let now = pic.now;
let truth = sim.truth && !pic.unaided;
// The frame's counts: what got a marker and what did not — out of the frame (behind the camera
// or past an edge) or past the budget. The header keeps the two apart (#141).
let mut shown = 0usize;
let mut offscreen = 0usize;
let mut capped = 0usize;
// The network's tracks: the nearest visible keep the markers; a target behind the camera no
// longer spends one, so a crowd behind cannot crowd out the target in frame.
let net = pick(pic.tracks.iter(), |t| t.est(now), |t| half(t.est(now).distance(player)), player, gui, &project);
offscreen += net.offscreen;
capped += net.capped;
for (t, p, h) in net.marks {
// Fresh: red; a forecast: orange, fading as it ages towards the track's drop (the radar's colours).
let (color, a) = if pic.unaided {
(RED, 1.0)
} else if t.forecast(now) {
(ORANGE, (1.0 - t.age(now) as f64 / t.ttl.max(1) as f64 * 0.7).max(0.3))
} else {
(RED, 1.0)
};
let color = alpha(color, a);
s.extend(square_outline(p.x, p.y, h, color));
s.push(text(track_label(t, now, player), p.x, label_y(p.y, h, gui.1, false), color, true));
shown += 1;
}
// The truth's own markers: the real drones, even the ones no radar holds, white and labelled
// with the actual type the network never shows. A tracked drone wears both: the network's
// estimate under the square, the truth over it — the offset between them is the point.
if truth {
let real = pick(
sim.drones.iter().filter(|d| d.alive()),
|d| d.pos,
|d| half(d.pos.distance(player)) + 2.0,
player,
gui,
&project,
);
offscreen += real.offscreen;
capped += real.capped;
for (d, p, h) in real.marks {
s.extend(square_outline(p.x, p.y, h, WHITE));
let label = format!("{} {}", d.kind.spec().name, distance(d.pos.distance(player)));
s.push(text(label, p.x, label_y(p.y, h, gui.1, true), WHITE, true));
shown += 1;
}
}
// The player's own interceptors: small yellow squares, no label — they are not targets, and
// the network never hid them (the radar has always shown them). They keep their own budget.
let own = pick(sim.missiles.iter(), |m| m.pos, |_| MISSILE_HALF, player, gui, &project);
for (_, p, h) in own.marks {
s.extend(square_outline(p.x, p.y, h, MISSILE));
}
// The mode, named as the map names it: the network's data by default, the sandbox's truth
// explicitly marked. The counts say what the frame holds, what left it, and what the budget cut.
let counts = format!("в кадре {shown}, за кадром {offscreen}, сверх бюджета {capped}");
let head = if truth {
format!("ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · {counts}")
} else {
format!("ОБЗОР · данные сети РЛС · {counts}")
};
s.push(text(head, gui.0 / 2.0, 2.0, if truth { YELLOW } else { GREEN }, true));
s
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::{DroneKind, Out, Sam, SamKind};
const GUI: (f32, f32) = (800.0, 600.0);
/// A projector as the game's: the world ahead lands on the screen, behind the camera None.
/// Here: south (+z) is ahead, x spreads across the screen, the height lines up at 64.
fn ahead(p: DVec3) -> Option<Point> {
if p.z <= 0.0 {
return None;
}
Some(pt(400.0 + p.x as f32, 300.0 - (p.y - 64.0) as f32))
}
fn sim_with(kind: DroneKind, at: DVec3) -> Sim {
let mut sim = Sim::new(1);
sim.launch(kind, at, DVec3::ZERO, DVec3::new(at.x, 64.0, 5000.0), &mut Out::default());
sim
}
fn fills(shapes: &[Shape], rgb: u32) -> usize {
shapes.iter().filter(|s| matches!(s, Shape::Fill(f) if f.color & 0xFFFFFF == rgb & 0xFFFFFF)).count()
}
fn texts(shapes: &[Shape]) -> Vec<&TextShape> {
shapes.iter().filter_map(|s| match s {
Shape::Text(t) => Some(t),
_ => None,
}).collect()
}
fn head(shapes: &[Shape]) -> String {
texts(shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).expect("no header").text.clone()
}
/// `n` targets in a row right behind the camera, each nearer than anything the tests put ahead.
fn crowd_behind(sim: &mut Sim, n: u32) {
for i in 0..n {
sim.launch(DroneKind::Shahed, DVec3::new(i as f64, 64.0, -50.0), DVec3::ZERO, DVec3::new(0.0, 64.0, -5000.0), &mut Out::default());
}
}
#[test]
fn a_visible_target_gets_a_square_and_a_short_line() {
let sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
// One marker: four red sides, and a label with the firm class's mark and the distance.
assert_eq!(fills(&shapes, RED), 4, "the marker is not one square outline");
let label = texts(&shapes).into_iter().find(|t| t.text.contains("100 м")).expect("no distance label");
assert!(label.text.starts_with("Д "), "the firm drone class is not marked: {}", label.text);
assert!(label.centered && label.at.y > 300.0, "the label sits under the square");
// The header names the network's data and the counts.
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
assert!(head.text.contains("данные сети РЛС") && head.text.contains("в кадре 1, за кадром 0"), "{}", head.text);
}
#[test]
fn behind_the_camera_and_off_screen_are_counted_not_drawn() {
let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, -100.0), DVec3::ZERO, DVec3::new(0.0, 64.0, -5000.0), &mut Out::default());
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
assert_eq!(fills(&shapes, RED), 4, "the drone behind the camera drew a marker");
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
assert!(head.text.contains("в кадре 1, за кадром 1"), "{}", head.text);
// Off the screen's edge: still a place, but no marker.
let shapes = draw(&sim, DVec3::ZERO, GUI, |_| Some(pt(-40.0, 300.0)));
assert_eq!(fills(&shapes, RED), 0);
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
assert!(head.text.contains("в кадре 0, за кадром 2"), "{}", head.text);
}
#[test]
fn the_label_never_leaks_the_type_of_an_unidentified_track() {
let t = Track { id: 1, class: ClassEst::Unknown, pos: DVec3::new(0.0, 64.0, 100.0), vel: DVec3::ZERO, tick: 0, own_tick: 0, source: 0, product: crate::sim::battery::Measure::Search, quality: 40, own_product: crate::sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 1, locked: false };
let label = track_label(&t, 0, DVec3::ZERO);
assert!(label.starts_with("? "), "{label}");
assert!(!label.contains("дрон") && !label.contains("Шахед"), "{label}");
// A probable class keeps its question mark; a firm one loses it.
let t = Track { class: ClassEst::Probable(crate::sim::Class::Cruise), ..t };
assert!(track_label(&t, 0, DVec3::ZERO).starts_with("К? "));
let t = Track { class: ClassEst::Firm(crate::sim::Class::Cruise), hits: 3, ..t };
assert!(track_label(&t, 0, DVec3::ZERO).starts_with("К "));
// A forecast says its age.
let label = track_label(&t, 100, DVec3::ZERO);
assert!(label.contains("~5с"), "{label}");
}
#[test]
fn the_truth_mode_marks_the_real_drones_apart_from_the_network() {
let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Buk, DVec3::new(0.0, 64.0, 0.0), 0.0));
// Without the truth mode: no white markers, no actual type anywhere.
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
assert_eq!(fills(&shapes, WHITE), 0);
assert!(!texts(&shapes).iter().any(|t| t.text.contains("Шахед")), "the network overlay leaked the type");
// With it: a white square with the real type, and the header says whose picture it is.
sim.truth = true;
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
assert_eq!(fills(&shapes, WHITE), 4, "the truth marker is not one white square");
let label = texts(&shapes).into_iter().find(|t| t.text.contains("Шахед-136")).expect("no truth label");
assert!(label.text.contains("100 м") && label.at.y < 300.0, "the truth label sits over the square: {label:?}");
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
assert!(head.text.contains("ИСТИНА (песочница)"), "{}", head.text);
// The truth mode with no system deployed adds nothing: the sky as it is was already shown.
sim.sams.clear();
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
assert_eq!(fills(&shapes, WHITE), 0);
}
#[test]
fn a_full_raid_stays_inside_the_huds_shape_budget() {
let mut sim = Sim::new(1);
sim.raid(DroneKind::Shahed, DVec3::new(0.0, 64.0, 0.0), 80, 300.0, &mut Out::default());
sim.truth = true;
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
assert!(shapes.len() <= 1024, "the overlay overflowed the HUD: {} shapes", shapes.len());
// The nearest markers were kept, the rest counted.
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
assert!(head.text.contains("за кадром"), "{}", head.text);
assert!(fills(&shapes, RED) / 4 <= MAX_MARKERS);
}
/// #141: 64 targets behind the camera and one in frame. The budget used to be spent on the
/// crowd before the visibility check, so the picture came out empty; the target in frame must
/// keep its marker, and the crowd is out of frame, not past the budget.
#[test]
fn a_crowd_behind_the_camera_leaves_the_network_budget_to_the_target_in_frame() {
let mut sim = Sim::new(1);
crowd_behind(&mut sim, 64);
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default());
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
assert_eq!(fills(&shapes, RED), 4, "the target in frame got no marker");
assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 1, за кадром 64, сверх бюджета 0");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
/// The truth layer keeps its own budget the same way: the real drone in frame is drawn, the
/// crowd behind the camera costs no white marker.
#[test]
fn a_crowd_behind_the_camera_leaves_the_truth_budget_to_the_target_in_frame() {
let mut sim = Sim::new(1);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Buk, DVec3::new(0.0, 64.0, 0.0), 0.0));
sim.truth = true;
crowd_behind(&mut sim, 64);
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default());
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
assert_eq!(fills(&shapes, WHITE), 4, "the drone in frame got no truth marker");
assert_eq!(fills(&shapes, RED), 0, "the network drew a track it does not hold");
assert_eq!(head(&shapes), "ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · в кадре 1, за кадром 64, сверх бюджета 0");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
/// The interceptors keep their own budget too: a salvo behind the camera leaves the marker
/// to the one in frame.
#[test]
fn a_crowd_behind_the_camera_leaves_the_interceptor_budget_to_the_one_in_frame() {
let mut sim = Sim::new(1);
for i in 0..64 {
sim.missiles.push(crate::sim::Missile::test_at(i + 1, DVec3::new(i as f64, 64.0, -50.0), 0));
}
sim.missiles.push(crate::sim::Missile::test_at(100, DVec3::new(0.0, 64.0, 100.0), 0));
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
assert_eq!(fills(&shapes, MISSILE), 4, "the interceptor in frame got no marker");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
/// The header tells what really left the frame from what the draw budget cut, and the markers
/// go to the nearest of the visible: 64 behind the camera, 65 in frame.
#[test]
fn the_header_separates_the_frames_edge_from_the_draw_budget() {
let mut sim = Sim::new(1);
crowd_behind(&mut sim, 64);
for i in 0..65 {
let z = 100.0 + i as f64 * 10.0;
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, z), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default());
}
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
// The 64 nearest in frame are drawn; the farthest one is past the draw budget, not out of frame.
assert_eq!(fills(&shapes, RED), 4 * MAX_MARKERS);
assert!(texts(&shapes).iter().any(|t| t.text.contains("100 м")), "the nearest visible lost its marker");
assert!(!texts(&shapes).iter().any(|t| t.text.contains("740 м")), "the farthest visible took a nearer one's marker");
assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 64, за кадром 64, сверх бюджета 1");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
/// The projection work itself is bounded: with more candidates than the scan budget, only the
/// nearest `MAX_SCAN` are looked at, and the rest are counted as past the budget.
#[test]
fn the_projection_work_is_bounded_by_the_scan_budget() {
let mut sim = Sim::new(1);
for i in 0..1000 {
sim.launch(DroneKind::Shahed, DVec3::new((i % 100) as f64, 64.0, -50.0), DVec3::ZERO, DVec3::new(0.0, 64.0, -5000.0), &mut Out::default());
}
let calls = std::cell::Cell::new(0usize);
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, |p| {
calls.set(calls.get() + 1);
ahead(p)
});
assert_eq!(calls.get(), MAX_SCAN, "one layer projected more than its scan budget");
assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 0, за кадром 256, сверх бюджета 744");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
#[test]
fn interceptors_wear_small_yellow_squares_without_labels() {
let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
sim.missiles.push(crate::sim::Missile::test_at(1, DVec3::new(10.0, 70.0, 120.0), 0));
sim.missiles.push(crate::sim::Missile::test_at(2, DVec3::new(0.0, 64.0, -50.0), 0));
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
// The one ahead: four yellow sides; the one behind the camera: nothing.
assert_eq!(fills(&shapes, MISSILE), 4);
assert!(!texts(&shapes).iter().any(|t| t.text.contains("перехват")), "an interceptor is not a target");
// The budget holds with a full salvo too.
for id in 3..100 {
sim.missiles.push(crate::sim::Missile::test_at(id, DVec3::new(id as f64, 64.0, 100.0), 0));
}
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
assert!(fills(&shapes, MISSILE) / 4 <= MAX_MARKERS);
}
#[test]
fn labels_flip_over_the_square_near_the_edges() {
// Near the bottom: the label goes over the square; near the top: under it.
assert!(label_y(590.0, 10.0, 600.0, false) < 590.0);
assert!(label_y(10.0, 10.0, 600.0, true) > 10.0);
assert!(label_y(300.0, 10.0, 600.0, false) > 300.0);
assert!(label_y(300.0, 10.0, 600.0, true) < 300.0);
}
}
+106 -12
View File
@@ -1,6 +1,6 @@
//! The summary panel (top right): the alert, what is in the air, each
//! air-defence system's state and the score.
use crate::sim::{AirPicture, DroneKind, Sim};
use crate::sim::{AirPicture, Class, ClassEst, Sim};
use glam::DVec3;
use horizon_mod_sdk::hud::Line;
@@ -31,28 +31,50 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
} else {
let blink = (sim.tick / 10) % 2 == 0;
lines.push(line(format!("ВОЗДУШНАЯ ТРЕВОГА — целей: {}", pic.tracks.len()), if blink { RED } else { PINK }));
// By type, as the radars classed them.
// By the class the tracks were estimated (#133): probable and firm counted apart, the
// unidentified named — the exact models stay in the sandbox's truth line.
let mut by_type = String::new();
for kind in DroneKind::ALL {
let n = pic.tracks.iter().filter(|t| t.kind == kind).count();
if n > 0 {
if !by_type.is_empty() {
by_type += ", ";
for c in Class::ALL {
let firm = pic.tracks.iter().filter(|t| t.class == ClassEst::Firm(c)).count();
let prob = pic.tracks.iter().filter(|t| t.class == ClassEst::Probable(c)).count();
for (n, pre) in [(firm, ""), (prob, "вер. ")] {
if n > 0 {
if !by_type.is_empty() {
by_type += ", ";
}
by_type += &format!("{pre}{} ×{n}", c.name());
}
by_type += &format!("{} ×{n}", kind.spec().name);
}
}
let unknown = pic.tracks.iter().filter(|t| t.class == ClassEst::Unknown).count();
if unknown > 0 {
if !by_type.is_empty() {
by_type += ", ";
}
by_type += &format!("не опознано ×{unknown}");
}
lines.push(line(by_type, PINK));
// The nearest track to the player: where it was last measured (a forecast says so, with its age).
if let Some(t) = pic.nearest(player) {
let e = t.est(now);
let mark = if t.forecast(now) { format!(" ~{}с", t.age(now) / 20) } else { String::new() };
lines.push(line(
format!("Ближ.: {} {} выс.{:.0} {:.0}км/ч{mark}", t.kind.spec().name, distance(e.distance(player)), e.y - player.y, kmh(t.vel)),
format!("Ближ.: {} {} выс.{:.0} {:.0}км/ч · {} кач.{}{mark}", t.class.name(), distance(e.distance(player)), e.y - player.y, kmh(t.vel), t.product.name(), t.quality),
PINK,
));
}
}
// Recon aircraft the network tracks: their presence and the coarse phase of the flight. This is
// what the visible aircraft are doing, not the enemy's knowledge — the marks and the reasons are
// the debug command's and the after-action review's alone (#135).
let recon_n = pic.tracks.iter().filter(|t| crate::sim::is_drone_id(t.id)).count();
if recon_n > 0 {
let mut text = format!("Разведка противника: разведчиков в воздухе {recon_n}");
if let Some(phase) = crate::recon_view::battle_phase(&sim.enemy_picture()) {
text += &format!(" · фаза: {phase}");
}
lines.push(line(text, YELLOW));
}
if sim.truth {
let real = sim.drones.iter().filter(|d| d.alive()).count();
let unseen = sim.drones.iter().filter(|d| d.alive() && pic.get(d.id).is_none()).count();
@@ -61,6 +83,12 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
text += ", противник планирует налёт";
}
lines.push(line(text, YELLOW));
// The recon phase, in the truth only: the aircraft out and the marks the enemy holds
// are its knowledge, not the player's (#135).
let (out, marks) = sim.recon_status();
if out > 0 || marks > 0 {
lines.push(line(format!("РАЗВЕДКА ПРОТИВНИКА: в воздухе {out}, отметок в картине {marks}"), YELLOW));
}
}
// The launch sites found, and the strike missiles (#101).
if !sim.strikes.known.is_empty() || !sim.strikes.flights.is_empty() {
@@ -77,6 +105,11 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
let worst = sim.target_health.iter().copied().fold(100.0, f64::min);
lines.push(line(format!("Объекты: {}", list.join(" ")), if worst < 50.0 { RED } else { GREEN }));
}
// The passive optical posts (#136): their own status and source, never a radar's emission.
let optics = sim.optical_reports();
if let Some(r) = optics.iter().find(|r| r.state == crate::sim::OpticalState::Observing).or_else(|| optics.first()) {
lines.push(line(format!("Опт. №{}: {}", r.index, r.line()), CYAN));
}
let lost = sim.sams.iter().filter(|s| !s.alive()).count();
if lost > 0 {
lines.push(line(format!("Потеряно комплексов: {lost}"), RED));
@@ -94,12 +127,12 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
}
for sam in sim.sams.iter().take(shown) {
let mut text = if sam.kind.armed() {
format!("{} [{}]", sam.status(), crate::sim::roles_text(sam.roles))
format!("{} [{}]", crate::battery_view::sam_status(sam, now), crate::sim::roles_text(sam.roles))
} else {
sam.status()
crate::battery_view::sam_status(sam, now)
};
if let Some(t) = sam.gun_target.or(sam.target).and_then(|t| pic.get(t)) {
text += &format!(" > {} {}", t.kind.spec().name, distance(t.est(now).distance(sam.pos)));
text += &format!(" > {} {}", t.class.name(), distance(t.est(now).distance(sam.pos)));
}
if sam.kills > 0 {
text += &format!(" ({})", sam.kills);
@@ -119,3 +152,64 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
));
lines
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::{Aim, AirPicture, Approach, DroneKind, Out, RaidOrder, Track};
use glam::DVec3;
fn track(id: u32, class: ClassEst) -> Track {
Track { id, class, pos: DVec3::new(0.0, 120.0, 300.0), vel: DVec3::new(0.0, 0.0, -0.5), tick: 100, own_tick: 100, source: 0, product: crate::sim::battery::Measure::Search, quality: 40, own_product: crate::sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 3, locked: false }
}
// A recon aircraft the network holds is named as such, with the flight's coarse phase; the line
// carries no mark, area or priority — the enemy's knowledge is not the HUD's (#135).
#[test]
fn a_tracked_recon_aircraft_shows_presence_and_phase_not_marks() {
let mut sim = Sim::new(135);
let object = DVec3::new(0.0, 70.0, 0.0);
sim.targets.push(object);
sim.target_health.push(100.0);
let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 2)], approach: Approach::Sector, dist: 300.0, aim: Aim::Smart };
sim.order_raid(&order, &[object], &mut Out::default());
let pic = sim.air_picture();
assert!(pic.tracks.iter().any(|t| crate::sim::is_drone_id(t.id)), "the smart wave sent no recon to track");
let lines = summary(&sim, &pic, DVec3::ZERO);
let recon = lines.iter().find(|l| l.text.contains("Разведка противника")).expect("no recon line");
assert!(recon.text.contains("разведчиков в воздухе"), "{}", recon.text);
assert!(recon.text.contains("фаза:"), "the flight's phase was not shown: {}", recon.text);
assert!(!recon.text.contains("приоритет") && !recon.text.contains("Отметка"), "the HUD leaked the enemy's marks: {}", recon.text);
assert!(lines.iter().all(|l| !l.text.contains("Отметка") && !l.text.contains("приоритет")), "a mark reached the normal HUD");
}
// An ordinary strike track is not a recon flight: no recon line appears.
#[test]
fn an_ordinary_track_is_not_called_recon() {
let sim = Sim::new(1);
let pic = AirPicture { now: 100, tracks: vec![track(1, ClassEst::Firm(Class::Drone))], unaided: false };
let lines = summary(&sim, &pic, DVec3::ZERO);
assert!(lines.iter().all(|l| !l.text.contains("Разведка противника")), "{lines:?}");
}
// A recon id in the picture is enough for the presence line even without a live sortie (a flight
// finishing its way home): the phase is then omitted, the presence stays.
#[test]
fn a_recon_track_without_a_sortie_still_names_the_presence() {
let sim = Sim::new(1);
let pic = AirPicture { now: 100, tracks: vec![track(0x3000_0001, ClassEst::Firm(Class::Drone))], unaided: false };
let lines = summary(&sim, &pic, DVec3::ZERO);
let recon = lines.iter().find(|l| l.text.contains("Разведка противника")).expect("no recon line");
assert!(recon.text.contains("разведчиков в воздухе 1"), "{}", recon.text);
assert!(!recon.text.contains("фаза:"), "a phase was invented without a sortie: {}", recon.text);
}
#[test]
fn an_empty_sky_has_no_recon_line() {
let sim = Sim::new(1);
let pic = AirPicture { now: 100, tracks: Vec::new(), unaided: false };
let lines = summary(&sim, &pic, DVec3::ZERO);
assert!(lines.iter().all(|l| !l.text.contains("Разведка противника")), "{lines:?}");
}
}
+295
View File
@@ -0,0 +1,295 @@
//! The command post lists every deployed unit without requesting camera views.
use crate::sim::{Part, PartState, Sam, SamKind, SamState, battery::RadarRole, decision, record::Recording};
/// Keep enough room under the engine's 512-row limit for large layouts.
pub const PAGE_SIZE: usize = 200;
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub enum Filter {
#[default]
All,
Weapons,
Sensors,
Support,
InCombat,
NoAmmo,
NoLink,
Damaged,
}
impl Filter {
const ALL: [Self; 8] = [
Self::All, Self::Weapons, Self::Sensors, Self::Support, Self::InCombat,
Self::NoAmmo, Self::NoLink, Self::Damaged,
];
pub fn next(self) -> Self {
Self::ALL[(self as usize + 1) % Self::ALL.len()]
}
pub fn label(self) -> &'static str {
match self {
Self::All => "Все",
Self::Weapons => "Огневые",
Self::Sensors => "Наблюдение",
Self::Support => "Поддержка",
Self::InCombat => "В работе",
Self::NoAmmo => "Без боезапаса",
Self::NoLink => "Отказ связи",
Self::Damaged => "Повреждённые",
}
}
fn matches(self, sam: &Sam) -> bool {
let sensor = matches!(sam.kind, SamKind::Radar | SamKind::Optical);
match self {
Self::All => true,
Self::Weapons => sam.kind.armed(),
Self::Sensors => sensor,
Self::Support => !sam.kind.armed() && !sensor,
Self::InCombat => sam.alive() && (
matches!(sam.state, SamState::Track | SamState::Slew | SamState::Lock | SamState::Launch | SamState::Fire)
|| sam.ew_on
|| (sensor && !sam.own.is_empty())
|| (sam.kind == SamKind::Optical && sam.optical.state() == crate::sim::OpticalState::Observing)
),
Self::NoAmmo => sam.alive() && sam.kind.armed() && sam.missiles == 0 && sam.bursts == 0,
Self::NoLink => sam.alive() && Part::Comms.on(sam.kind) && sam.part_state(Part::Comms) == PartState::Failed,
Self::Damaged => sam.health < 1.0 || !sam.comps.whole(),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum From {
World,
Post,
Map(u32),
Monitor,
Source,
}
#[derive(Clone, Copy)]
pub enum Action {
Checks,
Map,
Camera,
Source(u32),
Pin,
History,
}
pub enum Transition {
Map { unit: u32, centre: bool },
Card(u32),
}
#[derive(Default)]
pub struct Post {
pub filter: Filter,
pub query: String,
pub page: usize,
pub pinned: Option<u32>,
/// IDs and actions exactly as shown in the screen, even if the sim advances before a click.
pub shown: Vec<u32>,
pub actions: Vec<Action>,
pub decisions: Vec<RecordedChoice>,
pub source_origin: Option<(u32, From)>,
/// Let the client finish closing one screen before opening a different kind.
pub transition: Option<(Transition, bool)>,
}
#[derive(Clone, Copy)]
pub struct RecordedChoice {
pub raid: u32,
pub entry: decision::Entry,
}
pub fn decision_label(outcome: decision::Outcome) -> &'static str {
use decision::{Block as B, Outcome as O};
match outcome {
O::Held(B::Hold) => "Огонь запрещён",
O::Held(B::Moving) => "Комплекс на марше",
O::Held(B::Reload) => "Перезарядка",
O::Held(B::Empty) => "Ожидает пополнения",
O::Held(B::NoSelection) => "Цель не назначена",
O::Held(B::WaitingForTerrain) => "Ожидает данных о рельефе",
O::Held(B::Terrain) => "Траектория перекрыта",
O::Held(B::Aim) => "Доворачивается",
O::Held(B::Opening) => "Открывает ТПК",
O::Held(B::BusyWithGroundShot) => "Готовит наземный пуск",
O::Held(B::Cooldown) => "Пауза между выстрелами",
O::Held(B::GunFault) => "Орудие недоступно",
O::Held(B::LauncherFault) => "Пусковая недоступна",
O::Held(B::NoLock) => "Нет свежего захвата",
O::Held(B::Range) => "Вне дальности орудия",
O::Burst => "Очередь выпущена",
O::BurstMissed => "Промах очереди",
O::BurstHit | O::Intercepted(_) => "Цель сбита",
O::Launched(_) => "Ракета выпущена",
O::InterceptorMissed(_) => "Промах перехватчика",
O::InterceptorEnded(_) => "Полёт перехватчика завершён",
}
}
pub fn decision_lines(choice: RecordedChoice, rec: Option<&Recording>) -> Vec<String> {
use decision::{Channel, Outcome};
let entry = choice.entry;
let channel = match entry.channel {
Channel::Launcher => "Пусковая",
Channel::Gun => "Орудие",
Channel::Unit => "Комплекс",
};
let mut lines = vec![
format!("Налёт №{} · {} · {channel}", choice.raid, crate::replay::clock(f64::from(entry.at))),
format!("На тот момент · {}", decision_label(entry.outcome)),
];
if matches!(entry.outcome, Outcome::Held(_)) {
lines.push("На этой проверке выстрела не было".to_owned());
}
if let Some(target) = entry.target {
lines.push(format!("Трек №{target}"));
}
if let Some(mark) = entry.mark {
let source = if mark.own { "своя отметка".to_owned() } else {
rec.and_then(|rec| rec.sams.iter().position(|s| s.0 == mark.source))
.map_or_else(|| format!("источник ID {}", mark.source), |i| format!("источник №{}", i + 1))
};
lines.push(format!("{source} · {:.1} с назад", f64::from(mark.age) / 20.0));
lines.push(format!("{} · {} · качество {}", mark.product.name(), mark.class.name(), mark.quality));
}
if let Outcome::Launched(id) | Outcome::Intercepted(id) | Outcome::InterceptorMissed(id) | Outcome::InterceptorEnded(id) = entry.outcome {
lines.push(format!("Перехватчик ID {id}"));
}
lines
}
impl Post {
pub fn matching(&self, sams: &[Sam]) -> Vec<usize> {
let number = self.query.trim_start_matches('№').parse::<usize>().ok();
let mut rows: Vec<_> = sams.iter().enumerate()
.filter(|(i, sam)| self.filter.matches(sam) && (self.query.is_empty()
|| number == Some(i + 1)
|| sam.kind.key().contains(&self.query)
|| sam.kind.name().to_lowercase().contains(&self.query)))
.map(|(i, _)| i)
.collect();
if let Some(i) = rows.iter().position(|&i| self.pinned == Some(sams[i].id)) {
let pinned = rows.remove(i);
rows.insert(0, pinned);
}
rows
}
}
pub fn state(sam: &Sam) -> &'static str {
if !sam.alive() {
return "Уничтожен";
}
if sam.moving() {
return sam.state.name();
}
match sam.kind {
SamKind::Optical => sam.optical.state().name(),
SamKind::Radar if !sam.radar_on => "Излучение выкл.",
SamKind::Radar if !sam.radar_up() => "РЛС недоступна",
SamKind::Radar if !sam.own.is_empty() => "Есть отметки",
SamKind::Ew if sam.ew_on => "Активна",
SamKind::Ew | SamKind::Depot | SamKind::Tzm | SamKind::Light => "На позиции",
_ => sam.state.name(),
}
}
pub fn row(sam: &Sam, index: usize, pinned: bool) -> String {
let name = match sam.kind {
SamKind::Radar => match sam.radar_role {
RadarRole::Search => "РЛС обзора",
RadarRole::Engagement => "РЛС сопровождения",
RadarRole::Height => "РЛС высоты",
RadarRole::Multifunction => "РЛС",
},
SamKind::Depot => "Склад",
_ => sam.kind.name(),
};
let status = if Filter::NoLink.matches(sam) {
"Нет связи"
} else if Filter::NoAmmo.matches(sam) && sam.reloading == 0 {
"Нет БК"
} else {
state(sam)
};
let pin = if pinned { "★ " } else { "" };
let health = if sam.alive() && Filter::Damaged.matches(sam) {
format!(" · {:.0}%", sam.health * 100.0)
} else {
String::new()
};
format!("{pin}№{} {name} · {status}{health}", index + 1)
}
#[cfg(test)]
mod tests {
use super::*;
use glam::DVec3;
#[test]
fn the_post_includes_support_and_searches_names_keys_and_shown_numbers() {
let sams = [
Sam::new(77, SamKind::Pantsir, DVec3::ZERO, 0.0),
Sam::new(90, SamKind::Depot, DVec3::ZERO, 0.0),
Sam::new(23, SamKind::Radar, DVec3::ZERO, 0.0),
];
let mut post = Post { pinned: Some(23), ..Post::default() };
assert_eq!(post.matching(&sams), [2, 0, 1]);
for (query, expected) in [("панц", 0), ("depot", 1), ("№3", 2)] {
post.query = query.to_string();
assert_eq!(post.matching(&sams), [expected]);
}
post.query.clear();
post.filter = Filter::Support;
assert_eq!(post.matching(&sams), [1]);
assert_eq!(post.pinned, Some(23));
}
#[test]
fn availability_filters_distinguish_empty_worn_and_destroyed_units() {
let mut ready = Sam::new(15, SamKind::Pantsir, DVec3::ZERO, 0.0);
ready.missiles = 0;
ready.bursts = 0;
ready.comps.0[Part::Comms as usize] = 0.0;
assert!(Filter::NoAmmo.matches(&ready));
assert!(Filter::NoLink.matches(&ready));
assert!(Filter::Damaged.matches(&ready));
assert!(row(&ready, 0, true).starts_with("★ №1"));
ready.health = 0.0;
assert!(!Filter::NoAmmo.matches(&ready));
assert!(!Filter::NoLink.matches(&ready));
assert_eq!(state(&ready), "Уничтожен");
assert!(Filter::Damaged.matches(&ready));
}
#[test]
fn historical_details_use_the_recorded_station_and_separate_a_miss_from_a_refusal() {
let mut rec = Recording::blank(100);
rec.sams = vec![(96, SamKind::S400, DVec3::ZERO), (48, SamKind::Radar, DVec3::X)];
let entry = decision::Entry {
unit: 96,
at: 40,
target: Some(112),
channel: decision::Channel::Launcher,
outcome: decision::Outcome::Held(decision::Block::Terrain),
mark: Some(decision::Mark {
source: 48, age: 12, own: false, quality: 62,
product: crate::sim::battery::Measure::Search,
class: crate::sim::ClassEst::Unknown,
}),
};
let lines = decision_lines(RecordedChoice { raid: 2, entry }, Some(&rec));
assert!(lines.iter().any(|line| line == "источник №2 · 0.6 с назад"));
assert!(lines.iter().any(|line| line.contains("выстрела не было")));
let missed = decision::Entry { outcome: decision::Outcome::InterceptorMissed(144), mark: None, ..entry };
let lines = decision_lines(RecordedChoice { raid: 2, entry: missed }, None);
assert!(lines.iter().any(|line| line.contains("Промах перехватчика")));
assert!(!lines.iter().any(|line| line.contains("выстрела не было")));
}
}
+34
View File
@@ -286,6 +286,16 @@ impl<P, E> Session<P, E> {
Some(Cleanup { actions })
}
/// The world is gone (the title screen): the game stops ticking there, so an active export
/// would otherwise go on recording the title with its playback clock frozen. Nothing to do
/// in Live, and a world still open is not a leave.
pub fn world_left(&mut self, world: Option<&str>) -> Option<Cleanup> {
if self.is_live() || world.is_some() {
return None;
}
self.end(ExitCause::WorldChange)
}
/// A world change invalidates live work too. Active playback uses the normal cleanup path,
/// which advances generation exactly once; Live advances generation without host cleanup.
pub fn world_changed(&mut self) -> Option<Cleanup> {
@@ -466,6 +476,30 @@ mod tests {
assert_ne!(session.generation(), first);
}
#[test]
fn a_gone_world_ends_an_active_export_once() {
let mut session = Session::<(), ()>::default();
assert!(session.world_left(None).is_none(), "Live has nothing to clean up");
session.replay(());
assert!(session.world_left(Some("world:w")).is_none(), "the world is still open");
let State::Replay(playback) = session.take() else {
panic!("replay state lost")
};
session.export(playback, ());
let cleanup = session.world_left(None).expect("the title screen ends the export");
assert!(cleanup.actions.contains(&CleanupAction::CancelCapture));
let mut host = HostFixture::default();
host.apply(&cleanup);
let count = host.actions.len();
assert!(session.world_left(None).is_none(), "a second frame sees Live");
assert_eq!(host.actions.len(), count, "cleanup is not repeated");
assert_eq!(
host.actions.iter().filter(|a| **a == CleanupAction::CancelCapture).count(),
1
);
}
#[test]
fn end_and_restart_emit_cleanup_once_for_stop_unload_failure_and_success() {
for cause in [
+171 -14
View File
@@ -1,15 +1,24 @@
//! The radar screen (top left): a round scope round the player, north up,
//! with a sweeping beam; blips fade after the beam passes them.
//! The radar screen (bottom right): a round scope round the player, north up,
//! with a sweeping beam; blips fade after the beam passes them. A track's blip is a shape by the
//! class the radar measured (#132), big enough to read at a glance; close ones merge with a count.
use crate::panel::distance;
use crate::sim::{SamKind, Sim};
use crate::sim::{Class, ClassEst, SamKind, Sim};
use glam::DVec3;
use horizon_mod_sdk::render::{FillShape, Point, QuadShape, Rect, Shape, TextShape};
/// The scope's side in GUI pixels.
pub const SIZE: f32 = 112.0;
/// The corner box's height: the scope and its range label, plus the truth mode's own line when it shows one.
pub fn height(truth_label: bool) -> f32 {
SIZE + if truth_label { 22.0 } else { 12.0 }
}
/// Blocks from the centre to the edge.
const RANGE: f64 = 500.0;
const SEGMENTS: usize = 48;
/// A track blip's half-size: the icons span about six pixels, against the old dot's three and a half.
const BLIP: f32 = 3.0;
/// Tracks this close on the scope merge into one blip with their number.
const MERGE_R: f32 = 4.5;
fn pt(x: f32, y: f32) -> Point {
Point { x, y }
@@ -32,6 +41,34 @@ fn alpha(rgb: u32, a: f64) -> u32 {
((a.clamp(0.0, 1.0) * 255.0) as u32) << 24 | (rgb & 0xFFFFFF)
}
/// A track's blip: a shape by the estimated class, pointing along the measured course.
/// Drones are triangles, jets darts, cruise squares, supersonic diamonds, ballistic octagons;
/// an unidentified track gets a question mark instead of leaking the target's type (#133).
fn blip(class: ClassEst, x: f32, y: f32, color: u32, vel: DVec3) -> Vec<Shape> {
let h = DVec3::new(vel.x, 0.0, vel.z).normalize_or_zero();
let (hx, hy) = if h == DVec3::ZERO { (0.0, -1.0) } else { (h.x as f32, h.z as f32) };
let (px, py) = (-hy, hx);
let r = BLIP;
let at = |along: f32, side: f32| pt(x + hx * along + px * side, y + hy * along + py * side);
match class.class() {
Some(Class::Drone) => vec![quad(at(r * 1.2, 0.0), at(-r * 0.8, r * 0.9), at(-r * 0.8, -r * 0.9), at(-r * 0.8, -r * 0.9), color)],
Some(Class::Jet) => vec![quad(at(r * 1.3, 0.0), at(-r * 0.9, r * 0.9), at(-r * 0.3, 0.0), at(-r * 0.9, -r * 0.9), color)],
Some(Class::Cruise) => vec![square(x, y, 2.6, color)],
Some(Class::Supersonic) => vec![quad(pt(x, y - 3.2), pt(x + 3.2, y), pt(x, y + 3.2), pt(x - 3.2, y), color)],
Some(Class::Ballistic) => vec![square(x, y, 2.3, color), quad(pt(x, y - r), pt(x + r, y), pt(x, y + r), pt(x - r, y), color)],
None => vec![square(x, y, 2.4, color), text("?".into(), x, y - 3.0, 0xFF200808, true)],
}
}
/// Keeps a blip's centre far enough inside the disc that the whole icon stays on the scope: the longest point
/// of any class's icon is 1.3 × a half-size out.
fn inside(x: f32, y: f32, cx: f32, cy: f32, r: f32) -> (f32, f32) {
let (dx, dy) = (x - cx, y - cy);
let d = dx.hypot(dy);
let max = r - BLIP * 1.4 - 0.5;
if d > max && d > 0.0 { (cx + dx / d * max, cy + dy / d * max) } else { (x, y) }
}
pub fn draw(sim: &Sim, player: DVec3, yaw: f32) -> Vec<Shape> {
let mut s = Vec::new();
let r = SIZE / 2.0 - 2.0;
@@ -143,49 +180,169 @@ pub fn draw(sim: &Sim, player: DVec3, yaw: f32) -> Vec<Shape> {
s.push(square(x, y, 1.5, 0xFFFFFFA0));
}
}
// The player is below target blips: a close target must not disappear under the white arrow.
// Minecraft's yaw 0 looks south (+z, down the scope).
let face = yaw.to_radians();
let tip = |a: f32, l: f32| pt(cx - (face + a).sin() * l, cy + (face + a).cos() * l);
s.push(quad(tip(0.0, 6.0), tip(2.5, 4.0), pt(cx, cy), tip(-2.5, 4.0), 0xFFFFFFFF));
let mut far = 0;
// The air picture is what the systems' radars hold, as they last measured it (a track older than a second
// is a forecast, dimmer); with no system deployed, the sky as it is. Nothing else is read (#93).
let pic = sim.air_picture();
let now = pic.now;
// (x, y, class, colour, brightness, velocity) of every track on the scope, its icon kept inside the disc.
let mut marks: Vec<(f32, f32, ClassEst, u32, f64, DVec3)> = Vec::new();
for t in &pic.tracks {
let (pos, vel) = (t.est(now), t.vel);
match scope(pos) {
Some((x, y, bearing)) => {
// Fresh: bright and red; a forecast: orange, fading as it ages towards the track's drop.
// The product is visible: a coarse search plot is amber, a refinement yellow, a fire plot red.
let fresh_color = match t.product {
crate::sim::battery::Measure::Search => 0xFFB060,
crate::sim::battery::Measure::Refine => 0xFFE070,
crate::sim::battery::Measure::Fire => 0xFF4040,
};
let (a, color) = if pic.unaided {
(fade(bearing), 0xFF4040)
} else if t.forecast(now) {
((1.0 - t.age(now) as f64 / t.ttl.max(1) as f64 * 0.7).max(0.3), 0xFFB040)
} else {
(1.0, 0xFF4040)
(1.0, fresh_color)
};
s.push(square(x, y, 1.8, alpha(color, a)));
// Its heading, a short tail.
let v = vel.normalize_or_zero();
s.push(quad(pt(x, y), pt(x + 0.6, y), pt(x - v.x as f32 * 6.0 + 0.6, y - v.z as f32 * 6.0), pt(x - v.x as f32 * 6.0, y - v.z as f32 * 6.0), alpha(color, a * 0.6)));
let (x, y) = inside(x, y, cx, cy, r);
marks.push((x, y, t.class, color, a, vel));
}
None => far += 1,
}
}
// A tight raid reads as one blip with its number, not a pile of icons.
let pos: Vec<(f32, f32)> = marks.iter().map(|m| (m.0, m.1)).collect();
for grp in crate::map::group(&pos, MERGE_R) {
let (x, y, class, color, a, vel) = marks[grp[0]];
s.extend(blip(class, x, y, alpha(color, a), vel));
// Its heading, a short tail, kept on the disc too.
let v = vel.normalize_or_zero();
let (ex, ey) = inside(x - v.x as f32 * 7.0, y - v.z as f32 * 7.0, cx, cy, r);
s.push(quad(pt(x, y), pt(x + 1.0, y), pt(ex + 1.0, ey), pt(ex, ey), alpha(color, a * 0.6)));
if grp.len() > 1 {
s.push(text(format!("×{}", grp.len()), x + 4.0, y - 9.0, alpha(color, a), false));
}
}
// The true places, when the sandbox asks for them: a white dot beside the track, to see how far the picture is off.
if sim.truth && !pic.unaided {
for d in sim.drones.iter().filter(|d| d.alive()) {
if let Some((x, y, _)) = scope(d.pos) {
s.push(square(x, y, 0.8, 0xFFFFFFFF));
let (x, y) = inside(x, y, cx, cy, r);
s.push(square(x, y, 1.3, 0xFFFFFFFF));
}
}
}
// The player: a white arrow the way they look.
// Minecraft's yaw 0 looks south (+z, down the scope).
let face = yaw.to_radians();
let tip = |a: f32, l: f32| pt(cx - (face + a).sin() * l, cy + (face + a).cos() * l);
s.push(quad(tip(0.0, 6.0), tip(2.5, 4.0), pt(cx, cy), tip(-2.5, 4.0), 0xFFFFFFFF));
// Labels.
s.push(text(format!("РЛС · {}", distance(RANGE)), cx, SIZE + 2.0, 0xFF80FF90, true));
if sim.truth && !pic.unaided {
s.push(text("ИСТИНА · песочница".into(), cx, SIZE + 12.0, 0xFFFFE070, true));
}
s.push(text("С".into(), cx, 3.0, 0xFF80FF90, true));
if far > 0 {
s.push(text(format!("+{far} за пределом"), cx, SIZE - 14.0, 0xFFFF8080, true));
}
s
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::{DroneKind, Out, Sam};
#[test]
fn target_blips_are_drawn_over_the_player_arrow() {
let mut sim = Sim::new(1);
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, -10.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
let shapes = draw(&sim, DVec3::ZERO, 0.0);
let arrow = shapes.iter().rposition(|s| matches!(s, Shape::Quad(q) if q.color == 0xFFFFFFFF)).unwrap();
// The Shahed's blip is a red triangle (a quad with a repeated corner), drawn after the arrow.
let target = shapes.iter().rposition(|s| matches!(s, Shape::Quad(q) if q.color == 0xFFFF4040)).unwrap();
assert!(target > arrow, "the player arrow covers the target blip");
}
#[test]
fn every_class_has_its_own_blip_shape() {
let vel = DVec3::new(0.5, 0.0, 0.0);
let shapes: Vec<Vec<Shape>> = Class::ALL.iter().map(|c| blip(ClassEst::Firm(*c), 50.0, 50.0, 0xFFFF4040, vel)).collect();
for (i, a) in shapes.iter().enumerate() {
assert!(!a.is_empty());
for b in &shapes[i + 1..] {
assert_ne!(format!("{a:?}"), format!("{b:?}"), "two classes share one icon");
}
}
// A courseless track (a ballistic one straight overhead) still draws, pointing north.
assert!(!blip(ClassEst::Firm(Class::Ballistic), 50.0, 50.0, 0xFFFF4040, DVec3::Y).is_empty());
assert!(blip(ClassEst::Unknown, 50.0, 50.0, 0xFFFF4040, vel).iter().any(|s| matches!(s, Shape::Text(t) if t.text == "?")));
}
#[test]
fn blips_stay_inside_the_scope() {
let mut sim = Sim::new(1);
// One track near the rim on every bearing, one of each class among them, one just beyond it.
for k in 0..8 {
let a = k as f64 / 8.0 * std::f64::consts::TAU;
sim.launch(DroneKind::Shahed, DVec3::new(a.sin() * 495.0, 64.0, a.cos() * 495.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
}
for (k, kind) in [DroneKind::Geran3, DroneKind::Kh101, DroneKind::Kh22, DroneKind::Kinzhal].into_iter().enumerate() {
let a = (k as f64 + 0.5) / 4.0 * std::f64::consts::TAU;
sim.launch(kind, DVec3::new(a.sin() * 490.0, 64.0, a.cos() * 490.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
}
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, -700.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
let shapes = draw(&sim, DVec3::ZERO, 0.0);
let (cx, cy, r) = (SIZE / 2.0, SIZE / 2.0, SIZE / 2.0 - 2.0);
let mut blips = 0;
for s in &shapes {
let corners = match s {
Shape::Quad(q) if q.color & 0xFFFFFF == 0xFF4040 => vec![q.corners.0, q.corners.1, q.corners.2, q.corners.3],
Shape::Fill(f) if f.color & 0xFFFFFF == 0xFF4040 => vec![pt(f.rect.x, f.rect.y), pt(f.rect.x + f.rect.w, f.rect.y), pt(f.rect.x, f.rect.y + f.rect.h), pt(f.rect.x + f.rect.w, f.rect.y + f.rect.h)],
_ => continue,
};
blips += 1;
for p in corners {
assert!((p.x - cx).hypot(p.y - cy) <= r + 0.01, "a blip corner leaves the disc: {p:?}");
}
}
assert!(blips >= 8, "the rim tracks were not drawn");
assert!(shapes.iter().any(|s| matches!(s, Shape::Text(t) if t.text.contains("за пределом"))), "the track beyond the range is counted");
}
#[test]
fn a_tight_raid_merges_into_one_blip_with_a_count() {
let mut sim = Sim::new(1);
for k in 0..3 {
sim.launch(DroneKind::Shahed, DVec3::new(100.0 + k as f64, 64.0, -100.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
}
let shapes = draw(&sim, DVec3::ZERO, 0.0);
assert!(shapes.iter().any(|s| matches!(s, Shape::Text(t) if t.text == "×3")), "the merged blip has no count");
let triangles = shapes
.iter()
.filter(|s| matches!(s, Shape::Quad(q) if q.color & 0xFFFFFF == 0xFF4040 && q.corners.2.x == q.corners.3.x && q.corners.2.y == q.corners.3.y))
.count();
assert_eq!(triangles, 1, "three close tracks drew three icons");
}
#[test]
fn the_truth_mode_is_labelled_on_the_scope() {
let mut sim = Sim::new(1);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Buk, DVec3::new(0.0, 64.0, 0.0), 0.0));
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, -100.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
let plain = draw(&sim, DVec3::ZERO, 0.0);
assert!(!plain.iter().any(|s| matches!(s, Shape::Text(t) if t.text.contains("ИСТИНА"))));
sim.truth = true;
let shapes = draw(&sim, DVec3::ZERO, 0.0);
let label = shapes.iter().find_map(|s| match s {
Shape::Text(t) if t.text.contains("ИСТИНА") && t.text.contains("песочница") => Some(t),
_ => None,
}).expect("the truth mode is not marked");
// The corner box is sized to hold the label: a line of the HUD font is 9 pixels with its shadow.
assert!(label.at.y + 9.0 <= height(true), "the truth label falls outside the corner box");
assert!(height(true) > height(false));
}
}
+298
View File
@@ -0,0 +1,298 @@
//! Text for the enemy's reconnaissance (#135): the readable phase of a recon flight and the
//! reason a mark outranks another. It reads only the diagnostic report types (`EnemyPictureReport`,
//! `ReconReport`, `ReconSortieReport`) — an area, a public category, a channel, an age and a quality,
//! never a true place, `SamKind`, health, magazine, link or real id. The full picture is for the
//! explicit debug command and the after-action review; the battle HUD takes only the coarse phase
//! of aircraft the player's own network already tracks.
use crate::sim::{Category, Confidence, EnemyPictureReport, Quality, ReconReport, ReconSortieReport, priority_parts};
/// The public category a look reported, in the panel's words.
pub fn category_name(key: &str) -> &'static str {
match key {
"radar" => "РЛС",
"launcher" => "пусковая",
"gun" => "пушка",
"ew" => "РЭБ",
"support" => "тыл",
_ => "не определено",
}
}
/// A radar's role, public only once a refined look told it.
pub fn role_name(key: &str) -> &'static str {
match key {
"multi" => "многофункциональная",
"search" => "обзорная",
"engagement" => "наведения",
"height" => "высотомер",
_ => "не определена",
}
}
/// The channel that showed the unit.
pub fn source_name(key: &str) -> &'static str {
match key {
"emission" => "излучение",
"jamming" => "РЭБ",
"launch" => "пуск",
_ => "пролёт",
}
}
/// How well the area is known.
pub fn quality_name(key: &str) -> &'static str {
match key {
"refined" => "уточнённая",
_ => "грубая",
}
}
/// The trust the picture puts in a mark of this age.
pub fn confidence_name(confidence: Confidence) -> &'static str {
match confidence {
Confidence::Confirmed => "подтверждена",
Confidence::Probable => "вероятна",
Confidence::Doubtful => "сомнительна",
}
}
/// The phase of a sortie, as the timeline and the battle UI read it.
pub fn phase_name(phase: &str) -> &'static str {
match phase {
"reporting" => "донесение",
"done" => "завершение",
"looking" => "осмотр",
_ => "разведка",
}
}
/// Why a smart drone's aim is what it is, in words.
pub fn intent_name(intent: &str) -> &'static str {
match intent {
"sead" => "подавление ПВО",
"react" => "реакция",
"replace" => "замена",
_ => "план",
}
}
/// One mark in a line: its area's category and role, the channel, the quality, the trust, the age
/// and the priority the planner prices it at.
pub fn mark_line(m: &ReconReport) -> String {
let role = m.role.map(|k| format!(" ({})", role_name(k))).unwrap_or_default();
format!(
"Отметка {}: {}{} · {} · {} · {} · {} с назад · приоритет {}",
m.id,
category_name(m.category),
role,
source_name(m.source),
quality_name(m.quality),
confidence_name(m.confidence),
m.age / 20,
m.priority
)
}
/// Why the mark has the priority it does: the observed role, the freshness and the quality, each
/// with the weight the planner gives it, summing to the priority. The unit's true importance is not
/// in it — only what the look reported.
pub fn mark_reason(m: &ReconReport) -> String {
let category = Category::from_key(m.category).unwrap_or(Category::Unknown);
let quality = Quality::from_key(m.quality).unwrap_or(Quality::Coarse);
let role = m.role.and_then(crate::sim::battery::RadarRole::from_key);
let (freshness, quality_w, role_w) = priority_parts(m.confidence, quality, category, role);
let role_txt = match m.role {
Some(key) => format!("роль «{}»", role_name(key)),
None => format!("категория «{}»", category_name(m.category)),
};
format!(
"приоритет {} = свежесть {}×4 + качество {}×3 + роль {}: {} {}, {}",
m.priority,
freshness,
quality_w,
role_w,
confidence_name(m.confidence),
quality_name(m.quality),
role_txt
)
}
/// One sortie in a line: its phase, the zones left and when its pending report is due.
pub fn sortie_line(s: &ReconSortieReport) -> String {
let mut text = format!("Разведчик {}: {}", s.drone, phase_name(s.phase));
if s.zones_left > 0 {
text += &format!(" · зон осталось {}", s.zones_left);
}
if let Some(due) = s.report_in {
text += &format!(" · донесение через {} с", due / 20);
}
text
}
/// The coarse phase of the recon flight for the battle UI: a report going home now, else aircraft
/// still looking, else the flight finishing. `None` when no sortie is out. It says nothing of what
/// the enemy learned — only what its visible aircraft are doing.
pub fn battle_phase(pic: &EnemyPictureReport) -> Option<&'static str> {
if pic.recon_sorties.iter().any(|s| s.phase == "reporting") {
Some("донесение")
} else if pic.recon_sorties.iter().any(|s| s.phase == "outbound" || s.phase == "looking") {
Some("разведка")
} else if !pic.recon_sorties.is_empty() {
Some("завершение")
} else {
None
}
}
/// The whole picture for the debug command and the after-action review: the sorties and their
/// phases, then the marks best-first with the reason each outranks the rest, then the drones aimed
/// at a mark. Explicitly the enemy's belief, not the truth; never the normal HUD.
pub fn picture_lines(pic: &EnemyPictureReport) -> Vec<String> {
let mut lines = Vec::new();
if pic.recon.is_empty() && pic.recon_sorties.is_empty() {
lines.push("Разведки не было: противник не высылал разведчиков и ничего не запомнил.".into());
return lines;
}
lines.push(format!(
"Картина противника (debug/разбор): отметок {}, разведчиков в воздухе {}",
pic.recon.len(),
pic.recon_sorties.len()
));
for s in &pic.recon_sorties {
lines.push(sortie_line(s));
}
let mut marks: Vec<&ReconReport> = pic.recon.iter().collect();
marks.sort_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
for m in marks {
lines.push(mark_line(m));
lines.push(format!(" ↳ {}", mark_reason(m)));
}
for a in pic.aims.iter().filter(|a| a.recon) {
lines.push(format!(
"Дрон {} целится в отметку {} (приоритет {}, {})",
a.drone,
a.unit,
a.priority.unwrap_or(0),
intent_name(a.intent)
));
}
lines
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::{AimReport, BearingReport, Confidence, EnemyPictureReport, ReconReport, ReconSortieReport};
use glam::DVec3;
fn mark(id: u32, category: &'static str, role: Option<&'static str>, quality: &'static str, confidence: Confidence, age: u64) -> ReconReport {
let cat = Category::from_key(category).unwrap();
let qual = Quality::from_key(quality).unwrap();
let role_enum = role.and_then(crate::sim::battery::RadarRole::from_key);
let (f, q, r) = priority_parts(confidence, qual, cat, role_enum);
ReconReport { id, area: DVec3::ZERO, radius: 120.0, category, role, source: "flyby", age, quality, confidence, live: true, priority: f * 4 + q * 3 + r }
}
fn sortie(drone: u32, phase: &'static str, zones_left: usize, report_in: Option<u64>) -> ReconSortieReport {
ReconSortieReport { drone, phase, zones_left, report_in }
}
fn picture(recon: Vec<ReconReport>, recon_sorties: Vec<ReconSortieReport>, aims: Vec<AimReport>) -> EnemyPictureReport {
EnemyPictureReport {
now: 1000,
contacts: Vec::new(),
aims,
pending: Vec::new(),
work_per_tick: 4,
recon,
recon_sorties,
observations: Vec::new(),
bearing: BearingReport::default(),
refresh_waiting: false,
refresh_applied: 0,
}
}
// The reason names all three factors with the planner's own weights, and they sum to the priority.
#[test]
fn the_reason_is_the_observed_role_freshness_and_quality() {
let m = mark(0x1000_0001, "radar", Some("engagement"), "refined", Confidence::Confirmed, 100);
let reason = mark_reason(&m);
assert_eq!(m.priority, 4 * 4 + 2 * 3 + 3);
assert!(reason.contains("приоритет 25 = свежесть 4×4 + качество 2×3 + роль 3"), "{reason}");
assert!(reason.contains("подтверждена") && reason.contains("уточнённая") && reason.contains("роль «наведения»"), "{reason}");
// A coarse, doubtful, unknown mark: every part is zero, and the reason says so.
let weak = mark(0x1000_0002, "unknown", None, "coarse", Confidence::Doubtful, 5000);
assert_eq!(weak.priority, 0);
let weak_reason = mark_reason(&weak);
assert!(weak_reason.contains("свежесть 0×4 + качество 0×3 + роль 0"), "{weak_reason}");
assert!(weak_reason.contains("сомнительна") && weak_reason.contains("категория «не определено»"), "{weak_reason}");
}
// A fresh modest mark can outrank a stale big one: the reason reflects the age, not the truth.
#[test]
fn a_fresh_modest_mark_outranks_a_stale_big_one() {
let stale_big = mark(0x1000_0001, "radar", Some("engagement"), "refined", Confidence::Doubtful, 5000);
let fresh_modest = mark(0x1000_0002, "gun", None, "coarse", Confidence::Confirmed, 100);
assert!(fresh_modest.priority > stale_big.priority, "{} vs {}", fresh_modest.priority, stale_big.priority);
let fresh_id = fresh_modest.id;
let lines = picture_lines(&picture(vec![stale_big, fresh_modest], Vec::new(), Vec::new()));
let first = lines.iter().position(|l| l.starts_with("Отметка")).unwrap();
assert!(lines[first].contains(&format!("Отметка {fresh_id}")), "the fresh modest mark did not lead: {lines:?}");
}
#[test]
fn the_phase_reads_recon_report_and_done() {
assert_eq!(phase_name("outbound"), "разведка");
assert_eq!(phase_name("reporting"), "донесение");
assert_eq!(phase_name("done"), "завершение");
let reporting = picture(Vec::new(), vec![sortie(0x3000_0001, "reporting", 0, Some(40)), sortie(0x3000_0002, "outbound", 2, None)], Vec::new());
assert_eq!(battle_phase(&reporting), Some("донесение"));
let looking = picture(Vec::new(), vec![sortie(0x3000_0001, "outbound", 2, None)], Vec::new());
assert_eq!(battle_phase(&looking), Some("разведка"));
let done = picture(Vec::new(), vec![sortie(0x3000_0001, "done", 0, None)], Vec::new());
assert_eq!(battle_phase(&done), Some("завершение"));
assert_eq!(battle_phase(&picture(Vec::new(), Vec::new(), Vec::new())), None);
assert!(sortie_line(&sortie(0x3000_0001, "reporting", 1, Some(40))).contains("донесение через 2 с"));
}
#[test]
fn an_empty_picture_says_there_was_no_recon() {
let lines = picture_lines(&picture(Vec::new(), Vec::new(), Vec::new()));
assert_eq!(lines.len(), 1);
assert!(lines[0].contains("Разведки не было"), "{lines:?}");
}
// The review shows the marks with their reasons and the drones aimed at them; the ids are the
// synthetic ones, and nothing of the unit's truth (kind, health, exact place) is in the report.
#[test]
fn the_review_lists_marks_reasons_and_recon_aims() {
let m = mark(0x1000_0001, "launcher", None, "coarse", Confidence::Probable, 1000);
let mid = m.id;
let aim = AimReport { drone: 7, unit: mid, intent: "sead", since: 900, switches: 0, confidence: Some(Confidence::Probable), recon: true, priority: Some(m.priority) };
let unit_aim = AimReport { drone: 8, unit: 3, intent: "plan", since: 900, switches: 0, confidence: Some(Confidence::Confirmed), recon: false, priority: None };
let lines = picture_lines(&picture(vec![m], vec![sortie(0x3000_0001, "outbound", 1, None)], vec![aim, unit_aim]));
assert!(lines.iter().any(|l| l.contains(&format!("Отметка {mid}")) && l.contains("пусковая")), "{lines:?}");
assert!(lines.iter().any(|l| l.contains("↳") && l.contains("приоритет")), "{lines:?}");
assert!(lines.iter().any(|l| l.contains("Дрон 7 целится в отметку") && l.contains("подавление ПВО")), "{lines:?}");
// A unit contact's aim is not a recon aim: it is not listed here.
assert!(!lines.iter().any(|l| l.contains("Дрон 8")), "{lines:?}");
// No true unit id leaks: the mark id is synthetic, far above any real unit's.
assert!(mid >= 0x1000_0000);
}
#[test]
fn every_public_name_is_translated() {
for key in ["unknown", "radar", "launcher", "gun", "ew", "support"] {
assert_ne!(category_name(key), key, "{key}");
}
for key in ["multi", "search", "engagement", "height"] {
assert_ne!(role_name(key), key, "{key}");
}
for key in ["flyby", "emission", "jamming", "launch"] {
assert_ne!(source_name(key), key, "{key}");
}
assert_ne!(quality_name("coarse"), "coarse");
assert_ne!(quality_name("refined"), "refined");
}
}
+336 -38
View File
@@ -4,10 +4,12 @@
//! world and a director's camera (a full-screen camera view) follows them —
//! behind the drone, then behind the interceptor or from the side — slowing
//! time round the moment itself.
use crate::sim::catalog::sound;
use crate::film::{self, Film};
use crate::panel::distance;
use crate::sim::Ground;
use crate::sim::record::{EventKind, Recording, STEP, StrikeResult, What};
use crate::sim::record::{Chain, ChainOutcome, ChainStepKind, EventKind, Recording, STEP, StrikeResult, What};
use std::cell::Cell;
use crate::sim::{Class, DroneKind, Out, Sim};
use glam::DVec3;
@@ -122,7 +124,7 @@ fn line(a: (f32, f32), b: (f32, f32), w: f32, color: u32) -> Shape {
let p = |x: f32, y: f32| Point { x, y };
Shape::Quad(QuadShape { corners: (p(a.0 + nx, a.1 + ny), p(b.0 + nx, b.1 + ny), p(b.0 - nx, b.1 - ny), p(a.0 - nx, a.1 - ny)), color })
}
fn clock(ticks: f64) -> String {
pub(crate) fn clock(ticks: f64) -> String {
let s = (ticks / 20.0).max(0.0);
format!("{:02}:{:04.1}", (s / 60.0) as u32, s % 60.0)
}
@@ -185,6 +187,121 @@ pub fn row(rec: &Recording, i: usize) -> String {
format!("{} {what}", clock(e.at as f64))
}
/// A row of the after-action chain list and where a click on it opens a replay.
#[derive(Clone, Debug, PartialEq)]
pub struct ChainRow {
pub text: String,
/// The recorded event to clip (the outcome), when there is one.
pub event: Option<usize>,
/// Otherwise the recording's tick to open the map at (the launch, else the mark).
pub at: f64,
}
/// The short chains of a raid: отметка → передача → захват → пуск → исход, filtered by a
/// battery's id when asked. The list is the recording's measured transitions, not a guess.
pub fn chain_rows(rec: &Recording, battery: Option<u32>) -> Vec<ChainRow> {
chain_page(rec, battery, ChainFilter::All, 0, usize::MAX).rows
}
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum ChainFilter {
#[default]
All,
NoLaunch,
Breach,
}
impl ChainFilter {
pub fn next(self) -> Self {
match self {
Self::All => Self::NoLaunch,
Self::NoLaunch => Self::Breach,
Self::Breach => Self::All,
}
}
pub fn label(self) -> &'static str {
match self {
Self::All => "Все цепочки",
Self::NoLaunch => "Без записи пуска",
Self::Breach => "Прорывы",
}
}
fn matches(self, chain: &Chain) -> bool {
match self {
Self::All => true,
Self::NoLaunch => chain.missed(),
Self::Breach => chain.outcome == ChainOutcome::Hit,
}
}
}
#[derive(Default)]
pub(crate) struct ChainPage {
pub rows: Vec<ChainRow>,
pub total: usize,
pub index: usize,
}
pub(crate) fn chain_page(rec: &Recording, battery: Option<u32>, filter: ChainFilter, page: usize, size: usize) -> ChainPage {
let mut chains = rec.chains(battery);
chains.retain(|chain| filter.matches(chain));
let total = chains.len();
let index = page.min(total.div_ceil(size).saturating_sub(1));
let rows = chains.iter().skip(index * size).take(size).map(|chain| ChainRow {
text: chain_row(rec, chain),
event: chain.outcome_event(),
at: chain_jump_at(chain),
}).collect();
ChainPage { rows, total, index }
}
/// Where a chain opens in a replay when its outcome has no recorded event.
fn chain_jump_at(chain: &Chain) -> f64 {
chain
.step(ChainStepKind::Launch)
.or_else(|| chain.step(ChainStepKind::Mark))
.map_or(0.0, |s| s.at as f64)
}
fn chain_step_name(chain: &Chain, kind: ChainStepKind, own: bool) -> &'static str {
match kind {
ChainStepKind::Mark => "отметка",
ChainStepKind::Handoff if own => "передача (своя РЛС)",
ChainStepKind::Handoff => "передача (сеть)",
ChainStepKind::Lock => "захват",
ChainStepKind::Launch => "пуск",
ChainStepKind::Outcome => match chain.outcome {
ChainOutcome::Destroyed => "сбит",
ChainOutcome::Hit => "прорыв",
ChainOutcome::Lost => "потерян",
ChainOutcome::Unfinished => "без исхода",
},
}
}
/// One chain as a line: the battery, its contact, and the four or five measured steps.
pub fn chain_row(rec: &Recording, chain: &Chain) -> String {
let index = rec.sams.iter().position(|s| s.0 == chain.sam).map(|i| i + 1);
let kind = rec.sam(chain.sam).map_or("ПВО", |(kind, _)| kind.name());
let target = rec
.track(chain.target)
.and_then(|t| match t.what {
What::Drone(kind) => Some(kind.spec().name),
_ => None,
})
.unwrap_or("цель");
let steps: Vec<String> = chain.steps.iter().map(|s| format!("{} {}", chain_step_name(chain, s.kind, s.own), clock(s.at as f64))).collect();
let battery = index.map_or_else(|| format!("№? {kind}"), |i| format!("№{i} {kind}"));
format!(
"{} {battery} → «{target}»: {}{}",
clock(chain.marked_at() as f64),
steps.join(" → "),
if chain.missed() { " · пуск не записан" } else { "" },
)
}
/// How worth watching an event is: the reel takes the best.
pub fn interest(rec: &Recording, i: usize) -> f64 {
let e = &rec.events[i];
@@ -297,6 +414,16 @@ impl Player {
}
}
/// Opens the replay at a recording tick (a chain's launch or mark), holding that frame.
pub fn seek(&mut self, rec: &Recording, at: f64) {
self.t = at.clamp(0.0, rec.len as f64);
self.heard = self.t;
self.shot = (usize::MAX, 0);
self.fade = 0;
self.card = 0;
self.paused = true;
}
/// The wheel: scrubs the map and the full replay, skips clips.
pub fn wheel(&mut self, steps: f32, rec: &Recording) {
let c = if steps > 0.0 { Control::Back } else { Control::Forward };
@@ -523,14 +650,14 @@ impl Player {
/// Sounds as the camera hears them: moved so the player stands where the camera is.
fn sounds(&mut self, rec: &Recording, listener: DVec3, out: &mut Out) {
let heard = |p: DVec3| listener + (p - self.eye);
for e in rec.events.iter().filter(|e| (self.heard..self.t).contains(&(e.at as f64))) {
for (_, e) in rec.events_between(self.heard, self.t) {
let event = match e.kind {
EventKind::Kill { kind, outcome, .. } => crate::sim::outcome::look(kind, outcome).3,
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => ["airdef:blast.air", "airdef:blast.medium", "airdef:blast.big", "airdef:blast.heavy", "airdef:blast.huge"][(power as usize).min(4)],
EventKind::SamLost { .. } => "airdef:blast.big",
EventKind::Split { .. } => "airdef:boom.sonic",
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][(power as usize).min(4)],
EventKind::SamLost { .. } => sound::BLAST_BIG,
EventKind::Split { .. } => sound::BOOM_SONIC,
EventKind::Strike { result: StrikeResult::Halted, .. } => continue,
EventKind::Strike { result, .. } => ["airdef:blast.air", "airdef:blast.medium", "airdef:blast.big", "airdef:blast.heavy", "airdef:blast.huge"][match result {
EventKind::Strike { result, .. } => [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][match result {
StrikeResult::Destroyed => 4,
StrikeResult::Intercepted => 0,
_ => 3,
@@ -539,12 +666,12 @@ impl Player {
let gain = if let EventKind::Kill { kind, outcome, .. } = e.kind { crate::sim::outcome::look(kind, outcome).2 } else { 1.0 };
out.sound(event, heard(e.pos), gain, 1.0);
if let EventKind::Kill { outcome: crate::sim::outcome::Outcome::AirDetonation, .. } = e.kind {
out.sound("airdef:boom.sonic", heard(e.pos), 0.8, 1.2);
out.sound(sound::BOOM_SONIC, heard(e.pos), 0.8, 1.2);
}
}
// New recordings carry the exact launch and ignition sounds and their actual positions.
if let Some(scene) = &rec.scene {
for e in scene.events().iter().filter(|e| (self.heard..self.t).contains(&(e.at as f64))) {
for e in scene.events_between(self.heard, self.t) {
match e.kind {
crate::sim::record::SceneKind::MissileLaunch { sound, pitch, .. } => out.sound(sound, heard(e.pos), 1.0, pitch),
crate::sim::record::SceneKind::MotorIgnition { sound: Some(sound), .. } => out.sound(sound, heard(e.pos), 1.0, 1.0),
@@ -570,7 +697,7 @@ impl Player {
for tr in rec.tracks.iter().filter(|tr| matches!(tr.what, What::StrikeCarrier(_))) {
let at = tr.first as f64 + crate::sim::strike::EJECT_TICKS as f64;
if (self.heard..self.t).contains(&at) && let Some(p) = tr.at(rec.origin, at) {
out.sound("airdef:launch.s400", heard(p), 1.0, 1.0);
out.sound(sound::LAUNCH_S400, heard(p), 1.0, 1.0);
}
}
self.heard = self.t;
@@ -771,9 +898,9 @@ impl Player {
// The full replay follows what comes next: the next event within 6 s, else the drone
// nearest its target.
Mode::Full => rec
.events
.iter()
.position(|e| (self.t - 30.0..self.t + 120.0).contains(&(e.at as f64)))
.events_between(self.t - 30.0, self.t + 120.0)
.next()
.map(|(i, _)| i)
.or(if self.shot.0 != usize::MAX && (rec.events[self.shot.0].at as f64) > self.t - 60.0 { Some(self.shot.0) } else { None }),
Mode::Map | Mode::Film(_) => None,
};
@@ -971,11 +1098,11 @@ impl Player {
What::Missile(..) => (0x90FFD040, 0xFFFFE070),
What::Strike | What::StrikeCarrier(_) => (0x90FFA040, 0xFFFFC060),
};
let upto = ((self.t - tr.first as f64) / STEP as f64).floor();
let upto = ((self.t - tr.first as f64) / tr.step() as f64).floor();
if upto < 0.0 {
continue;
}
let last = ((tr.last() - tr.first) / STEP) as f64;
let last = ((tr.last() - tr.first) / tr.step()) as f64;
let count = upto.min(last) as usize + 1;
if count < 2 {
continue;
@@ -997,29 +1124,13 @@ impl Player {
s.push(fill(prev.0 - 1.5, prev.1 - 1.5, 3.0, 3.0, head));
}
}
// Events so far.
for e in rec.events.iter().filter(|e| (e.at as f64) <= self.t) {
let (x, y) = at(e.pos);
if !inside((x, y)) {
continue;
}
match e.kind {
EventKind::Kill { .. } => {
s.push(line((x - 2.5, y - 2.5), (x + 2.5, y + 2.5), 1.2, 0xFFFFE040));
s.push(line((x + 2.5, y - 2.5), (x - 2.5, y + 2.5), 1.2, 0xFFFFE040));
}
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => {
let r = 2.0 + power as f32;
s.push(fill(x - r, y - r, r * 2.0, r * 2.0, 0xB0FF3020));
}
EventKind::SamLost { .. } => s.push(fill(x - 4.0, y - 4.0, 8.0, 8.0, 0xFF200000)),
EventKind::Split { .. } => s.push(fill(x - 2.0, y - 2.0, 4.0, 4.0, 0xFFFF9020)),
EventKind::Strike { .. } => s.push(fill(x - 3.0, y - 3.0, 6.0, 6.0, 0xFFFFA040)),
}
}
// Events so far, in their order. The header's counts come from the recording's prefix
// index, not from walking the journal again; past the shape cap nothing drawn here
// survives `truncate`.
s.extend(event_marks(rec, self.t, &at, &inside, 1024usize.saturating_sub(s.len())));
// Header, legend, time line.
let kills = rec.events.iter().filter(|e| (e.at as f64) <= self.t && matches!(e.kind, EventKind::Kill { .. })).count();
let hits = rec.events.iter().filter(|e| (e.at as f64) <= self.t && matches!(e.kind, EventKind::Hit { .. })).count();
let kills = rec.kills_until(self.t);
let hits = rec.hits_until(self.t);
let state = if self.paused { "ПАУЗА".to_string() } else { format!("×{}", self.speed) };
s.push(text(format!("КАРТА НАЛЁТА №{} · {} / {} {state} · сбито {kills} · прилётов {hits}", rec.number, clock(self.t), clock(rec.len as f64)), 8.0, 6.0, 0xFF9FE0FF, false));
let legend = "красный: цели · серый: ложные · жёлтый: перехватчики · x сбит · квадрат: прилёт";
@@ -1038,6 +1149,10 @@ impl Player {
s.push(fill(tx, ty, tw, 3.0, 0x60FFFFFF));
let len = rec.len.max(1) as f32;
for e in &rec.events {
// The line is cut at 1024 shapes: past that, a mark would not be kept.
if s.len() >= 1024 {
break;
}
let x = tx + tw * e.at as f32 / len;
let c = match e.kind {
EventKind::Kill { .. } => 0xFFFFE040,
@@ -1055,6 +1170,42 @@ impl Player {
}
}
/// The marks of the events up to `t` on the raid map, in the order they happened: a kill as a
/// cross, a hit as a square, a lost system as a dark square, a split and a strike as dots. Reads
/// the journal by time (`events_until`) and stops at `room` shapes, the rest of the map's cap.
fn event_marks(
rec: &Recording,
t: f64,
at: &impl Fn(DVec3) -> (f32, f32),
inside: &impl Fn((f32, f32)) -> bool,
room: usize,
) -> Vec<Shape> {
let mut s = Vec::new();
for (_, e) in rec.events_until(t) {
if s.len() >= room {
break;
}
let (x, y) = at(e.pos);
if !inside((x, y)) {
continue;
}
match e.kind {
EventKind::Kill { .. } => {
s.push(line((x - 2.5, y - 2.5), (x + 2.5, y + 2.5), 1.2, 0xFFFFE040));
s.push(line((x + 2.5, y - 2.5), (x - 2.5, y + 2.5), 1.2, 0xFFFFE040));
}
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => {
let r = 2.0 + power as f32;
s.push(fill(x - r, y - r, r * 2.0, r * 2.0, 0xB0FF3020));
}
EventKind::SamLost { .. } => s.push(fill(x - 4.0, y - 4.0, 8.0, 8.0, 0xFF200000)),
EventKind::Split { .. } => s.push(fill(x - 2.0, y - 2.0, 4.0, 4.0, 0xFFFF9020)),
EventKind::Strike { .. } => s.push(fill(x - 3.0, y - 3.0, 6.0, 6.0, 0xFFFFA040)),
}
}
s
}
/// The ground the map shows, as [lo x, lo z, hi x, hi z]: everything that
/// flew (not the ballistic falls), with the systems and objects, or round the
/// origin when nothing did.
@@ -1100,6 +1251,69 @@ impl Player {
mod surface_tests {
use super::*;
#[test]
fn a_chain_row_lists_the_measured_steps_and_opens_its_frame() {
use crate::sim::record::{Event, SceneEvent, SceneJournal, SceneKind};
use crate::sim::outcome::Outcome;
use crate::sim::MissileKind;
let mut rec = Recording::blank(300);
rec.sams = vec![(10, crate::sim::SamKind::Pantsir, DVec3::ZERO)];
rec.straight(7, What::Drone(DroneKind::Shahed), 0, 200, DVec3::new(0.0, 80.0, 0.0), DVec3::new(200.0, 80.0, 0.0));
let mut scene = SceneJournal::default();
let at = |at: u32, kind| SceneEvent { at, pos: DVec3::ZERO, kind };
scene.fixture_push(at(20, SceneKind::TrackAcquired { sam: 10, target: 7, ever_own: false }));
scene.fixture_push(at(30, SceneKind::TrackSource { sam: 10, target: 7, ever_own: true }));
scene.fixture_push(at(40, SceneKind::TrackLock { sam: 10, target: 7, locked: true }));
scene.fixture_push(at(50, SceneKind::MissileLaunch { missile: 500, sam: 10, target: 7, kind: MissileKind::M57e6, sound: "airdef:launch.pantsir", pitch: 1.0 }));
rec.scene = Some(scene);
rec.events.push(Event {
at: 90,
pos: DVec3::ZERO,
kind: EventKind::Kill { drone: 7, kind: DroneKind::Shahed, sam: 10, sam_kind: crate::sim::SamKind::Pantsir, sam_index: 0, missile: Some(500), outcome: Outcome::DisabledFalling },
});
let rows = chain_rows(&rec, None);
assert_eq!(rows.len(), 1);
for step in ["отметка", "передача", "захват", "пуск", "сбит"] {
assert!(rows[0].text.contains(step), "the chain row misses {step}: {}", rows[0].text);
}
assert_eq!(rows[0].event, Some(0));
assert!(chain_rows(&rec, Some(10)).len() == 1);
assert!(chain_rows(&rec, Some(11)).is_empty());
// A chain with no recorded outcome opens its launch frame on the map, held still.
let mut player = Player::new(1, Mode::Map, &Sim::new(1));
player.seek(&rec, rows[0].at);
assert!(player.paused);
assert!((player.time() - rows[0].at).abs() < 1e-9);
}
#[test]
fn pages_and_filters_keep_the_original_replay_jump() {
use crate::sim::record::{Event, SceneEvent, SceneJournal, SceneKind};
let mut rec = Recording::blank(300);
let mut scene = SceneJournal::default();
for target in 1..=4 {
scene.fixture_push(SceneEvent {
at: target * 20,
pos: DVec3::ZERO,
kind: SceneKind::TrackAcquired { sam: 10, target, ever_own: true },
});
}
rec.scene = Some(scene);
rec.events.push(Event {
at: 100,
pos: DVec3::ZERO,
kind: EventKind::Hit { drone: 3, kind: DroneKind::Shahed, power: 1, object: Some(0), sam: None },
});
let page = chain_page(&rec, Some(10), ChainFilter::NoLaunch, 1, 2);
assert_eq!((page.index, page.total, page.rows.len()), (1, 4, 2));
assert_eq!((page.rows[0].event, page.rows[0].at), (Some(0), 60.0));
assert_eq!((page.rows[1].event, page.rows[1].at), (None, 80.0));
let page = chain_page(&rec, Some(10), ChainFilter::Breach, 9, 2);
assert_eq!((page.index, page.total, page.rows.len()), (0, 1, 1));
assert_eq!(page.rows[0].event, Some(0));
assert!(chain_page(&rec, Some(11), ChainFilter::All, 1, 2).rows.is_empty());
}
/// A gun standing on the sea floor films from above the water, not from under it.
#[test]
fn the_gun_camera_is_lifted_above_the_water() {
@@ -1208,7 +1422,7 @@ mod engine_tests {
assert_eq!(out.sounds.iter().map(|s| s.0).collect::<Vec<_>>(), vec!["airdef:launch.s400_eject"]);
assert!(out.engines.is_empty());
out = Out::default();
p.t = 16.0;
p.t = 10.0 + crate::sim::strike::EJECT_TICKS as f64 + 1.0;
p.sounds(&rec, DVec3::ZERO, &mut out);
p.engines(&rec, DVec3::ZERO, false, &mut out);
assert_eq!(out.sounds.iter().map(|s| s.0).collect::<Vec<_>>(), vec!["airdef:launch.s400"]);
@@ -1324,6 +1538,90 @@ mod engine_tests {
assert!(host.0.is_empty());
}
// #150: the sounds of a window are exactly the events it holds: the same set, order and
// names after any seek, forward or back, empty or spanning ties.
#[test]
fn event_sounds_are_exactly_the_events_of_the_window_after_any_seek() {
use crate::sim::catalog::sound;
use crate::sim::record::{Event, EventKind};
let mut rec = Recording::blank(1000);
rec.events = [10u32, 10, 25, 40, 40, 40, 75, 130]
.into_iter()
.enumerate()
.map(|(i, at)| Event {
at,
pos: DVec3::new(i as f64, 80.0, 0.0),
kind: EventKind::Crash { drone: 1, kind: DroneKind::Geran3, power: (i % 5) as u32 },
})
.collect();
let names = |lo: f64, hi: f64| -> Vec<&'static str> {
rec.events
.iter()
.filter(|e| (lo..hi).contains(&(e.at as f64)))
.map(|e| match e.kind {
EventKind::Crash { power, .. } => [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][(power as usize).min(4)],
_ => unreachable!(),
})
.collect()
};
let mut p = player(&rec);
let mut out = Out::default();
for &(heard, t) in &[(0.0, 11.0), (10.0, 10.0), (11.0, 25.0), (10.0, 40.0), (25.0, 40.5), (40.0, 41.0), (40.0, 75.0), (75.0, 130.5), (130.0, 0.0), (41.0, 25.0), (10.5, 40.0)] {
out.sounds.clear();
p.heard = heard;
p.t = t;
p.sounds(&rec, DVec3::ZERO, &mut out);
let got: Vec<&'static str> = out.sounds.iter().map(|s| s.0).collect();
assert_eq!(got, names(heard, t), "{heard}..{t}");
}
}
// #150: the map draws every event up to now, in its order, and reads only that far.
#[test]
fn the_map_marks_the_events_up_to_now_in_their_order() {
use crate::sim::record::{Event, EventKind, StrikeResult};
let ev = |at, kind| Event { at, pos: DVec3::new(at as f64, 0.0, 0.0), kind };
let mut rec = Recording::blank(1000);
rec.events = vec![
ev(100, EventKind::Kill { drone: 1, kind: DroneKind::Geran3, sam: 1, sam_kind: crate::sim::SamKind::S400, sam_index: 0, missile: None, outcome: Default::default() }),
ev(200, EventKind::Hit { drone: 1, kind: DroneKind::Geran3, power: 2, object: None, sam: None }),
ev(300, EventKind::Crash { drone: 1, kind: DroneKind::Geran3, power: 1 }),
ev(400, EventKind::SamLost { sam: 1, kind: crate::sim::SamKind::S400, index: 0 }),
ev(500, EventKind::Split { drone: 1 }),
ev(600, EventKind::Strike { site: 1, result: StrikeResult::Stunned }),
ev(900, EventKind::Kill { drone: 1, kind: DroneKind::Geran3, sam: 1, sam_kind: crate::sim::SamKind::S400, sam_index: 0, missile: None, outcome: Default::default() }),
];
rec.close();
let at = |p: DVec3| (p.x as f32, 0.0);
let all = |_: (f32, f32)| true;
let colors = |shapes: Vec<Shape>| shapes
.iter()
.map(|s| match s {
Shape::Fill(f) => f.color,
Shape::Quad(q) => q.color,
_ => 0,
})
.collect::<Vec<_>>();
// The kill's cross, then the hit, the crash, the lost system and the split: the earlier
// events only, in their order.
assert_eq!(
colors(event_marks(&rec, 500.0, &at, &all, usize::MAX)),
vec![0xFFFFE040, 0xFFFFE040, 0xB0FF3020, 0xB0FF3020, 0xFF200000, 0xFFFF9020]
);
assert_eq!(
colors(event_marks(&rec, 600.0, &at, &all, usize::MAX)),
vec![0xFFFFE040, 0xFFFFE040, 0xB0FF3020, 0xB0FF3020, 0xFF200000, 0xFFFF9020, 0xFFFFA040]
);
// The map's shape cap stops the reading; nothing past it would be kept anyway.
assert_eq!(event_marks(&rec, 600.0, &at, &all, 3).len(), 3);
// What lies outside the map is skipped, the rest keeps its order.
let left = |(x, _): (f32, f32)| x < 250.0;
assert_eq!(
colors(event_marks(&rec, 600.0, &at, &left, usize::MAX)),
vec![0xFFFFE040, 0xFFFFE040, 0xB0FF3020]
);
}
#[test]
fn a_fast_replay_is_silent() {
let rec = recording();
+9 -2
View File
@@ -36,9 +36,10 @@ fn names() -> Vec<String> {
impl AirDef {
/// The scenario as text.
fn scenario_text(&self, name: &str, fresh: bool) -> String {
pub(crate) fn scenario_text(&self, name: &str, fresh: bool) -> String {
let mut text = format!("scenario {VERSION}\nname {name}\nworld {}\n", self.state_key());
text += &self.state_text(fresh, false);
// A scenario is a start state: its body is the layout, not the raid a save happened to catch.
text += &self.state_text_with(fresh, false, false);
text += &format!("seed {}\nwave {}\n", self.sim.rng.state(), self.wave.text());
text
}
@@ -66,7 +67,9 @@ impl AirDef {
}
// Everything of the last layout goes: its systems with their jobs and targets, the sky,
// the cook-offs to come; ids are made anew with the new systems.
self.village = None;
self.sim.clear();
self.sim.clear_breakthroughs();
self.sim.sams.clear();
self.sim.targets.clear();
self.sim.target_health.clear();
@@ -76,6 +79,7 @@ impl AirDef {
self.sim.hits = 0;
self.sim.launched = 0;
self.monitor = None;
self.post = crate::post::Post::default();
self.grid_ids.clear();
self.moving = None;
self.pending.clear();
@@ -107,6 +111,9 @@ impl AirDef {
))
}
["load", name, flags @ ..] => {
if self.village_active() {
return Err("Чтобы загрузить другой сценарий, остановите «Оборону деревни»".into());
}
let name = valid(name)?;
let bytes = storage::get(&key(&name)).ok_or(format!("Нет сценария «{name}» (/airdef scenario list)"))?;
self.apply_scenario(&String::from_utf8_lossy(&bytes), flags.contains(&"force"))?;
+39
View File
@@ -54,6 +54,12 @@ pub(super) struct Result {
pub missed: u32,
/// Missiles fired by the heavy systems (S-400, S-500, Patriot).
pub heavy: u32,
/// Interceptors whose fuse ran without a kill; whose life ran out; that lost their target on the way;
/// and that fell below their guidance speed after motor burnout (#120's coast/energy tally).
pub fuse_missed: u32,
pub expired: u32,
pub orphaned: u32,
pub energy_lost: u32,
pub by_kind: Vec<(DroneKind, u32, u32)>,
pub tally: String,
/// Drones that vanished short of their aim without being shot down: kind, where, how far from the aim.
@@ -322,6 +328,10 @@ pub(super) fn fly(s: &Setup) -> Result {
result.crashes = sim.crashes;
result.blocked = sim.tally.blocked;
result.scrubbed = sim.tally.scrubbed;
result.fuse_missed = sim.tally.missed;
result.expired = sim.tally.expired;
result.orphaned = sim.tally.orphaned;
result.energy_lost = sim.tally.energy_lost;
result.leaked = sim.hits;
let mut kinds: HashMap<DroneKind, (u32, u32)> = HashMap::new();
for h in &gone_unkilled {
@@ -514,6 +524,35 @@ fn one_raid() {
}
}
/// Issue #120's wider sampling: battery sizes, launch-range bounds and the target classes of a raid
/// of 36, on the same seeds against the same cluster mix as `one_raid`. Prints CSV rows:
/// `variant,seed,sams,dist,sent,kills,leaked,missiles,heavy,ticks,blocked,scrubbed,crashes,fuse_miss,expired,orphaned,energy_lost,leaks_by_kind`.
/// `SEEDS=1-8 cargo test --release issue_120_grid -- --ignored --nocapture` (SEEDS overrides the seed range).
#[test]
#[ignore]
fn issue_120_grid() {
let seeds = match std::env::var("SEEDS") {
Ok(v) => {
let (a, b) = v.split_once('-').expect("SEEDS is a range like 1-8");
let a: u64 = a.parse().expect("SEEDS start");
let b: u64 = b.parse().expect("SEEDS end");
a..=b
}
Err(_) => 1..=8,
};
for (variant, sams, dist) in [("batt10", 10usize, 500.0), ("batt20", 20, 500.0), ("batt50", 50, 500.0), ("near200", 20, 200.0), ("far1500", 20, 1500.0), ("hills20", 20, 500.0)] {
for seed in seeds.clone() {
let mut s = Setup::new(sams, false, seed);
s.size = 36;
s.dist = dist;
s.hilly = variant == "hills20";
let r = fly(&s);
let kinds = r.by_kind.iter().map(|k| format!("{:?}:{}", k.0, k.1)).collect::<Vec<_>>().join(";");
eprintln!("{variant},{seed},{sams},{dist},{},{},{},{},{},{},{},{},{},{},{},{},{},{}", r.launched, r.kills, r.leaked, r.missiles, r.heavy, r.ticks, r.blocked, r.scrubbed, r.crashes, r.fuse_missed, r.expired, r.orphaned, r.energy_lost, kinds);
}
}
}
/// Far launches over mountains where only a disc round the player is known: who crashes, where and how often.
/// `cargo test --release far_table -- --ignored --nocapture` (DISC=300 sets the radius, 0 for all known).
#[test]
+288 -16
View File
@@ -33,11 +33,199 @@ impl RadarRole {
pub fn from_key(key: &str) -> Option<Self> {
match key { "multi" => Some(Self::Multifunction), "search" => Some(Self::Search), "engagement" => Some(Self::Engagement), "height" => Some(Self::Height), _ => None }
}
pub fn profile(self) -> RadarProfile { RadarProfile::of(self) }
pub fn authorizes(self) -> bool { self.profile().products & RadarProfile::FIRE_BIT != 0 }
}
/// What a measurement is good for. A search plot is a warning, a refined
/// plot fixes a matched contact, and a fire plot is a confirmed measurement
/// a launcher may use. Quality (0..100) is separate from identification:
/// a well-measured track can still be an unknown type (#133).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum Measure {
#[default]
Search,
Refine,
Fire,
}
impl Measure {
pub fn name(self) -> &'static str {
match self { Self::Multifunction => "многофункциональная", Self::Search => "обзорная", Self::Engagement => "сопровождения", Self::Height => "мачтовая" }
match self { Self::Search => "обзор", Self::Refine => "уточнение", Self::Fire => "пригоден для пуска" }
}
pub fn allows_fire(self) -> bool { self == Self::Fire }
}
/// A radar profile: a stable catalog identity over the existing `SamKind::Radar`.
/// The numbers are fictional game settings. The silhouette is shared with the
/// existing radar model: this slice does not add art (a separate owner's zone).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RadarProfile {
/// Stable content ID; old saves only have `RadarRole`, which maps here.
pub id: &'static str,
pub name: &'static str,
/// Allowed measurement products (`SEARCH_BIT`, `REFINE_BIT`, `FIRE_BIT`).
pub products: u8,
/// Ticks for the beam to go round.
pub cycle: u32,
/// Electronic revisit of held contacts between beam passes.
pub agile: bool,
/// Extra antenna height over the unit's spec mast (blocks).
pub mast: f64,
/// Search reach, a factor of the unit's sensor.
pub reach: f64,
/// Local search radius, a factor of the unit's sensor (1: the whole reach).
pub local: f64,
/// Simultaneous refined/fire channels; 0 means only search plots.
pub channels: u8,
/// Measurement error scale (blocks) and its growth per block of range.
pub sigma: f64,
pub spread: f64,
/// Vertical error as a share of the horizontal one.
pub vertical: f64,
pub deployment: &'static str,
/// The limit the profile deliberately keeps, shown in the UI.
pub limit: &'static str,
}
impl RadarProfile {
pub const SEARCH_BIT: u8 = 1;
pub const REFINE_BIT: u8 = 2;
pub const FIRE_BIT: u8 = 4;
pub const MULTI: RadarProfile = RadarProfile {
id: "radar_multi",
name: "многофункциональная",
products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT,
cycle: 140,
agile: false,
mast: 0.0,
reach: 1.0,
local: 0.55,
channels: 3,
sigma: 0.7,
spread: 0.004,
vertical: 0.75,
deployment: "стационарная",
limit: "универсальная: уступает специализированным по циклу, каналам и точности",
};
pub const SEARCH: RadarProfile = RadarProfile {
id: "radar_search",
name: "дальнего обзора",
products: Self::SEARCH_BIT,
cycle: 170,
agile: false,
mast: 0.0,
reach: 1.15,
local: 1.0,
channels: 0,
sigma: 1.0,
spread: 0.008,
vertical: 1.0,
deployment: "крупная стационарная антенна",
limit: "редкие грубые отметки; своего права на пуск не даёт",
};
pub const ENGAGEMENT: RadarProfile = RadarProfile {
id: "radar_track",
name: "сопровождения",
products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT,
cycle: 70,
agile: true,
mast: 0.0,
reach: 0.8,
local: 0.12,
channels: 2,
sigma: 0.35,
spread: 0.002,
vertical: 0.6,
deployment: "мобильная панель",
limit: "локальный поиск и два канала; сеть лишь подсказывает, измеряет станция",
};
pub const HEIGHT: RadarProfile = RadarProfile {
id: "radar_height",
name: "мачта низких высот",
products: Self::SEARCH_BIT | Self::REFINE_BIT,
cycle: 140,
agile: false,
mast: 8.0,
reach: 1.05,
local: 0.15,
channels: 3,
sigma: 0.5,
spread: 0.003,
vertical: 0.35,
deployment: "шасси с поднятой антенной",
limit: "уточняет низкие контакты над рельефом; сквозь препятствия не видит и права на пуск не даёт",
};
/// A weapon's own radar: it measures for its own fire control. Kept out of
/// the separate radar roles so embedded radars keep working as before.
pub const EMBEDDED: RadarProfile = RadarProfile {
id: "embedded",
name: "РЛС комплекса",
products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT,
cycle: 0,
agile: false,
mast: 0.0,
reach: 1.0,
local: 1.0,
channels: 0,
sigma: 0.8,
spread: 0.004,
// The old embedded scan drew its vertical error at half the horizontal one.
vertical: 0.5,
deployment: "встроенная",
limit: "обслуживает только свой комплекс",
};
pub fn of(role: RadarRole) -> Self {
match role {
RadarRole::Multifunction => Self::MULTI,
RadarRole::Search => Self::SEARCH,
RadarRole::Engagement => Self::ENGAGEMENT,
RadarRole::Height => Self::HEIGHT,
}
}
/// Old saves write the role key; new saves write the stable profile ID.
/// Both read here, so a legacy `search` line maps to `radar_search`.
pub fn from_id(id: &str) -> Option<Self> {
match id {
"radar_multi" | "multi" => Some(Self::MULTI),
"radar_search" | "search" => Some(Self::SEARCH),
"radar_track" | "engagement" => Some(Self::ENGAGEMENT),
"radar_height" | "height" => Some(Self::HEIGHT),
_ => None,
}
}
pub fn role(self) -> RadarRole {
match self.id {
"radar_search" => RadarRole::Search,
"radar_track" => RadarRole::Engagement,
"radar_height" => RadarRole::Height,
_ => RadarRole::Multifunction,
}
}
pub fn allows(self, product: Measure) -> bool {
match product {
Measure::Search => self.products & Self::SEARCH_BIT != 0,
Measure::Refine => self.products & Self::REFINE_BIT != 0,
Measure::Fire => self.products & Self::FIRE_BIT != 0,
}
}
pub fn products_text(self) -> &'static str {
match self.products {
p if p == Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT => "обзор, уточнение, пуск",
p if p == Self::SEARCH_BIT | Self::REFINE_BIT => "обзор, уточнение",
p if p == Self::SEARCH_BIT | Self::FIRE_BIT => "обзор, пуск",
_ => "обзор",
}
}
}
impl Sam {
/// The profile this unit measures with. Embedded radars keep their kind's
/// own scan and reach; only the separate radar uses a selectable profile.
pub fn radar_profile(&self) -> RadarProfile {
if self.kind == SamKind::Radar { RadarProfile::of(self.radar_role) } else { RadarProfile::EMBEDDED }
}
pub fn authorizes(self) -> bool { matches!(self, Self::Multifunction | Self::Engagement) }
pub(super) fn reach_factor(self) -> f64 { match self { Self::Multifunction => 1.0, Self::Search => 1.15, Self::Engagement => 0.8, Self::Height => 1.05 } }
}
impl Sam {
@@ -68,15 +256,22 @@ impl Sam {
}
}
/// A snapshot of the relevant configuration, independent of its presentation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BatteryStatus {
Radar { index: usize, role: RadarRole, emitting: bool, operational: bool },
Launcher { index: usize, kind: SamKind, mode: SamMode, linked: bool },
}
impl Sim {
/// Current configurations and whether a launcher has an operational radar link.
pub fn battery_status(&self) -> Vec<String> {
self.sams.iter().enumerate().filter_map(|(i, sam)| {
pub fn battery_status(&self) -> Vec<BatteryStatus> {
self.sams.iter().enumerate().filter_map(|(index, sam)| {
if sam.kind == SamKind::Radar {
Some(format!("№{} РЛС: {}, излучение {}, {}", i + 1, sam.radar_role.name(), if sam.radar_on { "вкл" } else { "выкл" }, if sam.radar_up() && sam.link_range() > 0.0 { "работает" } else { "нет связи или РЛС не работает" }))
Some(BatteryStatus::Radar { index, role: sam.radar_role, emitting: sam.radar_on, operational: sam.radar_up() && sam.link_range() > 0.0 })
} else if matches!(sam.kind, SamKind::S400 | SamKind::S500) {
let linked = self.sams.iter().any(|r| r.kind == SamKind::Radar && r.radar_role.authorizes() && r.radar_up() && r.link_range() > 0.0 && sam.link_range() > 0.0 && r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range()));
Some(format!("№{} {}: {}{}", i + 1, sam.kind.name(), sam.mode.key(), if sam.mode == SamMode::LauncherOnly { if linked { ", РЛС связана" } else { ", нет связанной РЛС сопровождения" } } else { "" }))
Some(BatteryStatus::Launcher { index, kind: sam.kind, mode: sam.mode, linked })
} else { None }
}).collect()
}
@@ -87,8 +282,44 @@ mod tests {
use super::*;
use super::super::{sight, why};
#[test]
fn status_reports_real_radar_links_and_preserves_indices() {
let mut sim = Sim::new(1);
sim.sams.push(Sam::new(1, SamKind::Pantsir, DVec3::ZERO, 0.0));
let mut radar = Sam::new(2, SamKind::Radar, DVec3::ZERO, 0.0);
radar.radar_role = RadarRole::Engagement;
sim.sams.push(radar);
let mut launcher = Sam::new(3, SamKind::S400, DVec3::new(10.0, 0.0, 0.0), 0.0);
launcher.set_mode(SamMode::LauncherOnly);
sim.sams.push(launcher);
assert_eq!(sim.battery_status(), vec![
BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: true, operational: true },
BatteryStatus::Launcher { index: 2, kind: SamKind::S400, mode: SamMode::LauncherOnly, linked: true },
]);
sim.sams[1].radar_on = false;
assert_eq!(sim.battery_status(), vec![
BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: false, operational: false },
BatteryStatus::Launcher { index: 2, kind: SamKind::S400, mode: SamMode::LauncherOnly, linked: false },
]);
}
fn track(now: u64) -> Track {
Track { id: 42, kind: DroneKind::Kh101, pos: DVec3::new(0.0, 100.0, -200.0), vel: DVec3::ZERO, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false }
Track {
id: 42,
class: ClassEst::Firm(Class::Cruise),
pos: DVec3::new(0.0, 100.0, -200.0),
vel: DVec3::ZERO,
tick: now,
own_tick: now,
source: 1,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 400,
hits: 3,
locked: false,
}
}
#[test]
@@ -226,6 +457,24 @@ mod tests {
assert!(sight::reach(&r, DroneKind::Kh101, 5000.0) > base_reach);
}
#[test]
fn profiles_have_stable_ids_and_deliberately_different_limits() {
let search = RadarRole::Search.profile();
let height = RadarRole::Height.profile();
let engagement = RadarRole::Engagement.profile();
let multi = RadarRole::Multifunction.profile();
assert_eq!((search.id, height.id, engagement.id, multi.id), ("radar_search", "radar_height", "radar_track", "radar_multi"));
assert!(!RadarRole::Search.authorizes() && !RadarRole::Height.authorizes() && RadarRole::Engagement.authorizes());
assert_eq!(search.products, RadarProfile::SEARCH_BIT);
assert_eq!(height.products, RadarProfile::SEARCH_BIT | RadarProfile::REFINE_BIT);
assert_ne!(search.cycle, engagement.cycle);
assert!(height.mast > search.mast && height.mast > engagement.mast);
assert!(engagement.channels < multi.channels && height.channels > 0 && search.channels == 0);
assert!(search.local > height.local && height.local > engagement.local);
assert_eq!(RadarProfile::from_id(search.id), Some(search));
assert_eq!(RadarProfile::from_id("search"), Some(search), "legacy role keys map to profiles");
}
#[test]
fn launcher_has_no_own_map_sensor_and_mode_switch_drops_stale_tracks() {
let mut sim = Sim::new(3);
@@ -260,7 +509,7 @@ mod tests {
mod emission_tests {
use super::*;
#[test]
fn silence_accepts_network_without_inventing_own_measurements_and_contacts_age() {
fn silence_discloses_nothing_and_contacts_age_and_channels_still_place_a_unit() {
let mut sim = Sim::new(121);
sim.tick = 20;
let mut source = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0);
@@ -269,29 +518,52 @@ mod emission_tests {
receiver.radar_on = false;
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 70.0, -100.0), DVec3::Z, DVec3::ZERO);
let id = sim.drones[0].id;
source.tracks.push(Track { id, kind: DroneKind::Kh101, pos: sim.drones[0].pos, vel: DVec3::ZERO, tick: 20, own_tick: 20, ttl: 200, hits: 2, locked: false });
source.tracks.push(Track {
id,
class: ClassEst::Firm(Class::Cruise),
pos: sim.drones[0].pos,
vel: DVec3::ZERO,
tick: 20,
own_tick: 20,
source: 1,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 200,
hits: 2,
locked: false,
});
sim.sams.extend([source, receiver]);
let mut ground = Ground::default();
sim.update_sight(&mut ground);
assert_eq!(sim.sams[1].track(id).unwrap().own_tick, 0);
assert_eq!(sim.sams[1].track(id).unwrap().tick, 20);
assert!(!sim.sams[1].radar_up());
assert_eq!(sim.known_units(), vec![(1, DVec3::ZERO)]);
// The emitting source is fixed by the drone; the silent receiver is not.
let picture = sim.picture_of_defences();
assert_eq!(picture.len(), 1);
assert_eq!((picture[0].id, picture[0].at), (1, DVec3::ZERO));
assert_eq!(picture[0].seen, ew::Seen::Emission);
sim.sams[0].radar_on = false;
// The truth moving is not an observation: the contact keeps the observed place.
sim.sams[0].pos = DVec3::new(400.0, 0.0, 0.0);
sim.tick = 40;
sim.update_sight(&mut ground);
assert_eq!(sim.known_units(), vec![(1, DVec3::ZERO)]);
assert_eq!(sim.sams[1].track(id).unwrap().tick, 20);
let picture = sim.picture_of_defences();
assert_eq!(picture.len(), 1);
assert_eq!(picture[0].at, DVec3::ZERO, "a hidden move changed the picture");
// A fresh emission fix re-places it where seen then.
sim.sams[0].radar_on = true;
sim.tick = 60;
sim.update_sight(&mut ground);
assert_eq!(sim.known_units(), vec![(1, DVec3::new(400.0, 0.0, 0.0))]);
assert_eq!(sim.picture_of_defences()[0].at, DVec3::new(400.0, 0.0, 0.0));
sim.sams[0].radar_on = false;
// Other disclosure channels still reveal a silent unit.
sim.intel.revealed.push((2, DVec3::ZERO, 60));
assert!(Sim::enemy_knows(&sim.sams[1], &sim.known_units()));
sim.intel.observe(&sim.sams[1], 60, ew::Seen::Launch);
assert!(sim.known_live(2));
sim.tick = 6060;
assert!(sim.known_units().is_empty());
assert!(sim.picture_of_defences().is_empty(), "an unrefreshed contact never ages out");
}
}
+268
View File
@@ -0,0 +1,268 @@
//! Bounded, observed facts about impacts. This is session history, not save data.
use super::*;
const MAX_ACTIVE: usize = 4096;
const MAX_HITS: usize = 128;
const PAGE_SIZE: usize = 3;
#[derive(Clone, Copy, Default)]
pub(super) struct FlightFacts {
/// False when observation began after the flight began, or after a load.
complete: bool,
pub(super) first: Option<(u64, u32)>,
launches: u32,
}
impl FlightFacts {
pub(super) fn new(complete: bool) -> Self {
Self {
complete,
..Default::default()
}
}
}
struct Hit {
tick: u64,
id: u32,
kind: DroneKind,
pos: DVec3,
object: Option<usize>,
facts: Option<FlightFacts>,
nearby: Vec<BatterySnapshot>,
}
struct BatterySnapshot {
kind: SamKind,
reason: why::BattleReason,
terrain_blocked: bool,
}
#[derive(Default)]
pub(super) struct Breakthroughs {
pub(super) active: HashMap<u32, FlightFacts>,
hits: VecDeque<Hit>,
}
impl Breakthroughs {
pub(super) fn begin(&mut self, id: u32, complete: bool) {
if self.active.len() < MAX_ACTIVE {
self.active.insert(id, FlightFacts::new(complete));
}
}
pub(super) fn bytes(&self) -> usize {
use super::memory::{map_bytes, vec_bytes, vecdeque_bytes};
map_bytes(
self.active.capacity(),
std::mem::size_of::<(u32, FlightFacts)>(),
) + vecdeque_bytes(&self.hits)
+ self
.hits
.iter()
.map(|h| vec_bytes(&h.nearby))
.sum::<usize>()
}
}
impl Sim {
/// Clears the displayed history; observation of flights already in progress continues.
pub fn clear_breakthroughs(&mut self) {
self.breakthroughs.hits.clear();
}
pub(super) fn breakthrough_launch(&mut self, id: u32) {
if let Some(facts) = self.breakthroughs.active.get_mut(&id) {
facts.launches = facts.launches.saturating_add(1);
}
}
pub(super) fn breakthrough_hit(
&mut self,
id: u32,
kind: DroneKind,
pos: DVec3,
object: Option<usize>,
) {
// Only the nearest three armed systems; this runs once per impact, not per tick.
let mut nearest: Vec<_> = self
.sams
.iter()
.enumerate()
.filter(|(_, s)| s.kind.armed())
.map(|(i, s)| (i, s.pos.distance_squared(pos)))
.collect();
nearest.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
let nearby = nearest
.into_iter()
.take(3)
.filter_map(|(i, _)| {
let sam = &self.sams[i];
Some(BatterySnapshot {
kind: sam.kind,
reason: self.battle_reason_at(i, Some(id))?,
terrain_blocked: sam.terrain_verdict(id, self.tick).is_some_and(|v| v != 0),
})
})
.collect();
let hit = Hit {
tick: self.tick,
id,
kind,
pos,
object,
facts: self.breakthroughs.active.get(&id).copied(),
nearby,
};
if self.breakthroughs.hits.len() == MAX_HITS {
self.breakthroughs.hits.pop_front();
}
self.breakthroughs.hits.push_back(hit);
}
pub fn breakthrough_pages(&self) -> usize {
self.breakthroughs.hits.len().div_ceil(PAGE_SIZE)
}
/// Most recent recorded impacts, three per page. Page is zero-based.
pub fn breakthrough_page(&self, page: usize) -> String {
let total = self.breakthroughs.hits.len();
if total == 0 {
return "Прорывов в истории нет".into();
}
let pages = self.breakthrough_pages();
if page >= pages {
return format!("Нет страницы {}. Страниц: {pages}", page.saturating_add(1));
}
let mut lines = vec![format!(
"Прорывы: страница {}/{} (последние {total})",
page + 1,
pages
)];
for hit in self
.breakthroughs
.hits
.iter()
.rev()
.skip(page * PAGE_SIZE)
.take(PAGE_SIZE)
{
let detection = match hit.facts {
Some(f) if f.complete => match f.first {
Some((t, radar)) => format!(
"первое измерение РЛС id {radar}: тик {t}, за {:.1} с до удара",
hit.tick.saturating_sub(t) as f64 / 20.0
),
None => "своих измерений РЛС не было".into(),
},
Some(f) => match f.first {
Some((t, radar)) => format!(
"первое известное измерение РЛС id {radar}: тик {t} (предыдущее неизвестно)"
),
None => "обнаружение до загрузки или начала наблюдения неизвестно".into(),
},
None => "данные обнаружения недоступны".into(),
};
let launches = hit.facts.map_or("пуски неизвестны".to_string(), |f| {
if f.complete {
format!("пусков: {}", f.launches)
} else {
format!("известных пусков: {} (предыдущие неизвестны)", f.launches)
}
});
let object = hit
.object
.map_or_else(String::new, |i| format!(" · объект №{}", i + 1));
lines.push(format!(
"{} №{} · ({:.0}, {:.0}, {:.0}){object}",
hit.kind.spec().name,
hit.id,
hit.pos.x,
hit.pos.y,
hit.pos.z
));
lines.push(format!("{detection} · {launches}"));
if !hit.nearby.is_empty() {
lines.push("Снимок перед ударом · ближайшие комплексы".into());
for battery in &hit.nearby {
let terrain = if battery.terrain_blocked {
" · рельеф перекрывал траекторию"
} else {
""
};
lines.push(format!(
"{} №{} · {}{terrain}",
battery.kind.name(),
battery.reason.sam + 1,
reason_text(&battery.reason),
));
}
}
}
lines.join("\n")
}
}
fn reason_text(reason: &why::BattleReason) -> &'static str {
use why::{BattleBlock as B, BattleKind as K};
match reason.kind {
K::Ready => "готов к пуску",
K::ObserveOnly => "только обзор",
K::AwaitingTrack => "ждёт сопровождения",
K::ChannelsBusy => "каналы заняты",
K::NoAmmo => "нет боезапаса или перезарядка",
K::Blocked => match reason.block {
Some(B::Destroyed) => "уничтожен",
Some(B::Moving) => "на марше",
Some(B::Hold) => "огонь запрещён",
Some(B::NoWeapon) => "нет оружия",
Some(B::NoTarget) => "нет цели",
Some(B::NoTrack) => "нет трассы",
Some(B::OutOfRoles) => "вне ролей",
Some(B::OutOfReach) => "вне дальности",
Some(B::Claimed) => "занята перехватчиками",
Some(B::Doctrine) => "доктрина",
Some(B::Aiming) => "наводится",
Some(B::Preparing) => "подготовка пуска",
Some(B::LauncherDown) => "пусковая отказала",
Some(B::Other) | None => "другая причина",
},
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn impact_history_is_bounded_and_pages_are_safe() {
let mut sim = Sim::new(1);
for id in 0..130 {
sim.tick = id as u64;
sim.breakthrough_hit(id, DroneKind::Geran3, DVec3::ZERO, None);
}
assert_eq!(sim.breakthroughs.hits.len(), MAX_HITS);
assert!(sim.breakthrough_page(0).contains("№129"));
assert!(sim.breakthrough_page(usize::MAX).contains("Нет страницы"));
sim.clear_breakthroughs();
assert!(sim.breakthrough_page(0).contains("истории нет"));
}
#[test]
fn detection_and_launches_distinguish_complete_and_partial_history() {
let mut sim = Sim::new(1);
sim.tick = 20;
sim.breakthroughs.active.insert(1, FlightFacts::new(true));
sim.breakthrough_launch(1);
sim.breakthrough_hit(1, DroneKind::Geran3, DVec3::ZERO, None);
let page = sim.breakthrough_page(0);
assert!(page.contains("измерений РЛС не было"));
assert!(page.contains("пусков: 1"));
sim.breakthroughs.active.insert(2, FlightFacts::new(false));
sim.breakthrough_hit(2, DroneKind::Geran3, DVec3::ZERO, None);
assert!(
sim.breakthrough_page(0)
.contains("до загрузки или начала наблюдения неизвестно")
);
}
}
+131 -32
View File
@@ -3,7 +3,7 @@
//! Balance and rendering remain in `DroneSpec` and `SamSpec`: the catalog
//! refers to those typed definitions instead of copying their values. The
//! first eleven drone entries retain the historical positional wave-save order.
use super::{DroneKind, SamKind};
use super::{battery::RadarProfile, battery::RadarRole, battery::SamMode, DroneKind, SamKind};
#[derive(Clone, Copy, Debug)]
pub struct Aircraft {
@@ -19,6 +19,30 @@ impl Aircraft {
pub fn id(self) -> &'static str { self.kind.spec().key }
}
/// A variant of a complex: a configuration over an existing kind, deployed
/// under its own command/menu id. Not new balance.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct UnitVariant {
/// Existing command/menu key; changing it requires an explicit migration.
pub id: &'static str,
/// Its own placeable remote, so every configuration is a separate item.
pub deploy_item: &'static str,
pub kind: SamKind,
pub mode: SamMode,
pub role: RadarRole,
/// The deploy menu's row.
pub label: &'static str,
/// What the configuration is for (shown in the deploy menu).
pub description: &'static str,
}
impl UnitVariant {
/// The typed radar profile behind a separate radar variant.
pub fn radar_profile(self) -> Option<RadarProfile> {
(self.kind == SamKind::Radar).then(|| RadarProfile::of(self.role))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GroundStrike {
/// Game-only RM48U coordinate-strike profile for S-400. Evidence: official agency report,
@@ -52,37 +76,14 @@ impl Unit {
}
use DroneKind::*;
/// The raid entries come first, in the order stored by existing scenario files.
pub const AIRCRAFT: &[Aircraft] = &[
Aircraft { kind: Gerbera, launch_item: None, raid: true },
Aircraft { kind: Shahed, launch_item: Some("airdef:launch_shahed"), raid: true },
Aircraft { kind: Geran3, launch_item: Some("airdef:launch_geran3"), raid: true },
Aircraft { kind: Lancet, launch_item: Some("airdef:launch_lancet"), raid: true },
Aircraft { kind: Kh101, launch_item: Some("airdef:launch_kh101"), raid: true },
Aircraft { kind: Kalibr, launch_item: Some("airdef:launch_kalibr"), raid: true },
Aircraft { kind: Kh22, launch_item: Some("airdef:launch_kh22"), raid: true },
Aircraft { kind: Zircon, launch_item: Some("airdef:launch_zircon"), raid: true },
Aircraft { kind: Iskander, launch_item: Some("airdef:launch_iskander"), raid: true },
Aircraft { kind: Kinzhal, launch_item: Some("airdef:launch_kinzhal"), raid: true },
Aircraft { kind: Oreshnik, launch_item: Some("airdef:launch_oreshnik"), raid: true },
Aircraft { kind: OreshnikBlock, launch_item: None, raid: false },
Aircraft { kind: OreshnikSub, launch_item: None, raid: false },
];
/// Stable sound IDs shared with the audio resource generator.
pub mod sound {
include!("catalog_sound_ids.rs");
}
macro_rules! units {
($( $kind:ident => $item:literal ),+ $(,)?) => {
pub const UNITS: &[Unit] = &[$(Unit { kind: SamKind::$kind, deploy_item: $item }),+];
};
}
units! {
Patriot => "airdef:deploy_patriot", Gepard => "airdef:deploy_gepard",
Pantsir => "airdef:deploy_pantsir", S400 => "airdef:deploy_s400",
S500 => "airdef:deploy_s500", IrisT => "airdef:deploy_irist",
Nasams => "airdef:deploy_nasams", Buk => "airdef:deploy_buk",
Tor => "airdef:deploy_tor", P1sun => "airdef:deploy_p1sun",
Radar => "airdef:deploy_radar", Depot => "airdef:deploy_depot",
Tzm => "airdef:deploy_tzm", Ew => "airdef:deploy_ew", Light => "airdef:deploy_light",
}
// Generated entries keep the historical raid and unit ordering.
include!("catalog_entries.rs");
include!("unit_variants_generated.rs");
/// Existing positional serialization makes the first entries' order part of the save format.
const fn raid_count() -> usize {
@@ -122,7 +123,7 @@ pub fn unit(kind: SamKind) -> &'static Unit {
/// Inventory ordering is stable for existing remotes, while availability comes from the same entries as raids.
const fn inventory_count() -> usize {
let mut n = UNIT_COUNT + 4;
let mut n = UNIT_COUNT + VARIANTS.len() + 4;
let mut i = 0;
while i < AIRCRAFT.len() {
if AIRCRAFT[i].launch_item.is_some() { n += 1; }
@@ -145,6 +146,10 @@ const fn inventory_items() -> [&'static str; INVENTORY_COUNT] {
out[n] = "airdef:mover";
out[n + 1] = "airdef:flare_gun";
out[n + 2] = "airdef:remover";
// Variant remotes come last: every existing remote keeps its slot.
n += 3;
i = 0;
while i < VARIANTS.len() { out[n] = VARIANTS[i].deploy_item; n += 1; i += 1; }
out
}
pub const INVENTORY: [&str; INVENTORY_COUNT] = inventory_items();
@@ -155,6 +160,18 @@ pub fn launch_item(id: &str) -> Option<DroneKind> {
pub fn deploy_item(id: &str) -> Option<SamKind> {
UNITS.iter().find(|entry| entry.deploy_item == id).map(|entry| entry.kind)
}
/// The configuration a remote item deploys: a unit's ordinary integrated
/// system or a variant's own mode and radar role.
pub fn deploy_item_configuration(id: &str) -> Option<(SamKind, SamMode, RadarRole)> {
if let Some(kind) = deploy_item(id) {
return Some((kind, SamMode::Integrated, RadarRole::Multifunction));
}
VARIANTS.iter().find(|entry| entry.deploy_item == id).map(|entry| (entry.kind, entry.mode, entry.role))
}
pub fn variant(id: &str) -> Option<&'static UnitVariant> {
VARIANTS.iter().find(|variant| variant.id == id)
}
#[cfg(test)]
mod tests {
@@ -194,6 +211,88 @@ mod tests {
}
assert_eq!(kinds, SamKind::ALL.into_iter().collect());
for e in VARIANTS {
assert!(items.insert(e.deploy_item), "duplicate item {}", e.deploy_item);
assert_eq!(e.deploy_item, format!("airdef:deploy_{}", e.id));
}
assert_eq!(&RAID_KINDS[..11], &[Gerbera, Shahed, Geran3, Lancet, Kh101, Kalibr, Kh22, Zircon, Iskander, Kinzhal, Oreshnik]);
}
/// `give` hands out every remote once; the ordinary units keep their historical
/// slots and the variant remotes are appended after them.
#[test]
fn inventory_holds_every_remote_once_and_keeps_existing_slots() {
let unique: HashSet<&str> = INVENTORY.iter().copied().collect();
assert_eq!(unique.len(), INVENTORY.len(), "duplicate inventory item");
let launches = AIRCRAFT.iter().filter(|a| a.launch_item.is_some()).count();
let first_unit = 1 + launches;
for (i, unit) in UNITS.iter().enumerate() {
assert_eq!(INVENTORY[first_unit + i], unit.deploy_item);
assert_eq!(deploy_item_configuration(unit.deploy_item), Some((unit.kind, SamMode::Integrated, RadarRole::Multifunction)));
}
let tail = first_unit + UNITS.len();
assert_eq!(&INVENTORY[tail..tail + 3], &["airdef:mover", "airdef:flare_gun", "airdef:remover"]);
assert_eq!(&INVENTORY[tail + 3..], &VARIANTS.iter().map(|v| v.deploy_item).collect::<Vec<_>>()[..]);
assert_eq!(deploy_item_configuration("airdef:designator"), None);
assert_eq!(deploy_item_configuration("airdef:deploy_radar_track"), Some((SamKind::Radar, SamMode::Integrated, RadarRole::Engagement)));
}
/// A variant is a configuration of an existing kind, one row in the catalog,
/// under an id that stays out of the other identities' keys; the battery-menu
/// order is part of the UI's tested behaviour.
#[test]
fn variants_configure_existing_units_under_free_ids() {
let ids: Vec<&str> = VARIANTS.iter().map(|v| v.id).collect();
assert_eq!(ids, ["s400_launcher", "s500_launcher", "radar_search", "radar_track", "radar_height"]);
for v in VARIANTS {
assert!(UNITS.iter().any(|unit| unit.kind == v.kind), "{} configures an unknown kind", v.id);
assert!(SamKind::from_key(v.id).is_none(), "{} shadows a unit kind", v.id);
assert!(!INVENTORY.contains(&format!("airdef:{}", v.id).as_str()), "{} doubles an item", v.id);
assert_eq!(v.deploy_item, format!("airdef:deploy_{}", v.id));
assert!(INVENTORY.contains(&v.deploy_item), "{} has no remote in the inventory", v.id);
assert_eq!(deploy_item_configuration(v.deploy_item), Some((v.kind, v.mode, v.role)));
assert!(!v.label.is_empty() && !v.description.is_empty());
assert_eq!(variant(v.id).map(|u| (u.kind, u.mode, u.role)), Some((v.kind, v.mode, v.role)));
if v.kind == SamKind::Radar {
let profile = v.radar_profile().expect("a radar variant has a profile");
assert_eq!(profile.id, v.id, "the stable profile ID is the variant ID");
assert_eq!(profile.role(), v.role);
assert!(profile.channels <= 3 && profile.cycle > 0);
} else {
assert!(v.radar_profile().is_none());
}
}
let launcher = variant("s400_launcher").unwrap();
assert_eq!((launcher.kind, launcher.mode, launcher.role), (SamKind::S400, SamMode::LauncherOnly, RadarRole::Multifunction));
assert_eq!(VARIANTS[4].id, "radar_height");
assert!(variant("miss").is_none() && variant("s400").is_none());
}
/// The catalog is the only copy of the numbers: a kind without a row, or a row under
/// another kind, would be a silent balance change.
#[test]
fn generated_specs_cover_every_kind_and_keep_their_keys() {
let mut drones = HashSet::new();
let mut drone_keys = HashSet::new();
for (kind, key) in super::super::DRONE_SPEC_KEYS {
assert_eq!(kind.spec().key, key, "profile/key mismatch for {kind:?}");
assert!(drones.insert(kind), "duplicate drone profile {kind:?}");
assert!(drone_keys.insert(key), "duplicate drone save key {key}");
assert!(kind.spec().rcs > 0.0 && kind.spec().launch_sound.starts_with("airdef:"));
}
assert_eq!(drones, DroneKind::ALL.into_iter().collect());
let mut missiles = HashSet::new();
for (kind, model) in super::super::MISSILE_SPEC_MODELS {
assert_eq!(kind.spec().model, model, "profile/model mismatch for {kind:?}");
assert!(missiles.insert(kind), "duplicate missile profile {kind:?}");
}
let mut units = HashSet::new();
let mut unit_keys = HashSet::new();
for (kind, key) in super::super::units::UNIT_SPEC_KEYS {
assert_eq!(kind.spec().key, key, "profile/key mismatch for {kind:?}");
assert!(units.insert(kind), "duplicate unit profile {kind:?}");
assert!(unit_keys.insert(key), "duplicate unit save key {key}");
}
assert_eq!(units, SamKind::ALL.into_iter().collect());
}
}
+35
View File
@@ -0,0 +1,35 @@
// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.
pub const AIRCRAFT: &[Aircraft] = &[
Aircraft { kind: Gerbera, launch_item: None, raid: true },
Aircraft { kind: Shahed, launch_item: Some("airdef:launch_shahed"), raid: true },
Aircraft { kind: Geran3, launch_item: Some("airdef:launch_geran3"), raid: true },
Aircraft { kind: Lancet, launch_item: Some("airdef:launch_lancet"), raid: true },
Aircraft { kind: Kh101, launch_item: Some("airdef:launch_kh101"), raid: true },
Aircraft { kind: Kalibr, launch_item: Some("airdef:launch_kalibr"), raid: true },
Aircraft { kind: Kh22, launch_item: Some("airdef:launch_kh22"), raid: true },
Aircraft { kind: Zircon, launch_item: Some("airdef:launch_zircon"), raid: true },
Aircraft { kind: Iskander, launch_item: Some("airdef:launch_iskander"), raid: true },
Aircraft { kind: Kinzhal, launch_item: Some("airdef:launch_kinzhal"), raid: true },
Aircraft { kind: Oreshnik, launch_item: Some("airdef:launch_oreshnik"), raid: true },
Aircraft { kind: OreshnikBlock, launch_item: None, raid: false },
Aircraft { kind: OreshnikSub, launch_item: None, raid: false },
];
pub const UNITS: &[Unit] = &[
Unit { kind: SamKind::Patriot, deploy_item: "airdef:deploy_patriot" },
Unit { kind: SamKind::Gepard, deploy_item: "airdef:deploy_gepard" },
Unit { kind: SamKind::Pantsir, deploy_item: "airdef:deploy_pantsir" },
Unit { kind: SamKind::S400, deploy_item: "airdef:deploy_s400" },
Unit { kind: SamKind::S500, deploy_item: "airdef:deploy_s500" },
Unit { kind: SamKind::IrisT, deploy_item: "airdef:deploy_irist" },
Unit { kind: SamKind::Nasams, deploy_item: "airdef:deploy_nasams" },
Unit { kind: SamKind::Buk, deploy_item: "airdef:deploy_buk" },
Unit { kind: SamKind::Tor, deploy_item: "airdef:deploy_tor" },
Unit { kind: SamKind::P1sun, deploy_item: "airdef:deploy_p1sun" },
Unit { kind: SamKind::Radar, deploy_item: "airdef:deploy_radar" },
Unit { kind: SamKind::Depot, deploy_item: "airdef:deploy_depot" },
Unit { kind: SamKind::Tzm, deploy_item: "airdef:deploy_tzm" },
Unit { kind: SamKind::Ew, deploy_item: "airdef:deploy_ew" },
Unit { kind: SamKind::Light, deploy_item: "airdef:deploy_light" },
Unit { kind: SamKind::Optical, deploy_item: "airdef:deploy_optical" },
];
+36
View File
@@ -0,0 +1,36 @@
// Generated by tools/gen_catalog.py from catalog/sounds.json. Do not edit.
pub const DRONE_SHAHED: &str = "airdef:drone.shahed";
pub const DRONE_GERAN3: &str = "airdef:drone.geran3";
pub const DRONE_LANCET: &str = "airdef:drone.lancet";
pub const DRONE_CRUISE: &str = "airdef:drone.cruise";
pub const DRONE_ROCKET: &str = "airdef:drone.rocket";
pub const MISSILE_FLIGHT: &str = "airdef:missile.flight";
pub const DRONE_BALLISTIC: &str = "airdef:drone.ballistic";
pub const BOOM_SONIC: &str = "airdef:boom.sonic";
pub const BOOM_SONIC_FAR: &str = "airdef:boom.sonic_far";
pub const LAUNCH_PATRIOT: &str = "airdef:launch.patriot";
pub const LAUNCH_PATRIOT_FAR: &str = "airdef:launch.patriot_far";
pub const LAUNCH_S400_EJECT: &str = "airdef:launch.s400_eject";
pub const LAUNCH_S400_EJECT_FAR: &str = "airdef:launch.s400_eject_far";
pub const LAUNCH_S400: &str = "airdef:launch.s400";
pub const LAUNCH_S400_FAR: &str = "airdef:launch.s400_far";
pub const LAUNCH_S500_EJECT: &str = "airdef:launch.s500_eject";
pub const LAUNCH_S500_EJECT_FAR: &str = "airdef:launch.s500_eject_far";
pub const LAUNCH_S500: &str = "airdef:launch.s500";
pub const LAUNCH_S500_FAR: &str = "airdef:launch.s500_far";
pub const LAUNCH_PANTSIR: &str = "airdef:launch.pantsir";
pub const LAUNCH_PANTSIR_FAR: &str = "airdef:launch.pantsir_far";
pub const GUN_GEPARD: &str = "airdef:gun.gepard";
pub const GUN_GEPARD_FAR: &str = "airdef:gun.gepard_far";
pub const GUN_PANTSIR: &str = "airdef:gun.pantsir";
pub const GUN_PANTSIR_FAR: &str = "airdef:gun.pantsir_far";
pub const BLAST_BIG: &str = "airdef:blast.big";
pub const BLAST_BIG_FAR: &str = "airdef:blast.big_far";
pub const BLAST_HEAVY: &str = "airdef:blast.heavy";
pub const BLAST_HEAVY_FAR: &str = "airdef:blast.heavy_far";
pub const BLAST_HUGE: &str = "airdef:blast.huge";
pub const BLAST_HUGE_FAR: &str = "airdef:blast.huge_far";
pub const BLAST_MEDIUM: &str = "airdef:blast.medium";
pub const BLAST_MEDIUM_FAR: &str = "airdef:blast.medium_far";
pub const BLAST_AIR: &str = "airdef:blast.air";
pub const BLAST_AIR_FAR: &str = "airdef:blast.air_far";
+8 -30
View File
@@ -54,6 +54,10 @@ impl Part {
Part::Comms => "Св",
}
}
/// The short label as this kind of unit reads it: a passive post has optics, not a radar.
pub fn short_on(self, kind: SamKind) -> &'static str {
if self == Part::Sensor && kind == SamKind::Optical { "Опт" } else { self.short() }
}
fn index(self) -> usize {
self as usize
}
@@ -61,7 +65,8 @@ impl Part {
pub fn on(self, kind: SamKind) -> bool {
let spec = kind.spec();
match self {
Part::Sensor => spec.sensor > 0.0,
// A passive optical post has a sensor without radar reach: it can be damaged and blinded too.
Part::Sensor => spec.sensor > 0.0 || kind == SamKind::Optical,
Part::Mount => kind.armed() && kind != SamKind::Light && (spec.missile.is_some() || spec.gun.is_some()),
Part::Launcher => spec.missile.is_some(),
Part::Gun => spec.gun.is_some(),
@@ -112,30 +117,6 @@ impl Comps {
pub fn whole(&self) -> bool {
self.0.iter().all(|&v| v >= 1.0)
}
/// Parts of this kind that are not whole, as "РЛС 40%, ходовая отказ".
pub fn describe(&self, kind: SamKind) -> String {
Part::ALL
.iter()
.filter(|p| p.on(kind) && self.get(**p) < 1.0)
.map(|p| match self.state(*p) {
PartState::Failed => format!("{} отказ", p.short()),
_ => format!("{} {:.0}%", p.short(), self.get(*p) * 100.0),
})
.collect::<Vec<_>>()
.join(", ")
}
/// The weakest part alone, for a one-line status (the full list is on the monitor).
pub fn worst(&self, kind: SamKind) -> String {
Part::ALL
.iter()
.filter(|p| p.on(kind) && self.get(**p) < 1.0)
.min_by(|a, b| self.get(**a).total_cmp(&self.get(**b)))
.map(|p| match self.state(*p) {
PartState::Failed => format!("{} отказ", p.short()),
_ => format!("{} {:.0}%", p.short(), self.get(*p) * 100.0),
})
.unwrap_or_default()
}
}
/// Health points an object loses at the centre of a blast.
@@ -443,9 +424,6 @@ impl Sam {
pub fn part_state(&self, p: Part) -> PartState {
if p.on(self.kind) { self.comps.state(p) } else { PartState::Ok }
}
pub fn parts_text(&self) -> String {
self.comps.describe(self.kind)
}
/// The aiming drive's share of its speed: a failed one doesn't turn at all.
pub(super) fn drive_fit(&self) -> f64 {
let h = self.part(Part::Mount);
@@ -461,7 +439,7 @@ impl Sam {
0.5 + 0.5 * self.part(Part::Gun)
}
/// Its launcher's cells still good: a damaged one holds fewer missiles.
pub(super) fn cells(&self) -> u32 {
pub fn cells(&self) -> u32 {
let Some(load) = &self.kind.spec().missile else { return 0 };
let h = self.part(Part::Launcher);
if h <= 0.0 { 0 } else { ((load.magazine as f64 * (0.4 + 0.6 * h)).ceil() as u32).clamp(1, load.magazine) }
@@ -475,7 +453,7 @@ impl Sam {
}
}
/// Ticks a reload takes: longer with a damaged launcher.
pub(super) fn reload_time(&self) -> u32 {
pub fn reload_time(&self) -> u32 {
let r = self.kind.spec().reload.max(1);
(r as f64 * (1.0 + 1.5 * (1.0 - self.part(Part::Launcher)))).round() as u32
}
+260
View File
@@ -0,0 +1,260 @@
//! Recorded choices at the firing checks, on the same clock as the replay.
use super::{ClassEst, Sam, battery::Measure, memory, why};
use std::collections::{HashMap, VecDeque};
const MAX_ENTRIES: usize = 4096;
const MAX_STREAMS: usize = 1024;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Channel {
Unit,
Gun,
Launcher,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Block {
Hold,
Moving,
Reload,
Empty,
NoSelection,
WaitingForTerrain,
Terrain,
Aim,
Opening,
BusyWithGroundShot,
Cooldown,
GunFault,
LauncherFault,
NoLock,
Range,
}
impl Block {
pub(super) fn gun(bits: u8) -> Self {
if bits & why::RELOADING != 0 {
Self::Reload
} else if bits & why::NO_ROUNDS != 0 {
Self::Empty
} else if bits & why::JAMMED != 0 {
Self::GunFault
} else if bits & why::NO_LOCK != 0 {
Self::NoLock
} else if bits & (why::NOT_AIMED | why::AIM_ERROR) != 0 {
Self::Aim
} else if bits & why::OUT_OF_RANGE != 0 {
Self::Range
} else {
Self::Cooldown
}
}
pub(super) fn launcher(bits: u8) -> Self {
if bits & why::RELOADING != 0 {
Self::Reload
} else if bits & why::NO_ROUNDS != 0 {
Self::Empty
} else if bits & why::LAUNCHER_DOWN != 0 {
Self::LauncherFault
} else {
Self::Cooldown
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Outcome {
Held(Block),
Burst,
BurstMissed,
BurstHit,
Launched(u32),
Intercepted(u32),
InterceptorMissed(u32),
InterceptorEnded(u32),
}
/// What the unit itself measured or received, with IDs fixed at recording time.
#[derive(Clone, Copy, Debug)]
pub struct Mark {
pub source: u32,
pub age: u16,
pub own: bool,
pub quality: u8,
pub product: Measure,
pub class: ClassEst,
}
#[derive(Clone, Copy, Debug)]
pub struct Entry {
pub at: u32,
pub unit: u32,
pub target: Option<u32>,
pub channel: Channel,
pub outcome: Outcome,
pub mark: Option<Mark>,
}
#[derive(Default)]
pub struct History {
entries: VecDeque<Entry>,
first: u64,
last: HashMap<(u32, Channel), (Option<u32>, Outcome)>,
truncated: bool,
}
impl History {
pub fn first_index(&self) -> u64 { self.first }
pub fn entries(&self) -> impl DoubleEndedIterator<Item = &Entry> {
self.entries.iter()
}
pub fn truncated(&self) -> bool {
self.truncated
}
pub(super) fn resume(&mut self, unit: u32, channel: Channel) {
self.last.remove(&(unit, channel));
}
pub(super) fn note(
&mut self,
at: u32,
now: u64,
sam: &Sam,
channel: Channel,
target: Option<u32>,
outcome: Outcome,
) {
let key = (sam.id, channel);
if matches!(outcome, Outcome::Held(_)) {
if self.last.get(&key) == Some(&(target, outcome)) {
return;
}
if self.last.len() == MAX_STREAMS && !self.last.contains_key(&key) {
self.truncated = true;
return;
}
self.last.insert(key, (target, outcome));
} else {
self.last.remove(&key);
}
let mark = target.and_then(|id| sam.track(id)).map(|track| Mark {
source: track.source,
age: track.age(now).min(u64::from(u16::MAX)) as u16,
own: track.source == sam.id,
quality: track.quality,
product: track.product,
class: track.class,
});
// A refusal is for a public track, or the absence of a selected track.
// An actual shot still identifies the track it was fired at.
let target = if matches!(outcome, Outcome::Held(_)) && mark.is_none() {
None
} else {
target
};
self.push(Entry {
at,
unit: sam.id,
target,
channel,
outcome,
mark,
});
}
pub(super) fn outcome(
&mut self,
at: u32,
unit: u32,
target: u32,
channel: Channel,
outcome: Outcome,
) {
self.push(Entry {
at,
unit,
target: Some(target),
channel,
outcome,
mark: None,
});
}
fn push(&mut self, entry: Entry) {
if self.entries.len() == MAX_ENTRIES {
self.entries.pop_front();
self.first += 1;
self.truncated = true;
}
self.entries.push_back(entry);
}
pub(super) fn close(&mut self) {
self.last = HashMap::new();
}
pub(super) fn bytes(&self) -> usize {
memory::vecdeque_bytes(&self.entries)
+ memory::map_bytes(
self.last.capacity(),
size_of::<((u32, Channel), (Option<u32>, Outcome))>(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::SamKind;
use glam::DVec3;
#[test]
fn deduplicates_continuous_refusals_and_preserves_a_known_miss() {
let sam = Sam::new(16, SamKind::S400, DVec3::ZERO, 0.0);
let mut history = History::default();
for at in 0..100 {
history.note(
at,
u64::from(at),
&sam,
Channel::Unit,
None,
Outcome::Held(Block::Hold),
);
}
history.note(
100,
100,
&sam,
Channel::Launcher,
Some(93),
Outcome::Launched(94),
);
history.outcome(
130,
sam.id,
93,
Channel::Launcher,
Outcome::InterceptorMissed(94),
);
let entries: Vec<_> = history.entries().collect();
assert_eq!(entries.len(), 3);
assert_eq!(entries[0].at, 0);
assert_eq!(entries[1].outcome, Outcome::Launched(94));
assert_eq!(entries[2].outcome, Outcome::InterceptorMissed(94));
}
#[test]
fn a_full_journal_keeps_recent_entries_and_marks_the_gap() {
let mut history = History::default();
for at in 0..MAX_ENTRIES as u32 + 3 {
history.outcome(at, 16, 93, Channel::Gun, Outcome::BurstHit);
}
assert!(history.truncated());
assert_eq!(history.entries().count(), MAX_ENTRIES);
assert_eq!(history.entries().next().unwrap().at, 3);
}
}
+32 -11
View File
@@ -85,6 +85,11 @@ impl Doctrine {
if near <= slack {
return true;
}
// One blip carries no measured course (#133): nothing says the contact passes the
// object by, so it is not ruled out as a threat on a velocity that is not there.
if track.hits <= 1 {
return true;
}
let (vx, vz) = (track.vel.x, track.vel.z);
let speed = vx.hypot(vz);
// Closing, and the line of flight passes the object within the slack.
@@ -97,23 +102,24 @@ impl Doctrine {
(if self.in_sector(pos, track.est(now)) { 0 } else { OUT_SECTOR }) | (if self.guards.is_empty() || self.threatens(track, now).is_some() { 0 } else { NO_THREAT })
}
/// What matters enough to spend the reserve: a ballistic missile, or anything about to hit.
pub fn matters(d: &Drone) -> bool {
d.kind.spec().class == Class::Ballistic || why::arrival(d) < why::URGENT
/// What matters enough to spend the reserve: a ballistic missile (as the track's estimate
/// classes it, an unidentified contact does not count), or anything about to hit.
pub fn matters(d: &Drone, class: ClassEst) -> bool {
class.class() == Some(Class::Ballistic) || why::arrival(d) < why::URGENT
}
/// The reserve holds the launch back: the magazine is at the reserve and the target doesn't matter.
pub fn reserve_blocks(&self, missiles: u32, d: &Drone) -> u8 {
if self.reserve > 0 && missiles <= self.reserve && !Self::matters(d) { RESERVE } else { 0 }
pub fn reserve_blocks(&self, missiles: u32, d: &Drone, class: ClassEst) -> u8 {
if self.reserve > 0 && missiles <= self.reserve && !Self::matters(d, class) { RESERVE } else { 0 }
}
/// Interceptors this doctrine asks for on `d`: `why::needed` by default, the base only when economical, one more when heavy.
pub fn needed(&self, d: &Drone) -> u32 {
let base = if d.kind.spec().class == Class::Ballistic { 2 } else { 1 };
pub fn needed(&self, d: &Drone, class: ClassEst) -> u32 {
let base = if class.class() == Some(Class::Ballistic) { 2 } else { 1 };
match self.salvo {
Salvo::Economy => base,
Salvo::Normal => why::needed(d),
Salvo::Heavy => why::needed(d) + 1,
Salvo::Normal => why::needed(d, class),
Salvo::Heavy => why::needed(d, class) + 1,
}
}
@@ -162,7 +168,22 @@ mod tests {
use super::*;
fn track(pos: DVec3, vel: DVec3) -> Track {
Track { id: 1, kind: DroneKind::Shahed, pos, vel, tick: 0, own_tick: 0, ttl: 100, hits: 3, locked: false }
Track {
id: 1,
class: ClassEst::Unknown,
pos,
vel,
tick: 0,
own_tick: 0,
source: 0,
product: battery::Measure::Search,
quality: 40,
own_product: battery::Measure::Search,
own_quality: 0,
ttl: 100,
hits: 3,
locked: false,
}
}
#[test]
@@ -219,7 +240,7 @@ mod tests {
}
// The explanation while the target is in the sky: all the lines it gave then.
if sim.tick % 10 == 0 {
lines.extend(sim.why(0).into_iter().map(|c| c.text));
lines.extend(sim.why(0).into_iter().map(|c| c.legacy_text().to_owned()));
}
}
(sim.sams[0].fired, first, lines)
File diff suppressed because it is too large Load Diff
+2107 -85
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -67,6 +67,13 @@ pub fn level(age: f64, life: f64) -> (f32, f32) {
}
impl Fires {
/// What the fires hold, about (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::vec_bytes;
vec_bytes(&self.list)
+ self.list.iter().map(|f| vec_bytes(&f.blocks)).sum::<usize>()
+ self.cleanup.iter().map(|s| s.capacity()).sum::<usize>()
}
/// Fires burning now.
pub fn len(&self) -> usize {
self.list.len()
+244 -66
View File
@@ -1,25 +1,7 @@
//! Logistics: once a depot stands, magazines are no longer refilled from
//! nowhere. A system out of missiles waits; one within reach of a depot
//! reloads from its stock; the reload trucks fill up at a depot and drive
//! reloads to the systems that wait, nearest first, and back.
//! Empty magazines are replenished from finite depot stock, either directly or via a truck.
use super::*;
/// How near a depot a system reloads straight from it.
const DEPOT_REACH: f64 = 60.0;
/// How near a truck must come to hand a reload over, or to load up at a depot.
const HANDOVER: f64 = 10.0;
/// What a truck carries.
const TRUCK_LOAD: u32 = 2;
const STOCK_LIMIT: u32 = 1_000_000;
impl Sim {
/// Whether ammunition is counted: a depot was set up (without one, magazines refill as
/// before). A destroyed depot still counts: losing the last one leaves the systems short,
/// not supplied from nowhere again.
pub fn logistics(&self) -> bool {
self.sams.iter().any(|s| s.kind == SamKind::Depot)
}
/// Prepare one explicitly typed round at a nearby living depot. Any displaced air round is retained there.
pub fn load_ground_round(&mut self, i: usize) -> Result<String, String> {
let s = self.sams.get(i).ok_or("Нет такого комплекса")?;
@@ -35,6 +17,9 @@ impl Sim {
let Some(depot) = depot else {
if s.ground_request { return Err("Заявка RM48U уже ожидает ТЗМ".into()); }
if !self.sams.iter().any(|d| d.alive() && ((d.kind == SamKind::Depot && d.ground_stock > 0) || (d.kind == SamKind::Tzm && d.ground_stock > 0))) {
if let Some((j, _)) = self.sams.iter().enumerate().find(|(_, d)| d.kind == SamKind::Depot && d.alive() && d.pos.distance(s.pos) < DEPOT_REACH) {
return Err(format!("Склад №{} рядом, но RM48U: 0. Задайте запас: /airdef ground-stock {} <количество>", j + 1, j + 1));
}
return Err("Нет живого склада с RM48U рядом (60 блоков)".into());
}
if !self.sams.iter().any(|t| t.kind == SamKind::Tzm && t.alive()) { return Err("Для доставки RM48U нужна исправная ТЗМ".into()); }
@@ -89,12 +74,6 @@ impl Sim {
/// Reloads from depots near the systems, and the trucks' rounds.
pub(super) fn step_supply(&mut self, out: &mut Out) {
if !self.logistics() {
for s in &mut self.sams {
s.empty = false;
}
return;
}
let now = self.tick;
// Systems by a depot reload from it.
for i in 0..self.sams.len() {
@@ -124,41 +103,58 @@ impl Sim {
let at = truck.pos;
let truck_id = truck.id;
// A return is picked up physically; its cargo remains marked until a depot accepts it.
// The return keeps its priority only while it can actually proceed (#128): a carrier
// holding a reserved round needs a depot with room in reach, an empty one a system
// ready to hand a round over (whole, deployed, not claimed by another truck, a
// reachable route). A return that is merely claimed but impossible used to clear the
// job and stop the truck, starving independent supply requests; the claim now stays
// untouched and only real RM48U demand pulls the truck away from its watch.
let return_cargo = truck.return_cargo && truck.ground_stock > 0;
let can_pick = truck.ground_stock == 0 && truck.air_48n6_stock < TRUCK_LOAD;
let return_work = truck.return_cargo || (can_pick && self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_return));
if return_work {
let taken: Vec<u32> = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect();
let target = if truck.return_cargo {
self.sams.iter().filter(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock < STOCK_LIMIT && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
} else {
self.sams.iter().filter(|s| s.kind == SamKind::S400 && s.alive() && s.ground_return && s.ground_rounds > 0 && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
}.map(|s| (s.id, s.pos));
self.sams[t].job = target.map(|x| x.0);
if let Some((id, to)) = target {
if at.distance(to) > HANDOVER {
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
self.order_move_near(t, to + side, 3.5);
} else if let Some(j) = self.sams.iter().position(|s| s.id == id) {
if self.sams[t].return_cargo {
self.sams[j].ground_stock += 1;
self.sams[t].ground_stock -= 1;
self.sams[t].return_cargo = false;
} else {
self.sams[j].ground_rounds -= 1;
self.sams[j].ground_return = false;
self.sams[t].ground_stock += 1;
self.sams[t].return_cargo = true;
if self.sams[t].air_48n6_stock > 0 && self.sams[j].missiles + self.sams[j].ground_rounds < self.sams[j].cells() {
self.sams[t].air_48n6_stock -= 1;
self.sams[j].missiles += 1;
}
let claim_pending = return_cargo || (can_pick && self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_return));
let taken: Vec<u32> = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect();
let target = if return_cargo {
self.sams.iter().filter(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock < STOCK_LIMIT && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
} else if can_pick {
self.sams.iter().filter(|s| s.kind == SamKind::S400 && s.alive() && s.ground_return && s.ground_rounds > 0 && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
} else {
None
}.map(|s| (s.id, s.pos));
if let Some((id, to)) = target {
self.sams[t].job = Some(id);
if at.distance(to) > HANDOVER {
self.order_move_near(t, to, HANDOVER - 0.75);
} else if let Some(j) = self.sams.iter().position(|s| s.id == id) {
if self.sams[t].return_cargo {
self.sams[j].ground_stock += 1;
self.sams[t].ground_stock -= 1;
self.sams[t].return_cargo = false;
} else {
self.sams[j].ground_rounds -= 1;
self.sams[j].ground_return = false;
self.sams[t].ground_stock += 1;
self.sams[t].return_cargo = true;
if self.sams[t].air_48n6_stock > 0 && self.sams[j].missiles + self.sams[j].ground_rounds < self.sams[j].cells() {
self.sams[t].air_48n6_stock -= 1;
self.sams[j].missiles += 1;
}
self.sams[t].job = None;
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
}
self.sams[t].job = None;
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
}
continue;
}
if claim_pending {
// The impossible return still outranks a mere stock run: without RM48U demand
// the truck holds its watch (and drops a stale job) exactly as before.
let supply_demand = (self.sams[t].ground_stock > 0 && self.sams.iter().any(|s| s.alive() && s.ground_request))
|| (self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_request)
&& self.sams.iter().any(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock > 0));
if !supply_demand {
self.sams[t].job = None;
continue;
}
}
// Typed strike cargo takes precedence over generic reloads. Jobs are reconstructed
// after loading a save; the request and physical cargo survive independently.
let typed_work = truck.ground_stock > 0 || truck.air_48n6_stock > 0 ||
@@ -181,6 +177,8 @@ impl Sim {
let take = self.sams[t].ground_stock.min(STOCK_LIMIT - self.sams[j].ground_stock);
self.sams[j].ground_stock += take;
self.sams[t].ground_stock -= take;
// The last reserved round left the truck: nothing marks as return cargo any more.
if self.sams[t].ground_stock == 0 { self.sams[t].return_cargo = false; }
}
if self.sams[t].ground_stock == 0 && self.sams[j].ground_stock > 0 && self.sams[t].air_48n6_stock == 0 && self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_request) {
self.sams[j].ground_stock -= 1;
@@ -193,14 +191,16 @@ impl Sim {
if self.sams[j].ground_rounds >= self.sams[j].cells() && self.sams[j].kind.spec().gun.is_none() { self.sams[j].empty = false; }
self.sams[j].ground_request = false;
self.sams[t].ground_stock -= 1;
// A round reserved for return redirected to a waiting request is no
// longer return cargo once the last one leaves the truck (#128).
if self.sams[t].ground_stock == 0 { self.sams[t].return_cargo = false; }
self.sams[t].air_48n6_stock += displaced;
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
}
self.sams[t].job = None;
} else {
let to = self.sams[j].pos;
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
self.order_move_near(t, to + side, 3.5);
self.order_move_near(t, to, HANDOVER - 0.75);
continue;
}
} else { self.sams[t].job = None; }
@@ -213,15 +213,16 @@ impl Sim {
}.map(|s| (s.id, s.pos));
if let Some((id, to)) = next {
self.sams[t].job = Some(id);
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
if to.distance(at) > HANDOVER { self.order_move_near(t, to + side, 3.5); }
if to.distance(at) > HANDOVER { self.order_move_near(t, to, HANDOVER - 0.75); }
}
continue;
}
// Where it was going: hand over, or load up.
if let Some(job) = truck.job
&& let Some(j) = self.sams.iter().position(|s| s.id == job)
{
if let Some(job) = truck.job {
let Some(j) = self.sams.iter().position(|s| s.id == job && s.alive()) else {
self.sams[t].job = None;
continue;
};
if self.sams[j].pos.distance(at) <= HANDOVER {
if self.sams[j].kind == SamKind::Depot {
let take = TRUCK_LOAD.saturating_sub(self.sams[t].cargo).min(self.sams[j].cargo);
@@ -233,11 +234,10 @@ impl Sim {
self.reload_now(j, out);
}
self.sams[t].job = None;
} else if self.sams[j].alive() && (self.sams[j].empty || self.sams[j].kind == SamKind::Depot) {
} else if self.sams[j].empty || self.sams[j].kind == SamKind::Depot {
// Stopped short of it (it drove off meanwhile): on to where it stands now.
let to = self.sams[j].pos;
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
self.order_move_near(t, to + side, 3.5);
self.order_move_near(t, to, HANDOVER - 0.75);
continue;
} else {
self.sams[t].job = None;
@@ -268,9 +268,8 @@ impl Sim {
if let Some((id, to)) = next {
self.sams[t].job = Some(id);
// Stop beside it, not on it.
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
if to.distance(at) > HANDOVER {
self.order_move_near(t, to + side, 3.5);
self.order_move_near(t, to, HANDOVER - 0.75);
}
}
}
@@ -288,6 +287,19 @@ impl Sim {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_empty_nearby_depot_explains_the_missing_typed_stock() {
let mut sim = Sim::new(1);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 1.0)] {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
let error = sim.load_ground_round(1).unwrap_err();
assert!(error.contains("RM48U: 0"));
assert!(error.contains("/airdef ground-stock 1"));
assert_eq!((sim.sams[0].ground_stock, sim.sams[1].ground_rounds, sim.sams[1].missiles), (0, 0, 4));
}
#[test]
fn return_waits_for_capacity_and_ready_carrier_and_can_be_cancelled() {
let mut sim = Sim::new(3);
@@ -400,4 +412,170 @@ mod tests {
assert!(!sim.sams[1].ground_request);
}
/// Runs `step_supply`, jumping the truck beside its current job each tick so handovers
/// resolve without a full drive (movement itself is covered by the lib round-trip tests).
/// Fails after 200 ticks if `done` never holds.
fn serve_until(sim: &mut Sim, truck: usize, mut done: impl FnMut(&Sim) -> bool) {
let mut ok = false;
for _ in 0..200 {
if done(sim) { ok = true; break; }
if let Some(id) = sim.sams[truck].job()
&& let Some(j) = sim.sams.iter().position(|s| s.id == id)
{
sim.sams[truck].pos = sim.sams[j].pos;
}
sim.sams[truck].state = SamState::Search;
sim.tick += 1;
sim.step_supply(&mut Out::default());
}
assert!(ok, "condition not reached within 200 step_supply calls");
}
/// #128: a return that is claimed but cannot proceed (here: the returning system is on the
/// move) must not stop the free truck with job=None; an independent typed request is served.
/// The claim stays, the rounds are conserved, and once the system stops the return completes.
#[test]
fn a_moving_return_claim_does_not_starve_an_independent_supply_request() {
let mut sim = Sim::new(5);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 40.0), (SamKind::S400, 160.0), (SamKind::Tzm, 0.0)] {
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
let (depot, a, b, truck) = (0usize, 1usize, 2usize, 3usize);
let b_id = sim.sams[b].id;
sim.sams[depot].ground_stock = 2;
sim.sams[a].ground_rounds = 1;
sim.sams[a].missiles = 3;
sim.sams[a].ground_return = true;
sim.sams[b].ground_request = true;
assert!(sim.order_move(a, DVec3::new(400.0, 70.0, 0.0)));
// The free truck loads one RM48U at the depot and starts driving to B within 100 ticks;
// before the fix it entered the return branch, found the moving A impossible and idled.
let mut started = false;
for _ in 0..100 {
sim.tick += 1;
sim.step_supply(&mut Out::default());
if sim.sams[truck].job() == Some(b_id) { started = true; break; }
}
assert!(started, "truck never started the delivery to B");
// The claim and the rounds are untouched by the fallback.
assert!(sim.sams[a].ground_return);
assert_eq!(sim.sams[a].ground_rounds, 1);
assert_eq!((sim.sams[depot].ground_stock, sim.sams[truck].ground_stock), (1, 1));
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
// Hand the round over to B; the full drive is exercised in the lib round-trip test.
serve_until(&mut sim, truck, |s| s.sams[b].ground_rounds == 1);
assert!(!sim.sams[b].ground_request);
assert_eq!((sim.sams[b].missiles, sim.sams[truck].air_48n6_stock), (3, 1));
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
// No request is left, so the truck holds its watch (a stock run aside): the pending
// return still outranks it and the claim survives.
for _ in 0..20 { sim.tick += 1; sim.step_supply(&mut Out::default()); }
assert!(sim.sams[a].ground_return);
assert_eq!(sim.sams[a].ground_rounds, 1);
// A stops: the actual return is picked up and driven back to the depot.
sim.sams[a].state = SamState::Search;
sim.sams[a].dest = None;
serve_until(&mut sim, truck, |s| s.sams[truck].return_cargo);
assert!(!sim.sams[a].ground_return);
assert_eq!((sim.sams[a].ground_rounds, sim.sams[a].missiles), (0, 4));
assert_eq!((sim.sams[truck].ground_stock, sim.sams[truck].air_48n6_stock), (1, 0));
serve_until(&mut sim, truck, |s| s.sams[depot].ground_stock == 2);
assert!(!sim.sams[truck].return_cargo);
assert_eq!((sim.sams[depot].ground_stock, sim.sams[truck].ground_stock, sim.sams[b].ground_rounds), (2, 0, 1));
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
}
/// #128 variant: the pickup is already claimed by another truck, so for this one the return
/// is impossible; it must turn to the waiting request instead of idling with job=None. A
/// dropped job (as after loading a save) is rebuilt, damaged trucks wait, and the repaired
/// claiming truck keeps the priority of the now executable return over the request.
#[test]
fn a_return_claimed_by_another_truck_leaves_the_supply_to_the_second_one() {
let mut sim = Sim::new(7);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 160.0), (SamKind::S400, 200.0), (SamKind::Tzm, 0.0), (SamKind::Tzm, 150.0)] {
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
let (depot, a, b, t2, t1) = (0usize, 1usize, 2usize, 3usize, 4usize);
let (a_id, b_id) = (sim.sams[a].id, sim.sams[b].id);
sim.sams[depot].ground_stock = 2;
sim.sams[a].ground_rounds = 1;
sim.sams[a].missiles = 3;
sim.sams[a].ground_return = true;
sim.sams[b].ground_request = true;
// The first truck claimed A's pickup earlier; both trucks start damaged: nothing
// moves, no round is lost, the claim waits.
sim.sams[t1].job = Some(a_id);
sim.sams[t1].comps.0[Part::Tracks as usize] = 0.0;
sim.sams[t2].comps.0[Part::Tracks as usize] = 0.0;
for _ in 0..30 { sim.tick += 1; sim.step_supply(&mut Out::default()); }
assert_eq!(sim.sams[t2].job(), None);
assert_eq!((sim.sams[depot].ground_stock, sim.sams[b].ground_rounds), (2, 0));
assert!(sim.sams[a].ground_return);
assert_eq!(sim.sams[depot].ground_stock + sim.sams[t1].ground_stock + sim.sams[t2].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
// Repaired, the second truck must not idle on the claimed return: depot first, then B.
sim.sams[t2].comps.0[Part::Tracks as usize] = 1.0;
let mut started = false;
for _ in 0..100 {
sim.tick += 1;
sim.step_supply(&mut Out::default());
if sim.sams[t2].job() == Some(b_id) { started = true; break; }
}
assert!(started, "second truck never started the delivery to B");
assert_eq!((sim.sams[depot].ground_stock, sim.sams[t2].ground_stock), (1, 1));
assert!(sim.sams[a].ground_return, "claimed return must survive the fallback");
// A save/load drops the job; the request and the cargo survive and the job is rebuilt.
sim.sams[t2].job = None;
serve_until(&mut sim, t2, |s| s.sams[t2].job() == Some(b_id));
// The claiming truck is repaired: the executable return has priority over the request,
// and the still-hauling second truck is not diverted from B.
sim.sams[t1].comps.0[Part::Tracks as usize] = 1.0;
serve_until(&mut sim, t1, |s| s.sams[t1].return_cargo);
assert!(!sim.sams[a].ground_return);
assert_eq!(sim.sams[a].ground_rounds, 0);
assert_eq!(sim.sams[t2].job(), Some(b_id), "hauling truck must keep its supply job");
// B gets its round; the displaced air round rides along.
serve_until(&mut sim, t2, |s| s.sams[b].ground_rounds == 1);
assert_eq!((sim.sams[b].missiles, sim.sams[t2].air_48n6_stock), (3, 1));
assert_eq!(sim.sams[depot].ground_stock + sim.sams[t1].ground_stock + sim.sams[t2].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
// And the picked-up return reaches the depot: everything is back except B's new round.
serve_until(&mut sim, t1, |s| s.sams[depot].ground_stock == 2);
assert!(!sim.sams[t1].return_cargo);
assert_eq!((sim.sams[depot].ground_stock, sim.sams[t1].ground_stock, sim.sams[b].ground_rounds), (2, 0, 1));
}
/// #128 variant: the route to the returning system is marked unreachable, so the return is
/// impossible for now; the truck serves the request, and the return completes once the
/// route is passable again and the system is still waiting with its claim.
#[test]
fn an_unreachable_route_falls_back_to_supply_until_it_expires() {
let mut sim = Sim::new(9);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 40.0), (SamKind::S400, 160.0), (SamKind::Tzm, 0.0)] {
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
let (depot, a, b, truck) = (0usize, 1usize, 2usize, 3usize);
let (a_id, b_id) = (sim.sams[a].id, sim.sams[b].id);
sim.sams[depot].ground_stock = 2;
sim.sams[a].ground_rounds = 1;
sim.sams[a].missiles = 3;
sim.sams[a].ground_return = true;
sim.sams[b].ground_request = true;
sim.routes.unreachable.insert((sim.sams[truck].id, a_id), u64::MAX);
let mut started = false;
for _ in 0..100 {
sim.tick += 1;
sim.step_supply(&mut Out::default());
if sim.sams[truck].job() == Some(b_id) { started = true; break; }
}
assert!(started, "truck never started the delivery to B");
assert!(sim.sams[a].ground_return, "claim must survive the blocked route");
serve_until(&mut sim, truck, |s| s.sams[b].ground_rounds == 1);
// The route is passable again: the waiting claim is picked up and returned.
sim.routes.unreachable.clear();
serve_until(&mut sim, truck, |s| s.sams[truck].return_cargo);
assert!(!sim.sams[a].ground_return);
serve_until(&mut sim, truck, |s| s.sams[depot].ground_stock == 2);
assert!(!sim.sams[truck].return_cargo);
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
}
}
+179
View File
@@ -0,0 +1,179 @@
//! Where the mod's memory goes: an estimate of what each consumer holds, for the budget
//! tests and the diagnostics. The whole mod lives in one 64 MiB WASM linear memory
//! (`horizon-mods` runtime `MEMORY`): the simulation, the ground and block caches, the
//! recordings and the enemy's memory all share it, and a hashbrown rehash briefly holds
//! the old and the new table at once. The estimates count allocated capacity, not len,
//! and the tables' control bytes; they are a lower bound on the allocator's footprint
//! (fragmentation and the transient query/answer vectors come on top).
use super::*;
/// A hashbrown table's allocation for `len` entries of `entry` bytes (key + value):
/// the capacity grows 3, 7, 14, 28, … at a 7/8 load, and the allocation is
/// `(capacity + group) * (entry + 1)` (one control byte per slot).
pub(super) fn map_bytes(len: usize, entry: usize) -> usize {
if len == 0 {
return 0;
}
let mut cap = 3usize;
while cap * 7 / 8 < len {
cap = if cap == 3 { 7 } else { cap * 2 };
}
(cap + 16) * (entry + 1)
}
/// A `BTreeMap`'s nodes, about: the entry plus the node's share of pointers and slack.
pub(super) fn btree_bytes(len: usize, entry: usize) -> usize {
len * (entry + 32)
}
pub(super) fn vec_bytes<T>(v: &Vec<T>) -> usize {
v.capacity() * std::mem::size_of::<T>()
}
pub(super) fn vecdeque_bytes<T>(v: &std::collections::VecDeque<T>) -> usize {
v.capacity() * std::mem::size_of::<T>()
}
/// What each consumer holds, in bytes (estimated allocated capacity).
#[derive(Clone, Copy, Default, Debug)]
pub struct MemoryReport {
/// `Ground::known`: the answered land heights by column.
pub ground_known: usize,
/// The ground's other bookkeeping: loading, questions waiting, chunks wanted.
pub ground_other: usize,
/// `WorldCache::secs`: the block sections, table and the mixed ones' bits.
pub world_sections: usize,
/// The block cache's other bookkeeping: exact rays, queues, questions, blasts expected.
pub world_other: usize,
/// The simulation's vectors: drones (and their routes), missiles, systems, objects,
/// effects, blasts, the launch queue and the rest of the live state.
pub units: usize,
/// The radars' tracks and horizons.
pub tracks: usize,
/// The recording in progress.
pub recording: usize,
/// The replays kept.
pub replays: usize,
/// The enemy's memory of the layout (contacts and outcomes).
pub intel: usize,
/// The recon memory (sorties, marks, checked zones).
pub recon: usize,
/// The vehicles' ground routes and their searches.
pub routes: usize,
/// The raid's launch sites.
pub sites: usize,
/// The counter-strikes on the sites.
pub strikes: usize,
/// The raid being planned (its grid, prices, routes, knowledge) and the retarget jobs.
pub plan: usize,
/// The rest: fires, flares, roles, tallies, the smart refresh.
pub other: usize,
}
impl MemoryReport {
pub fn total(&self) -> usize {
self.ground_known
+ self.ground_other
+ self.world_sections
+ self.world_other
+ self.units
+ self.tracks
+ self.recording
+ self.replays
+ self.intel
+ self.recon
+ self.routes
+ self.sites
+ self.strikes
+ self.plan
+ self.other
}
/// The largest table a rehash could double while the old one is still held: the
/// transient peak is the total plus twice this (old + new − steady).
pub fn rehash_headroom(&self) -> usize {
2 * self.ground_known.max(self.world_sections)
}
/// One line per consumer, biggest first: the budget report's shape.
pub fn text(&self) -> String {
let mut rows = [
("ground.known", self.ground_known),
("ground.other", self.ground_other),
("world.secs", self.world_sections),
("world.other", self.world_other),
("sim.units", self.units),
("sim.tracks", self.tracks),
("recording", self.recording),
("replays", self.replays),
("intel", self.intel),
("recon", self.recon),
("routes", self.routes),
("sites", self.sites),
("strikes", self.strikes),
("plan", self.plan),
("other", self.other),
];
rows.sort_by(|a, b| b.1.cmp(&a.1));
let mut out = format!("total {:.2} MiB (+{:.2} MiB rehash transient)", self.total() as f64 / (1024.0 * 1024.0), self.rehash_headroom() as f64 / (1024.0 * 1024.0));
for (name, bytes) in rows {
if bytes > 0 {
out.push_str(&format!("\n {name}: {:.2} MiB", bytes as f64 / (1024.0 * 1024.0)));
}
}
out
}
}
impl Sim {
/// What the simulation and the ground cache hold, about: the budget tests measure it
/// under load, and the diagnostics can show where the memory went.
pub fn memory(&self, ground: &Ground) -> MemoryReport {
let mut r = MemoryReport::default();
r.ground_known = map_bytes(ground.known.len(), std::mem::size_of::<(i32, i32)>() + std::mem::size_of::<(i32, u64)>());
r.ground_other = map_bytes(ground.loading.len(), std::mem::size_of::<(i32, i32)>() + std::mem::size_of::<u64>())
+ vec_bytes(&ground.wanted)
+ map_bytes(ground.asked.len(), std::mem::size_of::<(i32, i32)>())
+ vec_bytes(&ground.chunks);
let (sections, other) = ground.world.memory();
r.world_sections = sections;
r.world_other = other;
r.units = vec_bytes(&self.drones)
+ self.drones.iter().map(|d| vec_bytes(&d.route)).sum::<usize>()
+ vec_bytes(&self.missiles)
+ vec_bytes(&self.sams)
+ vec_bytes(&self.targets)
+ vec_bytes(&self.target_health)
+ vec_bytes(&self.fx)
+ vec_bytes(&self.blasts)
+ vec_bytes(&self.queue)
+ vec_bytes(&self.settling)
+ vec_bytes(&self.later)
+ vec_bytes(&self.flares)
+ vec_bytes(&self.lit);
r.tracks = self.sams.iter().map(|s| vec_bytes(&s.tracks)).sum::<usize>()
+ map_bytes(self.horizons.len(), std::mem::size_of::<u32>() + std::mem::size_of::<sight::Horizon>())
+ self.horizons.values().map(|h| vec_bytes(&h.rays) + h.rays.iter().map(|ray| vec_bytes(ray)).sum::<usize>()).sum::<usize>();
r.recording = self.rec.as_ref().map_or(0, |rec| rec.bytes());
r.replays = self.replays.iter().map(|rec| rec.bytes()).sum();
r.intel = self.intel.bytes();
r.recon = vec_bytes(&self.recon.sorties)
+ btree_bytes(self.recon.marks.len(), std::mem::size_of::<u32>() + std::mem::size_of::<recon::Mark>())
+ btree_bytes(self.recon.truth.len(), 2 * std::mem::size_of::<u32>())
+ btree_bytes(self.recon.checked.len(), std::mem::size_of::<(i64, i64)>() + std::mem::size_of::<u64>());
r.routes = self.routes.bytes();
r.sites = self.sites.bytes();
r.strikes = self.strikes.bytes();
r.plan = self.plan.as_ref().map_or(0, |p| p.bytes())
+ vecdeque_bytes(&self.retargets)
+ self.retargets.iter().map(|j| j.known.bytes() + j.relief.as_ref().map_or(0, |k| k.bytes())).sum::<usize>()
+ self.known_relief.as_ref().map_or(0, |k| k.bytes());
r.other = map_bytes(self.roles.len(), std::mem::size_of::<SamKind>() + std::mem::size_of::<u8>())
+ self.fires.bytes()
+ self.breakthroughs.bytes()
+ std::mem::size_of::<record::Tally>()
+ std::mem::size_of::<Self>();
r
}
}
+531 -553
View File
File diff suppressed because it is too large Load Diff
+268
View File
@@ -0,0 +1,268 @@
//! The planner's one public observation (#149): a disclosure `Contact` and a recon `Mark` are
//! two channels hinting at the same game objects, on two different scales. This module projects
//! both into a single [`Observation`] — an area, a channel, an age, a confidence and the public
//! game features — and matches them by those public features alone: a mark whose area holds a
//! contact's fix and whose observed category agrees is the same hint, not a second target.
//!
//! A match is a belief, never a fact: it is made only on an exact public category agreement and
//! area overlap, it is flagged (`matched`), and it invents nothing — the contact keeps the kind
//! and place it was observed with, the mark only adds what it publicly saw (a refined radar role,
//! a fresher look). A coarse `Unknown` mark or a contradicting category is *not* matched: it stays
//! a separate hint. The observer's truth map and the units' real ids play no part here.
use super::*;
/// A contact fix this far inside a mark's area (on top of its radius) reads as the same public
/// hint. The fix is exact, the area is coarse: the slack is the cell jitter a report carries.
const MATCH_SLACK: f64 = 8.0;
/// One public hint about one game object, from either channel (#149). There is no health,
/// magazine, link, hidden switch or true place in it: `kind` is `Some` only for a disclosure
/// contact, whose type was identified at the observation; a mark carries its coarse category.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Observation {
/// The hint's public id: a contact's id, or a mark's synthetic one. Never a matched unit's truth.
pub id: u32,
/// The best public place: a contact's fix, or a mark's area centre.
pub at: DVec3,
/// 0 for an exact fix; the area's radius for a mark.
pub radius: f64,
/// The channel that showed it last: flyby, emission, jamming or launch.
pub channel: recon::Source,
/// The tick of the observation this hint rests on.
pub observed: u64,
pub category: recon::Category,
/// A radar's role, once a refined look told it.
pub role: Option<battery::RadarRole>,
/// The type identified at a disclosure observation; `None` for a recon mark.
pub kind: Option<SamKind>,
pub quality: recon::Quality,
/// A second public hint agreed by area and category. A belief for the diagnostic, not a fact.
pub matched: bool,
}
impl Observation {
pub fn age(&self, now: u64) -> u64 {
now.saturating_sub(self.observed)
}
pub fn confidence(&self, now: u64) -> Confidence {
ew::confidence_for_age(self.age(now))
}
/// An exact disclosure fix, rather than a coarse area.
pub fn exact(&self) -> bool {
self.radius == 0.0
}
pub fn live(&self, now: u64) -> bool {
self.age(now) < ew::CONTACT_TTL
}
/// The one ranking scale both channels share (#149): the mark's priority parts (freshness,
/// quality, observed role) plus a small premium for being a fix rather than an area.
pub fn rank(&self, now: u64) -> u8 {
let (f, q, r) = recon::priority_parts(self.confidence(now), self.quality, self.category, self.role);
f * 4 + q * 3 + r + u8::from(self.exact()) * 3
}
}
/// The disclosure channel in the one scale the marks already use.
pub(super) fn channel_of(seen: ew::Seen) -> recon::Source {
match seen {
ew::Seen::Launch => recon::Source::Launch,
ew::Seen::Emission => recon::Source::Emission,
ew::Seen::Jamming => recon::Source::Jamming,
}
}
/// Projects contacts and marks into one list of public hints, best first. A mark is matched to a
/// contact only by public features (area overlap and an exact category agreement); a matched mark
/// is consumed — the object is one hint, priced and assigned once. Unmatched marks stand as areas.
pub(super) fn merge(contacts: &[ew::Contact], marks: &[recon::Mark], now: u64) -> Vec<Observation> {
let mut out: Vec<Observation> = contacts
.iter()
.filter(|c| c.live(now))
.map(|c| Observation {
id: c.id,
at: c.at,
radius: 0.0,
channel: channel_of(c.seen),
observed: c.tick,
category: recon::Category::of(c.kind),
role: None,
kind: Some(c.kind),
quality: recon::Quality::Refined,
matched: false,
})
.collect();
let mut areas = Vec::new();
for m in marks.iter().filter(|m| m.live(now)) {
let hit = out.iter_mut().find(|o| {
o.kind.is_some()
&& m.category != recon::Category::Unknown
&& m.category == o.category
&& (m.role.is_none() || o.category == recon::Category::Radar)
&& horizontal(o.at - m.area).length() <= m.radius + MATCH_SLACK
});
match hit {
Some(o) => {
// The match is public evidence, not truth: the fresher look and the refined role
// are what the mark itself saw; the contact's kind and fix are never rewritten.
o.matched = true;
if m.observed > o.observed {
o.observed = m.observed;
o.channel = m.source;
}
if o.category == recon::Category::Radar && m.role.is_some() {
o.role = m.role;
}
}
None => areas.push(Observation {
id: m.id,
at: m.area,
radius: m.radius,
channel: m.source,
observed: m.observed,
category: m.category,
role: m.role,
kind: None,
quality: m.quality,
matched: false,
}),
}
}
out.extend(areas);
out.sort_by(|a, b| b.rank(now).cmp(&a.rank(now)).then(b.observed.cmp(&a.observed)).then(a.id.cmp(&b.id)));
out
}
/// The small game policy (#149): which observed categories a kind is worth turning onto. One
/// place for the fit both the plan's picks and the adaptive assignments read — no hidden state,
/// only the public category and the kind's published role.
pub(super) fn fits(kind: DroneKind, category: recon::Category) -> bool {
use recon::Category as C;
match kind {
DroneKind::Lancet => matches!(category, C::Gun | C::Launcher | C::Ew),
DroneKind::Kh22 | DroneKind::Zircon => matches!(category, C::Radar | C::Launcher | C::Ew),
DroneKind::Iskander | DroneKind::Kinzhal => matches!(category, C::Radar | C::Launcher),
DroneKind::Shahed | DroneKind::Geran3 => matches!(category, C::Radar | C::Launcher | C::Gun | C::Ew),
_ => false,
}
}
/// The public worst-case envelope of a category: the furthest missile reach and gun range any
/// published kind of that category has, for this drone at this height. What a mark's area may
/// hold is priced by the catalog, never by a hidden unit's actual load (#149).
pub(super) fn category_envelope(category: recon::Category) -> (f64, f64, f64) {
let mut lo = f64::INFINITY;
let mut hi = 0.0f64;
let mut gun = 0.0f64;
for k in SamKind::ALL {
if recon::Category::of(k) != category {
continue;
}
let sp = k.spec();
if let Some(m) = &sp.missile {
lo = lo.min(m.min);
hi = hi.max(m.max);
}
if let Some(g) = &sp.gun {
gun = gun.max(g.range);
}
}
(lo.min(hi), hi, gun)
}
/// The published reach of the strongest radar kind, for a mark that only says "a radar is here".
pub(super) fn radar_envelope(drone: DroneKind, height: f64) -> f64 {
SamKind::ALL
.into_iter()
.filter(|k| recon::Category::of(*k) == recon::Category::Radar)
.map(|k| ew::published_reach(k, drone, height))
.fold(0.0, f64::max)
}
#[cfg(test)]
mod tests {
use super::*;
fn contact(id: u32, kind: SamKind, at: DVec3, tick: u64) -> ew::Contact {
ew::Contact { id, kind, at, tick, seen: ew::Seen::Emission, emission: Some(tick), destroyed: None, launches: 0 }
}
fn mark(id: u32, at: DVec3, category: recon::Category, observed: u64) -> recon::Mark {
recon::Mark {
id,
area: at,
radius: recon::COARSE_AREA,
category,
role: None,
source: recon::Source::Flyby,
observed,
reported: observed,
quality: recon::Quality::Coarse,
looks: 1,
}
}
// #149: one object, two channels, one hint. A mark whose area holds the contact's fix and
// whose category agrees is matched and consumed — not a second target. The match reads only
// public features: two marks of different hidden truths but the same public area/category
// both fold into the one contact.
#[test]
fn a_matching_mark_is_one_hint_not_two() {
let at = DVec3::new(100.0, 70.0, 0.0);
let c = contact(16, SamKind::Radar, at, 100);
let m1 = mark(recon::ID_BASE + 1, at + DVec3::new(20.0, 0.0, 0.0), recon::Category::Radar, 120);
let m2 = mark(recon::ID_BASE + 2, at + DVec3::new(-30.0, 0.0, 10.0), recon::Category::Radar, 130);
let obs = merge(&[c], &[m1, m2], 200);
assert_eq!(obs.len(), 1, "the same public object stayed two hints");
assert!(obs[0].matched && obs[0].exact() && obs[0].kind == Some(SamKind::Radar));
assert_eq!(obs[0].observed, 130, "the fresher public look was not taken");
assert_eq!(obs[0].id, 16, "the hint kept the mark's synthetic id over the contact's");
}
// #149: an unconfirmed match is not a fact. A coarse Unknown mark, a contradicting category,
// or an area that does not hold the fix stays a separate hint — nothing is merged on a guess.
#[test]
fn an_unconfirmed_match_stays_separate() {
let at = DVec3::new(100.0, 70.0, 0.0);
let c = contact(16, SamKind::Radar, at, 100);
let unknown = mark(recon::ID_BASE + 1, at, recon::Category::Unknown, 120);
let wrong = mark(recon::ID_BASE + 2, at, recon::Category::Launcher, 120);
let far = mark(recon::ID_BASE + 3, at + DVec3::new(400.0, 0.0, 0.0), recon::Category::Radar, 120);
let obs = merge(&[c], &[unknown, wrong, far], 200);
assert_eq!(obs.len(), 4, "a weak match was treated as a fact");
assert!(obs.iter().filter(|o| o.kind.is_some()).all(|o| !o.matched));
// A refined role is public only for a radar; a launcher mark never lends one.
let mut radar = mark(recon::ID_BASE + 4, at, recon::Category::Radar, 140);
radar.quality = recon::Quality::Refined;
radar.role = Some(battery::RadarRole::Engagement);
let obs = merge(&[c], &[radar], 200);
assert_eq!(obs.len(), 1);
assert_eq!(obs[0].role, Some(battery::RadarRole::Engagement));
}
// #149: one scale. A fresh confirmed fix outranks an old doubtful area; a refined big-role
// mark outranks a coarse modest one of the same age; the order never reads an id or a truth.
#[test]
fn the_rank_is_one_public_scale() {
let fresh = contact(16, SamKind::Radar, DVec3::ZERO, 190);
let old = mark(recon::ID_BASE + 1, DVec3::X * 500.0, recon::Category::Launcher, 0);
let obs = merge(&[fresh], &[old], 200);
assert_eq!(obs[0].id, 16, "a fresh fix did not lead an old area");
let mut big = mark(recon::ID_BASE + 2, DVec3::X * 900.0, recon::Category::Radar, 190);
big.quality = recon::Quality::Refined;
big.role = Some(battery::RadarRole::Engagement);
let modest = mark(recon::ID_BASE + 3, DVec3::X * 1300.0, recon::Category::Radar, 190);
let obs = merge(&[], &[modest, big], 200);
assert_eq!(obs[0].id, big.id, "the bigger observed role did not lead");
assert!(obs[0].rank(200) > obs[1].rank(200));
}
// #149: the policy fit is the public category, the same for the plan and the adaptive picks.
#[test]
fn the_fit_is_the_public_category() {
assert!(fits(DroneKind::Lancet, recon::Category::Gun));
assert!(!fits(DroneKind::Lancet, recon::Category::Radar));
assert!(fits(DroneKind::Kh22, recon::Category::Radar));
assert!(!fits(DroneKind::Iskander, recon::Category::Gun));
assert!(!fits(DroneKind::Gerbera, recon::Category::Launcher));
}
}
File diff suppressed because it is too large Load Diff
+49 -34
View File
@@ -18,9 +18,9 @@ impl SamKind {
Family::Truck => 10,
}
}
/// A depot doesn't drive.
/// A depot and a fixed optical post don't drive.
pub fn mobile(self) -> bool {
self != SamKind::Depot
!matches!(self, SamKind::Depot | SamKind::Optical)
}
}
@@ -35,10 +35,29 @@ impl Sam {
}
}
fn finish_move(sam: &mut Sam, routes: &mut route::Routes, index: usize, now: u64, why: Option<route::Why>, out: &mut Out) {
if let Some(why) = why {
let report = sam.job.take().is_none_or(|job| {
routes.unreachable.insert((sam.id, job), now + route::UNREACHABLE_FOR).is_none()
});
if report {
out.messages.push(format!("{} №{}: {}", sam.kind.name(), index + 1, why.text()));
}
}
routes.map.remove(&sam.id);
sam.dest = None;
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
}
impl Sim {
/// Orders unit `i` to drive to `to`. False for one that can't (a depot, a wreck, failed running gear).
pub fn order_move(&mut self, i: usize, to: DVec3) -> bool {
self.order_move_near(i, to, 0.0)
if !self.order_move_near(i, to, 0.0) {
return false;
}
self.sams[i].job = None;
true
}
/// The same, where arriving within `slack` blocks of `to` will do (a truck stops beside its job).
@@ -97,45 +116,45 @@ impl Sim {
sam.dest = None;
}
let Some(to) = sam.dest else {
routes.map.remove(&sam.id);
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
finish_move(sam, routes, n, now, None, out);
continue;
};
let route = routes.map.entry(sam.id).or_insert_with(|| route::Route::new(sam.pos, to, 0.0, sam.kind, now));
let (go, last) = match route.drive(ground, now, sam.pos, share) {
route::Drive::Wait(why) => {
if route.waited(now) > 40 && !route.told {
if sam.job.is_none() && route.waited(now) > 40 && !route.told {
route.told = true;
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, why.text()));
}
continue;
}
route::Drive::Fail(why) => {
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, why.text()));
// A truck leaves that job alone for a while, and takes another.
if let Some(job) = sam.job.take() {
routes.unreachable.insert((sam.id, job), now + route::UNREACHABLE_FOR);
if why == route::Why::NoWay && route.approach_works() {
continue;
}
routes.map.remove(&sam.id);
sam.dest = None;
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
if matches!(why, route::Why::NoWay | route::Why::Stuck)
&& route.try_works(ground, sam.pos, now, out)
{
continue;
}
finish_move(sam, routes, n, now, Some(why), out);
continue;
}
route::Drive::Go(p, last) => (p, last),
};
let flat = horizontal(go - sam.pos);
if last && flat.length() < SPEED * 2.0 {
let partial = route.partial;
sam.pos = DVec3::new(go.x, sam.pos.y, go.z);
sam.dest = None;
routes.map.remove(&sam.id);
if partial {
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, route::Why::Partial.text()));
}
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
let why = if route.work_approach() {
if route.try_works(ground, sam.pos, now, out) {
continue;
}
Some(route::Why::NoWay)
} else {
// A partial route already made measurable progress. A delivery
// continues from here when the next stretch of terrain is ready.
(route.partial && sam.job.is_none()).then_some(route::Why::Partial)
};
finish_move(sam, routes, n, now, why, out);
out.sound("minecraft:block.piston.contract", sam.pos, 2.0, 0.6);
continue;
}
@@ -143,17 +162,17 @@ impl Sim {
sam.heading = slew(sam.heading, heading_of(flat), 0.06);
let ahead = DQuat::from_rotation_y(sam.heading) * DVec3::NEG_Z;
let turning = angle_diff(sam.heading, heading_of(flat)).abs();
if sam.kind == SamKind::Tzm && turning > 0.45 {
sam.yaw = sam.heading;
continue;
}
let step = SPEED * sam.drive_speed() * (1.0 - turning / std::f64::consts::PI).max(0.2);
let next = sam.pos + ahead * step;
// The column and chassis clearance ahead: a wall, low ceiling or a change after planning
// turns the vehicle back to the planner. Unknown voxels remain a wait, never a drive.
let Some(y) = ground.at(next, now) else {
if route.wait_ahead() {
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, route::Why::NoMap.text()));
routes.map.remove(&sam.id);
sam.dest = None;
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
finish_move(sam, routes, n, now, Some(route::Why::NoMap), out);
}
continue;
};
@@ -161,11 +180,7 @@ impl Sim {
route::Clearance::Clear => {}
route::Clearance::Pending => {
if route.wait_ahead() {
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, route::Why::NoMap.text()));
routes.map.remove(&sam.id);
sam.dest = None;
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
finish_move(sam, routes, n, now, Some(route::Why::NoMap), out);
}
continue;
}
+3 -3
View File
@@ -123,9 +123,9 @@ pub fn look(kind: DroneKind, outcome: Outcome) -> (f32, u32, f32, &'static str)
let life = (8 + (w as u32) / 2) * 9;
let gain = 1.0 + 0.06 * w;
match outcome {
Outcome::DisabledFalling => (size, life, gain, "airdef:blast.air"),
Outcome::Breakup => (size * 0.9, life, gain * 0.9, "airdef:blast.medium"),
Outcome::AirDetonation => (size * 1.9, life * 8 / 5, gain * 1.5, "airdef:blast.big"),
Outcome::DisabledFalling => (size, life, gain, super::catalog::sound::BLAST_AIR),
Outcome::Breakup => (size * 0.9, life, gain * 0.9, super::catalog::sound::BLAST_MEDIUM),
Outcome::AirDetonation => (size * 1.9, life * 8 / 5, gain * 1.5, super::catalog::sound::BLAST_BIG),
}
}
+149
View File
@@ -0,0 +1,149 @@
//! Per-phase wall time of `Sim::step` (#147 step 3.1): observation only, never
//! a combat input. The simulation stays SDK-independent (it is also built as
//! `airdef-core`), so the adapter installs the host clock
//! (`game.monotonic-nanos`, API level 32) with [`set_clock`] before the first
//! tick; native tests fall back to `std::time::Instant`. The counters are
//! fixed-size and per-thread (a mod instance is single-threaded); timing reads
//! no randomness and changes no decision, so the ordered combat trace is
//! identical with or without it.
use std::cell::RefCell;
/// The named phases of `Sim::step`, as indices into the counters.
pub const PLAN: usize = 0;
pub const ADAPT: usize = 1;
pub const DRONES: usize = 2;
pub const MOVES: usize = 3;
pub const SIGHT: usize = 4;
pub const SAMS: usize = 5;
pub const RECORD: usize = 6;
const NAMED: usize = 7;
/// The phases' report names, in index order.
const NAMES: [&str; NAMED] = ["plan", "adapt", "drones", "moves", "sight", "sams", "record"];
#[derive(Default)]
struct Prof {
total_ns: [u64; NAMED],
max_ns: [u64; NAMED],
steps: u64,
step_ns: u64,
step_max_ns: u64,
other_ns: u64,
other_max_ns: u64,
cur_start: u64,
cur_named: u64,
}
thread_local! {
static PROF: RefCell<Prof> = const { RefCell::new(Prof {
total_ns: [0; NAMED],
max_ns: [0; NAMED],
steps: 0,
step_ns: 0,
step_max_ns: 0,
other_ns: 0,
other_max_ns: 0,
cur_start: 0,
cur_named: 0,
}) };
}
/// The clock the adapter installs (the host's monotonic import); none in native
/// tests, which use the process clock below.
static CLOCK: std::sync::OnceLock<fn() -> u64> = std::sync::OnceLock::new();
/// Installs the monotonic clock, once, before the first timed step.
pub fn set_clock(f: fn() -> u64) {
let _ = CLOCK.set(f);
}
fn now_ns() -> u64 {
match CLOCK.get() {
Some(f) => f(),
None => native_now_ns(),
}
}
#[cfg(not(target_arch = "wasm32"))]
fn native_now_ns() -> u64 {
use std::time::Instant;
static EPOCH: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
EPOCH.get_or_init(Instant::now).elapsed().as_nanos() as u64
}
/// Only reached if the adapter never installed a clock; the mod always does in
/// `init`, so the counters stay zero rather than reading an unsupported clock.
#[cfg(target_arch = "wasm32")]
fn native_now_ns() -> u64 {
0
}
/// Marks the start of one `Sim::step`.
pub fn begin_step() {
let start = now_ns();
PROF.with(|p| {
let p = &mut *p.borrow_mut();
p.cur_start = start;
p.cur_named = 0;
});
}
/// Times one named phase: its wall time joins the phase's counters and the
/// step's named sum, so `end_step` can derive the untimed remainder.
pub fn time<T>(phase: usize, f: impl FnOnce() -> T) -> T {
let start = now_ns();
let out = f();
let dt = now_ns().saturating_sub(start);
PROF.with(|p| {
let p = &mut *p.borrow_mut();
p.total_ns[phase] += dt;
p.max_ns[phase] = p.max_ns[phase].max(dt);
p.cur_named += dt;
});
out
}
/// Marks the end of one `Sim::step`: the whole step and its untimed remainder.
pub fn end_step() {
let end = now_ns();
PROF.with(|p| {
let p = &mut *p.borrow_mut();
let total = end.saturating_sub(p.cur_start);
let other = total.saturating_sub(p.cur_named);
p.steps += 1;
p.step_ns += total;
p.step_max_ns = p.step_max_ns.max(total);
p.other_ns += other;
p.other_max_ns = p.other_max_ns.max(other);
});
}
/// Clears the counters (a new world opens).
pub fn reset() {
PROF.with(|p| *p.borrow_mut() = Prof::default());
}
/// Parseable chat lines for `/airdef stats`: each `PROFILE key=value ...` with
/// millisecond totals and per-step maxima (three decimals) and the step count.
/// `other` is the whole step minus the named phases. Split to stay under the
/// game's 256-character chat line; the bench merges every `PROFILE` line.
pub fn report() -> Vec<String> {
PROF.with(|p| {
let p = p.borrow();
let ms = |ns: u64| ns as f64 / 1e6;
let phase = |i: usize| {
format!(
"{}_ms={:.3} {}_max_ms={:.3}",
NAMES[i], ms(p.total_ns[i]), NAMES[i], ms(p.max_ns[i]),
)
};
vec![
format!(
"PROFILE steps={} step_ms={:.3} step_max_ms={:.3} other_ms={:.3} other_max_ms={:.3}",
p.steps, ms(p.step_ns), ms(p.step_max_ns), ms(p.other_ns), ms(p.other_max_ns),
),
format!("PROFILE {} {} {} {}", phase(0), phase(1), phase(2), phase(3)),
format!("PROFILE {} {} {}", phase(4), phase(5), phase(6)),
]
})
}
+530 -132
View File
@@ -100,6 +100,9 @@ struct Item {
/// A raid being planned: its drones, the prices and routes so far, and the planned ones.
pub(super) struct Plan {
grid: Grid,
/// The one knowledge version the whole order was chosen on and is routed on (#146): every
/// kind's prices are worked out on it, whenever the budget reaches that kind.
knowledge: ew::KnowledgeSnapshot,
prices: HashMap<DroneKind, Vec<f32>>,
routes: HashMap<(DroneKind, i32, i32, i32), Vec<DVec3>>,
items: Vec<Item>,
@@ -124,6 +127,23 @@ pub(super) struct Plan {
mapped: bool,
}
impl Plan {
/// What the plan holds, about: the grid's heights, prices, routes and items (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::{map_bytes, vec_bytes};
map_bytes(self.prices.len(), std::mem::size_of::<DroneKind>() + std::mem::size_of::<Vec<f32>>())
+ self.prices.values().map(|p| vec_bytes(p)).sum::<usize>()
+ map_bytes(self.routes.len(), std::mem::size_of::<(DroneKind, i32, i32, i32)>() + std::mem::size_of::<Vec<DVec3>>())
+ self.routes.values().map(|r| vec_bytes(r)).sum::<usize>()
+ vec_bytes(&self.items)
+ vec_bytes(&self.done)
+ vec_bytes(&self.wants)
+ vec_bytes(&self.heights)
+ vec_bytes(&self.unanswered)
+ self.knowledge.bytes()
}
}
/// The raid in progress: the counts at its start, for the report.
pub(super) struct WaveStats {
kills: u32,
@@ -146,6 +166,7 @@ const LONGEST_WAIT: f64 = 12_000.0;
pub(super) const WORK_PER_TICK: usize = 40_000;
/// The planner's grid over a raid: its corner, its cells' size and how many a side.
#[derive(Clone, Copy)]
pub(super) struct Grid {
pub(super) min: DVec3,
pub(super) cell: f64,
@@ -157,22 +178,20 @@ impl Grid {
let n = self.size;
((((p.x - self.min.x) / self.cell) as i32).clamp(0, n - 1), (((p.z - self.min.z) / self.cell) as i32).clamp(0, n - 1))
}
fn centre(&self, (i, j): (i32, i32), y: f64) -> DVec3 {
pub(super) fn centre(&self, (i, j): (i32, i32), y: f64) -> DVec3 {
DVec3::new(self.min.x + (i as f64 + 0.5) * self.cell, y, self.min.z + (j as f64 + 0.5) * self.cell)
}
}
/// The cheapest way over `grid` from `from` to `to` by its prices (A*): points along it, `to` last.
pub(super) fn plan_route(grid: &Grid, prices: &[f32], from: DVec3, to: DVec3) -> (Vec<DVec3>, usize) {
plan_route_on(grid, prices, None, from, to)
}
/// The land a route crosses: its height under each cell (NaN unknown), the climb a kind holds for long
/// (rise a block), and the height above which the land forces a drone up from its low altitude.
/// (rise a block), and the height above which the land forces a drone up from its low altitude. Unknown
/// land costs `unknown` per cell on top of the open ground: zero for a plan routed over land it is still
/// mapping, more than free for a replanned retarget (#127).
pub(super) struct Relief<'a> {
pub heights: &'a [f32],
pub slope: f32,
pub floor: f32,
pub unknown: f32,
}
/// [`plan_route`] over relief: a climb steeper than the kind holds is dear (a cliff or a ridge it would have to
@@ -219,6 +238,9 @@ pub(super) fn plan_route_on(grid: &Grid, prices: &[f32], relief: Option<&Relief>
price += (slope - r.slope) * 20.0 * len;
}
}
} else if r.unknown > 0.0 {
// Unmapped land is not free: the route prefers what the plan actually knew.
price += len * r.unknown;
}
}
let ng = g + price;
@@ -260,9 +282,52 @@ impl PartialOrd for Open {
}
}
/// Ticks an air start waits for the land under it to be told of.
/// Ticks a scheduled launch waits for the local terrain before using a high entry.
const AIR_START_WAIT: u32 = 120;
/// The build ceiling of the vanilla terrain supported by AirDef.
pub(super) const VANILLA_BUILD_CEILING: f64 = 320.0;
fn unit_strike_limit(total: u32) -> u32 {
(total / 4).max(1).min(total.saturating_sub(1))
}
fn ballistic_velocity(from: DVec3, aim: DVec3, speed: f64) -> DVec3 {
let flat = horizontal(aim - from);
let time = (flat.length() / speed).max(30.0);
flat / time + DVec3::Y * ((aim.y - from.y + 0.5 * GRAVITY * time * time) / time)
}
/// Sample the actual launch column and the first stretch ahead at block resolution.
fn launch_floor(ground: &mut Ground, d: &Drone, offmap: bool) -> (f64, bool) {
let spec = d.kind.spec();
let ballistic = spec.ballistic.is_some();
let heading = horizontal(d.vel).normalize_or(DVec3::NEG_Z);
let climb = d.kind.climb();
let mut floor = d.pos.y;
let mut pending = false;
for blocks in 0..=if ballistic { 8 } else { 24 } {
let dist = f64::from(blocks);
let p = d.pos + heading * dist;
let x = p.x.floor() as i32;
let z = p.z.floor() as i32;
if let Some(Some(height)) = ground.column(x, z, 384) {
let clear = if ballistic { 10.0 } else if offmap { spec.clearance } else { 2.0 };
let rise = if ballistic {
let t = dist / horizontal(d.vel).length().max(0.1);
(d.vel.y * t - 0.5 * GRAVITY * t * t).max(0.0)
} else {
climb.gain(dist)
};
floor = floor.max(height + clear - rise);
} else {
ground.want_chunk((x >> 4, z >> 4));
pending = true;
}
}
(floor, pending)
}
impl Sim {
/// Orders a raid on `objects` (at least one point). A smart raid is planned over the next ticks
/// (each route found in full, a few a tick) and launched when its plan is ready.
@@ -278,6 +343,14 @@ impl Sim {
return 0;
}
let smart = order.aim == Aim::Smart;
// The planner's picture of the layout: one snapshot for the whole order, kept in the plan
// (#146). It is read-only while the plan is built, and taking it per drone made a big second
// order quadratic in the force's size (#122); a map of contacts makes it linear in them (#127).
let knowledge = self.knowledge_now();
let picture = &knowledge.contacts;
// The partial picture the recon flights have radioed home. It is memory, not the
// force: a mark has an area, a category and an age, never a unit's exact place (#135).
let leads = &knowledge.marks;
// A smart enemy comes from where its raids got through best.
let bearing = if smart { self.best_bearing() } else { self.rng.f() * TAU };
// The raid's sides (1, 2, or 4-5): its launch sites go there (#100).
@@ -290,7 +363,8 @@ impl Sim {
let grid = Grid { min: centre - DVec3::new(span, 0.0, span), cell, size: (2.0 * span / cell) as i32 + 1 };
let mut items = Vec::new();
// A smart raid goes for the radars too (a few strikers each); the others pick as they always did.
let radar_jobs = if smart { self.radar_strikes(&order.kinds) } else { Vec::new() };
let radar_jobs = if smart { self.radar_strikes(&order.kinds, picture, leads) } else { Vec::new() };
let mut diversions_left = unit_strike_limit(total).saturating_sub(radar_jobs.iter().flatten().count() as u32);
let mut index = 0usize;
for (group, &(kind, count)) in order.kinds.iter().enumerate() {
let spec = kind.spec();
@@ -306,14 +380,32 @@ impl Sim {
index += 1;
let (target, at_sam) = match job {
Some((at, id)) => (at, Some(id)),
None => self.choose_target(kind, object, order.aim),
None if smart && diversions_left == 0 => (object, None),
None => self.choose_target(kind, object, order.aim, picture, leads),
};
if smart && job.is_none() && at_sam.is_some() {
diversions_left -= 1;
}
let aim = target + DVec3::new(self.rng.s() * 4.0, 0.0, self.rng.s() * 4.0);
let dist = spec.ballistic.map_or(order.dist, |far| far.max(order.dist)) + self.rng.f() * 50.0;
let height = if spec.ballistic.is_some() { 10.0 } else if spec.cruise > 0.0 { spec.cruise } else { 25.0 };
// Where it starts is provisional: the site's pad, once the site is placed.
let from = centre + DVec3::new(a.sin() * dist, height + self.rng.s() * 6.0, a.cos() * dist);
let mut d = self.make_drone(kind, from, horizontal(aim - from), aim);
// The plan's own decision, recorded as such (#127): a radar job is SEAD, a unit
// chosen for the raid is the plan's objective, anything else is a marked object.
if let Some(id) = at_sam {
let confidence = picture
.iter()
.find(|c| c.id == id)
.map(|c| c.confidence(knowledge.tick))
.or_else(|| leads.iter().find(|c| c.id == id).map(|c| c.confidence(knowledge.tick)));
d.intent = if job.is_some() { ew::Intent::Sead } else { ew::Intent::Plan };
d.aim = confidence.map_or_else(|| ew::Aim::point(self.tick), |c| ew::Aim::unit(id, self.tick, c));
} else {
d.intent = ew::Intent::Plan;
d.aim = ew::Aim::point(self.tick);
}
let range = spec.ballistic.map_or(order.dist, |far| far.max(order.dist));
let want = sites::want_index(&mut wants, centre, side, a, sites::SiteClass::of(kind), range, order.dist.max(120.0));
let pad = wants[want].jobs;
@@ -329,6 +421,7 @@ impl Sim {
}
self.plan = Some(Plan {
grid,
knowledge,
prices: HashMap::new(),
routes: HashMap::new(),
items,
@@ -347,6 +440,11 @@ impl Sim {
waited: 0,
mapped: !smart,
});
// The smart enemy may send a small recon flight ahead of the strike -- physically in
// the air, not a pause: the strike is planned while they fly (#135).
if smart {
self.start_recon(objects, bearing, order.dist, out);
}
// A raid without routes is ready at once.
self.plan_step(None, out);
total
@@ -423,10 +521,7 @@ impl Sim {
from.y = floor;
d.pos.y = floor;
if spec.ballistic.is_some() {
let aimed = aim + d.err;
let flat = horizontal(aimed - from);
let time = (flat.length() / spec.speed).max(30.0);
d.vel = flat / time + DVec3::Y * ((aimed.y - from.y + 0.5 * GRAVITY * time * time) / time);
d.vel = ballistic_velocity(from, d.target, spec.speed);
}
}
}
@@ -437,7 +532,7 @@ impl Sim {
None => {
if !plan.prices.contains_key(&kind) {
let heights = (!plan.heights.is_empty()).then_some(plan.heights.as_slice());
let (p, cost) = self.price_grid_on(&plan.grid, kind, heights);
let (p, cost) = self.price_grid_on(&plan.grid, kind, heights, &plan.knowledge);
work += cost;
plan.prices.insert(kind, p);
}
@@ -445,6 +540,7 @@ impl Sim {
heights: &plan.heights,
slope: (kind.climb_pitch().tan() * 0.5) as f32,
floor: (aim.y + spec.clearance) as f32,
unknown: 0.0,
});
let (r, cost) = plan_route_on(&plan.grid, &plan.prices[&kind], relief.as_ref(), from, aim);
work += cost;
@@ -472,6 +568,7 @@ impl Sim {
// Timing: smart raids arrive at once; others leave at once (a moment apart).
let now = self.tick;
let arrive = plan.done.iter().map(|(_, t, e, g, _)| t + e - g).fold(0.0, f64::max);
let unit_strikes = plan.done.iter().filter(|(d, ..)| d.aim.unit != 0).count() as u32;
for (mut d, time, early, gap, site) in plan.done {
d.smart = plan.smart;
let wait = if plan.smart { arrive - (early - gap) - time } else { gap + self.rng.f() * 40.0 };
@@ -480,6 +577,19 @@ impl Sim {
}
self.queue.push((now + wait.clamp(0.0, LONGEST_WAIT) as u64, d));
}
// Keep the land this plan was worked out over (#127): a retarget later is planned over the same
// known relief, not over ground mapped since.
if plan.smart && !plan.heights.is_empty() {
self.known_relief = Some(std::sync::Arc::new(ew::KnownRelief::new(plan.grid, std::mem::take(&mut plan.heights))));
}
// The bounded refresh moment for the unreleased portion (#149): a recon flight is still
// out, so a report may arrive while the drones wait to launch, and the plan's own picks
// may be re-aimed once on it. The deadline is absolute and the launches keep their times
// — no report never pauses the raid.
if plan.smart && !self.smart_legacy && !self.recon.sorties.is_empty() {
self.refresh = Some(ew::Refresh { deadline: self.tick + ew::REFRESH_WINDOW, reports: self.recon.reports });
}
self.diversions_left = unit_strike_limit(plan.total).saturating_sub(unit_strikes);
self.wave = Some(WaveStats {
kills: self.kills,
hits: self.hits,
@@ -495,11 +605,38 @@ impl Sim {
out.sound("minecraft:event.raid.horn", plan.centre, 64.0, 1.0);
}
/// Start a new scenario with a fresh enemy picture while preserving the player's layout.
pub fn reset_raid_intelligence(&mut self) {
self.intel = ew::Intel::default();
self.recon = recon::Recon::default();
self.bearing = ew::BearingReport::default();
self.refresh = None;
}
/// Whether a raid is still being planned.
pub fn planning(&self) -> bool {
self.plan.is_some()
}
/// The plan's drones and the structured intent each was given (#127; tests and diagnostics).
#[cfg(test)]
pub(super) fn planned_intents(&self) -> Vec<(u32, ew::Intent)> {
self.plan.as_ref().map(|p| p.items.iter().map(|i| (i.d.id, i.d.intent)).collect()).unwrap_or_default()
}
/// The plan's unit aims and their intent: the same list, keyed by what the drone goes for.
#[cfg(test)]
pub(super) fn planned_aims(&self) -> Vec<(u32, ew::Intent)> {
self.plan.as_ref().map(|p| p.items.iter().map(|i| (i.d.aim.unit, i.d.intent)).collect()).unwrap_or_default()
}
/// The plan's grid, land, knowledge version and the prices worked out so far (#146; tests).
#[cfg(test)]
pub(super) fn plan_pricing(&self) -> Option<(Grid, Vec<f32>, ew::KnowledgeSnapshot, HashMap<DroneKind, Vec<f32>>)> {
let p = self.plan.as_ref()?;
Some((p.grid, p.heights.clone(), p.knowledge.clone(), p.prices.clone()))
}
/// A drone ready to fly from `from`, not yet in the sky.
pub(super) fn make_drone(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3) -> Drone {
let id = self.id();
@@ -509,10 +646,7 @@ impl Sim {
let err = self.aim_error(kind);
let target = target + err;
let (vel, flight) = if spec.ballistic.is_some() {
let flat = horizontal(target - from);
let time = (flat.length() / spec.speed).max(30.0);
let up = (target.y - from.y + 0.5 * GRAVITY * time * time) / time;
(flat / time + DVec3::Y * up, Flight::Ballistic)
(ballistic_velocity(from, target, spec.speed), Flight::Ballistic)
} else {
(dir.normalize_or(DVec3::NEG_Z) * spec.speed, Flight::Cruise)
};
@@ -534,6 +668,8 @@ impl Sim {
smart: false,
nav: Nav::default(),
err,
intent: ew::Intent::Plan,
aim: ew::Aim::point(0),
hold: 0,
pace: Pace::default(),
}
@@ -542,23 +678,49 @@ impl Sim {
/// The strikes a smart raid sends at observed radars: for drones of `kinds` in order,
/// the last observed place and id for those that go for one. Each radar
/// gets two or three, the fast strikers first, and all together no more than about a quarter of the raid.
pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)]) -> Vec<Option<(DVec3, u32)>> {
let mut radars: Vec<(u32, DVec3)> = self.known_units().into_iter()
.filter(|(id, _)| self.sams.iter().any(|s| s.id == *id && s.alive() && s.kind == SamKind::Radar))
.collect();
radars.sort_by_key(|(id, _)| *id);
/// Only contacts the picture still trusts: a doubtful one (aged, never re-seen) is not worth a missile.
pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)], picture: &[ew::Contact], leads: &[recon::Mark]) -> Vec<Option<(DVec3, u32)>> {
// Radars the picture trusts, best first. The candidate ranks the one merged hint list on
// the single public scale (#149): a mark matched to a contact is not a second radar. The
// legacy mode keeps the two chains and their old scales. The order is the observed role,
// freshness and quality -- never the id (#135). Both lists are the order's own knowledge
// version, not a later picture (#146).
let now = self.tick;
let mut radars: Vec<(u8, u64, u32, DVec3)> = if self.smart_legacy {
picture
.iter()
.filter(|c| c.kind == SamKind::Radar && c.confidence(now) >= ew::Confidence::Probable)
.map(|c| {
let seen = match c.confidence(now) {
ew::Confidence::Confirmed => 4,
ew::Confidence::Probable => 2,
ew::Confidence::Doubtful => 0,
};
(seen * 10 + 3, c.tick, c.id, c.at)
})
.chain(leads.iter().copied().filter(|m| m.category == recon::Category::Radar && m.confidence(now) >= ew::Confidence::Probable).map(|m| (m.priority(now), m.observed, m.id, m.area)))
.collect()
} else {
observe::merge(picture, leads, now)
.into_iter()
.filter(|o| o.category == recon::Category::Radar && o.confidence(now) >= ew::Confidence::Probable)
.map(|o| (o.rank(now), o.observed, o.id, o.at))
.collect()
};
radars.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2)));
let radars: Vec<(u32, DVec3)> = radars.into_iter().map(|(_, _, id, at)| (id, at)).collect();
let flat: Vec<DroneKind> = kinds.iter().flat_map(|&(k, n)| std::iter::repeat_n(k, n as usize)).collect();
let mut jobs = vec![None; flat.len()];
if radars.is_empty() {
return jobs;
}
// Fast ones first (a stable sort keeps the raid's order among equals).
const RANK: [DroneKind; 8] =
[DroneKind::Kh22, DroneKind::Zircon, DroneKind::Iskander, DroneKind::Kinzhal, DroneKind::Kh101, DroneKind::Geran3, DroneKind::Lancet, DroneKind::Shahed];
const RANK: [DroneKind; 6] =
[DroneKind::Kh22, DroneKind::Zircon, DroneKind::Kh101, DroneKind::Geran3, DroneKind::Lancet, DroneKind::Shahed];
let mut ranked: Vec<(usize, usize)> = flat.iter().enumerate().filter_map(|(i, k)| Some((RANK.iter().position(|r| r == k)?, i))).collect();
ranked.sort_by_key(|r| r.0);
let want = if flat.len() >= 24 { 3 } else { 2 };
let cap = (flat.len() / 4).max(1);
let cap = unit_strike_limit(flat.len() as u32) as usize;
for (n, &(_, i)) in ranked.iter().take((radars.len() * want).min(cap)).enumerate() {
let radar = radars[n % radars.len()];
jobs[i] = Some((radar.1, radar.0));
@@ -566,101 +728,155 @@ impl Sim {
jobs
}
/// What a drone goes for: an object, or (by its kind and the raid's aim) a system. Returns the
/// point and the system's id.
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim) -> (DVec3, Option<u32>) {
let alive: Vec<&Sam> = self.sams.iter().filter(|s| s.alive()).collect();
if alive.is_empty() || kind.spec().decoy || aim == Aim::Objects {
/// What a drone goes for: an object, or (by its kind and the raid's aim) a unit. Returns the
/// point and the unit's id. The planner has only the picture (#93, #127): what it knows of a
/// unit is the last observation — the place seen then, the type identified then — never where
/// the unit actually is or what it has become since.
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact], leads: &[recon::Mark]) -> (DVec3, Option<u32>) {
if kind.spec().class == Class::Ballistic || kind.spec().decoy || aim == Aim::Objects || (picture.is_empty() && leads.is_empty()) {
return (object, None);
}
let pick = |list: &[&Sam], r: f64| -> Option<(DVec3, u32)> {
(!list.is_empty()).then(|| {
let s = list[(r * list.len() as f64) as usize % list.len()];
(s.pos, s.id)
})
let pick = |list: &[ew::Contact], r: f64| -> Option<(DVec3, u32)> {
let c = list.get((r * list.len() as f64) as usize)?;
Some((c.at, c.id))
};
let r = self.rng.f();
let roll = self.rng.f();
if aim == Aim::ObjectsAndSams {
return if roll < 0.33 { pick(&alive, r).map_or((object, None), |(p, id)| (p, Some(id))) } else { (object, None) };
return if roll < 0.33 { pick(picture, r).map_or((object, None), |(p, id)| (p, Some(id))) } else { (object, None) };
}
// Smart: each kind at what it is good against; what gave itself away first (a jamming
// The candidate picks from the one merged hint list (#149): a matched mark is not a
// second target, and the fit is the small public policy, not a per-kind guess.
if !self.smart_legacy {
let obs = observe::merge(picture, leads, self.tick);
let pick_o = |list: &[&Observation], r: f64| -> Option<(DVec3, u32)> {
let o = list.get((r * list.len() as f64) as usize)?;
Some((o.at, o.id))
};
let jammers: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Ew && o.channel == recon::Source::Jamming).collect();
if matches!(kind, DroneKind::Lancet | DroneKind::Kh22) && !jammers.is_empty() && roll < 0.6 {
if let Some((at, id)) = pick_o(&jammers, r) {
return (at, Some(id));
}
}
let guns: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Gun || o.kind.is_some_and(|k| k.armed() && k.range() <= 350.0)).collect();
let long: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Radar || o.kind.is_some_and(|k| k.range() >= 450.0)).collect();
let all: Vec<&Observation> = obs.iter().collect();
let choice = match kind {
DroneKind::Lancet if roll < 0.75 => pick_o(&guns, r).or_else(|| pick_o(&all, r)),
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick_o(&long, r),
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick_o(&all, r),
_ => None,
};
if let Some((at, id)) = choice {
return (at, Some(id));
}
// Nothing the kind's usual preference picked: an unmerged mark whose observed
// category fits is the next best reason to turn a strike off the object.
let fits: Vec<&Observation> = obs.iter().filter(|o| o.kind.is_none() && observe::fits(kind, o.category)).collect();
if let Some((at, id)) = pick_o(&fits, r) {
return (at, Some(id));
}
return (object, None);
}
// Legacy smart: each kind at what it is good against; what gave itself away first (a jamming
// station, a radar, a system that fired).
// The planner has only what the enemy knows (#93): the radars (they emit) and the units that gave
// themselves away; the rest of the player's layout is not in its hands.
let known = self.known_units();
let alive: Vec<&Sam> = alive.iter().copied().filter(|s| Self::enemy_knows(s, &known)).collect();
let pick_known = |list: &[&Sam], r: f64| -> Option<(DVec3, u32)> {
let s = *list.get((r * list.len() as f64) as usize)?;
known.iter().find(|(id, _)| *id == s.id).map(|(_, pos)| (*pos, s.id))
};
let known_ew: Vec<&Sam> = alive.iter().copied().filter(|s| s.kind == SamKind::Ew).collect();
let known_ew: Vec<ew::Contact> = picture.iter().copied().filter(|c| c.kind == SamKind::Ew).collect();
if matches!(kind, DroneKind::Lancet | DroneKind::Kh22) && !known_ew.is_empty() && roll < 0.6 {
let s = known_ew[(r * known_ew.len() as f64) as usize % known_ew.len()];
return (known.iter().find(|(id, _)| *id == s.id).unwrap().1, Some(s.id));
let c = known_ew[(r * known_ew.len() as f64) as usize % known_ew.len()];
return (c.at, Some(c.id));
}
// Short-range systems (guns, Tor, P1-SUN) for the Lancets; long-range ones and the radars
// that feed them for the fast missiles.
let guns: Vec<&Sam> = alive.iter().copied().filter(|s| s.kind.armed() && s.kind.range() <= 300.0).collect();
let long: Vec<&Sam> =
alive.iter().copied().filter(|s| s.kind.range() >= 450.0 || s.kind == SamKind::Radar).collect();
let guns: Vec<ew::Contact> = picture.iter().copied().filter(|c| c.kind.armed() && c.kind.range() <= 350.0).collect();
let long: Vec<ew::Contact> =
picture.iter().copied().filter(|c| c.kind.range() >= 450.0 || c.kind == SamKind::Radar).collect();
let choice = match kind {
DroneKind::Lancet if roll < 0.75 => pick_known(&guns, r).or_else(|| pick_known(&alive, r)),
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick_known(&long, r),
DroneKind::Iskander | DroneKind::Kinzhal if roll < 0.3 => pick_known(&long, r),
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick_known(&alive, r),
DroneKind::Lancet if roll < 0.75 => pick(&guns, r).or_else(|| pick(picture, r)),
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick(&long, r),
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick(picture, r),
_ => None,
};
choice.map_or((object, None), |(p, id)| (p, Some(id)))
if let Some((p, id)) = choice {
return (p, Some(id));
}
// Nothing disclosed and nothing the kind's usual preference picked: a recon mark
// whose observed role fits is the next best reason to turn a strike off the object.
if let Some(m) = recon_pick(kind, leads, r) {
return (m.area, Some(m.id));
}
(object, None)
}
/// The price of each cell of `grid` for this kind flying low: 1, and much more where a
/// system sees it there (its radar's reach for it, the land) and can shoot it.
#[cfg(test)]
pub(super) fn price_grid(&self, grid: &Grid, kind: DroneKind) -> (Vec<f32>, usize) {
self.price_grid_on(grid, kind, None)
self.price_grid_on(grid, kind, None, &self.knowledge_now())
}
/// The same over known land: a cell's drone flies `height` over the land there, not over the system's feet,
/// so what a radar sees and what a hill hides follow the relief.
pub(super) fn price_grid_on(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>) -> (Vec<f32>, usize) {
/// The same over a knowledge version given explicitly: a smart plan's prices are priced on the
/// snapshot the plan was ordered with (#127, #146), whenever the budget reaches this kind.
/// Later observations change nothing here.
pub(super) fn price_grid_on(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>, knowledge: &ew::KnowledgeSnapshot) -> (Vec<f32>, usize) {
self.price_grid_known(grid, kind, land, knowledge)
}
/// The same over a snapshot of the defences: a retarget is priced on the knowledge its target was
/// chosen from, so the jobs of one adaptive tick do not each see a different world (#127), and a
/// job reached on a later tick still ages its contacts at its own version's tick (#146). Every
/// capability read here is the contact's published kind and the contact's own observations —
/// never the unit's actual switch settings, damage, roles, link health or magazine.
pub(super) fn price_grid_known(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>, knowledge: &ew::KnowledgeSnapshot) -> (Vec<f32>, usize) {
let mut cost = 0;
let spec = kind.spec();
let height = spec.clearance.max(6.0);
let known_now = self.known_units();
let n = grid.size;
let now = knowledge.tick;
let picture = &knowledge.contacts;
let mut prices = vec![1.0f32; (n * n) as usize];
// Known jamming stations: drones that navigate by satellite keep away.
if kind.jammable() {
let known = self.known_units();
for s in self.sams.iter().filter(|s| s.kind == SamKind::Ew && s.alive() && known.iter().any(|k| k.0 == s.id)) {
let pos = known.iter().find(|(id, _)| *id == s.id).unwrap().1;
let (ci, cj) = grid.index(pos);
let r = (EW_RADIUS / grid.cell).ceil() as i32;
for c in picture.iter().filter(|c| c.kind == SamKind::Ew) {
let (ci, cj) = grid.index(c.at);
let r = (ew::EW_RADIUS / grid.cell).ceil() as i32;
for i in (ci - r).max(0)..=(ci + r).min(n - 1) {
for j in (cj - r).max(0)..=(cj + r).min(n - 1) {
if horizontal(grid.centre((i, j), pos.y) - pos).length() < EW_RADIUS {
if horizontal(grid.centre((i, j), c.at.y) - c.at).length() < ew::EW_RADIUS {
prices[(i * n + j) as usize] += 12.0;
}
}
}
}
}
// Only the systems the enemy knows of are priced in (#93): a hidden one is flown into.
for s in self.sams.iter().filter(|s| s.alive() && s.roles & spec.class.bit() != 0 && Self::enemy_knows(s, &known_now)) {
let pos = known_now.iter().find(|(id, _)| *id == s.id).unwrap().1;
let sp = s.kind.spec();
// Only the systems the picture holds are priced in (#93): a hidden one is flown into.
for c in picture.iter().filter(|c| c.kind.spec().roles & spec.class.bit() != 0) {
let pos = c.at;
let sp = c.kind.spec();
let (lo, hi) = sp.missile.as_ref().map_or((0.0, 0.0), |m| (m.min, m.max));
let gun = sp.gun.as_ref().map_or(0.0, |g| g.range);
// A gun needs its own radar; a missile also flies on the tracks of any radar within data-link range.
let own = sight::reach(s, kind, height);
let net = self.sams.iter().filter_map(|r| {
let at = known_now.iter().find(|(id, _)| *id == r.id)?.1;
(r.id != s.id && at.distance(pos) <= sight::LINK).then(|| sight::reach(r, kind, height))
}).fold(0.0, f64::max);
// A gun needs its own radar; a missile also flies on the tracks of any radar the picture
// holds within data-link range of the unit's observed place. What those radars are set to
// (role, switch, damage) is not observable: a live contact of one is assumed to feed.
let own = if c.believes_own_sensor(now) { ew::published_reach(c.kind, kind, height) } else { 0.0 };
let net = picture
.iter()
.filter(|d| d.kind == SamKind::Radar && d.id != c.id && d.at.distance(pos) <= sight::LINK)
.map(|d| ew::published_reach(d.kind, kind, height))
.fold(0.0, f64::max);
// A trusted radar mark near the observed place feeds the network too (#149): the
// strongest published radar reach, since the mark does not name the kind.
let net = if self.smart_legacy {
net
} else {
knowledge.marks
.iter()
.filter(|m| m.category == recon::Category::Radar && m.confidence(now) >= ew::Confidence::Probable && m.area.distance(pos) <= sight::LINK)
.map(|_| observe::radar_envelope(kind, height))
.fold(net, f64::max)
};
let (hi, gun) = (hi.min(own.max(net)), gun.min(own));
let far = hi.max(gun);
let at = pos + (sight::antenna(s) - s.pos);
let horizon = (pos == s.pos).then(|| self.horizons.get(&s.id)).flatten();
// Only the cells round it.
let (ci, cj) = grid.index(pos);
let r = (far / grid.cell).ceil() as i32 + 1;
@@ -677,20 +893,61 @@ impl Sim {
if !(missile || d < gun) {
continue;
}
if horizon.is_some_and(|h| h.hides(at, p)) {
continue;
}
prices[(i * n + j) as usize] += if missile { 30.0 } else { 18.0 };
}
}
}
// The marks the contacts do not already stand for (#149): an area is priced by its public
// category's published envelope, weighted by the confidence the age alone gives. A mark
// matched to a contact is one hint and was priced through the contact above.
if !self.smart_legacy {
for o in knowledge.observations().into_iter().filter(|o| o.kind.is_none() && o.confidence(now) >= ew::Confidence::Probable) {
let scale: f32 = if o.confidence(now) == ew::Confidence::Confirmed { 1.0 } else { 0.5 };
let pos = o.at;
match o.category {
recon::Category::Ew if kind.jammable() => {
let reach = ew::EW_RADIUS + o.radius;
let (ci, cj) = grid.index(pos);
let r = (reach / grid.cell).ceil() as i32;
for i in (ci - r).max(0)..=(ci + r).min(n - 1) {
for j in (cj - r).max(0)..=(cj + r).min(n - 1) {
cost += 1;
if horizontal(grid.centre((i, j), pos.y) - pos).length() < reach {
prices[(i * n + j) as usize] += 12.0 * scale;
}
}
}
}
recon::Category::Launcher | recon::Category::Gun => {
let (lo, hi, gun) = observe::category_envelope(o.category);
let far = hi.max(gun) + o.radius;
let (ci, cj) = grid.index(pos);
let r = (far / grid.cell).ceil() as i32 + 1;
for i in (ci - r).max(0)..=(ci + r).min(n - 1) {
for j in (cj - r).max(0)..=(cj + r).min(n - 1) {
cost += 1;
let ground = land.map(|l| l[(i * n + j) as usize]).filter(|g| g.is_finite());
let p = grid.centre((i, j), ground.map_or(pos.y + height, |g| f64::from(g) + height));
let d = horizontal(p - pos).length();
if d > far {
continue;
}
let missile = (lo..hi).contains(&d);
if !(missile || d < gun) {
continue;
}
prices[(i * n + j) as usize] += (if missile { 30.0 } else { 18.0 }) * scale;
}
}
}
_ => {}
}
}
}
(prices, cost)
}
/// Ticks an air start waits for the land under it to be told of.
const AIR_START_WAIT: u32 = 120;
/// A planned raid's drones take off when their time comes.
/// A planned raid's drones take off when their time comes.
pub(super) fn release_queue(&mut self, ground: &mut Ground, out: &mut Out) {
let now = self.tick;
if self.queue.iter().all(|q| q.0 > now) {
@@ -702,25 +959,24 @@ const AIR_START_WAIT: u32 = 120;
for (t, mut d) in go {
// A site's job leaves its site one at a time, from its stock; a destroyed or empty site cancels it.
let from_site = self.sites.site_of(d.id);
// An air start (an off-map site's drone) was planned over land nobody had read. It waits (a second or
// two) for the land under it to be known, and begins above it if that is higher than the start: else it
// is born inside a hill and crashes at once.
let air = from_site.is_some_and(|id| self.sites.list.iter().any(|s| s.id == id && s.offmap));
if air {
let clear = if d.kind.spec().ballistic.is_some() { 10.0 } else { d.kind.spec().clearance };
match ground.at(d.pos, now) {
None if d.age < AIR_START_WAIT => {
// The game has no chunk there: it is asked to load the ones round the start (and kept a while).
let c = ((d.pos.x.floor() as i32) >> 4, (d.pos.z.floor() as i32) >> 4);
for (dx, dz) in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)] {
ground.want_chunk((c.0 + dx, c.1 + dz));
}
d.age += 1;
self.queue.push((t, d));
continue;
}
Some(g) if d.pos.y < g + clear => d.pos.y = g + clear,
_ => {}
if let Some(site) = from_site.and_then(|id| self.sites.get(id)).filter(|s| s.alive && s.stock > 0) {
if site.next_free > now {
self.queue.push((t, d));
continue;
}
let (floor, pending) = launch_floor(ground, &d, site.offmap);
if site.offmap && pending && d.age < AIR_START_WAIT {
d.age += 1;
self.queue.push((t, d));
continue;
}
d.pos.y = if site.offmap && pending {
floor.max(VANILLA_BUILD_CEILING + 10.0 + d.kind.spec().clearance)
} else {
floor
};
if d.flight == Flight::Ballistic {
d.vel = ballistic_velocity(d.pos, d.target, d.kind.spec().speed);
}
d.age = 0;
}
@@ -729,11 +985,7 @@ const AIR_START_WAIT: u32 = 120;
self.scout_launch(d.id, site, d.kind, d.pos);
}
match slot {
// Free: not a site's job. Air: an off-map site's drone, already in flight position.
sites::Slot::Free => {}
// The air start was planned over land nobody had read; if it is read by now and the land there is
// higher than the start, it begins above it (else it is born inside a hill and crashes at once).
sites::Slot::Air => {}
sites::Slot::Free | sites::Slot::Air => {}
sites::Slot::Busy => {
self.queue.push((t, d));
continue;
@@ -743,20 +995,13 @@ const AIR_START_WAIT: u32 = 120;
continue;
}
sites::Slot::Go => {
// On a slope the pad's side or the muzzle's far end can stand in the land that rises there: the
// drone leaves from above the land at its own column, not from inside the hill.
if let Some(g) = ground.at(d.pos, now)
&& d.pos.y < g + 1.5
&& g < d.pos.y + 40.0
{
d.pos.y = g + 1.5;
}
let dir = d.vel.normalize_or_zero();
out.sound(d.kind.launch_sound(), d.pos, 1.0, 1.0);
out.particles("minecraft:flame", d.pos - dir * 1.5, 0.15, -dir * 0.1, 0.02, 4);
out.particles("minecraft:large_smoke", d.pos - dir * 2.5, 0.5, DVec3::new(0.0, 0.05, 0.0), 0.02, 4);
}
}
self.breakthroughs.begin(d.id, true);
self.drones.push(d);
self.launched += 1;
}
@@ -840,9 +1085,7 @@ const AIR_START_WAIT: u32 = 120;
it.from = from;
it.d.pos = from;
if spec.ballistic.is_some() {
let flat = horizontal(it.d.target - from);
let time = (flat.length() / spec.speed).max(30.0);
it.d.vel = flat / time + DVec3::Y * ((it.d.target.y - from.y + 0.5 * GRAVITY * time * time) / time);
it.d.vel = ballistic_velocity(from, it.d.target, spec.speed);
} else {
let pitch = site.class.pitch();
let dir = horizontal(it.d.target - from).normalize_or(site.inward());
@@ -900,6 +1143,11 @@ const AIR_START_WAIT: u32 = 120;
if !why.is_empty() {
out.messages.push(format!("Неудачи ПВО: {why}"));
}
// What the enemy's recon flights saw: the marks are memory, so the picture may be old (#135).
let marks = self.recon.marks.values().filter(|m| m.live(self.tick)).count();
if marks > 0 {
out.messages.push(format!("Разведка противника: в картине {marks} отметок (возраст и качество — в разборе)"));
}
// What the counter-strikes did to the raid (#101): the launches that never happened.
let cut: u32 = self.strikes.cancelled.iter().map(|c| c.1).sum();
if cut > 0 {
@@ -921,6 +1169,20 @@ fn route_length(from: DVec3, route: &[DVec3], to: DVec3) -> f64 {
len
}
/// A recon mark whose observed category fits this kind. The list is already in priority
/// order, so the first fit is the best reason.
fn recon_pick(kind: DroneKind, leads: &[recon::Mark], r: f64) -> Option<recon::Mark> {
use recon::Category as C;
let fits = |c: C| match kind {
DroneKind::Lancet => matches!(c, C::Gun | C::Launcher | C::Ew),
DroneKind::Kh22 | DroneKind::Zircon => matches!(c, C::Radar | C::Launcher | C::Ew),
DroneKind::Shahed | DroneKind::Geran3 => matches!(c, C::Radar | C::Launcher | C::Gun | C::Ew),
_ => false,
};
let fits: Vec<&recon::Mark> = leads.iter().filter(|m| fits(m.category)).collect();
fits.get((r * fits.len() as f64) as usize).copied().copied()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -971,24 +1233,68 @@ mod tests {
sim.drones.iter().chain(sim.queue.iter().map(|q| &q.1)).filter(|d| d.alive() && (d.target - d.err).distance(p) < 6.0).map(|d| d.kind).collect()
}
#[test]
fn smart_waves_reserve_ballistics_and_the_bulk_of_the_raid_for_marked_objects() {
let mut sim = Sim::new(32);
let object = DVec3::new(0.0, 70.0, 0.0);
let kinds = [(DroneKind::Kinzhal, 2), (DroneKind::Iskander, 2), (DroneKind::Oreshnik, 1),
(DroneKind::Kh22, 10), (DroneKind::Shahed, 25)];
for (i, kind) in [SamKind::Radar, SamKind::Pantsir, SamKind::Radar, SamKind::Gepard].into_iter().enumerate() {
let id = sim.id();
let sam = Sam::new(id, kind, DVec3::new(100.0 * i as f64 + 50.0, 70.0, 0.0), 0.0);
sim.intel.observe(&sam, sim.tick, ew::Seen::Emission);
sim.sams.push(sam);
}
let order = RaidOrder { kinds: kinds.to_vec(), approach: Approach::Waves, dist: 400.0, aim: Aim::Smart };
let mut out = Out::default();
sim.order_raid(&order, &[object], &mut out);
let items = &sim.plan.as_ref().unwrap().items;
let ballistic: Vec<_> = items.iter().filter(|item| item.d.kind.spec().class == Class::Ballistic).collect();
assert_eq!(ballistic.len(), 5);
assert!(ballistic.iter().all(|item| item.d.aim.unit == 0 && item.aim.distance(object) < 6.0));
let attacks_on_units = items.iter().filter(|item| item.d.aim.unit != 0).count();
assert!((1..=10).contains(&attacks_on_units), "{attacks_on_units}");
}
#[test]
fn the_launch_floor_checks_the_near_slope_between_coarse_terrain_samples() {
let mut sim = Sim::new(2);
let d = sim.make_drone(DroneKind::Shahed, DVec3::new(0.5, 86.0, 0.5), DVec3::X, DVec3::new(400.0, 64.0, 0.5));
let mut ground = Ground::default();
let unattained = launch_floor(&mut ground, &d, true);
assert!(unattained.1);
let land = Land(|x, _| if x == 5 { 160 } else { 64 });
serve(&mut ground, &land, 1);
let (floor, pending) = launch_floor(&mut ground, &d, true);
assert!(!pending);
assert!(floor > 160.0, "{floor}");
}
#[test]
fn sead_uses_only_unexpired_observations_at_the_last_known_position() {
let mut sim = Sim::new(121);
let old = DVec3::new(100.0, 70.0, 200.0);
let mut radar = Sam::new(1, SamKind::Radar, old, 0.0);
radar.radar_on = false;
let radar = Sam::new(1, SamKind::Radar, old, 0.0);
sim.sams.push(radar);
let kinds = [(DroneKind::Kh22, 8)];
assert!(sim.radar_strikes(&kinds).iter().all(Option::is_none));
let none = Vec::new();
assert!(sim.radar_strikes(&kinds, &none, &[]).iter().all(Option::is_none));
sim.tick = 20;
sim.intel.revealed.push((1, old, sim.tick));
sim.intel.observe(&sim.sams[0], sim.tick, ew::Seen::Emission);
// The truth moving after the fix is not an observation: the strike goes to the seen place.
sim.sams[0].pos = DVec3::new(900.0, 70.0, 900.0);
sim.tick = 40;
let jobs = sim.radar_strikes(&kinds);
let picture = sim.picture_of_defences();
let jobs = sim.radar_strikes(&kinds, &picture, &[]);
assert_eq!(jobs.iter().flatten().count(), 2);
assert!(jobs.iter().flatten().all(|job| *job == (old, 1)));
// An old contact is not worth a strike either.
sim.tick = 3021;
let picture = sim.picture_of_defences();
assert!(sim.radar_strikes(&kinds, &picture, &[]).iter().all(Option::is_none), "a doubtful contact was struck");
sim.tick = 6020;
assert!(sim.radar_strikes(&kinds).iter().all(Option::is_none));
let picture = sim.picture_of_defences();
assert!(sim.radar_strikes(&kinds, &picture, &[]).iter().all(Option::is_none));
}
#[test]
@@ -998,9 +1304,10 @@ mod tests {
for (i, at) in [(-300.0, -200.0), (250.0, -250.0), (50.0, 300.0)].into_iter().enumerate() {
let id = sim.id();
let p = DVec3::new(at.0, 70.0, at.1);
sim.sams.push(Sam::new(id, SamKind::Radar, p, i as f64));
let sam = Sam::new(id, SamKind::Radar, p, i as f64);
sim.intel.observe(&sam, sim.tick, ew::Seen::Emission);
sim.sams.push(sam);
radars.push((id, p));
sim.intel.revealed.push((id, p, sim.tick));
}
let ew = sim.id();
sim.sams.push(Sam::new(ew, SamKind::Ew, DVec3::new(0.0, 70.0, 0.0), 0.0));
@@ -1036,7 +1343,7 @@ mod tests {
// The first strikers are the fast ones.
assert!(radars.iter().any(|(_, p)| aimed_at(&sim, *p).iter().any(|k| matches!(k, DroneKind::Kh22 | DroneKind::Zircon | DroneKind::Iskander | DroneKind::Kinzhal))));
// The enemy has learnt of the jamming station and re-aims what it can: not these.
sim.intel.revealed.push((ew, DVec3::new(0.0, 70.0, 0.0), sim.tick));
sim.intel.observe(&sim.sams.iter().find(|s| s.id == ew).unwrap(), sim.tick, ew::Seen::Jamming);
for _ in 0..160 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
@@ -1044,6 +1351,97 @@ mod tests {
check(&sim, "after adapting");
}
/// The picture the planner works from: one contact per unit, the newest observation
/// winning, the forgotten and the watched-dead out, the order deterministic — and it
/// never reads the force itself, so a contact of a unit that no longer exists stays
/// until its observations age out.
#[test]
fn picture_is_newest_per_unit_and_reads_no_truth() {
let mut sim = Sim::new(9);
let mut ids = Vec::new();
for (i, kind) in [SamKind::S400, SamKind::Ew, SamKind::Radar, SamKind::Tor, SamKind::Patriot].into_iter().enumerate() {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DVec3::new(i as f64 * 100.0, 70.0, -50.0), 0.0));
ids.push(id);
}
sim.tick = 7000;
let (a, b, c, d, e) = (ids[0], ids[1], ids[2], ids[3], ids[4]);
// A long fight: repeated observations (newest wins), one unit watched dying, one
// never seen, one id the force does not have, and one observation that aged out.
for t in 0..200u64 {
sim.intel.observe(&sim.sams[0], 1000 + t, ew::Seen::Launch);
sim.intel.observe(&sim.sams[2], 1000 + t, ew::Seen::Emission);
if t % 7 == 0 { sim.intel.observe(&sim.sams[1], 1000 + t, ew::Seen::Jamming); }
if t % 11 == 0 { sim.intel.observe(&sim.sams[3], 1000 + t, ew::Seen::Launch); }
if t % 13 == 0 {
sim.intel.note(999_999, SamKind::Radar, DVec3::new(1.0, 70.0, 0.0), true, 1000 + t, ew::Seen::Emission);
}
}
sim.intel.note(e, SamKind::Patriot, DVec3::new(15.0, 70.0, 0.0), true, 2, ew::Seen::Launch); // aged out at tick 7000
// The EW station is watched dying by a strike: observed, and so out of the targets.
sim.intel.outcome(b, false, sim.sams[1].pos, 1349);
let picture = sim.picture_of_defences();
let got: Vec<u32> = picture.iter().map(|c| c.id).collect();
// a and c were both seen last at tick 1199 (tie: the newer id first); d at 1198; the
// fake at 1195. The watched-dead b, the never-seen e and the aged-out are out.
assert_eq!(got, vec![c, a, d, 999_999]);
assert_eq!(picture[0].at, DVec3::new(200.0, 70.0, -50.0), "the observed place is the unit's own");
assert_eq!(picture[0].seen, ew::Seen::Emission);
assert_eq!(picture[1].kind, SamKind::S400);
assert!(picture.iter().all(|c| c.id != b && c.id != e));
assert_eq!(sim.picture_of_defences(), picture, "the picture is not deterministic");
}
/// The reported Windows stop (#122): the second big order from the UI path, with a fat
/// intel log and a large surviving force, must be accepted and launched like the first.
/// (The old per-drone planner snapshot was correct but quadratic; its cost is pinned by
/// the actual-WASM fuel measurements in docs/measurements/issue-122-ui-fuel.)
#[test]
fn a_second_smart_order_with_a_fat_intel_log_is_accepted_and_launched() {
let mut sim = Sim::new(31);
let mut ids = Vec::new();
for i in 0..48 {
let id = sim.id();
sim.sams.push(Sam::new(id, [SamKind::S400, SamKind::Patriot, SamKind::Nasams, SamKind::Pantsir][i % 4], DVec3::new((i % 8 * 40) as f64, 70.0, (i / 8 * 40) as f64), 0.0));
ids.push(id);
}
// A fought-off first raid leaves a long observation history: launches, emitting
// radars, stations. Its entries sit in the past of the sim clock, like real ones.
sim.tick = 4000;
for t in 0..3000u64 {
let sam = &sim.sams[(t as usize) % ids.len()];
sim.intel.observe(sam, 1001 + t, if t % 3 == 0 { ew::Seen::Emission } else { ew::Seen::Launch });
}
sim.targets.push(DVec3::new(160.0, 70.0, 160.0));
sim.target_health.push(100.0);
let mut ground = Ground::default();
let land = Land(|_, _| 64);
let mut out = Out::default();
for _ in 0..20 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
let mut order = RaidOrder::mix(36, 300.0);
order.aim = Aim::Smart;
order.approach = Approach::AllSides;
let total: u32 = order.kinds.iter().map(|k| k.1).sum();
let first = sim.order_raid(&order, &sim.targets.clone(), &mut out);
assert_eq!(first, total);
while sim.planning() {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
assert!(sim.queue.len() + sim.launched as usize >= total as usize, "the first order queued or launched every drone (queue {}, launched {})", sim.queue.len(), sim.launched);
// The second order — the path that stopped the mod on Windows — is accepted too.
let second = sim.order_raid(&order, &sim.targets.clone(), &mut out);
assert_eq!(second, total);
while sim.planning() {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
assert!(sim.queue.len() + sim.launched as usize >= 2 * total as usize, "both orders queued or launched their drones (queue {}, launched {})", sim.queue.len(), sim.launched);
}
#[test]
fn systems_ready_together_send_one_missile_at_a_drone() {
let mut sim = Sim::new(3);
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+751 -32
View File
@@ -54,9 +54,9 @@ fn network_launcher_must_contribute_to_route_risk() {
// The planner prices only observed units; neither unit is known initially.
let (prices,_)=sim.price_grid(&grid,DroneKind::Shahed);
assert!(prices.iter().all(|p|*p==1.),"an unknown launcher must not be priced");
sim.intel.revealed.push((sim.sams[0].id,DVec3::new(0.,70.,0.),0));
// Both the launcher and its supporting radar have been observed.
sim.intel.revealed.push((sim.sams[1].id,DVec3::new(0.,70.,0.),0));
// The launcher is seen firing without a sensor of its own; the radar is fixed emitting.
sim.intel.observe(&sim.sams[0],0,ew::Seen::Launch);
sim.intel.observe(&sim.sams[1],0,ew::Seen::Emission);
let (prices,_)=sim.price_grid(&grid,DroneKind::Shahed);
assert!(prices.iter().any(|p|*p>1.),"armed launcher with a network radar is invisible to route risk");
}
@@ -131,11 +131,14 @@ fn retargeted_smart_drone_gets_a_route_round_the_defences() {
sim.sams.push(Sam::new(id, SamKind::Radar, DVec3::new(0.0, 70.0, 0.0), 0.0));
let goal = sim.id();
sim.sams.push(Sam::new(goal, SamKind::Ew, DVec3::new(0.0, 70.0, 1000.0), 0.0));
sim.intel.revealed.push((goal, DVec3::new(0.0, 70.0, 1000.0), 0));
// Its first target, a system that is destroyed by now.
sim.intel.observe(&sim.sams[2], 0, ew::Seen::Jamming);
// Its first target: a system the picture watched die — seen firing, then the enemy's
// munition watched the wreck. A unit destroyed unobserved would keep the drone coming.
let id = sim.id();
let mut wreck = Sam::new(id, SamKind::Patriot, DVec3::new(3000.0, 70.0, -1000.0), 0.0);
sim.intel.observe(&wreck, 0, ew::Seen::Launch);
wreck.health = 0.0;
sim.intel.outcome(wreck.id, false, wreck.pos, 0);
sim.sams.push(wreck);
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 100.0, -1000.0), DVec3::Z, DVec3::new(3000.0, 70.0, -1000.0));
sim.drones[0].pos = DVec3::new(0.0, 100.0, -1000.0);
@@ -147,24 +150,434 @@ fn retargeted_smart_drone_gets_a_route_round_the_defences() {
assert!(d.route.len() > 1, "no route after the new target: it flies straight through the defences");
}
// #31: a big cache of fresh columns is not scanned on every answer
// #127: a mass retarget works its route jobs out over the following ticks. No drone is left without a
// route by the budget, old safe routes are kept until their replacements are ready, and the queue never
// grows or repeats a drone.
#[cfg(test)]
fn mass_retarget_sim(seed: u64) -> (Sim, HashMap<u32, Vec<DVec3>>, u32) {
let mut sim = Sim::new(seed);
for i in 0..8 {
for j in 0..5 {
let at = DVec3::new(-560.0 + i as f64 * 160.0, 70.0, -320.0 + j as f64 * 160.0);
let id = sim.id();
let sam = Sam::new(id, SamKind::S400, at, 0.0);
// Every system is on the picture, its radar fixed emitting once.
sim.intel.observe(&sam, 0, ew::Seen::Emission);
sim.sams.push(sam);
}
}
let mut old = HashMap::new();
let mut empty = 0;
for i in 0..40 {
let from = DVec3::new(-1800.0, 100.0, -800.0 + i as f64 * 40.0);
let mut d = sim.make_drone(DroneKind::Kh22, from, DVec3::X, DVec3::new(1800.0, 70.0, 1800.0));
d.smart = true;
d.route = vec![from, DVec3::new(1800.0, 70.0, 1800.0)];
// The last drone starts with no route at all (a drone whose route was lost): its job must wait its
// budget, not be dropped, and must give it a route in the end.
if i == 39 {
d.route.clear();
empty = d.id;
}
old.insert(d.id, d.route.clone());
sim.queue.push((0, d));
}
(sim, old, empty)
}
#[cfg(test)]
fn flight_state(sim: &Sim) -> Vec<(u32, u64, u64, u64, Vec<(u64, u64, u64)>)> {
sim.queue
.iter()
.map(|(_, d)| {
let route = d.route.iter().map(|p| (p.x.to_bits(), p.y.to_bits(), p.z.to_bits())).collect();
(d.id, d.target.x.to_bits(), d.target.y.to_bits(), d.target.z.to_bits(), route)
})
.collect()
}
#[test]
fn big_ground_cache_is_swept_rarely() {
fn mass_retarget_finishes_its_route_jobs_over_the_budget() {
let (mut sim, old, empty) = mass_retarget_sim(7);
sim.tick = 40;
sim.adapt();
let pending = sim.retarget_ids();
assert!(!pending.is_empty(), "the budget planned all 40 routes: the test no longer covers the queue");
assert_eq!(pending.len(), pending.iter().collect::<std::collections::HashSet<_>>().len(), "duplicate jobs");
// Assignments are throttled too: one adaptive tick hands out a bounded number of new aims,
// and the rest of the force is sent on the following adaptive ticks (#127).
assert!(pending.len() <= super::ew::ASSIGN_PER_TICK, "one adaptive tick assigned {} drones", pending.len());
for id in &pending {
let d = &sim.queue.iter().find(|(_, d)| d.id == *id).unwrap().1;
assert_eq!(&d.route, old.get(id).unwrap(), "an old safe route was replaced before the new one was ready");
}
let mut left = pending.len();
for _ in 0..400 {
sim.tick += 1;
sim.adapt();
if sim.tick % 40 == 0 {
// A new adaptive tick: more drones may be sent, still within the throttle.
let now = sim.retarget_ids().len();
assert!(now <= left + super::ew::ASSIGN_PER_TICK, "an adaptive tick assigned more than {} drones", super::ew::ASSIGN_PER_TICK);
left = now;
} else if left > 0 {
assert!(sim.retargets.len() < left, "a budget tick made no progress: {left} jobs left");
left = sim.retargets.len();
}
let still = sim.retarget_ids();
assert!(
// A drone the throttle has not sent yet is still on its own plan's route or has none to lose;
// one already sent at a unit whose route is empty must have a job that will fill it.
sim.queue.iter().all(|(_, d)| !d.route.is_empty() || still.contains(&d.id) || d.aim.unit == 0),
"a route is still empty with no job left to fill it"
);
}
assert_eq!(sim.retargets.len(), 0, "route jobs were never finished");
// No drone is left with an empty route for ever, and every new route ends at its aim. The drone
// that started with no route at all got one too: its job waited for the budget, not for ever.
for (_, d) in &sim.queue {
assert!(!d.route.is_empty(), "a drone was left with no route");
assert!(d.route.last().is_some_and(|p| p.distance(d.target) < 1e-6), "the new route does not end at the new aim");
assert!(d.aim.unit != 0, "a drone was never sent at a unit");
}
let empty = sim.queue.iter().find(|(_, d)| d.id == empty).unwrap().1.clone();
assert!(!empty.route.is_empty(), "the drone that started with no route never got one");
}
#[test]
fn mass_retarget_is_deterministic_and_never_duplicates_a_drone() {
let (mut a, _, _) = mass_retarget_sim(11);
let (mut b, _, _) = mass_retarget_sim(11);
a.tick = 40;
b.tick = 40;
a.adapt();
b.adapt();
assert_eq!(a.retarget_ids(), b.retarget_ids(), "the same seed left a different queue");
assert_eq!(flight_state(&a), flight_state(&b), "the same seed planned different routes");
for _ in 0..80 {
a.adapt();
b.adapt();
let ids = a.retarget_ids();
assert_eq!(ids.len(), ids.iter().collect::<std::collections::HashSet<_>>().len(), "a drone has two jobs");
assert_eq!(a.retarget_ids(), b.retarget_ids(), "the queues drifted apart");
assert_eq!(flight_state(&a), flight_state(&b), "the routes drifted apart");
if ids.is_empty() {
break;
}
a.tick += 1;
b.tick += 1;
// Another adaptive tick while the queue is still being worked: a known aim must not enqueue again.
if a.tick % 40 == 0 {
a.adapt();
b.adapt();
let ids = a.retarget_ids();
assert_eq!(ids.len(), ids.iter().collect::<std::collections::HashSet<_>>().len(), "a repeat adapt duplicated a job");
}
}
}
#[cfg(test)]
fn relief_grid() -> Grid {
Grid { min: DVec3::new(-2560.0, 0.0, -2560.0), cell: 32.0, size: 160 }
}
#[cfg(test)]
fn flat_relief() -> std::sync::Arc<super::ew::KnownRelief> {
let g = relief_grid();
std::sync::Arc::new(super::ew::KnownRelief::new(g, vec![70.0; (g.size * g.size) as usize]))
}
#[cfg(test)]
fn wall_relief() -> std::sync::Arc<super::ew::KnownRelief> {
let g = relief_grid();
let mut h = vec![70.0; (g.size * g.size) as usize];
for i in 0..g.size {
for j in 0..g.size {
let x = g.min.x + (f64::from(i) + 0.5) * g.cell;
let z = g.min.z + (f64::from(j) + 0.5) * g.cell;
// The wall spans every approach lane: whichever drone the adaptive tick leaves last,
// its east-west route crosses the ridge, so the two relief versions must differ (#149).
if (x + 1000.0).abs() < 80.0 && z.abs() < 2000.0 {
h[(i * g.size + j) as usize] = 1000.0;
}
}
}
std::sync::Arc::new(super::ew::KnownRelief::new(g, h))
}
#[cfg(test)]
fn finish_retargets(sim: &mut Sim) {
for _ in 0..200 {
if sim.retargets.is_empty() {
return;
}
sim.tick += 1;
sim.adapt();
}
panic!("the retarget queue did not finish");
}
#[cfg(test)]
fn retarget_route(sim: &Sim, id: u32) -> Vec<DVec3> {
sim.queue.iter().find(|(_, d)| d.id == id).unwrap().1.route.clone()
}
#[test]
fn pending_retarget_keeps_its_relief_version_after_a_new_plan() {
let flat = flat_relief();
let wall = wall_relief();
let outside = Grid { min: DVec3::new(3000.0, 0.0, 3000.0), cell: 32.0, size: 8 };
assert!(flat.sampled_on(&outside).is_none(), "land outside the plan must be Unknown");
let edge = Grid { min: DVec3::new(2500.0, 0.0, 2500.0), cell: 32.0, size: 8 };
let edge_flat = flat.sampled_on(&edge).unwrap();
assert!(edge_flat.iter().any(|h| h.is_nan()) && edge_flat.iter().any(|h| *h == 70.0));
let prepare = |relief| {
let (mut sim, _, _) = mass_retarget_sim(7);
sim.known_relief = Some(relief);
sim.tick = 40;
sim.adapt();
sim
};
let mut control = prepare(flat.clone());
let mut test = prepare(flat.clone());
let id = *test.retarget_ids().last().unwrap();
assert!(test.pending_relief(id).is_some(), "the chosen job is not waiting");
// Another smart plan finishes while the job waits: the global snapshot is the wall now.
test.known_relief = Some(wall.clone());
let bits = |v: Option<Vec<f32>>| v.map(|x| x.into_iter().map(f32::to_bits).collect::<Vec<_>>());
assert_eq!(
bits(test.pending_relief(id).unwrap().sampled_on(&edge)),
bits(flat.sampled_on(&edge)),
"a pending job's relief changed with the global snapshot"
);
finish_retargets(&mut control);
finish_retargets(&mut test);
assert_eq!(retarget_route(&control, id), retarget_route(&test, id), "the pending route used the newer relief");
let mut walled = prepare(wall);
finish_retargets(&mut walled);
assert_ne!(retarget_route(&control, id), retarget_route(&walled, id), "the test does not distinguish the relief versions");
}
#[test]
fn same_relief_different_known_snapshots_do_not_share_prices_or_routes() {
let flat = flat_relief();
let mut sim = Sim::new(3);
let start = DVec3::new(-1000.0, 100.0, 0.0);
let aim = DVec3::new(1000.0, 70.0, 0.0);
let threat = sim.id();
let threat_at = DVec3::new(0.0, 70.0, 0.0);
sim.sams.push(Sam::new(threat, SamKind::S400, threat_at, 0.0));
let target = sim.id();
sim.sams.push(Sam::new(target, SamKind::S400, aim, 0.0));
let contact = |id: u32, at: DVec3| super::ew::Contact {
id,
kind: SamKind::S400,
at,
tick: 0,
seen: super::ew::Seen::Emission,
emission: Some(0),
destroyed: None,
launches: 0,
};
let known_all = std::sync::Arc::new(super::ew::KnowledgeSnapshot { tick: 1, contacts: vec![contact(threat, threat_at), contact(target, aim)], marks: Vec::new() });
let known_target = std::sync::Arc::new(super::ew::KnowledgeSnapshot { tick: 2, contacts: vec![contact(target, aim)], marks: Vec::new() });
// The picture holds both units: a job's unit is alive only while the picture believes in it.
for c in known_all.contacts.iter() {
sim.intel.note(c.id, c.kind, c.at, true, 0, super::ew::Seen::Emission);
}
let mut add = |known: std::sync::Arc<super::ew::KnowledgeSnapshot>, version: u64| -> u32 {
let mut d = sim.make_drone(DroneKind::Kh22, start, DVec3::X, aim);
d.smart = true;
d.err = DVec3::ZERO;
d.target = aim;
d.route = vec![start, aim];
let id = d.id;
sim.queue.push((0, d));
sim.retargets.push_back(super::ew::RouteJob::for_test(id, aim, target, version, known, Some(flat.clone())));
id
};
// Same relief, same start and aim. Version 1 knows the threat on the direct line; version 2 does not.
let first = add(known_all.clone(), 1);
let other = add(known_target, 2);
// A second job of version 1: it may reuse the first one's price grid and route.
let same = add(known_all, 1);
sim.tick = 1;
for _ in 0..10 {
if sim.retargets.is_empty() {
break;
}
sim.adapt();
sim.tick += 1;
}
assert!(sim.retargets.is_empty(), "the jobs were not finished");
let route = |id| sim.queue.iter().find(|(_, d)| d.id == id).unwrap().1.route.clone();
let (r1, r2, r3) = (route(first), route(other), route(same));
assert_ne!(r1, r2, "jobs with different known snapshots shared a route");
assert_eq!(r1, r3, "jobs of one knowledge version did not reuse their route cache");
}
// #146: one Smart order, two kinds, the land answers starved while the plan waits and a visible
// contact disclosed mid-wait: every kind's targets and routes stay on the snapshot the order was
// chosen with, not on whatever the picture holds when the budget reaches that kind. The plan is
// driven by `plan_step` alone so no adaptive tick retargets the queue before it is read.
#[test]
fn smart_order_routes_every_kind_on_the_snapshot_it_was_ordered_with() {
use super::sites::testland::{serve, Land};
// What the order's drones end up with: kind, aim and route, in the plan's own order.
fn fly(extra_at_order: bool, extra_mid_wait: bool) -> Vec<(DroneKind, DVec3, Vec<DVec3>)> {
let mut sim = Sim::new(146);
let radar = sim.id();
sim.sams.push(Sam::new(radar, SamKind::Radar, DVec3::new(120.0, 70.0, 0.0), 0.0));
sim.intel.observe(&sim.sams[0], sim.tick, ew::Seen::Emission);
sim.targets.push(DVec3::new(0.0, 70.0, 0.0));
sim.target_health.push(100.0);
let extra = sim.id();
let extra_at = DVec3::new(0.0, 70.0, 150.0);
if extra_at_order {
sim.intel.note(extra, SamKind::S400, extra_at, true, sim.tick, ew::Seen::Emission);
}
let mut ground = Ground::default();
let land = Land(|_, _| 64);
let mut out = Out::default();
let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 6), (DroneKind::Geran3, 4)], approach: Approach::AllSides, dist: 300.0, aim: Aim::Smart };
let at = sim.tick;
assert_eq!(sim.order_raid(&order, &sim.targets.clone(), &mut out), 10);
let (_, _, knowledge, _) = sim.plan_pricing().expect("the order was not accepted");
assert_eq!(knowledge.tick, at, "the plan does not keep the tick it was ordered at");
assert!(knowledge.contacts.iter().any(|c| c.id == radar));
assert_eq!(knowledge.contacts.iter().any(|c| c.id == extra), extra_at_order);
let (mut starved, mut added) = (0, !extra_mid_wait);
for _ in 0..600 {
if !sim.planning() {
break;
}
let mapping = sim.plan_pricing().is_some_and(|(_, h, _, _)| !h.is_empty());
if mapping && !added {
// The game tells of no land for a while: the plan waits for the relief, and the
// contact arrives while it waits, after the targets were already chosen.
if starved < 10 {
sim.plan_step(Some(&mut ground), &mut out);
sim.tick += 1;
starved += 1;
continue;
}
sim.intel.note(extra, SamKind::S400, extra_at, true, sim.tick, ew::Seen::Emission);
added = true;
}
serve(&mut ground, &land, sim.tick);
sim.plan_step(Some(&mut ground), &mut out);
sim.tick += 1;
}
assert!(!sim.planning(), "the plan never finished");
assert!(added, "the mid-wait contact was never disclosed");
if extra_mid_wait {
assert!(sim.picture_of_defences().iter().any(|c| c.id == extra), "the disclosure did not reach the picture");
}
sim.queue.iter().map(|(_, d)| (d.kind, d.target, d.route.clone())).collect()
}
// The S400 engages jet drones, not propeller ones: Geran3 is the kind its report moves.
let waited = fly(false, true);
assert_eq!(waited, fly(false, false), "a contact disclosed while the plan waited for the land changed its routes");
assert_ne!(waited, fly(true, false), "the test does not distinguish the order's picture from a later one");
}
// #146: two jobs of one knowledge version, worked out on different ticks across the boundary
// where the current picture would stop believing a contact's own sensor, price the same world.
// An explicitly new retarget, with a fresh report of its own, may use the new report.
#[test]
fn retarget_jobs_of_one_version_age_at_their_own_tick() {
let mut sim = Sim::new(146);
let flat = flat_relief();
let start = DVec3::new(-1000.0, 100.0, 0.0);
let aim = DVec3::new(1000.0, 70.0, 0.0);
let threat = sim.id();
let threat_at = DVec3::new(0.0, 70.0, 0.0);
sim.sams.push(Sam::new(threat, SamKind::S400, threat_at, 0.0));
let target = sim.id();
sim.sams.push(Sam::new(target, SamKind::S400, aim, 0.0));
// The version sits one tick inside the emission belief's TTL: at the version the threat is
// believed to see on its own radar; one tick later the current picture would not believe it.
let version = ew::CONTACT_TTL - 1;
let contact = |id: u32, at: DVec3, tick: u64| ew::Contact { id, kind: SamKind::S400, at, tick, seen: ew::Seen::Emission, emission: Some(tick), destroyed: None, launches: 0 };
let known = std::sync::Arc::new(ew::KnowledgeSnapshot { tick: version, contacts: vec![contact(threat, threat_at, 0), contact(target, aim, version)], marks: Vec::new() });
sim.intel.note(target, SamKind::S400, aim, true, version, ew::Seen::Emission);
fn add(sim: &mut Sim, version: u64, known: std::sync::Arc<ew::KnowledgeSnapshot>, target: u32, start: DVec3, aim: DVec3, flat: &std::sync::Arc<ew::KnownRelief>) -> u32 {
// A jet drone: the S400's published roles engage it, so the belief in its radar prices it.
let mut d = sim.make_drone(DroneKind::Geran3, start, DVec3::X, aim);
d.smart = true;
d.err = DVec3::ZERO;
d.target = aim;
d.route = vec![start, aim];
// Past the switch cap: the adaptive tick may not turn these drones onto anything else.
d.aim = ew::Aim { unit: target, since: version, switches: ew::SWITCH_CAP, confidence: Some(ew::Confidence::Confirmed) };
let id = d.id;
sim.queue.push((0, d));
sim.retargets.push_back(ew::RouteJob::for_test(id, aim, target, version, known, Some(flat.clone())));
id
}
let first = add(&mut sim, version, known.clone(), target, start, aim, &flat);
sim.tick = version;
sim.adapt();
assert!(sim.retargets.is_empty(), "the first job was not finished");
let r1 = retarget_route(&sim, first);
// The same version and the same snapshot, reached one tick past the boundary.
let second = add(&mut sim, version, known.clone(), target, start, aim, &flat);
sim.tick = version + 1;
sim.adapt();
assert!(sim.retargets.is_empty(), "the second job was not finished");
let r2 = retarget_route(&sim, second);
assert_eq!(r1, r2, "a job of the same version aged its contacts with the current tick");
// An explicitly new retarget: a fresh report of the threat at the new version is priced again.
sim.intel.note(threat, SamKind::S400, threat_at, true, version + 1, ew::Seen::Emission);
let fresh = std::sync::Arc::new(ew::KnowledgeSnapshot { tick: version + 1, contacts: vec![contact(threat, threat_at, version + 1), contact(target, aim, version)], marks: Vec::new() });
let third = add(&mut sim, version + 1, fresh, target, start, aim, &flat);
sim.adapt();
assert!(sim.retargets.is_empty(), "the new job was not finished");
let r3 = retarget_route(&sim, third);
assert_eq!(r1, r3, "an explicitly new retarget could not use the new report");
// A new version without a new report: its own tick is past the boundary, so it no longer
// believes the threat's radar and flies the direct line. This is what the same-version job
// above must NOT do, and what makes the two versions distinguishable.
let stale = std::sync::Arc::new(ew::KnowledgeSnapshot { tick: version + 1, contacts: known.contacts.clone(), marks: Vec::new() });
let fourth = add(&mut sim, version + 1, stale, target, start, aim, &flat);
sim.adapt();
assert!(sim.retargets.is_empty(), "the fourth job was not finished");
let r4 = retarget_route(&sim, fourth);
assert_ne!(r1, r4, "the test does not distinguish believing the threat from not believing it");
assert_ne!(r3, r4, "a new version without a new report kept the old belief");
}
// #31: the ground cache is bounded — beyond the cap the oldest answers go, and the sweep
// lands well under the cap so it is not every answer (the fullscreen-map OOM: a cache that
// only swept above 300_000 fresh columns grew without bound under a wide query pattern).
#[test]
fn big_ground_cache_is_bounded_and_swept_rarely() {
let mut ground = Ground::default();
ground.known.extend((0..300_001).map(|x| ((x, 0), (64, 2000))));
ground.known.extend((0..KNOWN_MAX as i32).map(|x| ((x, 0), (64, 2000))));
ground.known.insert((-1, 0), (64, 0));
// The first answer past the threshold sweeps what is stale and keeps what is fresh.
// The answer past the cap sweeps: the stale column goes, the fresh stay, and the cache
// lands at three quarters of the cap.
ground.answer(vec![(-2, 0, 64)], 2100);
assert!(!ground.known.contains_key(&(-1, 0)), "a stale column was never swept");
assert!(ground.known.len() > 300_000);
// The next ones wait their pause: a stale column added now survives them.
assert!(ground.known.len() <= KNOWN_MAX * 3 / 4 + 1, "the sweep did not bound the cache: {}", ground.known.len());
assert!(ground.known.len() > KNOWN_MAX / 2, "the sweep took too much: {}", ground.known.len());
// The next answers do not sweep again at once: a stale column added now survives them.
ground.known.insert((-1, 0), (64, 0));
let swept = ground.swept;
let len = ground.known.len();
ground.answer(vec![(-3, 0, 64)], 2101);
assert_eq!(ground.swept, swept, "swept again at once");
assert_eq!(ground.known.len(), len + 1, "swept again at once");
assert!(ground.known.contains_key(&(-1, 0)));
ground.answer(vec![(-4, 0, 64)], 2100 + SWEEP_EVERY);
assert!(!ground.known.contains_key(&(-1, 0)), "never swept again");
// An evicted column is asked again when it is next needed: the cache is reconstructible.
let evicted = (0, 0);
assert!(!ground.known.contains_key(&evicted));
assert!(ground.at(DVec3::new(evicted.0 as f64, 0.0, 0.0), 2102).is_none());
assert!(ground.take_wanted().contains(&evicted), "an evicted column was not asked again");
}
// #32: the pieces of an Oreshnik teach the enemy about the sector it came from
@@ -717,7 +1130,7 @@ fn fires_start_merge_and_are_limited() {
// interceptors keep clear of it. A synthetic land (a height function) stands in for the game.
/// Land from a height function: blocks below it are solid, and the game's height map says the same.
struct Land<F: Fn(i32, i32) -> i32>(F);
pub(super) struct Land<F: Fn(i32, i32) -> i32>(F);
impl<F: Fn(i32, i32) -> i32> world::WorldSource for Land<F> {
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
Some(y < (self.0)(x, z))
@@ -725,7 +1138,7 @@ impl<F: Fn(i32, i32) -> i32> world::WorldSource for Land<F> {
}
/// What the game answers a tick after the sim asked: land heights, and the sections it needs.
fn answer_land<F: Fn(i32, i32) -> i32>(ground: &mut Ground, land: &Land<F>, now: u64) {
pub(super) fn answer_land<F: Fn(i32, i32) -> i32>(ground: &mut Ground, land: &Land<F>, now: u64) {
let columns = ground.take_wanted().into_iter().map(|(x, z)| (x, z, (land.0)(x, z))).collect();
ground.answer(columns, now);
let sections = ground.world.take_wanted(now);
@@ -737,7 +1150,7 @@ fn ridge(rise: i32, half: i32) -> Land<impl Fn(i32, i32) -> i32> {
ridge_at(300, rise, half)
}
fn ridge_at(crest: i32, rise: i32, half: i32) -> Land<impl Fn(i32, i32) -> i32> {
pub(super) fn ridge_at(crest: i32, rise: i32, half: i32) -> Land<impl Fn(i32, i32) -> i32> {
Land(move |x, _| 64 + (rise - (x - crest).abs() * rise / half).max(0))
}
@@ -830,9 +1243,23 @@ fn behind_ridge(land: &Land<impl Fn(i32, i32) -> i32>, crest: i32, kind: SamKind
// It crawls along the far side of the ridge, 20 blocks over the land.
let there = (land.0)(x as i32, 0) as f64;
sim.add_drone(DroneKind::Shahed, DVec3::new(x, there + 20.0, -100.0), DVec3::Z, DVec3::new(x, there, 3000.0));
let id = sim.drones[0].id;
for _ in 0..ticks {
sim.step(&mut ground, None, &mut out);
answer_land(&mut ground, land, sim.tick);
// The scenario is about the interceptor's path over the ridge, not about
// where the plot came from: give the system the crest radar's plot as its
// own confirmed fire measurement (separate authority is tested in
// `a_system_does_not_fire_at_a_target_masked_by_a_hill`).
if let Some(t) = sim.sams[1].track(id).copied() {
let mut own = t;
own.source = sim.sams[0].id;
own.own_tick = sim.tick;
own.own_product = battery::Measure::Fire;
own.own_quality = 90;
sim.sams[0].tracks.retain(|o| o.id != id);
sim.sams[0].tracks.push(own);
}
}
sim
}
@@ -858,27 +1285,25 @@ fn a_system_does_not_fire_at_a_target_masked_by_a_hill() {
answer_land(&mut ground, land, sim.tick);
}
sim.add_drone(DroneKind::Gerbera, DVec3::new(200.0, 84.0, -60.0), DVec3::Z, DVec3::new(200.0, 64.0, 3000.0));
let mut masked = 0u32;
let mut seen = false;
let mut told = false;
for _ in 0..300 {
sim.step(&mut ground, None, &mut out);
answer_land(&mut ground, land, sim.tick);
seen |= sim.sams[0].seen.len() == 1;
masked += sim.sams[0].terrain.values().filter(|(_, b)| *b == terrain::MASKED).count() as u32;
// `why` names the reason while the verdict stands.
told |= sim.why(0).iter().any(|c| !c.ok && c.text.contains("за рельефом"));
// The network shows the target, but the Tor has no own confirmed plot,
// so `why` must say that no launch is authorized.
told |= sim.why(0).iter().any(|c| !c.ok && c.legacy_text().contains("право на пуск: нет"));
}
(sim, seen, masked, told)
(sim, seen, told)
};
let (open, seen, _, _) = shot(&flat);
let (open, seen, _) = shot(&flat);
assert!(seen && open.sams[0].fired > 0, "control: with a clear line the Tor must fire (seen {seen}, fired {})", open.sams[0].fired);
let (shut, seen, masked, told) = shot(&hill);
let (shut, seen, told) = shot(&hill);
assert!(seen, "the network must have shown the target to the Tor");
assert_eq!(shut.sams[0].fired, 0, "the Tor fired at a target behind the hill");
assert!(masked > 0, "no launch was judged and refused for the land");
assert_eq!(shut.tally.blocked + shut.tally.scrubbed, 0);
assert!(told, "`why` never named the land as the reason");
assert!(told, "`why` never named the missing own fire plot");
}
// A long-range system lofts over a low ridge (its interceptor does not hit it) but not over a mountain.
@@ -895,7 +1320,7 @@ fn a_long_range_system_lofts_over_a_ridge_or_waits() {
let sim = behind_ridge(&tall, 150, SamKind::IrisT, 230.0, ticks);
assert_eq!(sim.sams[0].fired, 0, "no missile can climb a 400-block mountain at this range");
assert_eq!(sim.tally.blocked + sim.tally.scrubbed, 0);
told |= sim.why(0).iter().any(|c| !c.ok && c.text.contains("рельеф"));
told |= sim.why(0).iter().any(|c| !c.ok && c.legacy_text().contains("рельеф"));
}
assert!(told, "`why` never named the land as the reason");
}
@@ -1316,7 +1741,7 @@ fn raids_have_the_same_strike_accuracy_as_manual_launches() {
let mut sim = Sim::new(3);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Ew, DVec3::new(0.0, 70.0, 900.0), 0.0));
sim.intel.revealed.push((id, DVec3::new(0.0, 70.0, 900.0), 0));
sim.intel.observe(&sim.sams[0], 0, ew::Seen::Jamming);
let order = RaidOrder { kinds: vec![(DroneKind::Zircon, 20)], approach: Approach::Sector, dist: 400.0, aim: Aim::Objects };
sim.order_raid(&order, &[DVec3::new(0.0, 70.0, 0.0)], &mut Out::default());
// (The raid's launch sites need land the game has told of: a flat one is served.)
@@ -1969,6 +2394,8 @@ fn spent_motor_has_less_maneuver_at_low_speed() {
assert!(powered.x > coast.x && coast.x > 0.0, "{powered:?} {coast:?}");
}
// #129: the staged launch's exact speed rules: gas-drag ejection with a floor, a spooled
// departure that grows into full acceleration, full power at guidance, the coast drag after.
#[test]
fn cold_ejection_power_and_coast_use_their_own_speed_rules() {
let kind = MissileKind::M48n6;
@@ -1984,8 +2411,300 @@ fn cold_ejection_power_and_coast_use_their_own_speed_rules() {
sim.step_missiles(&mut Ground::default(), &mut Out::default());
sim.missiles[0].vel.length()
};
assert!((fly(0, 2.0) - 2.0 * 0.97).abs() < 1e-9, "cold ejection drag");
assert!((fly(spec.cold, 2.0) - (2.0 + spec.accel)).abs() < 1e-9, "powered acceleration");
assert!((fly(0, spec.eject) - (spec.eject - spec.eject_drag)).abs() < 1e-9, "cold ejection drag");
assert!((fly(spec.cold - 1, 0.1) - spec.eject * 0.25).abs() < 1e-9, "cold ejection floor near ignition");
assert!((fly(0, 0.2) - spec.eject * 0.25).abs() < 1e-9, "cold ejection floor");
let spool0 = 0.45 + 0.55 / f64::from(spec.boost);
assert!((fly(spec.cold, 2.0) - (2.0 + spec.accel * spool0)).abs() < 1e-9, "ignition spool-up");
assert!((fly(spec.cold + spec.boost - 1, 2.0) - (2.0 + spec.accel)).abs() < 1e-9, "powered acceleration");
assert!((fly(spec.cold + kind.burn_ticks(), 2.0) - 2.0 * 0.995).abs() < 1e-9, "coast drag");
assert!((fly(0, 0.2) - 0.4).abs() < 1e-9, "cold ejection minimum");
}
// ---- #129: the staged cold launch. Ejection (unlit gas throw) → ignition where the round has
// reached → departure (spool-up and course capture at a growing rate) → guidance at cold + boost.
/// Every cold-launched kind walks its stages in order; before ignition there is no motor voice,
/// no flame and no steering, the speed is continuous across ignition, and the turn each tick
/// never exceeds what the stage allows.
#[test]
fn cold_launch_stages_run_in_order_and_guidance_follows_ignition() {
for &kind in &[MissileKind::M48n6, MissileKind::M77n6, MissileKind::IrisT, MissileKind::M9m338] {
let spec = kind.spec();
let mut sim = Sim::new(120);
// A still target well off the vertical: the tip-over has somewhere to turn.
let target_pos = DVec3::new(300.0, 120.0, 300.0);
sim.add_drone(DroneKind::Shahed, target_pos, DVec3::ZERO, target_pos);
let (target, id) = (sim.drones[0].id, sim.id());
sim.missiles.push(Missile { id, kind, pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::Y * spec.eject, target, sam: 999, age: 0, hold: 0,
fix: Some(Fix { pos: target_pos, vel: DVec3::ZERO, tick: 0, seeker: false }), seen: 0 });
sim.begin_recording_if_active();
let mut previous_speed = spec.eject;
let mut previous_dir = DVec3::Y;
let mut saw_ignition = false;
for age in 1..=(spec.cold + spec.boost + 2) {
sim.tick += 1;
let mut out = Out::default();
sim.step_missiles(&mut Ground::default(), &mut out);
let m = sim.missiles.iter().find(|m| m.id == id).unwrap_or_else(|| panic!("{kind:?} age {age}"));
let speed = m.vel.length();
let dir = m.vel.normalize_or(DVec3::Y);
let voice = out.engines.iter().any(|e| e.key == (0x4000_0000 | id));
let flame = out.particles.iter().any(|p| p.kind == "minecraft:flame");
assert_eq!(voice, m.engine_lit(), "{kind:?} age {age}: the motor voice runs only when lit");
if !m.engine_lit() {
assert!(!voice && !flame, "{kind:?} age {age}: powered effects before ignition");
assert!((speed - (previous_speed - spec.eject_drag)).abs() < 1e-9, "{kind:?} age {age}: ejection drag");
assert!(dir.angle_between(DVec3::Y) < 1e-9, "{kind:?} age {age}: steering before ignition");
} else if !saw_ignition {
saw_ignition = true;
assert_eq!(m.age, spec.cold + 1, "{kind:?}: ignition one tick after the ejection ends");
assert!(speed > previous_speed - 1e-9, "{kind:?}: speed jumps down across ignition ({previous_speed} -> {speed})");
assert!(out.sounds.iter().any(|s| s.0 == sound::LAUNCH_S400 || s.0 == sound::LAUNCH_S500), "{kind:?}: ignition sound");
let events = sim.rec.as_ref().unwrap().scene.as_ref().unwrap().events();
assert!(events.iter().any(|e| matches!(e.kind, record::SceneKind::MotorIgnition { missile, .. } if missile == id)), "{kind:?}: ignition recorded");
}
let allowed = if spec.guided(m.age) {
spec.turn
} else if m.engine_lit() {
// Departure: the rate grows into the full one; no snap at the boundary.
spec.turn * (0.2 + 0.8 * spec.departure_ramp(m.age))
} else {
0.0
};
assert!(previous_dir.angle_between(dir) <= allowed + 1e-9, "{kind:?} age {age}: turned past the stage's rate");
previous_speed = speed;
previous_dir = dir;
}
assert!(saw_ignition, "{kind:?}: never lit");
let m = sim.missiles.iter().find(|m| m.id == id).unwrap();
assert!(m.vel.normalize().angle_between(DVec3::Y) > 0.3, "{kind:?}: still vertical after guidance started");
}
}
/// The invariant the issue is about: with a longer ignition delay the old `age >= boost` guidance
/// would have switched on before the motor existed. Now guidance implies ignition, for every
/// profile and every age, and the seeker opens with guidance, not with the raw boost counter.
#[test]
fn guidance_never_starts_before_ignition_for_any_profile() {
for kind in [
MissileKind::Pac3, MissileKind::M57e6, MissileKind::M48n6, MissileKind::M77n6, MissileKind::IrisT,
MissileKind::Amraam, MissileKind::M9m317, MissileKind::M9m338, MissileKind::P1sun,
] {
let spec = kind.spec();
for age in 0..=spec.life.min(2000) {
assert!(!spec.guided(age) || age > spec.cold, "{kind:?} age {age}: guidance before ignition (cold {})", spec.cold);
}
}
}
/// Across the whole staging the speed changes smoothly (no jumps beyond the stage's own drag or
/// full acceleration) and the per-tick turn never exceeds the profile's rate, for every kind.
/// A rocket's first powered tick is a throttled one for rail and cold launches alike (#129).
#[test]
fn launch_accel_and_turn_stay_continuous_for_every_interceptor() {
for kind in [
MissileKind::Pac3, MissileKind::M57e6, MissileKind::M48n6, MissileKind::M77n6, MissileKind::IrisT,
MissileKind::Amraam, MissileKind::M9m317, MissileKind::M9m338, MissileKind::P1sun,
] {
let spec = kind.spec();
let mut sim = Sim::new(120);
let target_pos = DVec3::new(400.0, 140.0, 400.0);
sim.add_drone(DroneKind::Shahed, target_pos, DVec3::ZERO, target_pos);
let (target, id) = (sim.drones[0].id, sim.id());
let v0 = if spec.cold > 0 { spec.eject } else { 0.8 };
sim.missiles.push(Missile { id, kind, pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::Y * v0, target, sam: 999, age: 0, hold: 0,
fix: Some(Fix { pos: target_pos, vel: DVec3::ZERO, tick: 0, seeker: false }), seen: 0 });
let mut previous_speed = v0;
let mut previous_dir = DVec3::Y;
let mut first_power: Option<f64> = None;
for _ in 0..120 {
sim.tick += 1;
sim.step_missiles(&mut Ground::default(), &mut Out::default());
let Some(m) = sim.missiles.iter().find(|m| m.id == id) else { break };
let speed = m.vel.length();
let dir = m.vel.normalize_or(DVec3::Y);
assert!(speed - previous_speed <= spec.accel + 1e-9, "{kind:?}: speed jumped up {previous_speed} -> {speed}");
let allowed_down = spec.eject_drag + previous_speed * 0.005;
assert!(speed >= previous_speed - allowed_down - 1e-9, "{kind:?}: speed jumped down {previous_speed} -> {speed}");
assert!(previous_dir.angle_between(dir) <= spec.turn + 1e-9, "{kind:?}: turned past the profile's rate");
if m.engine_lit() && first_power.is_none() {
first_power = Some(speed - previous_speed);
}
previous_speed = speed;
previous_dir = dir;
}
if spec.flame > 0.0 {
let gain = first_power.unwrap_or_else(|| panic!("{kind:?}: the motor never lit"));
let spooled = spec.accel * (0.45 + 0.55 / f64::from(spec.boost.max(1)));
assert!(gain > 0.0 && gain <= spooled + 1e-9, "{kind:?}: the motor reached full thrust at once ({gain} > {spooled})");
}
}
}
/// The electric P1-SUN is not a rocket: it keeps no flame, no powered smoke and its own voice.
#[test]
fn p1sun_stays_a_ramming_drone_without_a_plume() {
let kind = MissileKind::P1sun;
let spec = kind.spec();
assert_eq!(spec.flame, 0.0);
assert_eq!(spec.cold, 0);
let mut sim = Sim::new(120);
let target_pos = DVec3::new(200.0, 64.0, 0.0);
sim.add_drone(DroneKind::Shahed, target_pos, DVec3::ZERO, target_pos);
let (target, id) = (sim.drones[0].id, sim.id());
sim.missiles.push(Missile { id, kind, pos: DVec3::ZERO, vel: DVec3::X * 0.8, target, sam: 999, age: 0, hold: 0,
fix: Some(Fix { pos: target_pos, vel: DVec3::ZERO, tick: 0, seeker: false }), seen: 0 });
for _ in 0..40 {
sim.tick += 1;
let mut out = Out::default();
sim.step_missiles(&mut Ground::default(), &mut out);
assert!(!out.particles.iter().any(|p| p.kind == "minecraft:flame"), "P1-SUN grew a rocket plume");
if let Some(m) = sim.missiles.iter().find(|m| m.id == id) {
assert!(m.engine_lit(), "the electric interceptor's motor state is wrong");
let (event, _, _) = kind.engine_voice();
assert!(out.engines.iter().any(|e| e.key == (0x4000_0000 | id) && e.event == event));
} else {
break;
}
}
}
/// A real S-400 launch records the ejection and the ignition `cold` ticks apart; the replay's lit
/// state follows the recorded ignition, so a seek across it shows one flame and one voice sequence.
#[test]
fn recorded_ignition_is_cold_ticks_after_ejection_and_replay_follows_it() {
let mut sim = Sim::new(0x129);
let sam = sim.id();
sim.sams.push(Sam::new(sam, SamKind::S400, DVec3::new(0.0, 64.0, 0.0), 0.0));
sim.sams[0].cooldown = 0;
let mut out = Out::default();
sim.launch(DroneKind::Kh101, DVec3::new(0.0, 160.0, -600.0), DVec3::Z, DVec3::new(0.0, 64.0, 0.0), &mut out);
let mut ground = Ground::default();
for _ in 0..200 {
// The firing system's own measurement, fresh this tick (as `why::radar_sees` feeds it):
// the test is about the launch stages, not about the scan's chance.
let now = sim.tick;
let tracks: Vec<sight::Track> = sim.drones.iter().filter(|d| d.alive())
.map(|d| sight::Track {
id: d.id,
class: ClassEst::Firm(d.kind.spec().class),
pos: d.pos,
vel: d.vel,
tick: now,
own_tick: now,
source: 1,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 400,
hits: 3,
locked: false,
})
.collect();
sim.sams[0].tracks.retain(|t| !tracks.iter().any(|n| n.id == t.id));
sim.sams[0].tracks.extend(tracks);
let wanted = ground.take_wanted();
ground.answer(wanted.into_iter().map(|(x, z)| (x, z, 64)).collect(), sim.tick);
out = Out::default();
sim.step(&mut ground, None, &mut out);
if sim.replays.iter().chain(sim.rec.iter()).flat_map(|r| r.scene.iter().flat_map(|s| s.events())).any(|e| matches!(e.kind, record::SceneKind::MotorIgnition { .. })) {
break;
}
}
let rec = sim.rec.as_ref().or_else(|| sim.replays.last()).expect("a recording");
let scene = rec.scene.as_ref().unwrap();
let launch = scene.events().iter().find(|e| matches!(e.kind, record::SceneKind::MissileLaunch { .. })).expect("the ejection is recorded");
let missile = match launch.kind { record::SceneKind::MissileLaunch { missile, .. } => missile, _ => unreachable!() };
let spec = MissileKind::M48n6.spec();
let ignition = rec.missile_ignition(missile).expect("the ignition is recorded");
assert_eq!(ignition.at - launch.at, spec.cold, "ignition {} ticks after the ejection", spec.cold);
let track = rec.track(missile).expect("the interceptor's track");
for t in [ignition.at as f64 - 1.0, ignition.at as f64 - 0.1] {
assert!(!rec.missile_is_lit(track, t, spec.cold), "lit before the recorded ignition at {t}");
}
for t in [ignition.at as f64, ignition.at as f64 + 5.0] {
assert!(rec.missile_is_lit(track, t, spec.cold), "not lit at the recorded ignition ({t})");
}
assert!(!rec.missile_is_lit(track, ignition.at as f64 + spec.cold as f64 + f64::from(MissileKind::M48n6.burn_ticks()) + 2.0, spec.cold), "lit past the recorded burnout");
}
/// The physical RM48U strike ejects unlit and slow, then lights at `EJECT_TICKS` where it has
/// reached: no motor voice or flame before, one ignition sound at the hand-over.
#[test]
fn rm48u_strike_ejects_before_ignition_on_its_own_path() {
use super::sites::testland::{Land, serve};
use super::sites::{LaunchSite, SiteClass};
use super::strike::{Estimate, Known, SiteState};
use glam::DVec2;
let land = Land(|_, _| 64);
let mut sim = Sim::new(11);
// A fixed site the strike needs no scouting for; its launches are queued far ahead, so a wave
// boundary does not retire it while the test runs.
let id = sim.sites.add(LaunchSite {
id: 0, side: 0, sector: 0, bearing: 0.0, class: SiteClass::Ramp,
pos: DVec3::new(0.0, 64.0, 400.0), range: 400.0, water: false,
stock: 4, planned: 4, alive: true, next_free: 0, offmap: false,
});
for i in 0..4 {
let site = sim.sites.get(id).unwrap().clone();
let d = sim.make_drone(DroneKind::Shahed, site.muzzle(i), -DVec3::Z, DVec3::new(0.0, 70.0, 0.0));
sim.sites.job(d.id, id);
sim.queue.push((20_000 + u64::from(i), d));
}
sim.strikes.known.push(Known {
site: id, class: SiteClass::Ramp, obs: Vec::new(),
est: Some(Estimate { pos: DVec2::new(0.0, 400.0), radius: 5.0, fix: true, bearing: 0.0, bearing_err: 0.01, origin: DVec2::ZERO }),
launches: 1, last: 0, state: SiteState::Active, aimed: false,
});
let carrier = sim.id();
let mut sam = Sam::new(carrier, SamKind::S400, DVec3::new(0.0, 64.0, 0.0), 0.0);
sam.missiles = 2;
sam.ground_rounds = 2;
sam.cooldown = 0;
sim.sams.push(sam);
let mut out = Out::default();
sim.order_strike(id, DVec3::ZERO, &mut out).unwrap();
let (mut ground, mut heard_ignition) = (Ground::default(), 0);
let mut saw_voice_before = false;
let mut saw_flame_before = false;
let mut rise = 0.0f64;
let mut all_messages = Vec::new();
for _ in 0..(launch::OPEN_TICKS as usize + strike::EJECT_TICKS as usize + 6) {
serve(&mut ground, &land, sim.tick);
out = Out::default();
sim.step(&mut ground, None, &mut out);
all_messages.append(&mut out.messages);
if let Some(f) = sim.strikes.flights.first() {
let age = sim.tick - f.start;
if age < strike::EJECT_TICKS {
saw_voice_before |= out.engines.iter().any(|e| e.key == 0x7500_0000 + f.id * PARTS);
saw_flame_before |= out.models.iter().any(|m| m.name == "airdef:flame" && m.id == 0x7500_0000 + f.id * PARTS + 1);
rise = rise.max(f.pos.y - f.from.y);
}
if age == strike::EJECT_TICKS {
heard_ignition = out.sounds.iter().filter(|s| s.0 == sound::LAUNCH_S400).count();
}
}
}
assert!(rise > 10.0, "the ejection rose only {rise} blocks");
assert!(!saw_voice_before && !saw_flame_before, "powered effects during the unlit ejection");
assert_eq!(heard_ignition, 1, "exactly one ignition sound at the hand-over: {all_messages:?}");
}
#[test]
fn blast_forget_removes_only_columns_in_the_same_square() {
let mut ground = Ground::default();
for x in -25..=25 {
for z in -25..=25 {
ground.known.insert((x, z), (x * 100 + z, 123));
}
}
let before = ground.known.clone();
let at = DVec3::new(-3.2, 70.0, 4.9);
ground.forget(at, 8);
let expected: std::collections::HashMap<_, _> = before.into_iter()
.filter(|&((x, z), _)| (x + 4_i32).abs() > 8 || (z - 4_i32).abs() > 8)
.collect();
assert_eq!(ground.known, expected);
}
+194 -4
View File
@@ -171,6 +171,10 @@ pub(super) struct Route {
near: ((i32, i32), f64),
expanded: usize,
goal_checked: bool,
truck: bool,
work_approach: bool,
work_wait: u32,
works: u8,
phase: Phase,
pts: Vec<DVec3>,
next: usize,
@@ -206,6 +210,10 @@ impl Route {
near: ((0, 0), f64::MAX),
expanded: 0,
goal_checked: slack > 0.0,
truck: kind == SamKind::Tzm && slack > 0.0,
work_approach: false,
work_wait: 0,
works: 0,
phase: Phase::Search,
pts: Vec::new(),
next: 0,
@@ -231,7 +239,12 @@ impl Route {
horizontal(self.centre(c) - self.dest).length()
}
fn is_goal(&self, c: (i32, i32)) -> bool {
if self.slack > 0.0 { self.to_goal(c) <= self.slack } else { c == self.cell_of(self.dest) }
if self.slack == 0.0 {
return c == self.cell_of(self.dest);
}
let Some(info) = self.cells.get(&c) else { return false };
let p = self.centre(c);
DVec3::new(p.x, f64::from(info.h), p.z).distance(self.dest) <= self.slack
}
/// Searches afresh from `pos`, keeping the cells found bad.
@@ -252,6 +265,8 @@ impl Route {
self.expanded = 0;
self.near = (self.start, f64::MAX);
self.partial = false;
self.work_approach = false;
self.work_wait = 0;
self.cells.insert(self.start, Info { h: pos.y as f32, ok: true });
self.g.insert(self.start, 0.0);
let h = self.heur(self.start);
@@ -311,10 +326,18 @@ impl Route {
let Some(column) = ground.column(x, z, 1024) else { pending = true; continue };
let Some(h) = column else { return Clearance::Blocked };
let dh = h - base;
if dh > STEP_UP || dh < -STEP_DOWN {
let up = if self.truck { 2.0 } else { STEP_UP };
if dh > up || dh < -STEP_DOWN {
return Clearance::Blocked;
}
let top = DVec3::new(f64::from(x) + 0.5, h + 0.05, f64::from(z) + 0.5);
if self.truck && dx == 0 && dz == 0 {
match ground.world.sweep(top, top - DVec3::Y * 0.55, false, now) {
world::Sweep::Hit { .. } => {}
world::Sweep::Clear => return Clearance::Blocked,
_ => { pending = true; continue; }
}
}
match ground.world.sweep(top, top + DVec3::Y * self.chassis.height, false, now) {
world::Sweep::Clear => {}
world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => pending = true,
@@ -542,13 +565,117 @@ impl Route {
if self.phase == Phase::Search {
return Drive::Wait(Why::Map);
}
let reach = f64::from(self.cell) * 0.7;
let reach = if self.truck { 0.65 } else { f64::from(self.cell) * 0.7 };
while self.next + 1 < self.pts.len() && horizontal(self.pts[self.next] - pos).length() < reach {
self.next += 1;
}
Drive::Go(self.pts[self.next], self.next + 1 >= self.pts.len())
}
/// Let an automatic delivery approach the nearest reachable spot before trying local roadwork.
pub(super) fn approach_works(&mut self) -> bool {
if !self.truck || self.works >= 2 || self.near.0 == self.start
|| self.to_goal(self.start) - self.near.1 < f64::from(self.cell)
{
return false;
}
self.failed = None;
self.finish(self.near.0, true);
self.work_approach = true;
true
}
pub(super) fn work_approach(&self) -> bool {
self.work_approach
}
/// Make a short local crossing only after route search or motion finds a blockage.
/// Returns true while waiting for terrain data or after requesting the edits.
pub(super) fn try_works(&mut self, ground: &mut Ground, pos: DVec3, now: u64, out: &mut Out) -> bool {
if !self.truck || self.works >= 2 || self.work_wait >= 60 {
return false;
}
self.work_wait += 1;
let direction = horizontal(self.dest - pos);
let (dx, dz) = if direction.x.abs() >= direction.z.abs() {
(if direction.x >= 0.0 { 1 } else { -1 }, 0)
} else {
(0, if direction.z >= 0.0 { 1 } else { -1 })
};
let coord = |row: i32, side: i32| (
pos.x.floor() as i32 + dx * row + dz * side,
pos.z.floor() as i32 + dz * row + dx * side,
);
let width = self.chassis.radius.ceil() as i32;
let start = pos.y.round() as i32;
let (ex, ez) = coord(10, 0);
let Some(Some(end)) = ground.column(ex, ez, 1024) else {
ground.want_chunk((ex >> 4, ez >> 4));
return true;
};
let end = end.round() as i32;
if (end - start).abs() > 2 || !(-63..=320).contains(&start) || !(-63..=320).contains(&end) {
return false;
}
let mut commands = Vec::new();
for row in 1..=10 {
let level = start + ((end - start) as f64 * f64::from(row) / 10.0).round() as i32;
let mut deck = false;
for side in -width..=width {
let (x, z) = coord(row, side);
let Some(Some(top)) = ground.column(x, z, 1024) else {
ground.want_chunk((x >> 4, z >> 4));
return true;
};
let top = top.round() as i32;
if top > level + 2 {
return false;
}
let p = DVec3::new(f64::from(x) + 0.5, f64::from(level), f64::from(z) + 0.5);
match ground.world.sweep(p + DVec3::Y * 0.25, p - DVec3::Y * 0.25, false, now) {
world::Sweep::Hit { .. } if top >= level => {}
world::Sweep::Hit { .. } | world::Sweep::Clear => deck = true,
_ => return true,
}
if top > level {
// Only shallow natural cover is cleared. Vanilla fills preserve other materials.
for block in ["short_grass", "fern", "snow", "dirt", "grass_block", "sand", "gravel"] {
commands.push(format!("fill {x} {level} {z} {x} {} {z} minecraft:air replace minecraft:{block}", top - 1));
}
}
}
if deck {
let (ax, az) = coord(row, -width);
let (bx, bz) = coord(row, width);
let y = level - 1;
for block in ["air", "water"] {
commands.push(format!("fill {ax} {y} {az} {bx} {y} {bz} minecraft:cobblestone replace minecraft:{block}"));
}
}
}
if commands.is_empty() || out.commands.len() + commands.len() > 192 {
return false;
}
out.commands.extend(commands);
let centre = pos + DVec3::new(f64::from(dx * 5), 0.0, f64::from(dz * 5));
ground.forget(centre, 9);
let (cx, cz) = (centre.x.floor() as i32, centre.z.floor() as i32);
let mut chunks = Vec::new();
for x in (cx - 9).div_euclid(16)..=(cx + 9).div_euclid(16) {
for z in (cz - 9).div_euclid(16)..=(cz + 9).div_euclid(16) {
chunks.push((x, z));
}
}
ground.world.columns_changed(&chunks);
self.works += 1;
self.replans = 0;
self.failed = None;
self.bad.clear();
self.cells.clear();
self.restart(pos);
true
}
pub(super) fn searching(&self) -> bool {
self.phase == Phase::Search && self.failed.is_none()
}
@@ -563,6 +690,23 @@ pub(super) struct Routes {
}
impl Routes {
/// What the routes and their searches hold, about (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::{map_bytes, vec_bytes};
let cell = std::mem::size_of::<(i32, i32)>();
let mut n = map_bytes(self.map.len(), std::mem::size_of::<u32>() + std::mem::size_of::<Route>())
+ map_bytes(self.unreachable.len(), std::mem::size_of::<(u32, u32)>() + std::mem::size_of::<u64>());
for r in self.map.values() {
n += map_bytes(r.cells.len(), cell + std::mem::size_of::<Info>())
+ map_bytes(r.bad.len(), cell)
+ map_bytes(r.g.len(), cell + std::mem::size_of::<f32>())
+ map_bytes(r.came.len(), 2 * cell)
+ r.open.capacity() * std::mem::size_of::<Open>()
+ vec_bytes(&r.parked)
+ vec_bytes(&r.pts);
}
n
}
pub(super) fn out_of_reach(&self, truck: u32, job: u32, now: u64) -> bool {
self.unreachable.get(&(truck, job)).is_some_and(|&t| t > now)
}
@@ -617,7 +761,53 @@ mod tests {
ground.world.serve(src, sections, now);
}
/// Drives a Patriot from the origin to `to` over land of the given heights (water: a height over a lower floor).
#[test]
fn a_supply_truck_builds_a_bridge_then_crosses_it() {
struct Creek(HashSet<(i32, i32)>);
impl world::WorldSource for Creek {
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
let floor = if (16..20).contains(&x) && !self.0.contains(&(x, z)) { 60 } else { 64 };
Some(y < floor)
}
}
let mut creek = Creek(HashSet::new());
let mut sim = Sim::new(5);
let from = DVec3::new(0.5, 64.0, 0.5);
let to = DVec3::new(80.5, 64.0, 0.5);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Tzm, from, 0.0));
sim.sams[0].job = Some(999);
assert!(sim.order_move_near(0, to, HANDOVER - 0.75));
let mut ground = Ground::default();
let mut out = Out::default();
for _ in 0..2000 {
sim.tick += 1;
let columns = ground.take_wanted().into_iter().map(|(x, z)| (x, z, 64)).collect();
ground.answer(columns, sim.tick);
let sections = ground.world.take_wanted(sim.tick);
ground.world.serve(&creek, sections, sim.tick);
sim.step_moves(&mut ground, &mut out);
for command in out.commands.drain(..) {
let words: Vec<&str> = command.split_whitespace().collect();
if words[7] == "minecraft:cobblestone" && words[9] == "minecraft:water" {
let [ax, ay, az, bx, by, bz] = std::array::from_fn(|i| words[i + 1].parse::<i32>().unwrap());
assert_eq!((ay, by), (63, 63));
for x in ax.min(bx)..=ax.max(bx) {
for z in az.min(bz)..=az.max(bz) {
if (16..20).contains(&x) { creek.0.insert((x, z)); }
}
}
}
}
if !sim.sams[0].moving() { break; }
}
assert!(!creek.0.is_empty(), "the truck built no bridge");
assert!(sim.sams[0].pos.distance(to) <= HANDOVER, "{:?} {:?}", sim.sams[0].pos, out.messages);
assert!(out.messages.is_empty(), "{:?}", out.messages);
}
/// Drives a Patriot from the origin to `to` over land of the given heights.
fn march_kind<H: Fn(i32, i32) -> i32, B: Fn(i32, i32) -> i32>(kind: SamKind, height: H, floor: B, to: DVec3, ticks: u32) -> (Sim, Out, u32) {
let src = Src { height, floor };
let mut sim = Sim::new(3);
+619 -2
View File
@@ -1,5 +1,7 @@
//! Radar scan cycles with ageing tracks (#46) and damage to a system's parts (#50).
use super::sight::{swept, FORECAST_AGE};
use super::battery::{Measure, RadarRole};
use super::regress::{answer_land, ridge_at};
use super::sight::{swept, FIRE_QUALITY, FORECAST_AGE};
use super::*;
fn flat() -> (Ground, Out) {
@@ -122,6 +124,9 @@ fn a_failed_radar_gives_no_own_tracks_but_the_network_still_feeds_it() {
let early = radar_at(&mut sim, SamKind::Radar, 120.0);
let id = drone_from(&mut sim, -150.0);
sim.sams[p].comps.0[Part::Sensor as usize] = 0.0;
// Hold fire: the fed track is now acted on (an unidentified contact is a candidate under the
// general rules, #133), and this test is about the feed, not about the intercept.
sim.sams[p].roles = 0;
for _ in 0..500 {
sim.step(&mut ground, None, &mut out);
}
@@ -173,7 +178,7 @@ fn a_close_blast_can_leave_a_firing_but_immobile_system() {
if s.alive() && s.part(Part::Tracks) <= 0.0 && s.part(Part::Launcher) > 0.0 && s.part(Part::Gun) > 0.0 {
assert!(!sim.order_move(0, DVec3::new(300.0, 70.0, 0.0)), "failed running gear must refuse a march");
assert!(why::missile_blocks(&sim.sams[0]) & why::LAUNCHER_DOWN == 0);
assert!(sim.why(0).iter().any(|c| c.text.contains("ходовая отказала")), "{:?}", sim.why(0).iter().map(|c| &c.text).collect::<Vec<_>>());
assert!(sim.why(0).iter().any(|c| matches!(c.reason, why::CheckReason::PartEffect(why::PartEffect::TracksFailed))), "{:?}", sim.why(0));
found = true;
break;
}
@@ -254,3 +259,615 @@ fn the_same_seed_rolls_the_same_scan_and_damage() {
};
assert_eq!(run(), run());
}
// ---------------------------------------------------------------- #133: the class estimate
#[test]
fn the_classifier_steps_by_the_measurements_alone() {
// The same observed speeds give the same estimate whatever the contact truly is, and a
// contrary measurement replaces the hypothesis instead of being ignored.
let mut est = ClassEst::Unknown;
assert_eq!(est.step(1, 0.6), ClassEst::Unknown, "one blip says nothing of the class");
est = est.step(2, 0.6);
assert_eq!(est, ClassEst::Probable(Class::Drone));
est = est.step(3, 0.62);
assert_eq!(est, ClassEst::Firm(Class::Drone), "agreeing measurements firm the guess");
// The contact proves much faster (or the first readings misled): the hypothesis gives way,
// and one measurement is not enough to firm the new one.
est = est.step(4, 5.0);
assert_eq!(est, ClassEst::Probable(Class::Supersonic));
est = est.step(5, 5.1);
assert_eq!(est, ClassEst::Firm(Class::Supersonic));
// Whatever the true kind, the same observations read the same: a Kinzhal measured as a slow
// propeller is, to the network, a drone until its measurements say otherwise.
assert_eq!(ClassEst::Unknown.step(2, 0.5), ClassEst::Probable(Class::Drone));
}
#[test]
fn the_speed_bands_read_the_games_own_kinds_right() {
// The bands sit between the game's speed clusters: the measured speed of a kind reads as its
// class, so a slow Lancet is no jet and a Shahed no cruise missile. A fast ballistic and a
// supersonic missile fly alike (the Iskander and the Zircon): speed alone leaves that
// ambiguity, documented on `Class::of_speed`.
for kind in DroneKind::ALL {
let spec = kind.spec();
if spec.class == Class::Ballistic && spec.speed < 6.5 {
continue;
}
assert_eq!(Class::of_speed(spec.speed), spec.class, "{kind:?} at {} blocks a tick", spec.speed);
}
assert_eq!(Class::of_speed(5.0), Class::Supersonic, "a fast ballistic and a supersonic fly alike");
}
#[test]
fn the_first_blip_gives_no_class_and_no_speed() {
let mut sim = Sim::new(5);
let (mut ground, mut out) = flat();
let r = radar_at(&mut sim, SamKind::Radar, 0.0);
let id = drone_from(&mut sim, -150.0);
let mut first = None;
for _ in 0..300 {
sim.step(&mut ground, None, &mut out);
if let Some(t) = sim.sams[r].track(id) {
first = Some(*t);
break;
}
}
let t = first.expect("a track of the drone");
assert_eq!(t.hits, 1);
assert_eq!(t.class, ClassEst::Unknown, "the first measurement must not name a class");
assert_eq!(t.vel, DVec3::ZERO, "the true velocity must not leak into the track");
}
#[test]
fn tracks_of_different_kinds_one_class_firm_the_same_estimate() {
// A Shahed and a Gerbera are different machines of one class, flying alike; the picture both
// networks end up holding is the same: a firm slow drone, never a model name. (Faster kinds
// cross this little radar's reach between beam passes: too few measurements to firm anything.)
let roles = SamKind::S400.spec().roles;
let mut seen = Vec::new();
for kind in [DroneKind::Shahed, DroneKind::Gerbera] {
let mut sim = Sim::new(7);
let (mut ground, mut out) = flat();
// One radar: an uninterrupted chain of measurements (two early-warning radars do not
// exchange tracks — a radar is fed only when it serves fire control — so the second one
// would measure from a blank picture, its own chain apart).
radar_at(&mut sim, SamKind::Radar, 0.0);
let from = DVec3::new(-150.0, 95.0, 40.0);
sim.add_drone(kind, from, DVec3::X, DVec3::new(5000.0, 95.0, 40.0));
let id = sim.drones.last().unwrap().id;
let mut est = None;
for _ in 0..700 {
sim.step(&mut ground, None, &mut out);
if let Some(t) = sim.picture().get(&id) {
est = Some(t.class);
}
}
assert_eq!(est, Some(ClassEst::Firm(Class::Drone)), "{kind:?}: {est:?}");
// The wording and the class-dependent decisions come from the estimate, not the machine.
let est = est.unwrap();
seen.push((est, est.name(), est.mark(), est.in_roles(roles)));
}
assert_eq!(seen[0], seen[1], "the same observations read differently for two kinds: {seen:?}");
}
#[test]
fn the_role_policy_keeps_the_unidentified_and_holds_fire_with_no_roles() {
let some = Class::Drone.bit() | Class::Jet.bit();
// An unidentified contact is not a block: it stays a candidate under the general rules.
assert!(ClassEst::Unknown.in_roles(some));
// No roles at all is holding fire: nothing is a candidate, the unidentified included.
assert!(!ClassEst::Unknown.in_roles(0), "hold fire must block the unidentified too");
// A probable guess is a block when its class is out of the roles, and a pass when in them.
assert!(ClassEst::Probable(Class::Drone).in_roles(some));
assert!(!ClassEst::Probable(Class::Cruise).in_roles(some));
assert!(ClassEst::Firm(Class::Jet).in_roles(some));
assert!(!ClassEst::Firm(Class::Ballistic).in_roles(0));
}
#[test]
fn a_gun_lets_go_of_a_track_classified_out_of_its_roles() {
// The Gepard's roles are drones, jets and cruise missiles: a supersonic missile is out of them.
assert_eq!(SamKind::Gepard.spec().roles & Class::Supersonic.bit(), 0);
let mut sim = Sim::new(11);
let (mut ground, mut out) = flat();
let p = radar_at(&mut sim, SamKind::Gepard, 0.0);
sim.add_drone(DroneKind::Zircon, DVec3::new(0.0, 95.0, -60.0), DVec3::Z, DVec3::new(0.0, 70.0, -700.0));
let id = sim.drones.last().unwrap().id;
sim.tick = 10;
let seed = |sim: &mut Sim, class| {
let d = sim.drones[0].clone();
sim.sams[p].tracks.retain(|t| t.id != d.id);
let source = sim.sams[p].id;
sim.sams[p].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: sim.tick, own_tick: sim.tick, source, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 400, hits: 3, locked: false });
};
// Taken while the class was unknown: the general rules make it a candidate.
seed(&mut sim, ClassEst::Unknown);
sim.step_sams(&mut ground, &mut out);
assert_eq!(sim.sams[p].gun_target, Some(id), "an unidentified track is not its gun target");
// Classified: no longer a class the gun engages, and it is let go instead of being fired at.
seed(&mut sim, ClassEst::Firm(Class::Supersonic));
sim.step_sams(&mut ground, &mut out);
assert_eq!(sim.sams[p].gun_target, None, "the gun kept a track its roles do not cover");
}
#[test]
fn forecasts_and_relays_add_no_confidence() {
let mut sim = Sim::new(7);
let (mut ground, mut out) = flat();
let a = radar_at(&mut sim, SamKind::Radar, 0.0);
let _b = radar_at(&mut sim, SamKind::Radar, 500.0);
let n = radar_at(&mut sim, SamKind::P1sun, 250.0);
let id = drone_from(&mut sim, -50.0);
// The source's own track: while no new measurement lands (the tick unchanged, the track only
// forecast onwards) the estimate must not move — a forecast is not data.
let mut prev: Option<(u64, ClassEst)> = None;
let mut relayed = 0;
for _ in 0..800 {
sim.step(&mut ground, None, &mut out);
if let Some(t) = sim.sams[a].track(id).copied() {
if let Some((tick, class)) = prev {
assert!(t.tick > tick || t.class == class, "a forecast or a re-read firmed the class: {tick}->{:?} {:?}->{:?}", t.tick, class, t.class);
}
prev = Some((t.tick, t.class));
}
// The network's copy carries the estimate as it was, with its measurement's age; passing
// it on adds nothing (the receiver never measures: own_tick stays 0).
if let Some(t) = sim.sams[n].track(id).copied() {
relayed += 1;
assert_eq!(t.own_tick, 0);
let freshest = sim.sams.iter().filter(|s| s.id != sim.sams[n].id).filter_map(|s| s.track(id)).max_by_key(|t| t.tick);
assert_eq!(Some(t.class), freshest.map(|f| f.class), "a relay altered the estimate");
}
}
assert!(relayed > 100, "the network never passed the track ({relayed})");
assert!(prev.is_some_and(|(_, c)| c.class().is_some()), "the source never classified the contact");
}
// ---------------------------------------------------------------- separate radar profiles (#134)
fn radar_with_role(sim: &mut Sim, role: RadarRole, x: f64) -> usize {
let id = sim.id();
let mut sam = Sam::new(id, SamKind::Radar, DVec3::new(x, 70.0, 0.0), 0.0);
sam.set_radar_role(role);
sim.sams.push(sam);
sim.sams.len() - 1
}
fn bearing(from: DVec3, to: DVec3) -> f64 {
(to.x - from.x).atan2(-(to.z - from.z))
}
/// The beam of every radar is pointed at one of `targets` in turn, so a test
/// does not depend on where the initial phase happened to be.
fn sweep(sim: &mut Sim, ground: &mut Ground, radars: &[usize], targets: &[DVec3], tick: u64) {
sim.tick = tick;
for (k, &i) in radars.iter().enumerate() {
let at = targets[(tick as usize + k) % targets.len()];
sim.sams[i].beam = bearing(sim.sams[i].pos, at);
}
sim.update_sight(ground);
}
#[derive(Default, Debug, PartialEq, Eq)]
struct ProfileStats {
first_high: Option<u64>,
first_low_refined: Option<u64>,
first_close_fire: Option<u64>,
max_channels: usize,
search_or_height_authorized: bool,
}
/// A low contact at 330 blocks (above the search/engagement horizon but below
/// the mast's), a high contact at 700/430 (inside the search reach but outside
/// the mast's and engagement's local search), and two close contacts for the
/// tracked-contact channels.
fn profile_world(roles: &[RadarRole]) -> (Sim, Vec<usize>, Vec<u32>, Ground) {
let mut sim = Sim::new(134);
let radars: Vec<usize> = roles.iter().map(|role| radar_with_role(&mut sim, *role, 0.0)).collect();
sim.add_drone(DroneKind::Shahed, DVec3::new(330.0, 95.0, 0.0), DVec3::Z, DVec3::new(330.0, 95.0, 0.0));
let low = sim.drones.last().unwrap().id;
sim.add_drone(DroneKind::Shahed, DVec3::new(700.0, 500.0, 0.0), DVec3::Z, DVec3::new(700.0, 500.0, 0.0));
let high = sim.drones.last().unwrap().id;
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
let close1 = sim.drones.last().unwrap().id;
sim.add_drone(DroneKind::Gerbera, DVec3::new(180.0, 130.0, 40.0), DVec3::Z, DVec3::new(180.0, 130.0, 40.0));
let close2 = sim.drones.last().unwrap().id;
(sim, radars, vec![low, high, close1, close2], Ground::default())
}
fn run_profile_world(roles: &[RadarRole], ticks: u64) -> (ProfileStats, Sim, Vec<usize>, Vec<u32>) {
let (mut sim, radars, ids, mut ground) = profile_world(roles);
let [low, high, close1, close2] = [ids[0], ids[1], ids[2], ids[3]];
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
let mut stats = ProfileStats::default();
for tick in 1..=ticks {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
for &i in &radars {
let sam = &sim.sams[i];
for t in sam.tracks.iter().filter(|t| t.own_tick > 0) {
match t.id {
id if id == high && stats.first_high.is_none() => stats.first_high = Some(tick),
id if id == low && t.product == Measure::Refine && stats.first_low_refined.is_none() => stats.first_low_refined = Some(tick),
id if (id == close1 || id == close2) && t.product == Measure::Fire && t.own_authorizes(sim.tick) && stats.first_close_fire.is_none() => stats.first_close_fire = Some(tick),
_ => {}
}
}
if sam.radar_profile().id == "radar_search" || sam.radar_profile().id == "radar_height" {
stats.search_or_height_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
}
stats.max_channels = stats.max_channels.max(sam.own_channels_used(sim.tick));
}
}
(stats, sim, radars, ids)
}
#[test]
fn each_profile_is_useful_alone_and_the_full_set_covers_all_three_jobs() {
let search = run_profile_world(&[RadarRole::Search], 500).0;
assert!(search.first_high.is_some(), "the search radar gives no early high plot: {search:?}");
assert!(search.first_low_refined.is_none(), "search refined a low contact it does not reach: {search:?}");
assert!(search.first_close_fire.is_none(), "search authorized a launch: {search:?}");
let height = run_profile_world(&[RadarRole::Height], 500).0;
assert!(height.first_high.is_none(), "the mast radar searched beyond its local patch: {height:?}");
assert!(height.first_low_refined.is_some(), "the mast radar did not refine the low contact: {height:?}");
assert!(height.first_close_fire.is_none(), "the mast radar authorized a launch: {height:?}");
let engagement = run_profile_world(&[RadarRole::Engagement], 500).0;
assert!(engagement.first_high.is_none(), "the engagement radar searched beyond its local patch: {engagement:?}");
assert!(engagement.first_low_refined.is_none(), "the engagement radar reached a low contact below the horizon: {engagement:?}");
assert!(engagement.first_close_fire.is_some(), "the engagement radar gave no fire plot: {engagement:?}");
assert!(engagement.max_channels <= 2, "more than two tracked contacts: {engagement:?}");
let search_height = run_profile_world(&[RadarRole::Search, RadarRole::Height], 500).0;
assert!(search_height.first_high.is_some() && search_height.first_low_refined.is_some());
assert!(search_height.first_close_fire.is_none(), "a search/height pair authorized a launch: {search_height:?}");
let search_engagement = run_profile_world(&[RadarRole::Search, RadarRole::Engagement], 500).0;
assert!(search_engagement.first_high.is_some() && search_engagement.first_close_fire.is_some());
assert!(search_engagement.first_low_refined.is_none(), "the pair covered the mast's low gap: {search_engagement:?}");
let height_engagement = run_profile_world(&[RadarRole::Height, RadarRole::Engagement], 500).0;
assert!(height_engagement.first_low_refined.is_some() && height_engagement.first_close_fire.is_some());
assert!(height_engagement.first_high.is_none(), "the pair covered the search's far picture: {height_engagement:?}");
let full = run_profile_world(&[RadarRole::Search, RadarRole::Height, RadarRole::Engagement], 500).0;
assert!(full.first_high.is_some() && full.first_low_refined.is_some() && full.first_close_fire.is_some(), "{full:?}");
assert!(!full.search_or_height_authorized, "a non-fire radar authorized a launch");
// There is no set bonus in the profile table: a duplicated station adds no
// function, and the full set's advantage is only the union of the three jobs.
let duplicate = run_profile_world(&[RadarRole::Search, RadarRole::Search], 500).0;
assert!(duplicate.first_low_refined.is_none() && duplicate.first_close_fire.is_none(), "two search radars invented another function: {duplicate:?}");
}
#[test]
fn network_relay_keeps_source_age_and_quality_but_not_launch_authority() {
let mut sim = Sim::new(1341);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 10.0);
let receiver = {
let id = sim.id();
let mut s400 = Sam::new(id, SamKind::S400, DVec3::new(20.0, 70.0, 0.0), 0.0);
// A blind receiver: only the network can give it a track.
s400.comps.0[Part::Sensor as usize] = 0.0;
s400.roles = 0xff;
sim.sams.push(s400);
sim.sams.len() - 1
};
sim.add_drone(DroneKind::Shahed, DVec3::new(200.0, 120.0, 0.0), DVec3::Z, DVec3::new(200.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
let radars = [search, engagement];
for tick in 1..=120 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let own = sim.sams[engagement].track(id).expect("the engagement radar measured the target");
assert_eq!(own.source, sim.sams[engagement].id);
assert_eq!(own.product, Measure::Fire);
assert!(own.quality >= FIRE_QUALITY && own.own_authorizes(sim.tick));
let relayed = sim.sams[receiver].track(id).expect("the network shared the plot");
assert_eq!(relayed.own_tick, 0, "a relay became the receiver's own measurement");
assert_eq!(relayed.tick, own.tick, "a relay refreshed the measurement's age");
assert!(relayed.product == Measure::Fire && relayed.quality == own.quality, "relay lost product/quality");
assert_eq!(relayed.source, sim.sams[engagement].id, "relay lost the measuring station");
assert!(!relayed.own_authorizes(sim.tick));
let opts = why::Opts { last_chance: false, far_shots: false };
{
let load = sim.sams[receiver].kind.spec().missile.as_ref().unwrap();
let drone = &sim.drones[0];
assert!(why::basis(&sim.sams[receiver], load, relayed, drone, sim.tick, 0, 1.0, opts, true, false).is_none(), "a relayed plot authorized a launch");
}
// A launcher without a radar may use the supporting radar's own confirmed plot.
sim.sams[receiver].set_mode(battery::SamMode::LauncherOnly);
for tick in 121..=122 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let relayed = *sim.sams[receiver].track(id).expect("the launcher re-received the network plot");
assert!(why::radar_cue(&sim.sams[receiver], &[&sim.sams[engagement]], id, sim.tick));
{
let load = sim.sams[receiver].kind.spec().missile.as_ref().unwrap();
let drone = &sim.drones[0];
assert!(why::basis(&sim.sams[receiver], load, &relayed, drone, sim.tick, 0, 1.0, opts, true, false).is_some());
}
// The search radar's plot is coarse: it does not authorize even a launcher.
assert!(!why::radar_cue(&sim.sams[receiver], &[&sim.sams[search]], id, sim.tick));
// A broken data link ends the cue even while the radar itself still measures.
sim.sams[engagement].comps.0[Part::Comms as usize] = 0.0;
assert_eq!(sim.sams[engagement].link_range(), 0.0);
assert!(!why::radar_cue(&sim.sams[receiver], &[&sim.sams[engagement]], id, sim.tick), "a broken link still cued a launch");
}
#[test]
fn a_network_plot_cues_a_separate_fire_radar_but_not_the_embedded_one() {
// #145: a fire-quality radar is cued to look at a network contact, but the weapon's own
// embedded radar is not — cueing every relayed contact each tick flooded the embedded fire
// control with one-tick plots and degraded the intercepts. The embedded radar keeps its
// beam/revisit/lock acquisition; a separate engagement radar still takes the cue.
let mut sim = Sim::new(145);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 10.0);
let embedded = {
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::S400, DVec3::new(20.0, 70.0, 0.0), 0.0));
sim.sams.len() - 1
};
sim.add_drone(DroneKind::Shahed, DVec3::new(150.0, 120.0, 0.0), DVec3::Z, DVec3::new(150.0, 120.0, 0.0));
let id = sim.drones[0].id;
let at = sim.drones[0].pos;
let away = DVec3::new(-600.0, 120.0, 0.0);
let mut ground = Ground::default();
for tick in 1..=8 {
sim.tick = tick;
// The search radar measures the contact; the embedded and engagement radars look away,
// so only a cue (not the beam, a revisit or a lock) could give them an own plot.
sim.sams[search].beam = bearing(sim.sams[search].pos, at);
sim.sams[embedded].beam = bearing(sim.sams[embedded].pos, away);
sim.sams[engagement].beam = bearing(sim.sams[engagement].pos, away);
sim.update_sight(&mut ground);
}
let emb = sim.sams[embedded].track(id).expect("the embedded radar holds the network track");
assert_eq!(emb.own_tick, 0, "the embedded radar cue-measured a relayed contact (#145)");
assert!(!emb.own_authorizes(sim.tick), "a relayed plot gave the embedded radar fire authority");
let eng = sim.sams[engagement].track(id).expect("the engagement radar holds the track");
assert!(eng.own_tick > 0, "a separate fire-quality radar was not cued by the network plot");
}
#[test]
fn the_air_picture_prefers_the_better_plot_at_one_tick() {
let mut sim = Sim::new(1345);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let track = radar_with_role(&mut sim, RadarRole::Engagement, 10.0);
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
for tick in 1..=5 {
sweep(&mut sim, &mut ground, &[search, track], &targets, tick);
}
let pic = sim.air_picture();
let t = pic.tracks.iter().find(|t| t.id == id).expect("the raid is on the picture");
assert_eq!(t.source, sim.sams[track].id, "a coarse plot won over the better one at the same tick");
assert_eq!(t.product, Measure::Fire);
assert!(t.own_authorizes(sim.tick));
}
#[test]
fn tracked_channels_are_a_hard_limit_but_the_rest_keep_search_plots() {
let mut sim = Sim::new(1344);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 0.0);
for x in [100.0, 140.0, 180.0, 220.0] {
sim.add_drone(DroneKind::Gerbera, DVec3::new(x, 120.0, 0.0), DVec3::Z, DVec3::new(x, 120.0, 0.0));
}
let mut ground = Ground::default();
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
for tick in 1..=40 {
sweep(&mut sim, &mut ground, &[engagement], &targets, tick);
}
let own: Vec<&Track> = sim.sams[engagement].tracks.iter().filter(|t| t.own_tick > 0).collect();
let precise = own.iter().filter(|t| t.own_product != Measure::Search).count();
assert_eq!(precise, 2, "the station refined more contacts than its channels: {own:?}");
assert_eq!(sim.sams[engagement].own_channels_used(sim.tick), 2);
assert_eq!(own.len(), 4, "a full station stopped giving coarse search plots: {own:?}");
assert!(own.iter().filter(|t| t.own_product == Measure::Search).all(|t| !t.own_authorizes(sim.tick)));
}
// #140: a network heartbeat keeps an old contact's track fresh, but never holds the station's
// channel: two stale own fire plots free the channels for a new contact, and the survey tracks
// of the old ones stay on the picture — with the search radar left running.
#[test]
fn stale_own_plots_free_their_channels_while_the_network_keeps_the_tracks() {
let mut sim = Sim::new(140);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 0.0);
let search = radar_with_role(&mut sim, RadarRole::Search, 1550.0);
for x in [100.0, 140.0] {
sim.add_drone(DroneKind::Gerbera, DVec3::new(x, 120.0, 0.0), DVec3::Z, DVec3::new(x, 120.0, 0.0));
}
let old: Vec<u32> = sim.drones.iter().map(|d| d.id).collect();
let mut ground = Ground::default();
let radars = [engagement, search];
for tick in 1..=40 {
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let frozen: Vec<u64> = old
.iter()
.map(|&id| {
let t = sim.sams[engagement].track(id).expect("the station took the contact");
assert_ne!(t.own_product, Measure::Search, "the station took no channel: {t:?}");
t.own_tick
})
.collect();
assert_eq!(sim.sams[engagement].own_channels_used(sim.tick), 2);
// The two contacts leave the station's reach for the search radar beside them; the new one
// arrives close to the station. Only the network keeps the old tracks alive now.
for (k, d) in sim.drones.iter_mut().enumerate() {
d.pos = DVec3::new(1600.0 + 20.0 * k as f64, 120.0, 0.0);
}
sim.add_drone(DroneKind::Gerbera, DVec3::new(180.0, 120.0, 0.0), DVec3::Z, DVec3::new(180.0, 120.0, 0.0));
let fresh = sim.drones.last().unwrap().id;
for tick in 41..=750 {
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let now = sim.tick;
let station = &sim.sams[engagement];
assert_eq!(station.own_channels_used(now), 1, "the stale channels still hold: {:?}", station.tracks);
for (&id, &own_tick) in old.iter().zip(&frozen) {
let t = station.track(id).expect("the survey track was thrown away with its channel");
assert_eq!(t.own_tick, own_tick, "the network renewed the station's own plot");
assert!(t.tick > 500, "the network stopped relaying the old contact: {t:?}");
assert_eq!(t.product, Measure::Search, "the relayed survey plot is gone: {t:?}");
assert!(!t.holds_channel(now, station.track_ttl() as u64), "an old own plot still holds a channel: {t:?}");
assert!(!t.own_authorizes(now));
}
let new = station.track(fresh).expect("the new contact is not held");
assert_eq!(new.own_product, Measure::Fire, "the new contact never got a channel: {new:?}");
assert!(new.own_authorizes(now), "the new contact's own fire plot does not authorize: {new:?}");
}
#[test]
fn off_and_damage_remove_the_station_and_its_quality_without_touching_neighbours() {
let mut sim = Sim::new(1342);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 20.0);
sim.add_drone(DroneKind::Gerbera, DVec3::new(150.0, 120.0, 0.0), DVec3::Z, DVec3::new(150.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
let radars = [search, engagement];
for tick in 1..=80 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
assert!(sim.sams[engagement].track(id).is_some_and(|t| t.own_authorizes(sim.tick)));
let healthy = sim.sams[engagement].track(id).unwrap().own_quality;
// Off: the station emits nothing, its own plots stop, the neighbour still feeds the network.
sim.sams[engagement].radar_on = false;
let before = sim.sams[engagement].track(id).map(|t| t.own_tick);
for tick in 81..=110 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
assert!(!sim.sams[engagement].radar_up());
assert_eq!(sim.sams[engagement].track(id).map(|t| t.own_tick), before, "a silent radar renewed its own plot");
assert!(sim.sams[search].track(id).is_some_and(|t| t.own_tick > 0));
// Damage: a worn sensor still measures, with worse quality and no launch right.
sim.sams[engagement].radar_on = true;
sim.sams[engagement].comps.0[Part::Sensor as usize] = 0.2;
for tick in 111..=180 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let worn = sim.sams[engagement].track(id).expect("a worn radar still measures");
assert!(worn.own_quality < healthy, "damage did not lower quality: {worn:?}");
assert!(!worn.own_authorizes(sim.tick), "a worn sensor still authorized a launch");
}
#[test]
fn multifunction_and_embedded_radars_keep_their_fire_authority() {
let mut sim = Sim::new(1343);
let multi = radar_with_role(&mut sim, RadarRole::Multifunction, 0.0);
let pantsir = radar_at(&mut sim, SamKind::Pantsir, 20.0);
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
let radars = [multi, pantsir];
for tick in 1..=100 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
assert!(sim.sams[multi].track(id).is_some_and(|t| t.own_authorizes(sim.tick)), "the universal profile lost its own fire plot");
assert!(sim.sams[pantsir].track(id).is_some_and(|t| t.own_authorizes(sim.tick)), "an embedded radar lost its own fire plot");
}
#[test]
fn profiles_keep_their_jobs_over_a_ridge_on_one_seed_and_land() {
// One seed and one ridge: the low contact hides behind it, the high one flies over it,
// and two close contacts compete for the engagement channels on the far side.
let targets = [
DVec3::new(250.0, 84.0, 0.0),
DVec3::new(700.0, 500.0, 0.0),
DVec3::new(240.0, 90.0, 30.0),
DVec3::new(260.0, 95.0, -20.0),
];
#[derive(Default, Debug)]
struct RidgeStats {
low_marked: bool,
low_refined: bool,
low_fire: bool,
high_marked: bool,
track_channels: usize,
nonfire_authorized: bool,
}
let run = |stations: &[(RadarRole, DVec3)], land| -> RidgeStats {
let mut sim = Sim::new(134);
let radars: Vec<usize> = stations
.iter()
.map(|(role, pos)| {
let id = sim.id();
let mut sam = Sam::new(id, SamKind::Radar, *pos, 0.0);
sam.set_radar_role(*role);
sim.sams.push(sam);
sim.sams.len() - 1
})
.collect();
for (k, pos) in targets.iter().enumerate() {
let kind = if k < 2 { DroneKind::Shahed } else { DroneKind::Gerbera };
sim.add_drone(kind, *pos, DVec3::Z, *pos);
}
let ids: Vec<u32> = sim.drones.iter().map(|d| d.id).collect();
let mut ground = Ground::default();
// Unknown land hides nothing: let the heights answer before any measurement counts.
for tick in 1..=60 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
answer_land(&mut ground, land, tick);
}
for i in &radars {
sim.sams[*i].tracks.clear();
}
let mut stats = RidgeStats::default();
for tick in 61..=560 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
answer_land(&mut ground, land, tick);
for &i in &radars {
let sam = &sim.sams[i];
let profile = sam.radar_profile();
for t in sam.tracks.iter().filter(|t| t.own_tick > 0) {
if t.id == ids[0] {
stats.low_marked = true;
stats.low_refined |= t.product == Measure::Refine;
stats.low_fire |= t.own_authorizes(sim.tick);
}
stats.high_marked |= t.id == ids[1];
}
if profile.id == "radar_track" {
stats.track_channels = stats.track_channels.max(sam.own_channels_used(sim.tick));
}
if profile.id == "radar_search" || profile.id == "radar_height" {
stats.nonfire_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
}
}
}
stats
};
let near = DVec3::new(0.0, 64.0, 0.0);
let far = DVec3::new(220.0, 64.0, 0.0);
let ridge = ridge_at(150, 100, 60);
let search = run(&[(RadarRole::Search, near)], &ridge);
assert!(search.high_marked, "the search radar lost the high contact over the ridge: {search:?}");
assert!(!search.low_marked, "the search radar saw through the ridge: {search:?}");
// The same station on flat land does mark the low contact: the ridge is what hides it.
let flat = ridge_at(150, 0, 60);
let control = run(&[(RadarRole::Search, near)], &flat);
assert!(control.low_marked, "the control lost the low contact on flat land: {control:?}");
let height = run(&[(RadarRole::Height, far)], &ridge);
assert!(height.low_refined, "the mast did not refine the low contact behind the ridge: {height:?}");
assert!(!height.high_marked && !height.low_fire, "the mast left its patch or authorized a launch: {height:?}");
let engagement = run(&[(RadarRole::Engagement, far)], &ridge);
assert!(engagement.low_fire, "the engagement radar gave no fire plot on the low contact: {engagement:?}");
assert!(!engagement.high_marked, "the engagement radar searched beyond its patch: {engagement:?}");
assert!(engagement.track_channels <= 2, "more than two tracked contacts: {engagement:?}");
let full = run(&[(RadarRole::Search, near), (RadarRole::Height, far), (RadarRole::Engagement, far)], &ridge);
assert!(full.high_marked && full.low_refined && full.low_fire, "the full set lost a job on the ridge: {full:?}");
assert!(!full.nonfire_authorized, "a non-fire radar authorized a launch: {full:?}");
assert!(full.track_channels <= 2, "the engagement radar exceeded its channels: {full:?}");
}
+264 -42
View File
@@ -8,41 +8,50 @@
//! (a period by the kind of radar; an electronic one also revisits what it holds
//! more often), a target is measured when the beam passes it, with a chance that
//! falls with range and size, and the measurement is kept as a *track*: where it
//! was and how fast it went then, and when. Between measurements the track is
//! was measured, how fast it then seemed to go (from the measured places, never
//! the target's own figures), and when. Between measurements the track is
//! carried on by that velocity (a forecast, shown as one), and after three missed
//! scans it is dropped. A fire-control lock on a target the system is engaging is
//! a dedicated channel: it measures every tick while the target is in reach and in
//! sight. The network passes tracks with the age of their measurement; relaying
//! makes none of them fresher.
//! sight. The track also carries what the measurements say of the contact's class,
//! the estimate growing only on real measurements: a forecast, a relayed copy adds
//! nothing to it. The network passes tracks with the age of their measurement;
//! relaying makes none of them fresher.
use super::*;
/// Rays round a radar, and blocks between the land's samples along them.
const RAYS: usize = 48;
const STEP: f64 = 16.0;
/// The longest profiles use wider intervals to retain the same height-cache footprint.
const MAX_RAY_STEPS: f64 = 160.0;
/// How far units share their tracks (the network's data links).
pub(super) const LINK: f64 = 2250.0;
/// A launcher fires on a track no older than this (ticks); a gun needs its own radar's, newer than `GUN_AGE`.
pub(super) const MISSILE_AGE: u64 = 120;
pub(super) const GUN_AGE: u64 = 3;
/// A fire plot below this quality is not confirmed enough to authorize a launch.
pub const FIRE_QUALITY: u8 = 50;
/// A gun takes a target its radar measured this recently (then the lock refreshes it every tick).
pub(super) const GUN_PICK_AGE: u64 = 40;
/// A track older than this is shown as a forecast.
pub const FORECAST_AGE: u64 = 20;
/// Radio horizon: `HORIZON * (√mast + √height)` blocks.
const HORIZON: f64 = 35.0;
/// The game's radio horizon: `HORIZON * (√mast + √height)` blocks.
pub(super) const HORIZON: f64 = 95.0;
/// Anything this near is seen (and heard), whatever hides it.
const NEAR: f64 = 24.0;
pub(super) const NEAR: f64 = 24.0;
pub(super) struct Horizon {
/// Per ray, per sample out: the steepest rise of the land so far (tan of its elevation).
pub(super) rays: Vec<Vec<f32>>,
antenna: DVec3,
reach: f64,
step: f64,
}
impl Horizon {
fn build(antenna: DVec3, reach: f64, ground: &mut Ground, now: u64) -> Self {
let steps = (reach / STEP).ceil() as usize + 1;
let step = STEP.max(reach / MAX_RAY_STEPS);
let steps = (reach / step).ceil() as usize + 1;
let rays = (0..RAYS)
.map(|r| {
let a = r as f64 / RAYS as f64 * TAU;
@@ -50,7 +59,7 @@ impl Horizon {
let mut top = f32::NEG_INFINITY;
(1..=steps)
.map(|k| {
let d = k as f64 * STEP;
let d = k as f64 * step;
// Unknown land (not loaded, not answered yet) hides nothing.
if let Some(g) = ground.at(antenna + dir * d, now) {
top = top.max(((g - antenna.y) / d) as f32);
@@ -60,7 +69,7 @@ impl Horizon {
.collect()
})
.collect();
Self { rays, antenna, reach }
Self { rays, antenna, reach, step }
}
fn matches(&self, sam: &Sam) -> bool {
@@ -70,7 +79,7 @@ impl Horizon {
pub(super) fn hides(&self, antenna: DVec3, p: DVec3) -> bool {
let rel = p - antenna;
let flat = (rel.x * rel.x + rel.z * rel.z).sqrt();
let k = (flat / STEP) as usize;
let k = (flat / self.step) as usize;
if k == 0 {
return false;
}
@@ -87,7 +96,7 @@ pub(super) fn antenna(sam: &Sam) -> DVec3 {
}
fn sensor_span(sam: &Sam) -> f64 {
sam.kind.spec().sensor * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor() } else { 1.0 }
sam.kind.spec().sensor * sam.radar_profile().reach
}
/// How far a system's search radar reaches for this kind at `height` over the land:
@@ -97,7 +106,7 @@ pub(super) fn reach(sam: &Sam, kind: DroneKind, height: f64) -> f64 {
if spec.sensor <= 0.0 {
return 0.0;
}
let radar = spec.sensor * sam.radar_fit() * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor() } else { 1.0 } * kind.rcs().powf(0.25);
let radar = spec.sensor * sam.radar_fit() * sam.radar_profile().reach * kind.rcs().powf(0.25);
let horizon = HORIZON * (sam.sensor_mast().sqrt() + height.max(0.0).sqrt());
radar.min(horizon).max(NEAR)
}
@@ -142,7 +151,7 @@ impl Sim {
let fit = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(1.0, |s| s.radar_fit());
let height = LOW_KIND.spec().clearance;
let mast = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(spec.mast, |s| s.sensor_mast());
let factor = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).filter(|s| s.kind == SamKind::Radar).map_or(1.0, |s| s.radar_role.reach_factor());
let factor = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(1.0, |s| s.radar_profile().reach);
let radar = spec.sensor * fit * factor * LOW_KIND.rcs().powf(0.25);
let reach = radar.min(HORIZON * (mast.sqrt() + height.sqrt())).max(NEAR);
let terrain = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).is_some_and(|s| self.horizons.get(&s.id).is_some_and(|h| h.matches(s)));
@@ -243,17 +252,31 @@ impl Ident {
}
/// What a system knows of one target: the last measurement, not the target itself.
///
/// The track never carries the target's type or its true velocity (#133): `class` is what the
/// radars inferred from the measurements so far, `vel` the speed those measurements showed —
/// none from the first blip, then the change of the measured places between real measurements,
/// smoothed a little. The forecast and the guns live with that.
#[derive(Clone, Copy, Debug)]
pub struct Track {
pub id: u32,
/// What the radar made of it when it measured (the class the picture shows).
pub kind: DroneKind,
/// Where it was and how it went when last measured (blocks, blocks a tick).
/// What the radars make of it from the measurements (never the target's own type).
pub class: ClassEst,
/// Where it was measured and how fast it seemed to go then (blocks, blocks a tick).
pub pos: DVec3,
pub vel: DVec3,
/// When that was, and when this system's own radar last measured it (0: never, the network's only).
pub tick: u64,
pub own_tick: u64,
/// The station that measured the latest plot, and what it is good for.
pub source: u32,
pub product: battery::Measure,
/// Measurement quality (0..100), separate from identification (`hits`).
pub quality: u8,
/// This system's own measurement provenance. A fresher relay may replace
/// the published plot without granting or erasing the station's own right.
pub own_product: battery::Measure,
pub own_quality: u8,
/// Ticks the track lives without a new measurement.
pub ttl: u32,
pub hits: u8,
@@ -294,6 +317,34 @@ impl Track {
pub fn own_within(&self, now: u64, age: u64) -> bool {
self.own_tick > 0 && now.saturating_sub(self.own_tick) <= age
}
/// The station's own measurement was a confirmed fire plot, fresh enough.
/// A relayed plot has `own_tick == 0` and never passes this test.
pub fn own_fire_within(&self, now: u64, age: u64) -> bool {
self.own_within(now, age) && self.own_product.allows_fire() && self.own_quality >= FIRE_QUALITY
}
/// Own plot good enough for a launcher's ordinary shot.
pub fn own_authorizes(&self, now: u64) -> bool {
self.own_fire_within(now, MISSILE_AGE)
}
/// The station's own refine/fire channel on this contact is still live: the plot is its own,
/// finer than a search, and no older than the station keeps a contact without a fresh
/// measurement. A relayed plot never holds a channel: the network's heartbeat keeps the
/// track fresh, not the station's own tracking (#140).
pub fn holds_channel(&self, now: u64, ttl: u64) -> bool {
self.own_tick > 0
&& self.own_product != battery::Measure::Search
&& now.saturating_sub(self.own_tick) <= ttl
}
/// Who measured the latest plot, as an ID (`0`: no station).
pub fn measured_by(&self) -> Option<u32> {
(self.source != 0).then_some(self.source)
}
/// One passive optical look at this contact (#136): refines the class alone. The plot, its
/// age, source, quality and the station's own fire rights are untouched — optics never
/// authorize a shot and never make a track fresher.
pub fn refine_class_optical(&mut self, class: Class, uncertainty: f64) {
self.class = self.class.step_optical(class, uncertainty);
}
pub fn ident(&self) -> Ident {
match self.hits {
0 | 1 => Ident::Unknown,
@@ -310,16 +361,12 @@ impl Track {
impl Sam {
/// Fictional antenna height and scan characteristics for gameplay roles.
pub(super) fn sensor_mast(&self) -> f64 {
self.kind.spec().mast + if self.kind == SamKind::Radar && self.radar_role == battery::RadarRole::Height { 8.0 } else { 0.0 }
self.kind.spec().mast + self.radar_profile().mast
}
pub(super) fn scan_profile(&self) -> Scan {
if self.kind != SamKind::Radar { return self.kind.scan(); }
match self.radar_role {
battery::RadarRole::Multifunction => self.kind.scan(),
battery::RadarRole::Search => Scan { period: 170, agile: false },
battery::RadarRole::Engagement => Scan { period: 70, agile: true },
battery::RadarRole::Height => Scan { period: 140, agile: false },
}
let profile = self.radar_profile();
Scan { period: profile.cycle, agile: profile.agile }
}
/// Ticks for its beam to go round (longer when the radar is damaged).
pub(super) fn scan_ticks(&self) -> f64 {
@@ -329,9 +376,24 @@ impl Sam {
pub fn radar_up(&self) -> bool {
self.radar_on && self.mode != battery::SamMode::LauncherOnly && self.alive() && !self.moving() && self.kind.spec().sensor > 0.0 && self.part(Part::Sensor) > 0.0
}
/// Its jammer is really on the air: the switch, a live station and a deployed one. The same
/// state `step_ew` transmits in, so a look names jamming only while the transmitter works.
pub fn ew_up(&self) -> bool {
self.ew_on && !self.ew_lock && self.alive() && !self.moving()
}
pub fn track(&self, id: u32) -> Option<&Track> {
self.tracks.iter().find(|t| t.id == id)
}
/// Ticks a contact stays this station's own without a fresh measurement: three missed turns, at least 60.
pub(super) fn track_ttl(&self) -> u32 {
((self.scan_ticks() * 3.0) as u32).max(60)
}
/// Refined/fire channels this station is currently using: the same test the planner applies,
/// so the panel and the allocation never disagree about a stale channel.
pub fn own_channels_used(&self, now: u64) -> usize {
let ttl = self.track_ttl() as u64;
self.tracks.iter().filter(|t| t.holds_channel(now, ttl)).count()
}
}
/// Whether a beam that moved from `from` by `w` radians this tick passed `bearing` (all angles taken round 2π,
@@ -345,10 +407,18 @@ fn merge(tracks: &mut Vec<Track>, index: &mut HashMap<u32, usize>, t: Track) {
match index.get(&t.id) {
Some(&k) => {
let mine = &mut tracks[k];
if t.tick > mine.tick {
let (own_tick, locked) = (mine.own_tick, if t.own_tick > 0 { t.locked } else { mine.locked });
// Prefer the fresher plot; at the same tick the better one (a fire plot
// over a coarse search plot), without making anything newer.
if t.tick > mine.tick || (t.tick == mine.tick && t.quality > mine.quality) {
// A relayed plot is published with its source/quality, but it
// neither refreshes nor erases this station's own measurement and its right.
let (own_tick, own_product, own_quality, locked) = if t.own_tick > 0 {
(t.own_tick, t.own_product, t.own_quality, t.locked)
} else {
(mine.own_tick, mine.own_product, mine.own_quality, mine.locked)
};
let hits = mine.hits.max(t.hits);
*mine = Track { own_tick: if t.own_tick > 0 { t.own_tick } else { own_tick }, hits, locked, ..t };
*mine = Track { own_tick, own_product, own_quality, hits, locked, ..t };
}
}
None => {
@@ -358,6 +428,23 @@ fn merge(tracks: &mut Vec<Track>, index: &mut HashMap<u32, usize>, t: Track) {
}
}
/// A plot's quality (0..100). It uses only the measured geometry and the
/// station's own fit, never the target's hidden state.
fn plot_quality(sam: &Sam, profile: battery::RadarProfile, product: battery::Measure, ratio: f64, height: f64) -> u8 {
let ratio = ratio.clamp(0.0, 1.0);
let base = match profile.id {
"radar_search" => 46.0 - 14.0 * ratio,
"radar_height" => 74.0 - 12.0 * ratio + if height < 120.0 { 8.0 } else if height < 200.0 { 3.0 } else { 0.0 },
"radar_track" => 88.0 - 12.0 * ratio,
"radar_multi" => 72.0 - 14.0 * ratio,
_ => 78.0 - 14.0 * ratio,
};
// A search plot is coarse whatever the profile; only a matched refinement or
// a fire plot gets the profile's accuracy.
let base = if product == battery::Measure::Search { base.min(48.0) } else { base };
(base * sam.radar_fit()).round().clamp(5.0, 99.0) as u8
}
impl Sim {
/// Rebuilds the systems' horizons in turn, then lets each radar's beam pass the sky: new measurements
/// into the tracks, old tracks out, and the network's tracks shared.
@@ -386,6 +473,9 @@ impl Sim {
let heights: Vec<Option<f64>> =
self.drones.iter().map(|d| ground.at(d.pos, now).map(|g| d.pos.y - g)).collect();
let drone_at: HashMap<u32, usize> = self.drones.iter().enumerate().map(|(k, d)| (d.id, k)).collect();
if now % 80 == 0 {
self.breakthroughs.active.retain(|id, _| drone_at.contains_key(id));
}
let seed = self.seed;
let mut index: HashMap<u32, usize> = HashMap::new();
for sam in &mut self.sams {
@@ -401,13 +491,18 @@ impl Sim {
index.clear();
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
let spec = sam.kind.spec();
let profile = sam.radar_profile();
let scan = sam.scan_profile();
let period = sam.scan_ticks();
let w = TAU / period;
let (b0, ttl) = (sam.beam, ((period * 3.0) as u32).max(60));
let (b0, ttl) = (sam.beam, sam.track_ttl());
sam.beam = (b0 + w) % TAU;
let at = antenna(sam);
let horizon = self.horizons.get(&sam.id);
let local = spec.sensor * profile.local;
// Channels already refining or holding fire plots, by the same test the UI shows:
// a stale own plot (the network may keep the track) no longer occupies one.
let mut used = sam.own_channels_used(now);
let mut fresh: Vec<Track> = Vec::new();
for (d, h) in self.drones.iter().zip(&heights) {
if !d.alive() {
@@ -415,7 +510,7 @@ impl Sim {
}
let rel = d.pos - at;
let dist = rel.length();
if dist > spec.sensor * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor().max(1.0) * 1.2 } else { 1.2 } {
if dist > spec.sensor * profile.reach.max(1.0) * 1.2 {
continue;
}
let locked = sam.target == Some(d.id) || sam.gun_target == Some(d.id);
@@ -423,13 +518,38 @@ impl Sim {
// The beam passes its bearing this tick (the angle wraps at 2π: the difference is taken round).
let in_beam = swept(rel.x.atan2(-rel.z), b0, w);
let revisit = scan.agile && held.is_some_and(|t| t.own_tick > 0 && now - t.own_tick >= (period / 3.0) as u64);
// A search radar's network track cues this fictional tracking radar to look, but is
// never itself a measurement: reach, terrain, probability and noise still apply.
let cue = sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement
// A network plot cues a *separate* fire-quality radar to look, but is never itself
// a measurement: reach, terrain, probability and noise still apply. The weapon's
// own embedded radar is not cued: measuring every relayed contact each tick flooded
// its fire control with one-tick plots whose noisy velocity degraded the intercepts
// (#145); it keeps its beam/revisit/lock acquisition, as before the profiles (#134).
let cue = sam.kind == SamKind::Radar && profile.allows(battery::Measure::Fire)
&& held.is_some_and(|t| t.own_tick == 0 && t.age(now) <= MISSILE_AGE);
if !(in_beam || locked || revisit || cue) {
continue;
}
// The separate stations search their own patch; a cue or an already held
// contact may be followed beyond it, never an arbitrary target of the map.
if profile.local < 1.0 && dist > local && !locked && !(cue || held.is_some_and(|t| t.own_tick > 0)) {
continue;
}
// The tracked-contact channels are a hard limit: work per tick stays bounded
// and a full station does not silently refine the whole sky. A station already
// refining a contact keeps its channel; a new refinement needs a free one, and
// without one the station still publishes its ordinary coarse search plot.
let holds_channel = held.is_some_and(|t| t.holds_channel(now, ttl as u64));
let mut product = if profile.allows(battery::Measure::Fire) {
battery::Measure::Fire
} else if profile.allows(battery::Measure::Refine) && held.is_some() {
// Refinement only applies to a contact already matched, own or network.
battery::Measure::Refine
} else {
battery::Measure::Search
};
let wants_channel = product != battery::Measure::Search && !holds_channel;
if profile.channels > 0 && wants_channel && used >= profile.channels as usize {
product = battery::Measure::Search;
}
let height = h.unwrap_or(d.pos.y - sam.pos.y);
let reach = reach(sam, d.kind, height);
if dist > reach || (dist > NEAR && horizon.is_some_and(|hz| hz.hides(at, d.pos))) {
@@ -446,17 +566,43 @@ impl Sim {
if dist > NEAR && dice(seed, now, key, 0) >= p {
continue;
}
let sigma = if locked { 0.3 } else if sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement { 0.45 + dist * 0.002 } else { 0.8 + dist * 0.004 };
let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * 0.5, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma;
if let Some(facts) = self.breakthroughs.active.get_mut(&d.id) {
facts.first.get_or_insert((now, sam.id));
}
let sigma = if locked { 0.3 } else { profile.sigma + dist * profile.spread };
let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * profile.vertical, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma;
let measured = d.pos + noise;
let quality = plot_quality(sam, profile, product, dist / reach.max(1.0), height);
if profile.channels > 0 && wants_channel && product != battery::Measure::Search {
used += 1;
}
let hits = held.map_or(1, |t| t.hits.saturating_add(1));
// What this measurement says of the contact's class and speed, from the measured
// places alone: the first blip gives neither; a later one, the change of place over
// the ticks since the last real measurement (not a forecast's), smoothed into what
// the track held so the class does not flap on one noisy pair (#133).
let (vel, class) = match held {
Some(p) if p.tick < now => {
let seen = (measured - p.pos) / (now - p.tick) as f64;
let vel = if p.hits <= 1 { seen } else { p.vel + (seen - p.vel) / f64::from(p.hits.min(4)) };
(vel, p.class.step(hits, vel.length()))
}
_ => (DVec3::ZERO, ClassEst::Unknown),
};
fresh.push(Track {
id: d.id,
kind: d.kind,
pos: d.pos + noise,
vel: d.vel,
class,
pos: measured,
vel,
tick: now,
own_tick: now,
source: sam.id,
product,
quality,
own_product: product,
own_quality: quality,
ttl,
hits: held.map_or(1, |t| t.hits.saturating_add(1)),
hits,
locked,
});
}
@@ -471,7 +617,7 @@ impl Sim {
if now % 20 == 0 {
for s in self.sams.iter().filter(|s| s.radar_up()) {
if self.drones.iter().any(|d| d.alive() && d.pos.distance(s.pos) <= 1600.0) {
self.intel.revealed.push((s.id, s.pos, now));
self.intel.observe(s, now, ew::Seen::Emission);
}
}
}
@@ -482,7 +628,37 @@ impl Sim {
.map(|s| (s.id, s.pos, s.link_range(), s.tracks.iter().filter(|t| t.own_tick > 0 && t.own_tick == t.tick).copied().collect::<Vec<_>>()))
.filter(|s| !s.3.is_empty())
.collect();
// One freshest track per radar is all a cue needs: the posts never walk every contact.
let cues: Vec<(u32, DVec3, f64, Track)> = if self.sams.iter().any(|s| s.kind == SamKind::Optical) {
shared
.iter()
.filter_map(|(id, at, range, tracks)| tracks.iter().max_by_key(|t| t.tick).map(|t| (*id, *at, *range, *t)))
.collect()
} else {
Vec::new()
};
for sam in &mut self.sams {
if sam.kind == SamKind::Optical {
// An optical post receives a cue, not a track: the freshest network measurement within
// link range only points its head, and none of it enters `tracks`, `seen` or `own`.
sam.seen.clear();
sam.own.clear();
if sam.alive() && !sam.moving() && sam.link_range() > 0.0 {
let mine = sam.link_range();
let mut best: Option<Track> = None;
for (id, at, range, t) in &cues {
if *id != sam.id && at.distance(sam.pos) <= range.min(mine)
&& best.is_none_or(|b: Track| t.tick > b.tick)
{
best = Some(*t);
}
}
if let Some(t) = best {
sam.optical.offer_cue(t);
}
}
continue;
}
if sam.alive() && !sam.moving() && (sam.kind.armed() || (sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement)) && sam.link_range() > 0.0 && !shared.is_empty() {
index.clear();
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
@@ -490,7 +666,7 @@ impl Sim {
for (id, at, range, tracks) in &shared {
if *id != sam.id && at.distance(sam.pos) <= range.min(mine) {
for t in tracks {
merge(&mut sam.tracks, &mut index, Track { own_tick: 0, ..*t });
merge(&mut sam.tracks, &mut index, Track { own_tick: 0, own_product: battery::Measure::Search, own_quality: 0, ..*t });
}
}
}
@@ -504,6 +680,9 @@ impl Sim {
}
}
}
// Passive optics (#136) look after the network has spoken: a cue is only a cue, and every
// observation it makes is its own, never a track and never an emission.
self.update_optics(ground);
}
/// Whether any system's radar holds this drone (the player's radar shows only those).
@@ -520,8 +699,25 @@ impl Sim {
let mut tracks: Vec<Track> = if unaided {
self.drones
.iter()
// No system is deployed: no estimation happens, the fallback is the sky as it is
// (the screens have always had it), with the figures a system would show.
.filter(|d| d.alive())
.map(|d| Track { id: d.id, kind: d.kind, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 1, hits: 3, locked: false })
.map(|d| Track {
id: d.id,
class: ClassEst::Firm(d.kind.spec().class),
pos: d.pos,
vel: d.vel,
tick: now,
own_tick: now,
source: 0,
product: battery::Measure::Fire,
quality: 100,
own_product: battery::Measure::Fire,
own_quality: 100,
ttl: 1,
hits: 3,
locked: false,
})
.collect()
} else {
self.picture().into_values().collect()
@@ -530,11 +726,12 @@ impl Sim {
AirPicture { now, tracks, unaided }
}
/// The freshest track of each drone any system holds: the air picture.
/// The freshest track of each drone any system holds: the air picture. At one
/// tick the better plot (quality, then product) is the one the player sees.
pub fn picture(&self) -> HashMap<u32, Track> {
let mut best: HashMap<u32, Track> = HashMap::new();
for t in self.sams.iter().flat_map(|s| s.tracks.iter()) {
if best.get(&t.id).is_none_or(|b| t.tick > b.tick) {
if best.get(&t.id).is_none_or(|b| (t.tick, t.quality, t.product) > (b.tick, b.quality, b.product)) {
best.insert(t.id, *t);
}
}
@@ -612,3 +809,28 @@ mod low_view_tests {
assert!(seen > 0 && tint.as_millis() < 100, "{tint:?}");
}
}
#[cfg(test)]
mod relay_tests {
use super::*;
/// A relayed measurement: its class and hits arrive as they were, the receiver's own age is
/// kept, and passing the same message again adds nothing (#133).
#[test]
fn a_repeated_relay_adds_no_confidence_and_stays_foreign() {
let ours = Track { id: 7, class: ClassEst::Unknown, pos: DVec3::new(0.0, 100.0, 0.0), vel: DVec3::ZERO, tick: 90, own_tick: 90, source: 1, product: battery::Measure::Fire, quality: 80, own_product: battery::Measure::Fire, own_quality: 80, ttl: 400, hits: 1, locked: false };
let relay = Track { id: 7, class: ClassEst::Probable(Class::Drone), pos: DVec3::new(0.0, 100.0, -10.0), vel: DVec3::X, tick: 100, own_tick: 0, source: 2, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Search, own_quality: 0, ttl: 400, hits: 2, locked: false };
let mut tracks = vec![ours];
let mut index: HashMap<u32, usize> = HashMap::from([(7, 0)]);
merge(&mut tracks, &mut index, relay);
assert_eq!(tracks[0].own_tick, 90, "a relayed track is not the receiver's own measurement");
for _ in 0..5 {
merge(&mut tracks, &mut index, relay);
}
assert_eq!(tracks.len(), 1, "a relay of a held measurement is one track");
assert_eq!(tracks[0].hits, 2, "a repeated relay added confidence");
assert_eq!(tracks[0].class, ClassEst::Probable(Class::Drone), "a relay altered the estimate");
assert_eq!(tracks[0].tick, 100, "a relay refreshed the measurement");
assert_eq!(tracks[0].own_tick, 90, "a relay became the receiver's own");
}
}
+5
View File
@@ -184,6 +184,11 @@ pub(super) enum Slot {
}
impl Sites {
/// What the sites hold, about (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::vec_bytes;
vec_bytes(&self.list) + vec_bytes(&self.jobs) + vec_bytes(&self.holding) + vec_bytes(&self.flying)
}
pub fn get(&self, id: u32) -> Option<&LaunchSite> {
self.list.iter().find(|s| s.id == id)
}
+312
View File
@@ -0,0 +1,312 @@
//! Smart v2 (#149): the merged public picture, one knowledge version per order, the bounded
//! refresh of the unreleased portion, and the bearing window — and the metamorphic guarantee
//! that a hidden permutation nothing observed changes no decision.
use super::*;
use super::sites::testland::{Land, serve};
fn grid() -> raid::Grid {
raid::Grid { min: DVec3::new(-800.0, 0.0, -800.0), cell: 16.0, size: 100 }
}
fn mark(id: u32, at: DVec3, category: recon::Category, observed: u64) -> recon::Mark {
recon::Mark {
id,
area: at,
radius: recon::COARSE_AREA,
category,
role: None,
source: recon::Source::Flyby,
observed,
reported: observed,
quality: recon::Quality::Coarse,
looks: 1,
}
}
fn contact(id: u32, kind: SamKind, at: DVec3, tick: u64) -> ew::Contact {
ew::Contact { id, kind, at, tick, seen: ew::Seen::Emission, emission: Some(tick), destroyed: None, launches: 0 }
}
fn order() -> RaidOrder {
RaidOrder { kinds: vec![(DroneKind::Shahed, 4), (DroneKind::Kh22, 2)], approach: Approach::Sector, dist: 900.0, aim: Aim::Smart }
}
// #149: the metamorphic guarantee. Two worlds with the same seed and the same observed radar,
// whose hidden forces are a permutation of one another (kinds swapped between places), order
// the same recon flight, the same aims and intents, and the same prices — nothing unobserved
// leaks into a decision.
#[test]
fn a_hidden_permutation_changes_nothing_before_observation() {
let object = DVec3::new(0.0, 70.0, 0.0);
let build = |perm: bool| {
let mut sim = Sim::new(149);
let id = sim.id();
let radar = Sam::new(id, SamKind::Radar, DVec3::new(150.0, 70.0, -80.0), 0.0);
sim.intel.observe(&radar, 0, ew::Seen::Emission);
sim.sams.push(radar);
let spots = [DVec3::new(-200.0, 70.0, 100.0), DVec3::new(300.0, 70.0, 200.0), DVec3::new(-50.0, 70.0, -300.0)];
let kinds = if perm { [SamKind::Pantsir, SamKind::S400, SamKind::Tor] } else { [SamKind::S400, SamKind::Tor, SamKind::Pantsir] };
for (k, p) in kinds.into_iter().zip(spots) {
let id = sim.id();
sim.sams.push(Sam::new(id, k, p, 0.0));
}
sim.targets.push(object);
sim.target_health.push(100.0);
let mut out = Out::default();
sim.order_raid(&order(), &[object], &mut out);
let flight: Vec<_> = sim.recon.sorties.iter().map(|s| s.zones.iter().map(|z| (z.center, z.radius)).collect::<Vec<_>>()).collect();
let aims = sim.planned_aims();
let intents = sim.planned_intents();
let (prices, _) = sim.price_grid(&grid(), DroneKind::Kh101);
(flight, aims, intents, prices)
};
assert_eq!(build(false), build(true), "a hidden permutation changed the flight, the plan or the prices");
}
// #149: the same guarantee after a look. Once a radar is observed, permuting only the units
// nothing saw changes neither the structured picture nor the prices.
#[test]
fn a_hidden_permutation_changes_nothing_after_observation() {
let build = |perm: bool| {
let mut sim = Sim::new(149);
let id = sim.id();
let radar = Sam::new(id, SamKind::Radar, DVec3::new(150.0, 70.0, -80.0), 0.0);
sim.intel.observe(&radar, 0, ew::Seen::Emission);
sim.sams.push(radar);
let spots = [DVec3::new(-200.0, 70.0, 100.0), DVec3::new(300.0, 70.0, 200.0)];
let kinds = if perm { [SamKind::S400, SamKind::Pantsir] } else { [SamKind::Pantsir, SamKind::S400] };
for (k, p) in kinds.into_iter().zip(spots) {
let id = sim.id();
sim.sams.push(Sam::new(id, k, p, 0.0));
}
sim.tick = 100;
let (prices, _) = sim.price_grid(&grid(), DroneKind::Kh101);
(sim.enemy_picture(), prices)
};
assert_eq!(build(false), build(true), "a hidden permutation moved the picture or the prices after a look");
}
// #149: price_grid_known accounts for marks. A fresh probable mark raises the cells its public
// category covers; a doubtful one prices nothing; a mark matched to a contact is priced once,
// exactly as the contact alone. The legacy mode prices contacts only.
#[test]
fn a_fresh_mark_prices_the_map_and_a_doubtful_one_does_not() {
let mut sim = Sim::new(149);
let g = grid();
let m = mark(recon::ID_BASE + 1, DVec3::new(0.0, 70.0, 0.0), recon::Category::Launcher, 0);
let fresh = ew::KnowledgeSnapshot::new(100, Vec::new(), vec![m]);
let (prices, _) = sim.price_grid_known(&g, DroneKind::Kh101, None, &fresh);
assert!(prices.iter().any(|p| *p > 1.0), "a fresh launcher mark priced nothing");
let old = ew::KnowledgeSnapshot::new(4000, Vec::new(), vec![m]);
let (prices, _) = sim.price_grid_known(&g, DroneKind::Kh101, None, &old);
assert!(prices.iter().all(|p| *p == 1.0), "a doubtful mark was priced");
// Merged into a contact of the same public category: one hint, priced once.
let c = contact(16, SamKind::S400, m.area, 100);
let merged = ew::KnowledgeSnapshot::new(100, vec![c], vec![m]);
let only = ew::KnowledgeSnapshot::new(100, vec![c], Vec::new());
assert_eq!(
sim.price_grid_known(&g, DroneKind::Kh101, None, &merged).0,
sim.price_grid_known(&g, DroneKind::Kh101, None, &only).0,
"a matched mark was priced twice"
);
// The legacy mode does not price marks at all.
sim.smart_legacy = true;
let (prices, _) = sim.price_grid_known(&g, DroneKind::Kh101, None, &fresh);
assert!(prices.iter().all(|p| *p == 1.0), "the legacy mode priced a mark");
}
// #146/#149: one order prices every kind over the snapshot its targets were chosen from. A
// contact disclosed while the plan is still being worked out changes neither mode's routes:
// the #146 versioning is preserved for the candidate and the legacy picker alike.
#[test]
fn one_order_prices_every_kind_over_its_own_snapshot() {
let object = DVec3::new(0.0, 70.0, 300.0);
let build = |legacy: bool, disclose: bool| {
let mut sim = Sim::new(149);
sim.smart_legacy = legacy;
let id = sim.id();
let radar = Sam::new(id, SamKind::Radar, DVec3::new(600.0, 70.0, -600.0), 0.0);
sim.intel.observe(&radar, 0, ew::Seen::Emission);
sim.sams.push(radar);
sim.targets.push(object);
sim.target_health.push(100.0);
let mut ground = Ground::default();
let land = Land(|_, _| 64);
let mut out = Out::default();
for _ in 0..20 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
let order = RaidOrder { kinds: vec![(DroneKind::Kh101, 6), (DroneKind::Shahed, 8)], approach: Approach::Sector, dist: 600.0, aim: Aim::Smart };
sim.order_raid(&order, &[object], &mut out);
if disclose {
// A jamming station gives itself away at the objective while the plan waits for its
// land: every satellite-nav kind prices it, so the live picture bends the routes.
let id = sim.id();
let threat = Sam::new(id, SamKind::Ew, object, 0.0);
sim.intel.observe(&threat, sim.tick, ew::Seen::Jamming);
sim.sams.push(threat);
}
// Work the plan alone (no adaptive ticks): the queue's routes are the plan's own.
while sim.planning() {
serve(&mut ground, &land, sim.tick);
sim.tick += 1;
sim.plan_step(Some(&mut ground), &mut out);
}
sim.queue.iter().map(|(_, d)| (d.id, d.route.clone())).collect::<Vec<_>>()
};
assert_eq!(build(false, false), build(false, true), "the candidate mixed two knowledge versions in one order");
assert_eq!(build(true, false), build(true, true), "the legacy mode lost the #146 one-version pricing");
}
// #149: a report arriving while the raid's drones still wait re-aims the plan's own picks once,
// on a fresh snapshot, within the switch cap — and then the refresh is spent.
#[test]
fn a_report_refreshes_the_unreleased_portion_once() {
let object = DVec3::new(0.0, 70.0, 0.0);
let mut sim = Sim::new(149);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0), 0.0));
sim.targets.push(object);
sim.target_health.push(100.0);
let mut ground = Ground::default();
let land = Land(|_, _| 64);
let mut out = Out::default();
for _ in 0..20 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
sim.order_raid(&order(), &[object], &mut out);
// Force the first sortie's look so a report is pending, then finish the plan: the refresh
// moment is armed only because a report is actually on its way.
let s = sim.recon.sorties.first().expect("no recon sortie").clone();
let d = sim.drones.iter_mut().find(|d| d.id == s.drone).expect("the sortie has no aircraft");
d.pos = s.zones[s.next].center + DVec3::Y * 40.0;
sim.tick += 1;
sim.step_recon(&mut out);
let report_at = sim.recon.sorties.first().unwrap().report_at.expect("no pending report");
while sim.planning() {
serve(&mut ground, &land, sim.tick);
sim.tick += 1;
sim.plan_step(Some(&mut ground), &mut out);
}
assert!(sim.refresh.is_some(), "a pending report did not arm the bounded refresh");
// The report arrives: the mark is in the picture.
sim.tick = report_at;
sim.step_recon(&mut out);
assert!(sim.recon.reports > 0);
let m = *sim.recon.marks.values().next().expect("the report left no mark");
// One drone is past the switch cap: it keeps its aim.
sim.queue[0].1.aim.switches = ew::SWITCH_CAP;
let capped = sim.queue[0].1.id;
sim.step_refresh(&mut out);
assert!(sim.refresh.is_none(), "the refresh was not spent");
assert!(sim.refresh_applied > 0, "the report re-aimed nobody");
assert!(sim.queue.iter().any(|(_, d)| d.intent == ew::Intent::Refresh && d.aim.unit == m.id), "no drone was refreshed onto the mark");
assert!(sim.queue.iter().find(|(_, d)| d.id == capped).unwrap().1.intent != ew::Intent::Refresh, "a drone past the cap was refreshed");
// Spent: a second call changes nothing.
let applied = sim.refresh_applied;
sim.step_refresh(&mut out);
assert_eq!(sim.refresh_applied, applied);
}
// #149: no report never pauses the raid. Past the deadline the refresh is dropped and the
// launches keep the times the plan gave them.
#[test]
fn no_report_never_pauses_the_raid() {
let object = DVec3::new(0.0, 70.0, 0.0);
let mut sim = Sim::new(149);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0), 0.0));
sim.targets.push(object);
sim.target_health.push(100.0);
let mut ground = Ground::default();
let land = Land(|_, _| 64);
let mut out = Out::default();
for _ in 0..20 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
sim.order_raid(&order(), &[object], &mut out);
let s = sim.recon.sorties.first().expect("no recon sortie").clone();
let d = sim.drones.iter_mut().find(|d| d.id == s.drone).unwrap();
d.pos = s.zones[s.next].center + DVec3::Y * 40.0;
sim.tick += 1;
sim.step_recon(&mut out);
while sim.planning() {
serve(&mut ground, &land, sim.tick);
sim.tick += 1;
sim.plan_step(Some(&mut ground), &mut out);
}
let deadline = sim.refresh.as_ref().expect("the refresh was not armed").deadline;
let times: Vec<u64> = sim.queue.iter().map(|(t, _)| *t).collect();
// The report never arrives (the aircraft is lost); the deadline passes.
sim.drones.retain(|d| !recon::is_drone_id(d.id));
sim.tick = deadline + 1;
sim.step_refresh(&mut out);
assert!(sim.refresh.is_none(), "the refresh outlived its deadline");
assert_eq!(sim.refresh_applied, 0);
assert_eq!(sim.queue.iter().map(|(t, _)| *t).collect::<Vec<_>>(), times, "a missing report delayed a launch");
}
// #149: the bearing window forgets, and names why it explores. Few observations, a stale
// result and changed public conditions are distinct typed reasons; the legacy mode keeps its
// fixed share.
#[test]
fn the_bearing_window_forgets_and_names_its_reason() {
let mut sim = Sim::new(149);
sim.tick = 100;
for _ in 0..8 {
sim.learn(3, false);
}
sim.best_bearing();
let r = sim.bearing_report();
assert_eq!(r.reason, ew::BearingReason::Exploiting);
assert_eq!(r.observations, 8);
sim.tick = 100 + ew::OUTCOME_STALE + 1;
sim.best_bearing();
assert_eq!(sim.bearing_report().reason, ew::BearingReason::StaleResults);
sim.tick = 100 + ew::OUTCOME_WINDOW + 1;
sim.best_bearing();
let r = sim.bearing_report();
assert_eq!(r.reason, ew::BearingReason::FewObservations);
assert_eq!(r.observations, 0, "the window did not forget the old outcomes");
let mut sim = Sim::new(149);
sim.tick = 100;
for _ in 0..8 {
sim.learn(3, false);
}
let id = sim.id();
let radar = Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0);
sim.intel.observe(&radar, 100, ew::Seen::Emission);
sim.sams.push(radar);
sim.best_bearing();
assert_eq!(sim.bearing_report().reason, ew::BearingReason::ConditionsChanged);
sim.smart_legacy = true;
sim.best_bearing();
assert_eq!(sim.bearing_report().reason, ew::BearingReason::FixedShare);
}
// #149: the bearing window and a refresh intent are durable: a save writes them, a load reads
// them back, and an older save without the window loads with an empty one.
#[test]
fn the_bearing_window_and_a_refresh_intent_survive_a_save() {
let mut sim = Sim::new(149);
sim.tick = 500;
sim.learn(2, true);
sim.learn(5, false);
let mut d = sim.make_drone(DroneKind::Shahed, DVec3::new(-500.0, 120.0, 0.0), DVec3::X, DVec3::ZERO);
d.smart = true;
d.intent = ew::Intent::Refresh;
d.aim = ew::Aim::unit(recon::ID_BASE + 1, 500, Confidence::Confirmed);
sim.queue.push((600, d));
let text = sim.air_text().expect("the window and the queue are durable");
assert!(text.contains("airlearn"), "the bearing window was not written");
assert!(text.contains("refresh"), "the refresh intent was not written");
let mut back = Sim::new(1);
back.restore_air(Sim::parse_air(&text).expect("the save reads").expect("the air section is there"));
assert_eq!(back.intel.outcomes().len(), 2);
assert_eq!(back.queue[0].1.intent, ew::Intent::Refresh);
assert_eq!(back.queue[0].1.aim.unit, recon::ID_BASE + 1);
}
+542
View File
@@ -0,0 +1,542 @@
// Generated by tools/gen_catalog.py from catalog/specs.json. Do not edit.
// Game-scale values, not real weapon data; the catalog is the only copy.
/// Share of the old slew speed a launcher keeps when it has no rate of its own.
const DRIVE_SCALE: f64 = 0.4;
/// Ticks a drive takes to reach its top speed (and to stop from it).
const DRIVE_RAMP: f64 = 8.0;
const DRIVE_TRAINABLE: (f64, f64) = (0.12, 0.0);
const DRIVE_VERTICAL: (f64, f64) = (0.15, 0.0);
const DRIVE_OTHER: (f64, f64) = (0.05, 0.05);
/// Ballistic flight's gravity, blocks a tick².
const GRAVITY: f64 = 0.05;
/// Height over the target where the Oreshnik's blocks release their submunitions.
const BLOCK_SPLIT: f64 = 300.0;
/// How near a depot a system reloads straight from it.
const DEPOT_REACH: f64 = 60.0;
/// How near a truck must come to hand a reload over, or to load up at a depot.
const HANDOVER: f64 = 10.0;
/// What a truck carries.
const TRUCK_LOAD: u32 = 2;
const STOCK_LIMIT: u32 = 1000000;
const DRONE_SPEC_SHAHED: DroneSpec = DroneSpec {
name: "Шахед-136",
key: "shahed",
model: "airdef:shahed",
speed: 0.6,
turn: 0.035,
cruise: 45.0,
clearance: 18.0,
dive: 32.0,
warhead: 3,
scale: 1.3,
engine: Engine::Prop(1.34, 1.0),
decoy: false,
stealth: 1.0,
rcs: 0.3,
sound: (sound::DRONE_SHAHED, 1.0, 48),
class: Class::Drone,
ballistic: None,
launch_sound: sound::LAUNCH_S400_EJECT,
};
const DRONE_SPEC_GERAN3: DroneSpec = DroneSpec {
name: "Герань-3",
key: "geran3",
model: "airdef:geran3",
speed: 1.6,
turn: 0.03,
cruise: 60.0,
clearance: 18.0,
dive: 50.0,
warhead: 2,
scale: 1.15,
engine: Engine::Jet(0.34, 1.55, 1.0),
decoy: false,
stealth: 1.1,
rcs: 0.4,
sound: (sound::DRONE_GERAN3, 1.0, 40),
class: Class::Jet,
ballistic: None,
launch_sound: sound::LAUNCH_S400_EJECT,
};
const DRONE_SPEC_LANCET: DroneSpec = DroneSpec {
name: "Ланцет-3",
key: "lancet",
model: "airdef:lancet",
speed: 1.1,
turn: 0.07,
cruise: 25.0,
clearance: 10.0,
dive: 38.0,
warhead: 1,
scale: 0.9,
engine: Engine::Prop(0.93, 0.55),
decoy: false,
stealth: 1.4,
rcs: 0.08,
sound: (sound::DRONE_LANCET, 1.0, 32),
class: Class::Drone,
ballistic: None,
launch_sound: sound::LAUNCH_S400_EJECT,
};
const DRONE_SPEC_GERBERA: DroneSpec = DroneSpec {
name: "Гербера",
key: "gerbera",
model: "airdef:gerbera",
speed: 0.5,
turn: 0.04,
cruise: 40.0,
clearance: 15.0,
dive: 30.0,
warhead: 0,
scale: 1.1,
engine: Engine::Prop(1.03, 0.9),
decoy: true,
stealth: 0.9,
rcs: 0.4,
sound: (sound::DRONE_SHAHED, 1.3, 40),
class: Class::Drone,
ballistic: None,
launch_sound: sound::LAUNCH_S400_EJECT,
};
const DRONE_SPEC_KH101: DroneSpec = DroneSpec {
name: "Х-101",
key: "kh101",
model: "airdef:kh101",
speed: 2.4,
turn: 0.025,
cruise: 0.0,
clearance: 12.0,
dive: 26.0,
warhead: 6,
scale: 1.6,
engine: Engine::Jet(-0.27, 1.4, 0.6),
decoy: false,
stealth: 1.5,
rcs: 0.05,
sound: (sound::DRONE_CRUISE, 1.0, 50),
class: Class::Cruise,
ballistic: None,
launch_sound: sound::LAUNCH_PATRIOT,
};
const DRONE_SPEC_KALIBR: DroneSpec = DroneSpec {
name: "Калибр",
key: "kalibr",
model: "airdef:kalibr",
speed: 2.1,
turn: 0.025,
cruise: 0.0,
clearance: 15.0,
dive: 26.0,
warhead: 5,
scale: 1.5,
engine: Engine::Jet(-0.2, 1.5, 0.6),
decoy: false,
stealth: 1.3,
rcs: 0.15,
sound: (sound::DRONE_CRUISE, 1.2, 50),
class: Class::Cruise,
ballistic: None,
launch_sound: sound::LAUNCH_PATRIOT,
};
const DRONE_SPEC_KH22: DroneSpec = DroneSpec {
name: "Х-22",
key: "kh22",
model: "airdef:kh22",
speed: 4.0,
turn: 0.03,
cruise: 140.0,
clearance: 40.0,
dive: 150.0,
warhead: 7,
scale: 1.8,
engine: Engine::Rocket(1.5, 1.3),
decoy: false,
stealth: 1.4,
rcs: 1.0,
sound: (sound::DRONE_ROCKET, 0.8, 46),
class: Class::Supersonic,
ballistic: None,
launch_sound: sound::LAUNCH_PATRIOT,
};
const DRONE_SPEC_ZIRCON: DroneSpec = DroneSpec {
name: "Циркон",
key: "zircon",
model: "airdef:zircon",
speed: 5.5,
turn: 0.025,
cruise: 90.0,
clearance: 30.0,
dive: 110.0,
warhead: 6,
scale: 1.4,
engine: Engine::Rocket(1.5, 1.1),
decoy: false,
stealth: 2.0,
rcs: 0.4,
sound: (sound::DRONE_ROCKET, 1.35, 46),
class: Class::Supersonic,
ballistic: None,
launch_sound: sound::LAUNCH_S400,
};
const DRONE_SPEC_ISKANDER: DroneSpec = DroneSpec {
name: "Искандер-М",
key: "iskander",
model: "airdef:iskander",
speed: 5.0,
turn: 0.04,
cruise: 0.0,
clearance: 0.0,
dive: 0.0,
warhead: 8,
scale: 1.8,
engine: Engine::Rocket(1.5, 1.6),
decoy: false,
stealth: 1.6,
rcs: 0.6,
sound: (sound::DRONE_ROCKET, 0.7, 46),
class: Class::Ballistic,
ballistic: Some(1000.0),
launch_sound: sound::LAUNCH_S500,
};
const DRONE_SPEC_KINZHAL: DroneSpec = DroneSpec {
name: "Кинжал",
key: "kinzhal",
model: "airdef:kinzhal",
speed: 7.5,
turn: 0.03,
cruise: 0.0,
clearance: 0.0,
dive: 0.0,
warhead: 8,
scale: 1.7,
engine: Engine::Rocket(1.5, 1.5),
decoy: false,
stealth: 2.2,
rcs: 0.5,
sound: (sound::DRONE_ROCKET, 0.6, 46),
class: Class::Ballistic,
ballistic: Some(1500.0),
launch_sound: sound::LAUNCH_S500,
};
const DRONE_SPEC_ORESHNIK: DroneSpec = DroneSpec {
name: "Орешник",
key: "oreshnik",
model: "airdef:iskander",
speed: 9.0,
turn: 0.0,
cruise: 0.0,
clearance: 0.0,
dive: 0.0,
warhead: 0,
scale: 2.6,
engine: Engine::Rocket(1.5, 2.4),
decoy: false,
stealth: 3.0,
rcs: 2.0,
sound: (sound::DRONE_ROCKET, 0.5, 46),
class: Class::Ballistic,
ballistic: Some(2600.0),
launch_sound: sound::LAUNCH_S500,
};
const DRONE_SPEC_ORESHNIKBLOCK: DroneSpec = DroneSpec {
name: "Орешник: блок",
key: "oreshnik_block",
model: "airdef:reentry",
speed: 9.0,
turn: 0.0,
cruise: 0.0,
clearance: 0.0,
dive: 0.0,
warhead: 4,
scale: 1.6,
engine: Engine::Rocket(1.0, 1.0),
decoy: false,
stealth: 3.5,
rcs: 0.4,
sound: (sound::DRONE_BALLISTIC, 0.8, 9999),
class: Class::Ballistic,
ballistic: None,
launch_sound: sound::LAUNCH_S500,
};
const DRONE_SPEC_ORESHNIKSUB: DroneSpec = DroneSpec {
name: "Орешник: суббоеприпас",
key: "oreshnik_sub",
model: "airdef:reentry",
speed: 9.0,
turn: 0.05,
cruise: 0.0,
clearance: 0.0,
dive: 0.0,
warhead: 3,
scale: 1.1,
engine: Engine::Rocket(1.0, 1.0),
decoy: false,
stealth: 4.0,
rcs: 0.08,
sound: (sound::DRONE_BALLISTIC, 1.0, 9999),
class: Class::Ballistic,
ballistic: None,
launch_sound: sound::LAUNCH_S500,
};
const MISSILE_SPEC_PAC3: MissileSpec = MissileSpec {
model: "airdef:pac3",
speed: 5.5,
accel: 0.35,
turn: 0.3,
boost: 8,
cold: 0,
eject: 0.0,
eject_drag: 0.0,
pk: 0.9,
fuse: 4.0,
life: 360,
scale: 1.0,
flame: 1.0,
rear: 28.0,
seeker: 110.0,
launch_sound: sound::LAUNCH_PATRIOT,
voice: (sound::MISSILE_FLIGHT, 1.0, 1.0),
};
const MISSILE_SPEC_M57E6: MissileSpec = MissileSpec {
model: "airdef:m57e6",
speed: 5.0,
accel: 0.5,
turn: 0.32,
boost: 5,
cold: 0,
eject: 0.0,
eject_drag: 0.0,
pk: 0.82,
fuse: 3.0,
life: 160,
scale: 0.85,
flame: 0.65,
rear: 28.0,
seeker: 0.0,
launch_sound: sound::LAUNCH_PANTSIR,
voice: (sound::MISSILE_FLIGHT, 1.0, 1.12),
};
const MISSILE_SPEC_M48N6: MissileSpec = MissileSpec {
model: "airdef:m48n6",
speed: 7.0,
accel: 0.5,
turn: 0.22,
boost: 8,
cold: 20,
eject: 2.4,
eject_drag: 0.07,
pk: 0.9,
fuse: 5.0,
life: 390,
scale: 1.5,
flame: 1.4,
rear: 30.0,
seeker: 120.0,
launch_sound: sound::LAUNCH_S400_EJECT,
voice: (sound::MISSILE_FLIGHT, 1.0, 0.88),
};
const MISSILE_SPEC_M77N6: MissileSpec = MissileSpec {
model: "airdef:m77n6",
speed: 9.0,
accel: 0.6,
turn: 0.22,
boost: 8,
cold: 24,
eject: 2.6,
eject_drag: 0.07,
pk: 0.95,
fuse: 6.0,
life: 430,
scale: 1.7,
flame: 1.6,
rear: 32.0,
seeker: 120.0,
launch_sound: sound::LAUNCH_S500_EJECT,
voice: (sound::MISSILE_FLIGHT, 1.0, 0.8),
};
const MISSILE_SPEC_IRIST: MissileSpec = MissileSpec {
model: "airdef:irist_missile",
speed: 7.0,
accel: 0.5,
turn: 0.35,
boost: 6,
cold: 8,
eject: 1.8,
eject_drag: 0.1,
pk: 0.9,
fuse: 4.0,
life: 260,
scale: 0.95,
flame: 0.9,
rear: 28.0,
seeker: 90.0,
launch_sound: sound::LAUNCH_S400_EJECT,
voice: (sound::MISSILE_FLIGHT, 1.0, 1.05),
};
const MISSILE_SPEC_AMRAAM: MissileSpec = MissileSpec {
model: "airdef:amraam_missile",
speed: 6.0,
accel: 0.45,
turn: 0.3,
boost: 6,
cold: 0,
eject: 0.0,
eject_drag: 0.0,
pk: 0.85,
fuse: 4.0,
life: 260,
scale: 0.9,
flame: 0.9,
rear: 28.0,
seeker: 130.0,
launch_sound: sound::LAUNCH_PATRIOT,
voice: (sound::MISSILE_FLIGHT, 1.0, 1.05),
};
const MISSILE_SPEC_M9M317: MissileSpec = MissileSpec {
model: "airdef:m48n6",
speed: 6.5,
accel: 0.5,
turn: 0.25,
boost: 8,
cold: 0,
eject: 0.0,
eject_drag: 0.0,
pk: 0.85,
fuse: 5.0,
life: 300,
scale: 1.1,
flame: 1.2,
rear: 32.0,
seeker: 90.0,
launch_sound: sound::LAUNCH_PATRIOT,
voice: (sound::MISSILE_FLIGHT, 1.0, 0.9),
};
const MISSILE_SPEC_M9M338: MissileSpec = MissileSpec {
model: "airdef:m57e6",
speed: 5.5,
accel: 0.6,
turn: 0.4,
boost: 4,
cold: 8,
eject: 1.6,
eject_drag: 0.1,
pk: 0.9,
fuse: 3.0,
life: 160,
scale: 1.0,
flame: 0.8,
rear: 28.0,
seeker: 70.0,
launch_sound: sound::LAUNCH_S400_EJECT,
voice: (sound::MISSILE_FLIGHT, 1.0, 1.15),
};
const MISSILE_SPEC_P1SUN: MissileSpec = MissileSpec {
model: "airdef:p1sun",
speed: 2.8,
accel: 0.12,
turn: 0.3,
boost: 4,
cold: 0,
eject: 0.0,
eject_drag: 0.0,
pk: 0.8,
fuse: 3.0,
life: 900,
scale: 0.8,
flame: 0.0,
rear: 10.0,
seeker: 60.0,
launch_sound: sound::DRONE_LANCET,
voice: (sound::DRONE_LANCET, 0.8, 1.6),
};
impl DroneKind {
/// Its row of numbers from `catalog/specs.json`.
pub fn spec(self) -> &'static DroneSpec {
match self {
DroneKind::Shahed => &DRONE_SPEC_SHAHED,
DroneKind::Geran3 => &DRONE_SPEC_GERAN3,
DroneKind::Lancet => &DRONE_SPEC_LANCET,
DroneKind::Gerbera => &DRONE_SPEC_GERBERA,
DroneKind::Kh101 => &DRONE_SPEC_KH101,
DroneKind::Kalibr => &DRONE_SPEC_KALIBR,
DroneKind::Kh22 => &DRONE_SPEC_KH22,
DroneKind::Zircon => &DRONE_SPEC_ZIRCON,
DroneKind::Iskander => &DRONE_SPEC_ISKANDER,
DroneKind::Kinzhal => &DRONE_SPEC_KINZHAL,
DroneKind::Oreshnik => &DRONE_SPEC_ORESHNIK,
DroneKind::OreshnikBlock => &DRONE_SPEC_ORESHNIKBLOCK,
DroneKind::OreshnikSub => &DRONE_SPEC_ORESHNIKSUB,
}
}
}
impl MissileKind {
fn spec(self) -> &'static MissileSpec {
match self {
MissileKind::Pac3 => &MISSILE_SPEC_PAC3,
MissileKind::M57e6 => &MISSILE_SPEC_M57E6,
MissileKind::M48n6 => &MISSILE_SPEC_M48N6,
MissileKind::M77n6 => &MISSILE_SPEC_M77N6,
MissileKind::IrisT => &MISSILE_SPEC_IRIST,
MissileKind::Amraam => &MISSILE_SPEC_AMRAAM,
MissileKind::M9m317 => &MISSILE_SPEC_M9M317,
MissileKind::M9m338 => &MISSILE_SPEC_M9M338,
MissileKind::P1sun => &MISSILE_SPEC_P1SUN,
}
}
}
/// Save keys by kind; a rename needs an explicit migration.
#[cfg(test)]
pub(super) const DRONE_SPEC_KEYS: [(DroneKind, &str); 13] = [
(DroneKind::Shahed, "shahed"),
(DroneKind::Geran3, "geran3"),
(DroneKind::Lancet, "lancet"),
(DroneKind::Gerbera, "gerbera"),
(DroneKind::Kh101, "kh101"),
(DroneKind::Kalibr, "kalibr"),
(DroneKind::Kh22, "kh22"),
(DroneKind::Zircon, "zircon"),
(DroneKind::Iskander, "iskander"),
(DroneKind::Kinzhal, "kinzhal"),
(DroneKind::Oreshnik, "oreshnik"),
(DroneKind::OreshnikBlock, "oreshnik_block"),
(DroneKind::OreshnikSub, "oreshnik_sub"),
];
#[cfg(test)]
pub(super) const MISSILE_SPEC_MODELS: [(MissileKind, &str); 9] = [
(MissileKind::Pac3, "airdef:pac3"),
(MissileKind::M57e6, "airdef:m57e6"),
(MissileKind::M48n6, "airdef:m48n6"),
(MissileKind::M77n6, "airdef:m77n6"),
(MissileKind::IrisT, "airdef:irist_missile"),
(MissileKind::Amraam, "airdef:amraam_missile"),
(MissileKind::M9m317, "airdef:m48n6"),
(MissileKind::M9m338, "airdef:m57e6"),
(MissileKind::P1sun, "airdef:p1sun"),
];
+66 -17
View File
@@ -25,7 +25,16 @@ use glam::DVec2;
/// Minecraft presentation profile; neither dimensions nor timing reproduce a real weapon.
pub const ROUND_MODEL: &str = "airdef:rm48u";
pub const ROUND_SCALE: f64 = 1.5;
pub const EJECT_TICKS: u64 = 5;
/// Ticks the gas throw takes before the motor lights: the same staged cold launch as the
/// interceptor's `cold` (#129), so a physical strike shows the unlit ejection too.
pub const EJECT_TICKS: u64 = 20;
/// The unlit ejection's height at flight age `age`: a gas throw of 2.2 blocks a tick with a
/// linear drag of 0.09 a tick², integrated (game scale, like the interceptor's `eject`).
fn eject_rise(age: u64) -> f64 {
let a = age as f64;
(2.2 * a - 0.045 * a * a).max(0.0)
}
/// Shared live/replay appearance, including the unlit cold-ejection phase.
pub(super) fn round_visual(out: &mut Out, id: u32, pos: DVec3, rot: DQuat, lit: bool) {
@@ -340,6 +349,13 @@ pub struct Strikes {
}
impl Strikes {
/// What the counter-strikes hold, about (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::vec_bytes;
vec_bytes(&self.known) + vec_bytes(&self.flights) + vec_bytes(&self.pending) + vec_bytes(&self.flown)
+ vec_bytes(&self.wrecks) + vec_bytes(&self.cancelled)
+ self.news.iter().map(|s| s.capacity()).sum::<usize>()
}
pub fn new() -> Self {
Strikes { stock: TUNE.stock, ..Default::default() }
}
@@ -581,10 +597,18 @@ impl Sim {
let end = DVec3::new(f.land.x, below.unwrap_or(f.from.y), f.land.y);
let t = ((now - f.start) as f64 / (f.arrive - f.start).max(1) as f64).clamp(0.0, 1.0);
let age = now.saturating_sub(f.start);
let arc = |t: f64| TUNE.height * (std::f64::consts::PI * t).sin().max(0.0).sqrt();
let planned = if f.carrier.is_some() && age < EJECT_TICKS {
f.from + DVec3::Y * (age as f64 * 0.7)
// The unlit gas throw: it rises and slows, no motor yet (#129).
f.from + DVec3::Y * eject_rise(age)
} else if f.carrier.is_some() {
// From where the ejection reached, onto the cruise arc: the plan is continuous
// at ignition, and the flight time counted at the order includes the ejection.
let top = f.from + DVec3::Y * eject_rise(EJECT_TICKS);
let t = ((age - EJECT_TICKS) as f64 / (f.arrive - f.start).saturating_sub(EJECT_TICKS).max(1) as f64).clamp(0.0, 1.0);
top.lerp(end, t) + DVec3::Y * arc(t)
} else {
f.from.lerp(end, t) + DVec3::Y * (TUNE.height * (std::f64::consts::PI * t).sin().max(0.0).sqrt())
f.from.lerp(end, t) + DVec3::Y * arc(t)
};
let from = f.pos;
// Time spent waiting for world data must not accumulate into a faster step.
@@ -660,7 +684,7 @@ impl Sim {
out.model(id + 1, "airdef:geran3_flame", pos + rot * DVec3::new(0.0, up * spec.scale, back * spec.scale), rot, spec.scale * size * flicker, true);
}
if f.carrier.is_some() {
if age == EJECT_TICKS { out.sound("airdef:launch.s400", pos, 1.0, 1.0); }
if age == EJECT_TICKS { out.sound(super::catalog::sound::LAUNCH_S400, pos, 1.0, 1.0); }
if age >= EJECT_TICKS {
let (event, gain, pitch) = MissileKind::M48n6.engine_voice();
out.engine(id, event, pos, pos - from, gain, pitch, false);
@@ -694,7 +718,7 @@ impl Sim {
/// Reserve a physical carrier and its cell; ammunition is spent only on ejection.
pub fn order_strike(&mut self, id: u32, _from: DVec3, _out: &mut Out) -> Result<String, String> {
let k = self.strikes.get(id).ok_or_else(|| format!("ПУ №{id} не найдена"))?;
let est = k.est.filter(|e| e.fix).ok_or("Место ПУ неизвестно: нужна разведка")?;
let est = k.est.filter(|e| e.fix).ok_or("Место ПУ неизвестно: РЛС должна увидеть сам пуск. /airdef sites — состояние разведки")?;
if matches!(k.state, SiteState::Destroyed(_)) { return Err("ПУ уже уничтожена".into()); }
if self.strikes.flights.iter().any(|f| f.site == id) || self.strikes.pending.iter().any(|p| p.site == id) {
return Err("По этой ПУ ракета уже готовится или в полёте".into());
@@ -750,16 +774,19 @@ impl Sim {
sam.launched = 12;
sam.fired += 1;
let dist = (p.aim - DVec2::new(sam.pos.x, sam.pos.z)).length();
self.intel.revealed.push((p.carrier, sam.pos, self.tick));
// The launch betrays the carrier: the enemy saw it fire, no more than that.
self.intel.observe(&self.sams[i], self.tick, ew::Seen::Launch);
self.strikes.fired += 1;
self.strikes.next += 1;
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64;
// The counted flight includes the unlit ejection: the missile is honest about
// arriving a second later (#129).
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64 + EJECT_TICKS;
let (gx, gz) = (gauss(self.seed, self.strikes.next as u64, p.site as u64, 7), gauss(self.seed, self.strikes.next as u64, p.site as u64, 8));
self.strikes.flights.push(Flight { id: self.strikes.next, site: p.site, carrier: Some(p.carrier), from: start, pos: start, aim: p.aim,
land: p.aim + DVec2::new(gx, gz) * TUNE.cep, start: self.tick, arrive: self.tick + ticks, snap, hold: 0 });
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == p.site) { k.aimed = true; }
self.record_strike_launch(self.strikes.next, p.carrier, start);
out.sound("airdef:launch.s400_eject", start, 1.0, 1.0);
out.sound(super::catalog::sound::LAUNCH_S400_EJECT, start, 1.0, 1.0);
out.particles("minecraft:cloud", start, 0.6, DVec3::Y * 0.05, 0.05, 30);
}
}
@@ -790,7 +817,8 @@ impl Sim {
self.strikes.stock -= 1;
self.strikes.fired += 1;
self.strikes.next += 1;
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64;
// The counted flight includes the unlit ejection (#129).
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64 + EJECT_TICKS;
let start = from + DVec3::Y * 1.5;
// Its own scatter at the aim, rolled once here: the flight and its outcome name one point.
let (gx, gz) = (gauss(self.seed, self.strikes.next as u64, id as u64, 7), gauss(self.seed, self.strikes.next as u64, id as u64, 8));
@@ -954,9 +982,9 @@ impl Sim {
s
}).collect();
if v.is_empty() {
v.push("Известных ПУ нет: их находят РЛС по пускам и трекам вылетевших целей".into());
v.push("Известных ПУ нет: РЛС должна заметить пуск или вылетевшую цель; для удара нужно определить место пуска".into());
}
v.push("Удар: /airdef strike <ПУ>; подготовка RM48U: /airdef ground-load <номер С-400> у склада".into());
v.push("Удар: /airdef strike <вражеская ПУ>; RM48U: /airdef ground-stock <склад> <число>, затем ground-load <С-400>".into());
v
}
}
@@ -1062,7 +1090,22 @@ mod tests {
sim.drones.push(d);
sim.tick = hidden_launch_tick;
sim.scout_launch(drone, id, DroneKind::Shahed, DVec3::new(hidden_x, 70.0, 700.0));
let track = sight::Track { id: drone, kind: DroneKind::Shahed, pos: DVec3::new(0.0, 100.0, 1000.0), vel: -DVec3::Z * 5.0, tick: 100, own_tick: 100, ttl: 100, hits: 3, locked: false };
let track = sight::Track {
id: drone,
class: ClassEst::Firm(Class::Drone),
pos: DVec3::new(0.0, 100.0, 1000.0),
vel: -DVec3::Z * 5.0,
tick: 100,
own_tick: 100,
source: 1,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 100,
hits: 3,
locked: false,
};
sim.sams[0].tracks.push(track);
sim.tick = 100;
sim.step_strikes(&mut ground, None, &mut out);
@@ -1146,7 +1189,8 @@ mod tests {
assert!(sim.queue.is_empty(), "the jobs are cancelled");
assert!(sim.launched < 14 && sim.launched >= before, "launched {}", sim.launched);
assert!(out.messages.iter().any(|m| m.contains("уничтожена") && m.contains("отменено")), "{:?}", out.messages);
assert!(sim.strikes.wrecks.len() == 1 && sim.fires.list.len() == 1, "a wreck and a fire");
assert_eq!(sim.strikes.wrecks.len(), 1);
assert!(sim.fires.list.iter().any(|fire| horizontal(fire.at - site.pos).length() <= TUNE.hit_r), "a fire at the destroyed site");
assert!(!sim.blasts.is_empty() || sim.tick > 0);
assert!(matches!(sim.strikes.get(id).unwrap().state, SiteState::Destroyed(_)));
assert!(sim.order_test_strike(id, player, &mut out).is_err(), "destroyed already");
@@ -1408,10 +1452,14 @@ mod tests {
fn an_off_map_site_is_found_by_bearing_and_a_strike_there_only_ends_its_launches() {
let mut sim = Sim::new(5);
// Two radars apart watch the start of an off-map site's drones.
// Two radars apart watch the start of an off-map site's drones. They hold fire: this test
// is about the sighting and the strike, not about intercepting drones flown at 2 blocks a
// tick (which measure as cruise missiles, #133, and would be engaged on the roles).
for x in [-150.0, 150.0] {
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::new(x, 64.0, 0.0), 0.0));
let mut sam = Sam::new(id, SamKind::Patriot, DVec3::new(x, 64.0, 0.0), 0.0);
sam.roles = 0;
sim.sams.push(sam);
}
let id = sim.sites.add(LaunchSite {
id: 0,
@@ -1446,12 +1494,13 @@ mod tests {
k.est = Some(Estimate { pos: DVec2::new(0.0, 700.0), radius: 20.0, fix: true, bearing: 3.14, bearing_err: 0.01, origin: DVec2::ZERO });
sim.order_test_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap();
out.messages.clear();
let wrecks = sim.fires.list.len();
run(&mut sim, &mut ground, &mut out, 500);
assert!(out.messages.iter().any(|m| m.contains("за пределами") && m.contains("прекратились")), "{:?}", out.messages);
assert!(sim.queue.is_empty() && !sim.sites.get(id).unwrap().alive);
// Nothing drawn: no wreck, no fire, no blast of its own.
assert_eq!((sim.strikes.wrecks.len(), sim.fires.list.len()), (0, wrecks));
let site = sim.sites.get(id).unwrap();
assert!(sim.strikes.wrecks.is_empty());
assert!(sim.fires.list.iter().all(|fire| horizontal(fire.at - site.pos).length() > TUNE.hit_r));
}
#[test]
+451
View File
@@ -0,0 +1,451 @@
// Generated by tools/gen_catalog.py from catalog/specs.json. Do not edit.
// Game-scale values, not real weapon data; the catalog is the only copy.
const NAMED_BATTERY_RADAR: &[(&str, f64, f64)] = &[("airdef:radar_trailer", 0.0, 4.2)];
const NAMED_BATTERY_SPINNER: Option<(&str, f64, f64, f64, f64)> = Some(("airdef:radar_panel", 0.9, 4.2, 0.9, -0.3));
const NAMED_TUBE_PIVOT: DVec3 = DVec3::new(0.0, -0.5, 1.5);
const UNIT_SPEC_PATRIOT: SamSpec = SamSpec {
name: "Patriot",
key: "patriot",
missile: Some(MissileLoad { kind: MissileKind::Pac3, magazine: 4, min: 10.0, max: 950.0, interval: 16 }),
gun: None,
reload: 220,
scale: 1.3,
rest_pitch: 0.66,
roles: 30,
family: Family::Trainable,
parts: Parts {
body: "airdef:patriot_trailer",
launcher: Some("airdef:patriot_launcher"),
pack: None,
dish: None,
fixed: &[("airdef:patriot_truck", 0.0, -3.0), ("airdef:patriot_radar", 0.0, 3.6)],
spinner: None,
},
mount: (0.69, 1.2),
pivot: DVec3::new(0.0, -0.5, 1.375),
muzzle: Muzzle::Patriot,
sensor: 1350.0,
mast: 5.0,
};
const UNIT_SPEC_GEPARD: SamSpec = SamSpec {
name: "Гепард",
key: "gepard",
missile: None,
gun: Some(GunSpec { range: 180.0, track: 260.0, p: 0.3, bursts: 160, shell: 10.0, slew: (0.22, 0.16) }),
reload: 160,
scale: 1.25,
rest_pitch: 0.0,
roles: 7,
family: Family::Gun,
parts: Parts {
body: "airdef:gepard_hull",
launcher: Some("airdef:gepard_turret"),
pack: Some("airdef:gepard_guns"),
dish: Some(("airdef:gepard_dish", 0.95, 0.6, 0.0)),
fixed: &[],
spinner: None,
},
mount: (1.55, 0.25),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 335.0,
mast: 3.0,
};
const UNIT_SPEC_PANTSIR: SamSpec = SamSpec {
name: "Панцирь-С1",
key: "pantsir",
missile: Some(MissileLoad { kind: MissileKind::M57e6, magazine: 12, min: 25.0, max: 330.0, interval: 14 }),
gun: Some(GunSpec { range: 125.0, track: 185.0, p: 0.25, bursts: 140, shell: 9.0, slew: (0.25, 0.18) }),
reload: 280,
scale: 1.3,
rest_pitch: 0.0,
roles: 15,
family: Family::Turret,
parts: Parts {
body: "airdef:pantsir_truck",
launcher: Some("airdef:pantsir_turret"),
pack: Some("airdef:pantsir_pack"),
dish: Some(("airdef:pantsir_dish", 0.85, 0.3, 0.3)),
fixed: &[],
spinner: None,
},
mount: (1.35, 0.69),
pivot: DVec3::ZERO,
muzzle: Muzzle::Pantsir,
sensor: 450.0,
mast: 4.0,
};
const UNIT_SPEC_S400: SamSpec = SamSpec {
name: "С-400",
key: "s400",
missile: Some(MissileLoad { kind: MissileKind::M48n6, magazine: 4, min: 30.0, max: 1300.0, interval: 20 }),
gun: None,
reload: 420,
scale: 1.5,
rest_pitch: HALF_PI - 0.02,
roles: 30,
family: Family::Vertical,
parts: Parts {
body: "airdef:s400_chassis",
launcher: Some("airdef:s400_tubes"),
pack: None,
dish: None,
fixed: NAMED_BATTERY_RADAR,
spinner: NAMED_BATTERY_SPINNER,
},
mount: (0.7, 1.45),
pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 2, 7.0),
sensor: 1750.0,
mast: 5.0,
};
const UNIT_SPEC_S500: SamSpec = SamSpec {
name: "С-500",
key: "s500",
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 2, min: 40.0, max: 1850.0, interval: 20 }),
gun: None,
reload: 520,
scale: 1.6,
rest_pitch: HALF_PI - 0.02,
roles: 24,
family: Family::Vertical,
parts: Parts {
body: "airdef:s500_chassis",
launcher: Some("airdef:s500_tubes"),
pack: None,
dish: None,
fixed: NAMED_BATTERY_RADAR,
spinner: NAMED_BATTERY_SPINNER,
},
mount: (0.7, 1.45),
pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 1, 9.5),
sensor: 2450.0,
mast: 5.0,
};
const UNIT_SPEC_IRIST: SamSpec = SamSpec {
name: "IRIS-T SLM",
key: "irist",
missile: Some(MissileLoad { kind: MissileKind::IrisT, magazine: 8, min: 15.0, max: 600.0, interval: 10 }),
gun: None,
reload: 300,
scale: 1.4,
rest_pitch: HALF_PI - 0.02,
roles: 15,
family: Family::Vertical,
parts: Parts {
body: "airdef:irist_chassis",
launcher: Some("airdef:irist_tubes"),
pack: None,
dish: None,
fixed: NAMED_BATTERY_RADAR,
spinner: NAMED_BATTERY_SPINNER,
},
mount: (0.7, 1.45),
pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(4, 2, 4.0),
sensor: 780.0,
mast: 5.0,
};
const UNIT_SPEC_NASAMS: SamSpec = SamSpec {
name: "NASAMS",
key: "nasams",
missile: Some(MissileLoad { kind: MissileKind::Amraam, magazine: 6, min: 10.0, max: 450.0, interval: 14 }),
gun: None,
reload: 260,
scale: 1.3,
rest_pitch: 0.5,
roles: 14,
family: Family::Trainable,
parts: Parts {
body: "airdef:nasams_trailer",
launcher: Some("airdef:nasams_launcher"),
pack: None,
dish: None,
fixed: &[("airdef:radar_trailer", 0.0, 3.4)],
spinner: Some(("airdef:radar_panel", 0.9, 3.4, 0.6, -0.3)),
},
mount: (0.62, 0.4),
pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(3, 2, 4.0),
sensor: 585.0,
mast: 5.0,
};
const UNIT_SPEC_BUK: SamSpec = SamSpec {
name: "Бук-М2",
key: "buk",
missile: Some(MissileLoad { kind: MissileKind::M9m317, magazine: 4, min: 20.0, max: 675.0, interval: 18 }),
gun: None,
reload: 400,
scale: 1.4,
rest_pitch: 0.0,
roles: 14,
family: Family::Turret,
parts: Parts {
body: "airdef:buk_chassis",
launcher: Some("airdef:buk_turret"),
pack: Some("airdef:buk_rails"),
dish: None,
fixed: &[],
spinner: None,
},
mount: (1.55, 0.2),
pivot: DVec3::ZERO,
muzzle: Muzzle::Rails(&[-9.0, -3.0, 13.0, 19.0]),
sensor: 878.0,
mast: 4.0,
};
const UNIT_SPEC_TOR: SamSpec = SamSpec {
name: "Тор-М2",
key: "tor",
missile: Some(MissileLoad { kind: MissileKind::M9m338, magazine: 8, min: 8.0, max: 350.0, interval: 8 }),
gun: None,
reload: 300,
scale: 1.3,
rest_pitch: 0.0,
roles: 15,
family: Family::Vertical,
parts: Parts {
body: "airdef:tor_chassis",
launcher: Some("airdef:tor_turret"),
pack: None,
dish: None,
fixed: &[],
spinner: None,
},
mount: (1.5, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::Cells,
sensor: 475.0,
mast: 3.5,
};
const UNIT_SPEC_P1SUN: SamSpec = SamSpec {
name: "P1-SUN",
key: "p1sun",
missile: Some(MissileLoad { kind: MissileKind::P1sun, magazine: 8, min: 5.0, max: 675.0, interval: 12 }),
gun: None,
reload: 240,
scale: 1.1,
rest_pitch: 0.35,
roles: 1,
family: Family::Trainable,
parts: Parts {
body: "airdef:nasams_trailer",
launcher: Some("airdef:p1sun_launcher"),
pack: None,
dish: None,
fixed: &[],
spinner: None,
},
mount: (0.6, 0.3),
pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(4, 2, 3.0),
sensor: 0.0,
mast: 2.0,
};
const UNIT_SPEC_RADAR: SamSpec = SamSpec {
name: "РЛС дальнего обнаружения",
key: "radar",
missile: None,
gun: None,
reload: 0,
scale: 1.5,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts {
body: "airdef:radar_truck",
launcher: None,
pack: None,
dish: None,
fixed: &[],
spinner: Some(("airdef:radar_panel", 1.2, 1.2, 1.5, -0.25)),
},
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 3800.0,
mast: 16.0,
};
const UNIT_SPEC_DEPOT: SamSpec = SamSpec {
name: "Склад боеприпасов",
key: "depot",
missile: None,
gun: None,
reload: 0,
scale: 1.5,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts {
body: "airdef:depot",
launcher: None,
pack: None,
dish: None,
fixed: &[],
spinner: None,
},
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 1.0,
};
const UNIT_SPEC_TZM: SamSpec = SamSpec {
name: "ТЗМ",
key: "tzm",
missile: None,
gun: None,
reload: 0,
scale: 1.3,
rest_pitch: 0.0,
roles: 0,
family: Family::Truck,
parts: Parts {
body: "airdef:tzm_truck",
launcher: None,
pack: None,
dish: None,
fixed: &[],
spinner: None,
},
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 2.0,
};
const UNIT_SPEC_EW: SamSpec = SamSpec {
name: "Станция РЭБ",
key: "ew",
missile: None,
gun: None,
reload: 0,
scale: 1.3,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts {
body: "airdef:ew_truck",
launcher: None,
pack: None,
dish: None,
fixed: &[],
spinner: None,
},
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 3.0,
};
const UNIT_SPEC_LIGHT: SamSpec = SamSpec {
name: "Прожектор",
key: "light",
missile: None,
gun: None,
reload: 0,
scale: 1.2,
rest_pitch: 0.6,
roles: 0,
family: Family::Light,
parts: Parts {
body: "airdef:searchlight",
launcher: Some("airdef:searchlight_head"),
pack: None,
dish: None,
fixed: &[],
spinner: None,
},
mount: (0.85, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 1.5,
};
const UNIT_SPEC_OPTICAL: SamSpec = SamSpec {
name: "Оптический пост",
key: "optical",
missile: None,
gun: None,
reload: 0,
scale: 1.0,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts {
body: "airdef:radar_truck",
launcher: None,
pack: None,
dish: None,
fixed: &[],
spinner: Some(("airdef:radar_panel", 1.2, 0.0, 0.6, -0.2)),
},
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 2.5,
};
impl SamKind {
/// Its row of numbers from `catalog/specs.json`.
pub fn spec(self) -> &'static SamSpec {
match self {
SamKind::Patriot => &UNIT_SPEC_PATRIOT,
SamKind::Gepard => &UNIT_SPEC_GEPARD,
SamKind::Pantsir => &UNIT_SPEC_PANTSIR,
SamKind::S400 => &UNIT_SPEC_S400,
SamKind::S500 => &UNIT_SPEC_S500,
SamKind::IrisT => &UNIT_SPEC_IRIST,
SamKind::Nasams => &UNIT_SPEC_NASAMS,
SamKind::Buk => &UNIT_SPEC_BUK,
SamKind::Tor => &UNIT_SPEC_TOR,
SamKind::P1sun => &UNIT_SPEC_P1SUN,
SamKind::Radar => &UNIT_SPEC_RADAR,
SamKind::Depot => &UNIT_SPEC_DEPOT,
SamKind::Tzm => &UNIT_SPEC_TZM,
SamKind::Ew => &UNIT_SPEC_EW,
SamKind::Light => &UNIT_SPEC_LIGHT,
SamKind::Optical => &UNIT_SPEC_OPTICAL,
}
}
}
/// Save keys by kind; a rename needs an explicit migration.
#[cfg(test)]
pub(super) const UNIT_SPEC_KEYS: [(SamKind, &str); 16] = [
(SamKind::Patriot, "patriot"),
(SamKind::Gepard, "gepard"),
(SamKind::Pantsir, "pantsir"),
(SamKind::S400, "s400"),
(SamKind::S500, "s500"),
(SamKind::IrisT, "irist"),
(SamKind::Nasams, "nasams"),
(SamKind::Buk, "buk"),
(SamKind::Tor, "tor"),
(SamKind::P1sun, "p1sun"),
(SamKind::Radar, "radar"),
(SamKind::Depot, "depot"),
(SamKind::Tzm, "tzm"),
(SamKind::Ew, "ew"),
(SamKind::Light, "light"),
(SamKind::Optical, "optical"),
];
@@ -0,0 +1,8 @@
// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.
pub const VARIANTS: &[UnitVariant] = &[
UnitVariant { id: "s400_launcher", deploy_item: "airdef:deploy_s400_launcher", kind: SamKind::S400, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-400 — отдельная пусковая", description: "Пусковая С-400 без своей РЛС: работает по данным сети." },
UnitVariant { id: "s500_launcher", deploy_item: "airdef:deploy_s500_launcher", kind: SamKind::S500, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-500 — отдельная пусковая", description: "Пусковая С-500 без своей РЛС: работает по данным сети." },
UnitVariant { id: "radar_search", deploy_item: "airdef:deploy_radar_search", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Search, label: "РЛС обзора", description: "Дальний обзор: редкие грубые отметки и область поиска; права на пуск не даёт." },
UnitVariant { id: "radar_track", deploy_item: "airdef:deploy_radar_track", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Engagement, label: "РЛС сопровождения", description: "Сопровождение: локальный поиск, два канала точных треков; собственное измерение даёт право на пуск." },
UnitVariant { id: "radar_height", deploy_item: "airdef:deploy_radar_height", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Height, label: "Мачтовая РЛС", description: "Мачтовая: поднятая антенна уточняет низкие контакты над рельефом; права на пуск не даёт." },
];
+15 -369
View File
@@ -27,6 +27,8 @@ pub enum SamKind {
Ew,
/// A searchlight: lights up targets at night for the guns.
Light,
/// A passive optical observation post: no radar, no weapon, one class observation at a time (#136).
Optical,
}
/// How a vehicle is put together: how its launcher or turret moves and is drawn.
@@ -107,11 +109,6 @@ pub(super) struct Drive {
pub pitch: (f64, f64),
}
/// The drives are this share of the speeds they had before they had a speed of their own.
const DRIVE_SCALE: f64 = 0.4;
/// Ticks a drive takes to reach its top speed (and to stop from it).
const DRIVE_RAMP: f64 = 8.0;
pub struct SamSpec {
pub name: &'static str,
pub key: &'static str,
@@ -140,20 +137,16 @@ impl SamSpec {
pub(super) fn drive(&self) -> Drive {
let (yaw, pitch) = match (&self.gun, self.family) {
(Some(g), _) => g.slew,
(None, Family::Trainable) => (0.12, 0.0),
(None, Family::Vertical) => (0.15, 0.0),
(None, _) => (0.05, 0.05),
(None, Family::Trainable) => DRIVE_TRAINABLE,
(None, Family::Vertical) => DRIVE_VERTICAL,
(None, _) => DRIVE_OTHER,
};
let axis = |speed: f64| (speed * DRIVE_SCALE, speed * DRIVE_SCALE / DRIVE_RAMP);
Drive { yaw: axis(yaw), pitch: axis(pitch) }
}
}
const NO_PARTS: Parts = Parts { body: "", launcher: None, pack: None, dish: None, fixed: &[], spinner: None };
/// The battery radar trailer behind a vertical launcher.
const BATTERY_RADAR: &[(&str, f64, f64)] = &[("airdef:radar_trailer", 0.0, 4.2)];
const BATTERY_SPINNER: Option<(&str, f64, f64, f64, f64)> = Some(("airdef:radar_panel", 0.9, 4.2, 0.9, -0.3));
const TUBE_PIVOT: DVec3 = DVec3::new(0.0, -0.5, 1.5);
include!("unit_specs_generated.rs");
impl SamKind {
pub const ALL: [SamKind; super::catalog::UNIT_COUNT] = super::catalog::UNIT_KINDS;
@@ -170,361 +163,6 @@ impl SamKind {
SamKind::Tor,
SamKind::P1sun,
];
pub fn spec(self) -> &'static SamSpec {
match self {
SamKind::Patriot => {
const S: SamSpec = SamSpec {
name: "Patriot",
key: "patriot",
missile: Some(MissileLoad { kind: MissileKind::Pac3, magazine: 4, min: 10.0, max: 450.0, interval: 16 }),
gun: None,
reload: 220,
scale: 1.3,
rest_pitch: 0.66,
roles: 30,
family: Family::Trainable,
parts: Parts {
body: "airdef:patriot_trailer",
launcher: Some("airdef:patriot_launcher"),
fixed: &[("airdef:patriot_truck", 0.0, -3.0), ("airdef:patriot_radar", 0.0, 3.6)],
..NO_PARTS
},
mount: (0.69, 1.2),
pivot: DVec3::new(0.0, -0.5, 1.375),
muzzle: Muzzle::Patriot,
sensor: 585.0,
mast: 5.0,
};
&S
}
SamKind::Gepard => {
const S: SamSpec = SamSpec {
name: "Гепард",
key: "gepard",
missile: None,
gun: Some(GunSpec { range: 135.0, track: 195.0, p: 0.3, bursts: 160, shell: 10.0, slew: (0.22, 0.16) }),
reload: 160,
scale: 1.25,
rest_pitch: 0.0,
roles: 7,
family: Family::Gun,
parts: Parts {
body: "airdef:gepard_hull",
launcher: Some("airdef:gepard_turret"),
pack: Some("airdef:gepard_guns"),
dish: Some(("airdef:gepard_dish", 0.95, 0.6, 0.0)),
..NO_PARTS
},
mount: (1.55, 0.25),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 255.0,
mast: 3.0,
};
&S
}
SamKind::Pantsir => {
const S: SamSpec = SamSpec {
name: "Панцирь-С1",
key: "pantsir",
missile: Some(MissileLoad { kind: MissileKind::M57e6, magazine: 12, min: 25.0, max: 225.0, interval: 14 }),
gun: Some(GunSpec { range: 90.0, track: 135.0, p: 0.25, bursts: 140, shell: 9.0, slew: (0.25, 0.18) }),
reload: 280,
scale: 1.3,
rest_pitch: 0.0,
roles: 15,
family: Family::Turret,
parts: Parts {
body: "airdef:pantsir_truck",
launcher: Some("airdef:pantsir_turret"),
pack: Some("airdef:pantsir_pack"),
dish: Some(("airdef:pantsir_dish", 0.85, 0.3, 0.3)),
..NO_PARTS
},
mount: (1.35, 0.69),
pivot: DVec3::ZERO,
muzzle: Muzzle::Pantsir,
sensor: 292.0,
mast: 4.0,
};
&S
}
SamKind::S400 => {
const S: SamSpec = SamSpec {
name: "С-400",
key: "s400",
missile: Some(MissileLoad { kind: MissileKind::M48n6, magazine: 4, min: 30.0, max: 720.0, interval: 20 }),
gun: None,
reload: 420,
scale: 1.5,
rest_pitch: HALF_PI - 0.02,
roles: 30,
family: Family::Vertical,
parts: Parts {
body: "airdef:s400_chassis",
launcher: Some("airdef:s400_tubes"),
fixed: BATTERY_RADAR,
spinner: BATTERY_SPINNER,
..NO_PARTS
},
mount: (0.7, 1.45),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 2, 7.0),
sensor: 936.0,
mast: 5.0,
};
&S
}
SamKind::S500 => {
const S: SamSpec = SamSpec {
name: "С-500",
key: "s500",
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 2, min: 40.0, max: 1050.0, interval: 20 }),
gun: None,
reload: 520,
scale: 1.6,
rest_pitch: HALF_PI - 0.02,
roles: 24,
family: Family::Vertical,
parts: Parts {
body: "airdef:s500_chassis",
launcher: Some("airdef:s500_tubes"),
fixed: BATTERY_RADAR,
spinner: BATTERY_SPINNER,
..NO_PARTS
},
mount: (0.7, 1.45),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 1, 9.5),
sensor: 1365.0,
mast: 5.0,
};
&S
}
SamKind::IrisT => {
const S: SamSpec = SamSpec {
name: "IRIS-T SLM",
key: "irist",
missile: Some(MissileLoad { kind: MissileKind::IrisT, magazine: 8, min: 15.0, max: 600.0, interval: 10 }),
gun: None,
reload: 300,
scale: 1.4,
rest_pitch: HALF_PI - 0.02,
roles: 15,
family: Family::Vertical,
parts: Parts {
body: "airdef:irist_chassis",
launcher: Some("airdef:irist_tubes"),
fixed: BATTERY_RADAR,
spinner: BATTERY_SPINNER,
..NO_PARTS
},
mount: (0.7, 1.45),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(4, 2, 4.0),
sensor: 780.0,
mast: 5.0,
};
&S
}
SamKind::Nasams => {
const S: SamSpec = SamSpec {
name: "NASAMS",
key: "nasams",
missile: Some(MissileLoad { kind: MissileKind::Amraam, magazine: 6, min: 10.0, max: 450.0, interval: 14 }),
gun: None,
reload: 260,
scale: 1.3,
rest_pitch: 0.5,
roles: 14,
family: Family::Trainable,
parts: Parts {
body: "airdef:nasams_trailer",
launcher: Some("airdef:nasams_launcher"),
fixed: &[("airdef:radar_trailer", 0.0, 3.4)],
spinner: Some(("airdef:radar_panel", 0.9, 3.4, 0.6, -0.3)),
..NO_PARTS
},
mount: (0.62, 0.4),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(3, 2, 4.0),
sensor: 585.0,
mast: 5.0,
};
&S
}
SamKind::Buk => {
const S: SamSpec = SamSpec {
name: "Бук-М2",
key: "buk",
missile: Some(MissileLoad { kind: MissileKind::M9m317, magazine: 4, min: 20.0, max: 675.0, interval: 18 }),
gun: None,
reload: 400,
scale: 1.4,
rest_pitch: 0.0,
roles: 14,
family: Family::Turret,
parts: Parts {
body: "airdef:buk_chassis",
launcher: Some("airdef:buk_turret"),
pack: Some("airdef:buk_rails"),
..NO_PARTS
},
mount: (1.55, 0.2),
pivot: DVec3::ZERO,
muzzle: Muzzle::Rails(&[-9.0, -3.0, 13.0, 19.0]),
sensor: 878.0,
mast: 4.0,
};
&S
}
SamKind::Tor => {
const S: SamSpec = SamSpec {
name: "Тор-М2",
key: "tor",
missile: Some(MissileLoad { kind: MissileKind::M9m338, magazine: 8, min: 8.0, max: 240.0, interval: 8 }),
gun: None,
reload: 300,
scale: 1.3,
rest_pitch: 0.0,
roles: 15,
family: Family::Vertical,
parts: Parts { body: "airdef:tor_chassis", launcher: Some("airdef:tor_turret"), ..NO_PARTS },
mount: (1.5, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::Cells,
sensor: 315.0,
mast: 3.5,
};
&S
}
SamKind::P1sun => {
const S: SamSpec = SamSpec {
name: "P1-SUN",
key: "p1sun",
missile: Some(MissileLoad { kind: MissileKind::P1sun, magazine: 8, min: 5.0, max: 675.0, interval: 12 }),
gun: None,
reload: 240,
scale: 1.1,
rest_pitch: 0.35,
roles: 1,
family: Family::Trainable,
parts: Parts { body: "airdef:nasams_trailer", launcher: Some("airdef:p1sun_launcher"), ..NO_PARTS },
mount: (0.6, 0.3),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(4, 2, 3.0),
// No radar of its own: it fires on the network's tracks.
sensor: 0.0,
mast: 2.0,
};
&S
}
SamKind::Radar => {
const S: SamSpec = SamSpec {
name: "РЛС дальнего обнаружения",
key: "radar",
missile: None,
gun: None,
reload: 0,
scale: 1.5,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts {
body: "airdef:radar_truck",
spinner: Some(("airdef:radar_panel", 1.2, 1.2, 1.5, -0.25)),
..NO_PARTS
},
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 2550.0,
mast: 16.0,
};
&S
}
SamKind::Depot => {
const S: SamSpec = SamSpec {
name: "Склад боеприпасов",
key: "depot",
missile: None,
gun: None,
reload: 0,
scale: 1.5,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts { body: "airdef:depot", ..NO_PARTS },
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 1.0,
};
&S
}
SamKind::Tzm => {
const S: SamSpec = SamSpec {
name: "ТЗМ",
key: "tzm",
missile: None,
gun: None,
reload: 0,
scale: 1.3,
rest_pitch: 0.0,
roles: 0,
family: Family::Truck,
parts: Parts { body: "airdef:tzm_truck", ..NO_PARTS },
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 2.0,
};
&S
}
SamKind::Ew => {
const S: SamSpec = SamSpec {
name: "Станция РЭБ",
key: "ew",
missile: None,
gun: None,
reload: 0,
scale: 1.3,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts { body: "airdef:ew_truck", ..NO_PARTS },
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 3.0,
};
&S
}
SamKind::Light => {
const S: SamSpec = SamSpec {
name: "Прожектор",
key: "light",
missile: None,
gun: None,
reload: 0,
scale: 1.2,
rest_pitch: 0.6,
roles: 0,
family: Family::Light,
parts: Parts { body: "airdef:searchlight", launcher: Some("airdef:searchlight_head"), ..NO_PARTS },
mount: (0.85, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 1.5,
};
&S
}
}
}
pub fn name(self) -> &'static str {
self.spec().name
}
@@ -543,6 +181,14 @@ impl SamKind {
let s = self.spec();
s.missile.is_some() || s.gun.is_some()
}
/// Missiles its launcher's magazine holds; `None` without a launcher.
pub fn missile_magazine(self) -> Option<u32> {
self.spec().missile.as_ref().map(|m| m.magazine)
}
/// Whether it has a gun (its bursts are read by the status line).
pub fn has_gun(self) -> bool {
self.spec().gun.is_some()
}
}
impl Sam {
@@ -689,7 +335,7 @@ pub(super) fn draw_sam_model(sam: &Sam, rng: &mut Rng, out: &mut Out) {
part(out, model, sam.pos + up + DVec3::Y * h * s + base * DVec3::new(0.0, 0.0, back * s), base, s);
}
if let Some((model, h, back, size, tilt)) = parts.spinner {
let extra = if sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Height { 8.0 } else { 0.0 };
let extra = if sam.kind == SamKind::Radar { sam.radar_profile().mast } else { 0.0 };
let foot = sam.pos + up + DVec3::Y * h * s + base * DVec3::new(0.0, 0.0, back * s);
for segment in 0..(extra as u32 / 2) {
part(out, "airdef:radar_mast", foot + DVec3::Y * (segment as f64 * 2.0 + 0.5), base, 1.0);
+15 -14
View File
@@ -18,23 +18,24 @@ impl MissileKind {
/// The sound of its motor, its gain and its pitch: a rocket's roar, or the electric whine of
/// a motor without a flame.
pub fn engine_voice(self) -> (&'static str, f32, f32) {
if self.spec().flame == 0.0 {
return ("airdef:drone.lancet", 0.8, 1.6);
}
let pitch = match self {
MissileKind::Pac3 => 1.0,
MissileKind::M57e6 => 1.12,
MissileKind::M48n6 => 0.88,
MissileKind::M77n6 => 0.8,
MissileKind::IrisT | MissileKind::Amraam => 1.05,
MissileKind::M9m317 => 0.9,
MissileKind::M9m338 => 1.15,
MissileKind::P1sun => 1.7,
};
("airdef:missile.flight", 1.0, pitch)
self.spec().voice
}
/// Ticks from the launch until the motor lights (a cold launch throws it out of the tube first).
pub fn lit_after(self) -> u32 {
self.spec().cold
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::catalog::sound;
/// The catalog holds the voice that is actually played. P1-SUN has no flame, so it uses the
/// Lancet voice at 1.6; its old `P1sun => 1.7` match arm was unreachable behind `flame == 0`.
#[test]
fn missile_engine_voices_keep_their_played_values() {
assert_eq!(MissileKind::P1sun.engine_voice(), (sound::DRONE_LANCET, 0.8, 1.6));
assert_eq!(MissileKind::M48n6.engine_voice(), (sound::MISSILE_FLIGHT, 1.0, 0.88));
}
}
+1022 -71
View File
File diff suppressed because it is too large Load Diff
+19 -21
View File
@@ -232,33 +232,31 @@ impl WorldCache {
.map(|e| 48 + if matches!(e.fill, Fill::Mixed(_)) { 512 } else { 0 })
.sum()
}
/// What the cache holds, about: `(sections, other)` — the sections' table and mixed
/// bits, then the rays, queues, questions and blasts expected (see `sim::memory`).
pub fn memory(&self) -> (usize, usize) {
use super::memory::{map_bytes, vec_bytes};
let entry = std::mem::size_of::<Sec>() + std::mem::size_of::<Entry>();
let sections = map_bytes(self.secs.len(), entry)
+ self.secs.values().filter(|e| matches!(e.fill, Fill::Mixed(_))).count() * 512;
let ray_entry = std::mem::size_of::<(u32, [i32; 3])>() + std::mem::size_of::<RayEntry>();
let other = map_bytes(self.rays.entries.len(), ray_entry)
+ map_bytes(self.rays.by_id.len(), std::mem::size_of::<u32>() + std::mem::size_of::<(u32, [i32; 3])>())
+ vec_bytes(&self.rays.out)
+ vec_bytes(&self.urgent)
+ vec_bytes(&self.ahead)
+ map_bytes(self.queued.len(), std::mem::size_of::<Sec>())
+ map_bytes(self.asked.len(), std::mem::size_of::<Sec>() + std::mem::size_of::<u64>())
+ vec_bytes(&self.expected)
+ map_bytes(self.changed_cols.len(), std::mem::size_of::<(i32, i32)>());
(sections, other)
}
pub fn len(&self) -> usize {
self.secs.len()
}
pub fn is_empty(&self) -> bool {
self.secs.is_empty()
}
/// One line for the report.
pub fn text(&self) -> String {
let s = &self.stats;
format!(
"мир: {} секций ({} КБ), запросов {}, неизвестно {}, лучей {} (ударов {}, неизв. {}), клеток {}; взрывы в блоках: {} (подтверждено {}, без перемен {}, нет чанка {}), чужих ответов {}",
self.len(),
self.bytes() / 1024,
s.sections_asked,
s.sections_unknown,
s.sweeps,
s.hits,
s.unknown_sweeps,
s.cells,
s.blasts_asked,
s.blasts_confirmed,
s.blasts_unchanged,
s.blasts_unloaded,
s.late_dropped
)
}
/// The game's note of changes: another world voids everything; changed
/// sections (or too many to say) are read again when next used.
pub fn changed(&mut self, epoch: u32, overflow: bool, sections: &[Sec]) {
+12 -8
View File
@@ -13,6 +13,8 @@ use std::collections::HashMap;
const MAX_TRAIL: usize = 2400;
const MAX_TOTAL: usize = 4000;
// A small optical-density lift for powered missile trails. Keep geometry and budgets unchanged.
const MISSILE_TRAIL_DENSITY: f32 = 1.12;
struct Trail {
seg: SmokeSegment,
@@ -135,7 +137,7 @@ fn rocket(scale: f32, density: f32, life: f32) -> Look {
Look {
r0: 0.25 * scale,
r1: 1.2 + 1.6 * scale,
density,
density: density * MISSILE_TRAIL_DENSITY,
soot: 0.02,
clear: 0.8 + 1.2 * scale,
life: life + 250.0 * scale,
@@ -163,7 +165,7 @@ fn drone_look(class: Class, scale: f32) -> Look {
Class::Cruise => Look {
r0: 0.6,
r1: 3.0,
density: 0.6,
density: 0.6 * MISSILE_TRAIL_DENSITY,
soot: 0.3,
clear: 2.0,
life: 600.0,
@@ -606,13 +608,15 @@ mod tests {
#[test]
fn recorded_physical_strike_trail_starts_at_ignition_not_at_the_muzzle() {
use crate::sim::record::{Recording, What};
let mut rec = Recording::blank(40);
rec.straight(1, What::StrikeCarrier(77), 10, 30, DVec3::ZERO, DVec3::Z * 20.0);
let ignite = 10.0 + crate::sim::strike::EJECT_TICKS as f64;
let mut rec = Recording::blank(120);
rec.straight(1, What::StrikeCarrier(77), 10, 90, DVec3::ZERO, DVec3::Z * 80.0);
assert!(replay_smoke(&rec, 14.0).is_empty());
let segments = replay_smoke(&rec, 18.0);
assert_eq!(segments.len(), 1);
assert!((segments[0].az - 5.0).abs() < 1e-6);
assert!((segments[0].bz - 8.0).abs() < 1e-6);
assert!(replay_smoke(&rec, (ignite - 2.0).max(30.0)).is_empty(), "no trail before the ignition");
let segments = replay_smoke(&rec, ignite + 12.0);
assert_eq!(segments.len(), 2);
assert!((segments[0].az - 20.0).abs() < 1e-6 && (segments[0].bz - 24.0).abs() < 1e-6, "the trail begins at the recorded ignition");
assert!((segments[1].az - 24.0).abs() < 1e-6 && (segments[1].bz - 32.0).abs() < 1e-6);
}
#[test]
+678
View File
@@ -0,0 +1,678 @@
//! Three rounds over one village layout. The existing simulation owns all units,
//! health, ammunition, and combat. The scenario only schedules the rounds and scores objectives.
use super::*;
const PAUSE: u64 = 20 * 30;
const WAVES: u8 = 3;
const WAVE_SEED: u64 = 0x5649_4c4c_4147_4501;
const OBJECTIVES: [(&str, u32); 3] = [("Штаб", 50), ("Лазарет", 30), ("Укрытие", 20)];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Level {
Easy,
Normal,
Hard,
}
impl Level {
fn parse(key: &str) -> Option<Self> {
match key {
"easy" => Some(Self::Easy),
"normal" => Some(Self::Normal),
"hard" => Some(Self::Hard),
_ => None,
}
}
fn key(self) -> &'static str {
match self {
Self::Easy => "easy",
Self::Normal => "normal",
Self::Hard => "hard",
}
}
fn budget(self) -> u32 {
match self {
Self::Easy => 30,
Self::Normal => 25,
Self::Hard => 22,
}
}
fn order(self, wave: u8) -> sim::RaidOrder {
use DroneKind::*;
let extra = match self {
Self::Easy => 0,
Self::Normal => 3,
Self::Hard => 6,
};
let (kinds, dist, approach) = match wave {
0 => (
vec![
(Gerbera, 4 + extra),
(Shahed, 8 + extra),
(Geran3, 2 + extra),
],
430.0,
sim::Approach::Sector,
),
1 => (
vec![
(Gerbera, 6 + extra),
(Shahed, 10 + extra),
(Geran3, 5 + extra),
(Kh101, 3 + extra),
],
600.0,
sim::Approach::TwoSectors,
),
_ => (
vec![
(Gerbera, 8 + extra),
(Shahed, 12 + extra),
(Geran3, 6 + extra),
(Kh101, 4 + extra),
(Iskander, 1 + extra / 3),
],
760.0,
sim::Approach::Waves,
),
};
sim::RaidOrder {
kinds,
dist,
approach,
aim: sim::Aim::Smart,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Phase {
Survey { origin: DVec3, until: u64 },
Setup,
Waiting { wave: u8, until: u64 },
Fighting(u8),
Finished([f64; 3]),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Village {
level: Level,
phase: Phase,
spent: u32,
}
pub(crate) fn cost(kind: SamKind) -> u32 {
match kind {
SamKind::Light | SamKind::Optical => 1,
SamKind::Gepard | SamKind::Radar | SamKind::Depot | SamKind::Tzm | SamKind::Ew => 2,
SamKind::Pantsir | SamKind::Tor | SamKind::P1sun => 3,
SamKind::IrisT | SamKind::Nasams | SamKind::Buk => 4,
SamKind::Patriot | SamKind::S400 => 5,
SamKind::S500 => 6,
}
}
pub(crate) fn active(village: Option<Village>) -> bool {
village.is_some_and(|v| !matches!(v.phase, Phase::Finished(_)))
}
fn idle(sim: &Sim) -> bool {
!sim.planning() && sim.queue.is_empty() && sim.missiles.is_empty() && sim.drones.is_empty()
}
fn score(health: &[f64]) -> (f64, bool) {
let points = OBJECTIVES
.iter()
.zip(health)
.map(|((_, weight), hp)| f64::from(*weight) * hp.clamp(0.0, 100.0) / 100.0)
.sum::<f64>();
(
points,
points >= 65.0 && health.first().is_some_and(|hp| *hp > 0.0),
)
}
fn objective_status(health: &[f64]) -> String {
OBJECTIVES
.iter()
.zip(health)
.map(|((name, _), hp)| format!("{name} {:.0}%", hp))
.collect::<Vec<_>>()
.join(" · ")
}
impl Village {
fn used(self, layout_cost: u32) -> u32 {
if matches!(self.phase, Phase::Survey { .. } | Phase::Setup) {
layout_cost
} else {
self.spent
}
}
pub(crate) fn charge(&mut self, layout_cost: u32, cost: u32) -> Result<(), String> {
if matches!(self.phase, Phase::Finished(_)) {
return Ok(());
}
if !matches!(self.phase, Phase::Setup | Phase::Waiting { .. }) {
return Err("Расстановка доступна при подготовке и в паузе между волнами".into());
}
let remaining = self.level.budget().saturating_sub(self.used(layout_cost));
if cost > remaining {
return Err(format!(
"На эту технику нужно {cost} очк., доступно {remaining}"
));
}
if matches!(self.phase, Phase::Waiting { .. }) {
self.spent += cost;
}
Ok(())
}
pub(crate) fn ready(self) -> bool {
self.phase == Phase::Setup
}
pub(crate) fn fighting(self) -> bool {
matches!(self.phase, Phase::Fighting(_))
}
pub(crate) fn save(self, now: u64, air: bool) -> Option<String> {
let phase = match self.phase {
Phase::Survey { .. } => return None,
Phase::Setup => "setup 0 0".into(),
Phase::Waiting { wave, until } => format!("wait {wave} {}", until.saturating_sub(now)),
Phase::Fighting(wave) if air => format!("fight {wave} 0"),
Phase::Fighting(wave) => format!("wait {wave} 20"),
Phase::Finished([hq, clinic, shelter]) => format!("done 0 0 {hq} {clinic} {shelter}"),
};
Some(format!(
"village {} {} {phase}\n",
self.level.key(),
self.spent
))
}
pub(crate) fn read(text: &str, objectives: usize) -> Result<Option<Self>, String> {
let bad = || "Некорректное состояние сценария «Оборона деревни»".to_string();
let mut rows = text.lines().filter_map(|row| row.strip_prefix("village "));
let Some(row) = rows.next() else {
return Ok(None);
};
if rows.next().is_some() {
return Err(bad());
}
let words: Vec<_> = row.split_whitespace().collect();
let [level, spent, phase, wave, remaining, scores @ ..] = words.as_slice() else {
return Err(bad());
};
let level = Level::parse(level).ok_or_else(bad)?;
let spent = spent
.parse::<u32>()
.ok()
.filter(|&n| n <= level.budget())
.ok_or_else(bad)?;
let wave = wave
.parse::<u8>()
.ok()
.filter(|&n| n < WAVES)
.ok_or_else(bad)?;
let remaining = remaining
.parse::<u64>()
.ok()
.filter(|&n| n <= PAUSE)
.ok_or_else(bad)?;
let phase = match (*phase, wave, remaining, scores) {
("done", 0, 0, [hq, clinic, shelter]) => {
let parse = |s: &str| {
s.parse::<f64>()
.ok()
.filter(|hp| (0.0..=100.0).contains(hp))
.ok_or_else(bad)
};
Phase::Finished([parse(hq)?, parse(clinic)?, parse(shelter)?])
}
("setup", 0, 0, []) if objectives == OBJECTIVES.len() => Phase::Setup,
("wait", wave, remaining, []) if objectives == OBJECTIVES.len() => Phase::Waiting {
wave,
until: remaining,
},
("fight", wave, 0, []) if objectives == OBJECTIVES.len() => Phase::Fighting(wave),
_ => return Err(bad()),
};
Ok(Some(Self {
level,
phase,
spent,
}))
}
/// Move a saved countdown from its relative clock to the restored simulation clock.
pub(crate) fn resume(&mut self, now: u64) {
if let Phase::Waiting { until, .. } = &mut self.phase {
*until = until.saturating_add(now);
}
}
}
impl AirDef {
pub(crate) fn village_active(&self) -> bool {
active(self.village)
}
pub(crate) fn village_layout_cost(&self) -> u32 {
self.sim.sams.iter().map(|s| cost(s.kind)).sum()
}
fn request_village(&mut self, level: Level, origin: DVec3) -> Result<String, String> {
if self.village_active() || !idle(&self.sim) {
return Err("Завершите текущий налёт или остановите сценарий".into());
}
if self.village_layout_cost() > level.budget() {
return Err(format!(
"Текущая расстановка превышает бюджет в {} очк.",
level.budget()
));
}
let phase = if self.sim.targets.is_empty() {
Phase::Survey {
origin,
until: self.sim.tick + 160,
}
} else {
if self.sim.targets.len() != 3 || self.sim.target_health.as_slice() != [100.0; 3] {
return Err("Отметьте ровно три целых объекта или уберите все отметки для автоматической расстановки".into());
}
Phase::Setup
};
self.village = Some(Village {
phase,
level,
spent: 0,
});
self.dirty = true;
Ok(self.village_status())
}
pub(crate) fn village_status(&self) -> String {
let Some(v) = self.village else {
return "Оборона деревни · выберите сложность или /airdef scenario village normal"
.into();
};
let phase = match v.phase {
Phase::Survey { .. } => "ищу точки для объектов".into(),
Phase::Setup => "расставьте технику, затем начните оборону".into(),
Phase::Waiting { wave, until } => format!(
"волна {}/{WAVES} через {} с",
wave + 1,
until.saturating_sub(self.sim.tick).div_ceil(20)
),
Phase::Fighting(wave) => format!("идёт волна {}/{WAVES}", wave + 1),
Phase::Finished(health) => {
let (points, win) = score(&health);
format!(
"{} · {:.0}/100",
if win {
"Победа"
} else {
"Поражение"
},
points
)
}
};
let remaining = v
.level
.budget()
.saturating_sub(v.used(self.village_layout_cost()));
let health = match &v.phase {
Phase::Finished(health) => health.as_slice(),
_ => self.sim.target_health.as_slice(),
};
format!(
"Оборона деревни · {phase} · бюджет {remaining}/{}\n{}",
v.level.budget(),
objective_status(health)
)
}
pub(crate) fn village_command(&mut self, args: &[&str]) -> Result<String, String> {
match args {
[] | ["status"] => Ok(self.village_status()),
["prices"] => Ok(SamKind::ALL
.iter()
.map(|&k| format!("{} {}", k.name(), cost(k)))
.collect::<Vec<_>>()
.join(" · ")),
["stop"] => {
self.village = None;
self.dirty = true;
Ok("Сценарий остановлен. Расстановка и текущий налёт остаются в мире".into())
}
["start"] => {
let layout = self.village_layout_cost();
let v = self
.village
.as_mut()
.ok_or("Сначала выберите сложность сценария")?;
if v.phase != Phase::Setup || !idle(&self.sim) {
return Err(
"Оборона запускается после подготовки трёх объектов в спокойном небе"
.into(),
);
}
if layout == 0 || layout > v.level.budget() {
return Err(format!(
"Перед запуском разместите технику в пределах {} очк.",
v.level.budget()
));
}
v.spent = layout;
v.phase = Phase::Waiting {
wave: 0,
until: self.sim.tick + 20 * 5,
};
self.sim.reset_raid_intelligence();
self.sim.clear_breakthroughs();
self.dirty = true;
Ok(self.village_status())
}
[level] => {
let level = Level::parse(level).ok_or("Сложность: easy, normal или hard")?;
let p = player().ok_or("Нет игрока")?;
self.request_village(level, DVec3::new(p.x, p.y, p.z))
}
_ => Err("/airdef scenario village [easy|normal|hard|start|status|prices|stop]".into()),
}
}
pub(crate) fn tick_village(&mut self, out: &mut Out) {
let Some(mut v) = self.village else { return };
let now = self.sim.tick;
match v.phase {
Phase::Survey { origin, until } => {
let mut objects = [
origin,
origin + DVec3::new(48.0, 0.0, 12.0),
origin + DVec3::new(-35.0, 0.0, -32.0),
];
let mut ready = true;
for point in &mut objects {
if let Some(y) = self.ground.at(*point, now) {
point.y = y;
} else {
ready = false;
self.ground.want_chunk((
(point.x.floor() as i32) >> 4,
(point.z.floor() as i32) >> 4,
));
}
}
if ready {
self.sim.targets.extend(objects);
self.sim.target_health.extend([100.0; 3]);
v.phase = Phase::Setup;
out.messages.push(
"Штаб, лазарет и укрытие отмечены. Расставьте технику и начните оборону"
.into(),
);
} else if now >= until {
self.village = None;
self.dirty = true;
out.messages.push("Местность не загрузилась. Отметьте три объекта вручную или начните сценарий ближе к центру деревни".into());
return;
} else {
return;
}
}
Phase::Waiting { wave, until } if now >= until && idle(&self.sim) => {
let objects: Vec<_> = self
.sim
.targets
.iter()
.zip(&self.sim.target_health)
.filter(|(_, hp)| **hp > 0.0)
.map(|(&pos, _)| pos)
.collect();
if objects.is_empty() {
v.phase = Phase::Finished(
self.sim
.target_health
.as_slice()
.try_into()
.unwrap_or([0.0; 3]),
);
} else {
self.sim.reseed(WAVE_SEED.wrapping_add(u64::from(wave)));
if self.sim.order_raid(&v.level.order(wave), &objects, out) == 0 {
return;
}
v.phase = Phase::Fighting(wave);
out.messages
.push(format!("Оборона деревни · волна {}/{WAVES}", wave + 1));
}
}
Phase::Fighting(wave) if now % 20 == 0 && idle(&self.sim) => {
if wave + 1 == WAVES || self.sim.target_health.iter().all(|&hp| hp <= 0.0) {
v.phase = Phase::Finished(
self.sim
.target_health
.as_slice()
.try_into()
.unwrap_or([0.0; 3]),
);
} else {
v.phase = Phase::Waiting {
wave: wave + 1,
until: now + PAUSE,
};
out.messages.push(format!(
"Волна {}/{} завершена. Следующая через {} с. {}",
wave + 1,
WAVES,
PAUSE / 20,
objective_status(&self.sim.target_health)
));
}
}
_ => return,
}
self.village = Some(v);
self.dirty = true;
if self.menu == Some(Page::Village) {
self.open_menu(Page::Village);
}
if matches!(v.phase, Phase::Finished(_)) {
out.messages.push(format!(
"{} · разбор: /airdef breaches",
self.village_status()
));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::test_mod;
fn setup() -> AirDef {
let mut game = test_mod();
game.sim
.targets
.extend([DVec3::ZERO, DVec3::X * 50.0, DVec3::Z * 50.0]);
game.sim.target_health.extend([100.0; 3]);
game.request_village(Level::Normal, DVec3::ZERO).unwrap();
game
}
fn deploy(game: &mut AirDef, kind: SamKind) -> Result<u32, String> {
game.place(
kind,
sim::battery::SamMode::Integrated,
sim::battery::RadarRole::Multifunction,
DVec3::ZERO,
0.0,
)
}
#[test]
fn budget_guards_deployment_and_spent_points_stay_spent() {
let mut game = setup();
for _ in 0..4 {
deploy(&mut game, SamKind::S400).unwrap();
}
assert!(deploy(&mut game, SamKind::S500).is_err());
game.village_command(&["start"]).unwrap();
deploy(&mut game, SamKind::S400).unwrap();
game.sim.sams.remove(0);
assert!(deploy(&mut game, SamKind::Light).is_err());
assert!(game.command("airdef", "repair").is_err());
assert!(game.command("airdef", "targets clear").is_err());
assert!(game.command("airdef", "wave shahed 1").is_err());
assert_eq!(game.sim.targets.len(), 3);
}
#[test]
fn waiting_resumes_and_all_three_waves_keep_the_layout_state() {
let mut game = setup();
deploy(&mut game, SamKind::S400).unwrap();
game.village_command(&["start"]).unwrap();
game.sim.tick = 60;
game.sim.sams[0].missiles = 2;
game.sim.target_health[1] = 80.0;
let saved = game.state_text(false, false);
let mut restored = test_mod();
restored.apply_state(&saved).unwrap();
game = restored;
let mut out = Out::default();
for wave in 0..WAVES {
let v = game.village.unwrap();
let Phase::Waiting { wave: index, until } = v.phase else {
panic!("{:?}", v.phase)
};
assert_eq!(index, wave);
assert_eq!(until - game.sim.tick, if wave == 0 { 40 } else { PAUSE });
game.sim.tick = until - 1;
game.tick_village(&mut out);
assert!(!game.sim.planning());
game.sim.tick = until;
game.tick_village(&mut out);
assert!(game.sim.planning());
assert_eq!(game.village.unwrap().phase, Phase::Fighting(wave));
assert!(deploy(&mut game, SamKind::Gepard).is_err());
// Complete the combat externally here to test the scenario transitions in isolation.
game.sim.clear();
game.sim.tick = game.sim.tick.div_ceil(20) * 20;
game.tick_village(&mut out);
assert_eq!(game.sim.sams[0].missiles, 2);
assert_eq!(game.sim.target_health, [100.0, 80.0, 100.0]);
}
assert_eq!(
game.village.unwrap().phase,
Phase::Finished([100.0, 80.0, 100.0])
);
assert!(game.village_status().contains("Победа · 94/100"));
game.sim.targets.clear();
game.sim.target_health.clear();
let mut restored = test_mod();
restored
.apply_state(&game.state_text(false, false))
.unwrap();
assert!(restored.village_status().contains("Победа · 94/100"));
assert!(
out.messages
.iter()
.any(|line| line.contains("/airdef breaches"))
);
}
#[test]
fn three_playable_rounds_finish_and_the_report_lists_real_impacts() {
struct Flat;
impl sim::world::WorldSource for Flat {
fn solid(&self, _: i32, y: i32, _: i32) -> Option<bool> {
Some(y < 64)
}
}
let mut game = test_mod();
game.request_village(Level::Easy, DVec3::new(0.0, 64.0, 0.0))
.unwrap();
// Lay one battery and hold its fire so the mission reaches the report path.
game.sim.damage = false;
game.sim.hold = true;
let mut out = Out::default();
let mut wave_count = 0;
for _ in 0..9000 {
let now = game.sim.tick;
let columns = game
.ground
.take_wanted()
.into_iter()
.map(|(x, z)| (x, z, 64))
.collect();
game.ground.answer(columns, now);
let sections = game.ground.world.take_wanted(now);
game.ground.world.serve(&Flat, sections, now);
let rays = game.ground.world.take_rays(now);
game.ground.world.serve_rays(&Flat, rays);
game.ground.take_chunks();
game.sim.step(&mut game.ground, None, &mut out);
game.tick_village(&mut out);
let phase = game.village.unwrap().phase;
if phase == Phase::Setup {
deploy(&mut game, SamKind::Gepard).unwrap();
game.village_command(&["start"]).unwrap();
}
wave_count += out
.messages
.iter()
.filter(|m| m.starts_with("Оборона деревни · волна "))
.count();
if matches!(phase, Phase::Finished(_)) {
break;
}
out = Out::default();
}
assert_eq!(wave_count, 3);
assert!(matches!(game.village.unwrap().phase, Phase::Finished(_)));
assert!(game.sim.breakthrough_pages() > 0);
assert!(
game.sim
.breakthrough_page(0)
.contains("Снимок перед ударом")
);
}
#[test]
fn survey_uses_world_heights_and_score_weights_each_object() {
let mut game = test_mod();
game.request_village(Level::Easy, DVec3::ZERO).unwrap();
let mut out = Out::default();
game.tick_village(&mut out);
assert!(game.sim.targets.is_empty());
let wanted = game.ground.take_wanted();
assert_eq!(wanted.len(), 3);
game.ground.answer(
wanted
.into_iter()
.enumerate()
.map(|(i, (x, z))| (x, z, 64 + i as i32))
.collect(),
game.sim.tick,
);
game.tick_village(&mut out);
assert_eq!(
game.sim.targets.iter().map(|p| p.y).collect::<Vec<_>>(),
[64.0, 65.0, 66.0]
);
assert_eq!(score(&[0.0, 100.0, 100.0]), (50.0, false));
assert_eq!(score(&[90.0, 60.0, 10.0]), (65.0, true));
}
}
+24 -6
View File
@@ -172,21 +172,28 @@ impl WaveConfig {
#[cfg(test)]
mod catalog_tests {
use super::*;
use crate::sim::catalog::{AIRCRAFT, UNITS};
use crate::sim::catalog::{AIRCRAFT, UNITS, VARIANTS};
fn assets() -> std::path::PathBuf {
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("assets/airdef")
}
fn item_exists(item: &str) {
let name = item.strip_prefix("airdef:").expect("item namespace");
for path in [format!("items/{name}.json"), format!("models/item/{name}.json"), format!("textures/item/{name}.png")] {
for path in [format!("items/{name}.json"), format!("models/item/{name}.json")] {
assert!(assets().join(&path).is_file(), "{item}: missing {path}");
}
let definition = std::fs::read_to_string(assets().join(format!("items/{name}.json"))).unwrap();
assert!(definition.contains(&format!("airdef:item/{name}")), "{item}: wrong item model");
let model = std::fs::read_to_string(assets().join(format!("models/item/{name}.json"))).unwrap();
assert!(model.contains(&format!("airdef:item/{name}")), "{item}: wrong icon reference");
let png = std::fs::read(assets().join(format!("textures/item/{name}.png"))).unwrap();
// The icon reference may be an alias of an existing texture (the optical post uses the
// radar icon until its own asset lands, #136); what matters is that the PNG it names exists.
let layer = model
.split("\"layer0\": \"")
.nth(1)
.and_then(|s| s.split('"').next())
.unwrap_or_else(|| panic!("{item}: no icon reference"));
let texture = layer.strip_prefix("airdef:item/").unwrap_or_else(|| panic!("{item}: bad icon reference {layer}"));
let png = std::fs::read(assets().join(format!("textures/item/{texture}.png"))).unwrap();
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "{item}: invalid PNG signature");
}
fn model_exists(model: &str) {
@@ -208,15 +215,26 @@ mod catalog_tests {
for model in [p.launcher, p.pack, p.dish.map(|v| v.0), p.spinner.map(|v| v.0)].into_iter().flatten() { model_exists(model); }
for (model, _, _) in p.fixed { model_exists(model); }
}
for variant in VARIANTS {
item_exists(variant.deploy_item);
}
}
#[test]
fn inventory_entries_match_catalog_and_scenario_order_round_trips() {
for item in AIRCRAFT.iter().filter_map(|a| a.launch_item).chain(UNITS.iter().map(|u| u.deploy_item)) {
let catalogued = |item: &str| {
AIRCRAFT.iter().any(|a| a.launch_item == Some(item))
|| UNITS.iter().any(|u| u.deploy_item == item)
|| VARIANTS.iter().any(|v| v.deploy_item == item)
};
for item in AIRCRAFT.iter().filter_map(|a| a.launch_item)
.chain(UNITS.iter().map(|u| u.deploy_item))
.chain(VARIANTS.iter().map(|v| v.deploy_item))
{
assert_eq!(crate::ITEMS.iter().filter(|i| **i == item).count(), 1, "{item}");
}
for item in crate::ITEMS.iter().filter(|i| i.starts_with("airdef:launch_") || i.starts_with("airdef:deploy_")) {
assert!(AIRCRAFT.iter().any(|a| a.launch_item == Some(*item)) || UNITS.iter().any(|u| u.deploy_item == *item), "uncatalogued item {item}");
assert!(catalogued(item), "uncatalogued item {item}");
}
let mut wave = WaveConfig::default();
for (i, count) in wave.counts.iter_mut().enumerate() { *count = i as u32; }
+420
View File
@@ -0,0 +1,420 @@
//! Local bridge for the optional web panel. The engine's control endpoint stays local.
//! Snapshot and receipt I/O runs on explicit commands, never inside a tick or frame hook.
use crate::{AirDef, Out, battery_view, player, post, sim, wave, why_view};
use glam::DVec3;
use horizon_mod_sdk::storage;
use serde_json::{Value, json};
use std::collections::{HashSet, VecDeque};
const SNAPSHOT: &str = "panel-snapshot-v1.json";
const RECEIPT: &str = "panel-receipt-v1.json";
// Leave space under Horizon's 1 MiB per-call storage budget for both debug views
// and incremental logs from the active recording and the three retained replays.
const ENTITY_LIMIT: usize = 256;
const LOG_BATCH: usize = 128;
const RECEIPT_LIMIT: usize = 64;
#[derive(Default)]
pub(super) struct Link {
session: String,
receipts: VecDeque<(String, Value)>,
}
fn token(s: &str) -> bool {
(16..=32).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_hexdigit())
}
fn position(id: impl Into<Value>, label: impl Into<Value>, p: DVec3) -> Value {
json!({ "id": id.into(), "label": label.into(), "x": p.x, "y": p.y, "z": p.z })
}
fn merge(row: &mut Value, fields: Value) {
row.as_object_mut()
.unwrap()
.extend(fields.as_object().unwrap().clone());
}
fn configs() -> Value {
let presets: Vec<_> = wave::PRESETS
.iter()
.enumerate()
.map(|(i, preset)| {
let mut w = wave::WaveConfig::default();
w.apply(i);
json!({
"name": preset.name, "counts": w.counts.to_vec(), "distance": w.dist,
"approach": sim::Approach::ALL.iter().position(|a| *a == w.approach).unwrap(),
"aim": sim::Aim::ALL.iter().position(|a| *a == w.aim).unwrap()
})
})
.collect();
json!({
"kinds": wave::KINDS.iter().map(|k| k.spec().name).collect::<Vec<_>>(),
"approaches": sim::Approach::ALL.map(sim::Approach::name),
"aims": sim::Aim::ALL.map(sim::Aim::name),
"distance": [wave::DIST_MIN, wave::DIST_MAX],
"presets": presets,
})
}
fn public_live(sim: &sim::Sim) -> Value {
let now = sim.tick;
let picture = sim.air_picture();
// The local HUD has an unaided truth fallback. The web network view deliberately has none.
let mut known = HashSet::new();
let contacts: Vec<_> = picture.tracks.iter().take(ENTITY_LIMIT).filter(|_| !picture.unaided).map(|t| {
known.insert(t.id);
let mut row = position(t.id, t.class.name(), t.est(now));
merge(&mut row, json!({
"status": if t.forecast(now) { "Оценка положения" } else { "Измерено" },
"source": (t.source != 0).then_some(t.source), "age": t.age(now),
"quality": t.quality, "confidence": t.ident().name(), "radius": t.uncertainty(now),
"vx": t.vel.x * 20.0, "vz": t.vel.z * 20.0,
}));
row
}).collect();
let units: Vec<_> = sim
.sams
.iter()
.take(ENTITY_LIMIT)
.enumerate()
.map(|(i, s)| {
let mut row = position(s.id, format!("№{} {}", i + 1, s.kind.name()), s.pos);
merge(
&mut row,
json!({
"status": post::state(s), "details": battery_view::sam_status(s, now),
"health": s.health, "rounds": s.missiles, "bursts": s.bursts,
"target": s.target.or(s.gun_target).filter(|id| known.contains(id)),
}),
);
row
})
.collect();
let objects: Vec<_> = sim.targets.iter().take(ENTITY_LIMIT).enumerate().map(|(i, &p)| {
let mut row = position(i + 1, format!("Объект №{}", i + 1), p);
let health = sim.target_health.get(i).copied();
merge(&mut row, json!({ "health": health, "status": if health == Some(0.0) { "Уничтожен" } else { "Под защитой" } }));
row
}).collect();
let interceptors: Vec<_> = sim.missiles.iter().take(ENTITY_LIMIT).map(|m| {
let mut row = position(m.id, format!("Перехватчик №{}", m.id), m.pos);
merge(&mut row, json!({ "target": known.contains(&m.target()).then_some(m.target()), "status": "В полёте" }));
row
}).collect();
json!({
"units": units, "objects": objects, "contacts": contacts, "interceptors": interceptors,
"summary": { "kills": sim.kills, "hits": sim.hits, "planning": sim.planning(), "hold": sim.hold },
"limited": sim.sams.len() > ENTITY_LIMIT || (!picture.unaided && picture.tracks.len() > ENTITY_LIMIT)
|| sim.missiles.len() > ENTITY_LIMIT || sim.targets.len() > ENTITY_LIMIT
})
}
fn perspectives(sim: &sim::Sim, debug: bool) -> (Value, Value) {
if !debug {
return (Value::Null, Value::Null);
}
let report = sim.enemy_picture();
let observed: Vec<_> = report.observations.iter().take(ENTITY_LIMIT).map(|o| {
let mut row = position(o.id, o.kind.unwrap_or(o.category), o.at);
merge(&mut row, json!({
"status": format!("Донесение · {}", o.category), "confidence": format!("{:?}", o.confidence),
"radius": o.radius, "age": o.age, "source": o.channel, "quality": o.quality, "rank": o.rank,
}));
row
}).collect();
let reports: Vec<_> = report
.aims
.iter()
.filter(|a| a.unit != 0 && report.observations.iter().any(|o| o.id == a.unit))
.take(256)
.map(|a| json!({"contact": a.unit, "reason": a.intent, "at": a.since}))
.collect();
let sorties: Vec<_> = report
.recon_sorties
.iter()
.take(64)
.map(|r| json!({"phase": r.phase, "zones": r.zones_left, "reportIn": r.report_in}))
.collect();
let truth: Vec<_> = sim
.drones
.iter()
.filter(|d| d.alive())
.take(ENTITY_LIMIT)
.map(|d| {
let mut row = position(d.id, d.kind.spec().name, d.pos);
merge(
&mut row,
json!({"status": "Истина", "vx": d.vel.x * 20.0, "vz": d.vel.z * 20.0}),
);
row
})
.collect();
(
json!({"contacts": observed, "units": [], "objects": [], "interceptors": [], "reports": reports, "sorties": sorties,
"limited": report.observations.len() > ENTITY_LIMIT}),
json!(truth),
)
}
fn record_data(rec: &sim::record::Recording, cursor: (u64, usize, usize), active: bool) -> Value {
let first = rec.decisions.first_index();
let (dec, ev, sc) = cursor;
let decisions: Vec<_> = rec.decisions.entries().enumerate().skip(dec.saturating_sub(first) as usize).take(LOG_BATCH)
.map(|(i, &entry)| {
let choice = post::RecordedChoice { raid: rec.number, entry };
json!({ "seq": first + i as u64, "at": entry.at, "unit": entry.unit, "target": entry.target,
"label": post::decision_label(entry.outcome), "lines": post::decision_lines(choice, Some(rec)) })
}).collect();
let next_dec = decisions
.last()
.and_then(|d| d["seq"].as_u64())
.map_or(dec.max(first), |seq| seq + 1);
let mut next_ev = ev.min(rec.events.len());
let mut events = Vec::new();
for (i, event) in rec.events.iter().enumerate().skip(next_ev).take(LOG_BATCH) {
use sim::record::EventKind;
next_ev = i + 1;
let (label, unit, target, object) = match event.kind {
EventKind::Kill { sam, drone, .. } => ("Цель сбита", Some(sam), Some(drone), None),
EventKind::Hit {
drone,
object: Some(object),
..
} => ("Попадание по объекту", None, Some(drone), Some(object + 1)),
EventKind::Hit {
drone,
sam: Some((_, i)),
..
} => (
"Попадание по комплексу",
rec.sams.get(i).map(|s| s.0),
Some(drone),
None,
),
EventKind::SamLost { sam, .. } => ("Комплекс уничтожен", Some(sam), None, None),
_ => continue,
};
events.push(json!({ "seq": i, "at": event.at, "unit": unit, "target": target, "object": object, "label": label, "lines": [] }));
}
let mut observations = Vec::new();
let mut next_sc = sc;
if let Some(scene) = &rec.scene {
use sim::record::SceneKind::*;
next_sc = next_sc.min(scene.events().len());
for (i, event) in scene.events().iter().enumerate().skip(next_sc) {
next_sc = i + 1;
let (label, unit, target) = match event.kind {
TrackAcquired { sam, target, .. } => ("Отметка получена", sam, target),
TrackSource { sam, target, .. } => ("Изменился источник отметки", sam, target),
TrackLock {
sam,
target,
locked,
} => (
if locked {
"Контакт взят на сопровождение"
} else {
"Сопровождение прервано"
},
sam,
target,
),
TrackLost { sam, target } => ("Отметка потеряна", sam, target),
_ => continue,
};
observations.push(json!({ "seq": i, "at": event.at, "unit": unit, "target": target, "label": label, "lines": [] }));
if observations.len() == LOG_BATCH {
break;
}
}
}
json!({ "id": rec.number, "start": rec.started_at, "length": rec.len, "active": active,
"first": first, "gap": dec < first,
"limited": rec.decisions.truncated() || rec.scene.as_ref().is_some_and(|s| s.truncated || s.track_limit_reached()),
"next": [next_dec, next_ev as u64, next_sc as u64], "decisions": decisions, "events": events, "observations": observations })
}
fn cursors(raw: &str, session: &str, raid: u32) -> (u64, usize, usize) {
let Some((epoch, list)) = raw.split_once(':') else {
return (0, 0, 0);
};
if epoch != session {
return (0, 0, 0);
}
list.split(',')
.take(4)
.find_map(|s| {
let mut fields = s.split('.');
let number = fields.next()?.parse::<u32>().ok()?;
(number == raid).then_some((
fields.next()?.parse().ok()?,
fields.next()?.parse().ok()?,
fields.next().and_then(|n| n.parse().ok()).unwrap_or(0),
))
})
.unwrap_or_default()
}
fn parse_wave(raw: &str) -> Result<wave::WaveConfig, String> {
let chunks: Vec<_> = raw.split(':').collect();
let [a, d, aim, counts] = chunks.as_slice() else {
return Err("Неверный формат сценария".into());
};
let approach = a
.parse::<usize>()
.ok()
.and_then(|i| sim::Approach::ALL.get(i))
.ok_or("Неизвестный подход")?;
let aim = aim
.parse::<usize>()
.ok()
.and_then(|i| sim::Aim::ALL.get(i))
.ok_or("Неизвестная цель сценария")?;
let dist = d
.parse::<f64>()
.ok()
.filter(|x| (wave::DIST_MIN..=wave::DIST_MAX).contains(x))
.ok_or("Дальность вне диапазона")?;
let counts: Vec<u32> = counts
.split(',')
.map(str::parse)
.collect::<Result<_, _>>()
.map_err(|_| "Неверное количество")?;
if counts.len() != wave::KINDS.len()
|| counts.iter().any(|&n| n > 80)
|| counts.iter().all(|&n| n == 0)
{
return Err("Укажите допустимое количество аппаратов по каждому типу".into());
}
Ok(wave::WaveConfig {
counts: counts.try_into().unwrap(),
approach: *approach,
dist,
aim: *aim,
preset: 0,
})
}
impl AirDef {
pub(super) fn panel_command(&mut self, args: &[&str]) -> Result<Option<String>, String> {
match args {
["snapshot", nonce, privacy, raw]
if token(nonce) && matches!(*privacy, "public" | "debug") =>
{
if self.world.is_none() || player().is_none() {
return Err("Откройте игровой мир".into());
}
if self.web.session.is_empty() {
self.web.session = nonce.to_string();
}
let session = &self.web.session;
let (enemy, truth) = perspectives(&self.sim, *privacy == "debug");
let raids: Vec<_> = self
.sim
.replays
.iter()
.map(|r| (r, false))
.chain(self.sim.recording().map(|r| (r, true)))
.map(|(r, active)| record_data(r, cursors(raw, session, r.number), active))
.collect();
let selected = self.monitor_index().and_then(|i| {
self.sim.battle_reason(i).map(|reason| {
json!({"unit": self.sim.sams[i].id, "reason": why_view::unit_headline(reason)})
})
});
let content = json!({
"version": 1, "nonce": nonce, "session": session, "world": self.state_key(), "tick": self.sim.tick,
"live": public_live(&self.sim), "enemy": enemy, "truth": truth, "raids": raids, "catalog": configs(),
"selected": selected, "canLaunch": !self.sim.planning() && !self.village_active() && self.presentation.is_live(),
});
let bytes = serde_json::to_vec(&content).map_err(|e| e.to_string())?;
storage::set(SNAPSHOT, &bytes)?;
Ok(None)
}
["launch", id, session, wave] if token(id) => {
let receipt = if let Some((_, previous)) =
self.web.receipts.iter().find(|(key, _)| key == id)
{
previous.clone()
} else {
let result = self.panel_launch(session, wave);
let receipt = match result {
Ok(n) => {
json!({"id": id, "accepted": true, "message": format!("Игра приняла сценарий на {n} аппаратов")})
}
Err(error) => json!({"id": id, "accepted": false, "message": error}),
};
if self.web.receipts.len() == RECEIPT_LIMIT {
self.web.receipts.pop_front();
}
self.web
.receipts
.push_back((id.to_string(), receipt.clone()));
receipt
};
storage::set(
RECEIPT,
&serde_json::to_vec(&receipt).map_err(|e| e.to_string())?,
)?;
Ok(receipt["message"].as_str().map(str::to_owned))
}
_ => Err("Неизвестный запрос веб-пульта".into()),
}
}
fn panel_launch(&mut self, session: &str, raw: &str) -> Result<u32, String> {
if self.web.session.is_empty() || self.web.session != session {
return Err("Игровая сессия сменилась. Обновите карту".into());
}
if self.sim.planning() || self.village_active() || !self.presentation.is_live() {
return Err("В этом режиме нельзя запускать сценарий".into());
}
let p = player().ok_or("Игровой мир закрыт")?;
let wave = parse_wave(raw)?;
let objects = self.objects(DVec3::new(p.x, p.y, p.z));
let mut out = Out::default();
let n = self.sim.order_raid(&wave.order(), &objects, &mut out);
self.emit(out);
(n > 0)
.then_some(n)
.ok_or_else(|| "Игра не приняла сценарий".into())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_network_snapshot_has_no_truth_without_sensors() {
let mut sim = sim::Sim::new(1);
sim.launch(
sim::DroneKind::Shahed,
DVec3::X,
DVec3::Z,
DVec3::ZERO,
&mut Out::default(),
);
assert!(public_live(&sim)["contacts"].as_array().unwrap().is_empty());
let (_, truth) = perspectives(&sim, true);
assert_eq!(truth.as_array().unwrap().len(), 1);
assert!(perspectives(&sim, false).1.is_null());
}
#[test]
fn validates_wave_as_data_and_resets_cursors_between_game_sessions() {
let mut counts = vec!["0"; wave::KINDS.len()];
counts[0] = "2";
assert_eq!(
parse_wave(&format!("0:300:0:{}", counts.join(",")))
.unwrap()
.total(),
2
);
assert!(parse_wave("0:NaN:0:2").is_err());
assert!(parse_wave("0:300:0:1;clear").is_err());
assert_eq!(cursors("new:1.101.200.5,2.0.50.4", "new", 1), (101, 200, 5));
assert_eq!(cursors("old:1.101.200.5", "new", 1), (0, 0, 0));
}
}
+216
View File
@@ -0,0 +1,216 @@
//! Text for diagnostics produced by the simulation.
use crate::sim::why::{BattleBlock, BattleKind, BattleMark, BattleReason, CheckReason, PartEffect};
use crate::sim::{Comps, Part, SamKind};
fn part_value(part: Part, value: f64) -> String {
if value <= 0.0 { format!("{} отказ", part.short()) }
else { format!("{} {:.0}%", part.short(), value * 100.0) }
}
fn part_value_on(part: Part, value: f64, kind: SamKind) -> String {
if value <= 0.0 { format!("{} отказ", part.short_on(kind)) }
else { format!("{} {:.0}%", part.short_on(kind), value * 100.0) }
}
/// Every worn or failed part of a system, as the monitor and the status line read it.
pub fn parts(comps: &Comps, kind: SamKind) -> String {
Part::ALL.iter().filter(|p| p.on(kind) && comps.get(**p) < 1.0)
.map(|p| part_value_on(*p, comps.get(*p), kind)).collect::<Vec<_>>().join(", ")
}
/// The weakest worn or failed part alone, for a one-line status.
pub fn worst(comps: &Comps, kind: SamKind) -> String {
Part::ALL.iter().filter(|p| p.on(kind) && comps.get(**p) < 1.0)
.min_by(|a, b| comps.get(**a).total_cmp(&comps.get(**b)))
.map(|p| part_value_on(*p, comps.get(*p), kind)).unwrap_or_default()
}
/// The mark's age and where it came from, in the battery's own picture: a relayed plot names
/// its station, never the target's true place or kind.
pub fn mark_text(mark: &BattleMark) -> String {
let age = if mark.age == 0 { "сейчас".to_string() } else { format!("{:.1} с назад", mark.age as f64 / 20.0) };
let source = if mark.own {
"своя РЛС".to_string()
} else {
mark.source.map_or_else(|| "сеть".to_string(), |i| format!("сеть, РЛС №{}", i + 1))
};
let mut own = String::new();
if let Some(product) = mark.own_product {
if !mark.own {
own = format!(", своё измерение: {}", product.name());
}
}
let forecast = if mark.forecast { ", прогноз" } else { "" };
format!(
"отметка {age}, источник {source}, {} кач.{} {}{}{forecast}",
mark.product.name(),
mark.quality,
mark.class.name(),
own
)
}
fn with_mark(text: String, mark: Option<BattleMark>) -> String {
match mark {
Some(mark) => format!("{text}: {}", mark_text(&mark)),
None => text,
}
}
/// The one headline reason a battery fires or not, as the player reads it.
pub fn battle_text(reason: &BattleReason) -> String {
match reason.kind {
BattleKind::Ready => with_mark("готов к пуску".into(), reason.mark),
BattleKind::ObserveOnly => with_mark("есть только обзор, пуск не разрешён — нужно своё подтверждённое измерение".into(), reason.mark),
BattleKind::AwaitingTrack => with_mark("ждёт сопровождения — своё измерение ещё не разрешает пуск".into(), reason.mark),
BattleKind::ChannelsBusy => {
let channels = reason.channels.map_or_else(|| "каналы заняты".to_string(), |(used, total)| format!("каналы заняты: {used}/{total}"));
with_mark(channels, reason.mark)
}
BattleKind::NoAmmo => {
let mut text = format!("нет боезапаса: ракет {}, очередей {}", reason.rounds, reason.bursts);
if reason.reloading > 0 {
text += &format!(", перезарядка ещё {:.1} с", reason.reloading as f64 / 20.0);
}
with_mark(text, reason.mark)
}
BattleKind::Blocked => {
let text = match reason.block {
Some(BattleBlock::Destroyed) => "уничтожен".to_string(),
Some(BattleBlock::Moving) => "на марше, не стреляет".to_string(),
Some(BattleBlock::Hold) => "огонь запрещён или роли не заданы".to_string(),
Some(BattleBlock::NoWeapon) => "нет оружия (РЛС, склад, РЭБ, прожектор)".to_string(),
Some(BattleBlock::NoTarget) => "нет целей в небе".to_string(),
Some(BattleBlock::NoTrack) => "цель не обнаружена своей РЛС или сетью".to_string(),
Some(BattleBlock::OutOfRoles) => "цель вне ролей комплекса".to_string(),
Some(BattleBlock::OutOfReach) => "цель вне дальности".to_string(),
Some(BattleBlock::Claimed) => "цель уже занята перехватчиками".to_string(),
Some(BattleBlock::Doctrine) => "запрещено доктриной (сектор, охрана или резерв)".to_string(),
Some(BattleBlock::Aiming) => "ещё доворачивается на цель".to_string(),
Some(BattleBlock::Preparing) => "открывает ТПК".to_string(),
Some(BattleBlock::LauncherDown) => "пусковая отказала".to_string(),
Some(BattleBlock::Other) | None => "стрелять сейчас не может".to_string(),
};
with_mark(text, reason.mark)
}
}
}
/// A card can be opened in normal play, where an unobserved contact is absent from the UI.
pub fn unit_headline(mut reason: BattleReason) -> String {
if reason.mark.is_none() && (reason.target.is_some() || reason.block == Some(BattleBlock::NoTarget)) {
return "нет отметки у комплекса".into();
}
reason.mark = None;
battle_text(&reason)
}
pub fn reason(reason: &CheckReason) -> String {
match reason {
CheckReason::Text(text) => text.clone(),
CheckReason::Battle(battle) => battle_text(battle),
CheckReason::Parts(parts) => format!("узлы: {}", parts.iter().map(|(part, value)| part_value(*part, *value)).collect::<Vec<_>>().join(", ")),
CheckReason::PartEffect(effect) => match effect {
PartEffect::SensorFailed => "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети".into(),
PartEffect::SensorDamaged { fit } => format!("РЛС повреждена: дальность {:.0}%, обзор вдвое реже при худшем", fit * 100.0),
PartEffect::MountFailed { yaw_degrees } => format!("привод наведения заклинил: стоит на {yaw_degrees:.0}°, не доворачивается"),
PartEffect::MountDamaged { fit } => format!("привод наведения повреждён: поворот {:.0}% от нормы", fit * 100.0),
PartEffect::LauncherFailed => "пусковая отказала: пуски невозможны".into(),
PartEffect::LauncherDamaged { cells, capacity, reload_seconds } => format!("пусковая повреждена: {cells} ячеек из {capacity}, перезарядка {reload_seconds:.0} с"),
PartEffect::GunFailed => "орудие заклинило: не стреляет".into(),
PartEffect::GunDamaged { fit } => format!("орудие повреждено: меткость {:.0}%, заклинивает", fit * 100.0),
PartEffect::TracksFailed => "ходовая отказала: на марш не выйдет".into(),
PartEffect::TracksDamaged { speed } => format!("ходовая повреждена: скорость марша {:.0}%", speed * 100.0),
PartEffect::CommsFailed => "связь отказала: сети нет, цели только свои".into(),
PartEffect::CommsDamaged { range } => format!("связь повреждена: линия {range:.0} м"),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::{Comps, Part, SamKind};
#[test]
fn renders_worn_parts_without_the_reason_prefix() {
let mut comps = Comps([1.0; 6]);
comps.0[Part::Sensor as usize] = 0.4;
comps.0[Part::Tracks as usize] = 0.0;
assert_eq!(parts(&comps, SamKind::Pantsir), "РЛС 40%, Ход отказ");
assert_eq!(worst(&comps, SamKind::Pantsir), "Ход отказ");
// A passive post's sensor is optics; only its sensor is fitted.
let mut optics = Comps([1.0; 6]);
optics.0[Part::Sensor as usize] = 0.4;
assert_eq!(parts(&optics, SamKind::Optical), "Опт 40%");
}
#[test]
fn damaged_simulation_produces_player_diagnostics_in_order() {
use crate::sim::{Sam, SamKind, Sim};
let mut sim = Sim::new(1);
let mut sam = Sam::new(1, SamKind::Pantsir, glam::DVec3::ZERO, 0.0);
sam.comps.0[Part::Sensor as usize] = 0.4;
sam.comps.0[Part::Tracks as usize] = 0.0;
sim.sams.push(sam);
let lines: Vec<String> = sim.why(0).iter().map(|c| reason(&c.reason)).collect();
let summary = lines.iter().position(|s| s == "узлы: РЛС 40%, Ход отказ").unwrap();
let sensor = lines.iter().position(|s| s.starts_with("РЛС повреждена: дальность ")).unwrap();
let tracks = lines.iter().position(|s| s == "ходовая отказала: на марш не выйдет").unwrap();
assert!(summary < sensor && sensor < tracks, "{lines:?}");
}
#[test]
fn the_headline_reason_shows_the_marks_age_and_source_without_the_true_kind() {
use crate::sim::battery::Measure;
use crate::sim::ClassEst;
let mark = BattleMark {
age: 46,
own_age: None,
source: Some(2),
own: false,
product: Measure::Search,
quality: 40,
own_product: None,
forecast: false,
class: ClassEst::Unknown,
};
let reason = BattleReason {
kind: BattleKind::ObserveOnly,
block: None,
sam: 0,
target: Some(7),
mark: Some(mark),
rounds: 4,
bursts: 0,
reloading: 0,
channels: None,
};
let text = battle_text(&reason);
assert!(text.starts_with("есть только обзор"), "{text}");
assert!(text.contains("2.3 с назад"), "{text}");
assert!(text.contains("источник сеть, РЛС №3"), "{text}");
assert!(text.contains("тип не определён"), "{text}");
assert!(!text.contains("Шахед"), "the true kind leaked into the HUD: {text}");
}
#[test]
fn renders_damage_diagnostics() {
assert_eq!(reason(&CheckReason::Parts(vec![(Part::Sensor, 0.4), (Part::Tracks, 0.0)])), "узлы: РЛС 40%, Ход отказ");
let cases = [
(PartEffect::SensorFailed, "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети"),
(PartEffect::SensorDamaged { fit: 0.4 }, "РЛС повреждена: дальность 40%, обзор вдвое реже при худшем"),
(PartEffect::MountFailed { yaw_degrees: 42.0 }, "привод наведения заклинил: стоит на 42°, не доворачивается"),
(PartEffect::MountDamaged { fit: 0.3 }, "привод наведения повреждён: поворот 30% от нормы"),
(PartEffect::LauncherFailed, "пусковая отказала: пуски невозможны"),
(PartEffect::LauncherDamaged { cells: 2, capacity: 4, reload_seconds: 12.0 }, "пусковая повреждена: 2 ячеек из 4, перезарядка 12 с"),
(PartEffect::GunFailed, "орудие заклинило: не стреляет"),
(PartEffect::GunDamaged { fit: 0.5 }, "орудие повреждено: меткость 50%, заклинивает"),
(PartEffect::TracksFailed, "ходовая отказала: на марш не выйдет"),
(PartEffect::TracksDamaged { speed: 0.2 }, "ходовая повреждена: скорость марша 20%"),
(PartEffect::CommsFailed, "связь отказала: сети нет, цели только свои"),
(PartEffect::CommsDamaged { range: 123.0 }, "связь повреждена: линия 123 м"),
];
for (effect, expected) in cases { assert_eq!(reason(&CheckReason::PartEffect(effect)), expected); }
}
}
+34
View File
@@ -0,0 +1,34 @@
//! Player-facing world-cache report, also used by the headless scenario driver.
use airdef_core::sim::world::WorldCache;
pub fn text(world: &WorldCache) -> String {
let s = &world.stats;
format!(
"мир: {} секций ({} КБ), запросов {}, неизвестно {}, лучей {} (ударов {}, неизв. {}), клеток {}; взрывы в блоках: {} (подтверждено {}, без перемен {}, нет чанка {}), чужих ответов {}",
world.len(), world.bytes() / 1024, s.sections_asked, s.sections_unknown,
s.sweeps, s.hits, s.unknown_sweeps, s.cells, s.blasts_asked,
s.blasts_confirmed, s.blasts_unchanged, s.blasts_unloaded, s.late_dropped
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reports_cache_counts_in_existing_format() {
let mut world = WorldCache::default();
world.stats.sections_asked = 1;
world.stats.sections_unknown = 2;
world.stats.sweeps = 3;
world.stats.hits = 4;
world.stats.unknown_sweeps = 5;
world.stats.cells = 6;
world.stats.blasts_asked = 7;
world.stats.blasts_confirmed = 8;
world.stats.blasts_unchanged = 9;
world.stats.blasts_unloaded = 10;
world.stats.late_dropped = 11;
assert_eq!(text(&world), "мир: 0 секций (0 КБ), запросов 1, неизвестно 2, лучей 3 (ударов 4, неизв. 5), клеток 6; взрывы в блоках: 7 (подтверждено 8, без перемен 9, нет чанка 10), чужих ответов 11");
}
}

Some files were not shown because too many files have changed in this diff Show More