diff --git a/.gitignore b/.gitignore index 07bda0a..61bea65 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,10 @@ __pycache__/ /out/ /scratch/ +/dist/ +bin/ +obj/ +artifacts/ +build/ +.godot/ +.vs/ diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..32ef4f7 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,9 @@ + + + $(YMIR_ROOT) + $(MSBuildThisFileDirectory)..\Ymir + $(CULTLIB_ROOT) + $(MSBuildThisFileDirectory)..\CultLib + Release + + diff --git a/README.md b/README.md index e28e9d8..d500bb8 100644 --- a/README.md +++ b/README.md @@ -8,21 +8,59 @@ The lore lives in Weksa: `settings/rust-to-dust/` in [GameCult/Weksa](https://github.com/GameCult/Weksa) (setting, story, battle royale, aliens, language design). This repo holds no lore. -## What is here today +## What is live today (`nibu/rtd-prototype`) -Nothing runnable yet. This repo is the home for the mech work now being -prototyped: +- **`RustToDust.Core`**: + - Aetheria 2D grid chassis (`Dorsal` vehicles/quadrupeds and `Coronal` bipeds), + conductive/radiative heat transfer, trapezoidal thermal plateau curves, + localized armor + core destruction, and live cargo-to-hardpoint swapping. + - 6 playable chassis (`buggy`, `technical`, `tank`, `manticore`, `raptor`, + `paladin`), 8 human salvage modules, and 5 Imperial Tourist modules. + - Shrinking `SpectatorRing` perimeter (`Tourist`, `Patron`, and `Exemplar` + tiers with `Neutral` / `Cleared` / `Provoked` stances and Weksa-voiced + `BroadcastFeed` commentary). + - `TerrainField`: deterministic `1536m x 1536m` desert terrain (`8x8`, + `192m x 192m` tile grid) and a `3072m x 3072m` Sion, Switzerland alpine + arena (`1025x1025` `3m` DEM heightmap, `6x6` spatial building tiles, `2319` + buildings with RCOL collision), plus runtime crater / tire-track / + thermal-scorch stamping. +- **`RustToDust.Ymir`**: + - `ArenaSession` bridging `MatchState` onto Ymir's `Box3DSoaWorld` with + 4-corner spring-damper terrain support, Sion `StaticHeightField` + `StaticMesh` + building physics, raycast weapons, terrain crater/scorch impacts, and AI + contenders + perimeter spectators. +- **`tests/RustToDust.Tests`**: + - Behavioral xUnit suite covering Aetheria grid heat, spectator ring clearance, + Ymir vehicle driving/combat/swapping, procedural/dynamic terrain relief, and + Sion map parity + LOS. +- **`client/` (Godot 4.7.2 Mono)**: + - Dual-arena 3D client (`[M]` switcher or `RTD_MAP=sion`) supporting the + procedural desert bake and the `3072m` Sion map (LOD1/LOD2 building tiles), + Brokkr mechanical rigs rendered via `MultiMeshPartPool` + + `mech_paint.gdshader`, `PomDecalPool` combat scars, tactical radar, + clickable Aetheria Hardpoint & Heat schematic, and Imperial Broadcast chyron. + - Sion terrain and building data attribution: `"Federal Office of Topography swisstopo"`. + - Hybrid 3D combat audio (`ArenaAudioSystem` + `ProceduralAudioBank` + `WalkerFootstepTracker`): + curated weapon/mechanical WAVs by **Haven Kendrick** (`assets/audio/haven/`, + see [`assets/audio/ATTRIBUTION.md`](assets/audio/ATTRIBUTION.md)) paired with + deterministic `PcmSynth` GRF-synced footsteps, vehicle/servo loops, impacts, + and 2D UI cues behind a separable `WetMixMode` room stage. -- mechs kitbashed from parts with [Brokkr](https://eureka.gamecult.org/forge/GameCult/Brokkr) - (armour shells, ribs, cuts, joints, hoses, frames); -- a mechanical rig with one bone per degree of freedom, driven rams and linkages; -- generic walk and combat animation retargeted onto each chassis. +## Build, test, and run -That work currently lives on `nibu/fable-*` experiment branches in -GameCult/Brokkr and moves here as it settles. +Requires a sibling `Ymir` checkout beside `RustToDust` (or `YMIR_ROOT` set), +CMake, a C compiler, .NET SDK 8/10, and Godot 4.7.2 Mono (`--path client`). -## Planned, not live +```bash +# Run the behavioral test suite +dotnet test tests/RustToDust.Tests/RustToDust.Tests.csproj -c Release -- Mech parts library and chassis definitions. -- Rig generator and goal-space retargeting solver. -- A playable walk-and-fight prototype. +# Build the Godot 4.7.2 Mono client assembly (also builds Ymir native Box3D) +dotnet build client/RustToDust.Client.csproj -c Debug + +# Run the playable 3D client (press [M] in-game or set RTD_MAP=sion for Sion) +godot --path client + +# Run the headless Godot smoke test +godot --headless --path client res://tests/Smoke.tscn +``` diff --git a/RustToDust.slnx b/RustToDust.slnx new file mode 100644 index 0000000..e78085c --- /dev/null +++ b/RustToDust.slnx @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/THIRD_PARTY_NOTICES.txt b/THIRD_PARTY_NOTICES.txt new file mode 100644 index 0000000..3e7e1bb --- /dev/null +++ b/THIRD_PARTY_NOTICES.txt @@ -0,0 +1,15 @@ +THIRD-PARTY SOFTWARE NOTICES AND INFORMATION + +This product incorporates or bundles the following third-party software and +font assets under their respective licenses: + +1. Monaspace Krypton (Krypton.ttf — Monaspace Krypton Var.ttf v1.400) + Copyright (c) 2023, GitHub (https://github.com/githubnext/monaspace) + Reserved Font Names: 'Monaspace', 'Argon', 'Neon', 'Xenon', 'Radon', 'Krypton' + License: SIL Open Font License, Version 1.1 + Full license text: assets/fonts/OFL-1.1.txt + +2. HarfBuzz (15.2.0) — shaping and hb-gpu shader/curve encoder (rtd_hbgpu) + Copyright (C) HarfBuzz Authors (Behdad Esfahbod, Google Inc., Red Hat Inc., et al.) + License: HarfBuzz "Old MIT" License + Full license text: assets/fonts/HARFBUZZ-COPYING.txt diff --git a/assets/audio/ATTRIBUTION.md b/assets/audio/ATTRIBUTION.md new file mode 100644 index 0000000..743690b --- /dev/null +++ b/assets/audio/ATTRIBUTION.md @@ -0,0 +1,47 @@ +# Audio Attribution & Migration Notes + +## Curated Weapon & Mechanical Sound Effects (`assets/audio/haven/`) + +- **Author / Source:** **Haven Kendrick** (Cult member) — *MWO Soundpack* (original weapon and mechanical sound effects, used with explicit permission). +- **Modifications applied by `tools/audio/curate_haven_audio.py`:** + - Converted to mono `44,100 Hz` `16-bit` signed PCM WAV (`RIFF/WAVE`). + - Trimmed leading silence / sliced sustained loops into crisp single-shot and burst windows with smooth cosine fade-outs (`30-50 ms`). + - Peak-normalized to `0.89` (`-1.0 dBFS`). +- **Explicitly excluded:** All third-party/stock-named files in the source folder (`SW01_*`, `MW4 - *`, `Utilities-*`, `desktop.ini`) were excluded and never copied. + +### Curated Clip Manifest (25 files) + +| Destination (`assets/audio/haven/`) | Source File | Role | +|---|---|---| +| `mg_shot_01.wav` | `ClanMG3_fixed.wav` | 7.62 MG shot variant A (`0.24 s`) | +| `mg_shot_02.wav` | `New_MG 2.wav` | 7.62 MG shot variant B (`0.24 s`) | +| `mg_tail.wav` | `mgtail.wav` | MG mechanical receiver tail (`0.66 s`) | +| `ac_light_01.wav` | `AC5.wav` | Light autocannon variant A (`0.85 s`) | +| `ac_light_02.wav` | `AC5_2.wav` | Light autocannon variant B (`0.80 s`) | +| `ac_med_01.wav` | `AC10.wav` | Medium autocannon (`0.95 s`) | +| `ac_rotary.wav` | `RAC5.wav` | Rotary autocannon (`1.01 s`) | +| `flak_blast_01.wav` | `ClanLBX7_2019.wav` | Flak scattergun variant A (`1.15 s`) | +| `flak_blast_02.wav` | `IS_LBX20_2.wav` | Flak scattergun variant B (`1.35 s`) | +| `cannon_heavy_01.wav` | `BigCannon1.wav` | 105mm Recoilless / heavy cannon A (`1.80 s`) | +| `cannon_heavy_02.wav` | `AC20.wav` | 105mm Recoilless / heavy cannon B (`1.50 s`) | +| `pd_bark_01.wav` | `AMS3.wav` | Point-defense flak bark A (`0.28 s`) | +| `pd_bark_02.wav` | `amsTP.wav` | Point-defense flak bark B (`0.28 s`) | +| `pd_laser.wav` | `laserams.wav` | Imperial Aegis PD pulse (`0.32 s`) | +| `rocket_salvo_01.wav` | `MRM1.wav` | Rocket/missile salvo A (`1.20 s`) | +| `rocket_salvo_02.wav` | `NEWSRM1.wav` | Rocket/missile salvo B (`1.35 s`) | +| `plasma_ppc_01.wav` | `Snub_PPC2.wav` | Touring Plasma Repeater A (`1.25 s`) | +| `plasma_ppc_02.wav` | `PPcSWEET.wav` | Touring Plasma Repeater B (`0.78 s`) | +| `lance_beam_01.wav` | `CPPC_DEC2018_2.wav` | Gilded Thermal Lance (`1.55 s`) | +| `laser_heavy_01.wav` | `CLL3.wav` | Heavy laser (reserved for Cut 7) (`1.20 s`) | +| `gauss_rail_01.wav` | `Gauss Sweet 1.wav` | Gauss rifle (reserved for Cut 7) (`1.15 s`) | +| `mech_reload_bolt.wav` | `CannonReload2.wav` | Heavy chassis swap bolt-clank (`1.25 s`) | +| `mech_quick_bolt.wav` | `reload.wav` | Module equip latch (`0.94 s`) | +| `mech_eject.wav` | `eject.wav` | Ruin / casing ejection clatter (`0.74 s`) | +| `mech_turret_servo.wav` | `turret9.wav` | Turret traverse mechanical accent (`1.10 s`) | + +## Procedural Synth & `WetMixMode` Dry-Mode Migration Plan + +`RustToDust.Core.Audio.PcmSynth` synthesizes all non-weapon audio cues (GRF-synced mech footsteps, engine/rotor/servo loops, metallic ricochets, armor/core impacts, explosions, and 2D UI feedback) as **pure dry mono 44.1 kHz PCM buffers first**, then passes them through a cleanly separable `WetMixMode` post-stage: + +- **`WetMixMode = true` (current default):** Applies early reflections (`11-43 ms` taps), a short diffused room tail, and gentle `tanh` soft-clipping so procedural footsteps, impacts, and loops sit cohesively alongside Haven's pre-reverbed weapon recordings. +- **`WetMixMode = false` (future acoustic raycast DSP):** Bypasses the baked room stage and returns the dry PCM buffers untouched so an audio raytracer / convolution reverb bus can compute per-ray canyon and city-corridor reflections dynamically without double-reverberating procedural sources. diff --git a/assets/audio/haven/ac_light_01.wav b/assets/audio/haven/ac_light_01.wav new file mode 100644 index 0000000..624741d Binary files /dev/null and b/assets/audio/haven/ac_light_01.wav differ diff --git a/assets/audio/haven/ac_light_02.wav b/assets/audio/haven/ac_light_02.wav new file mode 100644 index 0000000..cd97a3d Binary files /dev/null and b/assets/audio/haven/ac_light_02.wav differ diff --git a/assets/audio/haven/ac_med_01.wav b/assets/audio/haven/ac_med_01.wav new file mode 100644 index 0000000..acad76f Binary files /dev/null and b/assets/audio/haven/ac_med_01.wav differ diff --git a/assets/audio/haven/ac_rotary.wav b/assets/audio/haven/ac_rotary.wav new file mode 100644 index 0000000..2aa4e24 Binary files /dev/null and b/assets/audio/haven/ac_rotary.wav differ diff --git a/assets/audio/haven/cannon_heavy_01.wav b/assets/audio/haven/cannon_heavy_01.wav new file mode 100644 index 0000000..cfed3ab Binary files /dev/null and b/assets/audio/haven/cannon_heavy_01.wav differ diff --git a/assets/audio/haven/cannon_heavy_02.wav b/assets/audio/haven/cannon_heavy_02.wav new file mode 100644 index 0000000..6c6c037 Binary files /dev/null and b/assets/audio/haven/cannon_heavy_02.wav differ diff --git a/assets/audio/haven/flak_blast_01.wav b/assets/audio/haven/flak_blast_01.wav new file mode 100644 index 0000000..73e2d3c Binary files /dev/null and b/assets/audio/haven/flak_blast_01.wav differ diff --git a/assets/audio/haven/flak_blast_02.wav b/assets/audio/haven/flak_blast_02.wav new file mode 100644 index 0000000..d13fefa Binary files /dev/null and b/assets/audio/haven/flak_blast_02.wav differ diff --git a/assets/audio/haven/gauss_rail_01.wav b/assets/audio/haven/gauss_rail_01.wav new file mode 100644 index 0000000..8d96ebb Binary files /dev/null and b/assets/audio/haven/gauss_rail_01.wav differ diff --git a/assets/audio/haven/lance_beam_01.wav b/assets/audio/haven/lance_beam_01.wav new file mode 100644 index 0000000..8f0c1cf Binary files /dev/null and b/assets/audio/haven/lance_beam_01.wav differ diff --git a/assets/audio/haven/laser_heavy_01.wav b/assets/audio/haven/laser_heavy_01.wav new file mode 100644 index 0000000..a9f5b0b Binary files /dev/null and b/assets/audio/haven/laser_heavy_01.wav differ diff --git a/assets/audio/haven/mech_eject.wav b/assets/audio/haven/mech_eject.wav new file mode 100644 index 0000000..95dd814 Binary files /dev/null and b/assets/audio/haven/mech_eject.wav differ diff --git a/assets/audio/haven/mech_quick_bolt.wav b/assets/audio/haven/mech_quick_bolt.wav new file mode 100644 index 0000000..a378c62 Binary files /dev/null and b/assets/audio/haven/mech_quick_bolt.wav differ diff --git a/assets/audio/haven/mech_reload_bolt.wav b/assets/audio/haven/mech_reload_bolt.wav new file mode 100644 index 0000000..3a7f1a0 Binary files /dev/null and b/assets/audio/haven/mech_reload_bolt.wav differ diff --git a/assets/audio/haven/mech_turret_servo.wav b/assets/audio/haven/mech_turret_servo.wav new file mode 100644 index 0000000..41e8598 Binary files /dev/null and b/assets/audio/haven/mech_turret_servo.wav differ diff --git a/assets/audio/haven/mg_shot_01.wav b/assets/audio/haven/mg_shot_01.wav new file mode 100644 index 0000000..433fe7b Binary files /dev/null and b/assets/audio/haven/mg_shot_01.wav differ diff --git a/assets/audio/haven/mg_shot_02.wav b/assets/audio/haven/mg_shot_02.wav new file mode 100644 index 0000000..73f02f3 Binary files /dev/null and b/assets/audio/haven/mg_shot_02.wav differ diff --git a/assets/audio/haven/mg_tail.wav b/assets/audio/haven/mg_tail.wav new file mode 100644 index 0000000..466e743 Binary files /dev/null and b/assets/audio/haven/mg_tail.wav differ diff --git a/assets/audio/haven/pd_bark_01.wav b/assets/audio/haven/pd_bark_01.wav new file mode 100644 index 0000000..2ab8bff Binary files /dev/null and b/assets/audio/haven/pd_bark_01.wav differ diff --git a/assets/audio/haven/pd_bark_02.wav b/assets/audio/haven/pd_bark_02.wav new file mode 100644 index 0000000..6f3b7ff Binary files /dev/null and b/assets/audio/haven/pd_bark_02.wav differ diff --git a/assets/audio/haven/pd_laser.wav b/assets/audio/haven/pd_laser.wav new file mode 100644 index 0000000..cabd5d0 Binary files /dev/null and b/assets/audio/haven/pd_laser.wav differ diff --git a/assets/audio/haven/plasma_ppc_01.wav b/assets/audio/haven/plasma_ppc_01.wav new file mode 100644 index 0000000..6cafe19 Binary files /dev/null and b/assets/audio/haven/plasma_ppc_01.wav differ diff --git a/assets/audio/haven/plasma_ppc_02.wav b/assets/audio/haven/plasma_ppc_02.wav new file mode 100644 index 0000000..61e366e Binary files /dev/null and b/assets/audio/haven/plasma_ppc_02.wav differ diff --git a/assets/audio/haven/rocket_salvo_01.wav b/assets/audio/haven/rocket_salvo_01.wav new file mode 100644 index 0000000..c31620c Binary files /dev/null and b/assets/audio/haven/rocket_salvo_01.wav differ diff --git a/assets/audio/haven/rocket_salvo_02.wav b/assets/audio/haven/rocket_salvo_02.wav new file mode 100644 index 0000000..35265b0 Binary files /dev/null and b/assets/audio/haven/rocket_salvo_02.wav differ diff --git a/assets/decals/decal_atlas_albedo.png b/assets/decals/decal_atlas_albedo.png new file mode 100644 index 0000000..c87f3e1 Binary files /dev/null and b/assets/decals/decal_atlas_albedo.png differ diff --git a/assets/decals/decal_atlas_normal.png b/assets/decals/decal_atlas_normal.png new file mode 100644 index 0000000..6155e10 Binary files /dev/null and b/assets/decals/decal_atlas_normal.png differ diff --git a/assets/decals/decal_atlas_ormh.png b/assets/decals/decal_atlas_ormh.png new file mode 100644 index 0000000..89b9590 Binary files /dev/null and b/assets/decals/decal_atlas_ormh.png differ diff --git a/assets/fonts/HARFBUZZ-COPYING.txt b/assets/fonts/HARFBUZZ-COPYING.txt new file mode 100644 index 0000000..1dd917e --- /dev/null +++ b/assets/fonts/HARFBUZZ-COPYING.txt @@ -0,0 +1,42 @@ +HarfBuzz is licensed under the so-called "Old MIT" license. Details follow. +For parts of HarfBuzz that are licensed under different licenses see individual +files names COPYING in subdirectories where applicable. + +Copyright © 2010-2022 Google, Inc. +Copyright © 2015-2020 Ebrahim Byagowi +Copyright © 2019,2020 Facebook, Inc. +Copyright © 2012,2015 Mozilla Foundation +Copyright © 2011 Codethink Limited +Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies) +Copyright © 2009 Keith Stribley +Copyright © 2011 Martin Hosken and SIL International +Copyright © 2007 Chris Wilson +Copyright © 2005,2006,2020,2021,2022,2023 Behdad Esfahbod +Copyright © 2004,2007,2008,2009,2010,2013,2021,2022,2023 Red Hat, Inc. +Copyright © 1998-2005 David Turner and Werner Lemberg +Copyright © 2016 Igalia S.L. +Copyright © 2022 Matthias Clasen +Copyright © 2018,2021 Khaled Hosny +Copyright © 2018,2019,2020 Adobe, Inc +Copyright © 2013-2015 Alexei Podtelezhnikov + +For full copyright notices consult the individual files in the package. + + +Permission is hereby granted, without written agreement and without +license or royalty fees, to use, copy, modify, and distribute this +software and its documentation for any purpose, provided that the +above copyright notice and the following two paragraphs appear in +all copies of this software. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR +DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN +IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. + +THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, +BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS +ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO +PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. diff --git a/assets/fonts/Krypton.ttf b/assets/fonts/Krypton.ttf new file mode 100644 index 0000000..821c61e Binary files /dev/null and b/assets/fonts/Krypton.ttf differ diff --git a/assets/fonts/OFL-1.1.txt b/assets/fonts/OFL-1.1.txt new file mode 100644 index 0000000..0ad8d06 --- /dev/null +++ b/assets/fonts/OFL-1.1.txt @@ -0,0 +1,94 @@ +Copyright (c) 2023, GitHub (https://github.com/githubnext/monaspace) +with Reserved Font Names 'Monaspace', 'Argon', 'Neon', 'Xenon', 'Radon', 'Krypton'. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSIONS & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to remain +under this license does not apply to any document created using the fonts +or their derivatives. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/gear/autocannon.glb b/assets/gear/autocannon.glb new file mode 100644 index 0000000..fa2c413 Binary files /dev/null and b/assets/gear/autocannon.glb differ diff --git a/assets/gear/copper_rad.glb b/assets/gear/copper_rad.glb new file mode 100644 index 0000000..e1c2692 Binary files /dev/null and b/assets/gear/copper_rad.glb differ diff --git a/assets/gear/gilded_lance.glb b/assets/gear/gilded_lance.glb new file mode 100644 index 0000000..1e0878b Binary files /dev/null and b/assets/gear/gilded_lance.glb differ diff --git a/assets/gear/gold_radiator.glb b/assets/gear/gold_radiator.glb new file mode 100644 index 0000000..b0952c8 Binary files /dev/null and b/assets/gear/gold_radiator.glb differ diff --git a/assets/gear/mg_762.glb b/assets/gear/mg_762.glb new file mode 100644 index 0000000..8c6658a Binary files /dev/null and b/assets/gear/mg_762.glb differ diff --git a/assets/gear/parts/brl_autocannon.glb b/assets/gear/parts/brl_autocannon.glb new file mode 100644 index 0000000..c039e8c Binary files /dev/null and b/assets/gear/parts/brl_autocannon.glb differ diff --git a/assets/gear/parts/brl_missile_tube.glb b/assets/gear/parts/brl_missile_tube.glb new file mode 100644 index 0000000..c81acba Binary files /dev/null and b/assets/gear/parts/brl_missile_tube.glb differ diff --git a/assets/gear/parts/brl_prism_lance.glb b/assets/gear/parts/brl_prism_lance.glb new file mode 100644 index 0000000..2a1a26f Binary files /dev/null and b/assets/gear/parts/brl_prism_lance.glb differ diff --git a/assets/gear/parts/brl_sabot_rail.glb b/assets/gear/parts/brl_sabot_rail.glb new file mode 100644 index 0000000..a36f051 Binary files /dev/null and b/assets/gear/parts/brl_sabot_rail.glb differ diff --git a/assets/gear/parts/fd_belt_drum.glb b/assets/gear/parts/fd_belt_drum.glb new file mode 100644 index 0000000..56e62f4 Binary files /dev/null and b/assets/gear/parts/fd_belt_drum.glb differ diff --git a/assets/gear/parts/fd_capacitor_bank.glb b/assets/gear/parts/fd_capacitor_bank.glb new file mode 100644 index 0000000..16f5a83 Binary files /dev/null and b/assets/gear/parts/fd_capacitor_bank.glb differ diff --git a/assets/gear/parts/fd_rotary_loader.glb b/assets/gear/parts/fd_rotary_loader.glb new file mode 100644 index 0000000..9b546fb Binary files /dev/null and b/assets/gear/parts/fd_rotary_loader.glb differ diff --git a/assets/gear/parts/fd_swarm_magazine.glb b/assets/gear/parts/fd_swarm_magazine.glb new file mode 100644 index 0000000..8f7c9f0 Binary files /dev/null and b/assets/gear/parts/fd_swarm_magazine.glb differ diff --git a/assets/gear/parts/mz_loiter_aero_fin.glb b/assets/gear/parts/mz_loiter_aero_fin.glb new file mode 100644 index 0000000..c8a6e0a Binary files /dev/null and b/assets/gear/parts/mz_loiter_aero_fin.glb differ diff --git a/assets/gear/parts/mz_mirv_warhead.glb b/assets/gear/parts/mz_mirv_warhead.glb new file mode 100644 index 0000000..8e93770 Binary files /dev/null and b/assets/gear/parts/mz_mirv_warhead.glb differ diff --git a/assets/gear/parts/mz_plasma_diffuser.glb b/assets/gear/parts/mz_plasma_diffuser.glb new file mode 100644 index 0000000..8097955 Binary files /dev/null and b/assets/gear/parts/mz_plasma_diffuser.glb differ diff --git a/assets/gear/parts/mz_slotted_brake.glb b/assets/gear/parts/mz_slotted_brake.glb new file mode 100644 index 0000000..cfaaf0e Binary files /dev/null and b/assets/gear/parts/mz_slotted_brake.glb differ diff --git a/assets/gear/parts/rx_auralian_prism.glb b/assets/gear/parts/rx_auralian_prism.glb new file mode 100644 index 0000000..074596a Binary files /dev/null and b/assets/gear/parts/rx_auralian_prism.glb differ diff --git a/assets/gear/parts/rx_korrathi_cradle.glb b/assets/gear/parts/rx_korrathi_cradle.glb new file mode 100644 index 0000000..1f1e32a Binary files /dev/null and b/assets/gear/parts/rx_korrathi_cradle.glb differ diff --git a/assets/gear/parts/rx_salvage_frame.glb b/assets/gear/parts/rx_salvage_frame.glb new file mode 100644 index 0000000..929671d Binary files /dev/null and b/assets/gear/parts/rx_salvage_frame.glb differ diff --git a/assets/gear/parts/rx_vex_pod_rack.glb b/assets/gear/parts/rx_vex_pod_rack.glb new file mode 100644 index 0000000..18d37f7 Binary files /dev/null and b/assets/gear/parts/rx_vex_pod_rack.glb differ diff --git a/assets/gear/recoilless.glb b/assets/gear/recoilless.glb new file mode 100644 index 0000000..815f0cc Binary files /dev/null and b/assets/gear/recoilless.glb differ diff --git a/assets/maps/sion/buildings_manifest.json b/assets/maps/sion/buildings_manifest.json new file mode 100644 index 0000000..60c9aa8 --- /dev/null +++ b/assets/maps/sion/buildings_manifest.json @@ -0,0 +1,58000 @@ +{ + "map": "sion", + "coordinateSystem": "rusttodust_arena_gltf", + "attribution": "Federal Office of Topography swisstopo", + "sizeMeters": 3072.0, + "tileGrid": 6, + "tileSizeMeters": 512.0, + "count": 2319, + "classes": { + "Gebaeude Einzelhaus": 2130, + "Offenes Gebaeude": 97, + "Mauer gross": 20, + "Hochhaus": 16, + "Im Bau": 16, + "Flugdach": 11, + "Lagertank": 10, + "Sakrales Gebaeude": 9, + "Unterirdisches Gebaeude": 5, + "Kapelle": 3, + "Sakraler Turm": 1, + "Treibhaus": 1 + }, + "buildings": [ + { + "id": "sion_0001", + "uuid": "{79F45852-C942-421B-A1B3-D405D5B0CDE1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -524.666, + 6.506, + 437.863 + ], + "size": [ + 13.777, + 10.79, + 14.366 + ], + "groundY": 1.111, + "roofY": 11.901, + "wallCount": 47, + "roofCount": 28 + }, + { + "id": "sion_0002", + "uuid": "{3EFA5FA4-45A5-45AD-B0D2-A39D96A7DA38}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -457.059, + 8.705, + 519.852 + ], + "size": [ + 93.32, + 14.962, + 67.95 + ], + "groundY": 1.224, + "roofY": 16.186, + "wallCount": 22, + "roofCount": 10 + }, + { + "id": "sion_0003", + "uuid": "{EC186A34-2806-4681-A9D5-5FBBA14F44DB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1109.613, + 7.856, + 218.27 + ], + "size": [ + 40.023, + 17.418, + 29.939 + ], + "groundY": -0.853, + "roofY": 16.565, + "wallCount": 26, + "roofCount": 21 + }, + { + "id": "sion_0004", + "uuid": "{408BED01-170F-4E9C-8EED-82ED4A0FFEAE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -923.979, + 296.84, + -1499.304 + ], + "size": [ + 23.809, + 10.9, + 24.068 + ], + "groundY": 291.39, + "roofY": 302.29, + "wallCount": 40, + "roofCount": 27 + }, + { + "id": "sion_0005", + "uuid": "{394508E5-94D3-4AFC-A089-97F3CC4044D5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1477.338, + 68.344, + 217.291 + ], + "size": [ + 16.754, + 9.928, + 29.723 + ], + "groundY": 63.38, + "roofY": 73.308, + "wallCount": 35, + "roofCount": 26 + }, + { + "id": "sion_0006", + "uuid": "{E3FBDDB8-8CA0-49A8-921A-9275DB751A89}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -966.238, + 60.771, + -180.966 + ], + "size": [ + 25.258, + 8.93, + 17.773 + ], + "groundY": 56.306, + "roofY": 65.236, + "wallCount": 30, + "roofCount": 4 + }, + { + "id": "sion_0007", + "uuid": "{E1B3FD18-71A1-4E67-B878-CF7470FFDB0C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1124.541, + 295.651, + -1491.381 + ], + "size": [ + 32.621, + 11.649, + 22.03 + ], + "groundY": 289.827, + "roofY": 301.476, + "wallCount": 37, + "roofCount": 27 + }, + { + "id": "sion_0008", + "uuid": "{0146E432-2468-462D-AADE-398086942AA4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -484.807, + 69.202, + -660.992 + ], + "size": [ + 23.809, + 17.385, + 21.256 + ], + "groundY": 60.51, + "roofY": 77.894, + "wallCount": 61, + "roofCount": 51 + }, + { + "id": "sion_0009", + "uuid": "{DE6A9087-266C-493B-93CB-FEA78391F108}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1242.514, + 139.005, + -375.101 + ], + "size": [ + 35.871, + 6.31, + 21.136 + ], + "groundY": 135.85, + "roofY": 142.16, + "wallCount": 32, + "roofCount": 12 + }, + { + "id": "sion_0010", + "uuid": "{7E4E14E0-9272-4EAC-91CB-7CC848B0A14A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1068.332, + 4.948, + 971.333 + ], + "size": [ + 50.531, + 14.715, + 45.557 + ], + "groundY": -2.409, + "roofY": 12.306, + "wallCount": 26, + "roofCount": 4 + }, + { + "id": "sion_0011", + "uuid": "{F9F270AB-E7EF-4438-AA6A-C561F1D74DCF}", + "name": "", + "class": "Sakraler Turm", + "archStyle": "fortress", + "tile": [ + 0, + 3 + ], + "center": [ + -1031.971, + 19.307, + 148.086 + ], + "size": [ + 3.332, + 28.989, + 3.001 + ], + "groundY": 4.813, + "roofY": 33.802, + "wallCount": 79, + "roofCount": 4 + }, + { + "id": "sion_0012", + "uuid": "{4731FA14-D712-4922-8327-00ADEC5571CB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -679.033, + 289.003, + -1288.825 + ], + "size": [ + 8.793, + 7.376, + 8.918 + ], + "groundY": 285.315, + "roofY": 292.691, + "wallCount": 45, + "roofCount": 22 + }, + { + "id": "sion_0013", + "uuid": "{37E34BE9-2012-4DD6-B422-07286AFEA1F8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -474.451, + 61.444, + -630.771 + ], + "size": [ + 23.387, + 17.251, + 23.116 + ], + "groundY": 52.818, + "roofY": 70.069, + "wallCount": 56, + "roofCount": 48 + }, + { + "id": "sion_0014", + "uuid": "{FA4B7596-EC19-4672-BB5A-5CA8F8B03D38}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1190.365, + 2.896, + 949.048 + ], + "size": [ + 16.246, + 8.466, + 17.482 + ], + "groundY": -1.337, + "roofY": 7.129, + "wallCount": 51, + "roofCount": 39 + }, + { + "id": "sion_0015", + "uuid": "{E774F9F6-77B1-448A-A96A-BFBE915B8337}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -641.98, + 9.369, + 307.867 + ], + "size": [ + 32.086, + 19.268, + 30.298 + ], + "groundY": -0.265, + "roofY": 19.003, + "wallCount": 80, + "roofCount": 28 + }, + { + "id": "sion_0016", + "uuid": "{6EA77527-40D6-4761-A01E-7A7375025B42}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -453.188, + 49.946, + -445.818 + ], + "size": [ + 13.664, + 17.138, + 14.896 + ], + "groundY": 41.377, + "roofY": 58.515, + "wallCount": 26, + "roofCount": 16 + }, + { + "id": "sion_0017", + "uuid": "{53D9B141-EDF2-448B-B9BA-BF5A4DF9420E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -603.855, + 5.729, + 477.823 + ], + "size": [ + 17.086, + 13.942, + 14.598 + ], + "groundY": -1.242, + "roofY": 12.7, + "wallCount": 46, + "roofCount": 30 + }, + { + "id": "sion_0018", + "uuid": "{E0C6227E-9165-4EEA-A88F-FC7A05A30ADC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1308.787, + 266.872, + -1017.527 + ], + "size": [ + 30.223, + 13.317, + 16.436 + ], + "groundY": 260.213, + "roofY": 273.53, + "wallCount": 68, + "roofCount": 47 + }, + { + "id": "sion_0019", + "uuid": "{D2D74AED-123B-4F52-A33A-8F63D36263C6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -455.928, + 26.572, + 131.565 + ], + "size": [ + 101.684, + 26.772, + 106.276 + ], + "groundY": 13.186, + "roofY": 39.958, + "wallCount": 188, + "roofCount": 161 + }, + { + "id": "sion_0020", + "uuid": "{45FCACD2-D722-47B8-89A6-291F87FD0A96}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1199.768, + 258.764, + -904.268 + ], + "size": [ + 20.715, + 9.896, + 16.591 + ], + "groundY": 253.816, + "roofY": 263.712, + "wallCount": 25, + "roofCount": 21 + }, + { + "id": "sion_0021", + "uuid": "{D294A36C-FFF7-4EF0-9092-3F80186F573D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1485.439, + 2.246, + 444.141 + ], + "size": [ + 15.668, + 12.346, + 14.578 + ], + "groundY": -3.927, + "roofY": 8.419, + "wallCount": 42, + "roofCount": 18 + }, + { + "id": "sion_0022", + "uuid": "{2B94E666-8859-4B5F-B1FC-1B70484B94C0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -578.092, + 25.177, + 100.289 + ], + "size": [ + 81.387, + 20.158, + 76.166 + ], + "groundY": 15.098, + "roofY": 35.256, + "wallCount": 106, + "roofCount": 267 + }, + { + "id": "sion_0023", + "uuid": "{0ADA0856-4594-48A6-AA32-DD54895E0A90}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -898.365, + 1.503, + 227.22 + ], + "size": [ + 25.184, + 5.181, + 11.442 + ], + "groundY": -1.087, + "roofY": 4.094, + "wallCount": 17, + "roofCount": 2 + }, + { + "id": "sion_0024", + "uuid": "{DECFA4B9-B824-4B74-A328-6F6AE531E50F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1409.111, + 45.973, + 203.296 + ], + "size": [ + 15.309, + 11.855, + 17.09 + ], + "groundY": 40.046, + "roofY": 51.901, + "wallCount": 50, + "roofCount": 16 + }, + { + "id": "sion_0025", + "uuid": "{E4CCB247-E8E0-4F06-80BB-A91C77090A84}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1519.365, + 156.976, + -255.953 + ], + "size": [ + 16.559, + 11.815, + 14.048 + ], + "groundY": 151.068, + "roofY": 162.883, + "wallCount": 42, + "roofCount": 28 + }, + { + "id": "sion_0026", + "uuid": "{E59EA16A-8B7E-4403-9342-4AE4F2359916}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -576.154, + 34.944, + -166.307 + ], + "size": [ + 31.699, + 14.814, + 42.426 + ], + "groundY": 27.537, + "roofY": 42.351, + "wallCount": 15, + "roofCount": 13 + }, + { + "id": "sion_0027", + "uuid": "{0EF178DA-22B3-485D-9EFB-DA355878B950}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -684.803, + 9.244, + 505.394 + ], + "size": [ + 63.379, + 21.388, + 63.464 + ], + "groundY": -1.45, + "roofY": 19.938, + "wallCount": 13, + "roofCount": 2 + }, + { + "id": "sion_0028", + "uuid": "{C87A41B1-30A7-4B7E-8326-0DBE04626F41}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1379.045, + 229.635, + -752.242 + ], + "size": [ + 18.231, + 9.304, + 29.53 + ], + "groundY": 224.983, + "roofY": 234.287, + "wallCount": 40, + "roofCount": 19 + }, + { + "id": "sion_0029", + "uuid": "{3D3CB7D3-CC3A-4DA1-9C7E-726501AB4A0D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -610.885, + 7.598, + 418.724 + ], + "size": [ + 14.191, + 17.606, + 14.487 + ], + "groundY": -1.205, + "roofY": 16.401, + "wallCount": 43, + "roofCount": 39 + }, + { + "id": "sion_0030", + "uuid": "{812F1498-94C2-4B33-A455-C0488908572B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -796.648, + 2.699, + 323.945 + ], + "size": [ + 13.945, + 10.91, + 10.628 + ], + "groundY": -2.756, + "roofY": 8.154, + "wallCount": 52, + "roofCount": 28 + }, + { + "id": "sion_0031", + "uuid": "{9827BA01-93BC-4E8D-AC03-4EE54A4C23AB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1188.545, + 285.858, + -1155.693 + ], + "size": [ + 16.777, + 9.526, + 15.95 + ], + "groundY": 281.095, + "roofY": 290.621, + "wallCount": 34, + "roofCount": 13 + }, + { + "id": "sion_0032", + "uuid": "{C79144DD-2E1E-48CF-8B90-118429BCD0B2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -543.121, + 5.98, + 443.248 + ], + "size": [ + 18.992, + 11.178, + 12.102 + ], + "groundY": 0.391, + "roofY": 11.569, + "wallCount": 42, + "roofCount": 16 + }, + { + "id": "sion_0033", + "uuid": "{C725B337-6507-451F-9937-9D05BBFD9E27}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1273.648, + 283.345, + -1109.476 + ], + "size": [ + 12.25, + 12.694, + 13.097 + ], + "groundY": 276.998, + "roofY": 289.692, + "wallCount": 54, + "roofCount": 32 + }, + { + "id": "sion_0034", + "uuid": "{20223371-13B6-4F57-ACAB-285D39F0EF30}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -523.988, + 23.12, + 231.818 + ], + "size": [ + 48.883, + 24.086, + 17.966 + ], + "groundY": 11.077, + "roofY": 35.163, + "wallCount": 41, + "roofCount": 12 + }, + { + "id": "sion_0035", + "uuid": "{0B60AF08-E4FF-4C02-A21F-980C2CD8F35F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1467.432, + 2.226, + 438.609 + ], + "size": [ + 16.293, + 12.328, + 15.097 + ], + "groundY": -3.938, + "roofY": 8.39, + "wallCount": 32, + "roofCount": 16 + }, + { + "id": "sion_0036", + "uuid": "{D4EA8196-9D08-4CC7-94A1-ABC95C941947}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -519.014, + 32.036, + -126.816 + ], + "size": [ + 27.598, + 12.81, + 18.698 + ], + "groundY": 25.631, + "roofY": 38.441, + "wallCount": 57, + "roofCount": 43 + }, + { + "id": "sion_0037", + "uuid": "{0CEE934A-254D-410B-86D7-9807886A6E02}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -986.043, + 296.881, + -1423.985 + ], + "size": [ + 19.023, + 10.693, + 30.439 + ], + "groundY": 291.534, + "roofY": 302.227, + "wallCount": 44, + "roofCount": 31 + }, + { + "id": "sion_0038", + "uuid": "{15DEA2A0-A914-4ED9-8106-B36C75409C7C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1135.674, + 0.454, + 670.742 + ], + "size": [ + 37.309, + 6.926, + 18.88 + ], + "groundY": -3.009, + "roofY": 3.917, + "wallCount": 14, + "roofCount": 2 + }, + { + "id": "sion_0039", + "uuid": "{4E3B4C74-8E6E-4939-8174-B0E5B8980AAA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1431.801, + 60.256, + 183.343 + ], + "size": [ + 16.641, + 13.266, + 15.386 + ], + "groundY": 53.623, + "roofY": 66.889, + "wallCount": 31, + "roofCount": 14 + }, + { + "id": "sion_0040", + "uuid": "{885FE677-400B-4922-9164-1BB4EE5B18E9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -523.935, + 18.606, + 300.091 + ], + "size": [ + 34.066, + 24.166, + 13.39 + ], + "groundY": 6.523, + "roofY": 30.689, + "wallCount": 27, + "roofCount": 17 + }, + { + "id": "sion_0041", + "uuid": "{7285FB75-6D5C-4E0A-BBAA-D441FF56B917}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1309.873, + 257.017, + -936.624 + ], + "size": [ + 39.559, + 11.524, + 17.7 + ], + "groundY": 251.255, + "roofY": 262.779, + "wallCount": 41, + "roofCount": 17 + }, + { + "id": "sion_0042", + "uuid": "{7AE0698D-CA33-4292-AD5E-1C06AC194EB0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -1013.959, + 295.691, + -1406.516 + ], + "size": [ + 12.769, + 10.844, + 24.624 + ], + "groundY": 290.269, + "roofY": 301.113, + "wallCount": 45, + "roofCount": 20 + }, + { + "id": "sion_0043", + "uuid": "{A0E7EAAD-7F59-4D27-9FB9-28341A189869}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -585.92, + 43.273, + -370.373 + ], + "size": [ + 19.231, + 12.862, + 19.42 + ], + "groundY": 36.842, + "roofY": 49.704, + "wallCount": 13, + "roofCount": 7 + }, + { + "id": "sion_0044", + "uuid": "{E8E79685-7A2C-42F4-A935-F45C9879A4FA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -747.228, + 67.536, + -349.246 + ], + "size": [ + 16.949, + 13.419, + 16.145 + ], + "groundY": 60.827, + "roofY": 74.246, + "wallCount": 39, + "roofCount": 17 + }, + { + "id": "sion_0045", + "uuid": "{6A489AC5-7A88-4C2A-A5EC-5F96A03E4BA5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1527.066, + 135.184, + -162.883 + ], + "size": [ + 6.461, + 10.134, + 6.448 + ], + "groundY": 130.117, + "roofY": 140.251, + "wallCount": 54, + "roofCount": 6 + }, + { + "id": "sion_0046", + "uuid": "{3A1E1E27-E17A-44DF-88CF-7331C4F1FA01}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -1008.449, + 121.29, + -479.446 + ], + "size": [ + 26.562, + 9.411, + 25.986 + ], + "groundY": 116.585, + "roofY": 125.996, + "wallCount": 52, + "roofCount": 26 + }, + { + "id": "sion_0047", + "uuid": "{72E49FCA-D387-4818-BE4B-395FB3D339EC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1441.719, + 73.595, + 16.736 + ], + "size": [ + 19.367, + 12.214, + 16.517 + ], + "groundY": 67.488, + "roofY": 79.702, + "wallCount": 45, + "roofCount": 20 + }, + { + "id": "sion_0048", + "uuid": "{49E60980-40E8-41EF-A0F8-0EE720AFB7CD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -589.648, + 28.184, + 29.223 + ], + "size": [ + 30.422, + 24.68, + 28.27 + ], + "groundY": 15.844, + "roofY": 40.524, + "wallCount": 170, + "roofCount": 35 + }, + { + "id": "sion_0049", + "uuid": "{34C72E0E-FF9B-4E44-A2DD-D7CB377F781D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1261.338, + 19.189, + 160.826 + ], + "size": [ + 36.965, + 24.222, + 42.952 + ], + "groundY": 7.078, + "roofY": 31.3, + "wallCount": 48, + "roofCount": 10 + }, + { + "id": "sion_0050", + "uuid": "{52CB2116-49F6-412D-83D2-ABFCF0702920}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -808.541, + 5.629, + 617.891 + ], + "size": [ + 23.324, + 14.06, + 18.026 + ], + "groundY": -1.401, + "roofY": 12.659, + "wallCount": 26, + "roofCount": 22 + }, + { + "id": "sion_0051", + "uuid": "{1CBB3629-D2B8-41C6-940D-98BA0BFB4A96}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -872.453, + 21.089, + 39.361 + ], + "size": [ + 21.727, + 19.478, + 21.06 + ], + "groundY": 11.35, + "roofY": 30.828, + "wallCount": 67, + "roofCount": 87 + }, + { + "id": "sion_0052", + "uuid": "{9C9A7B51-66F3-46AC-BB44-71CBEFA65FAA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -554.012, + 2.098, + 722.342 + ], + "size": [ + 7.234, + 5.398, + 10.224 + ], + "groundY": -0.601, + "roofY": 4.797, + "wallCount": 19, + "roofCount": 10 + }, + { + "id": "sion_0053", + "uuid": "{FB034529-08ED-4AED-9CB2-5AA7E25526ED}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1459.396, + 274.479, + -1011.477 + ], + "size": [ + 16.106, + 10.946, + 13.323 + ], + "groundY": 269.006, + "roofY": 279.952, + "wallCount": 61, + "roofCount": 33 + }, + { + "id": "sion_0054", + "uuid": "{AB97D0AD-3F35-4FC0-A2E2-8EA315DB21E2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -460.549, + 47.321, + -361.222 + ], + "size": [ + 30.629, + 21.44, + 24.813 + ], + "groundY": 36.601, + "roofY": 58.041, + "wallCount": 39, + "roofCount": 52 + }, + { + "id": "sion_0055", + "uuid": "{C1C60920-7BE6-4373-BC14-62ECFB945E93}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -899.912, + 74.121, + -244.46 + ], + "size": [ + 28.285, + 17.174, + 23.078 + ], + "groundY": 65.534, + "roofY": 82.708, + "wallCount": 92, + "roofCount": 50 + }, + { + "id": "sion_0056", + "uuid": "{8D2E6C08-D30E-4B55-9093-D5C61CD57E65}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1397.0, + 235.853, + -832.885 + ], + "size": [ + 21.328, + 10.12, + 18.746 + ], + "groundY": 230.793, + "roofY": 240.913, + "wallCount": 29, + "roofCount": 6 + }, + { + "id": "sion_0057", + "uuid": "{50F5B1B9-5B5C-4CB7-ADD0-6449F8E259E4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1330.754, + 34.375, + 177.693 + ], + "size": [ + 16.828, + 12.889, + 15.396 + ], + "groundY": 27.93, + "roofY": 40.819, + "wallCount": 46, + "roofCount": 28 + }, + { + "id": "sion_0058", + "uuid": "{2F5D2737-402D-49B9-BECB-EDC8F1B36B40}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1319.154, + 73.88, + -82.307 + ], + "size": [ + 14.199, + 5.525, + 14.067 + ], + "groundY": 71.118, + "roofY": 76.643, + "wallCount": 24, + "roofCount": 4 + }, + { + "id": "sion_0059", + "uuid": "{FD97BC4E-A885-4072-9BA5-2BFC592DCBC8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -1015.652, + 9.222, + 205.154 + ], + "size": [ + 40.68, + 20.717, + 25.822 + ], + "groundY": -1.136, + "roofY": 19.58, + "wallCount": 33, + "roofCount": 50 + }, + { + "id": "sion_0060", + "uuid": "{A8DE9354-E8DE-4B83-A35B-D6D7F921DA54}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1499.428, + 223.597, + -752.33 + ], + "size": [ + 10.691, + 10.362, + 15.348 + ], + "groundY": 218.416, + "roofY": 228.778, + "wallCount": 28, + "roofCount": 20 + }, + { + "id": "sion_0061", + "uuid": "{457E3B58-D5BC-4576-99E0-9CEADB506B8E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1146.676, + 110.956, + -330.695 + ], + "size": [ + 30.508, + 12.429, + 26.958 + ], + "groundY": 104.742, + "roofY": 117.17, + "wallCount": 52, + "roofCount": 41 + }, + { + "id": "sion_0062", + "uuid": "{6271834E-462B-4E06-95CE-BC9B1949EBA2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1137.266, + 293.891, + -1419.465 + ], + "size": [ + 13.977, + 9.932, + 16.05 + ], + "groundY": 288.925, + "roofY": 298.857, + "wallCount": 48, + "roofCount": 19 + }, + { + "id": "sion_0063", + "uuid": "{D8F1D26D-F0CC-433A-A6A2-3B0B7903D2F7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1292.049, + 293.861, + -1472.418 + ], + "size": [ + 33.73, + 14.734, + 18.85 + ], + "groundY": 286.494, + "roofY": 301.228, + "wallCount": 60, + "roofCount": 45 + }, + { + "id": "sion_0064", + "uuid": "{E289D2BE-CB70-427E-A126-C2AF124B2D9D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1279.643, + 293.224, + -1503.67 + ], + "size": [ + 19.394, + 11.104, + 12.481 + ], + "groundY": 287.672, + "roofY": 298.776, + "wallCount": 38, + "roofCount": 12 + }, + { + "id": "sion_0065", + "uuid": "{F51FBCA4-E8A9-4E4A-869B-9C664A4F81B1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -593.107, + 53.205, + -468.098 + ], + "size": [ + 11.832, + 13.749, + 12.536 + ], + "groundY": 46.331, + "roofY": 60.08, + "wallCount": 58, + "roofCount": 21 + }, + { + "id": "sion_0066", + "uuid": "{D2311505-29B7-4E6B-8B93-79B1F8FF4CBF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1176.842, + 287.338, + -1338.359 + ], + "size": [ + 7.262, + 6.865, + 8.56 + ], + "groundY": 283.906, + "roofY": 290.771, + "wallCount": 43, + "roofCount": 15 + }, + { + "id": "sion_0067", + "uuid": "{31A43A2C-C04E-40DC-9786-3C3D4E6679BB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1317.945, + 289.67, + -1357.961 + ], + "size": [ + 15.328, + 11.519, + 18.533 + ], + "groundY": 283.91, + "roofY": 295.429, + "wallCount": 37, + "roofCount": 24 + }, + { + "id": "sion_0068", + "uuid": "{43A8FA80-8117-4216-9455-95B239D8B947}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1179.184, + 4.976, + 281.109 + ], + "size": [ + 52.914, + 18.448, + 33.284 + ], + "groundY": -4.248, + "roofY": 14.2, + "wallCount": 97, + "roofCount": 71 + }, + { + "id": "sion_0069", + "uuid": "{25C01150-7D97-4461-BE94-4CA2ECAC4E19}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -683.588, + 20.104, + 238.116 + ], + "size": [ + 17.16, + 23.348, + 15.324 + ], + "groundY": 8.43, + "roofY": 31.778, + "wallCount": 65, + "roofCount": 34 + }, + { + "id": "sion_0070", + "uuid": "{C96BED0B-9E95-4D70-9218-4DC85E1BD209}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -870.637, + 110.554, + -547.856 + ], + "size": [ + 32.664, + 14.488, + 22.933 + ], + "groundY": 103.31, + "roofY": 117.798, + "wallCount": 46, + "roofCount": 21 + }, + { + "id": "sion_0071", + "uuid": "{F42C8D67-3D86-4AC0-A6E1-C774F791C3CF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -975.994, + 25.345, + -80.276 + ], + "size": [ + 38.582, + 17.836, + 23.294 + ], + "groundY": 16.427, + "roofY": 34.263, + "wallCount": 21, + "roofCount": 39 + }, + { + "id": "sion_0072", + "uuid": "{98D24BD6-CB13-4F86-A9F0-B5481D970A13}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -741.637, + 292.662, + -1249.403 + ], + "size": [ + 23.25, + 13.632, + 25.658 + ], + "groundY": 285.846, + "roofY": 299.477, + "wallCount": 28, + "roofCount": 9 + }, + { + "id": "sion_0073", + "uuid": "{5356C6A9-94B4-487F-939F-5D710DD28DBB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1289.137, + 293.188, + -1420.833 + ], + "size": [ + 14.32, + 12.422, + 33.953 + ], + "groundY": 286.977, + "roofY": 299.399, + "wallCount": 53, + "roofCount": 19 + }, + { + "id": "sion_0074", + "uuid": "{60D8354C-427A-4090-9B6F-2D0757962F16}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -844.053, + 3.263, + 990.813 + ], + "size": [ + 33.418, + 9.972, + 37.341 + ], + "groundY": -1.723, + "roofY": 8.249, + "wallCount": 29, + "roofCount": 4 + }, + { + "id": "sion_0075", + "uuid": "{F640F40E-7EB7-47B7-B0AC-122BD473342C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1373.963, + 212.358, + -633.731 + ], + "size": [ + 17.324, + 11.034, + 17.546 + ], + "groundY": 206.841, + "roofY": 217.875, + "wallCount": 50, + "roofCount": 11 + }, + { + "id": "sion_0076", + "uuid": "{A8845A32-F5CA-4144-BE8F-5F2D9839E052}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -458.695, + 72.642, + -740.594 + ], + "size": [ + 22.008, + 11.074, + 21.96 + ], + "groundY": 67.105, + "roofY": 78.179, + "wallCount": 57, + "roofCount": 10 + }, + { + "id": "sion_0077", + "uuid": "{A43C42DD-535F-4F8E-A125-8D1E6BBA974B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -683.74, + 6.001, + 303.189 + ], + "size": [ + 36.621, + 16.382, + 19.86 + ], + "groundY": -2.19, + "roofY": 14.192, + "wallCount": 45, + "roofCount": 26 + }, + { + "id": "sion_0078", + "uuid": "{CBF855DD-17C5-4CE6-BEFB-10602852842F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -970.576, + 19.497, + -50.098 + ], + "size": [ + 18.637, + 10.746, + 18.185 + ], + "groundY": 14.124, + "roofY": 24.87, + "wallCount": 16, + "roofCount": 27 + }, + { + "id": "sion_0079", + "uuid": "{00A91D8C-92DA-4EB1-B115-EFBC65DFE9FE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 2 + ], + "center": [ + -785.574, + 29.023, + -119.081 + ], + "size": [ + 32.164, + 19.67, + 29.46 + ], + "groundY": 19.188, + "roofY": 38.858, + "wallCount": 61, + "roofCount": 21 + }, + { + "id": "sion_0080", + "uuid": "{768E693A-8D2C-4983-8DF9-95163DB03DB4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -647.646, + 39.227, + -264.285 + ], + "size": [ + 26.66, + 21.032, + 25.47 + ], + "groundY": 28.711, + "roofY": 49.743, + "wallCount": 30, + "roofCount": 27 + }, + { + "id": "sion_0081", + "uuid": "{1057E322-D5FC-400F-BB9B-9E572D258197}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -647.904, + 24.915, + -29.279 + ], + "size": [ + 10.02, + 11.441, + 11.098 + ], + "groundY": 19.195, + "roofY": 30.636, + "wallCount": 54, + "roofCount": 23 + }, + { + "id": "sion_0082", + "uuid": "{70E4750C-2B63-4FA8-B151-7DCA694F7FFF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -533.795, + 62.022, + -591.657 + ], + "size": [ + 37.449, + 14.902, + 20.346 + ], + "groundY": 54.571, + "roofY": 69.473, + "wallCount": 36, + "roofCount": 20 + }, + { + "id": "sion_0083", + "uuid": "{E88B1CB9-56CB-4313-A9D7-8559A9C85884}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1340.066, + 123.587, + -231.226 + ], + "size": [ + 6.586, + 7.6, + 6.341 + ], + "groundY": 119.787, + "roofY": 127.387, + "wallCount": 59, + "roofCount": 10 + }, + { + "id": "sion_0084", + "uuid": "{59048C5C-018D-41FE-90F8-02E203FFDABF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -429.225, + 85.226, + -881.704 + ], + "size": [ + 18.895, + 11.661, + 22.611 + ], + "groundY": 79.396, + "roofY": 91.057, + "wallCount": 40, + "roofCount": 21 + }, + { + "id": "sion_0085", + "uuid": "{DAB5AFED-1293-4C1F-A6E5-A458520F2233}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1399.041, + 276.07, + -1238.788 + ], + "size": [ + 18.457, + 9.541, + 24.424 + ], + "groundY": 271.299, + "roofY": 280.84, + "wallCount": 35, + "roofCount": 31 + }, + { + "id": "sion_0086", + "uuid": "{5E7329C8-A4CF-496F-85D9-C8386952F84F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1382.158, + 201.882, + -502.885 + ], + "size": [ + 23.434, + 12.072, + 18.268 + ], + "groundY": 195.846, + "roofY": 207.918, + "wallCount": 85, + "roofCount": 36 + }, + { + "id": "sion_0087", + "uuid": "{7FFA645F-FA6C-4CD8-BC1E-29B37196B21C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -1017.662, + 295.57, + -1207.02 + ], + "size": [ + 16.176, + 10.592, + 13.048 + ], + "groundY": 290.274, + "roofY": 300.866, + "wallCount": 20, + "roofCount": 18 + }, + { + "id": "sion_0088", + "uuid": "{F94F15BD-331F-4718-8E8F-393EC41561B4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1277.332, + 51.344, + 33.951 + ], + "size": [ + 20.445, + 13.413, + 16.609 + ], + "groundY": 44.638, + "roofY": 58.051, + "wallCount": 91, + "roofCount": 20 + }, + { + "id": "sion_0089", + "uuid": "{879B0684-EC1D-4E34-AA74-1D216EA547D4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1305.215, + 228.784, + -760.807 + ], + "size": [ + 18.695, + 13.348, + 21.886 + ], + "groundY": 222.11, + "roofY": 235.458, + "wallCount": 44, + "roofCount": 24 + }, + { + "id": "sion_0090", + "uuid": "{D9E53BE9-3161-4F92-9189-ABB0D7213501}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1096.271, + 91.359, + -261.693 + ], + "size": [ + 21.035, + 12.647, + 19.194 + ], + "groundY": 85.036, + "roofY": 97.683, + "wallCount": 44, + "roofCount": 18 + }, + { + "id": "sion_0091", + "uuid": "{9E6333D0-B2CD-4B3F-AEA8-DFD9C0E106AA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -846.709, + 16.795, + 127.855 + ], + "size": [ + 31.168, + 18.447, + 12.788 + ], + "groundY": 7.572, + "roofY": 26.019, + "wallCount": 12, + "roofCount": 36 + }, + { + "id": "sion_0092", + "uuid": "{DF39008D-EFAD-4A42-A78D-A3554E5703D4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1363.719, + 243.501, + -871.975 + ], + "size": [ + 22.484, + 8.709, + 19.794 + ], + "groundY": 239.147, + "roofY": 247.856, + "wallCount": 30, + "roofCount": 14 + }, + { + "id": "sion_0093", + "uuid": "{366CEA43-3215-4351-8F68-5C45AB7B865E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1391.676, + 210.985, + -609.037 + ], + "size": [ + 16.18, + 11.573, + 15.408 + ], + "groundY": 205.198, + "roofY": 216.771, + "wallCount": 33, + "roofCount": 14 + }, + { + "id": "sion_0094", + "uuid": "{C835A74B-878F-471D-9B0F-944166B89CBE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -659.937, + 95.376, + -662.799 + ], + "size": [ + 15.688, + 9.578, + 15.148 + ], + "groundY": 90.587, + "roofY": 100.165, + "wallCount": 23, + "roofCount": 25 + }, + { + "id": "sion_0095", + "uuid": "{2188B1FF-E981-468F-9EDD-9BFF16BD09CD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -639.998, + 86.855, + -639.95 + ], + "size": [ + 19.176, + 10.778, + 19.896 + ], + "groundY": 81.466, + "roofY": 92.244, + "wallCount": 34, + "roofCount": 13 + }, + { + "id": "sion_0096", + "uuid": "{15DC95C9-60D8-4B74-B9BB-BCA34F4B7F5B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1241.299, + 0.79, + 823.868 + ], + "size": [ + 7.684, + 6.578, + 9.416 + ], + "groundY": -2.499, + "roofY": 4.079, + "wallCount": 26, + "roofCount": 2 + }, + { + "id": "sion_0097", + "uuid": "{A58B591D-64E9-4F23-BAD1-2D80D019BC85}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -739.16, + 29.07, + -104.813 + ], + "size": [ + 31.117, + 20.343, + 27.263 + ], + "groundY": 18.899, + "roofY": 39.242, + "wallCount": 32, + "roofCount": 23 + }, + { + "id": "sion_0098", + "uuid": "{853DF4DD-59A7-4A38-B775-B36F6491C91C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -565.633, + 64.267, + -578.621 + ], + "size": [ + 16.891, + 11.63, + 16.318 + ], + "groundY": 58.452, + "roofY": 70.082, + "wallCount": 13, + "roofCount": 7 + }, + { + "id": "sion_0099", + "uuid": "{08E3F0EA-5637-40E3-9788-5E5EDBFD8459}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1081.654, + 286.493, + -1278.581 + ], + "size": [ + 8.113, + 5.098, + 7.445 + ], + "groundY": 283.944, + "roofY": 289.042, + "wallCount": 43, + "roofCount": 2 + }, + { + "id": "sion_0100", + "uuid": "{717479C7-C8DC-4E93-B101-4704769BABF6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -800.164, + 24.674, + -15.409 + ], + "size": [ + 41.234, + 20.988, + 40.172 + ], + "groundY": 14.18, + "roofY": 35.168, + "wallCount": 66, + "roofCount": 40 + }, + { + "id": "sion_0101", + "uuid": "{661C5C4B-900B-434E-B383-667E56A0A270}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1382.662, + 8.365, + 489.889 + ], + "size": [ + 74.473, + 24.232, + 56.212 + ], + "groundY": -3.751, + "roofY": 20.481, + "wallCount": 187, + "roofCount": 62 + }, + { + "id": "sion_0102", + "uuid": "{2A69FE20-B6A5-4305-842C-E391E0E9C71B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -429.227, + 63.732, + -666.377 + ], + "size": [ + 26.555, + 17.231, + 25.721 + ], + "groundY": 55.117, + "roofY": 72.348, + "wallCount": 81, + "roofCount": 24 + }, + { + "id": "sion_0103", + "uuid": "{009BC55E-B08C-4C18-8F23-9820A5960EC3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -519.195, + 5.002, + 401.561 + ], + "size": [ + 8.531, + 6.357, + 6.376 + ], + "groundY": 1.824, + "roofY": 8.181, + "wallCount": 28, + "roofCount": 12 + }, + { + "id": "sion_0104", + "uuid": "{752E9AD7-884F-46D9-A772-BC57C44789A9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1187.727, + 64.207, + -37.799 + ], + "size": [ + 18.5, + 8.962, + 14.93 + ], + "groundY": 59.726, + "roofY": 68.688, + "wallCount": 30, + "roofCount": 4 + }, + { + "id": "sion_0105", + "uuid": "{D43C952E-3A9A-4BF3-8B64-2F312A248845}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1296.344, + 238.233, + -816.268 + ], + "size": [ + 13.57, + 7.612, + 11.939 + ], + "groundY": 234.427, + "roofY": 242.039, + "wallCount": 20, + "roofCount": 2 + }, + { + "id": "sion_0106", + "uuid": "{1E82C7A5-EF04-4D22-9B8D-D3369F27D99F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1495.037, + 274.644, + -1009.401 + ], + "size": [ + 16.434, + 14.707, + 14.876 + ], + "groundY": 267.291, + "roofY": 281.998, + "wallCount": 75, + "roofCount": 39 + }, + { + "id": "sion_0107", + "uuid": "{348A2A36-6091-444B-9E69-9965056972BC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -833.523, + 69.921, + -268.073 + ], + "size": [ + 16.023, + 10.512, + 16.574 + ], + "groundY": 64.665, + "roofY": 75.177, + "wallCount": 38, + "roofCount": 8 + }, + { + "id": "sion_0108", + "uuid": "{9FDB55AC-216A-4FFA-A2D1-0B9B4A0916EA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1446.033, + 89.478, + -38.832 + ], + "size": [ + 49.77, + 20.059, + 45.794 + ], + "groundY": 79.448, + "roofY": 99.507, + "wallCount": 81, + "roofCount": 50 + }, + { + "id": "sion_0109", + "uuid": "{CCB23CE0-D937-48FF-81C8-F067F83E40EC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -425.168, + 18.432, + 219.508 + ], + "size": [ + 16.289, + 14.327, + 16.466 + ], + "groundY": 11.269, + "roofY": 25.596, + "wallCount": 41, + "roofCount": 32 + }, + { + "id": "sion_0110", + "uuid": "{961ADC14-549C-4994-A493-3AEF44F0B328}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1137.441, + 291.005, + -1369.629 + ], + "size": [ + 27.641, + 9.446, + 30.695 + ], + "groundY": 286.282, + "roofY": 295.728, + "wallCount": 42, + "roofCount": 42 + }, + { + "id": "sion_0111", + "uuid": "{08B95A8B-D066-467F-A2BE-C8ACD6174210}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1345.402, + -0.399, + 591.156 + ], + "size": [ + 18.453, + 5.41, + 10.736 + ], + "groundY": -3.104, + "roofY": 2.306, + "wallCount": 10, + "roofCount": 2 + }, + { + "id": "sion_0112", + "uuid": "{E960B51C-542A-4207-902A-67BF6A2DFA9F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1351.33, + 278.791, + -1084.451 + ], + "size": [ + 13.863, + 10.746, + 12.744 + ], + "groundY": 273.418, + "roofY": 284.164, + "wallCount": 41, + "roofCount": 14 + }, + { + "id": "sion_0113", + "uuid": "{754400EE-BDB8-4CB2-A8F1-51E872F4DD9C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1471.627, + 272.743, + -1136.551 + ], + "size": [ + 15.699, + 9.798, + 12.674 + ], + "groundY": 267.844, + "roofY": 277.642, + "wallCount": 50, + "roofCount": 29 + }, + { + "id": "sion_0114", + "uuid": "{130DADC9-51EF-4BB7-8008-10A3F16C94E3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -579.232, + 59.37, + -518.921 + ], + "size": [ + 32.051, + 12.698, + 30.284 + ], + "groundY": 53.021, + "roofY": 65.719, + "wallCount": 14, + "roofCount": 26 + }, + { + "id": "sion_0115", + "uuid": "{9966E6A2-57EE-4B72-B1D3-7EF600BE508A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1130.738, + 263.689, + -953.224 + ], + "size": [ + 19.984, + 11.588, + 18.8 + ], + "groundY": 257.895, + "roofY": 269.483, + "wallCount": 47, + "roofCount": 20 + }, + { + "id": "sion_0116", + "uuid": "{CF26BE48-244E-4709-B74D-8B26F80881F2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -823.197, + 23.084, + -45.08 + ], + "size": [ + 16.199, + 14.958, + 16.452 + ], + "groundY": 15.605, + "roofY": 30.563, + "wallCount": 84, + "roofCount": 36 + }, + { + "id": "sion_0117", + "uuid": "{5FF3B50C-A1B6-40B4-8930-49489ECE6B90}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1152.861, + 248.877, + -877.987 + ], + "size": [ + 15.363, + 10.228, + 17.702 + ], + "groundY": 243.763, + "roofY": 253.991, + "wallCount": 46, + "roofCount": 27 + }, + { + "id": "sion_0118", + "uuid": "{C107AFF5-8367-4D67-B683-383651D10EC1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1259.002, + 2.955, + 856.002 + ], + "size": [ + 43.121, + 11.937, + 20.94 + ], + "groundY": -3.014, + "roofY": 8.923, + "wallCount": 26, + "roofCount": 8 + }, + { + "id": "sion_0119", + "uuid": "{8C687629-A9A2-46E2-BC54-1A475BB1B466}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -649.465, + 34.583, + -207.686 + ], + "size": [ + 18.477, + 15.604, + 17.884 + ], + "groundY": 26.781, + "roofY": 42.385, + "wallCount": 32, + "roofCount": 32 + }, + { + "id": "sion_0120", + "uuid": "{4457F36A-82C6-4448-8793-9E53CD459EE1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1058.521, + 294.949, + -1325.001 + ], + "size": [ + 30.496, + 11.616, + 25.606 + ], + "groundY": 289.141, + "roofY": 300.757, + "wallCount": 54, + "roofCount": 20 + }, + { + "id": "sion_0121", + "uuid": "{1F8CCE10-EA49-4B42-A8B8-EC622F306075}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -913.793, + 3.31, + 933.813 + ], + "size": [ + 31.289, + 10.412, + 58.355 + ], + "groundY": -1.896, + "roofY": 8.516, + "wallCount": 21, + "roofCount": 40 + }, + { + "id": "sion_0122", + "uuid": "{2DFBAF8E-6E55-4393-867D-0E04809EF9FA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1333.918, + 41.994, + 153.222 + ], + "size": [ + 15.727, + 10.32, + 10.418 + ], + "groundY": 36.834, + "roofY": 47.154, + "wallCount": 47, + "roofCount": 12 + }, + { + "id": "sion_0123", + "uuid": "{B7F5EF10-3F1F-410B-A0A2-57170ED42A09}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1317.207, + 6.079, + 280.569 + ], + "size": [ + 36.539, + 17.925, + 45.233 + ], + "groundY": -2.883, + "roofY": 15.042, + "wallCount": 8, + "roofCount": 50 + }, + { + "id": "sion_0124", + "uuid": "{FB048844-EC0B-4C12-A00A-0CBF527E1737}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -902.338, + 7.381, + 249.747 + ], + "size": [ + 39.121, + 19.256, + 21.9 + ], + "groundY": -2.247, + "roofY": 17.009, + "wallCount": 61, + "roofCount": 37 + }, + { + "id": "sion_0125", + "uuid": "{4B585326-96E2-419E-927F-8C45E18883B5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -879.228, + 3.85, + 1030.658 + ], + "size": [ + 58.574, + 10.981, + 33.756 + ], + "groundY": -1.64, + "roofY": 9.341, + "wallCount": 38, + "roofCount": 28 + }, + { + "id": "sion_0126", + "uuid": "{82E8C4CD-3A6D-4BF4-B346-3E8A64FE2620}", + "name": "", + "class": "Flugdach", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1164.668, + 2.461, + 961.949 + ], + "size": [ + 33.633, + 7.828, + 33.224 + ], + "groundY": -1.453, + "roofY": 6.375, + "wallCount": 15, + "roofCount": 10 + }, + { + "id": "sion_0127", + "uuid": "{B2F1521B-DA3F-4E6C-BDD7-73AE8631CB7B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -447.186, + 54.949, + -547.935 + ], + "size": [ + 24.52, + 19.716, + 15.134 + ], + "groundY": 45.091, + "roofY": 64.807, + "wallCount": 41, + "roofCount": 39 + }, + { + "id": "sion_0128", + "uuid": "{74345BAB-39EB-4AE5-9B6E-B7082FFF617E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -697.518, + 36.325, + -234.487 + ], + "size": [ + 19.012, + 11.76, + 18.782 + ], + "groundY": 30.445, + "roofY": 42.205, + "wallCount": 10, + "roofCount": 32 + }, + { + "id": "sion_0129", + "uuid": "{B64836A6-0A89-406F-AF26-79705100332E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1220.613, + 2.674, + 961.232 + ], + "size": [ + 32.242, + 9.794, + 26.62 + ], + "groundY": -2.223, + "roofY": 7.571, + "wallCount": 29, + "roofCount": 3 + }, + { + "id": "sion_0130", + "uuid": "{48D1FFA0-58FB-40BD-BF0C-78E0EA908407}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1325.324, + 16.075, + 415.81 + ], + "size": [ + 42.484, + 41.504, + 31.265 + ], + "groundY": -4.677, + "roofY": 36.827, + "wallCount": 50, + "roofCount": 12 + }, + { + "id": "sion_0131", + "uuid": "{BBCE775E-FA37-4CF5-BDAA-D19D3040BFA3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -921.174, + 298.095, + -1441.442 + ], + "size": [ + 23.215, + 12.061, + 21.985 + ], + "groundY": 292.064, + "roofY": 304.125, + "wallCount": 35, + "roofCount": 32 + }, + { + "id": "sion_0132", + "uuid": "{3F41FAE4-61A0-4660-8B3A-A3A27EC80168}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -968.057, + 205.68, + -808.515 + ], + "size": [ + 5.371, + 5.603, + 5.433 + ], + "groundY": 202.878, + "roofY": 208.481, + "wallCount": 18, + "roofCount": 4 + }, + { + "id": "sion_0133", + "uuid": "{FDF80442-50AF-4EA9-82B4-071838FBE024}", + "name": "Patinoire de l'ancien Stand", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -983.074, + 4.103, + 417.373 + ], + "size": [ + 81.883, + 13.53, + 45.876 + ], + "groundY": -2.662, + "roofY": 10.868, + "wallCount": 14, + "roofCount": 2 + }, + { + "id": "sion_0134", + "uuid": "{0BDB26DC-9415-4163-94C1-F35D74C9DE0E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -1010.309, + 18.397, + -17.512 + ], + "size": [ + 35.648, + 13.399, + 29.334 + ], + "groundY": 11.698, + "roofY": 25.097, + "wallCount": 24, + "roofCount": 10 + }, + { + "id": "sion_0135", + "uuid": "{1EDD707E-5F33-48B7-8A05-DA532C268A23}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1078.873, + 11.182, + 393.988 + ], + "size": [ + 30.582, + 31.214, + 16.002 + ], + "groundY": -4.425, + "roofY": 26.789, + "wallCount": 127, + "roofCount": 20 + }, + { + "id": "sion_0136", + "uuid": "{70F202D6-2F23-46A3-B424-A932F99A7685}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1053.914, + 257.682, + -957.306 + ], + "size": [ + 18.203, + 12.719, + 17.286 + ], + "groundY": 251.323, + "roofY": 264.042, + "wallCount": 39, + "roofCount": 22 + }, + { + "id": "sion_0137", + "uuid": "{1D36C5A5-2436-4014-BDA5-398F84E2A94F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -966.516, + 34.0, + -107.787 + ], + "size": [ + 25.156, + 10.146, + 14.666 + ], + "groundY": 28.927, + "roofY": 39.073, + "wallCount": 30, + "roofCount": 15 + }, + { + "id": "sion_0138", + "uuid": "{04BF676C-E68E-45AC-8059-1755D00E4828}", + "name": "", + "class": "Kapelle", + "archStyle": "fortress", + "tile": [ + 0, + 0 + ], + "center": [ + -1147.766, + 288.483, + -1215.504 + ], + "size": [ + 14.734, + 10.428, + 14.098 + ], + "groundY": 283.269, + "roofY": 293.697, + "wallCount": 83, + "roofCount": 28 + }, + { + "id": "sion_0139", + "uuid": "{6B30F12B-4548-4F08-9455-0E299717AD0D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -998.043, + 75.989, + -213.141 + ], + "size": [ + 17.781, + 13.832, + 17.024 + ], + "groundY": 69.073, + "roofY": 82.905, + "wallCount": 24, + "roofCount": 11 + }, + { + "id": "sion_0140", + "uuid": "{BA92DD97-B6BA-4FA3-B105-0590FCE10A58}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1256.523, + 40.459, + 91.945 + ], + "size": [ + 24.156, + 10.114, + 22.072 + ], + "groundY": 35.402, + "roofY": 45.516, + "wallCount": 44, + "roofCount": 14 + }, + { + "id": "sion_0141", + "uuid": "{E744FB5C-D187-4F34-AE3D-1C3258DA91D8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -648.705, + 46.925, + -365.627 + ], + "size": [ + 20.707, + 10.885, + 21.986 + ], + "groundY": 41.483, + "roofY": 52.367, + "wallCount": 29, + "roofCount": 47 + }, + { + "id": "sion_0142", + "uuid": "{23402289-81FF-4B06-887E-744BABBE07B8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1184.643, + 102.526, + -255.5 + ], + "size": [ + 15.613, + 13.129, + 20.277 + ], + "groundY": 95.962, + "roofY": 109.091, + "wallCount": 27, + "roofCount": 24 + }, + { + "id": "sion_0143", + "uuid": "{7C1096D4-39C7-45A3-B0E2-AACF57F70AD5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -809.152, + 97.38, + -510.505 + ], + "size": [ + 36.672, + 11.629, + 29.734 + ], + "groundY": 91.565, + "roofY": 103.194, + "wallCount": 22, + "roofCount": 6 + }, + { + "id": "sion_0144", + "uuid": "{AC37CEFE-0285-42BD-AA17-6AB17CF17721}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -923.123, + 32.099, + -133.179 + ], + "size": [ + 14.02, + 10.462, + 13.052 + ], + "groundY": 26.868, + "roofY": 37.33, + "wallCount": 47, + "roofCount": 2 + }, + { + "id": "sion_0145", + "uuid": "{002E5BB4-2CFB-45E7-9AA3-084EF00B59E2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1243.863, + 282.625, + -1165.864 + ], + "size": [ + 9.93, + 10.81, + 9.138 + ], + "groundY": 277.22, + "roofY": 288.03, + "wallCount": 55, + "roofCount": 23 + }, + { + "id": "sion_0146", + "uuid": "{C7F5035C-3D3F-4278-A100-92DDE20CA0F2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -698.119, + 8.568, + 676.032 + ], + "size": [ + 113.715, + 20.284, + 50.264 + ], + "groundY": -1.574, + "roofY": 18.71, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_0147", + "uuid": "{7DB079D3-2E60-44FA-8A31-7500ABAFA587}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -971.451, + 297.55, + -1438.417 + ], + "size": [ + 14.973, + 10.761, + 14.986 + ], + "groundY": 292.169, + "roofY": 302.93, + "wallCount": 46, + "roofCount": 9 + }, + { + "id": "sion_0148", + "uuid": "{5033F73B-89ED-439D-9826-2A85D8C4147E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -840.629, + 15.159, + 194.082 + ], + "size": [ + 30.664, + 22.354, + 22.935 + ], + "groundY": 3.982, + "roofY": 26.336, + "wallCount": 21, + "roofCount": 25 + }, + { + "id": "sion_0149", + "uuid": "{00D02B40-2916-4E17-8862-DEA411BD983B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -746.389, + 57.765, + -310.091 + ], + "size": [ + 17.996, + 12.704, + 17.206 + ], + "groundY": 51.413, + "roofY": 64.117, + "wallCount": 27, + "roofCount": 31 + }, + { + "id": "sion_0150", + "uuid": "{BD45FAF9-DA75-420F-8459-13D4BD999CD7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1531.246, + 267.337, + -1004.444 + ], + "size": [ + 32.297, + 14.485, + 20.92 + ], + "groundY": 260.095, + "roofY": 274.58, + "wallCount": 50, + "roofCount": 27 + }, + { + "id": "sion_0151", + "uuid": "{0A612374-4F9E-405E-9037-01F59DE4B2A1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -606.359, + 24.786, + 138.68 + ], + "size": [ + 33.398, + 21.419, + 27.678 + ], + "groundY": 14.077, + "roofY": 35.496, + "wallCount": 20, + "roofCount": 38 + }, + { + "id": "sion_0152", + "uuid": "{BCEECE30-70D2-45F2-817C-FC9B1EA0591E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1500.17, + 268.808, + -888.701 + ], + "size": [ + 15.965, + 12.846, + 13.866 + ], + "groundY": 262.385, + "roofY": 275.231, + "wallCount": 53, + "roofCount": 41 + }, + { + "id": "sion_0153", + "uuid": "{810D6196-5C3A-421C-8859-F4F31C68DBDA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1260.352, + 282.239, + -1139.236 + ], + "size": [ + 23.828, + 12.534, + 23.5 + ], + "groundY": 275.972, + "roofY": 288.506, + "wallCount": 66, + "roofCount": 39 + }, + { + "id": "sion_0154", + "uuid": "{310E419F-3C5B-49EF-9800-46FB317612BE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -818.277, + 71.12, + -286.008 + ], + "size": [ + 15.273, + 10.823, + 14.559 + ], + "groundY": 65.709, + "roofY": 76.532, + "wallCount": 29, + "roofCount": 2 + }, + { + "id": "sion_0155", + "uuid": "{A1B6C259-095B-4EFA-B91A-3328EFD8220A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -585.41, + 8.876, + 510.287 + ], + "size": [ + 41.031, + 20.825, + 24.393 + ], + "groundY": -1.537, + "roofY": 19.288, + "wallCount": 21, + "roofCount": 17 + }, + { + "id": "sion_0156", + "uuid": "{1A4829CE-9DB2-4CD6-BD09-E0B59BFA000F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -773.742, + 101.456, + -584.608 + ], + "size": [ + 21.883, + 12.502, + 14.884 + ], + "groundY": 95.205, + "roofY": 107.707, + "wallCount": 43, + "roofCount": 6 + }, + { + "id": "sion_0157", + "uuid": "{243B2450-4FEF-4A17-8F47-4DDBF1B68E0A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1140.533, + 16.601, + 69.952 + ], + "size": [ + 32.855, + 19.194, + 27.532 + ], + "groundY": 7.004, + "roofY": 26.198, + "wallCount": 51, + "roofCount": 22 + }, + { + "id": "sion_0158", + "uuid": "{C1FFD96F-7089-4956-BCB9-D683A7C0C4A1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1395.168, + 284.07, + -1377.498 + ], + "size": [ + 25.031, + 14.642, + 24.416 + ], + "groundY": 276.749, + "roofY": 291.391, + "wallCount": 58, + "roofCount": 44 + }, + { + "id": "sion_0159", + "uuid": "{BB9AAAC5-4452-4A43-81FD-D52A9AA56B23}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1230.105, + 283.383, + -1247.046 + ], + "size": [ + 13.164, + 14.968, + 21.206 + ], + "groundY": 275.899, + "roofY": 290.867, + "wallCount": 37, + "roofCount": 11 + }, + { + "id": "sion_0160", + "uuid": "{7C2B405C-5564-47A3-8249-D73254ED1F00}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -695.273, + 42.88, + -292.041 + ], + "size": [ + 25.672, + 10.749, + 23.557 + ], + "groundY": 37.505, + "roofY": 48.254, + "wallCount": 28, + "roofCount": 15 + }, + { + "id": "sion_0161", + "uuid": "{C13C1939-4F4A-4C80-A873-F4C6780056CC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -704.387, + 32.241, + -126.811 + ], + "size": [ + 41.57, + 20.305, + 31.794 + ], + "groundY": 22.088, + "roofY": 42.393, + "wallCount": 21, + "roofCount": 17 + }, + { + "id": "sion_0162", + "uuid": "{BE8A5F5E-9246-4D8E-B7D3-7099B6AE35D2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1369.445, + 280.297, + -1062.778 + ], + "size": [ + 17.172, + 16.701, + 18.68 + ], + "groundY": 271.946, + "roofY": 288.647, + "wallCount": 48, + "roofCount": 47 + }, + { + "id": "sion_0163", + "uuid": "{2483F918-865A-45F6-BCBE-295ADB1EEF41}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1247.764, + 118.626, + -295.16 + ], + "size": [ + 17.176, + 10.03, + 17.05 + ], + "groundY": 113.611, + "roofY": 123.641, + "wallCount": 45, + "roofCount": 12 + }, + { + "id": "sion_0164", + "uuid": "{CB552D26-E851-4C47-AF79-00B2E3B199F3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1463.117, + 225.653, + -768.71 + ], + "size": [ + 8.219, + 7.112, + 10.547 + ], + "groundY": 222.097, + "roofY": 229.209, + "wallCount": 47, + "roofCount": 30 + }, + { + "id": "sion_0165", + "uuid": "{A6CCCF58-4956-4DD9-96B6-8939C9C4E9BA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -924.619, + 15.881, + 44.534 + ], + "size": [ + 50.684, + 14.832, + 39.588 + ], + "groundY": 8.465, + "roofY": 23.297, + "wallCount": 35, + "roofCount": 6 + }, + { + "id": "sion_0166", + "uuid": "{D0B9FC45-AA55-440F-91C2-E0B44D36238B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -761.072, + 69.5, + -423.16 + ], + "size": [ + 23.269, + 13.432, + 22.777 + ], + "groundY": 62.784, + "roofY": 76.216, + "wallCount": 42, + "roofCount": 11 + }, + { + "id": "sion_0167", + "uuid": "{4F96BF6E-8A4F-4B37-900C-9763E7CEF683}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -847.504, + 96.369, + -481.727 + ], + "size": [ + 36.75, + 11.669, + 30.714 + ], + "groundY": 90.534, + "roofY": 102.203, + "wallCount": 17, + "roofCount": 7 + }, + { + "id": "sion_0168", + "uuid": "{AB18C61C-D739-4B9C-B5D8-450D633EA63F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -1011.309, + 75.235, + -221.27 + ], + "size": [ + 13.281, + 7.766, + 11.644 + ], + "groundY": 71.352, + "roofY": 79.118, + "wallCount": 38, + "roofCount": 14 + }, + { + "id": "sion_0169", + "uuid": "{7A783CB8-F680-4E7A-AA2D-3759F934A544}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1200.447, + 1.65, + 505.762 + ], + "size": [ + 53.559, + 8.979, + 32.762 + ], + "groundY": -2.84, + "roofY": 6.139, + "wallCount": 21, + "roofCount": 12 + }, + { + "id": "sion_0170", + "uuid": "{66B4A0AD-8015-407D-8A97-7398DF108A3C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1165.266, + 93.406, + -224.898 + ], + "size": [ + 17.664, + 11.693, + 15.573 + ], + "groundY": 87.559, + "roofY": 99.252, + "wallCount": 42, + "roofCount": 4 + }, + { + "id": "sion_0171", + "uuid": "{249A6621-91D2-45C3-B3AC-11CD5B8C4BC7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1040.83, + 293.723, + -1368.015 + ], + "size": [ + 3.371, + 6.149, + 6.328 + ], + "groundY": 290.649, + "roofY": 296.798, + "wallCount": 24, + "roofCount": 2 + }, + { + "id": "sion_0172", + "uuid": "{DC1731EE-40A6-4A99-B0E1-1A0980440144}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -622.121, + 52.782, + -425.787 + ], + "size": [ + 21.32, + 16.917, + 21.238 + ], + "groundY": 44.324, + "roofY": 61.241, + "wallCount": 44, + "roofCount": 45 + }, + { + "id": "sion_0173", + "uuid": "{274A3167-7186-47AD-8641-6FC8906224B6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -513.033, + 68.145, + -646.424 + ], + "size": [ + 23.238, + 19.498, + 20.958 + ], + "groundY": 58.396, + "roofY": 77.894, + "wallCount": 66, + "roofCount": 47 + }, + { + "id": "sion_0174", + "uuid": "{07F59781-D4C8-4F3F-AD0E-7471447D630A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1460.158, + -1.244, + 496.944 + ], + "size": [ + 17.988, + 5.059, + 10.644 + ], + "groundY": -3.773, + "roofY": 1.286, + "wallCount": 18, + "roofCount": 2 + }, + { + "id": "sion_0175", + "uuid": "{1BD5EBF4-00AD-4F4F-92F2-082EB609F05D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1304.26, + 2.918, + 695.106 + ], + "size": [ + 13.527, + 11.833, + 19.577 + ], + "groundY": -2.999, + "roofY": 8.834, + "wallCount": 56, + "roofCount": 25 + }, + { + "id": "sion_0176", + "uuid": "{68853087-7524-44C1-9A99-671486E57DEC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -638.941, + 17.613, + 277.189 + ], + "size": [ + 49.0, + 27.986, + 35.978 + ], + "groundY": 3.62, + "roofY": 31.606, + "wallCount": 60, + "roofCount": 20 + }, + { + "id": "sion_0177", + "uuid": "{A37AB7C3-1163-4865-8CA4-5F48BAF60C3A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -756.611, + 3.831, + 926.208 + ], + "size": [ + 29.582, + 9.844, + 25.408 + ], + "groundY": -1.091, + "roofY": 8.753, + "wallCount": 34, + "roofCount": 8 + }, + { + "id": "sion_0178", + "uuid": "{B8388A89-E9E4-49EE-908F-FDBE5F0DD5DF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1170.027, + 8.093, + 209.133 + ], + "size": [ + 33.477, + 16.544, + 26.574 + ], + "groundY": -0.179, + "roofY": 16.365, + "wallCount": 31, + "roofCount": 21 + }, + { + "id": "sion_0179", + "uuid": "{0B93AFDB-1A2C-412A-86FF-B49AA86C2799}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1410.789, + 211.038, + -597.525 + ], + "size": [ + 25.758, + 11.658, + 18.124 + ], + "groundY": 205.209, + "roofY": 216.867, + "wallCount": 38, + "roofCount": 14 + }, + { + "id": "sion_0180", + "uuid": "{B38EF14A-FC0C-4F94-BCF4-1BCDDADA4986}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1174.84, + 139.196, + -416.165 + ], + "size": [ + 65.719, + 15.862, + 34.137 + ], + "groundY": 131.265, + "roofY": 147.127, + "wallCount": 204, + "roofCount": 96 + }, + { + "id": "sion_0181", + "uuid": "{7CA29E9C-3395-4F79-9728-75EE3288C96E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1136.721, + 4.883, + 795.525 + ], + "size": [ + 44.488, + 13.914, + 50.494 + ], + "groundY": -2.074, + "roofY": 11.84, + "wallCount": 58, + "roofCount": 16 + }, + { + "id": "sion_0182", + "uuid": "{07077EFD-7648-4FFA-89D7-061EC8644CCC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -889.619, + 2.512, + 993.332 + ], + "size": [ + 50.059, + 8.349, + 29.684 + ], + "groundY": -1.662, + "roofY": 6.686, + "wallCount": 27, + "roofCount": 40 + }, + { + "id": "sion_0183", + "uuid": "{843E1E36-8C82-48D6-BE83-3FDCC0CBA90F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -711.863, + 3.664, + 950.53 + ], + "size": [ + 36.867, + 10.456, + 35.158 + ], + "groundY": -1.564, + "roofY": 8.892, + "wallCount": 21, + "roofCount": 40 + }, + { + "id": "sion_0184", + "uuid": "{90DB1778-BB1D-4892-8379-60FCAF81B1B6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1310.311, + 293.131, + -1501.942 + ], + "size": [ + 19.91, + 12.694, + 30.901 + ], + "groundY": 286.784, + "roofY": 299.478, + "wallCount": 30, + "roofCount": 26 + }, + { + "id": "sion_0185", + "uuid": "{98FB20DB-75B2-4C44-B88E-0672DF5395C2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1264.875, + 46.698, + 75.763 + ], + "size": [ + 17.148, + 8.626, + 13.282 + ], + "groundY": 42.385, + "roofY": 51.011, + "wallCount": 52, + "roofCount": 13 + }, + { + "id": "sion_0186", + "uuid": "{A50D634A-AC33-4599-914F-F33C339426B2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1446.617, + 226.889, + -715.53 + ], + "size": [ + 15.992, + 10.672, + 14.284 + ], + "groundY": 221.553, + "roofY": 232.225, + "wallCount": 49, + "roofCount": 22 + }, + { + "id": "sion_0187", + "uuid": "{D06DD0CC-C4D1-456B-9D5F-0B20AD61B6E5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -440.162, + 44.698, + -261.047 + ], + "size": [ + 71.441, + 26.624, + 47.174 + ], + "groundY": 31.386, + "roofY": 58.01, + "wallCount": 79, + "roofCount": 124 + }, + { + "id": "sion_0188", + "uuid": "{D4DD62FC-CC78-4634-99D1-46FA5DC870C8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -558.873, + 17.399, + 233.963 + ], + "size": [ + 13.457, + 13.012, + 10.361 + ], + "groundY": 10.893, + "roofY": 23.905, + "wallCount": 27, + "roofCount": 20 + }, + { + "id": "sion_0189", + "uuid": "{1A7337AE-CD9E-4876-B84B-7D104DF7D1FA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1408.725, + 279.472, + -1484.998 + ], + "size": [ + 25.512, + 10.452, + 24.703 + ], + "groundY": 274.246, + "roofY": 284.698, + "wallCount": 22, + "roofCount": 24 + }, + { + "id": "sion_0190", + "uuid": "{52413F98-DFB8-4F83-947B-2F55518381F3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1448.941, + 2.461, + 857.752 + ], + "size": [ + 14.672, + 11.17, + 11.668 + ], + "groundY": -3.124, + "roofY": 8.046, + "wallCount": 52, + "roofCount": 26 + }, + { + "id": "sion_0191", + "uuid": "{B4FF19CB-CF61-4ABB-8A04-C36452F92703}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1204.301, + 285.492, + -1324.721 + ], + "size": [ + 8.969, + 5.864, + 9.494 + ], + "groundY": 282.56, + "roofY": 288.424, + "wallCount": 49, + "roofCount": 2 + }, + { + "id": "sion_0192", + "uuid": "{D40A3E5E-91E5-43EC-B9BD-A2C3F577C607}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1531.711, + 58.105, + 334.829 + ], + "size": [ + 25.719, + 13.854, + 21.046 + ], + "groundY": 51.178, + "roofY": 65.032, + "wallCount": 80, + "roofCount": 19 + }, + { + "id": "sion_0193", + "uuid": "{0616E551-F76D-4937-9CD6-9683963013C0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1275.144, + 274.28, + -1206.225 + ], + "size": [ + 6.875, + 9.113, + 7.729 + ], + "groundY": 269.723, + "roofY": 278.836, + "wallCount": 46, + "roofCount": 11 + }, + { + "id": "sion_0194", + "uuid": "{9A28937E-D985-428A-9DCD-1AB0D0947DC2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -613.816, + 96.006, + -714.793 + ], + "size": [ + 18.391, + 11.722, + 19.79 + ], + "groundY": 90.145, + "roofY": 101.867, + "wallCount": 36, + "roofCount": 5 + }, + { + "id": "sion_0195", + "uuid": "{CE4F1998-4724-40C8-B3BE-FF2B754C91BF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1161.887, + 295.167, + -1480.567 + ], + "size": [ + 9.344, + 7.85, + 9.91 + ], + "groundY": 291.242, + "roofY": 299.092, + "wallCount": 43, + "roofCount": 24 + }, + { + "id": "sion_0196", + "uuid": "{988B7D65-AF52-4D1B-BC6A-B5E2AF73130D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -998.844, + 11.993, + 177.48 + ], + "size": [ + 28.422, + 18.651, + 18.071 + ], + "groundY": 2.668, + "roofY": 21.318, + "wallCount": 37, + "roofCount": 16 + }, + { + "id": "sion_0197", + "uuid": "{0EDE7F6C-FCDC-4535-9F72-8AACB696688E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -497.867, + 36.107, + -120.079 + ], + "size": [ + 49.719, + 22.414, + 29.966 + ], + "groundY": 24.9, + "roofY": 47.314, + "wallCount": 25, + "roofCount": 20 + }, + { + "id": "sion_0198", + "uuid": "{92AE2CAF-98E8-488F-BFDE-8ECFE0A7F17D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -554.957, + 32.944, + -227.926 + ], + "size": [ + 33.555, + 9.948, + 42.022 + ], + "groundY": 27.97, + "roofY": 37.918, + "wallCount": 18, + "roofCount": 4 + }, + { + "id": "sion_0199", + "uuid": "{711C78D5-AE6D-482F-B44D-17AE50F5D845}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1430.018, + 1.637, + 857.238 + ], + "size": [ + 12.801, + 9.13, + 6.902 + ], + "groundY": -2.928, + "roofY": 6.202, + "wallCount": 67, + "roofCount": 18 + }, + { + "id": "sion_0200", + "uuid": "{9B510B22-D6DD-48DC-B46C-1055BB06D61A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1463.645, + 276.503, + -1211.267 + ], + "size": [ + 18.359, + 11.198, + 21.34 + ], + "groundY": 270.904, + "roofY": 282.102, + "wallCount": 43, + "roofCount": 27 + }, + { + "id": "sion_0201", + "uuid": "{2791B142-2E67-411D-AC21-544481749696}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -547.072, + 2.079, + 720.778 + ], + "size": [ + 7.606, + 5.438, + 10.976 + ], + "groundY": -0.64, + "roofY": 4.798, + "wallCount": 38, + "roofCount": 2 + }, + { + "id": "sion_0202", + "uuid": "{19CD5BB5-005F-491A-995D-BD8C835EE984}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1071.428, + 296.922, + -1340.158 + ], + "size": [ + 17.574, + 10.75, + 16.558 + ], + "groundY": 291.547, + "roofY": 302.297, + "wallCount": 18, + "roofCount": 13 + }, + { + "id": "sion_0203", + "uuid": "{E3C4980C-C384-4D48-9502-169F3ACEE403}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1225.418, + 268.094, + -1003.732 + ], + "size": [ + 15.312, + 11.596, + 14.987 + ], + "groundY": 262.296, + "roofY": 273.892, + "wallCount": 33, + "roofCount": 11 + }, + { + "id": "sion_0204", + "uuid": "{24214E03-B95A-4B5A-BB19-0103A7EE3267}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1185.469, + 118.531, + -334.837 + ], + "size": [ + 6.445, + 8.282, + 6.303 + ], + "groundY": 114.39, + "roofY": 122.672, + "wallCount": 32, + "roofCount": 8 + }, + { + "id": "sion_0205", + "uuid": "{016C190B-573B-4721-973A-7AFF9B5B87AC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1121.551, + 293.568, + -1454.345 + ], + "size": [ + 11.172, + 11.002, + 10.689 + ], + "groundY": 288.067, + "roofY": 299.069, + "wallCount": 66, + "roofCount": 24 + }, + { + "id": "sion_0206", + "uuid": "{D199A23D-D631-40CD-B0BE-AB8555103EAE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -983.676, + 4.88, + 330.398 + ], + "size": [ + 47.281, + 17.217, + 20.276 + ], + "groundY": -3.729, + "roofY": 13.488, + "wallCount": 14, + "roofCount": 24 + }, + { + "id": "sion_0207", + "uuid": "{ABE7675A-7E4F-4E90-A8AE-ADF17C6C1091}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -831.123, + 4.432, + 295.89 + ], + "size": [ + 12.793, + 14.156, + 11.224 + ], + "groundY": -2.646, + "roofY": 11.51, + "wallCount": 78, + "roofCount": 31 + }, + { + "id": "sion_0208", + "uuid": "{14D34460-097E-4013-9C7C-B90BFDF58F27}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1264.203, + 271.134, + -1046.989 + ], + "size": [ + 13.133, + 11.018, + 12.422 + ], + "groundY": 265.625, + "roofY": 276.643, + "wallCount": 64, + "roofCount": 33 + }, + { + "id": "sion_0209", + "uuid": "{CAB36172-8E24-4A69-9873-5CB4A874B96C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1301.764, + 280.496, + -1143.731 + ], + "size": [ + 16.199, + 10.891, + 14.86 + ], + "groundY": 275.051, + "roofY": 285.942, + "wallCount": 50, + "roofCount": 24 + }, + { + "id": "sion_0210", + "uuid": "{5051DD2D-7919-4D7A-91E7-B0F4C324602F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -803.584, + 59.44, + -258.59 + ], + "size": [ + 22.637, + 12.242, + 18.454 + ], + "groundY": 53.319, + "roofY": 65.561, + "wallCount": 19, + "roofCount": 32 + }, + { + "id": "sion_0211", + "uuid": "{1330EF53-9455-4DF1-AC55-D07A1814F980}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1122.975, + 2.2, + 429.178 + ], + "size": [ + 11.902, + 11.09, + 21.428 + ], + "groundY": -3.345, + "roofY": 7.745, + "wallCount": 27, + "roofCount": 12 + }, + { + "id": "sion_0212", + "uuid": "{1BC1470B-75CD-4EBD-B0CE-49741F8329CA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -590.057, + 46.914, + -423.96 + ], + "size": [ + 15.535, + 13.106, + 15.908 + ], + "groundY": 40.361, + "roofY": 53.467, + "wallCount": 39, + "roofCount": 8 + }, + { + "id": "sion_0213", + "uuid": "{CED361C7-3A3B-4D2B-A2C4-5D50412D06BA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -697.379, + 3.701, + 1015.302 + ], + "size": [ + 49.477, + 10.271, + 79.464 + ], + "groundY": -1.435, + "roofY": 8.836, + "wallCount": 34, + "roofCount": 10 + }, + { + "id": "sion_0214", + "uuid": "{578305CD-4FEB-4C90-966E-51F616EA3124}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -792.328, + 20.098, + -49.53 + ], + "size": [ + 11.812, + 7.208, + 15.734 + ], + "groundY": 16.494, + "roofY": 23.702, + "wallCount": 38, + "roofCount": 21 + }, + { + "id": "sion_0215", + "uuid": "{58CA72CD-856B-46AE-820D-D6AE88948824}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1040.174, + 17.487, + 3.221 + ], + "size": [ + 24.684, + 13.736, + 21.682 + ], + "groundY": 10.619, + "roofY": 24.355, + "wallCount": 20, + "roofCount": 18 + }, + { + "id": "sion_0216", + "uuid": "{7312DDF7-C9A1-431E-9279-CC58589835B6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1251.994, + 261.36, + -930.371 + ], + "size": [ + 14.402, + 13.24, + 20.695 + ], + "groundY": 254.74, + "roofY": 267.98, + "wallCount": 64, + "roofCount": 33 + }, + { + "id": "sion_0217", + "uuid": "{6CE1ADB7-77EB-4E24-9044-114678160C3F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -777.029, + 22.21, + 109.811 + ], + "size": [ + 28.441, + 22.177, + 33.31 + ], + "groundY": 11.122, + "roofY": 33.298, + "wallCount": 11, + "roofCount": 38 + }, + { + "id": "sion_0218", + "uuid": "{4BA816FE-AB15-4189-9E19-5FF783F580A6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1086.428, + 294.675, + -1203.276 + ], + "size": [ + 19.551, + 11.528, + 14.388 + ], + "groundY": 288.911, + "roofY": 300.439, + "wallCount": 30, + "roofCount": 13 + }, + { + "id": "sion_0219", + "uuid": "{5869D8D7-06F9-4D51-9146-D73021B94FA7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1233.873, + 17.322, + 135.467 + ], + "size": [ + 23.434, + 19.643, + 22.508 + ], + "groundY": 7.5, + "roofY": 27.143, + "wallCount": 29, + "roofCount": 16 + }, + { + "id": "sion_0220", + "uuid": "{E967A833-56EC-4135-9846-4656BBB2FFAE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -718.545, + 5.891, + 292.414 + ], + "size": [ + 20.691, + 15.634, + 17.285 + ], + "groundY": -1.926, + "roofY": 13.708, + "wallCount": 27, + "roofCount": 31 + }, + { + "id": "sion_0221", + "uuid": "{8BD82661-AB42-4003-9B24-962C118A0260}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -761.266, + 39.076, + -216.139 + ], + "size": [ + 17.656, + 15.701, + 17.235 + ], + "groundY": 31.226, + "roofY": 46.927, + "wallCount": 17, + "roofCount": 31 + }, + { + "id": "sion_0222", + "uuid": "{AF8D2C91-86FD-40DA-B4F2-362754E99BBD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1327.805, + -0.013, + 903.061 + ], + "size": [ + 10.625, + 5.864, + 10.332 + ], + "groundY": -2.945, + "roofY": 2.919, + "wallCount": 16, + "roofCount": 17 + }, + { + "id": "sion_0223", + "uuid": "{5BE6B44E-2A65-47E4-83B0-F61CCF8F3D93}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -536.473, + 12.817, + 403.02 + ], + "size": [ + 25.883, + 24.353, + 20.689 + ], + "groundY": 0.641, + "roofY": 24.994, + "wallCount": 23, + "roofCount": 18 + }, + { + "id": "sion_0224", + "uuid": "{A5894A51-50F9-4305-B3C3-40B417780A26}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -855.455, + 7.963, + 288.86 + ], + "size": [ + 27.144, + 20.697, + 19.588 + ], + "groundY": -2.385, + "roofY": 18.312, + "wallCount": 49, + "roofCount": 11 + }, + { + "id": "sion_0225", + "uuid": "{9116BC1F-3C2F-4F22-A04A-92D08DB122D5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1029.777, + 122.364, + -454.632 + ], + "size": [ + 22.266, + 10.47, + 20.479 + ], + "groundY": 117.129, + "roofY": 127.6, + "wallCount": 29, + "roofCount": 24 + }, + { + "id": "sion_0226", + "uuid": "{37B2B18A-8274-4F32-A328-543F9A9995ED}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -794.543, + 82.802, + -471.964 + ], + "size": [ + 30.945, + 16.242, + 29.676 + ], + "groundY": 74.681, + "roofY": 90.923, + "wallCount": 58, + "roofCount": 18 + }, + { + "id": "sion_0227", + "uuid": "{9DC0C62A-094F-47FF-AE9C-1B855A1916AE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -953.619, + 6.202, + 270.828 + ], + "size": [ + 17.246, + 17.54, + 17.176 + ], + "groundY": -2.568, + "roofY": 14.972, + "wallCount": 24, + "roofCount": 26 + }, + { + "id": "sion_0228", + "uuid": "{25A47FFC-4FEF-4A19-8615-638CBFE13B0C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -411.084, + 64.449, + -684.068 + ], + "size": [ + 23.598, + 16.774, + 23.528 + ], + "groundY": 56.062, + "roofY": 72.836, + "wallCount": 90, + "roofCount": 22 + }, + { + "id": "sion_0229", + "uuid": "{EFB6693E-8814-4133-895A-9945D95FD344}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1270.912, + 139.06, + -365.233 + ], + "size": [ + 17.582, + 6.198, + 14.468 + ], + "groundY": 135.961, + "roofY": 142.159, + "wallCount": 35, + "roofCount": 4 + }, + { + "id": "sion_0230", + "uuid": "{C2CB13CA-A1F7-4980-B0FD-415CC4B35BFD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1448.643, + 1.861, + 433.571 + ], + "size": [ + 16.34, + 11.987, + 17.464 + ], + "groundY": -4.133, + "roofY": 7.854, + "wallCount": 49, + "roofCount": 20 + }, + { + "id": "sion_0231", + "uuid": "{24BC1D02-4AB7-4250-B0F0-2B2E7DCA7371}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -710.059, + 26.577, + -81.035 + ], + "size": [ + 17.516, + 18.421, + 16.0 + ], + "groundY": 17.367, + "roofY": 35.788, + "wallCount": 26, + "roofCount": 14 + }, + { + "id": "sion_0232", + "uuid": "{5AD718A5-AF51-48DB-B0E8-0C471E7C4E9A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1062.904, + 8.682, + 418.11 + ], + "size": [ + 40.652, + 26.702, + 29.506 + ], + "groundY": -4.669, + "roofY": 22.033, + "wallCount": 154, + "roofCount": 40 + }, + { + "id": "sion_0233", + "uuid": "{A6D3784C-E484-40A7-A7A5-184436B09DA7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1274.328, + 290.285, + -1454.862 + ], + "size": [ + 7.953, + 5.433, + 8.574 + ], + "groundY": 287.569, + "roofY": 293.002, + "wallCount": 40, + "roofCount": 2 + }, + { + "id": "sion_0234", + "uuid": "{4C94EF15-BE3A-456C-86A5-B0C8F29092A4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1192.199, + 265.814, + -1022.714 + ], + "size": [ + 13.336, + 8.944, + 11.578 + ], + "groundY": 261.342, + "roofY": 270.286, + "wallCount": 43, + "roofCount": 4 + }, + { + "id": "sion_0235", + "uuid": "{DECB828C-5114-41D8-8D4D-F3BB49587887}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -506.061, + 22.04, + 154.902 + ], + "size": [ + 16.863, + 15.148, + 14.483 + ], + "groundY": 14.466, + "roofY": 29.614, + "wallCount": 63, + "roofCount": 67 + }, + { + "id": "sion_0236", + "uuid": "{3A5543A4-6281-48E9-B64B-FF5E179A5C6B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1165.549, + 59.64, + -36.395 + ], + "size": [ + 14.473, + 8.29, + 13.171 + ], + "groundY": 55.495, + "roofY": 63.785, + "wallCount": 19, + "roofCount": 2 + }, + { + "id": "sion_0237", + "uuid": "{A500D40E-C86B-4F04-8D46-8183271037CB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1465.73, + 271.549, + -969.107 + ], + "size": [ + 17.07, + 12.12, + 20.67 + ], + "groundY": 265.489, + "roofY": 277.609, + "wallCount": 27, + "roofCount": 16 + }, + { + "id": "sion_0238", + "uuid": "{BA658F9E-34A5-4DF2-8126-E979EEDDCBD5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1250.885, + 281.603, + -1101.811 + ], + "size": [ + 9.215, + 8.838, + 8.265 + ], + "groundY": 277.184, + "roofY": 286.022, + "wallCount": 49, + "roofCount": 25 + }, + { + "id": "sion_0239", + "uuid": "{8125B374-7F56-49CB-8A51-45D9A2B09828}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -628.047, + 74.023, + -561.127 + ], + "size": [ + 25.797, + 9.164, + 25.225 + ], + "groundY": 69.441, + "roofY": 78.605, + "wallCount": 24, + "roofCount": 13 + }, + { + "id": "sion_0240", + "uuid": "{6E00B9DC-C8A3-4EBA-BBB5-041EF8B2E20F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1233.572, + 280.391, + -1193.18 + ], + "size": [ + 13.559, + 11.614, + 20.988 + ], + "groundY": 274.584, + "roofY": 286.198, + "wallCount": 58, + "roofCount": 17 + }, + { + "id": "sion_0241", + "uuid": "{DF599715-1987-4AF0-8E3E-3B0484B3455C}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 1, + 2 + ], + "center": [ + -903.328, + 25.897, + -98.559 + ], + "size": [ + 23.086, + 19.49, + 21.832 + ], + "groundY": 16.152, + "roofY": 35.642, + "wallCount": 62, + "roofCount": 6 + }, + { + "id": "sion_0242", + "uuid": "{D02BE349-4B8A-42B3-8527-DA936D972411}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -926.795, + 1.713, + 310.216 + ], + "size": [ + 14.098, + 10.536, + 11.13 + ], + "groundY": -3.555, + "roofY": 6.981, + "wallCount": 34, + "roofCount": 18 + }, + { + "id": "sion_0243", + "uuid": "{FD5F07E1-6BE5-431B-B09F-C834C7983468}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1301.828, + 280.127, + -1159.754 + ], + "size": [ + 10.945, + 11.254, + 9.538 + ], + "groundY": 274.5, + "roofY": 285.754, + "wallCount": 63, + "roofCount": 33 + }, + { + "id": "sion_0244", + "uuid": "{1059F20F-F580-479F-9D23-6CD09FEA684E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -979.057, + 68.264, + -202.741 + ], + "size": [ + 19.832, + 14.549, + 21.614 + ], + "groundY": 60.989, + "roofY": 75.538, + "wallCount": 28, + "roofCount": 12 + }, + { + "id": "sion_0245", + "uuid": "{7102FCF4-FE81-4301-A2B4-F12ED74578AA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -471.141, + 14.866, + 417.904 + ], + "size": [ + 24.992, + 23.359, + 21.302 + ], + "groundY": 3.187, + "roofY": 26.545, + "wallCount": 39, + "roofCount": 23 + }, + { + "id": "sion_0246", + "uuid": "{C2BAAA6A-B32C-4041-AD51-BB9693A9BFFA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1198.475, + 281.589, + -1101.459 + ], + "size": [ + 13.957, + 13.544, + 16.172 + ], + "groundY": 274.817, + "roofY": 288.361, + "wallCount": 55, + "roofCount": 14 + }, + { + "id": "sion_0247", + "uuid": "{2FBB802F-7EC5-4142-A822-4BE3F393EAAE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1484.527, + 220.309, + -597.813 + ], + "size": [ + 16.242, + 8.798, + 15.782 + ], + "groundY": 215.91, + "roofY": 224.708, + "wallCount": 44, + "roofCount": 8 + }, + { + "id": "sion_0248", + "uuid": "{C80B65FD-0CB5-4829-8980-9D85397DCAFB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -450.139, + 42.555, + -309.975 + ], + "size": [ + 62.098, + 17.143, + 44.086 + ], + "groundY": 33.984, + "roofY": 51.127, + "wallCount": 22, + "roofCount": 34 + }, + { + "id": "sion_0249", + "uuid": "{A87BEE65-DD84-47AB-87CC-75F222534C3D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -931.127, + 3.192, + 273.124 + ], + "size": [ + 11.293, + 12.1, + 12.744 + ], + "groundY": -2.858, + "roofY": 9.242, + "wallCount": 45, + "roofCount": 34 + }, + { + "id": "sion_0250", + "uuid": "{3E3BE0FD-D3F9-4D37-8C57-7D18351318E7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1393.502, + 264.651, + -964.309 + ], + "size": [ + 18.317, + 10.711, + 23.767 + ], + "groundY": 259.296, + "roofY": 270.007, + "wallCount": 23, + "roofCount": 20 + }, + { + "id": "sion_0251", + "uuid": "{26284C98-DD05-4379-970E-1C25AD3D42E2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -630.721, + 64.536, + -533.091 + ], + "size": [ + 9.98, + 6.635, + 10.018 + ], + "groundY": 61.219, + "roofY": 67.854, + "wallCount": 22, + "roofCount": 10 + }, + { + "id": "sion_0252", + "uuid": "{866D913A-2B56-4636-BB93-8F006B678B0C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1196.652, + 2.299, + 1007.87 + ], + "size": [ + 41.047, + 9.808, + 25.252 + ], + "groundY": -2.605, + "roofY": 7.203, + "wallCount": 15, + "roofCount": 21 + }, + { + "id": "sion_0253", + "uuid": "{0787ED0C-A986-4ADA-A95A-677F5196F614}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1283.242, + 208.836, + -671.058 + ], + "size": [ + 14.367, + 9.734, + 13.323 + ], + "groundY": 203.969, + "roofY": 213.703, + "wallCount": 38, + "roofCount": 4 + }, + { + "id": "sion_0254", + "uuid": "{41E2B8A9-1740-4DFF-8403-EDC32831A713}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -705.959, + 21.539, + 185.152 + ], + "size": [ + 25.356, + 23.393, + 16.21 + ], + "groundY": 9.843, + "roofY": 33.236, + "wallCount": 12, + "roofCount": 39 + }, + { + "id": "sion_0255", + "uuid": "{72097DFC-282C-413B-97BC-6021D90A7BD1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -822.426, + 3.017, + 1024.016 + ], + "size": [ + 24.086, + 9.065, + 15.45 + ], + "groundY": -1.516, + "roofY": 7.549, + "wallCount": 12, + "roofCount": 17 + }, + { + "id": "sion_0256", + "uuid": "{9C84663F-D7E8-4102-AED2-22DA7BF35026}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -950.535, + 296.574, + -1247.761 + ], + "size": [ + 24.609, + 12.086, + 20.292 + ], + "groundY": 290.531, + "roofY": 302.617, + "wallCount": 21, + "roofCount": 13 + }, + { + "id": "sion_0257", + "uuid": "{EF519C76-9F9A-4E31-A319-C3A119C1B7EC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -966.125, + 92.361, + -321.49 + ], + "size": [ + 31.766, + 15.108, + 30.809 + ], + "groundY": 84.807, + "roofY": 99.915, + "wallCount": 61, + "roofCount": 26 + }, + { + "id": "sion_0258", + "uuid": "{D08DB01D-8E87-4035-80F0-C75822B6B8BF}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 2, + 3 + ], + "center": [ + -446.637, + 15.243, + 450.053 + ], + "size": [ + 22.352, + 25.294, + 22.273 + ], + "groundY": 2.596, + "roofY": 27.89, + "wallCount": 46, + "roofCount": 2 + }, + { + "id": "sion_0259", + "uuid": "{267F73D2-037A-4028-8E56-2DBF46B7527D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1413.602, + 277.732, + -1047.566 + ], + "size": [ + 19.086, + 10.566, + 16.33 + ], + "groundY": 272.449, + "roofY": 283.015, + "wallCount": 67, + "roofCount": 17 + }, + { + "id": "sion_0260", + "uuid": "{541E9277-07D6-4295-95E2-ECA31D88705C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -480.221, + 44.668, + -454.22 + ], + "size": [ + 17.207, + 5.413, + 18.972 + ], + "groundY": 41.961, + "roofY": 47.374, + "wallCount": 12, + "roofCount": 7 + }, + { + "id": "sion_0261", + "uuid": "{8142E6B4-AB3A-4324-816F-635C2E7B224D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -675.049, + 29.346, + -79.954 + ], + "size": [ + 41.316, + 23.703, + 49.008 + ], + "groundY": 17.495, + "roofY": 41.198, + "wallCount": 129, + "roofCount": 99 + }, + { + "id": "sion_0262", + "uuid": "{F6BEA10E-06CD-4552-A869-5E8D15898736}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1241.336, + 112.069, + -243.908 + ], + "size": [ + 36.188, + 11.28, + 27.816 + ], + "groundY": 106.429, + "roofY": 117.709, + "wallCount": 99, + "roofCount": 36 + }, + { + "id": "sion_0263", + "uuid": "{3A9F60D0-3DA6-44F3-9CE1-687386D10F25}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -450.174, + 7.421, + 597.481 + ], + "size": [ + 38.004, + 15.526, + 16.896 + ], + "groundY": -0.342, + "roofY": 15.184, + "wallCount": 54, + "roofCount": 61 + }, + { + "id": "sion_0264", + "uuid": "{F84B50AC-D224-46E3-B8DF-DFB478ED8D9F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1174.158, + 264.916, + -1027.583 + ], + "size": [ + 15.16, + 9.348, + 10.389 + ], + "groundY": 260.242, + "roofY": 269.59, + "wallCount": 48, + "roofCount": 4 + }, + { + "id": "sion_0265", + "uuid": "{B2CFEE32-DFAD-4B6B-8FD3-B55155555A58}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -997.514, + 76.483, + -250.241 + ], + "size": [ + 18.332, + 10.083, + 15.27 + ], + "groundY": 71.442, + "roofY": 81.525, + "wallCount": 48, + "roofCount": 42 + }, + { + "id": "sion_0266", + "uuid": "{9CBE3754-B4FD-4D9A-B007-513E26D18571}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -725.709, + 26.207, + 23.326 + ], + "size": [ + 124.902, + 25.961, + 120.868 + ], + "groundY": 13.227, + "roofY": 39.188, + "wallCount": 206, + "roofCount": 143 + }, + { + "id": "sion_0267", + "uuid": "{47272D6D-9C9C-4E0E-8A6A-075C944B61CF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1356.883, + 267.238, + -992.541 + ], + "size": [ + 19.109, + 8.886, + 21.297 + ], + "groundY": 262.795, + "roofY": 271.681, + "wallCount": 47, + "roofCount": 8 + }, + { + "id": "sion_0268", + "uuid": "{A28BFE86-C0B6-495A-BA0E-4AB7D4F13591}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -812.482, + 202.133, + -886.072 + ], + "size": [ + 21.449, + 8.575, + 25.428 + ], + "groundY": 197.846, + "roofY": 206.421, + "wallCount": 31, + "roofCount": 21 + }, + { + "id": "sion_0269", + "uuid": "{1CDB162E-02A0-4ECA-ABB6-1233E7685D0B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1068.611, + 270.031, + -1000.735 + ], + "size": [ + 15.941, + 12.425, + 22.798 + ], + "groundY": 263.819, + "roofY": 276.244, + "wallCount": 38, + "roofCount": 16 + }, + { + "id": "sion_0270", + "uuid": "{0D273878-AF29-456E-A0C2-6FBF0074E2E3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1216.455, + 295.689, + -1419.617 + ], + "size": [ + 16.559, + 12.144, + 15.908 + ], + "groundY": 289.617, + "roofY": 301.761, + "wallCount": 48, + "roofCount": 23 + }, + { + "id": "sion_0271", + "uuid": "{E99C6A4F-B04F-4737-BC39-F2104A640829}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -707.41, + 16.131, + 237.596 + ], + "size": [ + 23.195, + 18.43, + 19.59 + ], + "groundY": 6.916, + "roofY": 25.346, + "wallCount": 47, + "roofCount": 28 + }, + { + "id": "sion_0272", + "uuid": "{CF2A99EC-6A68-4AA5-8530-99D133FEF859}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -971.996, + 103.363, + -451.383 + ], + "size": [ + 15.703, + 11.152, + 17.876 + ], + "groundY": 97.787, + "roofY": 108.938, + "wallCount": 36, + "roofCount": 10 + }, + { + "id": "sion_0273", + "uuid": "{EEC3CFD9-8873-4740-8A17-57D951FD6597}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -428.566, + 51.295, + -582.397 + ], + "size": [ + 40.25, + 7.658, + 79.442 + ], + "groundY": 47.466, + "roofY": 55.124, + "wallCount": 36, + "roofCount": 10 + }, + { + "id": "sion_0274", + "uuid": "{E1EE99F1-D3DD-4C6E-A9A2-C2D0D58CF062}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1514.396, + 273.177, + -1369.49 + ], + "size": [ + 18.348, + 7.729, + 8.662 + ], + "groundY": 269.313, + "roofY": 277.042, + "wallCount": 34, + "roofCount": 18 + }, + { + "id": "sion_0275", + "uuid": "{D6AE1251-5095-4744-9C02-2A26550B27B6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1169.908, + 263.425, + -957.449 + ], + "size": [ + 15.129, + 10.738, + 13.878 + ], + "groundY": 258.056, + "roofY": 268.794, + "wallCount": 34, + "roofCount": 4 + }, + { + "id": "sion_0276", + "uuid": "{64A7D940-E35A-4DD8-8128-884182440624}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -641.33, + 117.956, + -763.645 + ], + "size": [ + 14.629, + 9.976, + 14.668 + ], + "groundY": 112.968, + "roofY": 122.944, + "wallCount": 27, + "roofCount": 12 + }, + { + "id": "sion_0277", + "uuid": "{F43BA7F9-FA93-4277-A2AF-0033A09F03CC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -686.297, + 38.57, + -262.664 + ], + "size": [ + 24.484, + 13.569, + 17.958 + ], + "groundY": 31.785, + "roofY": 45.354, + "wallCount": 34, + "roofCount": 45 + }, + { + "id": "sion_0278", + "uuid": "{6BCB49AD-B7EE-4543-A9DF-A064BF6A707B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -1019.76, + 15.4, + -32.154 + ], + "size": [ + 30.363, + 4.94, + 23.572 + ], + "groundY": 12.93, + "roofY": 17.87, + "wallCount": 14, + "roofCount": 2 + }, + { + "id": "sion_0279", + "uuid": "{F89EE1E6-8A48-4CC3-82C6-5A0EFAC65CB0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 3 + ], + "center": [ + -506.082, + 24.269, + 180.338 + ], + "size": [ + 52.719, + 23.144, + 33.156 + ], + "groundY": 12.697, + "roofY": 35.841, + "wallCount": 75, + "roofCount": 25 + }, + { + "id": "sion_0280", + "uuid": "{19257C1E-6404-4B60-8C5B-FDA2EB155B46}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1426.375, + 69.57, + 36.204 + ], + "size": [ + 6.195, + 5.44, + 7.41 + ], + "groundY": 66.85, + "roofY": 72.29, + "wallCount": 25, + "roofCount": 18 + }, + { + "id": "sion_0281", + "uuid": "{514A3F48-A3B7-4FC9-BEA0-50C895135B41}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1385.4, + 200.526, + -513.273 + ], + "size": [ + 9.91, + 6.184, + 8.8 + ], + "groundY": 197.434, + "roofY": 203.618, + "wallCount": 31, + "roofCount": 8 + }, + { + "id": "sion_0282", + "uuid": "{B16A37C3-83E3-4EB5-A2DA-4849AA833F8D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -757.338, + 91.662, + -511.424 + ], + "size": [ + 40.715, + 6.548, + 30.128 + ], + "groundY": 88.388, + "roofY": 94.936, + "wallCount": 20, + "roofCount": 8 + }, + { + "id": "sion_0283", + "uuid": "{641D09D7-532D-40D6-8F71-7E54D0ECE6F7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1318.715, + 279.211, + -1140.036 + ], + "size": [ + 7.711, + 7.774, + 8.611 + ], + "groundY": 275.324, + "roofY": 283.098, + "wallCount": 47, + "roofCount": 15 + }, + { + "id": "sion_0284", + "uuid": "{D2620514-C4A9-4390-B7E7-DC4D989BE8E0}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 0, + 1 + ], + "center": [ + -1342.74, + 235.67, + -801.477 + ], + "size": [ + 17.043, + 10.366, + 22.11 + ], + "groundY": 230.487, + "roofY": 240.853, + "wallCount": 41, + "roofCount": 9 + }, + { + "id": "sion_0285", + "uuid": "{E0BDC2A5-36E7-4C09-B193-C20EB358669E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -714.295, + 6.842, + 804.634 + ], + "size": [ + 19.652, + 15.292, + 28.472 + ], + "groundY": -0.804, + "roofY": 14.488, + "wallCount": 29, + "roofCount": 4 + }, + { + "id": "sion_0286", + "uuid": "{1B97B77F-D133-4733-9B81-60DFA575F149}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -931.076, + 9.983, + 197.144 + ], + "size": [ + 33.09, + 20.841, + 22.614 + ], + "groundY": -0.438, + "roofY": 20.403, + "wallCount": 26, + "roofCount": 42 + }, + { + "id": "sion_0287", + "uuid": "{9A4FA64B-1FF8-4F91-A177-9A800AD7CE30}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1166.356, + 287.15, + -1151.525 + ], + "size": [ + 19.0, + 12.662, + 23.989 + ], + "groundY": 280.819, + "roofY": 293.481, + "wallCount": 70, + "roofCount": 27 + }, + { + "id": "sion_0288", + "uuid": "{28A3BDD9-87B2-41C2-9997-222D1F38D85C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1221.389, + 10.269, + 230.025 + ], + "size": [ + 69.793, + 22.393, + 59.338 + ], + "groundY": -0.927, + "roofY": 21.466, + "wallCount": 141, + "roofCount": 141 + }, + { + "id": "sion_0289", + "uuid": "{EA1BDF6C-062A-4D91-BC8E-17C4C45C908C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1098.572, + 239.258, + -862.08 + ], + "size": [ + 9.527, + 5.253, + 8.637 + ], + "groundY": 236.631, + "roofY": 241.884, + "wallCount": 26, + "roofCount": 6 + }, + { + "id": "sion_0290", + "uuid": "{BF7DC762-6488-48AB-BD7A-6BAF4069C5A1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1306.172, + 258.134, + -958.112 + ], + "size": [ + 20.078, + 11.414, + 12.176 + ], + "groundY": 252.427, + "roofY": 263.841, + "wallCount": 36, + "roofCount": 17 + }, + { + "id": "sion_0291", + "uuid": "{6DD7BCD0-031D-468A-94F9-3DD4DAD5ADA4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1174.242, + 264.992, + -1006.945 + ], + "size": [ + 22.344, + 10.122, + 10.258 + ], + "groundY": 259.931, + "roofY": 270.053, + "wallCount": 42, + "roofCount": 14 + }, + { + "id": "sion_0292", + "uuid": "{F16D66B1-CD39-4B28-A890-3C61BAB81551}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -987.5, + 297.589, + -1232.425 + ], + "size": [ + 15.531, + 11.381, + 14.92 + ], + "groundY": 291.898, + "roofY": 303.279, + "wallCount": 34, + "roofCount": 23 + }, + { + "id": "sion_0293", + "uuid": "{1CA7A4C6-3351-491E-B748-53CFD518937D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1030.643, + 294.078, + -1390.203 + ], + "size": [ + 13.473, + 10.168, + 22.008 + ], + "groundY": 288.994, + "roofY": 299.162, + "wallCount": 71, + "roofCount": 19 + }, + { + "id": "sion_0294", + "uuid": "{49C6B3A9-0301-4720-9508-E9159269F5FA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -538.982, + 20.264, + 202.062 + ], + "size": [ + 15.223, + 16.444, + 13.964 + ], + "groundY": 12.042, + "roofY": 28.486, + "wallCount": 29, + "roofCount": 46 + }, + { + "id": "sion_0295", + "uuid": "{0E7AA7BB-02DF-4418-B639-220E855898EE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -864.051, + 18.266, + 70.922 + ], + "size": [ + 20.461, + 17.356, + 18.418 + ], + "groundY": 9.588, + "roofY": 26.944, + "wallCount": 29, + "roofCount": 13 + }, + { + "id": "sion_0296", + "uuid": "{DC695CD7-500B-47C1-88B8-D1A82C15C614}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -891.703, + 292.243, + -1270.027 + ], + "size": [ + 16.133, + 11.145, + 17.466 + ], + "groundY": 286.671, + "roofY": 297.816, + "wallCount": 38, + "roofCount": 13 + }, + { + "id": "sion_0297", + "uuid": "{2EF57DE8-339C-4336-A96B-364D88D466A6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1476.088, + 266.103, + -953.064 + ], + "size": [ + 10.574, + 7.368, + 14.091 + ], + "groundY": 262.419, + "roofY": 269.787, + "wallCount": 58, + "roofCount": 8 + }, + { + "id": "sion_0298", + "uuid": "{CEBA34A6-233C-44CF-B7E6-FE5D33310B73}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -461.307, + 70.369, + -677.361 + ], + "size": [ + 23.035, + 16.371, + 24.082 + ], + "groundY": 62.184, + "roofY": 78.555, + "wallCount": 40, + "roofCount": 38 + }, + { + "id": "sion_0299", + "uuid": "{995AEFF8-AD42-4478-8961-C6237767570C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1389.844, + 283.012, + -1096.898 + ], + "size": [ + 17.695, + 9.341, + 18.233 + ], + "groundY": 278.342, + "roofY": 287.683, + "wallCount": 50, + "roofCount": 22 + }, + { + "id": "sion_0300", + "uuid": "{2D8CAB2D-F62E-4EC9-9773-2C1863C4AD87}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1530.893, + 159.33, + -342.285 + ], + "size": [ + 16.809, + 10.273, + 15.83 + ], + "groundY": 154.194, + "roofY": 164.467, + "wallCount": 51, + "roofCount": 14 + }, + { + "id": "sion_0301", + "uuid": "{DE3EA44A-D8A7-4C2F-B37A-AABA9EDF640D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1274.453, + 280.279, + -1090.632 + ], + "size": [ + 16.258, + 12.216, + 20.706 + ], + "groundY": 274.171, + "roofY": 286.387, + "wallCount": 53, + "roofCount": 25 + }, + { + "id": "sion_0302", + "uuid": "{8D0C160E-4D85-4188-8EC7-F62518853451}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -1010.328, + 2.588, + 270.212 + ], + "size": [ + 13.047, + 11.416, + 12.686 + ], + "groundY": -3.12, + "roofY": 8.296, + "wallCount": 32, + "roofCount": 18 + }, + { + "id": "sion_0303", + "uuid": "{93A2BA0B-F5D4-420A-ABE9-99889A864CDD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -901.098, + 96.42, + -434.716 + ], + "size": [ + 74.922, + 20.954, + 64.414 + ], + "groundY": 85.943, + "roofY": 106.897, + "wallCount": 46, + "roofCount": 34 + }, + { + "id": "sion_0304", + "uuid": "{8E71BF34-7F6A-4228-9CBC-65E3EBA908B1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1133.031, + 6.538, + 271.585 + ], + "size": [ + 22.5, + 18.251, + 32.902 + ], + "groundY": -2.587, + "roofY": 15.664, + "wallCount": 15, + "roofCount": 24 + }, + { + "id": "sion_0305", + "uuid": "{BF770524-302B-4300-A3EF-61B9250E8599}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1117.654, + 63.76, + -105.134 + ], + "size": [ + 116.082, + 23.226, + 46.07 + ], + "groundY": 52.147, + "roofY": 75.373, + "wallCount": 191, + "roofCount": 59 + }, + { + "id": "sion_0306", + "uuid": "{AAE57953-7297-42C4-9697-D8C9F41B1DC5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1276.66, + 280.492, + -1133.03 + ], + "size": [ + 11.352, + 9.768, + 21.198 + ], + "groundY": 275.608, + "roofY": 285.376, + "wallCount": 61, + "roofCount": 37 + }, + { + "id": "sion_0307", + "uuid": "{86D5DD53-37FA-4100-ACB4-CAFE59584CC6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -761.881, + 2.25, + 525.677 + ], + "size": [ + 65.394, + 7.507, + 92.6 + ], + "groundY": -1.504, + "roofY": 6.003, + "wallCount": 61, + "roofCount": 23 + }, + { + "id": "sion_0308", + "uuid": "{B63D265C-238C-42F9-950F-C6EAD2EB4406}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -609.707, + 58.579, + -497.97 + ], + "size": [ + 14.609, + 8.476, + 14.834 + ], + "groundY": 54.341, + "roofY": 62.817, + "wallCount": 47, + "roofCount": 4 + }, + { + "id": "sion_0309", + "uuid": "{3AD35B2C-8529-4B74-8A4C-4DB5E6135419}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -489.945, + 9.47, + 419.831 + ], + "size": [ + 18.094, + 13.42, + 21.144 + ], + "groundY": 2.76, + "roofY": 16.18, + "wallCount": 56, + "roofCount": 24 + }, + { + "id": "sion_0310", + "uuid": "{23FFB907-C1D0-4A50-8443-24610E637999}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1292.549, + 146.056, + -386.07 + ], + "size": [ + 26.879, + 10.026, + 19.654 + ], + "groundY": 141.043, + "roofY": 151.069, + "wallCount": 36, + "roofCount": 9 + }, + { + "id": "sion_0311", + "uuid": "{B248A929-0A91-4AB4-AF9A-964C369D5DD9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -707.098, + 18.767, + 208.741 + ], + "size": [ + 23.531, + 19.864, + 14.052 + ], + "groundY": 8.835, + "roofY": 28.699, + "wallCount": 26, + "roofCount": 17 + }, + { + "id": "sion_0312", + "uuid": "{FE769E9A-219C-4970-AA89-2DEB83A4E478}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1144.287, + 13.286, + 113.455 + ], + "size": [ + 26.785, + 16.582, + 24.598 + ], + "groundY": 4.995, + "roofY": 21.577, + "wallCount": 21, + "roofCount": 15 + }, + { + "id": "sion_0313", + "uuid": "{199BA417-D217-4E16-BD58-6128286047B5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1492.643, + 276.7, + -1169.845 + ], + "size": [ + 17.754, + 11.459, + 15.03 + ], + "groundY": 270.97, + "roofY": 282.429, + "wallCount": 54, + "roofCount": 19 + }, + { + "id": "sion_0314", + "uuid": "{C9EF25A8-9B2D-476B-9322-B295C8D2F26A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1283.785, + 203.298, + -565.133 + ], + "size": [ + 16.328, + 10.104, + 19.234 + ], + "groundY": 198.246, + "roofY": 208.35, + "wallCount": 27, + "roofCount": 12 + }, + { + "id": "sion_0315", + "uuid": "{678C1E47-58CD-418B-9E6A-115CB3071BAC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1050.752, + 49.046, + -105.638 + ], + "size": [ + 14.465, + 11.232, + 14.37 + ], + "groundY": 43.43, + "roofY": 54.662, + "wallCount": 52, + "roofCount": 16 + }, + { + "id": "sion_0316", + "uuid": "{B398AD7F-FF7C-4B5D-BD37-2900A03B2739}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -622.449, + 27.16, + 42.828 + ], + "size": [ + 24.195, + 22.216, + 25.184 + ], + "groundY": 16.052, + "roofY": 38.268, + "wallCount": 134, + "roofCount": 31 + }, + { + "id": "sion_0317", + "uuid": "{EDB1890A-0BC4-41C1-8F15-3DEE4EAFE223}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -411.373, + 70.168, + -774.702 + ], + "size": [ + 16.434, + 11.933, + 17.08 + ], + "groundY": 64.202, + "roofY": 76.135, + "wallCount": 44, + "roofCount": 24 + }, + { + "id": "sion_0318", + "uuid": "{464BC89B-2290-411F-BF79-A651D56D7018}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -694.803, + 24.41, + 128.261 + ], + "size": [ + 58.996, + 26.37, + 45.12 + ], + "groundY": 11.225, + "roofY": 37.595, + "wallCount": 23, + "roofCount": 15 + }, + { + "id": "sion_0319", + "uuid": "{9A94CCD6-ED83-4778-A941-33AA199182B7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -474.301, + 81.362, + -794.656 + ], + "size": [ + 21.414, + 11.394, + 20.074 + ], + "groundY": 75.665, + "roofY": 87.059, + "wallCount": 75, + "roofCount": 37 + }, + { + "id": "sion_0320", + "uuid": "{967E62E7-D9FE-4C03-9030-E556FFBDCB2D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -631.701, + 88.597, + -682.259 + ], + "size": [ + 23.887, + 12.694, + 27.198 + ], + "groundY": 82.25, + "roofY": 94.944, + "wallCount": 29, + "roofCount": 4 + }, + { + "id": "sion_0321", + "uuid": "{CB2B064A-3E09-44CC-9710-8B8F98E10D4B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -894.353, + 296.049, + -1473.438 + ], + "size": [ + 16.77, + 10.791, + 25.118 + ], + "groundY": 290.654, + "roofY": 301.445, + "wallCount": 33, + "roofCount": 14 + }, + { + "id": "sion_0322", + "uuid": "{672FA8B4-37FA-45DC-945B-6AC0609CB276}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1032.184, + 4.479, + 245.618 + ], + "size": [ + 18.164, + 12.779, + 11.594 + ], + "groundY": -1.91, + "roofY": 10.869, + "wallCount": 16, + "roofCount": 31 + }, + { + "id": "sion_0323", + "uuid": "{A2170063-66B9-48EB-91C9-3C8377B2B76F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -501.695, + 35.898, + -147.707 + ], + "size": [ + 22.359, + 15.283, + 22.746 + ], + "groundY": 28.257, + "roofY": 43.54, + "wallCount": 10, + "roofCount": 34 + }, + { + "id": "sion_0324", + "uuid": "{4CA7A693-B2EB-447D-8B56-0C3C1572D603}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1316.285, + 285.434, + -1307.145 + ], + "size": [ + 27.547, + 15.562, + 21.12 + ], + "groundY": 277.653, + "roofY": 293.215, + "wallCount": 59, + "roofCount": 31 + }, + { + "id": "sion_0325", + "uuid": "{6D7E356F-9F57-43F6-913F-F5A9B29F6ADA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1171.078, + 3.929, + 1014.128 + ], + "size": [ + 85.0, + 13.018, + 66.986 + ], + "groundY": -2.58, + "roofY": 10.438, + "wallCount": 29, + "roofCount": 29 + }, + { + "id": "sion_0326", + "uuid": "{EEC9C27D-3840-45B9-B905-54E0FCF0A29B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -720.615, + 295.455, + -1217.882 + ], + "size": [ + 23.949, + 14.556, + 22.441 + ], + "groundY": 288.177, + "roofY": 302.733, + "wallCount": 23, + "roofCount": 10 + }, + { + "id": "sion_0327", + "uuid": "{19AF82DD-C84D-4063-B205-01B2C4FB27E5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -464.594, + 56.358, + -575.055 + ], + "size": [ + 33.984, + 18.336, + 34.36 + ], + "groundY": 47.19, + "roofY": 65.526, + "wallCount": 109, + "roofCount": 47 + }, + { + "id": "sion_0328", + "uuid": "{2800718A-69A8-4463-AC75-EA419C6A8550}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -750.17, + 1.078, + 1033.381 + ], + "size": [ + 25.606, + 4.984, + 11.025 + ], + "groundY": -1.414, + "roofY": 3.57, + "wallCount": 28, + "roofCount": 29 + }, + { + "id": "sion_0329", + "uuid": "{81B055AE-FC4F-4AF6-8DB9-97896B452CD0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1235.834, + 3.652, + 726.516 + ], + "size": [ + 24.973, + 12.974, + 24.569 + ], + "groundY": -2.835, + "roofY": 10.139, + "wallCount": 123, + "roofCount": 26 + }, + { + "id": "sion_0330", + "uuid": "{0BFE095B-2D3D-4737-AFA4-459186E6DDC9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -553.902, + 29.236, + 15.553 + ], + "size": [ + 34.523, + 22.967, + 23.618 + ], + "groundY": 17.753, + "roofY": 40.719, + "wallCount": 11, + "roofCount": 7 + }, + { + "id": "sion_0331", + "uuid": "{10CAE089-8C0C-4703-BC2C-D07B7657D97E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1210.637, + 281.923, + -1114.543 + ], + "size": [ + 21.797, + 9.746, + 17.234 + ], + "groundY": 277.05, + "roofY": 286.796, + "wallCount": 49, + "roofCount": 20 + }, + { + "id": "sion_0332", + "uuid": "{05910818-B8BE-4C48-A662-0A4FA3A6D0D4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1453.922, + 71.227, + 178.093 + ], + "size": [ + 20.859, + 11.208, + 20.352 + ], + "groundY": 65.623, + "roofY": 76.831, + "wallCount": 32, + "roofCount": 12 + }, + { + "id": "sion_0333", + "uuid": "{F3BA78BB-F982-4D3C-B9EE-21166795734A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1225.76, + -0.318, + 692.544 + ], + "size": [ + 9.613, + 4.966, + 15.693 + ], + "groundY": -2.801, + "roofY": 2.165, + "wallCount": 18, + "roofCount": 2 + }, + { + "id": "sion_0334", + "uuid": "{5088C5CF-7D0E-4C24-B080-2DB6936E94D5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -607.705, + 66.61, + -544.275 + ], + "size": [ + 20.941, + 13.799, + 20.548 + ], + "groundY": 59.71, + "roofY": 73.509, + "wallCount": 14, + "roofCount": 10 + }, + { + "id": "sion_0335", + "uuid": "{6C009759-EED2-49A4-ADE8-77C0F1E441C3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1409.705, + 3.137, + 739.389 + ], + "size": [ + 49.394, + 13.516, + 96.485 + ], + "groundY": -3.621, + "roofY": 9.895, + "wallCount": 56, + "roofCount": 41 + }, + { + "id": "sion_0336", + "uuid": "{6B5DFDF6-D5BF-4CEC-82AC-BBA08C7099C2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1441.1, + 100.391, + -129.624 + ], + "size": [ + 17.246, + 10.352, + 17.06 + ], + "groundY": 95.215, + "roofY": 105.567, + "wallCount": 65, + "roofCount": 12 + }, + { + "id": "sion_0337", + "uuid": "{16994336-313D-4ED0-8F22-36A17C7063A8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -649.123, + 26.018, + 110.678 + ], + "size": [ + 22.395, + 24.699, + 36.308 + ], + "groundY": 13.669, + "roofY": 38.368, + "wallCount": 25, + "roofCount": 18 + }, + { + "id": "sion_0338", + "uuid": "{540A80D3-9EC0-483C-A9E6-7DCB92566E5D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -985.055, + 5.146, + 491.583 + ], + "size": [ + 71.594, + 15.947, + 53.809 + ], + "groundY": -2.827, + "roofY": 13.12, + "wallCount": 108, + "roofCount": 66 + }, + { + "id": "sion_0339", + "uuid": "{8266670C-1E3D-4846-BA81-E446AAA5B764}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -489.74, + 22.96, + 224.686 + ], + "size": [ + 21.691, + 22.063, + 18.958 + ], + "groundY": 11.929, + "roofY": 33.992, + "wallCount": 49, + "roofCount": 24 + }, + { + "id": "sion_0340", + "uuid": "{299FD68C-10C8-4FB5-BC72-4671319694CF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -505.482, + 20.726, + 270.259 + ], + "size": [ + 67.809, + 24.534, + 29.622 + ], + "groundY": 8.459, + "roofY": 32.993, + "wallCount": 49, + "roofCount": 21 + }, + { + "id": "sion_0341", + "uuid": "{3429A046-C4E5-4AEA-8786-9B99BB88EF13}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -542.689, + 4.378, + 799.911 + ], + "size": [ + 34.449, + 10.888, + 20.361 + ], + "groundY": -1.066, + "roofY": 9.822, + "wallCount": 48, + "roofCount": 22 + }, + { + "id": "sion_0342", + "uuid": "{56B1395C-528F-4B86-ABDB-805B7535A70F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1218.178, + 118.375, + -335.542 + ], + "size": [ + 9.902, + 8.698, + 16.355 + ], + "groundY": 114.026, + "roofY": 122.724, + "wallCount": 43, + "roofCount": 2 + }, + { + "id": "sion_0343", + "uuid": "{FE331CD3-9B8C-437F-8B0A-C4D81FFC3798}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1447.051, + 11.522, + 507.68 + ], + "size": [ + 25.875, + 28.534, + 19.666 + ], + "groundY": -2.745, + "roofY": 25.789, + "wallCount": 102, + "roofCount": 10 + }, + { + "id": "sion_0344", + "uuid": "{9F47EA75-20F1-45A8-B06B-A69FD0C22C6A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1071.59, + 294.0, + -1205.91 + ], + "size": [ + 9.203, + 8.183, + 8.578 + ], + "groundY": 289.909, + "roofY": 298.091, + "wallCount": 60, + "roofCount": 14 + }, + { + "id": "sion_0345", + "uuid": "{B213214F-5A94-4511-8FBE-14C02752F055}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -748.814, + 16.713, + 177.022 + ], + "size": [ + 10.152, + 13.878, + 9.726 + ], + "groundY": 9.774, + "roofY": 23.651, + "wallCount": 29, + "roofCount": 30 + }, + { + "id": "sion_0346", + "uuid": "{D6FEAE5E-7780-44C4-8689-FF7030E984E7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 2 + ], + "center": [ + -769.395, + 28.657, + -89.082 + ], + "size": [ + 27.727, + 20.246, + 27.484 + ], + "groundY": 18.534, + "roofY": 38.78, + "wallCount": 47, + "roofCount": 22 + }, + { + "id": "sion_0347", + "uuid": "{4CCBE34D-E6F5-414D-A5DB-315BA8708200}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1063.219, + 83.402, + -239.605 + ], + "size": [ + 24.594, + 13.56, + 18.208 + ], + "groundY": 76.622, + "roofY": 90.182, + "wallCount": 81, + "roofCount": 21 + }, + { + "id": "sion_0348", + "uuid": "{37F207D5-5F16-4873-8197-152BDB8CA030}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1206.896, + 56.617, + 16.279 + ], + "size": [ + 18.754, + 7.246, + 14.344 + ], + "groundY": 52.994, + "roofY": 60.24, + "wallCount": 31, + "roofCount": 6 + }, + { + "id": "sion_0349", + "uuid": "{4E9B75E7-9EBE-4DD6-B859-9A35DF3E80D1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -722.934, + 47.151, + -275.74 + ], + "size": [ + 19.883, + 12.025, + 18.864 + ], + "groundY": 41.138, + "roofY": 53.163, + "wallCount": 29, + "roofCount": 34 + }, + { + "id": "sion_0350", + "uuid": "{0E76A872-340C-4632-A14A-F7916164E1C3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -848.066, + 18.844, + 97.31 + ], + "size": [ + 35.797, + 18.568, + 16.774 + ], + "groundY": 9.56, + "roofY": 28.128, + "wallCount": 35, + "roofCount": 27 + }, + { + "id": "sion_0351", + "uuid": "{E331AC9A-C442-4A68-8362-852F4388B8B1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1341.463, + 288.902, + -1499.909 + ], + "size": [ + 28.145, + 10.793, + 24.582 + ], + "groundY": 283.506, + "roofY": 294.299, + "wallCount": 48, + "roofCount": 65 + }, + { + "id": "sion_0352", + "uuid": "{5AFE414F-CF8B-4D1C-8B78-E46042019D69}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1364.246, + 128.27, + -249.103 + ], + "size": [ + 8.727, + 7.303, + 8.229 + ], + "groundY": 124.619, + "roofY": 131.922, + "wallCount": 52, + "roofCount": 16 + }, + { + "id": "sion_0353", + "uuid": "{754314A2-256D-40C8-B3CF-4EF4879F0867}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -738.234, + 44.932, + -257.672 + ], + "size": [ + 18.766, + 10.916, + 19.266 + ], + "groundY": 39.474, + "roofY": 50.39, + "wallCount": 29, + "roofCount": 29 + }, + { + "id": "sion_0354", + "uuid": "{DD658A5D-F6A7-4861-ABC0-2BAA580F92B9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1035.918, + 92.817, + -303.739 + ], + "size": [ + 16.969, + 11.35, + 17.352 + ], + "groundY": 87.142, + "roofY": 98.492, + "wallCount": 39, + "roofCount": 24 + }, + { + "id": "sion_0355", + "uuid": "{6250F041-18FF-4D3E-9782-E694F1F91F4D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -974.666, + 78.091, + -273.489 + ], + "size": [ + 21.059, + 13.036, + 14.061 + ], + "groundY": 71.573, + "roofY": 84.609, + "wallCount": 131, + "roofCount": 72 + }, + { + "id": "sion_0356", + "uuid": "{1CDEEC8F-3319-48DF-BDD8-2C2B69F9B4EC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -872.143, + 294.364, + -1400.881 + ], + "size": [ + 18.754, + 11.93, + 17.18 + ], + "groundY": 288.399, + "roofY": 300.329, + "wallCount": 22, + "roofCount": 14 + }, + { + "id": "sion_0357", + "uuid": "{9CC72C7D-D75F-4159-9ACC-D90562328D18}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1397.281, + 8.204, + 614.315 + ], + "size": [ + 157.867, + 27.768, + 121.86 + ], + "groundY": -5.68, + "roofY": 22.088, + "wallCount": 300, + "roofCount": 126 + }, + { + "id": "sion_0358", + "uuid": "{98D964F5-D393-43CF-AB48-07C3EB6D1B23}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1071.301, + 293.861, + -1227.76 + ], + "size": [ + 22.102, + 12.9, + 17.356 + ], + "groundY": 287.411, + "roofY": 300.311, + "wallCount": 37, + "roofCount": 16 + }, + { + "id": "sion_0359", + "uuid": "{9CF39B8E-45EB-471F-87E2-F521FA73691D}", + "name": "", + "class": "Flugdach", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1194.012, + 5.559, + 887.951 + ], + "size": [ + 25.766, + 0.101, + 17.422 + ], + "groundY": 5.509, + "roofY": 5.609, + "wallCount": 1, + "roofCount": 2 + }, + { + "id": "sion_0360", + "uuid": "{92BB60A4-620C-488B-9B02-C11B50F181D1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1072.754, + 105.091, + -383.865 + ], + "size": [ + 33.523, + 16.74, + 29.38 + ], + "groundY": 96.721, + "roofY": 113.461, + "wallCount": 34, + "roofCount": 11 + }, + { + "id": "sion_0361", + "uuid": "{A34BE852-13F6-42CF-819A-FF9E766F2869}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1523.51, + 4.63, + 397.164 + ], + "size": [ + 43.254, + 14.66, + 25.162 + ], + "groundY": -2.7, + "roofY": 11.96, + "wallCount": 76, + "roofCount": 37 + }, + { + "id": "sion_0362", + "uuid": "{79D3D657-D70B-4695-A0F8-6D6E2DFBC583}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -929.203, + 110.619, + -496.283 + ], + "size": [ + 34.75, + 10.13, + 20.65 + ], + "groundY": 105.554, + "roofY": 115.684, + "wallCount": 41, + "roofCount": 10 + }, + { + "id": "sion_0363", + "uuid": "{D688A359-1500-46BD-ABE5-A6DB3AD6FF3F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1242.533, + 281.816, + -1223.224 + ], + "size": [ + 20.254, + 13.228, + 20.468 + ], + "groundY": 275.202, + "roofY": 288.43, + "wallCount": 64, + "roofCount": 43 + }, + { + "id": "sion_0364", + "uuid": "{6B723F75-FE6E-438D-99C4-6FD9F64EB771}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -762.137, + 296.081, + -1224.971 + ], + "size": [ + 21.844, + 18.545, + 27.356 + ], + "groundY": 286.808, + "roofY": 305.353, + "wallCount": 37, + "roofCount": 12 + }, + { + "id": "sion_0365", + "uuid": "{CDCE14DF-72AD-4F59-ABFB-7AC8E5515B26}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -650.01, + 21.865, + 194.918 + ], + "size": [ + 35.863, + 26.373, + 30.715 + ], + "groundY": 8.678, + "roofY": 35.051, + "wallCount": 32, + "roofCount": 24 + }, + { + "id": "sion_0366", + "uuid": "{97DDA14D-73E8-446B-B32F-D022F021AF37}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -984.457, + 19.233, + -34.148 + ], + "size": [ + 17.711, + 12.245, + 16.839 + ], + "groundY": 13.111, + "roofY": 25.356, + "wallCount": 33, + "roofCount": 22 + }, + { + "id": "sion_0367", + "uuid": "{B4CFA458-5F02-49F9-8B7F-F9B8524C9188}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1489.355, + 4.832, + 790.998 + ], + "size": [ + 48.984, + 16.061, + 45.863 + ], + "groundY": -3.198, + "roofY": 12.862, + "wallCount": 81, + "roofCount": 27 + }, + { + "id": "sion_0368", + "uuid": "{63F64C13-57CD-43D2-8B66-7BBB588A670F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1051.148, + 295.699, + -1205.449 + ], + "size": [ + 19.914, + 10.647, + 12.254 + ], + "groundY": 290.376, + "roofY": 301.023, + "wallCount": 25, + "roofCount": 34 + }, + { + "id": "sion_0369", + "uuid": "{5C6C0B5F-CB78-4446-A3DE-A8F394ABD347}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -741.008, + 25.435, + -47.818 + ], + "size": [ + 20.625, + 14.764, + 18.342 + ], + "groundY": 18.053, + "roofY": 32.817, + "wallCount": 37, + "roofCount": 40 + }, + { + "id": "sion_0370", + "uuid": "{47974D42-C9AC-4420-A1CC-3013C2F0B769}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1391.639, + 202.925, + -533.895 + ], + "size": [ + 23.043, + 8.657, + 18.481 + ], + "groundY": 198.596, + "roofY": 207.253, + "wallCount": 28, + "roofCount": 25 + }, + { + "id": "sion_0371", + "uuid": "{A9A85468-20DD-4D56-86D9-51FFCC1CD1AE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -793.973, + 0.78, + 473.036 + ], + "size": [ + 25.336, + 5.919, + 23.658 + ], + "groundY": -2.179, + "roofY": 3.74, + "wallCount": 31, + "roofCount": 10 + }, + { + "id": "sion_0372", + "uuid": "{3CBA95C7-CCEE-4EC9-B54F-62D2900EAEEC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -803.762, + 4.643, + 724.715 + ], + "size": [ + 120.07, + 12.306, + 87.723 + ], + "groundY": -1.51, + "roofY": 10.796, + "wallCount": 27, + "roofCount": 20 + }, + { + "id": "sion_0373", + "uuid": "{B76EA4BC-A6BC-425D-BB35-C5A60681B92B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1142.023, + 297.45, + -1468.123 + ], + "size": [ + 22.531, + 11.984, + 28.098 + ], + "groundY": 291.458, + "roofY": 303.442, + "wallCount": 53, + "roofCount": 37 + }, + { + "id": "sion_0374", + "uuid": "{EBDE2702-E283-49D8-BF76-81361EB7A788}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -726.205, + 35.908, + -218.88 + ], + "size": [ + 32.027, + 16.661, + 26.262 + ], + "groundY": 27.578, + "roofY": 44.239, + "wallCount": 57, + "roofCount": 43 + }, + { + "id": "sion_0375", + "uuid": "{2884628B-AB7D-49C3-BCD9-FE065C56D74D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1291.895, + 289.79, + -1448.338 + ], + "size": [ + 7.773, + 5.999, + 8.77 + ], + "groundY": 286.791, + "roofY": 292.79, + "wallCount": 56, + "roofCount": 4 + }, + { + "id": "sion_0376", + "uuid": "{551D3662-A89E-4C24-A942-98A2FB5575B5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -429.074, + 254.808, + -1493.823 + ], + "size": [ + 8.516, + 5.843, + 6.632 + ], + "groundY": 251.886, + "roofY": 257.729, + "wallCount": 21, + "roofCount": 10 + }, + { + "id": "sion_0377", + "uuid": "{B21770E4-A5FB-492E-8ACA-CE947C2244F4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -500.195, + 73.769, + -720.156 + ], + "size": [ + 27.672, + 7.518, + 33.936 + ], + "groundY": 70.01, + "roofY": 77.528, + "wallCount": 20, + "roofCount": 11 + }, + { + "id": "sion_0378", + "uuid": "{4141EA21-59F1-421D-AD71-49393C7CD49D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1364.166, + 2.155, + 315.013 + ], + "size": [ + 46.027, + 8.643, + 40.261 + ], + "groundY": -2.166, + "roofY": 6.477, + "wallCount": 45, + "roofCount": 52 + }, + { + "id": "sion_0379", + "uuid": "{BA7EE55C-73DE-4BE6-9DFA-E23830D88FD4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -1000.805, + 87.769, + -313.071 + ], + "size": [ + 18.062, + 12.046, + 14.53 + ], + "groundY": 81.746, + "roofY": 93.792, + "wallCount": 48, + "roofCount": 15 + }, + { + "id": "sion_0380", + "uuid": "{875728C5-85FE-4CAC-B947-7AE04A4C5F2C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -525.396, + 24.989, + -61.209 + ], + "size": [ + 14.434, + 4.934, + 11.236 + ], + "groundY": 22.522, + "roofY": 27.456, + "wallCount": 18, + "roofCount": 2 + }, + { + "id": "sion_0381", + "uuid": "{62314A83-5B91-4C63-BB44-E781621C5F31}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -838.67, + 22.669, + -8.336 + ], + "size": [ + 37.348, + 21.579, + 51.004 + ], + "groundY": 11.88, + "roofY": 33.459, + "wallCount": 26, + "roofCount": 14 + }, + { + "id": "sion_0382", + "uuid": "{0F563D93-48E0-4F79-B144-71D01E5626D6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -462.031, + 30.395, + 47.608 + ], + "size": [ + 89.805, + 29.907, + 87.548 + ], + "groundY": 15.442, + "roofY": 45.349, + "wallCount": 195, + "roofCount": 131 + }, + { + "id": "sion_0383", + "uuid": "{9FE56FCA-2A8F-45AB-A2AF-4B0DFFBF95C4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1203.16, + 105.609, + -268.094 + ], + "size": [ + 17.852, + 12.712, + 15.896 + ], + "groundY": 99.253, + "roofY": 111.965, + "wallCount": 70, + "roofCount": 28 + }, + { + "id": "sion_0384", + "uuid": "{8171221C-D6C1-428B-A1C3-B3626B029398}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1356.266, + 56.329, + 120.656 + ], + "size": [ + 16.656, + 9.67, + 19.626 + ], + "groundY": 51.494, + "roofY": 61.164, + "wallCount": 36, + "roofCount": 18 + }, + { + "id": "sion_0385", + "uuid": "{7E703A92-5249-4C54-9B25-09D8F68BEA66}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1447.605, + 280.397, + -1046.224 + ], + "size": [ + 25.078, + 11.91, + 20.79 + ], + "groundY": 274.442, + "roofY": 286.352, + "wallCount": 55, + "roofCount": 64 + }, + { + "id": "sion_0386", + "uuid": "{852DDA41-5BF0-4913-98D5-0539EA7BA654}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1081.475, + 289.159, + -1257.944 + ], + "size": [ + 12.207, + 9.72, + 9.41 + ], + "groundY": 284.299, + "roofY": 294.019, + "wallCount": 60, + "roofCount": 23 + }, + { + "id": "sion_0387", + "uuid": "{73F85D6D-2888-4D56-B47C-F4E8D72B5443}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -817.221, + 79.373, + -333.26 + ], + "size": [ + 20.879, + 14.602, + 21.212 + ], + "groundY": 72.072, + "roofY": 86.674, + "wallCount": 23, + "roofCount": 4 + }, + { + "id": "sion_0388", + "uuid": "{C07C26CB-9EF4-40F0-AB87-A4ED33E27E01}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1397.916, + 285.272, + -1300.493 + ], + "size": [ + 25.434, + 16.084, + 18.51 + ], + "groundY": 277.23, + "roofY": 293.314, + "wallCount": 29, + "roofCount": 30 + }, + { + "id": "sion_0389", + "uuid": "{4787E836-A7A6-4BD6-BE6C-B540EB15B4D7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1521.648, + 62.425, + 309.921 + ], + "size": [ + 8.289, + 7.714, + 8.031 + ], + "groundY": 58.568, + "roofY": 66.282, + "wallCount": 54, + "roofCount": 12 + }, + { + "id": "sion_0390", + "uuid": "{00AE8FBF-4D23-4354-8E6B-B8F23EFDB641}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1092.01, + 25.988, + -0.892 + ], + "size": [ + 44.301, + 20.132, + 34.854 + ], + "groundY": 15.922, + "roofY": 36.054, + "wallCount": 30, + "roofCount": 26 + }, + { + "id": "sion_0391", + "uuid": "{CF7698A2-847E-4880-A2D9-C6CCFCC7674F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1396.545, + 7.66, + 433.269 + ], + "size": [ + 65.488, + 22.202, + 34.356 + ], + "groundY": -3.441, + "roofY": 18.761, + "wallCount": 57, + "roofCount": 18 + }, + { + "id": "sion_0392", + "uuid": "{5967F1FB-E5E8-429B-A627-577584A5954D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1062.832, + 92.316, + -281.582 + ], + "size": [ + 32.367, + 11.078, + 21.332 + ], + "groundY": 86.777, + "roofY": 97.855, + "wallCount": 43, + "roofCount": 16 + }, + { + "id": "sion_0393", + "uuid": "{1D848C3A-CD25-4C83-82E9-23592DBE64F4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -836.559, + 18.118, + 164.643 + ], + "size": [ + 30.508, + 22.827, + 14.672 + ], + "groundY": 6.705, + "roofY": 29.532, + "wallCount": 44, + "roofCount": 42 + }, + { + "id": "sion_0394", + "uuid": "{D5CA51E1-F5FE-403C-8780-66FFE47B5DE4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -729.211, + 66.427, + -359.954 + ], + "size": [ + 17.32, + 13.828, + 16.434 + ], + "groundY": 59.513, + "roofY": 73.341, + "wallCount": 29, + "roofCount": 33 + }, + { + "id": "sion_0395", + "uuid": "{4B44F959-C77B-48BA-BAC8-9B8006033163}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1105.166, + 209.876, + -748.364 + ], + "size": [ + 14.848, + 9.48, + 14.672 + ], + "groundY": 205.136, + "roofY": 214.616, + "wallCount": 40, + "roofCount": 2 + }, + { + "id": "sion_0396", + "uuid": "{64A77B83-63DA-49CD-9B06-0ACF5ED4900B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1227.787, + 278.034, + -1076.297 + ], + "size": [ + 20.348, + 14.314, + 15.992 + ], + "groundY": 270.877, + "roofY": 285.191, + "wallCount": 34, + "roofCount": 23 + }, + { + "id": "sion_0397", + "uuid": "{1B1635C9-BFE2-433F-A3A1-1D4F0B6E7BEB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -562.693, + 21.212, + 267.213 + ], + "size": [ + 28.246, + 24.501, + 18.584 + ], + "groundY": 8.961, + "roofY": 33.462, + "wallCount": 32, + "roofCount": 28 + }, + { + "id": "sion_0398", + "uuid": "{1C94931B-6D98-423E-B1BD-68C050CBACAF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1279.766, + 3.722, + 822.089 + ], + "size": [ + 43.461, + 13.446, + 34.882 + ], + "groundY": -3.001, + "roofY": 10.445, + "wallCount": 14, + "roofCount": 2 + }, + { + "id": "sion_0399", + "uuid": "{7AB459CA-0199-4D33-9442-CE7220793DA6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -532.869, + 27.257, + 51.075 + ], + "size": [ + 17.66, + 24.269, + 19.906 + ], + "groundY": 15.122, + "roofY": 39.391, + "wallCount": 42, + "roofCount": 41 + }, + { + "id": "sion_0400", + "uuid": "{E80E7AF8-7FC6-4E48-8365-D2E46B4A3E01}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -920.27, + 96.035, + -326.975 + ], + "size": [ + 17.906, + 17.012, + 17.782 + ], + "groundY": 87.529, + "roofY": 104.541, + "wallCount": 43, + "roofCount": 35 + }, + { + "id": "sion_0401", + "uuid": "{5A63E535-0686-420F-B7C1-6189F4356938}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -456.686, + 5.228, + 950.75 + ], + "size": [ + 146.223, + 12.287, + 111.673 + ], + "groundY": -0.915, + "roofY": 11.372, + "wallCount": 16, + "roofCount": 29 + }, + { + "id": "sion_0402", + "uuid": "{837FA505-8CE3-45AE-8FF4-24542B08E0D4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1249.486, + 279.313, + -1073.354 + ], + "size": [ + 9.426, + 10.7, + 13.44 + ], + "groundY": 273.963, + "roofY": 284.663, + "wallCount": 47, + "roofCount": 19 + }, + { + "id": "sion_0403", + "uuid": "{86CECAA4-87DB-4972-A33C-E0DD017F425D}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1177.223, + 15.257, + 427.032 + ], + "size": [ + 69.086, + 37.698, + 48.224 + ], + "groundY": -3.592, + "roofY": 34.106, + "wallCount": 59, + "roofCount": 124 + }, + { + "id": "sion_0404", + "uuid": "{459A48B5-9EEF-495B-8614-B340609E2C1F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -705.654, + 63.776, + -454.878 + ], + "size": [ + 36.84, + 9.578, + 23.08 + ], + "groundY": 58.987, + "roofY": 68.565, + "wallCount": 51, + "roofCount": 22 + }, + { + "id": "sion_0405", + "uuid": "{413BA900-C7D9-4A2D-83DA-6DF8A04A8245}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1281.783, + -0.748, + 688.521 + ], + "size": [ + 13.09, + 5.116, + 24.81 + ], + "groundY": -3.306, + "roofY": 1.81, + "wallCount": 14, + "roofCount": 2 + }, + { + "id": "sion_0406", + "uuid": "{AB649AE7-EE30-4984-8B71-31415F965107}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -630.988, + 31.661, + -101.706 + ], + "size": [ + 37.32, + 21.48, + 53.486 + ], + "groundY": 20.921, + "roofY": 42.401, + "wallCount": 12, + "roofCount": 22 + }, + { + "id": "sion_0407", + "uuid": "{5C085679-4595-4CEC-B94B-39985C80DA30}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -712.014, + 11.415, + 271.52 + ], + "size": [ + 12.668, + 13.45, + 11.7 + ], + "groundY": 4.69, + "roofY": 18.139, + "wallCount": 62, + "roofCount": 18 + }, + { + "id": "sion_0408", + "uuid": "{0D674C64-ABDB-461B-8B43-65A838FFF4BF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1512.643, + 258.438, + -847.716 + ], + "size": [ + 24.684, + 10.419, + 17.54 + ], + "groundY": 253.229, + "roofY": 263.648, + "wallCount": 51, + "roofCount": 31 + }, + { + "id": "sion_0409", + "uuid": "{4A5C0A7B-74E3-406F-8502-87A3F098282E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1286.244, + 295.428, + -1528.455 + ], + "size": [ + 26.652, + 12.016, + 28.952 + ], + "groundY": 289.42, + "roofY": 301.436, + "wallCount": 52, + "roofCount": 29 + }, + { + "id": "sion_0410", + "uuid": "{7B856F92-5921-4C4F-9561-F651748A9299}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -594.189, + 8.574, + 549.967 + ], + "size": [ + 26.051, + 20.559, + 36.62 + ], + "groundY": -1.706, + "roofY": 18.853, + "wallCount": 39, + "roofCount": 53 + }, + { + "id": "sion_0411", + "uuid": "{3B03F95F-2BB0-4FDB-BFEB-74FB3A8DE266}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -1002.934, + 2.641, + 297.265 + ], + "size": [ + 13.078, + 11.954, + 11.681 + ], + "groundY": -3.336, + "roofY": 8.618, + "wallCount": 32, + "roofCount": 21 + }, + { + "id": "sion_0412", + "uuid": "{F882FD3E-70F1-4DDA-93F1-343A072427EE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1142.891, + 211.265, + -764.045 + ], + "size": [ + 18.703, + 8.879, + 15.162 + ], + "groundY": 206.826, + "roofY": 215.704, + "wallCount": 21, + "roofCount": 2 + }, + { + "id": "sion_0413", + "uuid": "{575AD71A-A1CE-4318-9ABB-CE1D7D89679E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -579.436, + 17.112, + 231.704 + ], + "size": [ + 12.754, + 13.148, + 11.604 + ], + "groundY": 10.538, + "roofY": 23.686, + "wallCount": 34, + "roofCount": 25 + }, + { + "id": "sion_0414", + "uuid": "{D88764F9-E411-469D-84E3-7CC0B21F0F01}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -913.408, + 295.284, + -1458.688 + ], + "size": [ + 10.879, + 7.442, + 12.079 + ], + "groundY": 291.563, + "roofY": 299.005, + "wallCount": 38, + "roofCount": 27 + }, + { + "id": "sion_0415", + "uuid": "{1CEDE183-9FE9-4AFC-8AAC-ED435E006133}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1121.471, + 0.006, + 516.769 + ], + "size": [ + 20.207, + 5.086, + 8.983 + ], + "groundY": -2.537, + "roofY": 2.549, + "wallCount": 20, + "roofCount": 6 + }, + { + "id": "sion_0416", + "uuid": "{45A40737-E08A-4AEF-8BD2-F6614EC3C9ED}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -493.879, + 59.18, + -588.183 + ], + "size": [ + 21.648, + 17.036, + 14.595 + ], + "groundY": 50.662, + "roofY": 67.698, + "wallCount": 24, + "roofCount": 31 + }, + { + "id": "sion_0417", + "uuid": "{4623F9BD-4443-45C5-8053-E6C6CD987A36}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1476.021, + 277.093, + -1030.241 + ], + "size": [ + 19.09, + 12.652, + 22.544 + ], + "groundY": 270.767, + "roofY": 283.419, + "wallCount": 83, + "roofCount": 34 + }, + { + "id": "sion_0418", + "uuid": "{E071EE72-68DC-4010-ABAC-16338C61BB21}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -1008.852, + 6.474, + 783.72 + ], + "size": [ + 181.758, + 18.365, + 109.43 + ], + "groundY": -2.708, + "roofY": 15.657, + "wallCount": 169, + "roofCount": 138 + }, + { + "id": "sion_0419", + "uuid": "{03211C89-D8BF-45E3-81AB-5FC09199CB22}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1230.848, + 283.81, + -1231.45 + ], + "size": [ + 16.227, + 14.288, + 20.318 + ], + "groundY": 276.666, + "roofY": 290.954, + "wallCount": 42, + "roofCount": 17 + }, + { + "id": "sion_0420", + "uuid": "{6D0328C4-E7D6-46B5-A34C-DAEA0C503AF2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -654.75, + 1.73, + 382.696 + ], + "size": [ + 29.859, + 6.605, + 27.7 + ], + "groundY": -1.572, + "roofY": 5.033, + "wallCount": 24, + "roofCount": 11 + }, + { + "id": "sion_0421", + "uuid": "{02E1E779-C270-4AF8-8575-774A9DC1EC86}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1238.145, + 290.384, + -1357.787 + ], + "size": [ + 26.516, + 15.102, + 22.314 + ], + "groundY": 282.833, + "roofY": 297.935, + "wallCount": 57, + "roofCount": 47 + }, + { + "id": "sion_0422", + "uuid": "{69E9BCA6-03A4-4880-8009-BA7AFC282992}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1284.125, + 283.423, + -1313.054 + ], + "size": [ + 15.141, + 7.422, + 21.972 + ], + "groundY": 279.712, + "roofY": 287.134, + "wallCount": 14, + "roofCount": 4 + }, + { + "id": "sion_0423", + "uuid": "{AB36993F-E33A-44A4-836A-4EE594056AAE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -422.361, + 17.053, + 196.531 + ], + "size": [ + 6.793, + 7.369, + 9.988 + ], + "groundY": 13.368, + "roofY": 20.737, + "wallCount": 29, + "roofCount": 14 + }, + { + "id": "sion_0424", + "uuid": "{9EFAE6D5-7E38-4FDB-A0A5-EDD699100F8B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1382.004, + 60.27, + 123.613 + ], + "size": [ + 13.086, + 15.208, + 15.238 + ], + "groundY": 52.666, + "roofY": 67.874, + "wallCount": 63, + "roofCount": 16 + }, + { + "id": "sion_0425", + "uuid": "{EA20A2FD-052B-40DA-889C-DE8507908FCB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1178.609, + 288.386, + -1173.361 + ], + "size": [ + 15.195, + 11.938, + 15.025 + ], + "groundY": 282.417, + "roofY": 294.355, + "wallCount": 44, + "roofCount": 10 + }, + { + "id": "sion_0426", + "uuid": "{9E5DB2E0-ED8E-4459-97BF-A04DA1E97615}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1193.461, + 297.548, + -1513.454 + ], + "size": [ + 13.266, + 11.304, + 12.439 + ], + "groundY": 291.896, + "roofY": 303.2, + "wallCount": 56, + "roofCount": 28 + }, + { + "id": "sion_0427", + "uuid": "{5B228987-14DE-4655-9B16-652549F793C0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -852.176, + 295.932, + -1448.577 + ], + "size": [ + 20.273, + 10.241, + 16.51 + ], + "groundY": 290.812, + "roofY": 301.053, + "wallCount": 46, + "roofCount": 17 + }, + { + "id": "sion_0428", + "uuid": "{96EF9646-8188-4F46-94E4-FDC451FD1586}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1493.828, + 272.648, + -1026.661 + ], + "size": [ + 13.398, + 13.392, + 17.076 + ], + "groundY": 265.952, + "roofY": 279.344, + "wallCount": 80, + "roofCount": 18 + }, + { + "id": "sion_0429", + "uuid": "{7F07C2A4-A150-455C-9431-B534B95122AE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -531.643, + 31.512, + -149.139 + ], + "size": [ + 21.809, + 9.561, + 13.632 + ], + "groundY": 26.732, + "roofY": 36.293, + "wallCount": 38, + "roofCount": 33 + }, + { + "id": "sion_0430", + "uuid": "{ED65DC7A-2B00-45EA-802A-38FF10C85939}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -511.867, + 8.5, + 414.249 + ], + "size": [ + 16.477, + 12.686, + 16.426 + ], + "groundY": 2.157, + "roofY": 14.843, + "wallCount": 72, + "roofCount": 49 + }, + { + "id": "sion_0431", + "uuid": "{75D0CBC6-DC0C-4096-9432-EE633B894662}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -514.426, + 35.299, + -83.155 + ], + "size": [ + 18.969, + 22.781, + 17.238 + ], + "groundY": 23.909, + "roofY": 46.689, + "wallCount": 63, + "roofCount": 71 + }, + { + "id": "sion_0432", + "uuid": "{25339E7B-227C-4B52-8DE8-02FA53236E31}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -994.432, + 93.969, + -391.767 + ], + "size": [ + 31.988, + 16.346, + 30.478 + ], + "groundY": 85.796, + "roofY": 102.142, + "wallCount": 19, + "roofCount": 21 + }, + { + "id": "sion_0433", + "uuid": "{7B649991-C467-4116-93EE-757096E4D678}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1241.684, + 47.407, + 75.296 + ], + "size": [ + 14.172, + 12.584, + 12.63 + ], + "groundY": 41.115, + "roofY": 53.699, + "wallCount": 87, + "roofCount": 38 + }, + { + "id": "sion_0434", + "uuid": "{76540D60-77E5-404F-9C67-5DE9803FC2AC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -775.076, + 17.936, + 171.434 + ], + "size": [ + 10.324, + 15.266, + 10.398 + ], + "groundY": 10.303, + "roofY": 25.569, + "wallCount": 47, + "roofCount": 36 + }, + { + "id": "sion_0435", + "uuid": "{EACF4716-3C43-4342-AB30-CB075E6005B7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1228.615, + 118.63, + -331.566 + ], + "size": [ + 19.832, + 9.328, + 20.22 + ], + "groundY": 113.966, + "roofY": 123.294, + "wallCount": 47, + "roofCount": 2 + }, + { + "id": "sion_0436", + "uuid": "{DA1D9F65-9F99-4F72-8A26-DFFF20B625C3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1278.49, + 1.547, + 885.736 + ], + "size": [ + 11.512, + 8.614, + 27.746 + ], + "groundY": -2.76, + "roofY": 5.854, + "wallCount": 19, + "roofCount": 35 + }, + { + "id": "sion_0437", + "uuid": "{BF6BEF71-84C4-4169-8622-078B45E66118}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1521.174, + 272.711, + -1439.095 + ], + "size": [ + 11.738, + 7.79, + 11.068 + ], + "groundY": 268.816, + "roofY": 276.606, + "wallCount": 39, + "roofCount": 26 + }, + { + "id": "sion_0438", + "uuid": "{D7FF2B1B-B92A-4AF9-8AFE-5A8A56534111}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -1008.467, + 296.543, + -1372.559 + ], + "size": [ + 16.16, + 11.134, + 19.122 + ], + "groundY": 290.976, + "roofY": 302.11, + "wallCount": 61, + "roofCount": 35 + }, + { + "id": "sion_0439", + "uuid": "{91440531-E8DA-4711-B8D1-0414BAC55CDF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1337.656, + 266.84, + -1006.968 + ], + "size": [ + 18.438, + 9.151, + 25.603 + ], + "groundY": 262.264, + "roofY": 271.415, + "wallCount": 48, + "roofCount": 12 + }, + { + "id": "sion_0440", + "uuid": "{D04B5997-0FD0-47A8-AC5B-07ACDC6C16BE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1057.359, + 1.904, + 880.455 + ], + "size": [ + 43.477, + 9.295, + 71.008 + ], + "groundY": -2.744, + "roofY": 6.551, + "wallCount": 25, + "roofCount": 40 + }, + { + "id": "sion_0441", + "uuid": "{158FB49C-92C6-43A5-BC21-BF9AC5E67BCF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -607.971, + 75.153, + -594.854 + ], + "size": [ + 27.863, + 16.77, + 23.173 + ], + "groundY": 66.768, + "roofY": 83.538, + "wallCount": 62, + "roofCount": 22 + }, + { + "id": "sion_0442", + "uuid": "{328B78F0-7B45-4657-9CFC-0222CC31EBA4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -901.541, + 102.045, + -482.988 + ], + "size": [ + 61.91, + 12.867, + 59.428 + ], + "groundY": 95.611, + "roofY": 108.478, + "wallCount": 109, + "roofCount": 37 + }, + { + "id": "sion_0443", + "uuid": "{2AB60A83-A421-4583-AB33-4646718EEB8A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1491.398, + 5.728, + 513.321 + ], + "size": [ + 23.945, + 18.714, + 43.846 + ], + "groundY": -3.629, + "roofY": 15.085, + "wallCount": 14, + "roofCount": 2 + }, + { + "id": "sion_0444", + "uuid": "{62DCFDAE-2654-4D27-A633-ECFE2D53AD38}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1117.234, + 95.423, + -259.59 + ], + "size": [ + 11.172, + 9.294, + 10.479 + ], + "groundY": 90.776, + "roofY": 100.07, + "wallCount": 48, + "roofCount": 28 + }, + { + "id": "sion_0445", + "uuid": "{3733F9C7-5CFE-484F-9CC6-A53EBFEC8020}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1274.602, + 207.638, + -650.408 + ], + "size": [ + 14.367, + 9.742, + 15.0 + ], + "groundY": 202.767, + "roofY": 212.509, + "wallCount": 29, + "roofCount": 10 + }, + { + "id": "sion_0446", + "uuid": "{3F8248B9-AC6D-4097-9C4E-D4404D565090}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1430.059, + 272.542, + -1006.749 + ], + "size": [ + 18.578, + 11.365, + 16.965 + ], + "groundY": 266.859, + "roofY": 278.224, + "wallCount": 24, + "roofCount": 14 + }, + { + "id": "sion_0447", + "uuid": "{6A72E26F-BB8F-4AC6-B183-D96786EEA17E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1373.83, + 286.107, + -1320.378 + ], + "size": [ + 17.129, + 11.94, + 15.204 + ], + "groundY": 280.137, + "roofY": 292.077, + "wallCount": 37, + "roofCount": 17 + }, + { + "id": "sion_0448", + "uuid": "{5839F4AC-1CC2-4973-BAF4-4849F0BC8A0A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -403.691, + 27.896, + 121.587 + ], + "size": [ + 21.68, + 22.101, + 25.859 + ], + "groundY": 16.846, + "roofY": 38.947, + "wallCount": 19, + "roofCount": 14 + }, + { + "id": "sion_0449", + "uuid": "{EBD44EC8-3FE1-4EBF-B9DE-D8D3F2CF2686}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -915.096, + 85.967, + -376.221 + ], + "size": [ + 17.199, + 9.492, + 23.904 + ], + "groundY": 81.221, + "roofY": 90.713, + "wallCount": 45, + "roofCount": 12 + }, + { + "id": "sion_0450", + "uuid": "{76406B01-1130-4764-A0DF-0FFC51BDFEF2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -866.92, + 0.741, + 233.574 + ], + "size": [ + 13.324, + 4.596, + 9.962 + ], + "groundY": -1.557, + "roofY": 3.039, + "wallCount": 18, + "roofCount": 2 + }, + { + "id": "sion_0451", + "uuid": "{791D71B2-971F-48CA-8867-90A13E68BFDF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1242.566, + 267.624, + -1000.466 + ], + "size": [ + 13.938, + 11.021, + 12.714 + ], + "groundY": 262.114, + "roofY": 273.135, + "wallCount": 46, + "roofCount": 14 + }, + { + "id": "sion_0452", + "uuid": "{355BC443-8059-4FD4-8973-9FE62276B7BD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1328.162, + 244.759, + -825.435 + ], + "size": [ + 20.902, + 10.737, + 18.845 + ], + "groundY": 239.391, + "roofY": 250.128, + "wallCount": 49, + "roofCount": 24 + }, + { + "id": "sion_0453", + "uuid": "{D2AF8E4E-9AE0-4B68-AED3-68DA6E648D7A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -587.965, + 67.478, + -567.904 + ], + "size": [ + 22.883, + 15.352, + 21.612 + ], + "groundY": 59.802, + "roofY": 75.154, + "wallCount": 14, + "roofCount": 10 + }, + { + "id": "sion_0454", + "uuid": "{BBC2172D-44A8-4271-BAEE-497FEC6BA57F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -801.205, + 105.789, + -578.229 + ], + "size": [ + 18.543, + 13.328, + 20.247 + ], + "groundY": 99.125, + "roofY": 112.453, + "wallCount": 56, + "roofCount": 28 + }, + { + "id": "sion_0455", + "uuid": "{D5A8CD49-0DA4-488E-A755-F48241C1F899}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1351.693, + 194.579, + -477.835 + ], + "size": [ + 7.574, + 7.554, + 8.738 + ], + "groundY": 190.802, + "roofY": 198.356, + "wallCount": 47, + "roofCount": 15 + }, + { + "id": "sion_0456", + "uuid": "{8A96E266-99AA-49F6-A3EA-3B1B9DEE30DF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -633.781, + 69.606, + -515.62 + ], + "size": [ + 22.547, + 17.295, + 22.79 + ], + "groundY": 60.959, + "roofY": 78.254, + "wallCount": 24, + "roofCount": 53 + }, + { + "id": "sion_0457", + "uuid": "{B3CFF8AB-A71D-49EB-85B0-6EE36EF1752C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1339.395, + 281.769, + -1115.732 + ], + "size": [ + 24.414, + 13.038, + 18.407 + ], + "groundY": 275.25, + "roofY": 288.288, + "wallCount": 34, + "roofCount": 32 + }, + { + "id": "sion_0458", + "uuid": "{386A1FA0-35F4-4024-BB0E-85B8BBE7D875}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -796.512, + 10.968, + 247.023 + ], + "size": [ + 42.086, + 19.524, + 31.168 + ], + "groundY": 1.206, + "roofY": 20.73, + "wallCount": 47, + "roofCount": 52 + }, + { + "id": "sion_0459", + "uuid": "{08DCEC80-420E-4420-9716-B82F323D79EB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -504.982, + 2.663, + 856.651 + ], + "size": [ + 20.106, + 7.31, + 29.306 + ], + "groundY": -0.992, + "roofY": 6.317, + "wallCount": 25, + "roofCount": 10 + }, + { + "id": "sion_0460", + "uuid": "{7FBB26EA-AC60-4B21-A702-F054163C84CF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -753.082, + 12.525, + 264.234 + ], + "size": [ + 18.93, + 17.178, + 15.916 + ], + "groundY": 3.936, + "roofY": 21.114, + "wallCount": 41, + "roofCount": 56 + }, + { + "id": "sion_0461", + "uuid": "{E7B58247-922E-4F4A-9C15-B58BEA0753A2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -532.154, + 21.385, + 88.203 + ], + "size": [ + 11.645, + 9.772, + 14.441 + ], + "groundY": 16.499, + "roofY": 26.271, + "wallCount": 19, + "roofCount": 28 + }, + { + "id": "sion_0462", + "uuid": "{E77A8C2F-5A3F-4B36-B3FD-ADECB49B907F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -786.596, + 67.995, + -308.543 + ], + "size": [ + 28.988, + 9.458, + 23.801 + ], + "groundY": 63.266, + "roofY": 72.724, + "wallCount": 27, + "roofCount": 21 + }, + { + "id": "sion_0463", + "uuid": "{93695C96-D95D-406A-8685-A3CA61C42648}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1502.207, + 53.895, + 282.332 + ], + "size": [ + 24.391, + 14.368, + 35.844 + ], + "groundY": 46.711, + "roofY": 61.079, + "wallCount": 70, + "roofCount": 20 + }, + { + "id": "sion_0464", + "uuid": "{7986870E-EE45-4B13-8850-57441B2F2DD6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -735.277, + 5.412, + 450.096 + ], + "size": [ + 40.391, + 13.888, + 40.149 + ], + "groundY": -1.532, + "roofY": 12.356, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_0465", + "uuid": "{20C5D2A1-747D-4CCD-9D6F-8AACD82B41B1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1323.412, + 206.146, + -600.305 + ], + "size": [ + 31.668, + 9.354, + 21.588 + ], + "groundY": 201.469, + "roofY": 210.823, + "wallCount": 37, + "roofCount": 22 + }, + { + "id": "sion_0466", + "uuid": "{9B9ECE1D-6C0A-4EB5-BAFB-8CB9C0DCEDA9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1157.881, + 209.259, + -707.77 + ], + "size": [ + 36.168, + 10.299, + 33.72 + ], + "groundY": 204.11, + "roofY": 214.409, + "wallCount": 42, + "roofCount": 12 + }, + { + "id": "sion_0467", + "uuid": "{78F9D6ED-5558-49BE-ADC5-A4C8A4B18D98}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -598.756, + 29.785, + -16.351 + ], + "size": [ + 26.691, + 20.575, + 20.648 + ], + "groundY": 19.498, + "roofY": 40.073, + "wallCount": 20, + "roofCount": 18 + }, + { + "id": "sion_0468", + "uuid": "{C40F273F-1D0C-4F77-AD50-08D1BB80F614}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1031.893, + 55.577, + -135.654 + ], + "size": [ + 29.137, + 11.878, + 16.899 + ], + "groundY": 49.638, + "roofY": 61.516, + "wallCount": 59, + "roofCount": 20 + }, + { + "id": "sion_0469", + "uuid": "{1E8ED1EE-7C6E-4ABE-BC1D-5111E5C4679E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -715.264, + 55.273, + -335.837 + ], + "size": [ + 20.105, + 11.367, + 16.727 + ], + "groundY": 49.59, + "roofY": 60.957, + "wallCount": 32, + "roofCount": 12 + }, + { + "id": "sion_0470", + "uuid": "{8E626F30-3B39-4F5A-B1B9-E22E56E24347}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1267.715, + 292.274, + -1388.264 + ], + "size": [ + 13.359, + 9.47, + 18.512 + ], + "groundY": 287.539, + "roofY": 297.009, + "wallCount": 37, + "roofCount": 19 + }, + { + "id": "sion_0471", + "uuid": "{C7342E45-EC7B-46C3-90E6-2F3A5D314C13}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 3 + ], + "center": [ + -405.119, + 18.63, + 156.277 + ], + "size": [ + 27.816, + 9.786, + 29.936 + ], + "groundY": 13.737, + "roofY": 23.523, + "wallCount": 25, + "roofCount": 2 + }, + { + "id": "sion_0472", + "uuid": "{35BA07F1-8368-414A-99DF-CDC6DB772C21}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -478.377, + 35.777, + -87.573 + ], + "size": [ + 41.067, + 24.346, + 39.11 + ], + "groundY": 23.604, + "roofY": 47.95, + "wallCount": 56, + "roofCount": 15 + }, + { + "id": "sion_0473", + "uuid": "{81036C80-DD77-472E-A966-8E9CCB67ADF2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1413.898, + 232.928, + -771.792 + ], + "size": [ + 15.234, + 14.61, + 17.695 + ], + "groundY": 225.623, + "roofY": 240.233, + "wallCount": 58, + "roofCount": 8 + }, + { + "id": "sion_0474", + "uuid": "{A4EA7454-9265-4F3B-ABA7-E09B46ED0DB4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -750.062, + 16.064, + 227.063 + ], + "size": [ + 16.922, + 18.211, + 13.112 + ], + "groundY": 6.959, + "roofY": 25.17, + "wallCount": 44, + "roofCount": 25 + }, + { + "id": "sion_0475", + "uuid": "{C97F04B0-2387-4C06-B7ED-84D7363DF3EF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1375.225, + 276.963, + -1259.782 + ], + "size": [ + 16.559, + 9.405, + 17.38 + ], + "groundY": 272.261, + "roofY": 281.665, + "wallCount": 55, + "roofCount": 14 + }, + { + "id": "sion_0476", + "uuid": "{5C659C12-8A60-4F5B-969E-94E746A32939}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1221.439, + 214.056, + -743.153 + ], + "size": [ + 15.996, + 9.164, + 13.424 + ], + "groundY": 209.474, + "roofY": 218.638, + "wallCount": 38, + "roofCount": 25 + }, + { + "id": "sion_0477", + "uuid": "{ECD84F8F-2D69-4321-9FF9-BA86782D6C4E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -799.164, + 76.555, + -355.819 + ], + "size": [ + 19.562, + 12.129, + 24.726 + ], + "groundY": 70.491, + "roofY": 82.62, + "wallCount": 34, + "roofCount": 40 + }, + { + "id": "sion_0478", + "uuid": "{70BD3859-0E3F-466C-B8DF-EBACCAF734AC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -789.762, + 22.245, + 81.922 + ], + "size": [ + 24.953, + 21.111, + 26.538 + ], + "groundY": 11.69, + "roofY": 32.801, + "wallCount": 14, + "roofCount": 42 + }, + { + "id": "sion_0479", + "uuid": "{B204E27E-5239-45B5-AEA2-D593ABC803ED}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1347.314, + 6.292, + 693.172 + ], + "size": [ + 52.418, + 20.476, + 32.895 + ], + "groundY": -3.946, + "roofY": 16.53, + "wallCount": 88, + "roofCount": 113 + }, + { + "id": "sion_0480", + "uuid": "{0C6DD67E-D1D5-4F29-A02C-99162613CA16}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -635.451, + 8.851, + 919.474 + ], + "size": [ + 119.777, + 19.399, + 105.626 + ], + "groundY": -0.848, + "roofY": 18.551, + "wallCount": 20, + "roofCount": 4 + }, + { + "id": "sion_0481", + "uuid": "{45083B8F-4A36-4DD6-8BF5-7FA79610EC62}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 3 + ], + "center": [ + -474.494, + 6.976, + 467.48 + ], + "size": [ + 29.723, + 11.29, + 34.173 + ], + "groundY": 1.331, + "roofY": 12.621, + "wallCount": 23, + "roofCount": 6 + }, + { + "id": "sion_0482", + "uuid": "{760C7A68-EDF1-4A48-BF19-66EFAFB5923E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -765.355, + 58.923, + -296.462 + ], + "size": [ + 17.211, + 10.388, + 16.352 + ], + "groundY": 53.729, + "roofY": 64.117, + "wallCount": 13, + "roofCount": 24 + }, + { + "id": "sion_0483", + "uuid": "{BBA31A1A-1A22-4658-BE04-176C843AD42B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1402.266, + 2.668, + 326.079 + ], + "size": [ + 11.328, + 10.618, + 12.186 + ], + "groundY": -2.641, + "roofY": 7.977, + "wallCount": 45, + "roofCount": 18 + }, + { + "id": "sion_0484", + "uuid": "{7AF69BA5-3103-4DE6-A368-D3A05198CF71}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1460.387, + 279.647, + -1037.058 + ], + "size": [ + 13.758, + 12.612, + 14.856 + ], + "groundY": 273.341, + "roofY": 285.953, + "wallCount": 52, + "roofCount": 13 + }, + { + "id": "sion_0485", + "uuid": "{B8C98023-8E0B-4F6A-92D2-8FBD6F8A3056}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1473.478, + 44.75, + 277.405 + ], + "size": [ + 21.598, + 11.947, + 34.204 + ], + "groundY": 38.777, + "roofY": 50.723, + "wallCount": 92, + "roofCount": 46 + }, + { + "id": "sion_0486", + "uuid": "{FCAAADAE-9508-4842-AE65-A0A632AD6D74}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 1 + ], + "center": [ + -1408.293, + 244.323, + -862.541 + ], + "size": [ + 23.484, + 10.319, + 16.455 + ], + "groundY": 239.163, + "roofY": 249.482, + "wallCount": 32, + "roofCount": 15 + }, + { + "id": "sion_0487", + "uuid": "{D697E404-2AC3-4EA4-B333-78A415AB1462}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1143.703, + -0.162, + 515.552 + ], + "size": [ + 22.148, + 5.254, + 12.07 + ], + "groundY": -2.789, + "roofY": 2.465, + "wallCount": 32, + "roofCount": 11 + }, + { + "id": "sion_0488", + "uuid": "{A1D252E6-014A-4882-885B-DDDD206B4009}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1214.086, + 138.562, + -383.602 + ], + "size": [ + 17.891, + 7.196, + 15.748 + ], + "groundY": 134.964, + "roofY": 142.16, + "wallCount": 37, + "roofCount": 11 + }, + { + "id": "sion_0489", + "uuid": "{436323AD-8B60-407B-A1DC-7A1C4E0FE556}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1238.037, + 284.911, + -1112.889 + ], + "size": [ + 25.996, + 14.25, + 41.64 + ], + "groundY": 277.786, + "roofY": 292.036, + "wallCount": 87, + "roofCount": 46 + }, + { + "id": "sion_0490", + "uuid": "{A7AFE0A8-C174-41C4-A2EB-00055C1CC02A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1349.588, + 64.235, + 42.715 + ], + "size": [ + 13.668, + 5.988, + 16.53 + ], + "groundY": 61.241, + "roofY": 67.229, + "wallCount": 23, + "roofCount": 4 + }, + { + "id": "sion_0491", + "uuid": "{564B23F8-622A-4959-A502-D16BD9C2C407}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1350.064, + 67.961, + 68.477 + ], + "size": [ + 23.801, + 14.294, + 17.75 + ], + "groundY": 60.814, + "roofY": 75.108, + "wallCount": 114, + "roofCount": 22 + }, + { + "id": "sion_0492", + "uuid": "{987B8B1B-6560-4594-9FAE-07F148E6EEF4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -672.133, + 86.743, + -572.695 + ], + "size": [ + 30.398, + 12.742, + 24.028 + ], + "groundY": 80.372, + "roofY": 93.114, + "wallCount": 29, + "roofCount": 24 + }, + { + "id": "sion_0493", + "uuid": "{EC5C3CD1-18AE-4A9E-854E-E7110ED98B0E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1069.502, + 47.541, + -84.901 + ], + "size": [ + 12.387, + 10.052, + 15.646 + ], + "groundY": 42.515, + "roofY": 52.567, + "wallCount": 30, + "roofCount": 2 + }, + { + "id": "sion_0494", + "uuid": "{56C1167D-BB76-41B3-8454-C8642A232B59}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1410.711, + 3.142, + 856.089 + ], + "size": [ + 15.484, + 12.424, + 12.271 + ], + "groundY": -3.07, + "roofY": 9.354, + "wallCount": 34, + "roofCount": 29 + }, + { + "id": "sion_0495", + "uuid": "{734E0736-CBE6-419F-8196-E02DE920AA44}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -691.646, + 56.006, + -371.494 + ], + "size": [ + 34.473, + 15.613, + 23.16 + ], + "groundY": 48.2, + "roofY": 63.813, + "wallCount": 82, + "roofCount": 27 + }, + { + "id": "sion_0496", + "uuid": "{7DE1BDE7-BC1E-4EE1-A75B-33675A1CC243}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1445.293, + 54.918, + 222.118 + ], + "size": [ + 45.039, + 21.642, + 46.504 + ], + "groundY": 44.097, + "roofY": 65.739, + "wallCount": 136, + "roofCount": 50 + }, + { + "id": "sion_0497", + "uuid": "{69A44698-A4D8-4BAA-A1F2-597F477C399B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1247.695, + 271.018, + -1024.876 + ], + "size": [ + 15.0, + 10.867, + 17.195 + ], + "groundY": 265.585, + "roofY": 276.452, + "wallCount": 32, + "roofCount": 12 + }, + { + "id": "sion_0498", + "uuid": "{A66BC53F-A234-40BF-A26B-D0F26F589B6F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -601.18, + 19.636, + 265.842 + ], + "size": [ + 41.125, + 25.662, + 17.25 + ], + "groundY": 6.805, + "roofY": 32.467, + "wallCount": 29, + "roofCount": 21 + }, + { + "id": "sion_0499", + "uuid": "{28A5456D-E5C5-4A87-B01C-EB9DC48A442F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -859.48, + 2.497, + 264.566 + ], + "size": [ + 16.305, + 9.09, + 21.45 + ], + "groundY": -2.048, + "roofY": 7.042, + "wallCount": 28, + "roofCount": 28 + }, + { + "id": "sion_0500", + "uuid": "{21FFF641-D1CB-4DDD-AC62-29609DB3B931}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1307.125, + 260.844, + -992.864 + ], + "size": [ + 12.648, + 10.688, + 15.59 + ], + "groundY": 255.5, + "roofY": 266.188, + "wallCount": 33, + "roofCount": 35 + }, + { + "id": "sion_0501", + "uuid": "{1E6DD44D-05A9-4509-8812-4F3E9D204968}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1295.406, + 207.068, + -635.478 + ], + "size": [ + 16.242, + 9.878, + 17.407 + ], + "groundY": 202.129, + "roofY": 212.007, + "wallCount": 19, + "roofCount": 10 + }, + { + "id": "sion_0502", + "uuid": "{87AA2C56-DDCC-4D5C-B8AE-79D42A83B813}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1242.598, + 140.358, + -394.673 + ], + "size": [ + 46.609, + 9.668, + 27.348 + ], + "groundY": 135.524, + "roofY": 145.192, + "wallCount": 16, + "roofCount": 2 + }, + { + "id": "sion_0503", + "uuid": "{691C93DF-D4EF-439D-927D-92747B2218A7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -559.721, + 23.5, + 201.49 + ], + "size": [ + 16.77, + 23.952, + 45.608 + ], + "groundY": 11.524, + "roofY": 35.476, + "wallCount": 101, + "roofCount": 131 + }, + { + "id": "sion_0504", + "uuid": "{49FC06F7-04BE-41FD-93BF-6BFA12F0545B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1056.967, + 7.524, + 575.216 + ], + "size": [ + 29.23, + 21.586, + 49.382 + ], + "groundY": -3.269, + "roofY": 18.317, + "wallCount": 63, + "roofCount": 18 + }, + { + "id": "sion_0505", + "uuid": "{D4ED1186-0036-4C1A-BCF9-166BAE28F485}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1283.932, + 205.413, + -615.693 + ], + "size": [ + 15.629, + 10.535, + 17.942 + ], + "groundY": 200.145, + "roofY": 210.68, + "wallCount": 28, + "roofCount": 13 + }, + { + "id": "sion_0506", + "uuid": "{924C49C8-E54A-4375-8DEA-1AE31D237DED}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -516.791, + 40.127, + -377.05 + ], + "size": [ + 17.043, + 7.948, + 19.718 + ], + "groundY": 36.153, + "roofY": 44.101, + "wallCount": 27, + "roofCount": 17 + }, + { + "id": "sion_0507", + "uuid": "{338AE335-BD00-40A7-AED7-7470ED6F0940}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1108.223, + 3.865, + 404.528 + ], + "size": [ + 16.688, + 14.176, + 51.698 + ], + "groundY": -3.223, + "roofY": 10.953, + "wallCount": 40, + "roofCount": 12 + }, + { + "id": "sion_0508", + "uuid": "{2314291F-B4AC-480F-91D1-FB404FF3B544}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -932.238, + 69.651, + -243.226 + ], + "size": [ + 17.164, + 10.232, + 15.864 + ], + "groundY": 64.535, + "roofY": 74.767, + "wallCount": 44, + "roofCount": 28 + }, + { + "id": "sion_0509", + "uuid": "{21ACE019-38ED-4EA0-B3FA-C7042556C1B1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -954.41, + 15.938, + 129.799 + ], + "size": [ + 34.656, + 18.96, + 29.286 + ], + "groundY": 6.458, + "roofY": 25.418, + "wallCount": 28, + "roofCount": 50 + }, + { + "id": "sion_0510", + "uuid": "{19420598-C884-4C88-9212-AE991613B272}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1055.947, + 22.222, + -20.517 + ], + "size": [ + 26.981, + 18.655, + 24.905 + ], + "groundY": 12.895, + "roofY": 31.55, + "wallCount": 41, + "roofCount": 15 + }, + { + "id": "sion_0511", + "uuid": "{ACFC9777-71DF-4240-8DBB-C30FF7B8F6C1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1102.604, + 0.708, + 874.096 + ], + "size": [ + 48.09, + 6.626, + 88.086 + ], + "groundY": -2.605, + "roofY": 4.021, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_0512", + "uuid": "{25DA7EFB-547E-4466-B17D-8D05A2DC7512}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1403.295, + 284.347, + -1104.148 + ], + "size": [ + 38.449, + 16.75, + 41.834 + ], + "groundY": 275.972, + "roofY": 292.722, + "wallCount": 70, + "roofCount": 30 + }, + { + "id": "sion_0513", + "uuid": "{BF2EC73C-61AC-41F2-AF92-8994E0F834F5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1460.133, + 76.703, + 22.572 + ], + "size": [ + 19.672, + 12.906, + 15.85 + ], + "groundY": 70.25, + "roofY": 83.156, + "wallCount": 43, + "roofCount": 23 + }, + { + "id": "sion_0514", + "uuid": "{DCAEB2A6-69B9-4609-BD57-72FF449A3CBA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1275.637, + 6.571, + 664.708 + ], + "size": [ + 38.055, + 20.05, + 23.211 + ], + "groundY": -3.454, + "roofY": 16.596, + "wallCount": 49, + "roofCount": 20 + }, + { + "id": "sion_0515", + "uuid": "{6FD9FB75-F0BE-4BA3-AF21-92A4A39DAE9B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1300.057, + 208.864, + -656.762 + ], + "size": [ + 16.301, + 9.702, + 16.146 + ], + "groundY": 204.013, + "roofY": 213.715, + "wallCount": 32, + "roofCount": 14 + }, + { + "id": "sion_0516", + "uuid": "{8337FC03-6FA4-4A62-B3B8-B7EE729F18B5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -601.107, + 33.617, + -124.282 + ], + "size": [ + 27.644, + 19.662, + 23.066 + ], + "groundY": 23.786, + "roofY": 43.448, + "wallCount": 13, + "roofCount": 8 + }, + { + "id": "sion_0517", + "uuid": "{1C6FED47-D9D4-49B3-B0DB-84E427216E17}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1437.129, + 223.816, + -651.396 + ], + "size": [ + 16.773, + 8.211, + 12.733 + ], + "groundY": 219.71, + "roofY": 227.921, + "wallCount": 79, + "roofCount": 10 + }, + { + "id": "sion_0518", + "uuid": "{8CC3C05C-64DA-4E4A-B4BB-756254BED86B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -881.855, + 1.919, + 327.81 + ], + "size": [ + 11.641, + 9.85, + 11.034 + ], + "groundY": -3.006, + "roofY": 6.844, + "wallCount": 65, + "roofCount": 28 + }, + { + "id": "sion_0519", + "uuid": "{C4638CC9-4583-4002-AEB4-E914ABE73CCD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1197.992, + 273.132, + -1070.444 + ], + "size": [ + 20.883, + 12.16, + 14.836 + ], + "groundY": 267.052, + "roofY": 279.212, + "wallCount": 43, + "roofCount": 19 + }, + { + "id": "sion_0520", + "uuid": "{4146174F-D17F-476C-BC76-0672FC163081}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -711.627, + 33.709, + -168.545 + ], + "size": [ + 22.145, + 20.952, + 22.172 + ], + "groundY": 23.233, + "roofY": 44.185, + "wallCount": 38, + "roofCount": 33 + }, + { + "id": "sion_0521", + "uuid": "{5C81C33B-599E-4030-B29B-1A00DFFC69F6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -816.789, + 3.835, + 313.449 + ], + "size": [ + 13.078, + 13.469, + 11.9 + ], + "groundY": -2.899, + "roofY": 10.57, + "wallCount": 61, + "roofCount": 37 + }, + { + "id": "sion_0522", + "uuid": "{20063A82-22CF-4B1A-80EE-786823797449}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -949.334, + 118.705, + -525.741 + ], + "size": [ + 17.457, + 10.712, + 12.246 + ], + "groundY": 113.349, + "roofY": 124.061, + "wallCount": 34, + "roofCount": 24 + }, + { + "id": "sion_0523", + "uuid": "{F8DCED1C-8FB1-43C9-BA06-AC06303E1594}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1180.869, + 284.894, + -1129.402 + ], + "size": [ + 26.371, + 15.18, + 17.882 + ], + "groundY": 277.304, + "roofY": 292.484, + "wallCount": 74, + "roofCount": 33 + }, + { + "id": "sion_0524", + "uuid": "{44361DA7-B5E2-4779-A17D-B200DFCB238A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1380.965, + 33.714, + 216.033 + ], + "size": [ + 44.078, + 19.978, + 46.203 + ], + "groundY": 23.725, + "roofY": 43.703, + "wallCount": 76, + "roofCount": 33 + }, + { + "id": "sion_0525", + "uuid": "{FA62BE00-6E1E-4869-9742-702AB3FC82A1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -805.789, + 17.387, + 164.903 + ], + "size": [ + 12.445, + 15.682, + 11.006 + ], + "groundY": 9.546, + "roofY": 25.228, + "wallCount": 38, + "roofCount": 43 + }, + { + "id": "sion_0526", + "uuid": "{742A3392-33F1-42D1-9BFE-886EE5E19329}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1175.0, + 12.32, + 131.861 + ], + "size": [ + 32.273, + 15.938, + 26.456 + ], + "groundY": 4.351, + "roofY": 20.288, + "wallCount": 40, + "roofCount": 21 + }, + { + "id": "sion_0527", + "uuid": "{1A36D069-221D-411A-A180-67CDFC14643E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1350.691, + 290.474, + -1332.678 + ], + "size": [ + 22.891, + 18.186, + 16.318 + ], + "groundY": 281.381, + "roofY": 299.567, + "wallCount": 46, + "roofCount": 20 + }, + { + "id": "sion_0528", + "uuid": "{58460ED1-6C9B-453C-9E11-DC7704C7E04F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1322.85, + 251.256, + -906.965 + ], + "size": [ + 41.348, + 10.031, + 17.219 + ], + "groundY": 246.241, + "roofY": 256.272, + "wallCount": 93, + "roofCount": 57 + }, + { + "id": "sion_0529", + "uuid": "{5F7F558B-5D6E-4F6D-BD14-6244CE711161}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1034.686, + 293.032, + -1415.195 + ], + "size": [ + 15.277, + 9.412, + 19.933 + ], + "groundY": 288.326, + "roofY": 297.738, + "wallCount": 52, + "roofCount": 4 + }, + { + "id": "sion_0530", + "uuid": "{E628BD24-32C0-43AD-B45C-078F749FA3ED}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1530.473, + 5.574, + 525.513 + ], + "size": [ + 23.523, + 18.783, + 43.612 + ], + "groundY": -3.817, + "roofY": 14.966, + "wallCount": 14, + "roofCount": 2 + }, + { + "id": "sion_0531", + "uuid": "{30B9EC81-E04D-46E8-B969-FB99A1C77CA0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -784.107, + 43.661, + -228.968 + ], + "size": [ + 18.637, + 16.793, + 17.408 + ], + "groundY": 35.264, + "roofY": 52.057, + "wallCount": 36, + "roofCount": 31 + }, + { + "id": "sion_0532", + "uuid": "{B47B9C79-9D5B-4A06-9025-EF1A44EBC245}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1270.137, + 81.274, + -79.487 + ], + "size": [ + 78.781, + 25.697, + 64.344 + ], + "groundY": 68.426, + "roofY": 94.123, + "wallCount": 103, + "roofCount": 90 + }, + { + "id": "sion_0533", + "uuid": "{E211077E-D1B3-4C82-BC7B-E65C642CA9C4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1471.049, + 276.253, + -1009.696 + ], + "size": [ + 13.965, + 11.192, + 13.294 + ], + "groundY": 270.657, + "roofY": 281.849, + "wallCount": 47, + "roofCount": 18 + }, + { + "id": "sion_0534", + "uuid": "{076CBCC3-9368-4E25-8EFA-940987525629}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -848.723, + 1.414, + 943.882 + ], + "size": [ + 15.266, + 6.768, + 13.302 + ], + "groundY": -1.97, + "roofY": 4.798, + "wallCount": 40, + "roofCount": 23 + }, + { + "id": "sion_0535", + "uuid": "{946E6EB8-9181-4F93-A783-90DE3B8E754F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1101.154, + 82.474, + -179.016 + ], + "size": [ + 38.262, + 12.008, + 39.212 + ], + "groundY": 76.47, + "roofY": 88.478, + "wallCount": 59, + "roofCount": 29 + }, + { + "id": "sion_0536", + "uuid": "{1F5F8A87-846E-4AB8-B691-3FB03D2009B9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1168.119, + 8.54, + 580.274 + ], + "size": [ + 56.356, + 22.136, + 77.524 + ], + "groundY": -2.528, + "roofY": 19.608, + "wallCount": 30, + "roofCount": 8 + }, + { + "id": "sion_0537", + "uuid": "{411029A7-A824-4091-8E9F-B5F3F8AB87A4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1511.764, + 263.832, + -950.119 + ], + "size": [ + 19.113, + 14.772, + 20.141 + ], + "groundY": 256.446, + "roofY": 271.218, + "wallCount": 73, + "roofCount": 25 + }, + { + "id": "sion_0538", + "uuid": "{5D91E145-24D7-4191-941E-1DF1AE8A6BF2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1152.172, + 238.984, + -843.325 + ], + "size": [ + 12.844, + 10.106, + 16.018 + ], + "groundY": 233.931, + "roofY": 244.037, + "wallCount": 28, + "roofCount": 12 + }, + { + "id": "sion_0539", + "uuid": "{B05AA112-B0E4-4F86-912B-09B38BA161CC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1434.965, + 224.733, + -677.046 + ], + "size": [ + 23.859, + 6.754, + 22.309 + ], + "groundY": 221.356, + "roofY": 228.11, + "wallCount": 26, + "roofCount": 28 + }, + { + "id": "sion_0540", + "uuid": "{6C32A66E-C776-41B7-A49B-9C65710A6D1D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -652.35, + 5.497, + 334.505 + ], + "size": [ + 19.59, + 13.331, + 12.756 + ], + "groundY": -1.168, + "roofY": 12.163, + "wallCount": 20, + "roofCount": 26 + }, + { + "id": "sion_0541", + "uuid": "{F324BA03-988E-4D86-AB13-DB71DD3E2FF5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -592.346, + 96.184, + -740.561 + ], + "size": [ + 27.949, + 8.934, + 21.323 + ], + "groundY": 91.717, + "roofY": 100.651, + "wallCount": 24, + "roofCount": 8 + }, + { + "id": "sion_0542", + "uuid": "{5EDADF36-2094-4B65-BBA2-68D60164CF19}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -578.482, + 31.941, + -62.909 + ], + "size": [ + 17.371, + 22.365, + 18.802 + ], + "groundY": 20.759, + "roofY": 43.124, + "wallCount": 76, + "roofCount": 30 + }, + { + "id": "sion_0543", + "uuid": "{38F2BB4D-8C9B-449F-A21B-DB83F19C21C3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1530.393, + 231.349, + -659.433 + ], + "size": [ + 11.223, + 9.116, + 11.44 + ], + "groundY": 226.791, + "roofY": 235.907, + "wallCount": 58, + "roofCount": 11 + }, + { + "id": "sion_0544", + "uuid": "{0BA86F32-2DE6-4306-9348-F84D8147D628}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1475.496, + 1.66, + 466.43 + ], + "size": [ + 15.016, + 11.362, + 13.556 + ], + "groundY": -4.021, + "roofY": 7.341, + "wallCount": 36, + "roofCount": 13 + }, + { + "id": "sion_0545", + "uuid": "{ACA748C1-396B-4932-88E9-88AAAAC6C6ED}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1120.211, + 291.976, + -1430.733 + ], + "size": [ + 18.297, + 8.217, + 20.86 + ], + "groundY": 287.867, + "roofY": 296.084, + "wallCount": 41, + "roofCount": 23 + }, + { + "id": "sion_0546", + "uuid": "{6B0F2D36-0B9C-4856-8C73-76F331D52BDA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -504.98, + 4.386, + 893.367 + ], + "size": [ + 36.68, + 10.804, + 35.514 + ], + "groundY": -1.016, + "roofY": 9.788, + "wallCount": 40, + "roofCount": 10 + }, + { + "id": "sion_0547", + "uuid": "{47A14B7C-C1AD-495E-8567-6246EAE4FC52}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1105.424, + 263.709, + -996.409 + ], + "size": [ + 13.043, + 5.151, + 15.53 + ], + "groundY": 261.133, + "roofY": 266.284, + "wallCount": 27, + "roofCount": 4 + }, + { + "id": "sion_0548", + "uuid": "{87DCE1D7-2923-44ED-A87D-9F528A340EE4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1436.654, + 70.392, + 65.387 + ], + "size": [ + 29.582, + 15.791, + 28.354 + ], + "groundY": 62.497, + "roofY": 78.287, + "wallCount": 31, + "roofCount": 17 + }, + { + "id": "sion_0549", + "uuid": "{540A3128-12F0-4008-9E87-56D2A63243B0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1447.92, + 225.598, + -755.572 + ], + "size": [ + 10.684, + 5.958, + 7.77 + ], + "groundY": 222.619, + "roofY": 228.577, + "wallCount": 25, + "roofCount": 2 + }, + { + "id": "sion_0550", + "uuid": "{67451093-91FC-4AF5-A6F3-17425ADBFF88}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1175.123, + 56.63, + -4.659 + ], + "size": [ + 15.082, + 8.914, + 15.868 + ], + "groundY": 52.173, + "roofY": 61.087, + "wallCount": 29, + "roofCount": 4 + }, + { + "id": "sion_0551", + "uuid": "{597C19F8-BF0C-4702-95A8-6C50E1187BA0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1431.172, + 7.122, + 317.971 + ], + "size": [ + 26.609, + 13.69, + 22.68 + ], + "groundY": 0.277, + "roofY": 13.967, + "wallCount": 47, + "roofCount": 48 + }, + { + "id": "sion_0552", + "uuid": "{C525E8AF-174C-423B-9C80-D2F3036D0CEB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1456.607, + -1.247, + 481.174 + ], + "size": [ + 33.613, + 5.064, + 15.316 + ], + "groundY": -3.779, + "roofY": 1.285, + "wallCount": 12, + "roofCount": 2 + }, + { + "id": "sion_0553", + "uuid": "{15175C11-AA51-439C-9369-EE223BA3251D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1140.518, + 41.965, + 13.375 + ], + "size": [ + 20.598, + 14.835, + 19.229 + ], + "groundY": 34.548, + "roofY": 49.383, + "wallCount": 32, + "roofCount": 14 + }, + { + "id": "sion_0554", + "uuid": "{03B52E9C-CA76-4E8C-82BC-2172255EC8C6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -916.584, + 293.401, + -1259.521 + ], + "size": [ + 14.184, + 9.303, + 15.888 + ], + "groundY": 288.75, + "roofY": 298.052, + "wallCount": 50, + "roofCount": 6 + }, + { + "id": "sion_0555", + "uuid": "{DD4879B2-ED44-4AF4-8E0E-1E5C952F91E6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -697.65, + 74.309, + -496.45 + ], + "size": [ + 27.488, + 12.082, + 25.2 + ], + "groundY": 68.268, + "roofY": 80.35, + "wallCount": 14, + "roofCount": 4 + }, + { + "id": "sion_0556", + "uuid": "{0C6A241E-0A71-4D1E-B5D9-1018EBDF0D83}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -967.98, + 7.734, + 215.211 + ], + "size": [ + 21.469, + 18.078, + 19.848 + ], + "groundY": -1.305, + "roofY": 16.773, + "wallCount": 34, + "roofCount": 50 + }, + { + "id": "sion_0557", + "uuid": "{6E60C739-252A-4062-B07F-BA701EB09E94}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -942.785, + 297.552, + -1409.543 + ], + "size": [ + 15.648, + 9.866, + 21.809 + ], + "groundY": 292.619, + "roofY": 302.485, + "wallCount": 30, + "roofCount": 16 + }, + { + "id": "sion_0558", + "uuid": "{C1D1FD2C-C7AD-4B0B-9837-131B96ACDE77}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1053.135, + 270.693, + -1009.933 + ], + "size": [ + 13.543, + 11.104, + 13.483 + ], + "groundY": 265.141, + "roofY": 276.245, + "wallCount": 27, + "roofCount": 18 + }, + { + "id": "sion_0559", + "uuid": "{C061653E-19E4-4906-A636-964A6A927141}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1360.318, + 83.019, + -100.29 + ], + "size": [ + 26.184, + 20.395, + 40.75 + ], + "groundY": 72.822, + "roofY": 93.216, + "wallCount": 44, + "roofCount": 21 + }, + { + "id": "sion_0560", + "uuid": "{CAB3FEED-F346-466B-8595-6A1629F344E3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -406.689, + 21.26, + 278.543 + ], + "size": [ + 108.332, + 25.471, + 71.383 + ], + "groundY": 8.524, + "roofY": 33.995, + "wallCount": 111, + "roofCount": 102 + }, + { + "id": "sion_0561", + "uuid": "{7811ED15-D839-4B5A-B573-D3A2916E3232}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -406.645, + 13.506, + 326.713 + ], + "size": [ + 24.914, + 7.542, + 12.496 + ], + "groundY": 9.735, + "roofY": 17.277, + "wallCount": 41, + "roofCount": 13 + }, + { + "id": "sion_0562", + "uuid": "{792AB448-C84C-47EF-B987-28A4D5670B74}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -723.803, + 28.856, + -155.993 + ], + "size": [ + 12.269, + 12.91, + 12.188 + ], + "groundY": 22.401, + "roofY": 35.311, + "wallCount": 35, + "roofCount": 12 + }, + { + "id": "sion_0563", + "uuid": "{E2DADC75-CE45-4CE3-B29F-B3C64774C07B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -490.273, + 30.92, + -15.282 + ], + "size": [ + 35.25, + 20.498, + 27.882 + ], + "groundY": 20.671, + "roofY": 41.169, + "wallCount": 25, + "roofCount": 31 + }, + { + "id": "sion_0564", + "uuid": "{A93DD52B-D71A-4BB7-A27A-302766B0DD3B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1322.059, + 209.426, + -631.28 + ], + "size": [ + 18.289, + 9.144, + 15.258 + ], + "groundY": 204.854, + "roofY": 213.998, + "wallCount": 40, + "roofCount": 20 + }, + { + "id": "sion_0565", + "uuid": "{68F08DD0-0D80-49F2-9961-43BEA43F0F98}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -478.541, + 12.515, + 659.822 + ], + "size": [ + 159.129, + 29.524, + 65.548 + ], + "groundY": -2.247, + "roofY": 27.277, + "wallCount": 201, + "roofCount": 62 + }, + { + "id": "sion_0566", + "uuid": "{775F7E83-6533-4264-BB9D-56D50ABDF5AD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -498.639, + 51.08, + -484.899 + ], + "size": [ + 162.371, + 21.938, + 88.162 + ], + "groundY": 40.111, + "roofY": 62.048, + "wallCount": 210, + "roofCount": 262 + }, + { + "id": "sion_0567", + "uuid": "{63273DAB-4028-4A40-94C1-C18F5684A098}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1200.818, + 18.184, + 110.936 + ], + "size": [ + 43.402, + 19.897, + 35.966 + ], + "groundY": 8.236, + "roofY": 28.132, + "wallCount": 23, + "roofCount": 31 + }, + { + "id": "sion_0568", + "uuid": "{6B6A03E3-5B1D-458D-B944-08A29EE05E18}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -971.135, + 19.589, + 21.938 + ], + "size": [ + 42.559, + 22.151, + 42.655 + ], + "groundY": 8.513, + "roofY": 30.664, + "wallCount": 77, + "roofCount": 20 + }, + { + "id": "sion_0569", + "uuid": "{57294E4D-791F-4261-A0AC-AA7DAA7DF941}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1179.078, + 199.34, + -621.095 + ], + "size": [ + 18.445, + 11.36, + 14.189 + ], + "groundY": 193.66, + "roofY": 205.02, + "wallCount": 53, + "roofCount": 31 + }, + { + "id": "sion_0570", + "uuid": "{596E307D-A820-41AF-B85C-389867A4F921}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1294.123, + 0.792, + 961.514 + ], + "size": [ + 49.395, + 6.924, + 47.116 + ], + "groundY": -2.67, + "roofY": 4.254, + "wallCount": 20, + "roofCount": 4 + }, + { + "id": "sion_0571", + "uuid": "{8E819AEC-6FD3-4B8C-8729-D3B729704EF7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1179.307, + 205.425, + -653.786 + ], + "size": [ + 15.465, + 7.918, + 13.356 + ], + "groundY": 201.466, + "roofY": 209.384, + "wallCount": 35, + "roofCount": 24 + }, + { + "id": "sion_0572", + "uuid": "{E0DBCB38-F0C7-4FF9-9D61-774EA0C8EE69}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1258.285, + 204.613, + -630.24 + ], + "size": [ + 24.547, + 9.271, + 18.906 + ], + "groundY": 199.978, + "roofY": 209.249, + "wallCount": 36, + "roofCount": 7 + }, + { + "id": "sion_0573", + "uuid": "{B741CAD8-2994-4E25-8BEB-78B43F722414}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1203.994, + 0.84, + 849.41 + ], + "size": [ + 38.996, + 7.097, + 24.554 + ], + "groundY": -2.708, + "roofY": 4.389, + "wallCount": 18, + "roofCount": 6 + }, + { + "id": "sion_0574", + "uuid": "{3A621D26-F8A6-44F2-9C35-E869FA7AA517}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1224.002, + 284.209, + -1132.626 + ], + "size": [ + 15.746, + 10.525, + 17.773 + ], + "groundY": 278.947, + "roofY": 289.472, + "wallCount": 40, + "roofCount": 17 + }, + { + "id": "sion_0575", + "uuid": "{EE029B2C-A27F-49F4-8BFF-B53C129C694B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -440.656, + 83.951, + -853.487 + ], + "size": [ + 21.922, + 11.672, + 20.176 + ], + "groundY": 78.115, + "roofY": 89.787, + "wallCount": 45, + "roofCount": 25 + }, + { + "id": "sion_0576", + "uuid": "{4A09BAB4-9F8D-4DCC-97AE-9F76C0F52679}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1171.381, + 288.315, + -1189.565 + ], + "size": [ + 19.137, + 12.46, + 18.168 + ], + "groundY": 282.085, + "roofY": 294.545, + "wallCount": 52, + "roofCount": 27 + }, + { + "id": "sion_0577", + "uuid": "{E367E047-744B-447B-87F6-6AF271C543A3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1033.416, + 289.413, + -1296.351 + ], + "size": [ + 31.465, + 8.44, + 25.155 + ], + "groundY": 285.193, + "roofY": 293.633, + "wallCount": 17, + "roofCount": 21 + }, + { + "id": "sion_0578", + "uuid": "{96DE6AF6-8E11-441B-836F-7ABEE078A451}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1311.738, + 274.14, + -1076.451 + ], + "size": [ + 13.156, + 6.329, + 12.576 + ], + "groundY": 270.975, + "roofY": 277.304, + "wallCount": 14, + "roofCount": 2 + }, + { + "id": "sion_0579", + "uuid": "{3E1AB78D-2D1D-4652-8507-6DC333332D2A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1061.703, + 290.616, + -1286.269 + ], + "size": [ + 22.672, + 11.999, + 17.341 + ], + "groundY": 284.617, + "roofY": 296.616, + "wallCount": 46, + "roofCount": 24 + }, + { + "id": "sion_0580", + "uuid": "{E43FB864-A1DD-4744-B04E-BA6C040D91B9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -964.504, + 298.25, + -1512.887 + ], + "size": [ + 20.102, + 9.638, + 21.136 + ], + "groundY": 293.431, + "roofY": 303.069, + "wallCount": 33, + "roofCount": 17 + }, + { + "id": "sion_0581", + "uuid": "{3FEA53CC-FA37-4D9E-B35D-E8AC5F1BF751}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1511.938, + 206.049, + -514.591 + ], + "size": [ + 15.727, + 10.986, + 16.456 + ], + "groundY": 200.556, + "roofY": 211.542, + "wallCount": 38, + "roofCount": 20 + }, + { + "id": "sion_0582", + "uuid": "{4EC000DC-1BBC-48E7-A8C7-8FD842ED068A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1096.146, + 265.658, + -1004.294 + ], + "size": [ + 8.519, + 10.121, + 8.96 + ], + "groundY": 260.598, + "roofY": 270.719, + "wallCount": 49, + "roofCount": 12 + }, + { + "id": "sion_0583", + "uuid": "{2D600AC2-8D70-4EDF-8546-42C3CE2FA238}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1211.412, + 283.13, + -1255.551 + ], + "size": [ + 19.535, + 12.451, + 13.506 + ], + "groundY": 276.904, + "roofY": 289.355, + "wallCount": 83, + "roofCount": 16 + }, + { + "id": "sion_0584", + "uuid": "{3935854F-74D6-40E8-8487-2D511F972463}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -752.49, + 15.495, + 202.049 + ], + "size": [ + 23.535, + 12.747, + 16.33 + ], + "groundY": 9.122, + "roofY": 21.869, + "wallCount": 44, + "roofCount": 27 + }, + { + "id": "sion_0585", + "uuid": "{E94206BF-B8A2-4271-8DF0-CB67865791B2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1204.186, + 96.546, + -215.171 + ], + "size": [ + 37.723, + 14.26, + 28.691 + ], + "groundY": 89.416, + "roofY": 103.676, + "wallCount": 18, + "roofCount": 33 + }, + { + "id": "sion_0586", + "uuid": "{F16D82B7-9ADD-4DEC-AF35-B519DA6A9C5D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1076.684, + 34.95, + -34.609 + ], + "size": [ + 29.008, + 21.859, + 27.25 + ], + "groundY": 24.021, + "roofY": 45.88, + "wallCount": 44, + "roofCount": 19 + }, + { + "id": "sion_0587", + "uuid": "{E2FED06A-C5E3-4213-B224-2E825CA184EA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1264.576, + 202.409, + -577.263 + ], + "size": [ + 17.949, + 11.126, + 15.397 + ], + "groundY": 196.846, + "roofY": 207.972, + "wallCount": 48, + "roofCount": 22 + }, + { + "id": "sion_0588", + "uuid": "{6D7AB25D-EDBE-424F-B781-2F831863A0AC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1373.318, + 71.294, + 3.907 + ], + "size": [ + 25.527, + 17.375, + 24.792 + ], + "groundY": 62.607, + "roofY": 79.982, + "wallCount": 64, + "roofCount": 26 + }, + { + "id": "sion_0589", + "uuid": "{D10A4DE6-FA65-4D92-AAC1-1BA83E01DA82}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1105.041, + 6.858, + 258.194 + ], + "size": [ + 24.863, + 18.062, + 39.569 + ], + "groundY": -2.173, + "roofY": 15.889, + "wallCount": 16, + "roofCount": 20 + }, + { + "id": "sion_0590", + "uuid": "{1A2F8982-7816-4F94-9EC0-542E95285A9A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -845.225, + 9.646, + 223.078 + ], + "size": [ + 55.027, + 21.964, + 38.332 + ], + "groundY": -1.336, + "roofY": 20.628, + "wallCount": 46, + "roofCount": 23 + }, + { + "id": "sion_0591", + "uuid": "{CFADC5B8-22BC-4E8D-BBA2-FAB012C566D1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1285.383, + 275.126, + -1219.613 + ], + "size": [ + 16.375, + 13.39, + 17.41 + ], + "groundY": 268.431, + "roofY": 281.821, + "wallCount": 51, + "roofCount": 32 + }, + { + "id": "sion_0592", + "uuid": "{28797B4A-F517-4571-9A9C-3570C5CABE8B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -796.152, + 74.902, + -423.858 + ], + "size": [ + 18.836, + 9.94, + 23.804 + ], + "groundY": 69.932, + "roofY": 79.872, + "wallCount": 56, + "roofCount": 10 + }, + { + "id": "sion_0593", + "uuid": "{462F53F1-143B-428B-B9B0-2CDA1D08A490}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -775.277, + 109.683, + -610.65 + ], + "size": [ + 19.188, + 8.97, + 16.39 + ], + "groundY": 105.198, + "roofY": 114.168, + "wallCount": 35, + "roofCount": 13 + }, + { + "id": "sion_0594", + "uuid": "{FB29296E-4A76-4E08-BB7F-2B89C3A1FD31}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -864.064, + 76.925, + -250.782 + ], + "size": [ + 17.926, + 12.364, + 14.506 + ], + "groundY": 70.743, + "roofY": 83.107, + "wallCount": 27, + "roofCount": 20 + }, + { + "id": "sion_0595", + "uuid": "{E8750BC7-0F09-4B19-AA72-E3F373E199A9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -1007.734, + 1.3, + 971.757 + ], + "size": [ + 11.953, + 7.487, + 10.622 + ], + "groundY": -2.443, + "roofY": 5.044, + "wallCount": 59, + "roofCount": 6 + }, + { + "id": "sion_0596", + "uuid": "{D429A6C8-D9C9-4436-9517-9F0A6EB454A7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1426.695, + 280.806, + -1061.41 + ], + "size": [ + 17.344, + 9.726, + 12.223 + ], + "groundY": 275.943, + "roofY": 285.669, + "wallCount": 46, + "roofCount": 35 + }, + { + "id": "sion_0597", + "uuid": "{B61ADEB2-BAF4-491D-8198-B3DAAEA0D0EB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1451.059, + 228.23, + -695.516 + ], + "size": [ + 23.617, + 10.266, + 20.28 + ], + "groundY": 223.097, + "roofY": 233.363, + "wallCount": 37, + "roofCount": 27 + }, + { + "id": "sion_0598", + "uuid": "{38085E2A-259F-4C64-8D61-8D8E9ABC7E12}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1127.693, + 287.991, + -1254.997 + ], + "size": [ + 17.621, + 9.6, + 16.128 + ], + "groundY": 283.191, + "roofY": 292.791, + "wallCount": 41, + "roofCount": 25 + }, + { + "id": "sion_0599", + "uuid": "{4F6C5E09-F777-43A6-BC8F-144037946952}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1071.221, + 97.857, + -333.297 + ], + "size": [ + 27.809, + 13.92, + 27.432 + ], + "groundY": 90.897, + "roofY": 104.817, + "wallCount": 14, + "roofCount": 26 + }, + { + "id": "sion_0600", + "uuid": "{92BEB270-FA21-47B6-A918-84113F45E94F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -739.979, + 70.351, + -395.631 + ], + "size": [ + 20.129, + 14.951, + 17.594 + ], + "groundY": 62.876, + "roofY": 77.827, + "wallCount": 24, + "roofCount": 34 + }, + { + "id": "sion_0601", + "uuid": "{C666212D-1E99-4BF6-B6F1-03BCA3EEC7A2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -755.689, + 5.503, + 283.774 + ], + "size": [ + 42.871, + 15.773, + 21.556 + ], + "groundY": -2.384, + "roofY": 13.389, + "wallCount": 15, + "roofCount": 20 + }, + { + "id": "sion_0602", + "uuid": "{A1C42721-738A-4CE5-A978-5571FB22FF6B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -627.701, + 45.931, + -380.182 + ], + "size": [ + 24.012, + 10.674, + 22.172 + ], + "groundY": 40.594, + "roofY": 51.268, + "wallCount": 35, + "roofCount": 24 + }, + { + "id": "sion_0603", + "uuid": "{0DD7D073-D35C-426E-AF7D-0000CB558311}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1375.359, + 281.302, + -1126.944 + ], + "size": [ + 24.609, + 15.07, + 22.101 + ], + "groundY": 273.767, + "roofY": 288.837, + "wallCount": 55, + "roofCount": 25 + }, + { + "id": "sion_0604", + "uuid": "{6EEEEA77-23BB-42DD-8AAB-1A8DC3B501A5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1375.451, + 265.223, + -978.147 + ], + "size": [ + 17.215, + 9.502, + 27.366 + ], + "groundY": 260.472, + "roofY": 269.974, + "wallCount": 45, + "roofCount": 12 + }, + { + "id": "sion_0605", + "uuid": "{E76B836A-68ED-4F16-B77E-99DEDEDA8990}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -659.471, + 41.229, + -313.034 + ], + "size": [ + 36.348, + 11.082, + 30.15 + ], + "groundY": 35.688, + "roofY": 46.77, + "wallCount": 40, + "roofCount": 192 + }, + { + "id": "sion_0606", + "uuid": "{1DC2CE6B-8C3D-4034-86C2-E44B45DE4941}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1464.82, + 271.434, + -1186.332 + ], + "size": [ + 33.086, + 6.723, + 27.104 + ], + "groundY": 268.073, + "roofY": 274.796, + "wallCount": 25, + "roofCount": 5 + }, + { + "id": "sion_0607", + "uuid": "{FDA65AC0-46E4-480F-A3D4-9D51223C7419}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1119.055, + 12.62, + 136.274 + ], + "size": [ + 30.188, + 19.139, + 39.106 + ], + "groundY": 3.051, + "roofY": 22.19, + "wallCount": 45, + "roofCount": 43 + }, + { + "id": "sion_0608", + "uuid": "{F3468C3A-82F9-4217-8074-1C579323CC55}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 2 + ], + "center": [ + -917.998, + 22.276, + -26.483 + ], + "size": [ + 58.48, + 19.079, + 45.312 + ], + "groundY": 12.737, + "roofY": 31.816, + "wallCount": 32, + "roofCount": 6 + }, + { + "id": "sion_0609", + "uuid": "{FC431DE9-9B1F-4A9A-BE2E-625BE5F61325}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -953.961, + 4.702, + 232.441 + ], + "size": [ + 12.211, + 13.169, + 12.042 + ], + "groundY": -1.882, + "roofY": 11.287, + "wallCount": 52, + "roofCount": 28 + }, + { + "id": "sion_0610", + "uuid": "{65AFB1A9-A5BC-4BCB-A4CA-D4EC1CD04240}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -566.254, + 23.462, + 155.751 + ], + "size": [ + 19.742, + 18.592, + 19.387 + ], + "groundY": 14.166, + "roofY": 32.758, + "wallCount": 55, + "roofCount": 35 + }, + { + "id": "sion_0611", + "uuid": "{5BC4EBC7-76DD-4F19-A697-A236E99C0A58}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1276.406, + 116.977, + -234.423 + ], + "size": [ + 23.688, + 9.923, + 17.748 + ], + "groundY": 112.015, + "roofY": 121.938, + "wallCount": 52, + "roofCount": 68 + }, + { + "id": "sion_0612", + "uuid": "{4B378D28-8920-451F-9C69-60FC5763CD65}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1059.764, + 15.316, + 73.701 + ], + "size": [ + 95.223, + 19.644, + 69.796 + ], + "groundY": 5.494, + "roofY": 25.138, + "wallCount": 61, + "roofCount": 22 + }, + { + "id": "sion_0613", + "uuid": "{31897F97-5CD2-4C7D-AFA5-9B0BB1519B02}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -894.055, + 5.725, + 294.455 + ], + "size": [ + 34.438, + 18.634, + 47.822 + ], + "groundY": -3.592, + "roofY": 15.042, + "wallCount": 157, + "roofCount": 78 + }, + { + "id": "sion_0614", + "uuid": "{F49EDC3C-E7E0-4256-82B0-BFB4A3C5CAAF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -835.393, + 20.205, + 66.486 + ], + "size": [ + 24.84, + 18.75, + 32.996 + ], + "groundY": 10.83, + "roofY": 29.58, + "wallCount": 45, + "roofCount": 25 + }, + { + "id": "sion_0615", + "uuid": "{A87CE973-467C-4420-93DF-FEA63EEA6FCC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -835.664, + 286.971, + -1296.651 + ], + "size": [ + 15.469, + 10.095, + 19.666 + ], + "groundY": 281.924, + "roofY": 292.019, + "wallCount": 33, + "roofCount": 32 + }, + { + "id": "sion_0616", + "uuid": "{031ECAB1-41D0-4A0B-AF7F-CD4DD1396A38}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 0, + 1 + ], + "center": [ + -1229.264, + 204.979, + -642.478 + ], + "size": [ + 30.113, + 12.873, + 43.474 + ], + "groundY": 198.543, + "roofY": 211.416, + "wallCount": 32, + "roofCount": 8 + }, + { + "id": "sion_0617", + "uuid": "{77D31914-986B-4548-8626-7692BA9B8AB4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1193.73, + 296.059, + -1464.945 + ], + "size": [ + 19.773, + 9.156, + 17.124 + ], + "groundY": 291.481, + "roofY": 300.637, + "wallCount": 43, + "roofCount": 27 + }, + { + "id": "sion_0618", + "uuid": "{A9131C48-BB68-4E5E-97D3-63A9A1EF9270}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1491.334, + 269.411, + -1104.531 + ], + "size": [ + 21.793, + 9.92, + 35.464 + ], + "groundY": 264.451, + "roofY": 274.371, + "wallCount": 43, + "roofCount": 43 + }, + { + "id": "sion_0619", + "uuid": "{C2188881-928E-4B09-BAAC-A2600255B02D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1181.332, + 137.702, + -388.2 + ], + "size": [ + 5.945, + 5.258, + 5.914 + ], + "groundY": 135.073, + "roofY": 140.331, + "wallCount": 12, + "roofCount": 2 + }, + { + "id": "sion_0620", + "uuid": "{9CBEB321-FD46-4981-B5C3-2857A049A6C6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1442.105, + 235.245, + -825.378 + ], + "size": [ + 26.273, + 12.893, + 27.924 + ], + "groundY": 228.799, + "roofY": 241.692, + "wallCount": 57, + "roofCount": 25 + }, + { + "id": "sion_0621", + "uuid": "{C2F67DBD-C6EF-4CFF-B02E-0B2D430F0ADD}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 0, + 2 + ], + "center": [ + -1254.994, + 97.734, + -191.319 + ], + "size": [ + 51.832, + 13.376, + 32.314 + ], + "groundY": 91.046, + "roofY": 104.422, + "wallCount": 28, + "roofCount": 6 + }, + { + "id": "sion_0622", + "uuid": "{B2201596-79AA-4D12-94C7-A312CF06ED55}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1291.469, + 237.444, + -798.883 + ], + "size": [ + 15.258, + 9.947, + 20.93 + ], + "groundY": 232.471, + "roofY": 242.417, + "wallCount": 50, + "roofCount": 9 + }, + { + "id": "sion_0623", + "uuid": "{60C3E524-6F72-414C-BCAD-854B2C5CB8E8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1377.74, + 49.466, + 166.998 + ], + "size": [ + 18.246, + 11.369, + 25.891 + ], + "groundY": 43.781, + "roofY": 55.15, + "wallCount": 62, + "roofCount": 22 + }, + { + "id": "sion_0624", + "uuid": "{9EF75475-83C7-459B-A5B1-0BF880D90121}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1195.014, + 247.425, + -859.627 + ], + "size": [ + 18.746, + 11.221, + 15.684 + ], + "groundY": 241.815, + "roofY": 253.036, + "wallCount": 53, + "roofCount": 11 + }, + { + "id": "sion_0625", + "uuid": "{08624A4F-A1ED-4FCE-ABD2-995FBF97EA15}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -804.975, + 22.28, + 52.525 + ], + "size": [ + 31.691, + 20.807, + 36.976 + ], + "groundY": 11.876, + "roofY": 32.683, + "wallCount": 43, + "roofCount": 52 + }, + { + "id": "sion_0626", + "uuid": "{94ADE21D-27D5-456F-B1F0-7C7531F7116D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1075.432, + 237.962, + -873.275 + ], + "size": [ + 21.637, + 9.062, + 18.878 + ], + "groundY": 233.431, + "roofY": 242.493, + "wallCount": 29, + "roofCount": 10 + }, + { + "id": "sion_0627", + "uuid": "{3FB7F947-1D69-4505-8D4E-3A893D367FFA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -1000.018, + 55.561, + -145.272 + ], + "size": [ + 21.106, + 11.78, + 14.55 + ], + "groundY": 49.671, + "roofY": 61.451, + "wallCount": 57, + "roofCount": 23 + }, + { + "id": "sion_0628", + "uuid": "{AFDEDF91-85E0-42C4-ABDA-94B0F1D371E8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1314.619, + 36.272, + 167.489 + ], + "size": [ + 15.215, + 13.284, + 17.298 + ], + "groundY": 29.63, + "roofY": 42.914, + "wallCount": 60, + "roofCount": 25 + }, + { + "id": "sion_0629", + "uuid": "{8B943425-2C6B-4F4E-9C74-516E2D13E1BF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1325.883, + 203.689, + -546.311 + ], + "size": [ + 16.609, + 10.016, + 17.716 + ], + "groundY": 198.681, + "roofY": 208.697, + "wallCount": 36, + "roofCount": 17 + }, + { + "id": "sion_0630", + "uuid": "{40F1CA80-0DB1-4210-971E-C1517272B692}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -547.027, + 28.646, + -70.147 + ], + "size": [ + 20.977, + 12.57, + 16.231 + ], + "groundY": 22.361, + "roofY": 34.931, + "wallCount": 17, + "roofCount": 28 + }, + { + "id": "sion_0631", + "uuid": "{F27BB429-2433-482D-AE6F-672967A823A2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1315.357, + 0.681, + 817.935 + ], + "size": [ + 9.934, + 7.546, + 9.651 + ], + "groundY": -3.092, + "roofY": 4.454, + "wallCount": 35, + "roofCount": 22 + }, + { + "id": "sion_0632", + "uuid": "{CE5DB162-D8D3-4FAF-9A7B-674311C58DB5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -603.066, + 33.289, + -194.857 + ], + "size": [ + 9.102, + 11.2, + 10.233 + ], + "groundY": 27.689, + "roofY": 38.889, + "wallCount": 56, + "roofCount": 10 + }, + { + "id": "sion_0633", + "uuid": "{6428415D-F108-44C3-89B0-9D7C9DD513A3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1067.805, + 82.714, + -214.264 + ], + "size": [ + 19.234, + 13.345, + 18.254 + ], + "groundY": 76.042, + "roofY": 89.386, + "wallCount": 43, + "roofCount": 12 + }, + { + "id": "sion_0634", + "uuid": "{DC0790E8-9319-4012-B20B-D45F01B33C46}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -808.629, + 6.65, + 274.384 + ], + "size": [ + 49.75, + 17.526, + 26.384 + ], + "groundY": -2.113, + "roofY": 15.413, + "wallCount": 51, + "roofCount": 34 + }, + { + "id": "sion_0635", + "uuid": "{5F9A9890-26E3-48BE-9889-F07543823226}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1184.623, + 291.542, + -1382.675 + ], + "size": [ + 20.543, + 11.057, + 17.248 + ], + "groundY": 286.014, + "roofY": 297.07, + "wallCount": 39, + "roofCount": 18 + }, + { + "id": "sion_0636", + "uuid": "{B9E19A3A-2D63-4933-AA19-360006FF6769}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -1019.555, + 2.927, + 298.74 + ], + "size": [ + 13.445, + 12.158, + 16.08 + ], + "groundY": -3.152, + "roofY": 9.006, + "wallCount": 25, + "roofCount": 25 + }, + { + "id": "sion_0637", + "uuid": "{E19AB6C6-A213-4D8D-A2C6-3CC812AA3F6D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -641.074, + 36.404, + -286.264 + ], + "size": [ + 16.703, + 9.388, + 20.046 + ], + "groundY": 31.71, + "roofY": 41.098, + "wallCount": 28, + "roofCount": 11 + }, + { + "id": "sion_0638", + "uuid": "{3B7EE228-DDE3-4485-B68D-921DB51C2A82}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -981.395, + 5.232, + 280.877 + ], + "size": [ + 16.406, + 16.035, + 38.5 + ], + "groundY": -2.785, + "roofY": 13.25, + "wallCount": 26, + "roofCount": 22 + }, + { + "id": "sion_0639", + "uuid": "{770FF37E-30E4-4366-803D-1305B2A53F53}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -949.596, + 3.225, + 300.838 + ], + "size": [ + 15.176, + 12.848, + 13.387 + ], + "groundY": -3.199, + "roofY": 9.649, + "wallCount": 41, + "roofCount": 29 + }, + { + "id": "sion_0640", + "uuid": "{9A9DB608-2295-4608-8C34-45F7A8F8FC8C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -544.068, + 57.789, + -539.352 + ], + "size": [ + 30.863, + 16.528, + 24.806 + ], + "groundY": 49.525, + "roofY": 66.053, + "wallCount": 42, + "roofCount": 20 + }, + { + "id": "sion_0641", + "uuid": "{416047FA-94CB-4A23-9391-ECEBB2932E17}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -772.777, + 74.654, + -453.934 + ], + "size": [ + 18.352, + 10.088, + 23.925 + ], + "groundY": 69.61, + "roofY": 79.698, + "wallCount": 42, + "roofCount": 23 + }, + { + "id": "sion_0642", + "uuid": "{16AD8333-7B86-4ADC-9F5D-3F6E8EA8E7DD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1221.293, + 114.226, + -297.587 + ], + "size": [ + 15.828, + 10.302, + 18.658 + ], + "groundY": 109.075, + "roofY": 119.377, + "wallCount": 26, + "roofCount": 4 + }, + { + "id": "sion_0643", + "uuid": "{8F5BB852-D6C1-4676-B385-D5DA18472A21}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1136.168, + 70.293, + -74.865 + ], + "size": [ + 9.234, + 7.72, + 8.758 + ], + "groundY": 66.433, + "roofY": 74.153, + "wallCount": 46, + "roofCount": 12 + }, + { + "id": "sion_0644", + "uuid": "{5D72EC1F-0C24-4743-9CC6-B6EC1073B9F5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1482.992, + 7.521, + 384.391 + ], + "size": [ + 27.875, + 19.713, + 20.278 + ], + "groundY": -2.335, + "roofY": 17.378, + "wallCount": 53, + "roofCount": 20 + }, + { + "id": "sion_0645", + "uuid": "{D7CD40A8-8891-430C-9161-5370EFB2A46B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1397.453, + 280.013, + -1261.089 + ], + "size": [ + 19.102, + 12.39, + 16.779 + ], + "groundY": 273.818, + "roofY": 286.208, + "wallCount": 31, + "roofCount": 17 + }, + { + "id": "sion_0646", + "uuid": "{AAA9AF5F-56E0-46A0-9347-CADF254C441C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -665.934, + 52.099, + -388.71 + ], + "size": [ + 19.984, + 12.476, + 19.878 + ], + "groundY": 45.861, + "roofY": 58.337, + "wallCount": 13, + "roofCount": 31 + }, + { + "id": "sion_0647", + "uuid": "{591739C7-0896-47E7-8164-31EBCE29658C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1518.744, + 223.735, + -752.134 + ], + "size": [ + 15.832, + 9.672, + 16.83 + ], + "groundY": 218.899, + "roofY": 228.571, + "wallCount": 57, + "roofCount": 33 + }, + { + "id": "sion_0648", + "uuid": "{779EAE00-003A-4F88-AA14-11EBBF03401E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -864.016, + 294.935, + -1503.106 + ], + "size": [ + 15.523, + 9.366, + 17.802 + ], + "groundY": 290.252, + "roofY": 299.618, + "wallCount": 36, + "roofCount": 20 + }, + { + "id": "sion_0649", + "uuid": "{3AF7C755-E384-4E7C-A665-1D48783D9AEF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1328.232, + 281.398, + -1151.46 + ], + "size": [ + 21.254, + 12.062, + 17.958 + ], + "groundY": 275.367, + "roofY": 287.429, + "wallCount": 37, + "roofCount": 17 + }, + { + "id": "sion_0650", + "uuid": "{73F7F6E1-4CB2-4393-B71D-D93A921936D9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1329.557, + 82.718, + -118.631 + ], + "size": [ + 24.277, + 20.613, + 37.17 + ], + "groundY": 72.412, + "roofY": 93.025, + "wallCount": 25, + "roofCount": 21 + }, + { + "id": "sion_0651", + "uuid": "{FE148700-2D27-4962-85BF-E18EB77F6FDC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1158.387, + 281.553, + -1128.91 + ], + "size": [ + 7.523, + 6.883, + 7.04 + ], + "groundY": 278.112, + "roofY": 284.995, + "wallCount": 37, + "roofCount": 16 + }, + { + "id": "sion_0652", + "uuid": "{B714B7D2-C62E-4C81-A5D4-B2DAFA39556F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1243.785, + 281.958, + -1154.11 + ], + "size": [ + 13.125, + 9.301, + 9.564 + ], + "groundY": 277.308, + "roofY": 286.609, + "wallCount": 46, + "roofCount": 31 + }, + { + "id": "sion_0653", + "uuid": "{FCED8671-BE25-460E-B554-7DBFD4EE8A94}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -543.746, + 5.444, + 910.903 + ], + "size": [ + 25.938, + 13.386, + 40.853 + ], + "groundY": -1.249, + "roofY": 12.137, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_0654", + "uuid": "{0FAE753B-ED03-46DB-AA68-F8646BA50160}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -895.961, + 15.271, + 175.371 + ], + "size": [ + 78.648, + 25.074, + 29.139 + ], + "groundY": 2.734, + "roofY": 27.808, + "wallCount": 76, + "roofCount": 46 + }, + { + "id": "sion_0655", + "uuid": "{FFE99530-66A9-40CF-82F8-34B700BBF1E4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -590.131, + 31.417, + -90.06 + ], + "size": [ + 23.871, + 21.109, + 22.088 + ], + "groundY": 20.863, + "roofY": 41.971, + "wallCount": 44, + "roofCount": 18 + }, + { + "id": "sion_0656", + "uuid": "{192F3861-3963-4AA7-AC4A-C77869EFC8A4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -869.58, + 2.978, + 255.683 + ], + "size": [ + 14.16, + 10.064, + 12.476 + ], + "groundY": -2.054, + "roofY": 8.01, + "wallCount": 43, + "roofCount": 23 + }, + { + "id": "sion_0657", + "uuid": "{0810063A-09D5-4CD4-A4C5-D9159B02C2D8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1037.816, + 81.402, + -249.049 + ], + "size": [ + 19.906, + 14.772, + 17.649 + ], + "groundY": 74.016, + "roofY": 88.788, + "wallCount": 59, + "roofCount": 53 + }, + { + "id": "sion_0658", + "uuid": "{D424760D-1A3F-4934-9275-FC54693F272C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -436.395, + 68.343, + -697.525 + ], + "size": [ + 27.562, + 13.242, + 24.36 + ], + "groundY": 61.722, + "roofY": 74.964, + "wallCount": 51, + "roofCount": 50 + }, + { + "id": "sion_0659", + "uuid": "{A16877AA-043B-4FE0-AD63-B38EB695CEA9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -651.771, + 18.85, + 232.07 + ], + "size": [ + 39.231, + 20.207, + 13.55 + ], + "groundY": 8.747, + "roofY": 28.954, + "wallCount": 14, + "roofCount": 24 + }, + { + "id": "sion_0660", + "uuid": "{57403081-34BA-4460-A4E4-D8A357F99FB8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1103.779, + 288.429, + -1272.368 + ], + "size": [ + 17.645, + 10.091, + 13.488 + ], + "groundY": 283.384, + "roofY": 293.475, + "wallCount": 30, + "roofCount": 14 + }, + { + "id": "sion_0661", + "uuid": "{35E1A4C9-878B-463B-9A91-CCFEDD79D224}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1200.678, + 264.509, + -951.402 + ], + "size": [ + 27.973, + 8.858, + 23.032 + ], + "groundY": 260.08, + "roofY": 268.938, + "wallCount": 44, + "roofCount": 14 + }, + { + "id": "sion_0662", + "uuid": "{39049F38-E154-47F4-82EB-00515EDD0061}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1220.803, + 284.553, + -1169.859 + ], + "size": [ + 29.894, + 16.988, + 32.62 + ], + "groundY": 276.059, + "roofY": 293.047, + "wallCount": 102, + "roofCount": 41 + }, + { + "id": "sion_0663", + "uuid": "{808DDED0-AFB6-458F-B5F3-E400236C189A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -631.287, + 29.176, + -3.75 + ], + "size": [ + 20.285, + 24.676, + 35.42 + ], + "groundY": 16.838, + "roofY": 41.514, + "wallCount": 14, + "roofCount": 17 + }, + { + "id": "sion_0664", + "uuid": "{B76274A2-A47F-4EF7-ACDF-323AB11F5A60}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -973.355, + 54.952, + -154.842 + ], + "size": [ + 24.898, + 12.004, + 15.436 + ], + "groundY": 48.95, + "roofY": 60.954, + "wallCount": 51, + "roofCount": 21 + }, + { + "id": "sion_0665", + "uuid": "{D890AD2D-D9C5-41CA-B0BE-31EB52FFBE83}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -524.738, + 15.961, + 337.031 + ], + "size": [ + 162.578, + 31.243, + 97.446 + ], + "groundY": 0.34, + "roofY": 31.582, + "wallCount": 137, + "roofCount": 53 + }, + { + "id": "sion_0666", + "uuid": "{0BF8F20B-75E7-4C49-A22B-F189613AA9EA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1120.996, + 135.904, + -436.736 + ], + "size": [ + 14.141, + 12.821, + 16.096 + ], + "groundY": 129.494, + "roofY": 142.315, + "wallCount": 54, + "roofCount": 13 + }, + { + "id": "sion_0667", + "uuid": "{4E1A285D-0B82-4927-90AD-1472B22AF6DC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -674.975, + 1.961, + 991.64 + ], + "size": [ + 10.074, + 6.004, + 17.981 + ], + "groundY": -1.041, + "roofY": 4.963, + "wallCount": 33, + "roofCount": 6 + }, + { + "id": "sion_0668", + "uuid": "{4C96CE9B-D8F5-489B-90FD-A411CFE40AB4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1258.615, + 216.61, + -745.857 + ], + "size": [ + 24.473, + 10.883, + 19.157 + ], + "groundY": 211.169, + "roofY": 222.052, + "wallCount": 33, + "roofCount": 60 + }, + { + "id": "sion_0669", + "uuid": "{50E604C5-8E55-4F7F-BBCE-1E41DCCCFDC2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -715.951, + 3.768, + 318.702 + ], + "size": [ + 14.121, + 11.999, + 11.602 + ], + "groundY": -2.231, + "roofY": 9.768, + "wallCount": 50, + "roofCount": 20 + }, + { + "id": "sion_0670", + "uuid": "{9CDFD173-CA90-4D95-8020-2C88856C32EA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1300.555, + 282.539, + -1128.549 + ], + "size": [ + 31.75, + 13.996, + 21.939 + ], + "groundY": 275.541, + "roofY": 289.537, + "wallCount": 75, + "roofCount": 38 + }, + { + "id": "sion_0671", + "uuid": "{047549A2-BA16-406F-8576-65B5C5E79F26}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -870.691, + 26.357, + -117.331 + ], + "size": [ + 23.641, + 15.808, + 21.387 + ], + "groundY": 18.453, + "roofY": 34.261, + "wallCount": 33, + "roofCount": 8 + }, + { + "id": "sion_0672", + "uuid": "{226BABEF-7AA4-4D6B-BE32-E52EC7BEE1FA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1496.693, + 229.476, + -647.445 + ], + "size": [ + 26.621, + 9.19, + 24.158 + ], + "groundY": 224.881, + "roofY": 234.071, + "wallCount": 24, + "roofCount": 24 + }, + { + "id": "sion_0673", + "uuid": "{4A45502D-D77F-49B7-8DE3-2B268687776A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -742.684, + 67.61, + -450.865 + ], + "size": [ + 18.164, + 10.76, + 24.168 + ], + "groundY": 62.23, + "roofY": 72.99, + "wallCount": 56, + "roofCount": 21 + }, + { + "id": "sion_0674", + "uuid": "{314D6E66-2777-47F2-8863-662E1F3C3D37}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -958.564, + 296.503, + -1491.296 + ], + "size": [ + 19.105, + 9.936, + 14.727 + ], + "groundY": 291.535, + "roofY": 301.471, + "wallCount": 36, + "roofCount": 13 + }, + { + "id": "sion_0675", + "uuid": "{608CAFAA-3DAF-4FF7-B406-6A49EAADE3BA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1298.336, + 34.033, + 151.232 + ], + "size": [ + 16.281, + 16.295, + 17.38 + ], + "groundY": 25.885, + "roofY": 42.18, + "wallCount": 80, + "roofCount": 25 + }, + { + "id": "sion_0676", + "uuid": "{6674F8A7-2598-47DD-867D-36DD162AAFF1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1068.504, + 77.475, + -172.962 + ], + "size": [ + 26.758, + 13.212, + 27.13 + ], + "groundY": 70.869, + "roofY": 84.081, + "wallCount": 48, + "roofCount": 16 + }, + { + "id": "sion_0677", + "uuid": "{0C76DAF6-9825-4AE0-B157-A4E6C80D129D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1212.836, + 118.363, + -337.539 + ], + "size": [ + 9.633, + 8.725, + 16.391 + ], + "groundY": 114.001, + "roofY": 122.726, + "wallCount": 26, + "roofCount": 2 + }, + { + "id": "sion_0678", + "uuid": "{B05F0FC4-57B8-4691-A209-81CA6F7C74D7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1128.82, + 2.963, + 397.056 + ], + "size": [ + 13.164, + 12.222, + 33.672 + ], + "groundY": -3.148, + "roofY": 9.074, + "wallCount": 21, + "roofCount": 21 + }, + { + "id": "sion_0679", + "uuid": "{6E8F923A-C785-4A9D-B780-C704720D565D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1511.17, + 157.753, + -341.112 + ], + "size": [ + 12.262, + 11.533, + 14.258 + ], + "groundY": 151.986, + "roofY": 163.519, + "wallCount": 50, + "roofCount": 10 + }, + { + "id": "sion_0680", + "uuid": "{AAA83B37-7568-4801-B0FE-30D386755EC9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1198.205, + 286.522, + -1189.539 + ], + "size": [ + 18.137, + 13.469, + 20.082 + ], + "groundY": 279.788, + "roofY": 293.257, + "wallCount": 27, + "roofCount": 20 + }, + { + "id": "sion_0681", + "uuid": "{3FA03437-9E2B-48BF-A0DE-E86675A46D3E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -714.076, + 294.327, + -1253.514 + ], + "size": [ + 23.543, + 15.298, + 19.804 + ], + "groundY": 286.678, + "roofY": 301.976, + "wallCount": 22, + "roofCount": 9 + }, + { + "id": "sion_0682", + "uuid": "{D0A43AE3-C126-4372-A984-9E610484A513}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1270.369, + 231.862, + -782.969 + ], + "size": [ + 18.856, + 9.437, + 18.032 + ], + "groundY": 227.143, + "roofY": 236.58, + "wallCount": 48, + "roofCount": 25 + }, + { + "id": "sion_0683", + "uuid": "{23E20763-8E5D-4361-9090-C6113A71ECA6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1263.512, + 281.063, + -1092.769 + ], + "size": [ + 11.148, + 11.374, + 17.819 + ], + "groundY": 275.376, + "roofY": 286.75, + "wallCount": 45, + "roofCount": 26 + }, + { + "id": "sion_0684", + "uuid": "{21B4E2A4-7F39-4A60-83AF-3F48D98019C8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1310.83, + 19.746, + 541.262 + ], + "size": [ + 41.777, + 44.946, + 47.238 + ], + "groundY": -2.727, + "roofY": 42.218, + "wallCount": 55, + "roofCount": 21 + }, + { + "id": "sion_0685", + "uuid": "{E842474C-ED50-49DB-B86D-83617BDA36EA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -472.465, + 6.052, + 885.773 + ], + "size": [ + 22.531, + 14.046, + 31.622 + ], + "groundY": -0.971, + "roofY": 13.075, + "wallCount": 45, + "roofCount": 16 + }, + { + "id": "sion_0686", + "uuid": "{EA189F86-26ED-489F-8A1C-B7988D5D9138}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -776.461, + 2.03, + 570.112 + ], + "size": [ + 18.961, + 7.024, + 19.04 + ], + "groundY": -1.482, + "roofY": 5.542, + "wallCount": 13, + "roofCount": 2 + }, + { + "id": "sion_0687", + "uuid": "{93E01D73-A655-4B66-BC5D-719377477B23}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -1011.842, + 63.401, + -172.264 + ], + "size": [ + 41.441, + 16.46, + 26.06 + ], + "groundY": 55.171, + "roofY": 71.631, + "wallCount": 61, + "roofCount": 43 + }, + { + "id": "sion_0688", + "uuid": "{C3AA4B4A-017D-44B2-AC4F-EBB8DA359200}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -985.697, + 43.062, + -118.198 + ], + "size": [ + 29.371, + 11.212, + 23.088 + ], + "groundY": 37.456, + "roofY": 48.668, + "wallCount": 47, + "roofCount": 10 + }, + { + "id": "sion_0689", + "uuid": "{4AA9DE9D-624C-4AA6-8C43-D7DFFD53F093}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1338.852, + 279.509, + -1086.623 + ], + "size": [ + 19.609, + 11.3, + 20.504 + ], + "groundY": 273.859, + "roofY": 285.159, + "wallCount": 43, + "roofCount": 13 + }, + { + "id": "sion_0690", + "uuid": "{CDA6FEF3-FBC3-4C0B-A485-4A27F88F8289}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1094.842, + 218.136, + -806.487 + ], + "size": [ + 23.363, + 6.028, + 21.074 + ], + "groundY": 215.122, + "roofY": 221.15, + "wallCount": 29, + "roofCount": 9 + }, + { + "id": "sion_0691", + "uuid": "{3C54ADAA-D29D-4CBB-95CA-4EFACD45AE44}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -666.211, + 76.76, + -528.389 + ], + "size": [ + 45.602, + 15.033, + 29.69 + ], + "groundY": 69.244, + "roofY": 84.277, + "wallCount": 27, + "roofCount": 49 + }, + { + "id": "sion_0692", + "uuid": "{B99499D2-5228-4825-B88E-BBDB46B35B04}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -598.109, + 21.969, + 196.618 + ], + "size": [ + 41.117, + 25.545, + 80.191 + ], + "groundY": 9.197, + "roofY": 34.742, + "wallCount": 62, + "roofCount": 53 + }, + { + "id": "sion_0693", + "uuid": "{1F4B9C67-D91B-4161-AA2B-BC841BAD5A9F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1428.701, + 277.16, + -1214.032 + ], + "size": [ + 27.379, + 17.088, + 30.942 + ], + "groundY": 268.616, + "roofY": 285.704, + "wallCount": 72, + "roofCount": 32 + }, + { + "id": "sion_0694", + "uuid": "{2B9ECAA0-484B-4EF0-A209-C624ECAAA577}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1301.176, + 123.986, + -300.342 + ], + "size": [ + 17.562, + 9.986, + 16.458 + ], + "groundY": 118.993, + "roofY": 128.979, + "wallCount": 39, + "roofCount": 6 + }, + { + "id": "sion_0695", + "uuid": "{1A55D5E0-8E4E-4049-A40B-8FBB7CCA92A7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1237.795, + 294.933, + -1413.296 + ], + "size": [ + 18.762, + 11.738, + 14.146 + ], + "groundY": 289.064, + "roofY": 300.802, + "wallCount": 37, + "roofCount": 34 + }, + { + "id": "sion_0696", + "uuid": "{CA786191-9F21-4A35-BABA-B408FD793EDD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -565.943, + 5.877, + 452.458 + ], + "size": [ + 23.035, + 12.332, + 13.809 + ], + "groundY": -0.289, + "roofY": 12.043, + "wallCount": 32, + "roofCount": 9 + }, + { + "id": "sion_0697", + "uuid": "{B92F34B7-B8D8-4C70-94C2-CB61E4E734ED}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1370.365, + 19.366, + 559.208 + ], + "size": [ + 47.856, + 44.862, + 47.773 + ], + "groundY": -3.065, + "roofY": 41.797, + "wallCount": 129, + "roofCount": 36 + }, + { + "id": "sion_0698", + "uuid": "{0C5D0802-7FA2-4C19-B69C-D32618D89392}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -926.473, + 62.245, + -216.533 + ], + "size": [ + 20.547, + 12.553, + 21.034 + ], + "groundY": 55.969, + "roofY": 68.522, + "wallCount": 31, + "roofCount": 11 + }, + { + "id": "sion_0699", + "uuid": "{4EA4DB14-3917-4ECA-A9D8-D8E8F53FFC64}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -662.072, + 62.099, + -472.255 + ], + "size": [ + 18.527, + 11.226, + 19.954 + ], + "groundY": 56.486, + "roofY": 67.712, + "wallCount": 31, + "roofCount": 13 + }, + { + "id": "sion_0700", + "uuid": "{E8997395-8DF2-4AD1-B842-0D0AFD6182E0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1324.537, + 0.013, + 596.08 + ], + "size": [ + 17.902, + 6.316, + 36.391 + ], + "groundY": -3.145, + "roofY": 3.171, + "wallCount": 30, + "roofCount": 15 + }, + { + "id": "sion_0701", + "uuid": "{A4A9B984-201D-432B-8665-AF5F3E69E9E4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -569.81, + 34.372, + -112.733 + ], + "size": [ + 21.059, + 23.728, + 21.164 + ], + "groundY": 22.508, + "roofY": 46.236, + "wallCount": 26, + "roofCount": 14 + }, + { + "id": "sion_0702", + "uuid": "{9885A42B-7EE0-4DB8-A553-3D9BF1192266}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -746.518, + 98.825, + -594.765 + ], + "size": [ + 17.996, + 8.425, + 15.515 + ], + "groundY": 94.613, + "roofY": 103.038, + "wallCount": 33, + "roofCount": 8 + }, + { + "id": "sion_0703", + "uuid": "{2CA2003E-8444-470B-B7CB-B86DED33BEC1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -1018.846, + 295.846, + -1234.961 + ], + "size": [ + 28.301, + 11.513, + 16.883 + ], + "groundY": 290.09, + "roofY": 301.602, + "wallCount": 31, + "roofCount": 14 + }, + { + "id": "sion_0704", + "uuid": "{6F7BCA88-0F48-407F-B4C2-ED60CB7ADFFF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -975.373, + 11.063, + 60.992 + ], + "size": [ + 61.199, + 8.838, + 72.227 + ], + "groundY": 6.644, + "roofY": 15.482, + "wallCount": 104, + "roofCount": 61 + }, + { + "id": "sion_0705", + "uuid": "{AEF3E96C-F0A0-4646-B7A2-F99193A09FBF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1175.729, + 266.923, + -989.367 + ], + "size": [ + 16.41, + 10.098, + 11.643 + ], + "groundY": 261.874, + "roofY": 271.972, + "wallCount": 40, + "roofCount": 32 + }, + { + "id": "sion_0706", + "uuid": "{0D94E19D-796C-4DFF-B3E7-687F45360F20}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -502.523, + 28.76, + 37.5 + ], + "size": [ + 39.906, + 23.033, + 29.504 + ], + "groundY": 17.243, + "roofY": 40.276, + "wallCount": 19, + "roofCount": 22 + }, + { + "id": "sion_0707", + "uuid": "{9110CBEC-C89F-403C-B89B-145C0A752E28}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -436.303, + 2.342, + 698.557 + ], + "size": [ + 34.371, + 6.679, + 20.642 + ], + "groundY": -0.997, + "roofY": 5.682, + "wallCount": 36, + "roofCount": 16 + }, + { + "id": "sion_0708", + "uuid": "{96B86CCF-2E87-40A4-A2F0-030EB7B62FB4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -657.873, + 26.014, + 3.759 + ], + "size": [ + 16.215, + 15.306, + 16.25 + ], + "groundY": 18.361, + "roofY": 33.667, + "wallCount": 49, + "roofCount": 66 + }, + { + "id": "sion_0709", + "uuid": "{FB3A2278-E204-4604-A4A2-CA248A0E96A4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -714.811, + 5.029, + 455.434 + ], + "size": [ + 95.066, + 13.429, + 95.372 + ], + "groundY": -1.685, + "roofY": 11.744, + "wallCount": 56, + "roofCount": 22 + }, + { + "id": "sion_0710", + "uuid": "{8C01A7FF-C481-48AF-A142-BECC88EAB85D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1135.328, + 105.642, + -282.602 + ], + "size": [ + 22.117, + 13.177, + 16.741 + ], + "groundY": 99.054, + "roofY": 112.231, + "wallCount": 45, + "roofCount": 16 + }, + { + "id": "sion_0711", + "uuid": "{B8209ACA-B04A-4534-8B7F-82BD3AA73B61}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -504.348, + 54.363, + -523.475 + ], + "size": [ + 44.992, + 20.761, + 34.944 + ], + "groundY": 43.983, + "roofY": 64.744, + "wallCount": 26, + "roofCount": 29 + }, + { + "id": "sion_0712", + "uuid": "{F98B7CF0-B988-4921-A6AB-4664A346B647}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1377.039, + 222.812, + -708.897 + ], + "size": [ + 20.883, + 10.632, + 19.819 + ], + "groundY": 217.496, + "roofY": 228.128, + "wallCount": 41, + "roofCount": 32 + }, + { + "id": "sion_0713", + "uuid": "{C1E8F037-6500-426D-A9F2-B8171309F89D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -495.859, + 276.394, + -1350.554 + ], + "size": [ + 8.281, + 5.736, + 8.96 + ], + "groundY": 273.526, + "roofY": 279.262, + "wallCount": 49, + "roofCount": 14 + }, + { + "id": "sion_0714", + "uuid": "{7BC294A8-1BDB-4593-A3E3-1A2FEB5EAAA2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1529.33, + 221.208, + -568.334 + ], + "size": [ + 16.019, + 11.363, + 21.478 + ], + "groundY": 215.527, + "roofY": 226.889, + "wallCount": 36, + "roofCount": 11 + }, + { + "id": "sion_0715", + "uuid": "{79DA8FF3-972A-4833-B5AF-09AEF0D50B8F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1381.551, + 6.574, + 264.434 + ], + "size": [ + 76.023, + 14.155, + 48.256 + ], + "groundY": -0.504, + "roofY": 13.651, + "wallCount": 131, + "roofCount": 53 + }, + { + "id": "sion_0716", + "uuid": "{18B7713B-C4BF-47E6-9DB3-FE77D24F8FFE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -444.625, + 2.306, + 884.308 + ], + "size": [ + 20.414, + 6.083, + 17.354 + ], + "groundY": -0.735, + "roofY": 5.348, + "wallCount": 32, + "roofCount": 10 + }, + { + "id": "sion_0717", + "uuid": "{FA84E205-46EB-4E09-8673-D5C66F487290}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 0, + 1 + ], + "center": [ + -1125.189, + 206.966, + -732.917 + ], + "size": [ + 26.442, + 4.606, + 25.818 + ], + "groundY": 204.663, + "roofY": 209.269, + "wallCount": 12, + "roofCount": 2 + }, + { + "id": "sion_0718", + "uuid": "{F6D42720-16B3-4FAB-B4E5-822D1149A9AF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -651.564, + 51.728, + -406.067 + ], + "size": [ + 18.996, + 10.416, + 19.013 + ], + "groundY": 46.52, + "roofY": 56.936, + "wallCount": 16, + "roofCount": 13 + }, + { + "id": "sion_0719", + "uuid": "{35223B8F-B666-41B1-BA5E-FA5460557248}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1338.758, + 290.017, + -1403.857 + ], + "size": [ + 17.68, + 11.336, + 15.832 + ], + "groundY": 284.349, + "roofY": 295.685, + "wallCount": 20, + "roofCount": 12 + }, + { + "id": "sion_0720", + "uuid": "{E1B12BB4-F4F2-4937-8032-9625069617AA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1268.273, + 278.666, + -1069.856 + ], + "size": [ + 30.328, + 14.839, + 18.661 + ], + "groundY": 271.247, + "roofY": 286.086, + "wallCount": 40, + "roofCount": 16 + }, + { + "id": "sion_0721", + "uuid": "{1C6F6767-9A27-44C3-98C0-519F769ECBB6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -1019.043, + 93.964, + -321.065 + ], + "size": [ + 21.656, + 13.809, + 20.278 + ], + "groundY": 87.06, + "roofY": 100.869, + "wallCount": 34, + "roofCount": 13 + }, + { + "id": "sion_0722", + "uuid": "{73D8AAB8-4791-4050-9345-3C579AF9FB7C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -526.625, + 76.881, + -699.438 + ], + "size": [ + 19.281, + 9.497, + 18.329 + ], + "groundY": 72.132, + "roofY": 81.629, + "wallCount": 15, + "roofCount": 11 + }, + { + "id": "sion_0723", + "uuid": "{E5220A23-87A2-44CB-8200-C8A7E8A9F92B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -968.981, + 73.242, + -239.754 + ], + "size": [ + 28.75, + 12.798, + 30.83 + ], + "groundY": 66.843, + "roofY": 79.641, + "wallCount": 99, + "roofCount": 99 + }, + { + "id": "sion_0724", + "uuid": "{D74A9571-9A2D-4696-9C40-4D2D5BABB674}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 2 + ], + "center": [ + -902.537, + 33.291, + -150.977 + ], + "size": [ + 45.387, + 20.658, + 39.477 + ], + "groundY": 22.962, + "roofY": 43.62, + "wallCount": 83, + "roofCount": 26 + }, + { + "id": "sion_0725", + "uuid": "{A6026478-E80E-4BF9-AE08-168F41443A2E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1405.891, + 227.551, + -746.251 + ], + "size": [ + 16.891, + 5.546, + 17.223 + ], + "groundY": 224.778, + "roofY": 230.324, + "wallCount": 30, + "roofCount": 10 + }, + { + "id": "sion_0726", + "uuid": "{5407F250-DD3A-45CE-9269-C300AE3ADA5D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -884.555, + 16.931, + 123.358 + ], + "size": [ + 30.0, + 17.403, + 16.483 + ], + "groundY": 8.23, + "roofY": 25.633, + "wallCount": 37, + "roofCount": 44 + }, + { + "id": "sion_0727", + "uuid": "{05B720C4-3297-4472-BA77-367A8BC0F7A1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1029.494, + 102.072, + -404.697 + ], + "size": [ + 20.316, + 12.764, + 18.774 + ], + "groundY": 95.69, + "roofY": 108.454, + "wallCount": 36, + "roofCount": 33 + }, + { + "id": "sion_0728", + "uuid": "{E061BA6E-0ACB-4922-9395-00083DA9C073}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1163.568, + 109.819, + -318.156 + ], + "size": [ + 12.731, + 7.064, + 16.034 + ], + "groundY": 106.287, + "roofY": 113.351, + "wallCount": 46, + "roofCount": 21 + }, + { + "id": "sion_0729", + "uuid": "{33F75874-95F2-4E7F-BA72-BAB7E04C8C88}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -676.584, + 4.036, + 328.521 + ], + "size": [ + 15.652, + 11.792, + 13.294 + ], + "groundY": -1.86, + "roofY": 9.932, + "wallCount": 33, + "roofCount": 9 + }, + { + "id": "sion_0730", + "uuid": "{E5B13EB3-5E30-4D28-BB27-CF012E1B0475}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -488.188, + 2.784, + 826.426 + ], + "size": [ + 23.195, + 7.65, + 14.786 + ], + "groundY": -1.041, + "roofY": 6.609, + "wallCount": 38, + "roofCount": 20 + }, + { + "id": "sion_0731", + "uuid": "{938DB147-3B24-47B0-AE87-B7067252DEA3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1084.148, + 262.116, + -948.139 + ], + "size": [ + 23.008, + 12.171, + 20.8 + ], + "groundY": 256.03, + "roofY": 268.201, + "wallCount": 34, + "roofCount": 24 + }, + { + "id": "sion_0732", + "uuid": "{B34F8CF4-EB4E-464F-B7B9-5DCE7E3C5621}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1331.311, + 4.857, + 749.967 + ], + "size": [ + 56.699, + 16.214, + 47.238 + ], + "groundY": -3.25, + "roofY": 12.964, + "wallCount": 14, + "roofCount": 2 + }, + { + "id": "sion_0733", + "uuid": "{B09BB013-BFF7-4C50-8390-3A5D57F9FB91}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1332.939, + 289.451, + -1446.333 + ], + "size": [ + 21.942, + 11.014, + 17.705 + ], + "groundY": 283.944, + "roofY": 294.958, + "wallCount": 41, + "roofCount": 33 + }, + { + "id": "sion_0734", + "uuid": "{94D81FBF-9FB1-452A-8A70-C0F3524E70DF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1151.246, + 0.454, + 647.958 + ], + "size": [ + 75.719, + 7.075, + 43.887 + ], + "groundY": -3.083, + "roofY": 3.992, + "wallCount": 28, + "roofCount": 12 + }, + { + "id": "sion_0735", + "uuid": "{C7332EA6-44EA-4612-914F-68973DB18153}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -799.652, + 2.827, + 937.481 + ], + "size": [ + 46.266, + 9.365, + 30.2 + ], + "groundY": -1.855, + "roofY": 7.51, + "wallCount": 40, + "roofCount": 29 + }, + { + "id": "sion_0736", + "uuid": "{EECC6C51-9E3C-45C9-9AC3-744573AEEF10}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -1005.939, + 292.392, + -1322.924 + ], + "size": [ + 23.817, + 12.418, + 18.954 + ], + "groundY": 286.183, + "roofY": 298.601, + "wallCount": 40, + "roofCount": 33 + }, + { + "id": "sion_0737", + "uuid": "{F49CBE6A-2A8B-4860-B4B2-BE2CEDBEB4AD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1429.795, + 5.352, + 337.072 + ], + "size": [ + 15.309, + 13.475, + 15.144 + ], + "groundY": -1.385, + "roofY": 12.09, + "wallCount": 55, + "roofCount": 42 + }, + { + "id": "sion_0738", + "uuid": "{87BDF9E4-4CFB-4F31-ABE9-DC1CCB819ECB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1359.266, + 236.489, + -793.233 + ], + "size": [ + 16.203, + 12.562, + 18.524 + ], + "groundY": 230.208, + "roofY": 242.77, + "wallCount": 43, + "roofCount": 8 + }, + { + "id": "sion_0739", + "uuid": "{FF5F9314-FC59-47A0-887E-7C1411C68E48}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1294.797, + 273.69, + -1207.235 + ], + "size": [ + 11.086, + 10.717, + 11.49 + ], + "groundY": 268.331, + "roofY": 279.048, + "wallCount": 49, + "roofCount": 16 + }, + { + "id": "sion_0740", + "uuid": "{0862D35C-7C65-4B6E-A7EF-5EA55F98491D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -744.508, + 296.036, + -1201.011 + ], + "size": [ + 29.281, + 16.05, + 26.424 + ], + "groundY": 288.011, + "roofY": 304.061, + "wallCount": 10, + "roofCount": 7 + }, + { + "id": "sion_0741", + "uuid": "{61D2199F-69EE-41E8-AD3A-03BD4E917B84}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1495.48, + 223.056, + -607.07 + ], + "size": [ + 9.117, + 6.128, + 9.288 + ], + "groundY": 219.992, + "roofY": 226.12, + "wallCount": 60, + "roofCount": 2 + }, + { + "id": "sion_0742", + "uuid": "{E98047BA-3468-4D7E-BD12-910B5242695D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1362.814, + 219.286, + -669.851 + ], + "size": [ + 67.176, + 13.176, + 45.677 + ], + "groundY": 212.698, + "roofY": 225.874, + "wallCount": 118, + "roofCount": 76 + }, + { + "id": "sion_0743", + "uuid": "{8AD96849-3CCC-4992-9189-86F586DBDB92}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -879.787, + 295.886, + -1436.787 + ], + "size": [ + 20.395, + 9.197, + 23.672 + ], + "groundY": 291.288, + "roofY": 300.485, + "wallCount": 29, + "roofCount": 12 + }, + { + "id": "sion_0744", + "uuid": "{83566271-5169-425C-B992-F2413A1AF3A5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -664.494, + 25.9, + 63.951 + ], + "size": [ + 46.512, + 24.174, + 42.605 + ], + "groundY": 13.813, + "roofY": 37.987, + "wallCount": 92, + "roofCount": 41 + }, + { + "id": "sion_0745", + "uuid": "{509EFAD1-DBFB-4089-BCCB-2D0C3E3D6D1E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1167.756, + 247.301, + -867.597 + ], + "size": [ + 15.121, + 9.964, + 17.762 + ], + "groundY": 242.319, + "roofY": 252.283, + "wallCount": 38, + "roofCount": 19 + }, + { + "id": "sion_0746", + "uuid": "{DD2B4E42-48D4-4DFB-999A-F4F9B9DE578B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -968.846, + 292.38, + -1337.563 + ], + "size": [ + 23.816, + 12.442, + 18.962 + ], + "groundY": 286.159, + "roofY": 298.601, + "wallCount": 44, + "roofCount": 29 + }, + { + "id": "sion_0747", + "uuid": "{2AF26732-2470-4188-AFD2-ABC7DDED3D0C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1083.373, + 268.715, + -994.518 + ], + "size": [ + 12.473, + 10.62, + 16.92 + ], + "groundY": 263.405, + "roofY": 274.025, + "wallCount": 41, + "roofCount": 16 + }, + { + "id": "sion_0748", + "uuid": "{C8EF4B29-2B4D-4867-8D51-22F950D3D062}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -573.076, + 10.707, + 397.117 + ], + "size": [ + 45.684, + 22.664, + 35.189 + ], + "groundY": -0.625, + "roofY": 22.04, + "wallCount": 30, + "roofCount": 18 + }, + { + "id": "sion_0749", + "uuid": "{9449298B-9F4E-4C32-BFF3-B7DBBF72666B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1330.031, + 279.632, + -1097.304 + ], + "size": [ + 14.555, + 9.064, + 15.4 + ], + "groundY": 275.1, + "roofY": 284.164, + "wallCount": 46, + "roofCount": 14 + }, + { + "id": "sion_0750", + "uuid": "{BC70D57D-E7B2-41B9-A70A-9D405055A4A0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -926.229, + 290.919, + -1291.397 + ], + "size": [ + 16.41, + 10.852, + 14.612 + ], + "groundY": 285.493, + "roofY": 296.345, + "wallCount": 57, + "roofCount": 13 + }, + { + "id": "sion_0751", + "uuid": "{2C6583D5-BBB7-4141-B93E-625B564AAA8F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1289.818, + 231.956, + -770.492 + ], + "size": [ + 21.84, + 10.912, + 16.63 + ], + "groundY": 226.5, + "roofY": 237.412, + "wallCount": 35, + "roofCount": 21 + }, + { + "id": "sion_0752", + "uuid": "{253DD958-840E-421B-A554-0A254AB29319}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -520.971, + 7.592, + 480.229 + ], + "size": [ + 16.191, + 15.28, + 18.173 + ], + "groundY": -0.048, + "roofY": 15.232, + "wallCount": 25, + "roofCount": 44 + }, + { + "id": "sion_0753", + "uuid": "{4E0B6103-D70C-4C51-ABFC-8391D16DC317}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1205.949, + 3.925, + 796.701 + ], + "size": [ + 12.234, + 10.593, + 12.391 + ], + "groundY": -1.372, + "roofY": 9.221, + "wallCount": 45, + "roofCount": 16 + }, + { + "id": "sion_0754", + "uuid": "{F397AD1E-6FE5-4598-93D2-C9F2F4C12E32}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -564.178, + 77.869, + -675.058 + ], + "size": [ + 19.363, + 12.3, + 16.929 + ], + "groundY": 71.719, + "roofY": 84.019, + "wallCount": 21, + "roofCount": 24 + }, + { + "id": "sion_0755", + "uuid": "{EB034DB5-8D6C-46D9-9042-3EDB46CE2EA7}", + "name": "", + "class": "Treibhaus", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -944.738, + 0.22, + 449.044 + ], + "size": [ + 6.969, + 5.177, + 15.08 + ], + "groundY": -2.368, + "roofY": 2.808, + "wallCount": 30, + "roofCount": 2 + }, + { + "id": "sion_0756", + "uuid": "{B4A5D3E2-AF11-4FE6-9B2D-85241ABAF9B5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -709.158, + 90.439, + -549.786 + ], + "size": [ + 38.199, + 14.738, + 44.664 + ], + "groundY": 83.07, + "roofY": 97.808, + "wallCount": 65, + "roofCount": 43 + }, + { + "id": "sion_0757", + "uuid": "{DCE5E9A7-3217-4752-A1D2-8D54B873A0E9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1482.646, + 153.417, + -334.074 + ], + "size": [ + 19.285, + 12.973, + 17.435 + ], + "groundY": 146.931, + "roofY": 159.904, + "wallCount": 66, + "roofCount": 26 + }, + { + "id": "sion_0758", + "uuid": "{9F43295F-8BF4-4D9E-B820-A7FFB53A5434}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -888.832, + 63.832, + -221.45 + ], + "size": [ + 21.297, + 12.81, + 20.664 + ], + "groundY": 57.427, + "roofY": 70.237, + "wallCount": 151, + "roofCount": 22 + }, + { + "id": "sion_0759", + "uuid": "{B9981D95-CE18-478B-AE1C-A01B5395EED4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -928.897, + 50.164, + -179.783 + ], + "size": [ + 48.699, + 12.202, + 41.052 + ], + "groundY": 44.063, + "roofY": 56.265, + "wallCount": 81, + "roofCount": 24 + }, + { + "id": "sion_0760", + "uuid": "{35860CF8-42DC-42F0-A6DF-96D2D2436347}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1065.98, + 219.848, + -816.608 + ], + "size": [ + 35.422, + 8.942, + 24.308 + ], + "groundY": 215.377, + "roofY": 224.319, + "wallCount": 22, + "roofCount": 6 + }, + { + "id": "sion_0761", + "uuid": "{E2C31138-AB5F-4722-8D3A-9CAD5CB6BBEF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1111.008, + 18.452, + 40.739 + ], + "size": [ + 40.18, + 22.398, + 34.986 + ], + "groundY": 7.253, + "roofY": 29.651, + "wallCount": 58, + "roofCount": 20 + }, + { + "id": "sion_0762", + "uuid": "{85F031D9-F966-4FF3-B6E4-32B618AFC869}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -827.457, + 63.142, + -246.962 + ], + "size": [ + 19.586, + 8.0, + 16.238 + ], + "groundY": 59.142, + "roofY": 67.142, + "wallCount": 34, + "roofCount": 16 + }, + { + "id": "sion_0763", + "uuid": "{33090183-F0DB-4CF6-89D9-18DFA257A827}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -403.25, + 55.935, + -660.245 + ], + "size": [ + 9.57, + 4.687, + 10.588 + ], + "groundY": 53.592, + "roofY": 58.279, + "wallCount": 25, + "roofCount": 2 + }, + { + "id": "sion_0764", + "uuid": "{A528E8F1-E199-41DF-A076-A3AEBAD61D68}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 2 + ], + "center": [ + -816.002, + 27.469, + -98.928 + ], + "size": [ + 32.309, + 19.386, + 29.66 + ], + "groundY": 17.776, + "roofY": 37.162, + "wallCount": 51, + "roofCount": 11 + }, + { + "id": "sion_0765", + "uuid": "{EC784D1E-6746-471A-8779-CB8C64733B8F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -842.037, + 25.145, + -83.494 + ], + "size": [ + 19.16, + 16.728, + 18.258 + ], + "groundY": 16.781, + "roofY": 33.509, + "wallCount": 55, + "roofCount": 39 + }, + { + "id": "sion_0766", + "uuid": "{8641E37A-6A86-44BD-8503-90670BB4D9FE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -594.008, + 85.634, + -683.74 + ], + "size": [ + 20.477, + 10.401, + 16.018 + ], + "groundY": 80.433, + "roofY": 90.834, + "wallCount": 34, + "roofCount": 16 + }, + { + "id": "sion_0767", + "uuid": "{BA2AE074-DD07-4F08-A85C-F6D7CEB6BFC7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -607.318, + 80.778, + -651.308 + ], + "size": [ + 18.449, + 10.002, + 21.59 + ], + "groundY": 75.777, + "roofY": 85.779, + "wallCount": 32, + "roofCount": 6 + }, + { + "id": "sion_0768", + "uuid": "{AB203FDD-8A19-42C0-A2C9-3210A55EAD61}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -754.641, + 5.345, + 317.837 + ], + "size": [ + 51.453, + 19.969, + 22.725 + ], + "groundY": -4.639, + "roofY": 15.33, + "wallCount": 68, + "roofCount": 70 + }, + { + "id": "sion_0769", + "uuid": "{9D6CCAB5-1D8B-4F70-9802-3053480D3144}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1302.877, + 204.476, + -583.592 + ], + "size": [ + 21.676, + 9.47, + 16.376 + ], + "groundY": 199.741, + "roofY": 209.211, + "wallCount": 38, + "roofCount": 32 + }, + { + "id": "sion_0770", + "uuid": "{E3402738-CAB3-4B5D-BAE2-4014EAA50D21}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1354.447, + 201.451, + -521.248 + ], + "size": [ + 28.926, + 8.57, + 15.549 + ], + "groundY": 197.166, + "roofY": 205.736, + "wallCount": 26, + "roofCount": 13 + }, + { + "id": "sion_0771", + "uuid": "{483C46FD-2253-4F40-B00A-ABCE59D4EBA2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1218.178, + 282.169, + -1099.479 + ], + "size": [ + 20.848, + 12.066, + 17.882 + ], + "groundY": 276.136, + "roofY": 288.202, + "wallCount": 31, + "roofCount": 21 + }, + { + "id": "sion_0772", + "uuid": "{CC55B9C9-BE55-4D3F-8892-70EFE19251A1}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 0, + 0 + ], + "center": [ + -1037.16, + 292.639, + -1439.153 + ], + "size": [ + 15.703, + 8.796, + 20.392 + ], + "groundY": 288.241, + "roofY": 297.037, + "wallCount": 36, + "roofCount": 8 + }, + { + "id": "sion_0773", + "uuid": "{58B86D25-ADF8-4279-8AC3-D1257C16BAB7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -536.059, + 26.475, + -59.103 + ], + "size": [ + 11.695, + 8.074, + 14.864 + ], + "groundY": 22.438, + "roofY": 30.512, + "wallCount": 38, + "roofCount": 27 + }, + { + "id": "sion_0774", + "uuid": "{E04A8BE5-7BDA-4029-8695-444DD681CAEB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1120.693, + 297.385, + -1475.901 + ], + "size": [ + 21.082, + 15.316, + 20.256 + ], + "groundY": 289.727, + "roofY": 305.043, + "wallCount": 25, + "roofCount": 10 + }, + { + "id": "sion_0775", + "uuid": "{9BADFF12-0DA9-4E5A-9930-BAE6E4EAE270}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -496.166, + 5.531, + 406.881 + ], + "size": [ + 6.824, + 5.516, + 4.468 + ], + "groundY": 2.773, + "roofY": 8.289, + "wallCount": 18, + "roofCount": 2 + }, + { + "id": "sion_0776", + "uuid": "{1E2DCBBB-4C5B-4392-BA2A-7D18F17DAB57}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -1001.039, + 294.828, + -1257.831 + ], + "size": [ + 25.062, + 12.372, + 18.874 + ], + "groundY": 288.642, + "roofY": 301.014, + "wallCount": 53, + "roofCount": 34 + }, + { + "id": "sion_0777", + "uuid": "{A597B819-03C2-4A97-B4ED-C2268D1F77B2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1360.512, + 278.992, + -1035.113 + ], + "size": [ + 40.172, + 17.298, + 25.624 + ], + "groundY": 270.343, + "roofY": 287.641, + "wallCount": 73, + "roofCount": 21 + }, + { + "id": "sion_0778", + "uuid": "{C0236D0C-FA43-4772-92D3-62916FE47BBC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1298.26, + 60.554, + 17.68 + ], + "size": [ + 26.981, + 13.285, + 27.438 + ], + "groundY": 53.911, + "roofY": 67.196, + "wallCount": 31, + "roofCount": 21 + }, + { + "id": "sion_0779", + "uuid": "{E93373BE-6EE9-4413-B327-37B4568289E8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -622.746, + 35.624, + -211.527 + ], + "size": [ + 16.125, + 13.585, + 26.756 + ], + "groundY": 28.832, + "roofY": 42.417, + "wallCount": 34, + "roofCount": 24 + }, + { + "id": "sion_0780", + "uuid": "{376498E7-AFAC-4642-B51A-5B870CF605AB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1028.963, + 23.711, + -45.915 + ], + "size": [ + 34.332, + 19.158, + 28.5 + ], + "groundY": 14.132, + "roofY": 33.29, + "wallCount": 47, + "roofCount": 20 + }, + { + "id": "sion_0781", + "uuid": "{FA9AA1AF-50F4-4AF8-B726-545CF7E887F6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1346.121, + 206.736, + -588.058 + ], + "size": [ + 16.742, + 9.498, + 17.778 + ], + "groundY": 201.987, + "roofY": 211.485, + "wallCount": 34, + "roofCount": 17 + }, + { + "id": "sion_0782", + "uuid": "{AC923DB2-DCCA-4B99-A436-88509701C9A1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1230.58, + 272.563, + -1054.92 + ], + "size": [ + 15.754, + 9.852, + 23.867 + ], + "groundY": 267.637, + "roofY": 277.489, + "wallCount": 44, + "roofCount": 26 + }, + { + "id": "sion_0783", + "uuid": "{DF3C56CA-4DA6-42B9-A36F-6015FA8B8D4F}", + "name": "", + "class": "Sakrales Gebaeude", + "archStyle": "fortress", + "tile": [ + 1, + 3 + ], + "center": [ + -1018.693, + 12.861, + 116.787 + ], + "size": [ + 38.441, + 16.497, + 33.01 + ], + "groundY": 4.613, + "roofY": 21.11, + "wallCount": 90, + "roofCount": 22 + }, + { + "id": "sion_0784", + "uuid": "{400BE460-0306-40B2-BABD-83C9B017CD44}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -851.109, + 5.49, + 319.909 + ], + "size": [ + 42.352, + 16.86, + 26.046 + ], + "groundY": -2.94, + "roofY": 13.92, + "wallCount": 30, + "roofCount": 23 + }, + { + "id": "sion_0785", + "uuid": "{E93FFE19-D080-49E1-B208-5B7A638BC12D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -762.092, + 66.868, + -334.014 + ], + "size": [ + 16.191, + 11.488, + 15.933 + ], + "groundY": 61.124, + "roofY": 72.612, + "wallCount": 32, + "roofCount": 7 + }, + { + "id": "sion_0786", + "uuid": "{9C3F8E97-4A2A-4771-9A13-BDDD3C42CAA5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1199.645, + 284.294, + -1160.42 + ], + "size": [ + 7.008, + 7.091, + 7.048 + ], + "groundY": 280.749, + "roofY": 287.839, + "wallCount": 50, + "roofCount": 12 + }, + { + "id": "sion_0787", + "uuid": "{9D6D0848-F175-4D9D-8079-50BD5BD20B3A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1481.414, + 274.027, + -990.731 + ], + "size": [ + 36.328, + 15.554, + 24.712 + ], + "groundY": 266.25, + "roofY": 281.803, + "wallCount": 79, + "roofCount": 56 + }, + { + "id": "sion_0788", + "uuid": "{102DC039-3C06-4211-B0F2-0053045E28BF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -728.643, + 3.889, + 880.06 + ], + "size": [ + 35.887, + 9.865, + 41.616 + ], + "groundY": -1.043, + "roofY": 8.821, + "wallCount": 28, + "roofCount": 33 + }, + { + "id": "sion_0789", + "uuid": "{3F2FF50E-A2CF-428B-BE22-81D7393786D4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1490.145, + 82.759, + 35.391 + ], + "size": [ + 30.812, + 13.452, + 22.946 + ], + "groundY": 76.033, + "roofY": 89.485, + "wallCount": 39, + "roofCount": 18 + }, + { + "id": "sion_0790", + "uuid": "{B99897F2-9F5A-4CED-9097-95A6CB2288D0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -534.758, + 25.703, + 152.094 + ], + "size": [ + 41.461, + 28.638, + 46.816 + ], + "groundY": 11.384, + "roofY": 40.022, + "wallCount": 35, + "roofCount": 14 + }, + { + "id": "sion_0791", + "uuid": "{AB47CDAF-EFA7-4942-AFA2-C88A81DD1E99}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1117.029, + 239.427, + -852.163 + ], + "size": [ + 29.574, + 5.77, + 22.54 + ], + "groundY": 236.542, + "roofY": 242.312, + "wallCount": 29, + "roofCount": 10 + }, + { + "id": "sion_0792", + "uuid": "{336F5D61-D415-42BB-9D7E-062E18F5F9B4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1344.771, + 209.025, + -614.954 + ], + "size": [ + 18.144, + 8.903, + 15.348 + ], + "groundY": 204.574, + "roofY": 213.477, + "wallCount": 45, + "roofCount": 18 + }, + { + "id": "sion_0793", + "uuid": "{616F7B84-2AAC-4F6F-801A-464A76C6E954}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1212.428, + 285.243, + -1238.995 + ], + "size": [ + 19.981, + 14.624, + 20.348 + ], + "groundY": 277.931, + "roofY": 292.555, + "wallCount": 64, + "roofCount": 47 + }, + { + "id": "sion_0794", + "uuid": "{605AC480-7227-4092-85B0-F2C1D7DCF167}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -572.01, + 44.637, + -393.143 + ], + "size": [ + 17.793, + 13.99, + 20.798 + ], + "groundY": 37.642, + "roofY": 51.632, + "wallCount": 39, + "roofCount": 50 + }, + { + "id": "sion_0795", + "uuid": "{AF423A8D-4149-4997-B201-3794EA58CB95}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1290.273, + 281.905, + -1100.28 + ], + "size": [ + 19.648, + 14.436, + 27.214 + ], + "groundY": 274.687, + "roofY": 289.123, + "wallCount": 44, + "roofCount": 26 + }, + { + "id": "sion_0796", + "uuid": "{23873222-AE66-4ECB-9918-D8835956220F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -904.391, + 113.845, + -539.771 + ], + "size": [ + 17.242, + 13.407, + 22.013 + ], + "groundY": 107.142, + "roofY": 120.549, + "wallCount": 46, + "roofCount": 18 + }, + { + "id": "sion_0797", + "uuid": "{25FE0EEE-BC73-4CF9-9004-7F0B237B42FB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -636.465, + 34.477, + -154.292 + ], + "size": [ + 26.852, + 20.432, + 24.322 + ], + "groundY": 24.261, + "roofY": 44.693, + "wallCount": 46, + "roofCount": 25 + }, + { + "id": "sion_0798", + "uuid": "{26D93C4B-DD70-45ED-8D7E-38ABA6D4FF7E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -714.037, + 25.965, + -47.575 + ], + "size": [ + 15.277, + 15.384, + 14.994 + ], + "groundY": 18.273, + "roofY": 33.657, + "wallCount": 53, + "roofCount": 20 + }, + { + "id": "sion_0799", + "uuid": "{B8399A29-95EA-434F-8C81-B96ED27A3BAF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -793.488, + 2.766, + 969.005 + ], + "size": [ + 33.508, + 8.657, + 30.605 + ], + "groundY": -1.562, + "roofY": 7.094, + "wallCount": 12, + "roofCount": 2 + }, + { + "id": "sion_0800", + "uuid": "{57D806BD-EA4D-4181-B201-E6D8AC43E643}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1336.838, + 0.455, + 853.103 + ], + "size": [ + 27.59, + 6.566, + 23.687 + ], + "groundY": -2.828, + "roofY": 3.738, + "wallCount": 17, + "roofCount": 4 + }, + { + "id": "sion_0801", + "uuid": "{CD567B9F-1405-43E8-80CF-44E7481A5A7F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1310.953, + 47.267, + 121.278 + ], + "size": [ + 22.844, + 20.632, + 27.862 + ], + "groundY": 36.951, + "roofY": 57.583, + "wallCount": 134, + "roofCount": 28 + }, + { + "id": "sion_0802", + "uuid": "{324692FE-AFE4-4BFA-8FDB-2226F6D510FB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -729.758, + 56.222, + -325.693 + ], + "size": [ + 16.055, + 11.278, + 15.729 + ], + "groundY": 50.583, + "roofY": 61.861, + "wallCount": 42, + "roofCount": 16 + }, + { + "id": "sion_0803", + "uuid": "{42B2DAA5-404C-433F-93BB-939C35F01850}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1112.783, + 253.273, + -906.429 + ], + "size": [ + 19.902, + 16.202, + 11.731 + ], + "groundY": 245.172, + "roofY": 261.374, + "wallCount": 116, + "roofCount": 38 + }, + { + "id": "sion_0804", + "uuid": "{2BF74A23-ED07-4AEA-9F5D-B18EBB6C3F46}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -577.404, + 288.534, + -1253.95 + ], + "size": [ + 26.777, + 13.117, + 20.168 + ], + "groundY": 281.976, + "roofY": 295.093, + "wallCount": 30, + "roofCount": 15 + }, + { + "id": "sion_0805", + "uuid": "{2D56A314-5580-4284-8A21-798D96463F8E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -684.326, + 61.907, + -433.045 + ], + "size": [ + 18.371, + 11.051, + 14.969 + ], + "groundY": 56.381, + "roofY": 67.432, + "wallCount": 50, + "roofCount": 27 + }, + { + "id": "sion_0806", + "uuid": "{D147F9D1-334F-42FC-82C3-28508ACC013A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1094.342, + 288.859, + -1248.772 + ], + "size": [ + 15.535, + 10.572, + 14.964 + ], + "groundY": 283.573, + "roofY": 294.145, + "wallCount": 46, + "roofCount": 18 + }, + { + "id": "sion_0807", + "uuid": "{A24A7EBE-4106-4116-825C-6ECAA4779704}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1138.025, + 3.148, + 486.151 + ], + "size": [ + 45.113, + 12.633, + 28.702 + ], + "groundY": -3.168, + "roofY": 9.465, + "wallCount": 43, + "roofCount": 27 + }, + { + "id": "sion_0808", + "uuid": "{AEC7F250-9D01-48D2-95FA-53D651A23319}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -853.512, + 294.757, + -1483.335 + ], + "size": [ + 14.062, + 9.276, + 15.0 + ], + "groundY": 290.119, + "roofY": 299.395, + "wallCount": 39, + "roofCount": 22 + }, + { + "id": "sion_0809", + "uuid": "{2A4CC4AD-2D18-4CEE-8BA7-B1B11C7E2474}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1038.98, + 296.814, + -1345.839 + ], + "size": [ + 12.891, + 10.541, + 10.96 + ], + "groundY": 291.543, + "roofY": 302.084, + "wallCount": 32, + "roofCount": 19 + }, + { + "id": "sion_0810", + "uuid": "{30207DB5-CF0B-4611-BD9D-19C182D355EC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -800.783, + 3.444, + 890.586 + ], + "size": [ + 80.621, + 9.627, + 38.115 + ], + "groundY": -1.369, + "roofY": 8.258, + "wallCount": 12, + "roofCount": 29 + }, + { + "id": "sion_0811", + "uuid": "{ADBCE3A1-9C66-48AC-95D0-88359AA3AAA9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1291.635, + 138.887, + -361.607 + ], + "size": [ + 14.934, + 6.548, + 14.099 + ], + "groundY": 135.613, + "roofY": 142.161, + "wallCount": 24, + "roofCount": 15 + }, + { + "id": "sion_0812", + "uuid": "{B13AB99F-99F7-4BEC-A79B-240D39113F06}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1117.461, + 263.719, + -985.764 + ], + "size": [ + 9.695, + 9.231, + 10.142 + ], + "groundY": 259.104, + "roofY": 268.335, + "wallCount": 47, + "roofCount": 35 + }, + { + "id": "sion_0813", + "uuid": "{5FD6E2D9-55F7-42B2-B4EB-66847D71D254}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1279.15, + 6.817, + 742.119 + ], + "size": [ + 27.707, + 19.712, + 20.861 + ], + "groundY": -3.039, + "roofY": 16.673, + "wallCount": 63, + "roofCount": 10 + }, + { + "id": "sion_0814", + "uuid": "{870CC0F4-19B2-4F47-BE75-3674CBF6BB6B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1523.336, + 266.649, + -1025.001 + ], + "size": [ + 27.391, + 11.312, + 22.814 + ], + "groundY": 260.993, + "roofY": 272.305, + "wallCount": 40, + "roofCount": 34 + }, + { + "id": "sion_0815", + "uuid": "{A12ABD73-24E5-46FD-A385-4FEC87BC8173}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1311.022, + 216.088, + -699.912 + ], + "size": [ + 18.051, + 12.428, + 17.686 + ], + "groundY": 209.874, + "roofY": 222.302, + "wallCount": 56, + "roofCount": 45 + }, + { + "id": "sion_0816", + "uuid": "{E461D773-43AA-45A0-B033-0C177499A13B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1308.127, + 233.698, + -792.067 + ], + "size": [ + 8.48, + 6.023, + 13.802 + ], + "groundY": 230.686, + "roofY": 236.709, + "wallCount": 35, + "roofCount": 4 + }, + { + "id": "sion_0817", + "uuid": "{E523492B-4AF0-4F03-860C-7306DFB3A0F6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -456.832, + 81.564, + -815.6 + ], + "size": [ + 26.117, + 10.505, + 26.513 + ], + "groundY": 76.311, + "roofY": 86.817, + "wallCount": 48, + "roofCount": 30 + }, + { + "id": "sion_0818", + "uuid": "{7F6748B0-995C-474F-AE44-CDEC70A263F8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -768.91, + 97.282, + -534.929 + ], + "size": [ + 36.828, + 11.604, + 29.6 + ], + "groundY": 91.48, + "roofY": 103.084, + "wallCount": 16, + "roofCount": 6 + }, + { + "id": "sion_0819", + "uuid": "{EBFBB1DB-75C8-4056-9584-1F2A3105C4A2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -842.709, + 295.143, + -1501.941 + ], + "size": [ + 19.551, + 11.206, + 18.989 + ], + "groundY": 289.54, + "roofY": 300.746, + "wallCount": 41, + "roofCount": 50 + }, + { + "id": "sion_0820", + "uuid": "{E5C2B5D1-7480-4BEA-A079-A1FDE9484EEE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1130.562, + 291.715, + -1176.627 + ], + "size": [ + 19.391, + 13.802, + 17.292 + ], + "groundY": 284.814, + "roofY": 298.616, + "wallCount": 40, + "roofCount": 14 + }, + { + "id": "sion_0821", + "uuid": "{FE21304D-5CF4-4C6B-AC0C-B462CB06BE5D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -875.127, + 3.244, + 922.189 + ], + "size": [ + 40.629, + 10.106, + 36.325 + ], + "groundY": -1.809, + "roofY": 8.297, + "wallCount": 22, + "roofCount": 2 + }, + { + "id": "sion_0822", + "uuid": "{AECDF540-2664-440B-A13C-E0FDA2D19D43}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1117.846, + 0.441, + 466.387 + ], + "size": [ + 15.285, + 6.958, + 10.762 + ], + "groundY": -3.038, + "roofY": 3.92, + "wallCount": 41, + "roofCount": 11 + }, + { + "id": "sion_0823", + "uuid": "{B442A203-AB31-4B89-8F91-8D55BAFB77BA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -551.852, + 36.813, + -135.297 + ], + "size": [ + 24.844, + 22.743, + 20.672 + ], + "groundY": 25.442, + "roofY": 48.185, + "wallCount": 44, + "roofCount": 33 + }, + { + "id": "sion_0824", + "uuid": "{AB21E546-7AFF-48E0-985C-95657536ABAD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1362.822, + 242.363, + -846.939 + ], + "size": [ + 18.543, + 10.908, + 14.075 + ], + "groundY": 236.909, + "roofY": 247.817, + "wallCount": 51, + "roofCount": 23 + }, + { + "id": "sion_0825", + "uuid": "{14D7EFA1-243B-409F-BE44-4679B53F4D20}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1089.676, + 48.009, + -70.165 + ], + "size": [ + 20.109, + 10.331, + 18.617 + ], + "groundY": 42.844, + "roofY": 53.175, + "wallCount": 54, + "roofCount": 9 + }, + { + "id": "sion_0826", + "uuid": "{1985B385-240D-4DAE-861A-DC1320712C3A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1107.703, + 291.395, + -1180.851 + ], + "size": [ + 26.383, + 11.972, + 20.636 + ], + "groundY": 285.409, + "roofY": 297.381, + "wallCount": 26, + "roofCount": 26 + }, + { + "id": "sion_0827", + "uuid": "{B950AC54-B4BC-4554-9EBD-890E05A80345}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1159.131, + 56.635, + -12.711 + ], + "size": [ + 27.481, + 8.905, + 20.072 + ], + "groundY": 52.182, + "roofY": 61.087, + "wallCount": 38, + "roofCount": 10 + }, + { + "id": "sion_0828", + "uuid": "{927DEC77-83FA-4117-B3CF-5203B6C60EBF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -785.883, + 59.144, + -280.645 + ], + "size": [ + 19.117, + 11.132, + 16.261 + ], + "groundY": 53.578, + "roofY": 64.71, + "wallCount": 29, + "roofCount": 41 + }, + { + "id": "sion_0829", + "uuid": "{CD24B36B-F4AB-4B5A-B3E4-BE5F625BBE72}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1349.207, + 282.203, + -1134.426 + ], + "size": [ + 17.188, + 11.588, + 16.79 + ], + "groundY": 276.409, + "roofY": 287.997, + "wallCount": 21, + "roofCount": 10 + }, + { + "id": "sion_0830", + "uuid": "{A617FD00-279C-4BEC-A980-1ED56B17BE10}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1071.521, + 19.69, + 21.592 + ], + "size": [ + 36.137, + 20.494, + 31.25 + ], + "groundY": 9.443, + "roofY": 29.937, + "wallCount": 62, + "roofCount": 34 + }, + { + "id": "sion_0831", + "uuid": "{CF9419A0-0C52-42F3-BDAF-EF57D22805E7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1075.367, + 290.912, + -1187.332 + ], + "size": [ + 25.664, + 10.375, + 24.477 + ], + "groundY": 285.724, + "roofY": 296.1, + "wallCount": 34, + "roofCount": 39 + }, + { + "id": "sion_0832", + "uuid": "{794F3AB9-9040-45BA-9600-C1335BC9D8D3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -585.031, + 23.843, + 196.286 + ], + "size": [ + 11.656, + 23.596, + 13.279 + ], + "groundY": 12.045, + "roofY": 35.641, + "wallCount": 33, + "roofCount": 15 + }, + { + "id": "sion_0833", + "uuid": "{97B3CB11-8030-4FBE-90FC-B7313A6AAE56}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -472.996, + 75.327, + -724.768 + ], + "size": [ + 14.766, + 11.535, + 14.45 + ], + "groundY": 69.56, + "roofY": 81.095, + "wallCount": 22, + "roofCount": 22 + }, + { + "id": "sion_0834", + "uuid": "{ACB3BC3A-C201-44A0-8520-3E315E49C87D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1354.629, + 279.634, + -1148.975 + ], + "size": [ + 25.805, + 17.486, + 22.429 + ], + "groundY": 270.891, + "roofY": 288.377, + "wallCount": 36, + "roofCount": 17 + }, + { + "id": "sion_0835", + "uuid": "{6C2A04CB-9B47-4E60-8032-D6CDD75500BD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1318.75, + 272.585, + -1230.667 + ], + "size": [ + 20.195, + 9.122, + 14.604 + ], + "groundY": 268.024, + "roofY": 277.146, + "wallCount": 44, + "roofCount": 17 + }, + { + "id": "sion_0836", + "uuid": "{8F7E2522-7981-404E-AB5C-5C897782F362}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1248.855, + 7.051, + 689.538 + ], + "size": [ + 23.82, + 19.864, + 31.521 + ], + "groundY": -2.881, + "roofY": 16.983, + "wallCount": 45, + "roofCount": 8 + }, + { + "id": "sion_0837", + "uuid": "{FDA7A1E1-F5DA-48FF-AB68-7528915BAC70}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1415.727, + 201.106, + -489.657 + ], + "size": [ + 15.648, + 6.468, + 10.603 + ], + "groundY": 197.872, + "roofY": 204.34, + "wallCount": 35, + "roofCount": 13 + }, + { + "id": "sion_0838", + "uuid": "{A168B92B-4B42-40C6-AA87-DA3227955CB2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1230.312, + 9.436, + 193.161 + ], + "size": [ + 30.195, + 18.992, + 39.966 + ], + "groundY": -0.06, + "roofY": 18.932, + "wallCount": 23, + "roofCount": 22 + }, + { + "id": "sion_0839", + "uuid": "{D18DB9D6-A697-4D12-B32D-8726F2115CDD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1276.484, + 121.75, + -312.207 + ], + "size": [ + 25.594, + 10.482, + 17.658 + ], + "groundY": 116.509, + "roofY": 126.991, + "wallCount": 44, + "roofCount": 9 + }, + { + "id": "sion_0840", + "uuid": "{6375F845-7F17-4552-A762-9250C6FDF83D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -565.998, + 42.336, + -260.258 + ], + "size": [ + 100.449, + 27.782, + 56.061 + ], + "groundY": 28.445, + "roofY": 56.227, + "wallCount": 134, + "roofCount": 15 + }, + { + "id": "sion_0841", + "uuid": "{07B4B462-B065-4B02-AA5C-0223464F3572}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -685.789, + 48.126, + -344.785 + ], + "size": [ + 32.414, + 15.167, + 22.068 + ], + "groundY": 40.543, + "roofY": 55.71, + "wallCount": 76, + "roofCount": 26 + }, + { + "id": "sion_0842", + "uuid": "{2EFAEA51-758A-4B91-95BB-4B84E4016F68}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -868.889, + 290.718, + -1278.709 + ], + "size": [ + 15.582, + 11.484, + 22.811 + ], + "groundY": 284.976, + "roofY": 296.46, + "wallCount": 28, + "roofCount": 14 + }, + { + "id": "sion_0843", + "uuid": "{0CF66EEC-5A35-4BD0-AB7C-2871A6B21610}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -799.49, + 25.926, + -71.362 + ], + "size": [ + 32.527, + 20.524, + 28.704 + ], + "groundY": 15.664, + "roofY": 36.188, + "wallCount": 59, + "roofCount": 41 + }, + { + "id": "sion_0844", + "uuid": "{F3959867-79BB-4FF3-BA1B-134888A76F97}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1076.111, + 5.911, + 243.482 + ], + "size": [ + 24.691, + 18.539, + 44.538 + ], + "groundY": -3.359, + "roofY": 15.18, + "wallCount": 13, + "roofCount": 29 + }, + { + "id": "sion_0845", + "uuid": "{CD34A23D-DB73-42B8-B4AC-E59DF70D1651}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -554.678, + 7.566, + 492.201 + ], + "size": [ + 14.824, + 14.809, + 12.662 + ], + "groundY": 0.161, + "roofY": 14.97, + "wallCount": 45, + "roofCount": 59 + }, + { + "id": "sion_0846", + "uuid": "{56E175DF-60BC-486C-BD7E-52C991A8F7F8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1198.33, + 0.797, + 872.766 + ], + "size": [ + 26.809, + 7.042, + 19.698 + ], + "groundY": -2.724, + "roofY": 4.318, + "wallCount": 26, + "roofCount": 4 + }, + { + "id": "sion_0847", + "uuid": "{1CCE7810-DE7F-4223-8021-53232B8A121F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -865.648, + 6.581, + 814.76 + ], + "size": [ + 44.523, + 17.1, + 69.498 + ], + "groundY": -1.969, + "roofY": 15.131, + "wallCount": 34, + "roofCount": 12 + }, + { + "id": "sion_0848", + "uuid": "{8206E84A-A728-4F4C-9717-3FA18C65198C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -443.041, + 11.37, + 770.176 + ], + "size": [ + 43.277, + 24.87, + 19.766 + ], + "groundY": -1.065, + "roofY": 23.805, + "wallCount": 134, + "roofCount": 30 + }, + { + "id": "sion_0849", + "uuid": "{F1E92EDE-2507-401D-8067-59372D2324AE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -622.887, + 294.576, + -1291.918 + ], + "size": [ + 29.602, + 15.937, + 22.84 + ], + "groundY": 286.608, + "roofY": 302.545, + "wallCount": 22, + "roofCount": 11 + }, + { + "id": "sion_0850", + "uuid": "{703B67AD-5654-4E3D-BC3B-AE84C7091ED9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1432.119, + -0.015, + 739.371 + ], + "size": [ + 8.152, + 6.99, + 9.204 + ], + "groundY": -3.51, + "roofY": 3.48, + "wallCount": 23, + "roofCount": 0 + }, + { + "id": "sion_0851", + "uuid": "{FBBF5BE1-956B-4581-83F7-186ECFA9F1D9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -1010.988, + 79.621, + -270.397 + ], + "size": [ + 16.797, + 12.408, + 16.952 + ], + "groundY": 73.417, + "roofY": 85.825, + "wallCount": 31, + "roofCount": 10 + }, + { + "id": "sion_0852", + "uuid": "{88B6AD07-ABFD-45E8-84B4-C6F098572939}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1162.584, + 6.386, + 150.033 + ], + "size": [ + 11.238, + 5.881, + 9.992 + ], + "groundY": 3.445, + "roofY": 9.326, + "wallCount": 26, + "roofCount": 2 + }, + { + "id": "sion_0853", + "uuid": "{EED671C8-0931-47AF-8886-962E8004D208}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1402.281, + 235.898, + -781.551 + ], + "size": [ + 12.578, + 12.084, + 9.874 + ], + "groundY": 229.856, + "roofY": 241.939, + "wallCount": 70, + "roofCount": 4 + }, + { + "id": "sion_0854", + "uuid": "{3EC7B223-2D2F-4935-B871-211BE0B90294}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 0, + 1 + ], + "center": [ + -1216.596, + 199.633, + -607.608 + ], + "size": [ + 17.41, + 9.91, + 17.319 + ], + "groundY": 194.678, + "roofY": 204.588, + "wallCount": 25, + "roofCount": 4 + }, + { + "id": "sion_0855", + "uuid": "{9225C1FE-AEAE-4EF5-B67B-64704BF142E3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -547.336, + 70.06, + -621.135 + ], + "size": [ + 34.695, + 16.481, + 29.065 + ], + "groundY": 61.82, + "roofY": 78.301, + "wallCount": 10, + "roofCount": 19 + }, + { + "id": "sion_0856", + "uuid": "{14F1DE46-0B78-4D20-A8AC-ED5AF01A64ED}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -834.746, + 20.138, + -62.164 + ], + "size": [ + 23.82, + 8.601, + 18.292 + ], + "groundY": 15.838, + "roofY": 24.439, + "wallCount": 40, + "roofCount": 14 + }, + { + "id": "sion_0857", + "uuid": "{CA42E2B0-69A8-43E2-AB04-B923BC15D1E0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -579.041, + 73.506, + -600.639 + ], + "size": [ + 21.129, + 14.206, + 16.254 + ], + "groundY": 66.403, + "roofY": 80.609, + "wallCount": 37, + "roofCount": 20 + }, + { + "id": "sion_0858", + "uuid": "{5E9BEBF5-8CDC-4B84-BD33-BB0591961310}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -782.475, + 4.26, + 809.187 + ], + "size": [ + 99.309, + 10.338, + 79.61 + ], + "groundY": -0.909, + "roofY": 9.429, + "wallCount": 57, + "roofCount": 37 + }, + { + "id": "sion_0859", + "uuid": "{300E5AC1-5A9F-4D73-8988-86AA400A49FB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -928.514, + 2.503, + 292.253 + ], + "size": [ + 13.488, + 10.765, + 11.38 + ], + "groundY": -2.879, + "roofY": 7.885, + "wallCount": 68, + "roofCount": 39 + }, + { + "id": "sion_0860", + "uuid": "{32A4C003-4733-433C-8E37-D3819E1AFD1D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -495.301, + 26.524, + -46.776 + ], + "size": [ + 19.695, + 8.705, + 18.604 + ], + "groundY": 22.172, + "roofY": 30.877, + "wallCount": 25, + "roofCount": 7 + }, + { + "id": "sion_0861", + "uuid": "{6D3FB9F6-C005-434E-8E80-A148C685BD04}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1079.146, + 17.491, + 479.599 + ], + "size": [ + 58.988, + 42.946, + 39.67 + ], + "groundY": -3.982, + "roofY": 38.964, + "wallCount": 178, + "roofCount": 34 + }, + { + "id": "sion_0862", + "uuid": "{39226AC8-8628-49F3-9A20-6EFAF1349029}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1097.889, + 290.269, + -1302.444 + ], + "size": [ + 15.957, + 9.16, + 19.634 + ], + "groundY": 285.689, + "roofY": 294.849, + "wallCount": 66, + "roofCount": 19 + }, + { + "id": "sion_0863", + "uuid": "{D98BAB11-CDA9-41CB-9B5D-AD024A023581}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1504.314, + 229.664, + -793.939 + ], + "size": [ + 16.043, + 11.223, + 13.36 + ], + "groundY": 224.053, + "roofY": 235.276, + "wallCount": 49, + "roofCount": 33 + }, + { + "id": "sion_0864", + "uuid": "{E0CCFC97-E8A5-47DB-B435-0400E5B7DBFC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -619.978, + 31.281, + -50.501 + ], + "size": [ + 55.051, + 23.803, + 31.205 + ], + "groundY": 19.38, + "roofY": 43.183, + "wallCount": 14, + "roofCount": 16 + }, + { + "id": "sion_0865", + "uuid": "{47F23AC3-B695-49A6-A32F-73F2A17A183F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -735.195, + 12.174, + 268.356 + ], + "size": [ + 14.742, + 17.094, + 14.479 + ], + "groundY": 3.627, + "roofY": 20.721, + "wallCount": 47, + "roofCount": 20 + }, + { + "id": "sion_0866", + "uuid": "{99B9408F-EEB8-42E3-87A6-97DCE86EC086}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1301.105, + 9.119, + 213.48 + ], + "size": [ + 55.031, + 16.358, + 59.788 + ], + "groundY": 0.94, + "roofY": 17.298, + "wallCount": 148, + "roofCount": 75 + }, + { + "id": "sion_0867", + "uuid": "{30B35BFA-2505-4DAC-9680-2AC6E77CC352}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -777.428, + 72.007, + -375.53 + ], + "size": [ + 27.051, + 13.26, + 27.292 + ], + "groundY": 65.377, + "roofY": 78.637, + "wallCount": 39, + "roofCount": 13 + }, + { + "id": "sion_0868", + "uuid": "{2E7388CB-9F74-4B23-9C49-B1BA83ABF517}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -726.518, + 25.826, + -77.814 + ], + "size": [ + 13.488, + 13.724, + 13.948 + ], + "groundY": 18.964, + "roofY": 32.688, + "wallCount": 73, + "roofCount": 35 + }, + { + "id": "sion_0869", + "uuid": "{F32F1E1E-95C1-4517-B2FB-B8DC1E07E67B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -507.195, + 27.791, + 91.726 + ], + "size": [ + 26.703, + 22.759, + 23.418 + ], + "groundY": 16.412, + "roofY": 39.171, + "wallCount": 19, + "roofCount": 15 + }, + { + "id": "sion_0870", + "uuid": "{898A0A4C-2CB7-4C8D-A67C-03CCAFFED152}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1120.797, + 260.29, + -926.323 + ], + "size": [ + 16.539, + 12.39, + 14.014 + ], + "groundY": 254.095, + "roofY": 266.485, + "wallCount": 31, + "roofCount": 10 + }, + { + "id": "sion_0871", + "uuid": "{6B4B4A7C-2FB2-42D3-8E65-624C247D0EAE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1247.223, + 283.204, + -1090.348 + ], + "size": [ + 18.18, + 12.724, + 16.134 + ], + "groundY": 276.842, + "roofY": 289.566, + "wallCount": 44, + "roofCount": 26 + }, + { + "id": "sion_0872", + "uuid": "{9E9166E1-E2B6-4017-A19C-0D62A9ECFC2D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1387.213, + 281.496, + -1079.876 + ], + "size": [ + 32.809, + 15.48, + 35.186 + ], + "groundY": 273.756, + "roofY": 289.236, + "wallCount": 107, + "roofCount": 34 + }, + { + "id": "sion_0873", + "uuid": "{20544018-A87A-487D-A02B-2A2DE2557A51}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1248.143, + 119.043, + -328.82 + ], + "size": [ + 18.254, + 9.072, + 16.326 + ], + "groundY": 114.507, + "roofY": 123.579, + "wallCount": 40, + "roofCount": 4 + }, + { + "id": "sion_0874", + "uuid": "{8CCE1210-3CA1-40F3-BF7C-70AF03F9666B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -608.082, + 6.034, + 460.341 + ], + "size": [ + 15.359, + 14.317, + 11.889 + ], + "groundY": -1.124, + "roofY": 13.193, + "wallCount": 57, + "roofCount": 26 + }, + { + "id": "sion_0875", + "uuid": "{B2C2F2D1-37E2-4E77-A5CF-77B805E71739}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1305.82, + 203.35, + -555.846 + ], + "size": [ + 15.453, + 10.003, + 17.274 + ], + "groundY": 198.348, + "roofY": 208.351, + "wallCount": 38, + "roofCount": 16 + }, + { + "id": "sion_0876", + "uuid": "{74F8E8D9-1F37-4D04-A777-50825FE1126D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1225.848, + 3.948, + 301.008 + ], + "size": [ + 38.156, + 16.054, + 49.312 + ], + "groundY": -4.079, + "roofY": 11.975, + "wallCount": 70, + "roofCount": 44 + }, + { + "id": "sion_0877", + "uuid": "{7B3B88DC-4FC9-4F5C-8E9A-69EC706105AF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1290.318, + 212.003, + -707.225 + ], + "size": [ + 13.598, + 8.244, + 12.006 + ], + "groundY": 207.881, + "roofY": 216.125, + "wallCount": 32, + "roofCount": 2 + }, + { + "id": "sion_0878", + "uuid": "{80B4CD5F-1617-4452-BB90-CDBAFCBCBF28}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -424.416, + 54.617, + -530.357 + ], + "size": [ + 24.574, + 19.633, + 15.384 + ], + "groundY": 44.801, + "roofY": 64.434, + "wallCount": 28, + "roofCount": 36 + }, + { + "id": "sion_0879", + "uuid": "{49C506A3-6EE3-4082-816D-86ABAB62A8DD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -800.412, + 23.691, + -45.234 + ], + "size": [ + 15.207, + 15.013, + 14.292 + ], + "groundY": 16.184, + "roofY": 31.197, + "wallCount": 49, + "roofCount": 36 + }, + { + "id": "sion_0880", + "uuid": "{32684C0A-69B3-4F3F-ABB7-C0DD3EB4CE6B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -625.285, + 58.575, + -484.051 + ], + "size": [ + 16.852, + 8.484, + 16.624 + ], + "groundY": 54.333, + "roofY": 62.817, + "wallCount": 65, + "roofCount": 12 + }, + { + "id": "sion_0881", + "uuid": "{15E63777-6CF6-4787-AE89-AA81AE238B63}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1032.312, + 77.176, + -200.797 + ], + "size": [ + 30.414, + 13.806, + 24.742 + ], + "groundY": 70.273, + "roofY": 84.079, + "wallCount": 24, + "roofCount": 30 + }, + { + "id": "sion_0882", + "uuid": "{A06DDD29-E0D1-4CE9-A85A-AC4DA2791C1D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1043.539, + 202.803, + -752.809 + ], + "size": [ + 23.273, + 9.918, + 18.901 + ], + "groundY": 197.844, + "roofY": 207.762, + "wallCount": 38, + "roofCount": 8 + }, + { + "id": "sion_0883", + "uuid": "{935F9C3A-EFF1-42F2-BF44-C12EB0CA5397}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1364.697, + 280.859, + -1102.181 + ], + "size": [ + 23.113, + 11.387, + 25.332 + ], + "groundY": 275.166, + "roofY": 286.553, + "wallCount": 42, + "roofCount": 18 + }, + { + "id": "sion_0884", + "uuid": "{84E7DEAF-3B2E-4567-A1CE-A241F1797DE4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1046.301, + 33.757, + -70.375 + ], + "size": [ + 19.938, + 15.756, + 21.531 + ], + "groundY": 25.879, + "roofY": 41.635, + "wallCount": 41, + "roofCount": 27 + }, + { + "id": "sion_0885", + "uuid": "{74DE19E1-C38E-4382-A2A1-144A4B71239A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -746.287, + 288.936, + -1290.617 + ], + "size": [ + 18.973, + 11.306, + 24.538 + ], + "groundY": 283.283, + "roofY": 294.589, + "wallCount": 44, + "roofCount": 20 + }, + { + "id": "sion_0886", + "uuid": "{0050AD6F-00B4-411C-B52F-9D482E7044A7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -452.111, + 23.477, + 217.459 + ], + "size": [ + 32.52, + 23.216, + 38.135 + ], + "groundY": 11.869, + "roofY": 35.085, + "wallCount": 115, + "roofCount": 88 + }, + { + "id": "sion_0887", + "uuid": "{35E87D73-A232-4C44-966A-242605B098DA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -665.988, + 34.255, + -183.113 + ], + "size": [ + 24.219, + 16.347, + 18.187 + ], + "groundY": 26.082, + "roofY": 42.429, + "wallCount": 70, + "roofCount": 57 + }, + { + "id": "sion_0888", + "uuid": "{5C63808B-1B96-49FB-B2F8-28B8646FE033}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1142.061, + 7.426, + 317.085 + ], + "size": [ + 179.043, + 22.069, + 67.951 + ], + "groundY": -3.609, + "roofY": 18.46, + "wallCount": 190, + "roofCount": 102 + }, + { + "id": "sion_0889", + "uuid": "{895FB46A-7DFA-493D-9ABD-944F597FB28B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -538.852, + 33.714, + -105.276 + ], + "size": [ + 22.75, + 21.693, + 18.21 + ], + "groundY": 22.867, + "roofY": 44.56, + "wallCount": 34, + "roofCount": 14 + }, + { + "id": "sion_0890", + "uuid": "{45B1C27B-6816-4A8F-943C-6CBD46E581E7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1464.143, + 12.199, + 352.451 + ], + "size": [ + 49.223, + 28.87, + 40.278 + ], + "groundY": -2.236, + "roofY": 26.634, + "wallCount": 107, + "roofCount": 28 + }, + { + "id": "sion_0891", + "uuid": "{AB069D80-48CE-41A1-8AC1-724826888E2E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1344.772, + 100.869, + -175.713 + ], + "size": [ + 6.223, + 6.666, + 6.794 + ], + "groundY": 97.536, + "roofY": 104.202, + "wallCount": 36, + "roofCount": 9 + }, + { + "id": "sion_0892", + "uuid": "{E570CE7F-68C5-43B7-815D-82FAC519A15E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -806.992, + 16.492, + 206.057 + ], + "size": [ + 33.594, + 18.73, + 28.878 + ], + "groundY": 7.127, + "roofY": 25.857, + "wallCount": 12, + "roofCount": 34 + }, + { + "id": "sion_0893", + "uuid": "{9D784E1C-3E57-46F3-9B3A-BF7179732581}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1350.797, + 258.18, + -956.176 + ], + "size": [ + 13.805, + 10.3, + 16.43 + ], + "groundY": 253.03, + "roofY": 263.33, + "wallCount": 33, + "roofCount": 16 + }, + { + "id": "sion_0894", + "uuid": "{B2275EA0-79BE-4ED3-ADCC-F4E3416F2B82}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -753.785, + 2.508, + 967.218 + ], + "size": [ + 14.742, + 8.398, + 23.292 + ], + "groundY": -1.691, + "roofY": 6.707, + "wallCount": 22, + "roofCount": 24 + }, + { + "id": "sion_0895", + "uuid": "{158E320F-9EB0-43B6-95C1-0DF416B3D2CE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1126.625, + 219.878, + -794.538 + ], + "size": [ + 19.344, + 9.616, + 15.51 + ], + "groundY": 215.07, + "roofY": 224.686, + "wallCount": 49, + "roofCount": 13 + }, + { + "id": "sion_0896", + "uuid": "{D1BC8E73-F9AA-4812-9397-221E8A83DA5D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1406.803, + 270.541, + -1017.017 + ], + "size": [ + 11.09, + 6.268, + 11.509 + ], + "groundY": 267.407, + "roofY": 273.675, + "wallCount": 67, + "roofCount": 12 + }, + { + "id": "sion_0897", + "uuid": "{1520CFCE-3CE8-4643-84ED-F6267D42E6DE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1275.189, + 203.824, + -595.07 + ], + "size": [ + 16.426, + 10.211, + 17.49 + ], + "groundY": 198.718, + "roofY": 208.929, + "wallCount": 25, + "roofCount": 21 + }, + { + "id": "sion_0898", + "uuid": "{CDC33A95-5A18-4CBC-BA6E-E7B94A42D495}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1243.547, + 295.101, + -1448.866 + ], + "size": [ + 19.125, + 14.893, + 35.697 + ], + "groundY": 287.655, + "roofY": 302.548, + "wallCount": 39, + "roofCount": 18 + }, + { + "id": "sion_0899", + "uuid": "{F7C3DBCD-34FE-4449-9B1C-EB89F1FEE5FA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1045.795, + 11.588, + 187.279 + ], + "size": [ + 26.121, + 17.485, + 16.815 + ], + "groundY": 2.846, + "roofY": 20.331, + "wallCount": 62, + "roofCount": 35 + }, + { + "id": "sion_0900", + "uuid": "{485BD128-A3A8-4DB9-B9A7-6EE279B7540D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -693.225, + 9.336, + 280.015 + ], + "size": [ + 14.004, + 12.056, + 12.594 + ], + "groundY": 3.308, + "roofY": 15.364, + "wallCount": 43, + "roofCount": 15 + }, + { + "id": "sion_0901", + "uuid": "{67CBDD80-5111-4E38-AF44-6626741858D5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1494.211, + 91.011, + 1.938 + ], + "size": [ + 37.57, + 15.234, + 44.595 + ], + "groundY": 83.394, + "roofY": 98.628, + "wallCount": 71, + "roofCount": 20 + }, + { + "id": "sion_0902", + "uuid": "{CD87FA8C-D643-495B-BA08-E614CF2C0404}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1504.072, + 221.449, + -583.656 + ], + "size": [ + 24.316, + 12.177, + 19.528 + ], + "groundY": 215.36, + "roofY": 227.537, + "wallCount": 43, + "roofCount": 47 + }, + { + "id": "sion_0903", + "uuid": "{1CE137A0-D9CA-4213-BD2E-B78867D1D0A4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1246.029, + 278.409, + -1182.32 + ], + "size": [ + 8.402, + 9.427, + 11.794 + ], + "groundY": 273.696, + "roofY": 283.122, + "wallCount": 54, + "roofCount": 18 + }, + { + "id": "sion_0904", + "uuid": "{B71A1896-D075-4B0F-B349-0C0949679CF7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1205.973, + 10.885, + 158.298 + ], + "size": [ + 30.164, + 16.091, + 30.1 + ], + "groundY": 2.84, + "roofY": 18.931, + "wallCount": 34, + "roofCount": 21 + }, + { + "id": "sion_0905", + "uuid": "{E8CB2826-0354-4D19-920B-C419A4447183}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1048.098, + 246.567, + -923.992 + ], + "size": [ + 22.102, + 11.609, + 17.998 + ], + "groundY": 240.763, + "roofY": 252.372, + "wallCount": 52, + "roofCount": 12 + }, + { + "id": "sion_0906", + "uuid": "{93AF190F-75E7-426F-A020-E3EC8A3BBD3C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -738.775, + 86.205, + -492.617 + ], + "size": [ + 24.793, + 11.307, + 20.156 + ], + "groundY": 80.552, + "roofY": 91.859, + "wallCount": 31, + "roofCount": 24 + }, + { + "id": "sion_0907", + "uuid": "{70AD13A0-1B69-4AFB-955D-19B9646BEDCA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -977.596, + 9.107, + 192.076 + ], + "size": [ + 11.574, + 15.74, + 13.976 + ], + "groundY": 1.237, + "roofY": 16.977, + "wallCount": 46, + "roofCount": 40 + }, + { + "id": "sion_0908", + "uuid": "{3F7A3875-0270-46F1-BD3C-C78286DCF135}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1203.647, + 114.067, + -311.267 + ], + "size": [ + 11.949, + 9.08, + 11.276 + ], + "groundY": 109.527, + "roofY": 118.607, + "wallCount": 49, + "roofCount": 2 + }, + { + "id": "sion_0909", + "uuid": "{D7C2439A-07AD-4345-AD53-980359809AF3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -920.398, + 1.298, + 221.813 + ], + "size": [ + 8.445, + 4.816, + 12.343 + ], + "groundY": -1.11, + "roofY": 3.706, + "wallCount": 24, + "roofCount": 11 + }, + { + "id": "sion_0910", + "uuid": "{40D9A021-E591-401D-80BC-986944463665}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -664.248, + 24.016, + 146.045 + ], + "size": [ + 54.785, + 24.379, + 17.766 + ], + "groundY": 11.827, + "roofY": 36.206, + "wallCount": 22, + "roofCount": 23 + }, + { + "id": "sion_0911", + "uuid": "{A8D707D5-7156-4AD2-9C9F-37D16B67D158}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1158.578, + 206.99, + -655.568 + ], + "size": [ + 20.359, + 12.205, + 20.86 + ], + "groundY": 200.887, + "roofY": 213.093, + "wallCount": 23, + "roofCount": 10 + }, + { + "id": "sion_0912", + "uuid": "{69498604-E2A7-4454-BBE5-B26C09892396}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -401.264, + 65.65, + -702.349 + ], + "size": [ + 4.895, + 14.712, + 5.347 + ], + "groundY": 58.294, + "roofY": 73.006, + "wallCount": 36, + "roofCount": 2 + }, + { + "id": "sion_0913", + "uuid": "{C94E35C1-69B0-4D5C-B61F-5895C2AB63C0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1465.145, + 259.893, + -868.586 + ], + "size": [ + 18.984, + 9.502, + 20.391 + ], + "groundY": 255.142, + "roofY": 264.644, + "wallCount": 47, + "roofCount": 17 + }, + { + "id": "sion_0914", + "uuid": "{674A8E98-E1F0-49CC-A14D-0EED26487792}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1521.256, + 5.026, + 483.03 + ], + "size": [ + 24.043, + 17.34, + 17.612 + ], + "groundY": -3.644, + "roofY": 13.696, + "wallCount": 22, + "roofCount": 2 + }, + { + "id": "sion_0915", + "uuid": "{70CBCC6B-04C9-4A9A-BA45-76EA2ADA0B75}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -568.484, + 0.876, + 536.696 + ], + "size": [ + 23.859, + 5.556, + 38.46 + ], + "groundY": -1.902, + "roofY": 3.654, + "wallCount": 39, + "roofCount": 14 + }, + { + "id": "sion_0916", + "uuid": "{D44D89BE-32B7-40D8-BE8E-B46DB6827F5D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -680.094, + 19.561, + 184.444 + ], + "size": [ + 11.328, + 16.24, + 10.39 + ], + "groundY": 11.441, + "roofY": 27.681, + "wallCount": 32, + "roofCount": 31 + }, + { + "id": "sion_0917", + "uuid": "{50FFA981-67C3-4368-8595-CCB59074696F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1233.408, + 58.332, + 23.047 + ], + "size": [ + 21.129, + 12.527, + 20.738 + ], + "groundY": 52.069, + "roofY": 64.595, + "wallCount": 51, + "roofCount": 16 + }, + { + "id": "sion_0918", + "uuid": "{17B8F6D9-6365-440D-9F17-FC845B6E6566}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -950.252, + 20.95, + -59.417 + ], + "size": [ + 24.067, + 13.909, + 23.656 + ], + "groundY": 13.996, + "roofY": 27.904, + "wallCount": 10, + "roofCount": 27 + }, + { + "id": "sion_0919", + "uuid": "{8FB9E5B3-0AE6-4C66-8E43-506831D86466}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -1008.432, + 2.97, + 241.481 + ], + "size": [ + 10.231, + 10.312, + 10.39 + ], + "groundY": -2.186, + "roofY": 8.126, + "wallCount": 42, + "roofCount": 22 + }, + { + "id": "sion_0920", + "uuid": "{4F9FBF49-8B21-4D98-8D00-E5B4E78AEB45}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1095.178, + -0.584, + 466.192 + ], + "size": [ + 27.941, + 6.72, + 11.79 + ], + "groundY": -3.944, + "roofY": 2.776, + "wallCount": 21, + "roofCount": 2 + }, + { + "id": "sion_0921", + "uuid": "{22AC38AD-502C-4195-A3F3-A0E580DB63B0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1187.033, + 9.591, + 182.899 + ], + "size": [ + 34.129, + 18.101, + 27.821 + ], + "groundY": 0.54, + "roofY": 18.641, + "wallCount": 32, + "roofCount": 12 + }, + { + "id": "sion_0922", + "uuid": "{A28C8F56-58B7-43D6-9B0F-F0D9A42BDFB0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1146.895, + 5.31, + 173.093 + ], + "size": [ + 31.43, + 7.308, + 24.732 + ], + "groundY": 1.656, + "roofY": 8.964, + "wallCount": 16, + "roofCount": 2 + }, + { + "id": "sion_0923", + "uuid": "{1809B828-CA3C-4357-AA95-DD33D0054F0B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1107.254, + 10.143, + 170.844 + ], + "size": [ + 23.992, + 16.03, + 21.178 + ], + "groundY": 2.128, + "roofY": 18.158, + "wallCount": 25, + "roofCount": 12 + }, + { + "id": "sion_0924", + "uuid": "{8FED04FE-9552-447E-ACD7-879CBF8B66E4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -836.17, + 105.442, + -563.943 + ], + "size": [ + 25.199, + 11.143, + 23.66 + ], + "groundY": 99.871, + "roofY": 111.014, + "wallCount": 40, + "roofCount": 66 + }, + { + "id": "sion_0925", + "uuid": "{7F55FBF6-3E71-4E45-A6A1-B1CEBCDF6999}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1324.232, + 62.138, + 46.045 + ], + "size": [ + 29.254, + 11.178, + 31.088 + ], + "groundY": 56.549, + "roofY": 67.727, + "wallCount": 28, + "roofCount": 28 + }, + { + "id": "sion_0926", + "uuid": "{E822F145-8833-4C14-9705-1A46A74C5E84}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1414.906, + 67.471, + 118.76 + ], + "size": [ + 50.984, + 15.016, + 34.441 + ], + "groundY": 59.963, + "roofY": 74.979, + "wallCount": 95, + "roofCount": 34 + }, + { + "id": "sion_0927", + "uuid": "{B04727DA-752A-4779-AA60-2FD060E0BB37}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -857.125, + 86.021, + -326.131 + ], + "size": [ + 30.734, + 16.72, + 40.884 + ], + "groundY": 77.661, + "roofY": 94.381, + "wallCount": 77, + "roofCount": 45 + }, + { + "id": "sion_0928", + "uuid": "{4974EB04-487E-43C8-8780-D448AA15D730}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -949.664, + 294.922, + -1472.534 + ], + "size": [ + 28.516, + 10.06, + 17.91 + ], + "groundY": 289.892, + "roofY": 299.952, + "wallCount": 29, + "roofCount": 18 + }, + { + "id": "sion_0929", + "uuid": "{70B2B7ED-6E4C-4CA4-A81D-525BDD482D8C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1499.271, + 206.565, + -534.758 + ], + "size": [ + 15.559, + 10.714, + 16.198 + ], + "groundY": 201.208, + "roofY": 211.922, + "wallCount": 33, + "roofCount": 18 + }, + { + "id": "sion_0930", + "uuid": "{EF0678A1-A2AC-47B0-BBF5-D1ED513C512B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1114.068, + 101.552, + -307.671 + ], + "size": [ + 21.027, + 9.498, + 17.746 + ], + "groundY": 96.803, + "roofY": 106.301, + "wallCount": 42, + "roofCount": 19 + }, + { + "id": "sion_0931", + "uuid": "{98B6DF3A-680C-493A-A79A-686A417EDF36}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1199.205, + 215.597, + -752.346 + ], + "size": [ + 17.035, + 10.637, + 16.672 + ], + "groundY": 210.278, + "roofY": 220.915, + "wallCount": 42, + "roofCount": 24 + }, + { + "id": "sion_0932", + "uuid": "{06776C85-EA01-4607-BC6A-4C907AB3FFFE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -737.803, + 28.784, + -154.255 + ], + "size": [ + 17.238, + 14.087, + 20.7 + ], + "groundY": 21.741, + "roofY": 35.828, + "wallCount": 35, + "roofCount": 25 + }, + { + "id": "sion_0933", + "uuid": "{18000350-A5F8-47C6-89C5-77C4633E73D2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1098.34, + 268.616, + -985.434 + ], + "size": [ + 17.836, + 13.469, + 14.804 + ], + "groundY": 261.882, + "roofY": 275.351, + "wallCount": 46, + "roofCount": 18 + }, + { + "id": "sion_0934", + "uuid": "{093B9CF5-7F31-44E9-85C4-D05C67E73677}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -558.377, + 30.394, + -21.113 + ], + "size": [ + 19.34, + 19.082, + 15.932 + ], + "groundY": 20.853, + "roofY": 39.935, + "wallCount": 95, + "roofCount": 50 + }, + { + "id": "sion_0935", + "uuid": "{0A20BB9E-56B2-40AE-BBB2-8D470967CECE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1050.785, + 10.105, + 223.175 + ], + "size": [ + 25.391, + 20.973, + 35.044 + ], + "groundY": -0.382, + "roofY": 20.591, + "wallCount": 53, + "roofCount": 41 + }, + { + "id": "sion_0936", + "uuid": "{7B668069-96A7-46D5-863C-8751E8F339E4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1336.459, + 229.767, + -756.071 + ], + "size": [ + 22.879, + 12.207, + 24.264 + ], + "groundY": 223.663, + "roofY": 235.87, + "wallCount": 50, + "roofCount": 32 + }, + { + "id": "sion_0937", + "uuid": "{78F03CBC-B045-4DB0-AB68-AEE3B5E85DDE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1137.57, + 7.55, + 129.868 + ], + "size": [ + 12.062, + 6.421, + 10.874 + ], + "groundY": 4.34, + "roofY": 10.761, + "wallCount": 24, + "roofCount": 15 + }, + { + "id": "sion_0938", + "uuid": "{AC28A787-91E5-438C-9C40-7F781B4D8384}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1422.107, + 98.16, + -134.593 + ], + "size": [ + 11.941, + 8.617, + 13.418 + ], + "groundY": 93.852, + "roofY": 102.469, + "wallCount": 33, + "roofCount": 4 + }, + { + "id": "sion_0939", + "uuid": "{6B029969-632A-45B0-92D1-C3A8C9ADB41F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -966.758, + 93.598, + -420.023 + ], + "size": [ + 36.344, + 13.24, + 31.97 + ], + "groundY": 86.978, + "roofY": 100.218, + "wallCount": 28, + "roofCount": 8 + }, + { + "id": "sion_0940", + "uuid": "{DA89D2C6-E819-465F-BC60-5EEB0FEB4B82}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -777.434, + 16.365, + 223.255 + ], + "size": [ + 24.562, + 18.473, + 23.232 + ], + "groundY": 7.129, + "roofY": 25.602, + "wallCount": 88, + "roofCount": 42 + }, + { + "id": "sion_0941", + "uuid": "{A4FC46C7-1B9A-49C1-98E4-83A537660ABE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1156.016, + 290.79, + -1202.953 + ], + "size": [ + 17.891, + 15.744, + 17.895 + ], + "groundY": 282.918, + "roofY": 298.662, + "wallCount": 52, + "roofCount": 12 + }, + { + "id": "sion_0942", + "uuid": "{A73B730C-E75E-4F06-83D5-CD2D1F0E424B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -763.695, + 3.043, + 1014.599 + ], + "size": [ + 44.352, + 8.907, + 34.485 + ], + "groundY": -1.411, + "roofY": 7.496, + "wallCount": 32, + "roofCount": 12 + }, + { + "id": "sion_0943", + "uuid": "{07D6EAC4-3649-4477-AD06-AD146F366B10}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -654.361, + 294.295, + -1278.651 + ], + "size": [ + 23.574, + 15.366, + 20.026 + ], + "groundY": 286.612, + "roofY": 301.978, + "wallCount": 15, + "roofCount": 13 + }, + { + "id": "sion_0944", + "uuid": "{A7FE1D30-D1C4-46B2-BE30-9AF0D642A09E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -935.969, + 3.351, + 327.852 + ], + "size": [ + 35.438, + 13.24, + 17.825 + ], + "groundY": -3.269, + "roofY": 9.971, + "wallCount": 36, + "roofCount": 15 + }, + { + "id": "sion_0945", + "uuid": "{21ABB32D-4B9F-496A-958F-636E6753194B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 1 + ], + "center": [ + -734.969, + 107.372, + -637.738 + ], + "size": [ + 24.133, + 10.869, + 18.984 + ], + "groundY": 101.938, + "roofY": 112.807, + "wallCount": 27, + "roofCount": 10 + }, + { + "id": "sion_0946", + "uuid": "{BEC07634-18DF-4553-81E3-6B31CBD3DB9B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1504.502, + 6.358, + 461.568 + ], + "size": [ + 18.605, + 20.032, + 22.632 + ], + "groundY": -3.658, + "roofY": 16.374, + "wallCount": 43, + "roofCount": 2 + }, + { + "id": "sion_0947", + "uuid": "{8742D2A6-77FF-46F4-9B5D-329E3A3D6C66}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -602.018, + 43.429, + -400.756 + ], + "size": [ + 20.481, + 8.684, + 21.852 + ], + "groundY": 39.087, + "roofY": 47.771, + "wallCount": 13, + "roofCount": 16 + }, + { + "id": "sion_0948", + "uuid": "{37141162-3525-4FF7-AD74-D9FF3B6C5D46}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1099.625, + 291.009, + -1222.93 + ], + "size": [ + 25.656, + 12.094, + 17.384 + ], + "groundY": 284.962, + "roofY": 297.056, + "wallCount": 103, + "roofCount": 54 + }, + { + "id": "sion_0949", + "uuid": "{9AD0015B-984B-4276-A33A-CB1F44BF2F66}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -791.992, + 6.741, + 303.12 + ], + "size": [ + 17.016, + 18.409, + 11.494 + ], + "groundY": -2.463, + "roofY": 15.946, + "wallCount": 31, + "roofCount": 12 + }, + { + "id": "sion_0950", + "uuid": "{773C9F75-678C-45A6-887E-C30002551965}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1362.432, + 52.967, + 149.137 + ], + "size": [ + 18.262, + 10.48, + 19.204 + ], + "groundY": 47.727, + "roofY": 58.207, + "wallCount": 62, + "roofCount": 15 + }, + { + "id": "sion_0951", + "uuid": "{7BFF05B1-228C-457A-A29A-A7B1DC0C800D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -714.834, + 65.04, + -420.499 + ], + "size": [ + 18.793, + 10.757, + 16.357 + ], + "groundY": 59.662, + "roofY": 70.419, + "wallCount": 41, + "roofCount": 6 + }, + { + "id": "sion_0952", + "uuid": "{2E665D61-335A-40FB-96EC-9663D8CB5EAA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1292.82, + 290.758, + -1372.684 + ], + "size": [ + 18.672, + 12.328, + 20.726 + ], + "groundY": 284.594, + "roofY": 296.922, + "wallCount": 37, + "roofCount": 31 + }, + { + "id": "sion_0953", + "uuid": "{9A417AAE-3F4F-4F0B-8829-758B99EC7487}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1228.668, + 287.457, + -1327.121 + ], + "size": [ + 20.414, + 10.042, + 15.5 + ], + "groundY": 282.436, + "roofY": 292.478, + "wallCount": 49, + "roofCount": 28 + }, + { + "id": "sion_0954", + "uuid": "{CC58DC28-C034-477A-9EE5-144702250604}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -533.971, + 46.055, + -356.782 + ], + "size": [ + 23.863, + 20.116, + 21.614 + ], + "groundY": 35.997, + "roofY": 56.113, + "wallCount": 17, + "roofCount": 27 + }, + { + "id": "sion_0955", + "uuid": "{CD74B4DA-6099-418F-BB84-FFF955AA030A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -646.617, + 4.252, + 767.921 + ], + "size": [ + 51.875, + 11.722, + 43.58 + ], + "groundY": -1.609, + "roofY": 10.113, + "wallCount": 35, + "roofCount": 10 + }, + { + "id": "sion_0956", + "uuid": "{FABE19C1-8AA3-4810-B2E3-561501D1C8D5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1152.668, + 290.477, + -1171.727 + ], + "size": [ + 26.266, + 14.567, + 17.812 + ], + "groundY": 283.193, + "roofY": 297.76, + "wallCount": 51, + "roofCount": 24 + }, + { + "id": "sion_0957", + "uuid": "{18903E43-BAE1-4439-8BCB-D38AA40B4C40}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -930.213, + 23.172, + -80.324 + ], + "size": [ + 27.223, + 19.208, + 24.134 + ], + "groundY": 13.568, + "roofY": 32.776, + "wallCount": 23, + "roofCount": 19 + }, + { + "id": "sion_0958", + "uuid": "{FF9A9689-1A0D-4585-8CB4-E4DE0B947F30}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1096.76, + 131.995, + -446.418 + ], + "size": [ + 19.168, + 12.345, + 16.424 + ], + "groundY": 125.823, + "roofY": 138.167, + "wallCount": 60, + "roofCount": 21 + }, + { + "id": "sion_0959", + "uuid": "{682D4C72-F791-4578-A127-4D3ADCDE4200}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -756.018, + 31.294, + -140.339 + ], + "size": [ + 31.441, + 20.359, + 27.42 + ], + "groundY": 21.115, + "roofY": 41.474, + "wallCount": 32, + "roofCount": 38 + }, + { + "id": "sion_0960", + "uuid": "{E593A05B-8F20-422F-80BC-61039841CB29}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -1022.066, + 3.446, + 328.823 + ], + "size": [ + 13.461, + 13.376, + 13.28 + ], + "groundY": -3.242, + "roofY": 10.134, + "wallCount": 52, + "roofCount": 19 + }, + { + "id": "sion_0961", + "uuid": "{CA22D628-B156-4EB4-831F-9C42E1EDA7FF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -992.195, + 4.26, + 239.731 + ], + "size": [ + 20.508, + 13.542, + 15.362 + ], + "groundY": -2.511, + "roofY": 11.031, + "wallCount": 53, + "roofCount": 34 + }, + { + "id": "sion_0962", + "uuid": "{44F3D2BB-B791-44DF-B956-93FCCFD3F7E3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1089.209, + 100.67, + -313.492 + ], + "size": [ + 15.527, + 10.23, + 15.648 + ], + "groundY": 95.555, + "roofY": 105.785, + "wallCount": 44, + "roofCount": 11 + }, + { + "id": "sion_0963", + "uuid": "{4565C09A-7CCA-4402-9CDD-F8AFA6F1D333}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -697.189, + 26.691, + -54.085 + ], + "size": [ + 19.387, + 19.007, + 18.764 + ], + "groundY": 17.188, + "roofY": 36.195, + "wallCount": 51, + "roofCount": 13 + }, + { + "id": "sion_0964", + "uuid": "{DCA53A43-BA19-44B0-97E4-B9B76AEF0D39}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1262.441, + 282.998, + -1115.202 + ], + "size": [ + 11.742, + 11.114, + 9.176 + ], + "groundY": 277.441, + "roofY": 288.555, + "wallCount": 45, + "roofCount": 24 + }, + { + "id": "sion_0965", + "uuid": "{CF9B4A6B-DC9B-4B0C-88BC-9B10D0336A74}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -603.324, + 3.811, + 724.965 + ], + "size": [ + 43.695, + 10.299, + 144.777 + ], + "groundY": -1.338, + "roofY": 8.96, + "wallCount": 238, + "roofCount": 107 + }, + { + "id": "sion_0966", + "uuid": "{B0C19748-9DE3-4A13-97D2-C6452D1474FE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1445.244, + 286.108, + -1318.433 + ], + "size": [ + 20.801, + 20.108, + 27.698 + ], + "groundY": 276.054, + "roofY": 296.162, + "wallCount": 58, + "roofCount": 25 + }, + { + "id": "sion_0967", + "uuid": "{CA14FC9A-5758-4947-92C7-69D6382D06B1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -579.65, + 11.584, + 430.913 + ], + "size": [ + 21.598, + 24.09, + 33.792 + ], + "groundY": -0.461, + "roofY": 23.629, + "wallCount": 21, + "roofCount": 20 + }, + { + "id": "sion_0968", + "uuid": "{8385BF24-7A98-4531-B29C-3EEFAB58B1F0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -477.766, + 11.485, + 726.906 + ], + "size": [ + 22.289, + 25.1, + 41.02 + ], + "groundY": -1.065, + "roofY": 24.035, + "wallCount": 134, + "roofCount": 30 + }, + { + "id": "sion_0969", + "uuid": "{747F8284-C62F-4F28-AD46-82EDBBC4231C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1025.959, + 3.092, + 273.943 + ], + "size": [ + 14.106, + 12.216, + 11.802 + ], + "groundY": -3.016, + "roofY": 9.2, + "wallCount": 36, + "roofCount": 31 + }, + { + "id": "sion_0970", + "uuid": "{35AEA41A-AD5A-4F5B-8D6E-F55205E487E4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -622.5, + 39.63, + -274.288 + ], + "size": [ + 19.727, + 16.356, + 19.332 + ], + "groundY": 31.452, + "roofY": 47.808, + "wallCount": 47, + "roofCount": 10 + }, + { + "id": "sion_0971", + "uuid": "{ABC88FF5-0B15-4B9E-B28F-67DF7C395036}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1409.533, + 273.559, + -1023.497 + ], + "size": [ + 14.285, + 11.229, + 13.603 + ], + "groundY": 267.944, + "roofY": 279.173, + "wallCount": 50, + "roofCount": 21 + }, + { + "id": "sion_0972", + "uuid": "{B9D910DA-DEF7-4F41-8590-945B04DBA83B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -754.918, + 284.797, + -1323.757 + ], + "size": [ + 26.5, + 8.693, + 21.021 + ], + "groundY": 280.451, + "roofY": 289.144, + "wallCount": 29, + "roofCount": 18 + }, + { + "id": "sion_0973", + "uuid": "{676BCF9A-6203-415D-8FE4-74A3C13CD065}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1168.539, + 17.833, + 87.424 + ], + "size": [ + 24.945, + 16.727, + 22.654 + ], + "groundY": 9.47, + "roofY": 26.197, + "wallCount": 30, + "roofCount": 16 + }, + { + "id": "sion_0974", + "uuid": "{CBF9ABF5-307C-45AF-98FE-D16491DCDAFC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -993.574, + 296.485, + -1458.409 + ], + "size": [ + 26.859, + 9.728, + 20.893 + ], + "groundY": 291.621, + "roofY": 301.349, + "wallCount": 27, + "roofCount": 18 + }, + { + "id": "sion_0975", + "uuid": "{674B36C3-A92B-45D0-86D9-7CE2651DDD8F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1526.779, + 275.196, + -1234.607 + ], + "size": [ + 32.684, + 8.827, + 30.304 + ], + "groundY": 270.783, + "roofY": 279.609, + "wallCount": 17, + "roofCount": 27 + }, + { + "id": "sion_0976", + "uuid": "{CCE7809F-88B3-4896-B017-6B6EF82C79E9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -731.836, + 3.688, + 998.278 + ], + "size": [ + 16.719, + 10.271, + 20.742 + ], + "groundY": -1.448, + "roofY": 8.823, + "wallCount": 28, + "roofCount": 12 + }, + { + "id": "sion_0977", + "uuid": "{299877D6-6D68-45D0-BB25-AC5D83734644}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1400.738, + 59.593, + 155.233 + ], + "size": [ + 28.008, + 17.704, + 18.644 + ], + "groundY": 50.741, + "roofY": 68.445, + "wallCount": 95, + "roofCount": 16 + }, + { + "id": "sion_0978", + "uuid": "{1BD37A60-8AB7-4CD6-BC2D-83E1905196F2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1120.633, + 287.822, + -1285.656 + ], + "size": [ + 27.039, + 6.701, + 18.42 + ], + "groundY": 284.472, + "roofY": 291.172, + "wallCount": 20, + "roofCount": 14 + }, + { + "id": "sion_0979", + "uuid": "{2CA4E056-04B3-4440-AD1F-A33870BDA6CA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 4 + ], + "center": [ + -892.072, + 4.225, + 733.748 + ], + "size": [ + 62.754, + 13.026, + 45.588 + ], + "groundY": -2.288, + "roofY": 10.738, + "wallCount": 35, + "roofCount": 69 + }, + { + "id": "sion_0980", + "uuid": "{2360047D-C3BC-4B83-BF37-F3DC4BC27A0E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -773.875, + 25.274, + -53.17 + ], + "size": [ + 21.945, + 17.057, + 22.086 + ], + "groundY": 16.746, + "roofY": 33.803, + "wallCount": 89, + "roofCount": 54 + }, + { + "id": "sion_0981", + "uuid": "{E2E0FD88-4A8F-43CD-BD97-1642EB17C0FF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -754.828, + 43.779, + -243.28 + ], + "size": [ + 16.633, + 14.469, + 17.138 + ], + "groundY": 36.544, + "roofY": 51.013, + "wallCount": 36, + "roofCount": 9 + }, + { + "id": "sion_0982", + "uuid": "{13ED8D2F-631E-4E01-8B77-82D518A691B7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -823.541, + 82.844, + -446.049 + ], + "size": [ + 30.582, + 16.102, + 29.342 + ], + "groundY": 74.793, + "roofY": 90.895, + "wallCount": 32, + "roofCount": 20 + }, + { + "id": "sion_0983", + "uuid": "{72A97893-1463-48FD-9AEA-35A348AA4260}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1111.268, + 107.483, + -363.563 + ], + "size": [ + 27.754, + 12.433, + 31.5 + ], + "groundY": 101.267, + "roofY": 113.7, + "wallCount": 60, + "roofCount": 35 + }, + { + "id": "sion_0984", + "uuid": "{94337E15-5D22-4BBF-A425-D6B4AAB37661}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -465.771, + 32.363, + -41.749 + ], + "size": [ + 42.137, + 28.335, + 44.121 + ], + "groundY": 18.195, + "roofY": 46.53, + "wallCount": 90, + "roofCount": 29 + }, + { + "id": "sion_0985", + "uuid": "{649339E9-4473-46BA-8716-295C05B5B245}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -806.973, + 20.636, + 122.265 + ], + "size": [ + 34.562, + 20.709, + 19.124 + ], + "groundY": 10.282, + "roofY": 30.991, + "wallCount": 34, + "roofCount": 20 + }, + { + "id": "sion_0986", + "uuid": "{C3A8851A-2538-4C08-AB7B-617234F547D2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1293.584, + 272.565, + -1172.962 + ], + "size": [ + 12.894, + 6.298, + 12.057 + ], + "groundY": 269.416, + "roofY": 275.714, + "wallCount": 34, + "roofCount": 13 + }, + { + "id": "sion_0987", + "uuid": "{76B38E7B-310C-4720-B102-F3D268E332E9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1387.75, + 68.826, + 73.944 + ], + "size": [ + 26.633, + 13.334, + 24.416 + ], + "groundY": 62.159, + "roofY": 75.493, + "wallCount": 16, + "roofCount": 13 + }, + { + "id": "sion_0988", + "uuid": "{2015F0E8-BE25-4497-BAF0-F1593CAD09A4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -922.074, + 17.19, + 112.698 + ], + "size": [ + 30.195, + 20.524, + 26.574 + ], + "groundY": 6.928, + "roofY": 27.452, + "wallCount": 123, + "roofCount": 57 + }, + { + "id": "sion_0989", + "uuid": "{67ECC163-FEE3-424D-9246-84916DA799DF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -505.232, + 8.401, + 471.551 + ], + "size": [ + 17.144, + 15.076, + 16.576 + ], + "groundY": 0.863, + "roofY": 15.939, + "wallCount": 24, + "roofCount": 68 + }, + { + "id": "sion_0990", + "uuid": "{4BB9B014-0D93-4E74-A27A-06B5EC22B4C6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1463.412, + 209.865, + -577.173 + ], + "size": [ + 16.48, + 10.153, + 14.99 + ], + "groundY": 204.789, + "roofY": 214.942, + "wallCount": 40, + "roofCount": 4 + }, + { + "id": "sion_0991", + "uuid": "{D40A9D52-F8C4-417E-8062-3AD258FEFC43}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1325.299, + 7.129, + 466.298 + ], + "size": [ + 24.613, + 22.07, + 35.33 + ], + "groundY": -3.906, + "roofY": 18.164, + "wallCount": 45, + "roofCount": 20 + }, + { + "id": "sion_0992", + "uuid": "{72848876-F2D7-4257-A24D-3C757921F3F4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1509.26, + 267.078, + -976.533 + ], + "size": [ + 15.621, + 11.062, + 15.05 + ], + "groundY": 261.547, + "roofY": 272.609, + "wallCount": 45, + "roofCount": 24 + }, + { + "id": "sion_0993", + "uuid": "{7ED7EB96-109E-42CC-888C-2025AE931389}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1313.086, + 284.451, + -1341.1 + ], + "size": [ + 11.859, + 5.742, + 17.188 + ], + "groundY": 281.58, + "roofY": 287.322, + "wallCount": 37, + "roofCount": 15 + }, + { + "id": "sion_0994", + "uuid": "{B30BF060-3B98-4597-B6D2-6AE1449041F4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1090.562, + 4.494, + 637.529 + ], + "size": [ + 53.281, + 14.857, + 44.666 + ], + "groundY": -2.934, + "roofY": 11.923, + "wallCount": 14, + "roofCount": 11 + }, + { + "id": "sion_0995", + "uuid": "{D9A6FDA2-4715-4D17-842A-CF58F368CF38}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -849.367, + 31.691, + -172.95 + ], + "size": [ + 21.828, + 13.348, + 16.814 + ], + "groundY": 25.017, + "roofY": 38.365, + "wallCount": 53, + "roofCount": 18 + }, + { + "id": "sion_0996", + "uuid": "{023DBC8E-8B12-4BC7-97B7-EF08839914F0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1484.924, + 233.2, + -808.197 + ], + "size": [ + 16.918, + 8.264, + 15.992 + ], + "groundY": 229.068, + "roofY": 237.332, + "wallCount": 31, + "roofCount": 2 + }, + { + "id": "sion_0997", + "uuid": "{A84F6931-9081-4F02-9E85-EF964911E7C4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1232.982, + 295.339, + -1399.598 + ], + "size": [ + 17.254, + 14.126, + 15.222 + ], + "groundY": 288.276, + "roofY": 302.402, + "wallCount": 41, + "roofCount": 30 + }, + { + "id": "sion_0998", + "uuid": "{A36891CB-0E47-4738-BF49-090D89D8FBC3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1327.879, + 259.074, + -981.157 + ], + "size": [ + 17.25, + 10.209, + 21.05 + ], + "groundY": 253.969, + "roofY": 264.178, + "wallCount": 42, + "roofCount": 10 + }, + { + "id": "sion_0999", + "uuid": "{BC121CA2-A2AC-4D01-ABE3-FF7687D9498D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1357.51, + 279.205, + -1120.733 + ], + "size": [ + 12.324, + 5.214, + 11.754 + ], + "groundY": 276.598, + "roofY": 281.812, + "wallCount": 16, + "roofCount": 2 + }, + { + "id": "sion_1000", + "uuid": "{C94EA914-6545-41C7-9520-ADFC6BCE28E3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1305.355, + 289.58, + -1364.07 + ], + "size": [ + 9.992, + 11.698, + 17.522 + ], + "groundY": 283.731, + "roofY": 295.429, + "wallCount": 44, + "roofCount": 24 + }, + { + "id": "sion_1001", + "uuid": "{6B651F06-13EC-4F15-9B56-18EADB3619FD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -713.4, + 2.891, + 577.17 + ], + "size": [ + 146.652, + 8.875, + 74.637 + ], + "groundY": -1.546, + "roofY": 7.329, + "wallCount": 105, + "roofCount": 50 + }, + { + "id": "sion_1002", + "uuid": "{CEA0BA79-896A-41AB-8030-55D258DB09D8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -537.686, + 41.367, + -201.911 + ], + "size": [ + 44.02, + 26.928, + 28.714 + ], + "groundY": 27.903, + "roofY": 54.831, + "wallCount": 72, + "roofCount": 162 + }, + { + "id": "sion_1003", + "uuid": "{52093900-F14B-4D19-A2D3-6D6F030CD25F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1434.404, + 119.28, + -186.96 + ], + "size": [ + 7.965, + 7.776, + 5.684 + ], + "groundY": 115.392, + "roofY": 123.168, + "wallCount": 37, + "roofCount": 17 + }, + { + "id": "sion_1004", + "uuid": "{3E048AAC-B23E-4F49-9762-D9B11CA3BCF2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -933.889, + 298.516, + -1528.18 + ], + "size": [ + 23.996, + 9.209, + 24.306 + ], + "groundY": 293.911, + "roofY": 303.12, + "wallCount": 43, + "roofCount": 49 + }, + { + "id": "sion_1005", + "uuid": "{EB6D0244-05F5-4F25-81E8-785B0575A6DA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1410.27, + 283.984, + -1077.879 + ], + "size": [ + 20.242, + 11.568, + 26.586 + ], + "groundY": 278.2, + "roofY": 289.768, + "wallCount": 51, + "roofCount": 27 + }, + { + "id": "sion_1006", + "uuid": "{EFA6894B-9BE5-4719-B084-00FC35BE2BBC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -968.891, + 1.019, + 450.324 + ], + "size": [ + 29.289, + 6.232, + 16.924 + ], + "groundY": -2.097, + "roofY": 4.135, + "wallCount": 16, + "roofCount": 2 + }, + { + "id": "sion_1007", + "uuid": "{D3D5F0A3-58E9-4B95-9B41-5B85C1E3BD6D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -608.416, + 53.259, + -456.743 + ], + "size": [ + 12.074, + 11.961, + 12.83 + ], + "groundY": 47.279, + "roofY": 59.24, + "wallCount": 37, + "roofCount": 18 + }, + { + "id": "sion_1008", + "uuid": "{4C1389AB-18F1-458C-9976-278537EDAE6A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1526.465, + 267.236, + -1082.195 + ], + "size": [ + 22.109, + 9.62, + 20.166 + ], + "groundY": 262.426, + "roofY": 272.046, + "wallCount": 28, + "roofCount": 18 + }, + { + "id": "sion_1009", + "uuid": "{C39163B5-09F9-44FB-ACC3-CCE3D219E05F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1323.719, + 202.382, + -571.205 + ], + "size": [ + 9.68, + 6.903, + 11.939 + ], + "groundY": 198.931, + "roofY": 205.834, + "wallCount": 26, + "roofCount": 19 + }, + { + "id": "sion_1010", + "uuid": "{847130A0-EC41-4FE8-9989-683AB16567D9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1024.955, + 272.467, + -1025.995 + ], + "size": [ + 29.356, + 19.238, + 31.753 + ], + "groundY": 262.848, + "roofY": 282.086, + "wallCount": 32, + "roofCount": 10 + }, + { + "id": "sion_1011", + "uuid": "{A9FC3F33-B256-4AB6-985B-89839DCC39D5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1410.289, + 73.902, + -5.58 + ], + "size": [ + 42.727, + 16.574, + 34.189 + ], + "groundY": 65.615, + "roofY": 82.188, + "wallCount": 61, + "roofCount": 18 + }, + { + "id": "sion_1012", + "uuid": "{9447D016-D81F-4BEF-B5CF-8CBA7B5E18D8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1075.24, + 204.624, + -733.495 + ], + "size": [ + 25.004, + 9.784, + 19.622 + ], + "groundY": 199.732, + "roofY": 209.516, + "wallCount": 25, + "roofCount": 15 + }, + { + "id": "sion_1013", + "uuid": "{F8128FC4-CD39-44E6-9DEA-ACDB683C2F9B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1340.896, + 49.103, + 143.501 + ], + "size": [ + 15.262, + 13.228, + 13.85 + ], + "groundY": 42.489, + "roofY": 55.717, + "wallCount": 73, + "roofCount": 20 + }, + { + "id": "sion_1014", + "uuid": "{93D1D5A4-FD99-493E-A4C5-8AF0654B7488}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1264.713, + 294.519, + -1433.714 + ], + "size": [ + 19.27, + 13.633, + 29.506 + ], + "groundY": 287.702, + "roofY": 301.335, + "wallCount": 30, + "roofCount": 31 + }, + { + "id": "sion_1015", + "uuid": "{19F3EB6E-93E2-4957-9E67-5B8DB8DD2419}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1488.102, + 264.299, + -945.27 + ], + "size": [ + 11.945, + 16.044, + 23.995 + ], + "groundY": 256.277, + "roofY": 272.321, + "wallCount": 61, + "roofCount": 17 + }, + { + "id": "sion_1016", + "uuid": "{450E5E4B-BE6F-4862-AB7B-73575B09D18A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1322.203, + 71.175, + -43.554 + ], + "size": [ + 20.742, + 5.438, + 15.402 + ], + "groundY": 68.456, + "roofY": 73.894, + "wallCount": 23, + "roofCount": 2 + }, + { + "id": "sion_1017", + "uuid": "{573599BA-C4B2-4B99-B95A-0D9CEE1EDA26}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1470.119, + 225.047, + -617.601 + ], + "size": [ + 19.902, + 13.03, + 19.078 + ], + "groundY": 218.532, + "roofY": 231.562, + "wallCount": 81, + "roofCount": 18 + }, + { + "id": "sion_1018", + "uuid": "{C0766392-075E-4B10-8933-9FCF838C0FEB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 4 + ], + "center": [ + -1066.133, + 1.374, + 1018.833 + ], + "size": [ + 16.945, + 7.286, + 16.143 + ], + "groundY": -2.269, + "roofY": 5.017, + "wallCount": 37, + "roofCount": 6 + }, + { + "id": "sion_1019", + "uuid": "{EE409AB3-9C56-41AC-A476-295F1BF5BC9E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1146.551, + 7.034, + 240.312 + ], + "size": [ + 33.164, + 16.224, + 25.73 + ], + "groundY": -1.078, + "roofY": 15.146, + "wallCount": 47, + "roofCount": 19 + }, + { + "id": "sion_1020", + "uuid": "{F25A0FDB-973F-44A7-B7B2-1DA6704BEC8F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -1021.426, + 11.622, + 180.662 + ], + "size": [ + 20.008, + 17.501, + 16.294 + ], + "groundY": 2.872, + "roofY": 20.373, + "wallCount": 32, + "roofCount": 22 + }, + { + "id": "sion_1021", + "uuid": "{028E66C8-FA61-4B72-9227-C4B6DD91B5AE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -636.496, + 5.097, + 424.573 + ], + "size": [ + 12.195, + 13.689, + 18.366 + ], + "groundY": -1.747, + "roofY": 11.942, + "wallCount": 26, + "roofCount": 17 + }, + { + "id": "sion_1022", + "uuid": "{9CAF78C1-447B-4C68-B2B9-04C413401020}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 4 + ], + "center": [ + -635.94, + 9.154, + 811.417 + ], + "size": [ + 64.059, + 20.194, + 42.789 + ], + "groundY": -0.943, + "roofY": 19.251, + "wallCount": 34, + "roofCount": 8 + }, + { + "id": "sion_1023", + "uuid": "{47CE7411-B29A-4525-B986-512B16BBB71E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1354.588, + 222.494, + -718.199 + ], + "size": [ + 20.879, + 9.75, + 19.82 + ], + "groundY": 217.619, + "roofY": 227.369, + "wallCount": 37, + "roofCount": 32 + }, + { + "id": "sion_1024", + "uuid": "{1C7841C2-90C3-4D0C-AB5A-9E0C24D834E2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1043.559, + 96.239, + -349.819 + ], + "size": [ + 29.844, + 16.936, + 28.666 + ], + "groundY": 87.771, + "roofY": 104.707, + "wallCount": 26, + "roofCount": 28 + }, + { + "id": "sion_1025", + "uuid": "{543D682D-2252-446D-A63D-197D5604DFFA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1528.188, + 273.001, + -1175.471 + ], + "size": [ + 35.734, + 5.029, + 21.664 + ], + "groundY": 270.487, + "roofY": 275.515, + "wallCount": 14, + "roofCount": 12 + }, + { + "id": "sion_1026", + "uuid": "{4855B8F0-F8DC-4C07-86E5-70758A967756}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -986.207, + 93.434, + -350.861 + ], + "size": [ + 29.344, + 16.752, + 28.614 + ], + "groundY": 85.058, + "roofY": 101.81, + "wallCount": 25, + "roofCount": 13 + }, + { + "id": "sion_1027", + "uuid": "{4A669F13-4E27-48E1-A106-75FD4F13CBEB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -890.127, + 17.706, + 90.613 + ], + "size": [ + 32.84, + 18.951, + 28.396 + ], + "groundY": 8.231, + "roofY": 27.182, + "wallCount": 48, + "roofCount": 32 + }, + { + "id": "sion_1028", + "uuid": "{05DCFCCF-2F81-4DED-A13A-9B1979D78159}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -558.451, + 46.109, + -418.881 + ], + "size": [ + 22.715, + 15.804, + 18.334 + ], + "groundY": 38.207, + "roofY": 54.011, + "wallCount": 53, + "roofCount": 64 + }, + { + "id": "sion_1029", + "uuid": "{4A9841CB-AEBD-40D9-882C-1DB98437F306}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -866.877, + 24.389, + -51.895 + ], + "size": [ + 32.012, + 19.468, + 39.345 + ], + "groundY": 14.655, + "roofY": 34.123, + "wallCount": 21, + "roofCount": 17 + }, + { + "id": "sion_1030", + "uuid": "{703A03F7-1CC6-496E-8C89-7522D0AB1A99}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1198.24, + 289.597, + -1342.569 + ], + "size": [ + 18.09, + 11.73, + 13.738 + ], + "groundY": 283.732, + "roofY": 295.462, + "wallCount": 50, + "roofCount": 21 + }, + { + "id": "sion_1031", + "uuid": "{8FA29081-D637-4797-A596-72FF937724F5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1400.373, + 202.384, + -495.693 + ], + "size": [ + 16.426, + 8.726, + 13.89 + ], + "groundY": 198.021, + "roofY": 206.747, + "wallCount": 31, + "roofCount": 16 + }, + { + "id": "sion_1032", + "uuid": "{336037E9-DB4D-4EDA-BACB-CE7C280644B0}", + "name": "Eglise de la Sainte Famille", + "class": "Sakrales Gebaeude", + "archStyle": "fortress", + "tile": [ + 2, + 4 + ], + "center": [ + -405.951, + 4.534, + 856.064 + ], + "size": [ + 20.41, + 10.732, + 39.356 + ], + "groundY": -0.832, + "roofY": 9.9, + "wallCount": 86, + "roofCount": 71 + }, + { + "id": "sion_1033", + "uuid": "{9856E88D-4CDB-4268-9D2D-64C94F300727}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -881.307, + 289.767, + -1309.062 + ], + "size": [ + 12.777, + 13.021, + 12.647 + ], + "groundY": 283.256, + "roofY": 296.277, + "wallCount": 55, + "roofCount": 17 + }, + { + "id": "sion_1034", + "uuid": "{D3E7464B-9D37-4254-B167-51A20C85D0AB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -537.605, + 5.743, + 484.375 + ], + "size": [ + 18.297, + 11.073, + 16.498 + ], + "groundY": 0.207, + "roofY": 11.28, + "wallCount": 46, + "roofCount": 24 + }, + { + "id": "sion_1035", + "uuid": "{2C104AC0-818C-4A6D-8CBA-21073286CFE5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -531.908, + 31.06, + -37.12 + ], + "size": [ + 22.262, + 18.322, + 20.786 + ], + "groundY": 21.899, + "roofY": 40.221, + "wallCount": 32, + "roofCount": 26 + }, + { + "id": "sion_1036", + "uuid": "{33E86550-62B1-4D4A-A6BA-4C447EF4EC62}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 3 + ], + "center": [ + -1077.439, + 14.484, + 118.122 + ], + "size": [ + 27.183, + 19.182, + 29.38 + ], + "groundY": 4.893, + "roofY": 24.075, + "wallCount": 45, + "roofCount": 16 + }, + { + "id": "sion_1037", + "uuid": "{B489FFA8-F1B4-46E9-A4DA-EC34C035EE82}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -684.953, + 294.479, + -1265.854 + ], + "size": [ + 29.305, + 15.754, + 22.479 + ], + "groundY": 286.602, + "roofY": 302.356, + "wallCount": 10, + "roofCount": 11 + }, + { + "id": "sion_1038", + "uuid": "{A5E5FC92-42EF-4FB2-9FDB-7F9999663F3F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1428.5, + 47.233, + 233.836 + ], + "size": [ + 20.273, + 9.332, + 17.672 + ], + "groundY": 42.567, + "roofY": 51.899, + "wallCount": 48, + "roofCount": 14 + }, + { + "id": "sion_1039", + "uuid": "{E6AB50A0-3B34-4BAA-8B32-BA62FBBF4FD8}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1511.766, + 9.508, + 747.505 + ], + "size": [ + 52.758, + 25.416, + 38.146 + ], + "groundY": -3.2, + "roofY": 22.216, + "wallCount": 95, + "roofCount": 15 + }, + { + "id": "sion_1040", + "uuid": "{F43D0412-84DC-4520-BBF7-2AC065DE6CEE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 2 + ], + "center": [ + -1160.246, + 103.071, + -273.49 + ], + "size": [ + 19.078, + 11.154, + 24.676 + ], + "groundY": 97.494, + "roofY": 108.648, + "wallCount": 42, + "roofCount": 4 + }, + { + "id": "sion_1041", + "uuid": "{DA431EFB-6743-4314-BF12-6415DC9D0817}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -613.574, + 33.859, + -185.48 + ], + "size": [ + 20.773, + 15.783, + 16.405 + ], + "groundY": 25.968, + "roofY": 41.751, + "wallCount": 38, + "roofCount": 15 + }, + { + "id": "sion_1042", + "uuid": "{9EF6DB31-BC50-4701-A9DD-1A862C2A7346}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1510.586, + 275.375, + -1142.778 + ], + "size": [ + 30.078, + 19.246, + 45.844 + ], + "groundY": 265.752, + "roofY": 284.998, + "wallCount": 44, + "roofCount": 18 + }, + { + "id": "sion_1043", + "uuid": "{F06FB788-AB95-4A7D-BD0B-A918EFBCB80F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 2 + ], + "center": [ + -949.352, + 40.773, + -133.591 + ], + "size": [ + 17.188, + 8.874, + 17.614 + ], + "groundY": 36.336, + "roofY": 45.21, + "wallCount": 28, + "roofCount": 2 + }, + { + "id": "sion_1044", + "uuid": "{A452E4C0-53F3-4B4E-AE5B-6BA15B812828}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 0 + ], + "center": [ + -1201.574, + 286.581, + -1145.672 + ], + "size": [ + 25.555, + 15.092, + 22.107 + ], + "groundY": 279.035, + "roofY": 294.127, + "wallCount": 79, + "roofCount": 24 + }, + { + "id": "sion_1045", + "uuid": "{CF2764B4-084D-4BAC-8D35-47CBBA43C717}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 0 + ], + "center": [ + -829.494, + 287.63, + -1280.66 + ], + "size": [ + 12.629, + 7.648, + 11.484 + ], + "groundY": 283.806, + "roofY": 291.454, + "wallCount": 40, + "roofCount": 10 + }, + { + "id": "sion_1046", + "uuid": "{09B83F2C-A6EF-4F1E-B5C6-71DA61A6A803}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -448.08, + 51.419, + -424.157 + ], + "size": [ + 109.152, + 26.325, + 71.344 + ], + "groundY": 38.256, + "roofY": 64.581, + "wallCount": 167, + "roofCount": 312 + }, + { + "id": "sion_1047", + "uuid": "{152D2EF3-CA5F-405B-89FC-5F23869F2296}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 3 + ], + "center": [ + -893.586, + 9.125, + 206.389 + ], + "size": [ + 37.43, + 18.942, + 24.542 + ], + "groundY": -0.346, + "roofY": 18.595, + "wallCount": 37, + "roofCount": 23 + }, + { + "id": "sion_1048", + "uuid": "{C4F5F6A4-1F03-45C9-9114-133759F23180}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1289.027, + 10.057, + 588.87 + ], + "size": [ + 21.117, + 25.728, + 28.828 + ], + "groundY": -2.807, + "roofY": 22.921, + "wallCount": 110, + "roofCount": 12 + }, + { + "id": "sion_1049", + "uuid": "{12FC2A57-4EE6-4892-ADAD-D44E35ECAB04}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1401.607, + 68.833, + 38.211 + ], + "size": [ + 41.043, + 14.114, + 32.908 + ], + "groundY": 61.776, + "roofY": 75.89, + "wallCount": 35, + "roofCount": 0 + }, + { + "id": "sion_1050", + "uuid": "{C1035395-B19D-4E07-8B76-0F7B5BF317C4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1069.137, + 3.792, + 1363.663 + ], + "size": [ + 91.406, + 13.069, + 65.197 + ], + "groundY": -2.742, + "roofY": 10.327, + "wallCount": 32, + "roofCount": 14 + }, + { + "id": "sion_1051", + "uuid": "{FB1EEDC7-6EA5-425F-BBAA-87DF2EBB234A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1373.244, + 0.104, + 1375.987 + ], + "size": [ + 20.379, + 5.814, + 15.618 + ], + "groundY": -2.803, + "roofY": 3.011, + "wallCount": 18, + "roofCount": 44 + }, + { + "id": "sion_1052", + "uuid": "{1FB4F31B-0A30-4538-AACF-7C9D739BFBE0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -778.816, + 4.326, + 1438.25 + ], + "size": [ + 37.32, + 9.782, + 51.979 + ], + "groundY": -0.565, + "roofY": 9.217, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1053", + "uuid": "{42A6BE5F-3283-4907-B9D4-A78E55B388D6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -545.295, + 6.179, + 1112.531 + ], + "size": [ + 62.738, + 13.272, + 39.56 + ], + "groundY": -0.457, + "roofY": 12.815, + "wallCount": 21, + "roofCount": 8 + }, + { + "id": "sion_1054", + "uuid": "{43122073-8C18-4C7D-AE4F-551366C6F159}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1393.287, + 1.103, + 1392.597 + ], + "size": [ + 10.199, + 8.355, + 12.61 + ], + "groundY": -3.075, + "roofY": 5.28, + "wallCount": 43, + "roofCount": 18 + }, + { + "id": "sion_1055", + "uuid": "{EE7E0C49-31B7-4DC5-BE55-89A9806DE864}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -629.023, + 5.763, + 1391.575 + ], + "size": [ + 47.961, + 11.578, + 39.812 + ], + "groundY": -0.026, + "roofY": 11.552, + "wallCount": 11, + "roofCount": 16 + }, + { + "id": "sion_1056", + "uuid": "{CEC61DB3-2304-4298-9134-5E228ABB01AE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -458.033, + 7.673, + 1292.837 + ], + "size": [ + 69.613, + 15.52, + 67.584 + ], + "groundY": -0.087, + "roofY": 15.433, + "wallCount": 165, + "roofCount": 58 + }, + { + "id": "sion_1057", + "uuid": "{52F9CAD6-784C-4593-A138-3121D35AC00D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -549.934, + 3.19, + 1268.929 + ], + "size": [ + 47.312, + 7.529, + 73.236 + ], + "groundY": -0.574, + "roofY": 6.954, + "wallCount": 32, + "roofCount": 17 + }, + { + "id": "sion_1058", + "uuid": "{1D4785E4-6ED3-4208-A7C9-4AD3942ECC6B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -416.334, + 3.008, + 1229.225 + ], + "size": [ + 17.371, + 6.472, + 21.888 + ], + "groundY": -0.228, + "roofY": 6.244, + "wallCount": 42, + "roofCount": 15 + }, + { + "id": "sion_1059", + "uuid": "{568C5187-3770-4BF8-A246-965E90F96DEE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1156.777, + 3.727, + 1428.225 + ], + "size": [ + 54.352, + 12.228, + 43.384 + ], + "groundY": -2.387, + "roofY": 9.841, + "wallCount": 31, + "roofCount": 6 + }, + { + "id": "sion_1060", + "uuid": "{04E5F1E1-E9EF-4CDB-A9D4-F3F8E981903E}", + "name": "", + "class": "Lagertank", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1189.701, + 6.222, + 1326.425 + ], + "size": [ + 3.277, + 16.509, + 3.27 + ], + "groundY": -2.032, + "roofY": 14.477, + "wallCount": 36, + "roofCount": 75 + }, + { + "id": "sion_1061", + "uuid": "{F18F500D-CFA0-4A2E-8F8B-9067EBD7DA57}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1126.641, + 2.822, + 1511.461 + ], + "size": [ + 64.594, + 9.734, + 35.312 + ], + "groundY": -2.045, + "roofY": 7.688, + "wallCount": 22, + "roofCount": 5 + }, + { + "id": "sion_1062", + "uuid": "{194A1725-80A4-444B-9F64-816A01E1D483}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -725.574, + 4.265, + 1277.046 + ], + "size": [ + 71.383, + 10.743, + 48.406 + ], + "groundY": -1.107, + "roofY": 9.636, + "wallCount": 22, + "roofCount": 4 + }, + { + "id": "sion_1063", + "uuid": "{2F85FCB7-17FF-4B39-BDA5-51AE8612B6E8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1240.705, + 1.947, + 1352.202 + ], + "size": [ + 31.215, + 8.158, + 45.066 + ], + "groundY": -2.132, + "roofY": 6.026, + "wallCount": 14, + "roofCount": 2 + }, + { + "id": "sion_1064", + "uuid": "{C966105C-BFF8-47D6-9E0E-41AB8C15DB14}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -737.986, + 6.299, + 1366.093 + ], + "size": [ + 52.418, + 14.628, + 60.446 + ], + "groundY": -1.015, + "roofY": 13.613, + "wallCount": 11, + "roofCount": 29 + }, + { + "id": "sion_1065", + "uuid": "{AE8B2295-9D0D-4E7F-81A5-0495CD135FD7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1087.777, + 1.799, + 1408.063 + ], + "size": [ + 11.0, + 7.738, + 11.21 + ], + "groundY": -2.07, + "roofY": 5.668, + "wallCount": 54, + "roofCount": 16 + }, + { + "id": "sion_1066", + "uuid": "{9BFE11A0-5725-4B34-9F27-FF4529D33682}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -756.207, + 4.643, + 1181.247 + ], + "size": [ + 55.969, + 10.505, + 60.46 + ], + "groundY": -0.61, + "roofY": 9.895, + "wallCount": 19, + "roofCount": 35 + }, + { + "id": "sion_1067", + "uuid": "{80F1B2FF-D833-4269-92D3-D5DFD1F72AA2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1420.262, + 3.21, + 1382.076 + ], + "size": [ + 27.961, + 12.252, + 19.893 + ], + "groundY": -2.916, + "roofY": 9.336, + "wallCount": 30, + "roofCount": 31 + }, + { + "id": "sion_1068", + "uuid": "{5F254E96-3EB4-4154-9E83-2E1819963ABD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -982.57, + 3.366, + 1498.105 + ], + "size": [ + 53.164, + 10.07, + 61.078 + ], + "groundY": -1.669, + "roofY": 8.401, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1069", + "uuid": "{D5876BE8-CD36-46AD-99EB-F2177CF7FFB6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -449.041, + 2.373, + 1103.469 + ], + "size": [ + 31.754, + 5.32, + 56.59 + ], + "groundY": -0.287, + "roofY": 5.033, + "wallCount": 15, + "roofCount": 2 + }, + { + "id": "sion_1070", + "uuid": "{6F6E667B-7FDE-4833-9FAB-530B6077B6BF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1076.201, + 10.51, + 1246.504 + ], + "size": [ + 17.723, + 25.56, + 10.324 + ], + "groundY": -2.27, + "roofY": 23.29, + "wallCount": 53, + "roofCount": 2 + }, + { + "id": "sion_1071", + "uuid": "{436C5994-83ED-4655-ADD1-8C9924E98306}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -847.822, + 12.155, + 1345.904 + ], + "size": [ + 31.934, + 28.564, + 27.687 + ], + "groundY": -2.127, + "roofY": 26.437, + "wallCount": 55, + "roofCount": 6 + }, + { + "id": "sion_1072", + "uuid": "{89E45D97-6D73-49AA-A3D1-2DF6D44F34E3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -629.629, + 2.757, + 1355.785 + ], + "size": [ + 10.836, + 7.184, + 13.238 + ], + "groundY": -0.835, + "roofY": 6.349, + "wallCount": 42, + "roofCount": 13 + }, + { + "id": "sion_1073", + "uuid": "{162C89B1-9AF1-44CC-A685-5A98692F2D29}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -932.15, + 3.878, + 1345.85 + ], + "size": [ + 86.645, + 12.776, + 112.399 + ], + "groundY": -2.51, + "roofY": 10.266, + "wallCount": 26, + "roofCount": 29 + }, + { + "id": "sion_1074", + "uuid": "{E9D2DB53-1B54-4830-942D-E6E45F8EA159}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -581.186, + 4.737, + 1283.826 + ], + "size": [ + 35.348, + 10.565, + 42.596 + ], + "groundY": -0.545, + "roofY": 10.02, + "wallCount": 23, + "roofCount": 15 + }, + { + "id": "sion_1075", + "uuid": "{2F147D7D-C149-4428-9898-A34B0CB28775}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1322.861, + 0.785, + 1461.1 + ], + "size": [ + 12.41, + 6.333, + 12.802 + ], + "groundY": -2.382, + "roofY": 3.951, + "wallCount": 39, + "roofCount": 22 + }, + { + "id": "sion_1076", + "uuid": "{03282822-9FB5-43E2-9FF5-011BBBE3AFA2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -430.365, + 3.245, + 1231.929 + ], + "size": [ + 21.051, + 6.854, + 27.336 + ], + "groundY": -0.182, + "roofY": 6.672, + "wallCount": 46, + "roofCount": 112 + }, + { + "id": "sion_1077", + "uuid": "{C383ACFE-31B4-443B-BA26-E28A655C9EED}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -777.072, + 2.722, + 1366.375 + ], + "size": [ + 19.644, + 7.653, + 23.689 + ], + "groundY": -1.104, + "roofY": 6.549, + "wallCount": 29, + "roofCount": 13 + }, + { + "id": "sion_1078", + "uuid": "{80BFDAB4-98BC-4BFB-969D-32B0F6C9A4FE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1127.264, + 3.727, + 1246.141 + ], + "size": [ + 29.27, + 10.853, + 28.263 + ], + "groundY": -1.699, + "roofY": 9.154, + "wallCount": 43, + "roofCount": 4 + }, + { + "id": "sion_1079", + "uuid": "{0EE9D04C-83A2-4B97-8F77-9C8150814FB1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1521.197, + 2.334, + 1378.071 + ], + "size": [ + 36.027, + 11.108, + 39.86 + ], + "groundY": -3.22, + "roofY": 7.888, + "wallCount": 8, + "roofCount": 6 + }, + { + "id": "sion_1080", + "uuid": "{0D244DBB-C5EB-4497-B2CE-9A72ACF0E5E2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -842.957, + 4.864, + 1488.472 + ], + "size": [ + 63.945, + 11.164, + 63.681 + ], + "groundY": -0.718, + "roofY": 10.446, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1081", + "uuid": "{3EB9B693-84F6-4BBF-945F-8210407B5493}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -807.492, + 4.41, + 1182.471 + ], + "size": [ + 33.234, + 10.716, + 42.97 + ], + "groundY": -0.948, + "roofY": 9.768, + "wallCount": 22, + "roofCount": 22 + }, + { + "id": "sion_1082", + "uuid": "{44EE0D72-0456-458C-B8E1-947A29E068D9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1165.045, + 2.696, + 1517.944 + ], + "size": [ + 17.441, + 9.03, + 22.096 + ], + "groundY": -1.819, + "roofY": 7.211, + "wallCount": 23, + "roofCount": 22 + }, + { + "id": "sion_1083", + "uuid": "{B90570D6-ED9B-4689-AF00-076805AE73AF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -821.58, + 6.025, + 1401.112 + ], + "size": [ + 83.777, + 14.012, + 65.394 + ], + "groundY": -0.981, + "roofY": 13.031, + "wallCount": 36, + "roofCount": 21 + }, + { + "id": "sion_1084", + "uuid": "{EEACE6A9-1F9C-470C-855E-B3F8B89B99BF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1406.984, + 1.659, + 1399.42 + ], + "size": [ + 22.406, + 8.938, + 19.328 + ], + "groundY": -2.81, + "roofY": 6.128, + "wallCount": 22, + "roofCount": 27 + }, + { + "id": "sion_1085", + "uuid": "{7CC671EA-9F69-4C04-9912-D25E1BAA23DF}", + "name": "", + "class": "Lagertank", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1187.33, + 6.264, + 1331.074 + ], + "size": [ + 3.316, + 16.425, + 3.314 + ], + "groundY": -1.948, + "roofY": 14.477, + "wallCount": 21, + "roofCount": 75 + }, + { + "id": "sion_1086", + "uuid": "{5EEFEBD9-F008-4F12-81C2-9000AA1E5D19}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -815.107, + 4.74, + 1052.665 + ], + "size": [ + 34.402, + 12.701, + 57.918 + ], + "groundY": -1.61, + "roofY": 11.09, + "wallCount": 35, + "roofCount": 56 + }, + { + "id": "sion_1087", + "uuid": "{B3BD70FC-9DAD-4196-BA3B-925BB15FA203}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1388.523, + -0.18, + 1077.162 + ], + "size": [ + 7.289, + 5.804, + 11.171 + ], + "groundY": -3.082, + "roofY": 2.722, + "wallCount": 30, + "roofCount": 13 + }, + { + "id": "sion_1088", + "uuid": "{1F3C1F4D-69A6-4585-9311-72AD98A71A7B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -652.916, + 5.943, + 1307.917 + ], + "size": [ + 104.754, + 13.488, + 67.822 + ], + "groundY": -0.801, + "roofY": 12.687, + "wallCount": 50, + "roofCount": 18 + }, + { + "id": "sion_1089", + "uuid": "{9ACDE6ED-5928-424D-8207-604EE0448C08}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -840.807, + 3.601, + 1199.816 + ], + "size": [ + 59.949, + 9.518, + 57.538 + ], + "groundY": -1.158, + "roofY": 8.36, + "wallCount": 36, + "roofCount": 25 + }, + { + "id": "sion_1090", + "uuid": "{B7343B10-BF3C-4D63-AAE7-877DC9732254}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1103.033, + 2.85, + 1445.248 + ], + "size": [ + 42.082, + 10.164, + 42.062 + ], + "groundY": -2.232, + "roofY": 7.932, + "wallCount": 21, + "roofCount": 14 + }, + { + "id": "sion_1091", + "uuid": "{626E7C5D-9478-4F60-9537-ECE6B8FE3221}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1431.871, + 0.282, + 1366.488 + ], + "size": [ + 19.648, + 6.213, + 15.224 + ], + "groundY": -2.824, + "roofY": 3.389, + "wallCount": 38, + "roofCount": 19 + }, + { + "id": "sion_1092", + "uuid": "{F81BDA47-BCE4-4BC3-9790-15FFBF412230}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -473.928, + 5.868, + 1118.396 + ], + "size": [ + 51.66, + 11.712, + 78.769 + ], + "groundY": 0.012, + "roofY": 11.724, + "wallCount": 37, + "roofCount": 27 + }, + { + "id": "sion_1093", + "uuid": "{2B746C91-8653-4CCF-876B-8B0CB2820601}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1230.523, + 3.631, + 1141.936 + ], + "size": [ + 34.984, + 12.428, + 63.979 + ], + "groundY": -2.583, + "roofY": 9.845, + "wallCount": 43, + "roofCount": 17 + }, + { + "id": "sion_1094", + "uuid": "{627F18F2-3F14-4AAC-AB16-09202BB67B70}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1189.385, + 3.491, + 1354.677 + ], + "size": [ + 13.144, + 10.869, + 13.476 + ], + "groundY": -1.943, + "roofY": 8.926, + "wallCount": 41, + "roofCount": 11 + }, + { + "id": "sion_1095", + "uuid": "{12F2919C-1567-491A-AB61-64EA4E53C408}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -645.318, + 4.231, + 1355.856 + ], + "size": [ + 19.754, + 10.209, + 24.021 + ], + "groundY": -0.873, + "roofY": 9.336, + "wallCount": 26, + "roofCount": 27 + }, + { + "id": "sion_1096", + "uuid": "{526FE45A-4935-4362-A2A3-9880943430F4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -663.258, + 4.216, + 1146.296 + ], + "size": [ + 42.531, + 10.138, + 44.402 + ], + "groundY": -0.853, + "roofY": 9.285, + "wallCount": 29, + "roofCount": 13 + }, + { + "id": "sion_1097", + "uuid": "{D222BADB-44DD-475C-A18F-776F9EDEFA3C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1411.242, + 4.483, + 1212.477 + ], + "size": [ + 208.828, + 15.244, + 80.418 + ], + "groundY": -3.139, + "roofY": 12.105, + "wallCount": 54, + "roofCount": 12 + }, + { + "id": "sion_1098", + "uuid": "{8A0FAA9B-CA3B-4A1F-9DA6-A34776C6CA6B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -797.422, + 2.964, + 1320.205 + ], + "size": [ + 37.773, + 8.564, + 34.533 + ], + "groundY": -1.318, + "roofY": 7.246, + "wallCount": 28, + "roofCount": 19 + }, + { + "id": "sion_1099", + "uuid": "{9BC3FAF0-4CF5-48C5-B8CA-CD03B6581419}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1529.123, + 1.592, + 1164.829 + ], + "size": [ + 74.02, + 9.753, + 44.135 + ], + "groundY": -3.284, + "roofY": 6.469, + "wallCount": 17, + "roofCount": 10 + }, + { + "id": "sion_1100", + "uuid": "{DA1DA88D-12FF-455B-AD25-C863C44A1A7A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -592.08, + 3.624, + 1379.532 + ], + "size": [ + 21.387, + 7.976, + 23.38 + ], + "groundY": -0.364, + "roofY": 7.612, + "wallCount": 16, + "roofCount": 4 + }, + { + "id": "sion_1101", + "uuid": "{EF1078C1-93E5-4D84-B64A-5A447B7C6365}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -855.041, + 3.058, + 1081.376 + ], + "size": [ + 22.184, + 8.809, + 14.279 + ], + "groundY": -1.347, + "roofY": 7.462, + "wallCount": 25, + "roofCount": 4 + }, + { + "id": "sion_1102", + "uuid": "{37F3EBD2-F17E-4351-8D58-03A3F6DB0CC1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -690.199, + 1.728, + 1179.819 + ], + "size": [ + 26.891, + 5.688, + 17.735 + ], + "groundY": -1.116, + "roofY": 4.572, + "wallCount": 16, + "roofCount": 18 + }, + { + "id": "sion_1103", + "uuid": "{5AA805F5-25A9-4582-BA02-7BAC0051EE12}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -516.334, + 6.167, + 1163.546 + ], + "size": [ + 54.832, + 14.172, + 46.016 + ], + "groundY": -0.919, + "roofY": 13.253, + "wallCount": 18, + "roofCount": 6 + }, + { + "id": "sion_1104", + "uuid": "{639C8518-FF22-4E3C-B3BC-A7CF16D91FF4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -637.484, + 2.448, + 1338.434 + ], + "size": [ + 11.727, + 6.587, + 10.901 + ], + "groundY": -0.845, + "roofY": 5.742, + "wallCount": 35, + "roofCount": 20 + }, + { + "id": "sion_1105", + "uuid": "{D4B167C7-2D9F-42B9-AC4E-6CFD357BCB0E}", + "name": "", + "class": "Lagertank", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1185.27, + 6.223, + 1324.273 + ], + "size": [ + 3.445, + 16.506, + 3.441 + ], + "groundY": -2.03, + "roofY": 14.476, + "wallCount": 18, + "roofCount": 75 + }, + { + "id": "sion_1106", + "uuid": "{B268CFF8-D7F9-4668-A841-3A00CE3310AE}", + "name": "", + "class": "Lagertank", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1182.926, + 6.275, + 1328.809 + ], + "size": [ + 3.258, + 16.403, + 3.256 + ], + "groundY": -1.926, + "roofY": 14.477, + "wallCount": 13, + "roofCount": 75 + }, + { + "id": "sion_1107", + "uuid": "{E0AD52E9-56E7-4CF2-9067-7CFE58AFFABD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1497.699, + 2.39, + 1465.934 + ], + "size": [ + 57.617, + 11.634, + 50.97 + ], + "groundY": -3.427, + "roofY": 8.207, + "wallCount": 34, + "roofCount": 44 + }, + { + "id": "sion_1108", + "uuid": "{739225C8-55D9-4F17-B114-CD27697E5CC4}", + "name": "", + "class": "Flugdach", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -1007.115, + 2.221, + 1420.452 + ], + "size": [ + 34.816, + 8.544, + 30.738 + ], + "groundY": -2.051, + "roofY": 6.493, + "wallCount": 18, + "roofCount": 11 + }, + { + "id": "sion_1109", + "uuid": "{4C78D56F-5658-4840-8760-AEA68E4F116D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1168.365, + 2.985, + 1392.98 + ], + "size": [ + 43.91, + 10.404, + 35.716 + ], + "groundY": -2.217, + "roofY": 8.187, + "wallCount": 23, + "roofCount": 8 + }, + { + "id": "sion_1110", + "uuid": "{0F976197-14DC-49D8-A9E7-061509F70B33}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -710.766, + 2.598, + 1354.083 + ], + "size": [ + 10.422, + 6.99, + 8.246 + ], + "groundY": -0.897, + "roofY": 6.093, + "wallCount": 19, + "roofCount": 28 + }, + { + "id": "sion_1111", + "uuid": "{A76DBDBB-2B44-4C7B-920A-B607B58D4484}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -599.453, + 6.544, + 1150.353 + ], + "size": [ + 81.227, + 15.05, + 86.097 + ], + "groundY": -0.981, + "roofY": 14.069, + "wallCount": 105, + "roofCount": 61 + }, + { + "id": "sion_1112", + "uuid": "{DC563901-4050-40D1-A8A1-156AAB3D7C0E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -687.65, + 4.705, + 1364.153 + ], + "size": [ + 20.23, + 10.896, + 27.104 + ], + "groundY": -0.743, + "roofY": 10.153, + "wallCount": 49, + "roofCount": 23 + }, + { + "id": "sion_1113", + "uuid": "{2187B5F4-F739-4134-AD5D-ABDF143D51A1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -873.562, + 2.768, + 1301.179 + ], + "size": [ + 57.633, + 9.828, + 48.546 + ], + "groundY": -2.146, + "roofY": 7.682, + "wallCount": 15, + "roofCount": 21 + }, + { + "id": "sion_1114", + "uuid": "{D067644A-FBA0-472D-9C8F-AE13ED0C6B6C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1040.316, + 1.024, + 1405.959 + ], + "size": [ + 10.828, + 6.318, + 16.272 + ], + "groundY": -2.135, + "roofY": 4.183, + "wallCount": 32, + "roofCount": 3 + }, + { + "id": "sion_1115", + "uuid": "{A36DB96C-C458-4908-8CE3-D1530405CFCF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -900.039, + 3.711, + 1480.616 + ], + "size": [ + 54.453, + 9.958, + 98.838 + ], + "groundY": -1.268, + "roofY": 8.69, + "wallCount": 52, + "roofCount": 58 + }, + { + "id": "sion_1116", + "uuid": "{F151BA0E-55C6-44B2-BD8D-73459E963037}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -890.238, + 3.255, + 1061.937 + ], + "size": [ + 28.953, + 9.85, + 51.144 + ], + "groundY": -1.67, + "roofY": 8.18, + "wallCount": 21, + "roofCount": 30 + }, + { + "id": "sion_1117", + "uuid": "{328C1597-3BD9-4AED-A80B-BB83C9F0ED8B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 5 + ], + "center": [ + -1202.52, + 4.887, + 1323.107 + ], + "size": [ + 36.305, + 13.605, + 21.578 + ], + "groundY": -1.916, + "roofY": 11.689, + "wallCount": 38, + "roofCount": 15 + }, + { + "id": "sion_1118", + "uuid": "{7BBC79F6-7653-48CB-ABC7-B7981FE15AF5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 1, + 5 + ], + "center": [ + -764.66, + 3.835, + 1053.256 + ], + "size": [ + 15.617, + 10.569, + 18.632 + ], + "groundY": -1.449, + "roofY": 9.12, + "wallCount": 26, + "roofCount": 32 + }, + { + "id": "sion_1119", + "uuid": "{9AB21802-FBA9-4A73-A01A-2175FF1F685B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -704.139, + 1.93, + 1155.47 + ], + "size": [ + 32.379, + 6.056, + 36.096 + ], + "groundY": -1.098, + "roofY": 4.958, + "wallCount": 24, + "roofCount": 6 + }, + { + "id": "sion_1120", + "uuid": "{B57C2323-517E-46FA-A868-FDE378DA5518}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -362.309, + 157.802, + -1171.228 + ], + "size": [ + 6.141, + 5.589, + 6.128 + ], + "groundY": 155.008, + "roofY": 160.597, + "wallCount": 20, + "roofCount": 16 + }, + { + "id": "sion_1121", + "uuid": "{4017C7ED-6407-44BC-A0E3-61E1E05F427F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 46.043, + 6.515, + 744.167 + ], + "size": [ + 35.312, + 11.062, + 29.197 + ], + "groundY": 0.984, + "roofY": 12.046, + "wallCount": 41, + "roofCount": 28 + }, + { + "id": "sion_1122", + "uuid": "{66A97F4D-A03B-4AFF-8E9F-BC8133D9CECF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 609.52, + 237.422, + -1366.427 + ], + "size": [ + 10.406, + 9.898, + 10.559 + ], + "groundY": 232.473, + "roofY": 242.371, + "wallCount": 58, + "roofCount": 30 + }, + { + "id": "sion_1123", + "uuid": "{509EAB18-F0A3-48F5-96D9-6DFEED9D55F6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -75.504, + 50.872, + -384.99 + ], + "size": [ + 15.18, + 13.245, + 29.4 + ], + "groundY": 44.25, + "roofY": 57.494, + "wallCount": 36, + "roofCount": 8 + }, + { + "id": "sion_1124", + "uuid": "{A5F1732E-7D67-4277-A04E-6538708EAEC9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -174.803, + 31.932, + 92.83 + ], + "size": [ + 38.894, + 23.541, + 28.658 + ], + "groundY": 20.162, + "roofY": 43.703, + "wallCount": 65, + "roofCount": 39 + }, + { + "id": "sion_1125", + "uuid": "{D3EB4B30-AA51-4F3A-AA4C-7F547893FF4F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 90.078, + 63.201, + -793.721 + ], + "size": [ + 16.703, + 10.238, + 18.532 + ], + "groundY": 58.082, + "roofY": 68.32, + "wallCount": 41, + "roofCount": 17 + }, + { + "id": "sion_1126", + "uuid": "{D7F8BDC2-3D24-4B7A-8A1B-19BE56E857F6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 622.611, + 234.618, + -1364.164 + ], + "size": [ + 14.699, + 4.457, + 8.606 + ], + "groundY": 232.389, + "roofY": 236.846, + "wallCount": 16, + "roofCount": 12 + }, + { + "id": "sion_1127", + "uuid": "{E03A0B2A-0C6D-4182-9AF0-0E60D95F5857}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 724.342, + 15.628, + -29.735 + ], + "size": [ + 31.379, + 25.884, + 21.689 + ], + "groundY": 2.686, + "roofY": 28.57, + "wallCount": 92, + "roofCount": 17 + }, + { + "id": "sion_1128", + "uuid": "{719663BC-91C9-4855-81B3-37BE94540CA5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 108.461, + 67.471, + -841.515 + ], + "size": [ + 29.734, + 17.863, + 23.748 + ], + "groundY": 58.54, + "roofY": 76.402, + "wallCount": 28, + "roofCount": 14 + }, + { + "id": "sion_1129", + "uuid": "{C7CD5572-FED9-4665-855C-1495162EEAA9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 343.197, + 6.212, + 843.021 + ], + "size": [ + 26.418, + 7.958, + 27.011 + ], + "groundY": 2.233, + "roofY": 10.191, + "wallCount": 29, + "roofCount": 19 + }, + { + "id": "sion_1130", + "uuid": "{05B0DAE7-95B5-414A-985B-1A8E4FB6DDA9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 812.9, + 5.165, + -218.168 + ], + "size": [ + 23.441, + 5.24, + 33.223 + ], + "groundY": 2.545, + "roofY": 7.785, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1131", + "uuid": "{B4B780E8-D568-40BB-AF0E-8C855537EBB9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 796.824, + 8.424, + 534.644 + ], + "size": [ + 45.141, + 8.38, + 34.707 + ], + "groundY": 4.234, + "roofY": 12.614, + "wallCount": 16, + "roofCount": 4 + }, + { + "id": "sion_1132", + "uuid": "{93E7110A-5AC0-4DEB-AB90-FD381E7B2576}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 334.689, + 11.547, + 9.999 + ], + "size": [ + 23.09, + 7.066, + 11.424 + ], + "groundY": 8.014, + "roofY": 15.08, + "wallCount": 16, + "roofCount": 6 + }, + { + "id": "sion_1133", + "uuid": "{AA53BAD7-F783-4D48-8A5B-D24A0426A36B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 148.816, + 172.265, + -1228.516 + ], + "size": [ + 30.672, + 9.75, + 14.522 + ], + "groundY": 167.39, + "roofY": 177.14, + "wallCount": 47, + "roofCount": 29 + }, + { + "id": "sion_1134", + "uuid": "{493EB25B-A686-4BB8-8022-D22F24D572C3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -197.395, + 62.978, + -728.775 + ], + "size": [ + 12.383, + 13.95, + 15.63 + ], + "groundY": 56.003, + "roofY": 69.953, + "wallCount": 40, + "roofCount": 54 + }, + { + "id": "sion_1135", + "uuid": "{64CDB2F3-AD64-4239-8D0D-2FF316A2A805}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -240.545, + 46.407, + -317.245 + ], + "size": [ + 47.481, + 21.275, + 25.064 + ], + "groundY": 35.77, + "roofY": 57.045, + "wallCount": 87, + "roofCount": 59 + }, + { + "id": "sion_1136", + "uuid": "{B3C434BD-80A8-4C89-81AC-3FE8AC991C5E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 380.998, + 9.477, + 479.888 + ], + "size": [ + 19.668, + 13.401, + 18.815 + ], + "groundY": 2.776, + "roofY": 16.177, + "wallCount": 12, + "roofCount": 6 + }, + { + "id": "sion_1137", + "uuid": "{B57ACE0F-FD27-4516-B53A-EF1E0EBB8F5E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 734.037, + 8.079, + -74.358 + ], + "size": [ + 30.363, + 7.875, + 23.854 + ], + "groundY": 4.142, + "roofY": 12.017, + "wallCount": 67, + "roofCount": 26 + }, + { + "id": "sion_1138", + "uuid": "{B3C0478B-61BC-4252-B6A1-8FF31DBD99B4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -271.959, + 56.76, + -537.693 + ], + "size": [ + 50.051, + 20.796, + 16.494 + ], + "groundY": 46.362, + "roofY": 67.158, + "wallCount": 58, + "roofCount": 89 + }, + { + "id": "sion_1139", + "uuid": "{37F7BDB8-39B1-45E1-A36C-18B6F86E609C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -278.85, + 74.895, + -870.87 + ], + "size": [ + 23.473, + 14.421, + 19.559 + ], + "groundY": 67.685, + "roofY": 82.106, + "wallCount": 13, + "roofCount": 33 + }, + { + "id": "sion_1140", + "uuid": "{23C10AF2-21F8-4B7B-A671-2B406A2C07FA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 189.844, + 60.457, + -797.783 + ], + "size": [ + 43.953, + 14.545, + 25.034 + ], + "groundY": 53.185, + "roofY": 67.73, + "wallCount": 16, + "roofCount": 27 + }, + { + "id": "sion_1141", + "uuid": "{E1E25407-BBB3-403C-B973-E94033ED34A2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 474.48, + 79.899, + -336.005 + ], + "size": [ + 7.016, + 7.832, + 6.848 + ], + "groundY": 75.983, + "roofY": 83.815, + "wallCount": 61, + "roofCount": 12 + }, + { + "id": "sion_1142", + "uuid": "{DBE91FC9-3725-45A0-8474-2AAE7E5E5A1C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 108.83, + 71.851, + -917.619 + ], + "size": [ + 28.379, + 18.963, + 19.731 + ], + "groundY": 62.37, + "roofY": 81.333, + "wallCount": 10, + "roofCount": 14 + }, + { + "id": "sion_1143", + "uuid": "{75E6242E-8C7A-453F-A798-421F5DDFE5E6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 177.857, + 9.182, + 693.691 + ], + "size": [ + 23.918, + 13.999, + 22.968 + ], + "groundY": 2.183, + "roofY": 16.182, + "wallCount": 52, + "roofCount": 21 + }, + { + "id": "sion_1144", + "uuid": "{7347C5B4-91F7-4058-9DC9-59543B76F906}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 366.629, + 17.679, + 101.405 + ], + "size": [ + 61.211, + 24.236, + 44.552 + ], + "groundY": 5.561, + "roofY": 29.797, + "wallCount": 41, + "roofCount": 18 + }, + { + "id": "sion_1145", + "uuid": "{495D92F4-804E-4974-B6B9-AFCC1C96BD20}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 443.242, + 219.84, + -1344.402 + ], + "size": [ + 16.602, + 9.365, + 15.524 + ], + "groundY": 215.157, + "roofY": 224.522, + "wallCount": 55, + "roofCount": 26 + }, + { + "id": "sion_1146", + "uuid": "{B7E2E067-596D-4A63-8B1F-F5AB734F6DDD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 98.619, + 74.303, + -950.713 + ], + "size": [ + 28.301, + 21.351, + 19.305 + ], + "groundY": 63.628, + "roofY": 84.979, + "wallCount": 12, + "roofCount": 16 + }, + { + "id": "sion_1147", + "uuid": "{0F075D89-B5FF-4CB8-9AC2-A1C8C732B293}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 245.867, + 71.17, + -899.196 + ], + "size": [ + 16.406, + 10.052, + 15.353 + ], + "groundY": 66.144, + "roofY": 76.196, + "wallCount": 31, + "roofCount": 14 + }, + { + "id": "sion_1148", + "uuid": "{ECEC43E5-C4AC-457B-A837-15D8010102F0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 817.078, + 16.001, + 76.517 + ], + "size": [ + 37.797, + 25.006, + 33.09 + ], + "groundY": 3.498, + "roofY": 28.504, + "wallCount": 104, + "roofCount": 22 + }, + { + "id": "sion_1149", + "uuid": "{A5D7489C-F09A-49E0-A220-2810F1118E13}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 512.934, + 219.256, + -1508.925 + ], + "size": [ + 14.5, + 10.362, + 14.34 + ], + "groundY": 214.075, + "roofY": 224.437, + "wallCount": 20, + "roofCount": 11 + }, + { + "id": "sion_1150", + "uuid": "{382D2A79-AB5A-4B55-8662-432D919089C0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 0.623, + 58.725, + -293.713 + ], + "size": [ + 5.848, + 5.466, + 6.15 + ], + "groundY": 55.992, + "roofY": 61.458, + "wallCount": 18, + "roofCount": 8 + }, + { + "id": "sion_1151", + "uuid": "{A06B4601-6B99-4097-8FDD-35D780F9833F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -230.07, + 21.103, + 304.533 + ], + "size": [ + 68.539, + 24.826, + 39.364 + ], + "groundY": 8.69, + "roofY": 33.516, + "wallCount": 94, + "roofCount": 77 + }, + { + "id": "sion_1152", + "uuid": "{1B0122D7-397A-4828-8A74-7151F678378E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 227.629, + 14.43, + 258.172 + ], + "size": [ + 20.805, + 13.58, + 19.958 + ], + "groundY": 7.64, + "roofY": 21.22, + "wallCount": 10, + "roofCount": 7 + }, + { + "id": "sion_1153", + "uuid": "{4773E7AD-EA6F-469D-8AF3-67F9973CD304}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 646.568, + 12.997, + 94.426 + ], + "size": [ + 16.098, + 19.784, + 59.75 + ], + "groundY": 3.105, + "roofY": 22.889, + "wallCount": 45, + "roofCount": 34 + }, + { + "id": "sion_1154", + "uuid": "{2BCA7AD7-D4D2-4B0F-9B47-830282ECCB5D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1347.125, + 11.399, + 426.846 + ], + "size": [ + 26.344, + 8.458, + 90.906 + ], + "groundY": 7.17, + "roofY": 15.628, + "wallCount": 42, + "roofCount": 13 + }, + { + "id": "sion_1155", + "uuid": "{6623F4F1-2811-4FA1-B510-8D1C1A95B1C6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 13.918, + 78.621, + -255.211 + ], + "size": [ + 15.227, + 12.857, + 14.775 + ], + "groundY": 72.193, + "roofY": 85.049, + "wallCount": 30, + "roofCount": 8 + }, + { + "id": "sion_1156", + "uuid": "{8268FF9F-368A-4EFE-875D-5ED298146D15}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 184.77, + 10.227, + 396.38 + ], + "size": [ + 25.656, + 11.322, + 21.988 + ], + "groundY": 4.566, + "roofY": 15.888, + "wallCount": 19, + "roofCount": 11 + }, + { + "id": "sion_1157", + "uuid": "{FA3BCCF2-6311-4FF0-A42A-E49B1D8675EC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -391.725, + 10.51, + 481.711 + ], + "size": [ + 53.09, + 19.33, + 81.6 + ], + "groundY": 0.845, + "roofY": 20.175, + "wallCount": 59, + "roofCount": 29 + }, + { + "id": "sion_1158", + "uuid": "{03A23E6E-E4AB-4E0B-B802-B2A76202EF05}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 770.307, + 10.732, + -235.786 + ], + "size": [ + 36.481, + 15.392, + 29.346 + ], + "groundY": 3.036, + "roofY": 18.428, + "wallCount": 58, + "roofCount": 2 + }, + { + "id": "sion_1159", + "uuid": "{C92FAF45-C137-4716-AC97-7A47C6D13B27}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 690.627, + 11.478, + 193.239 + ], + "size": [ + 22.113, + 19.353, + 21.694 + ], + "groundY": 1.802, + "roofY": 21.155, + "wallCount": 53, + "roofCount": 7 + }, + { + "id": "sion_1160", + "uuid": "{10C8ADD0-9AEB-4288-8C58-6D853F27855A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 440.902, + 218.102, + -1370.609 + ], + "size": [ + 17.742, + 5.674, + 16.065 + ], + "groundY": 215.265, + "roofY": 220.939, + "wallCount": 27, + "roofCount": 2 + }, + { + "id": "sion_1161", + "uuid": "{3C8DF548-2761-4370-8207-9F6D76A70DFD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 2 + ], + "center": [ + 87.121, + 25.081, + -69.442 + ], + "size": [ + 31.766, + 13.8, + 35.774 + ], + "groundY": 18.181, + "roofY": 31.98, + "wallCount": 20, + "roofCount": 4 + }, + { + "id": "sion_1162", + "uuid": "{F0C16585-0B26-471B-B0DD-CB3863B392BD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 300.785, + 6.937, + 885.322 + ], + "size": [ + 30.547, + 9.619, + 29.844 + ], + "groundY": 2.127, + "roofY": 11.746, + "wallCount": 17, + "roofCount": 8 + }, + { + "id": "sion_1163", + "uuid": "{85F80483-3AC9-4EA8-B645-2A669E32C930}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 310.055, + 208.488, + -1390.637 + ], + "size": [ + 18.797, + 10.749, + 21.674 + ], + "groundY": 203.114, + "roofY": 213.863, + "wallCount": 40, + "roofCount": 21 + }, + { + "id": "sion_1164", + "uuid": "{C91B443F-19FD-4A00-9A2D-A439B566226D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 12.877, + 7.848, + 760.584 + ], + "size": [ + 28.402, + 14.882, + 26.275 + ], + "groundY": 0.407, + "roofY": 15.289, + "wallCount": 20, + "roofCount": 2 + }, + { + "id": "sion_1165", + "uuid": "{3C48D3F7-A06A-4154-A1F4-FF6934E880BC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -373.816, + 54.374, + -477.085 + ], + "size": [ + 29.336, + 21.118, + 52.649 + ], + "groundY": 43.815, + "roofY": 64.933, + "wallCount": 148, + "roofCount": 82 + }, + { + "id": "sion_1166", + "uuid": "{16FE43FC-A6DC-4AAF-9FA8-1BE131EF2F22}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -388.479, + 47.138, + -378.364 + ], + "size": [ + 20.637, + 14.448, + 17.41 + ], + "groundY": 39.914, + "roofY": 54.362, + "wallCount": 26, + "roofCount": 17 + }, + { + "id": "sion_1167", + "uuid": "{6E285A08-D8B4-48DD-8150-88EB11BD5F01}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -65.754, + 78.723, + -925.478 + ], + "size": [ + 21.211, + 18.567, + 39.36 + ], + "groundY": 69.44, + "roofY": 88.007, + "wallCount": 39, + "roofCount": 29 + }, + { + "id": "sion_1168", + "uuid": "{5504E7BD-FF94-47C1-8451-C8508BC34A74}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 219.256, + 57.48, + -710.245 + ], + "size": [ + 16.027, + 9.672, + 12.714 + ], + "groundY": 52.644, + "roofY": 62.316, + "wallCount": 38, + "roofCount": 16 + }, + { + "id": "sion_1169", + "uuid": "{AD1AE676-D941-4A2C-AE90-0E1EE986881C}", + "name": "", + "class": "Sakrales Gebaeude", + "archStyle": "fortress", + "tile": [ + 2, + 3 + ], + "center": [ + -85.625, + 25.103, + 182.207 + ], + "size": [ + 38.078, + 22.8, + 49.629 + ], + "groundY": 13.703, + "roofY": 36.503, + "wallCount": 142, + "roofCount": 58 + }, + { + "id": "sion_1170", + "uuid": "{4B00ABA3-3F49-4A50-9276-CE0E9C01210F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 0 + ], + "center": [ + 1266.23, + 22.171, + -1278.382 + ], + "size": [ + 6.844, + 6.418, + 6.354 + ], + "groundY": 18.962, + "roofY": 25.38, + "wallCount": 34, + "roofCount": 7 + }, + { + "id": "sion_1171", + "uuid": "{A85AFA4D-95AA-4E5E-945C-52FC6891CA19}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 873.572, + 7.942, + 725.246 + ], + "size": [ + 59.637, + 9.9, + 51.0 + ], + "groundY": 2.992, + "roofY": 12.892, + "wallCount": 65, + "roofCount": 40 + }, + { + "id": "sion_1172", + "uuid": "{A7895A58-7D0A-4E81-AE1F-E914475EF027}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 322.316, + 67.531, + -637.352 + ], + "size": [ + 19.094, + 12.12, + 19.317 + ], + "groundY": 61.471, + "roofY": 73.591, + "wallCount": 44, + "roofCount": 25 + }, + { + "id": "sion_1173", + "uuid": "{2237F3CA-2EAA-40AC-8D0E-4767F32330B1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -50.209, + 54.343, + -430.976 + ], + "size": [ + 19.637, + 20.902, + 33.468 + ], + "groundY": 43.892, + "roofY": 64.794, + "wallCount": 10, + "roofCount": 24 + }, + { + "id": "sion_1174", + "uuid": "{8BC5F6D3-EE97-435E-B560-201F64F2A301}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 194.699, + 5.497, + 685.506 + ], + "size": [ + 13.414, + 6.641, + 13.775 + ], + "groundY": 2.177, + "roofY": 8.818, + "wallCount": 10, + "roofCount": 13 + }, + { + "id": "sion_1175", + "uuid": "{B33658B3-C7E6-4066-9C84-553D75BEA001}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 1 + ], + "center": [ + 1500.324, + 9.876, + -615.63 + ], + "size": [ + 5.031, + 5.89, + 5.042 + ], + "groundY": 6.931, + "roofY": 12.821, + "wallCount": 5, + "roofCount": 4 + }, + { + "id": "sion_1176", + "uuid": "{D787DE24-0541-4124-912B-C2C9CBD7C1C1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 179.551, + 22.961, + 74.638 + ], + "size": [ + 17.328, + 15.69, + 17.654 + ], + "groundY": 15.116, + "roofY": 30.806, + "wallCount": 8, + "roofCount": 26 + }, + { + "id": "sion_1177", + "uuid": "{B784C122-D6C5-41B1-8DC0-4E143FFBF2E9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 260.227, + 19.049, + 171.341 + ], + "size": [ + 23.305, + 14.271, + 18.618 + ], + "groundY": 11.913, + "roofY": 26.184, + "wallCount": 44, + "roofCount": 21 + }, + { + "id": "sion_1178", + "uuid": "{5A26EC9D-7D3F-4EB3-8062-A090BD07D5F4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 338.174, + 56.743, + -794.789 + ], + "size": [ + 33.418, + 15.088, + 24.1 + ], + "groundY": 49.199, + "roofY": 64.287, + "wallCount": 22, + "roofCount": 23 + }, + { + "id": "sion_1179", + "uuid": "{96FDB35A-8CD8-49BC-A34E-CF1449EB06F2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1084.018, + 10.965, + 399.717 + ], + "size": [ + 13.668, + 10.807, + 15.204 + ], + "groundY": 5.562, + "roofY": 16.369, + "wallCount": 30, + "roofCount": 33 + }, + { + "id": "sion_1180", + "uuid": "{048C48F3-AB13-488A-8782-B207BF91DC99}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 215.719, + 187.285, + -1387.895 + ], + "size": [ + 27.203, + 11.481, + 16.743 + ], + "groundY": 181.545, + "roofY": 193.026, + "wallCount": 57, + "roofCount": 15 + }, + { + "id": "sion_1181", + "uuid": "{811C00B8-913B-4FE9-9B7C-FE5CDA514020}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 221.533, + 25.999, + 301.903 + ], + "size": [ + 29.051, + 40.621, + 31.096 + ], + "groundY": 5.688, + "roofY": 46.309, + "wallCount": 116, + "roofCount": 13 + }, + { + "id": "sion_1182", + "uuid": "{05EC83A2-8EC1-4CC0-BCA0-A296E4B78975}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 815.891, + 7.918, + 948.317 + ], + "size": [ + 13.469, + 6.149, + 13.36 + ], + "groundY": 4.843, + "roofY": 10.992, + "wallCount": 33, + "roofCount": 16 + }, + { + "id": "sion_1183", + "uuid": "{2A4F438C-C095-4141-A35D-4E9E1E556695}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 284.465, + 206.348, + -1323.588 + ], + "size": [ + 16.688, + 12.828, + 16.98 + ], + "groundY": 199.934, + "roofY": 212.762, + "wallCount": 37, + "roofCount": 9 + }, + { + "id": "sion_1184", + "uuid": "{BB849F0F-4792-49E6-B781-E05382C13EB9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 4 + ], + "center": [ + 1039.897, + 11.418, + 544.676 + ], + "size": [ + 13.973, + 11.87, + 40.75 + ], + "groundY": 5.483, + "roofY": 17.353, + "wallCount": 18, + "roofCount": 24 + }, + { + "id": "sion_1185", + "uuid": "{4C00A2F1-0C4A-48EF-80AC-D094B63552D4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -11.219, + 71.518, + -863.02 + ], + "size": [ + 26.594, + 13.177, + 22.089 + ], + "groundY": 64.93, + "roofY": 78.107, + "wallCount": 44, + "roofCount": 24 + }, + { + "id": "sion_1186", + "uuid": "{4A5341A6-1B06-460A-9C83-A46C9FD43D4E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -291.262, + 20.176, + 312.003 + ], + "size": [ + 18.484, + 20.087, + 23.672 + ], + "groundY": 10.133, + "roofY": 30.22, + "wallCount": 44, + "roofCount": 39 + }, + { + "id": "sion_1187", + "uuid": "{E45546AD-C1A7-4CBD-9038-6C0A8E248767}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 530.287, + 224.514, + -1478.347 + ], + "size": [ + 34.785, + 17.592, + 32.742 + ], + "groundY": 215.718, + "roofY": 233.31, + "wallCount": 52, + "roofCount": 57 + }, + { + "id": "sion_1188", + "uuid": "{66F74EC4-C813-4A01-B458-B00ACD5F9273}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1103.771, + 13.758, + 311.445 + ], + "size": [ + 30.715, + 18.682, + 32.866 + ], + "groundY": 4.417, + "roofY": 23.1, + "wallCount": 106, + "roofCount": 31 + }, + { + "id": "sion_1189", + "uuid": "{FAE6BB76-C347-4B5C-A970-6F67D74280B4}", + "name": "", + "class": "Lagertank", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 616.148, + 14.688, + 801.64 + ], + "size": [ + 19.398, + 24.855, + 19.398 + ], + "groundY": 2.261, + "roofY": 27.116, + "wallCount": 383, + "roofCount": 104 + }, + { + "id": "sion_1190", + "uuid": "{D0908697-3164-499D-A288-4E384900EA64}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -106.127, + 65.744, + -735.447 + ], + "size": [ + 21.855, + 13.946, + 18.828 + ], + "groundY": 58.771, + "roofY": 72.717, + "wallCount": 23, + "roofCount": 12 + }, + { + "id": "sion_1191", + "uuid": "{61A7DD14-C9A7-49B8-BA64-60CBE406A0BC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 931.658, + 15.75, + -33.414 + ], + "size": [ + 48.121, + 25.69, + 40.12 + ], + "groundY": 2.905, + "roofY": 28.595, + "wallCount": 69, + "roofCount": 10 + }, + { + "id": "sion_1192", + "uuid": "{1E21BBCB-B98E-4D39-AFD8-86B6868D3F35}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 217.189, + 60.435, + -646.131 + ], + "size": [ + 12.988, + 11.667, + 7.81 + ], + "groundY": 54.601, + "roofY": 66.268, + "wallCount": 32, + "roofCount": 25 + }, + { + "id": "sion_1193", + "uuid": "{21A6F0D1-39C4-4018-BA25-E131219BF3C9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -321.74, + 55.184, + -488.074 + ], + "size": [ + 30.707, + 20.434, + 13.758 + ], + "groundY": 44.967, + "roofY": 65.401, + "wallCount": 43, + "roofCount": 32 + }, + { + "id": "sion_1194", + "uuid": "{54796B90-3964-4C7F-BB33-4C08B50B1FD6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 460.592, + 10.955, + 767.072 + ], + "size": [ + 50.254, + 14.175, + 56.394 + ], + "groundY": 3.868, + "roofY": 18.043, + "wallCount": 54, + "roofCount": 48 + }, + { + "id": "sion_1195", + "uuid": "{F908A9B1-8976-4D21-8554-AAAB81BD6061}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 155.441, + 9.331, + 335.989 + ], + "size": [ + 27.234, + 7.448, + 30.065 + ], + "groundY": 5.607, + "roofY": 13.055, + "wallCount": 20, + "roofCount": 5 + }, + { + "id": "sion_1196", + "uuid": "{336E2C42-A284-49E5-8ED0-F51BFA9D5EFE}", + "name": "", + "class": "Unterirdisches Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 672.652, + 17.578, + -72.393 + ], + "size": [ + 65.586, + 30.08, + 67.573 + ], + "groundY": 2.538, + "roofY": 32.618, + "wallCount": 147, + "roofCount": 61 + }, + { + "id": "sion_1197", + "uuid": "{94EA80C7-0F70-4F15-B580-EE65FD31A921}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 313.492, + 90.421, + -1045.633 + ], + "size": [ + 36.898, + 13.614, + 21.082 + ], + "groundY": 83.614, + "roofY": 97.228, + "wallCount": 46, + "roofCount": 22 + }, + { + "id": "sion_1198", + "uuid": "{52D77A42-768C-41AB-BCCE-BF09742B9634}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -195.984, + 75.48, + -858.965 + ], + "size": [ + 20.875, + 22.088, + 22.804 + ], + "groundY": 64.436, + "roofY": 86.524, + "wallCount": 33, + "roofCount": 16 + }, + { + "id": "sion_1199", + "uuid": "{F693BAB7-CFE8-4416-A225-9634FB8E0021}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 4 + ], + "center": [ + 1073.877, + 10.45, + 640.331 + ], + "size": [ + 72.012, + 10.095, + 19.699 + ], + "groundY": 5.403, + "roofY": 15.498, + "wallCount": 14, + "roofCount": 25 + }, + { + "id": "sion_1200", + "uuid": "{97D1F438-AEF5-402F-845F-52C8F39D6B95}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -282.65, + 12.42, + 489.472 + ], + "size": [ + 111.691, + 15.097, + 45.09 + ], + "groundY": 4.872, + "roofY": 19.969, + "wallCount": 34, + "roofCount": 39 + }, + { + "id": "sion_1201", + "uuid": "{4EDF6B4D-71B3-42B1-8528-7D43B59DF082}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 170.637, + 24.159, + -101.942 + ], + "size": [ + 45.195, + 22.094, + 15.622 + ], + "groundY": 13.112, + "roofY": 35.206, + "wallCount": 20, + "roofCount": 29 + }, + { + "id": "sion_1202", + "uuid": "{003886CF-A6E6-4FF8-8873-0A2FCDF1BEBD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -78.287, + 34.167, + -27.22 + ], + "size": [ + 54.73, + 22.328, + 55.328 + ], + "groundY": 23.003, + "roofY": 45.331, + "wallCount": 157, + "roofCount": 90 + }, + { + "id": "sion_1203", + "uuid": "{51ED90EA-C51E-41A2-AFBE-D535E79E5ED3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 613.877, + 93.875, + -1093.276 + ], + "size": [ + 27.855, + 10.402, + 12.735 + ], + "groundY": 88.674, + "roofY": 99.076, + "wallCount": 27, + "roofCount": 17 + }, + { + "id": "sion_1204", + "uuid": "{22FBEBB3-095A-4C97-8A09-B2382097FD84}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 423.193, + 72.856, + -994.536 + ], + "size": [ + 23.113, + 8.144, + 15.742 + ], + "groundY": 68.784, + "roofY": 76.928, + "wallCount": 39, + "roofCount": 21 + }, + { + "id": "sion_1205", + "uuid": "{DC99F0D4-7F88-4F6E-8CBF-0ACA2153480B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -351.479, + 69.204, + -837.322 + ], + "size": [ + 66.465, + 8.405, + 19.806 + ], + "groundY": 65.001, + "roofY": 73.406, + "wallCount": 32, + "roofCount": 11 + }, + { + "id": "sion_1206", + "uuid": "{AC223CE7-2BEA-4C64-816E-143C32852D2E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 32.832, + 70.34, + -835.627 + ], + "size": [ + 27.648, + 19.68, + 38.746 + ], + "groundY": 60.5, + "roofY": 80.18, + "wallCount": 32, + "roofCount": 15 + }, + { + "id": "sion_1207", + "uuid": "{F7B72078-35A5-4BC4-AAB7-6BCC8271E439}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1213.668, + 9.228, + 201.393 + ], + "size": [ + 24.203, + 5.391, + 6.042 + ], + "groundY": 6.533, + "roofY": 11.924, + "wallCount": 16, + "roofCount": 2 + }, + { + "id": "sion_1208", + "uuid": "{772BBAA1-BBA1-4DC2-B363-3AE1398275B3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 129.195, + 174.611, + -1262.843 + ], + "size": [ + 12.812, + 10.908, + 15.254 + ], + "groundY": 169.157, + "roofY": 180.065, + "wallCount": 52, + "roofCount": 30 + }, + { + "id": "sion_1209", + "uuid": "{768BFEBA-9644-4377-A9F0-D5CEFD8E3FFF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1472.365, + 14.789, + 431.968 + ], + "size": [ + 50.856, + 13.424, + 57.296 + ], + "groundY": 8.077, + "roofY": 21.501, + "wallCount": 54, + "roofCount": 72 + }, + { + "id": "sion_1210", + "uuid": "{7C57EDCB-1CBE-4577-85EC-6D9F7A761F1E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 374.844, + 214.53, + -1410.275 + ], + "size": [ + 13.203, + 10.708, + 13.813 + ], + "groundY": 209.176, + "roofY": 219.884, + "wallCount": 48, + "roofCount": 12 + }, + { + "id": "sion_1211", + "uuid": "{D1A584BF-22CD-4C1B-AD74-439BACE150CB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 2 + ], + "center": [ + 1201.717, + 10.623, + -5.261 + ], + "size": [ + 15.863, + 5.642, + 21.144 + ], + "groundY": 7.802, + "roofY": 13.444, + "wallCount": 12, + "roofCount": 14 + }, + { + "id": "sion_1212", + "uuid": "{E26F2EA9-B623-44AA-8A3B-5E6A068FA9D1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 978.445, + 12.842, + 323.212 + ], + "size": [ + 65.781, + 19.342, + 24.531 + ], + "groundY": 3.171, + "roofY": 22.513, + "wallCount": 26, + "roofCount": 8 + }, + { + "id": "sion_1213", + "uuid": "{9C2CBCEA-3EA0-402F-92A1-3E10B2291FC0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 203.572, + 57.153, + -758.718 + ], + "size": [ + 15.879, + 9.604, + 13.976 + ], + "groundY": 52.351, + "roofY": 61.955, + "wallCount": 34, + "roofCount": 19 + }, + { + "id": "sion_1214", + "uuid": "{B4895B16-917C-4D72-896B-80C300289011}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 474.783, + 63.107, + -936.993 + ], + "size": [ + 20.082, + 9.645, + 18.59 + ], + "groundY": 58.285, + "roofY": 67.93, + "wallCount": 30, + "roofCount": 18 + }, + { + "id": "sion_1215", + "uuid": "{4F100319-0754-413C-9A3F-2F72F1007A97}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -199.678, + 34.091, + 29.537 + ], + "size": [ + 48.894, + 22.427, + 33.447 + ], + "groundY": 22.877, + "roofY": 45.304, + "wallCount": 115, + "roofCount": 80 + }, + { + "id": "sion_1216", + "uuid": "{D199D9E1-6261-4264-86B5-496E2A23B5FD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 801.691, + 15.53, + -32.955 + ], + "size": [ + 27.742, + 25.676, + 25.219 + ], + "groundY": 2.692, + "roofY": 28.368, + "wallCount": 87, + "roofCount": 15 + }, + { + "id": "sion_1217", + "uuid": "{7B5C74B3-B608-49B1-ADE5-4C5DE104AB83}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 3 + ], + "center": [ + -54.814, + 20.833, + 146.299 + ], + "size": [ + 44.637, + 10.507, + 33.352 + ], + "groundY": 15.58, + "roofY": 26.087, + "wallCount": 36, + "roofCount": 18 + }, + { + "id": "sion_1218", + "uuid": "{E6873DC6-516F-4D0C-ABAF-D7D1A277C82B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 611.135, + 227.971, + -1520.954 + ], + "size": [ + 43.184, + 21.514, + 31.71 + ], + "groundY": 217.214, + "roofY": 238.728, + "wallCount": 106, + "roofCount": 73 + }, + { + "id": "sion_1219", + "uuid": "{EE4CE93C-E7D3-4F1D-96B6-3A0C56282B06}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -71.02, + 98.319, + -1243.2 + ], + "size": [ + 30.688, + 11.448, + 44.264 + ], + "groundY": 92.595, + "roofY": 104.043, + "wallCount": 26, + "roofCount": 4 + }, + { + "id": "sion_1220", + "uuid": "{90ABD45C-9205-4CE5-B88C-423EB2B1A1D9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 4 + ], + "center": [ + 1322.408, + 16.71, + 945.95 + ], + "size": [ + 10.16, + 6.515, + 7.062 + ], + "groundY": 13.452, + "roofY": 19.967, + "wallCount": 35, + "roofCount": 16 + }, + { + "id": "sion_1221", + "uuid": "{4F37D57E-D673-48F8-BC97-5E65261831B1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -345.066, + 15.09, + 350.575 + ], + "size": [ + 16.672, + 13.448, + 16.952 + ], + "groundY": 8.366, + "roofY": 21.814, + "wallCount": 44, + "roofCount": 25 + }, + { + "id": "sion_1222", + "uuid": "{79FA05DD-CA56-494F-9F8C-CB0B6080CE4A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 743.777, + 9.241, + 909.455 + ], + "size": [ + 56.516, + 10.564, + 54.281 + ], + "groundY": 3.959, + "roofY": 14.523, + "wallCount": 29, + "roofCount": 22 + }, + { + "id": "sion_1223", + "uuid": "{C367926E-58F3-4C55-9663-1044E288B4B7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1268.408, + 10.961, + 300.816 + ], + "size": [ + 11.996, + 7.154, + 16.792 + ], + "groundY": 7.384, + "roofY": 14.538, + "wallCount": 31, + "roofCount": 32 + }, + { + "id": "sion_1224", + "uuid": "{5B37BCCA-A087-43DA-95A6-E1BF3127ABF8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 21.455, + 19.501, + 341.348 + ], + "size": [ + 47.012, + 26.402, + 52.238 + ], + "groundY": 6.3, + "roofY": 32.702, + "wallCount": 140, + "roofCount": 107 + }, + { + "id": "sion_1225", + "uuid": "{8E2F2D76-647B-46DE-9205-96E03F74B396}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -381.668, + 8.764, + 640.31 + ], + "size": [ + 17.492, + 17.812, + 15.899 + ], + "groundY": -0.142, + "roofY": 17.67, + "wallCount": 41, + "roofCount": 28 + }, + { + "id": "sion_1226", + "uuid": "{D3BDF4E5-0D11-49CE-A227-47B581CB2715}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -55.506, + 52.115, + -470.717 + ], + "size": [ + 17.168, + 10.499, + 22.632 + ], + "groundY": 46.866, + "roofY": 57.365, + "wallCount": 37, + "roofCount": 26 + }, + { + "id": "sion_1227", + "uuid": "{76B5E332-4950-4EE7-9518-80EF949D2E25}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 845.998, + 15.532, + 33.969 + ], + "size": [ + 36.692, + 24.325, + 31.086 + ], + "groundY": 3.37, + "roofY": 27.695, + "wallCount": 16, + "roofCount": 2 + }, + { + "id": "sion_1228", + "uuid": "{788EA279-4673-4E0F-B699-0A7464698B39}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 33.772, + 64.635, + -799.562 + ], + "size": [ + 11.949, + 9.767, + 11.427 + ], + "groundY": 59.752, + "roofY": 69.518, + "wallCount": 36, + "roofCount": 11 + }, + { + "id": "sion_1229", + "uuid": "{1D02DB09-2D9B-4838-AECB-953EF8944081}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -41.566, + 76.551, + -891.017 + ], + "size": [ + 60.484, + 19.5, + 34.674 + ], + "groundY": 66.801, + "roofY": 86.301, + "wallCount": 32, + "roofCount": 33 + }, + { + "id": "sion_1230", + "uuid": "{44A1ADD4-8C47-4373-B2EF-12E734ACD117}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -253.092, + 68.142, + -746.144 + ], + "size": [ + 21.832, + 16.307, + 17.168 + ], + "groundY": 59.989, + "roofY": 76.296, + "wallCount": 57, + "roofCount": 47 + }, + { + "id": "sion_1231", + "uuid": "{10FE9974-6C4A-4D97-912C-CCF44E140CD1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -172.814, + 29.443, + 136.171 + ], + "size": [ + 54.652, + 25.091, + 55.838 + ], + "groundY": 16.898, + "roofY": 41.989, + "wallCount": 40, + "roofCount": 56 + }, + { + "id": "sion_1232", + "uuid": "{A37E651F-E04B-4F69-BDDC-BC8AB9922BA6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1164.527, + 11.886, + 317.243 + ], + "size": [ + 11.75, + 11.186, + 10.378 + ], + "groundY": 6.293, + "roofY": 17.479, + "wallCount": 57, + "roofCount": 35 + }, + { + "id": "sion_1233", + "uuid": "{27873B08-6DE4-4140-83C9-2ABEC5546EE1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -33.914, + 49.027, + -393.098 + ], + "size": [ + 18.859, + 11.564, + 19.214 + ], + "groundY": 43.245, + "roofY": 54.809, + "wallCount": 22, + "roofCount": 13 + }, + { + "id": "sion_1234", + "uuid": "{FA264CA9-0CC5-4773-B2DA-4478B3EB3DAE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 239.062, + 201.289, + -1364.377 + ], + "size": [ + 13.711, + 11.87, + 13.805 + ], + "groundY": 195.354, + "roofY": 207.224, + "wallCount": 45, + "roofCount": 24 + }, + { + "id": "sion_1235", + "uuid": "{E371EF28-EC3B-451C-B909-606AD2DFED23}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -284.215, + 34.541, + -6.052 + ], + "size": [ + 26.031, + 24.529, + 30.256 + ], + "groundY": 22.277, + "roofY": 46.806, + "wallCount": 51, + "roofCount": 42 + }, + { + "id": "sion_1236", + "uuid": "{C98F6EC2-371B-4A4B-BA13-EF7A40F3D294}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 595.297, + 8.26, + 42.564 + ], + "size": [ + 9.078, + 7.526, + 6.106 + ], + "groundY": 4.497, + "roofY": 12.023, + "wallCount": 10, + "roofCount": 19 + }, + { + "id": "sion_1237", + "uuid": "{1B90A8FC-32AB-412B-9559-752920CB006E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 941.869, + 9.87, + 418.959 + ], + "size": [ + 20.231, + 11.899, + 18.506 + ], + "groundY": 3.921, + "roofY": 15.82, + "wallCount": 45, + "roofCount": 37 + }, + { + "id": "sion_1238", + "uuid": "{05E2BAF1-9E8B-4107-B425-43BD1EC4CFA7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -14.381, + 65.975, + -820.299 + ], + "size": [ + 10.606, + 5.966, + 10.229 + ], + "groundY": 62.992, + "roofY": 68.958, + "wallCount": 21, + "roofCount": 2 + }, + { + "id": "sion_1239", + "uuid": "{24A080E6-3419-4522-A474-1F00C34F8BBE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -190.213, + 62.252, + -713.517 + ], + "size": [ + 13.676, + 12.654, + 14.022 + ], + "groundY": 55.925, + "roofY": 68.579, + "wallCount": 67, + "roofCount": 35 + }, + { + "id": "sion_1240", + "uuid": "{BA4765E1-E6DD-4C62-8CE7-52F0DFCEE14E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 202.549, + 10.412, + 409.006 + ], + "size": [ + 46.223, + 11.908, + 32.062 + ], + "groundY": 4.458, + "roofY": 16.366, + "wallCount": 18, + "roofCount": 21 + }, + { + "id": "sion_1241", + "uuid": "{C9DEF82A-A7FE-4257-AD65-AD0DA9DD8C01}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 29.428, + 60.879, + -663.051 + ], + "size": [ + 35.277, + 17.476, + 30.316 + ], + "groundY": 52.141, + "roofY": 69.617, + "wallCount": 13, + "roofCount": 9 + }, + { + "id": "sion_1242", + "uuid": "{B8AE8F59-CB8E-4295-B244-A26FCF0C0DBA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 13.463, + 24.512, + -72.66 + ], + "size": [ + 12.285, + 6.542, + 10.412 + ], + "groundY": 21.241, + "roofY": 27.783, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1243", + "uuid": "{25431A80-ED48-4AA3-866B-F9F9223D4BAD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 2 + ], + "center": [ + 394.717, + 15.314, + -132.569 + ], + "size": [ + 32.059, + 22.536, + 50.882 + ], + "groundY": 4.046, + "roofY": 26.582, + "wallCount": 34, + "roofCount": 8 + }, + { + "id": "sion_1244", + "uuid": "{A932E067-295B-4E1B-9F72-08711B908F30}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -272.656, + 5.067, + 1034.787 + ], + "size": [ + 36.149, + 10.17, + 22.072 + ], + "groundY": -0.018, + "roofY": 10.152, + "wallCount": 12, + "roofCount": 2 + }, + { + "id": "sion_1245", + "uuid": "{73514E4C-6DEE-4EA6-A3D7-387C2FB6B83A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 318.924, + 77.561, + -968.543 + ], + "size": [ + 26.324, + 13.755, + 16.738 + ], + "groundY": 70.684, + "roofY": 84.438, + "wallCount": 50, + "roofCount": 60 + }, + { + "id": "sion_1246", + "uuid": "{E95F88C1-CE9A-405F-82AA-BF4F2F436220}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1147.168, + 14.929, + 421.063 + ], + "size": [ + 26.859, + 16.663, + 16.895 + ], + "groundY": 6.598, + "roofY": 23.26, + "wallCount": 98, + "roofCount": 16 + }, + { + "id": "sion_1247", + "uuid": "{86C7382D-1415-4F37-B914-80F946671192}", + "name": "", + "class": "Sakrales Gebaeude", + "archStyle": "fortress", + "tile": [ + 2, + 2 + ], + "center": [ + -273.562, + 57.308, + -243.34 + ], + "size": [ + 70.102, + 48.779, + 50.594 + ], + "groundY": 32.919, + "roofY": 81.698, + "wallCount": 164, + "roofCount": 114 + }, + { + "id": "sion_1248", + "uuid": "{F536E131-8278-4D97-840C-E254DBB7C8CC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1148.824, + 14.582, + 381.301 + ], + "size": [ + 26.859, + 16.692, + 16.9 + ], + "groundY": 6.236, + "roofY": 22.928, + "wallCount": 100, + "roofCount": 12 + }, + { + "id": "sion_1249", + "uuid": "{9185354C-42E0-4BEE-BF68-A180BBBD441E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -70.525, + 68.486, + -762.446 + ], + "size": [ + 13.27, + 15.421, + 10.616 + ], + "groundY": 60.775, + "roofY": 76.196, + "wallCount": 37, + "roofCount": 46 + }, + { + "id": "sion_1250", + "uuid": "{97710136-F35E-4E6E-A11C-51DAF8C71EA5}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 313.9, + 170.89, + -508.518 + ], + "size": [ + 85.746, + 36.924, + 48.94 + ], + "groundY": 152.428, + "roofY": 189.352, + "wallCount": 498, + "roofCount": 179 + }, + { + "id": "sion_1251", + "uuid": "{44E9C0CE-2970-4265-A887-8831523AAA64}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 968.277, + 7.954, + -317.133 + ], + "size": [ + 42.078, + 10.014, + 39.32 + ], + "groundY": 2.947, + "roofY": 12.961, + "wallCount": 32, + "roofCount": 28 + }, + { + "id": "sion_1252", + "uuid": "{666ED04A-A9D7-40B1-8765-5C917E91EEC8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 2 + ], + "center": [ + 1319.129, + 11.258, + -43.349 + ], + "size": [ + 11.68, + 6.828, + 11.746 + ], + "groundY": 7.844, + "roofY": 14.672, + "wallCount": 26, + "roofCount": 11 + }, + { + "id": "sion_1253", + "uuid": "{D3D71739-437A-4446-8209-E2E4885732E1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1200.77, + 13.714, + 104.51 + ], + "size": [ + 35.727, + 15.604, + 38.628 + ], + "groundY": 5.912, + "roofY": 21.516, + "wallCount": 27, + "roofCount": 43 + }, + { + "id": "sion_1254", + "uuid": "{2E34EFB6-468A-4214-85A5-C34EFE825B33}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 633.461, + 12.81, + 466.188 + ], + "size": [ + 45.391, + 21.114, + 40.004 + ], + "groundY": 2.253, + "roofY": 23.367, + "wallCount": 40, + "roofCount": 12 + }, + { + "id": "sion_1255", + "uuid": "{99E1CAA5-1B02-4913-9307-3E9D73E4A668}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -206.354, + 40.701, + -151.458 + ], + "size": [ + 59.137, + 25.359, + 65.623 + ], + "groundY": 28.021, + "roofY": 53.38, + "wallCount": 248, + "roofCount": 206 + }, + { + "id": "sion_1256", + "uuid": "{13F65D35-E5DC-4D88-AC3A-7B1FB400EFC6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 920.072, + 15.31, + 85.978 + ], + "size": [ + 30.441, + 25.17, + 27.847 + ], + "groundY": 2.725, + "roofY": 27.895, + "wallCount": 111, + "roofCount": 16 + }, + { + "id": "sion_1257", + "uuid": "{C7B15074-9261-48F5-8E57-2A61C32B550A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 112.527, + 27.566, + 96.475 + ], + "size": [ + 128.25, + 29.133, + 102.138 + ], + "groundY": 12.999, + "roofY": 42.132, + "wallCount": 219, + "roofCount": 153 + }, + { + "id": "sion_1258", + "uuid": "{AEF5814C-6816-4C3D-A099-6EB396FEFD44}", + "name": "Gu\u00e9rite Br\u00fblefer", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 752.686, + 167.836, + -1237.505 + ], + "size": [ + 10.754, + 10.375, + 10.678 + ], + "groundY": 162.649, + "roofY": 173.024, + "wallCount": 50, + "roofCount": 12 + }, + { + "id": "sion_1259", + "uuid": "{91835479-BBC8-449A-91AA-1B8671C06905}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1511.65, + 17.211, + 266.336 + ], + "size": [ + 46.488, + 18.907, + 18.704 + ], + "groundY": 7.758, + "roofY": 26.665, + "wallCount": 97, + "roofCount": 39 + }, + { + "id": "sion_1260", + "uuid": "{66358F62-F532-41EB-A109-9145CC23AFB4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 831.771, + 9.481, + 965.449 + ], + "size": [ + 16.137, + 9.254, + 17.622 + ], + "groundY": 4.854, + "roofY": 14.108, + "wallCount": 34, + "roofCount": 23 + }, + { + "id": "sion_1261", + "uuid": "{D1BD4E39-B2B0-401D-986B-904A05A0F2AE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1287.557, + 11.536, + 411.074 + ], + "size": [ + 48.738, + 9.04, + 73.726 + ], + "groundY": 7.016, + "roofY": 16.056, + "wallCount": 16, + "roofCount": 6 + }, + { + "id": "sion_1262", + "uuid": "{164B7701-8A94-424D-9C53-83D0B69726A7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -216.869, + 53.505, + -525.891 + ], + "size": [ + 11.934, + 11.386, + 14.378 + ], + "groundY": 47.812, + "roofY": 59.198, + "wallCount": 28, + "roofCount": 8 + }, + { + "id": "sion_1263", + "uuid": "{C5619C87-204C-4DC9-A172-52B9DBA7F5A3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 433.568, + 16.844, + 299.057 + ], + "size": [ + 69.738, + 20.806, + 49.933 + ], + "groundY": 6.441, + "roofY": 27.247, + "wallCount": 66, + "roofCount": 48 + }, + { + "id": "sion_1264", + "uuid": "{08A8547D-5233-4A89-8CB1-C2FE97D8ADBB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 855.539, + 6.554, + -321.524 + ], + "size": [ + 9.047, + 7.016, + 8.858 + ], + "groundY": 3.046, + "roofY": 10.062, + "wallCount": 45, + "roofCount": 11 + }, + { + "id": "sion_1265", + "uuid": "{027AA308-1E14-4005-80A5-EC02063892BD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 2 + ], + "center": [ + 1468.728, + 14.337, + -124.653 + ], + "size": [ + 20.707, + 13.931, + 26.941 + ], + "groundY": 7.371, + "roofY": 21.302, + "wallCount": 49, + "roofCount": 8 + }, + { + "id": "sion_1266", + "uuid": "{37E86DFC-7EAE-4EDC-ADF4-5E4C7EFE3FE7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 314.037, + 6.164, + 821.265 + ], + "size": [ + 32.082, + 8.052, + 31.038 + ], + "groundY": 2.138, + "roofY": 10.19, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1267", + "uuid": "{71AB4C2A-F2FE-4639-B60A-215E7B92DE56}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -38.707, + 61.235, + -609.914 + ], + "size": [ + 35.211, + 22.6, + 31.883 + ], + "groundY": 49.935, + "roofY": 72.535, + "wallCount": 122, + "roofCount": 45 + }, + { + "id": "sion_1268", + "uuid": "{7C53E56F-AEB4-47F5-9E23-EE6B542735DF}", + "name": "", + "class": "Sakrales Gebaeude", + "archStyle": "fortress", + "tile": [ + 2, + 2 + ], + "center": [ + -299.715, + 44.817, + -185.031 + ], + "size": [ + 42.18, + 26.464, + 27.874 + ], + "groundY": 31.585, + "roofY": 58.049, + "wallCount": 127, + "roofCount": 113 + }, + { + "id": "sion_1269", + "uuid": "{999B05A7-1BFA-4EF1-8580-82897DDC56E3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -123.014, + 70.315, + -800.35 + ], + "size": [ + 13.457, + 13.607, + 11.97 + ], + "groundY": 63.511, + "roofY": 77.118, + "wallCount": 36, + "roofCount": 55 + }, + { + "id": "sion_1270", + "uuid": "{95B59AC2-2B75-418D-94D9-34614109F425}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 293.947, + 11.812, + 4.274 + ], + "size": [ + 9.856, + 6.732, + 22.821 + ], + "groundY": 8.446, + "roofY": 15.178, + "wallCount": 20, + "roofCount": 2 + }, + { + "id": "sion_1271", + "uuid": "{647B07D2-5E10-40D7-9217-BCAEA1F8ACAB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -82.342, + 68.979, + -795.696 + ], + "size": [ + 11.293, + 12.247, + 13.97 + ], + "groundY": 62.856, + "roofY": 75.103, + "wallCount": 43, + "roofCount": 29 + }, + { + "id": "sion_1272", + "uuid": "{E405E2EA-D51A-4B4F-82E3-F017D6F677ED}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 735.824, + 11.639, + 529.793 + ], + "size": [ + 31.961, + 15.951, + 30.672 + ], + "groundY": 3.664, + "roofY": 19.615, + "wallCount": 39, + "roofCount": 12 + }, + { + "id": "sion_1273", + "uuid": "{FAE01D2C-A999-4C5A-8300-EE2A010CC62E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 0 + ], + "center": [ + 1300.105, + 11.643, + -1053.428 + ], + "size": [ + 47.234, + 12.962, + 54.27 + ], + "groundY": 5.162, + "roofY": 18.124, + "wallCount": 30, + "roofCount": 20 + }, + { + "id": "sion_1274", + "uuid": "{EDAC417F-2017-414F-8DB6-82687DB6C9F5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 917.176, + 9.24, + 407.505 + ], + "size": [ + 13.203, + 10.773, + 9.79 + ], + "groundY": 3.854, + "roofY": 14.627, + "wallCount": 43, + "roofCount": 15 + }, + { + "id": "sion_1275", + "uuid": "{E341C36D-8C62-4B70-9EF4-486B3A7F0265}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 194.154, + 56.369, + -696.826 + ], + "size": [ + 15.051, + 6.002, + 10.572 + ], + "groundY": 53.368, + "roofY": 59.37, + "wallCount": 12, + "roofCount": 2 + }, + { + "id": "sion_1276", + "uuid": "{C920BA11-660C-424A-8B40-C79CFCD32E3A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 173.553, + 180.862, + -1425.126 + ], + "size": [ + 16.066, + 8.698, + 19.732 + ], + "groundY": 176.513, + "roofY": 185.211, + "wallCount": 33, + "roofCount": 23 + }, + { + "id": "sion_1277", + "uuid": "{3A3C5659-29AA-4538-8FE4-D2428D17E250}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 201.969, + 8.736, + 429.652 + ], + "size": [ + 12.484, + 9.098, + 11.788 + ], + "groundY": 4.187, + "roofY": 13.285, + "wallCount": 30, + "roofCount": 28 + }, + { + "id": "sion_1278", + "uuid": "{711B940A-E816-480E-83D2-FA47BF08BDF9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 877.225, + 9.695, + 554.665 + ], + "size": [ + 43.941, + 10.588, + 63.812 + ], + "groundY": 4.401, + "roofY": 14.989, + "wallCount": 30, + "roofCount": 40 + }, + { + "id": "sion_1279", + "uuid": "{0605CCB1-71C3-428D-9FAC-334E676EF223}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 40.043, + 97.05, + -1064.675 + ], + "size": [ + 30.977, + 7.102, + 10.198 + ], + "groundY": 93.499, + "roofY": 100.601, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1280", + "uuid": "{D7E33C42-56A2-40FE-9BDD-A6B1399901F4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -162.691, + 85.676, + -992.591 + ], + "size": [ + 55.094, + 23.269, + 63.021 + ], + "groundY": 74.042, + "roofY": 97.311, + "wallCount": 122, + "roofCount": 130 + }, + { + "id": "sion_1281", + "uuid": "{FBAB9A12-B852-4D50-B280-BA5C61395BB9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -18.967, + 7.824, + 852.696 + ], + "size": [ + 85.449, + 14.808, + 77.772 + ], + "groundY": 0.42, + "roofY": 15.228, + "wallCount": 14, + "roofCount": 44 + }, + { + "id": "sion_1282", + "uuid": "{153F32B5-F660-43EB-AE75-513C4D7DB135}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 263.678, + 20.782, + -2.97 + ], + "size": [ + 14.269, + 21.341, + 38.474 + ], + "groundY": 10.111, + "roofY": 31.452, + "wallCount": 10, + "roofCount": 20 + }, + { + "id": "sion_1283", + "uuid": "{5E4291DD-CFE2-480E-864F-000B44452C2A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -304.207, + 65.715, + -644.013 + ], + "size": [ + 57.156, + 26.693, + 54.178 + ], + "groundY": 52.369, + "roofY": 79.062, + "wallCount": 398, + "roofCount": 187 + }, + { + "id": "sion_1284", + "uuid": "{003CB6FD-2DC1-4891-94D8-9E98D570889E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1058.193, + 9.776, + 397.035 + ], + "size": [ + 11.309, + 10.266, + 9.128 + ], + "groundY": 4.643, + "roofY": 14.909, + "wallCount": 47, + "roofCount": 29 + }, + { + "id": "sion_1285", + "uuid": "{A7A88A2E-1DCB-4806-9BD2-D5A68301085D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -93.098, + 36.851, + -125.482 + ], + "size": [ + 29.68, + 21.604, + 26.042 + ], + "groundY": 26.049, + "roofY": 47.653, + "wallCount": 92, + "roofCount": 28 + }, + { + "id": "sion_1286", + "uuid": "{515D26EF-722C-47F0-99FB-025CA8A1FF42}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -272.035, + 50.993, + -374.022 + ], + "size": [ + 18.539, + 22.028, + 15.063 + ], + "groundY": 39.979, + "roofY": 62.007, + "wallCount": 60, + "roofCount": 40 + }, + { + "id": "sion_1287", + "uuid": "{89A6CE3E-5AAF-4B08-9885-721D9770415C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -81.639, + 97.751, + -1208.95 + ], + "size": [ + 19.285, + 14.755, + 20.914 + ], + "groundY": 90.373, + "roofY": 105.128, + "wallCount": 38, + "roofCount": 15 + }, + { + "id": "sion_1288", + "uuid": "{952CF754-A8B1-4378-A409-83559F494F87}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 1018.779, + 12.389, + 358.954 + ], + "size": [ + 23.082, + 16.109, + 17.004 + ], + "groundY": 4.335, + "roofY": 20.444, + "wallCount": 88, + "roofCount": 23 + }, + { + "id": "sion_1289", + "uuid": "{7125F4AD-ED74-478D-978D-9281E2C36554}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 278.781, + 21.227, + 107.665 + ], + "size": [ + 49.0, + 21.969, + 45.479 + ], + "groundY": 10.243, + "roofY": 32.212, + "wallCount": 14, + "roofCount": 12 + }, + { + "id": "sion_1290", + "uuid": "{95771A8B-D7BF-49E1-94B3-AC0656E38653}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1218.072, + 12.162, + 291.281 + ], + "size": [ + 30.285, + 10.807, + 11.618 + ], + "groundY": 6.759, + "roofY": 17.566, + "wallCount": 25, + "roofCount": 22 + }, + { + "id": "sion_1291", + "uuid": "{72A8C5CB-33A7-4619-ADF6-24B466909D68}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -315.551, + 12.794, + 708.176 + ], + "size": [ + 57.406, + 27.168, + 17.326 + ], + "groundY": -0.79, + "roofY": 26.378, + "wallCount": 86, + "roofCount": 22 + }, + { + "id": "sion_1292", + "uuid": "{8E58DC17-92D2-4CA6-9484-EAC1AC7D77CB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 155.645, + 10.381, + 654.182 + ], + "size": [ + 20.547, + 17.819, + 19.878 + ], + "groundY": 1.471, + "roofY": 19.29, + "wallCount": 29, + "roofCount": 25 + }, + { + "id": "sion_1293", + "uuid": "{A1BD8F1B-DA1D-47D9-9A7D-1146CDF12533}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 116.016, + 19.972, + 285.3 + ], + "size": [ + 51.195, + 25.463, + 35.598 + ], + "groundY": 7.241, + "roofY": 32.704, + "wallCount": 98, + "roofCount": 25 + }, + { + "id": "sion_1294", + "uuid": "{1971CC05-D3DE-4FAE-94FD-271E60F44089}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 90.148, + 7.296, + 589.382 + ], + "size": [ + 45.984, + 10.807, + 46.279 + ], + "groundY": 1.892, + "roofY": 12.699, + "wallCount": 8, + "roofCount": 5 + }, + { + "id": "sion_1295", + "uuid": "{47CBBFDA-3130-439A-BEFE-983DF24D4FA2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 237.846, + 76.943, + -955.949 + ], + "size": [ + 56.551, + 18.704, + 26.7 + ], + "groundY": 67.591, + "roofY": 86.295, + "wallCount": 29, + "roofCount": 19 + }, + { + "id": "sion_1296", + "uuid": "{B5FB8EAC-55DA-4674-9DA2-8D0B91491178}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 424.881, + 8.446, + 446.858 + ], + "size": [ + 17.887, + 10.608, + 17.284 + ], + "groundY": 3.142, + "roofY": 13.75, + "wallCount": 16, + "roofCount": 14 + }, + { + "id": "sion_1297", + "uuid": "{4503694E-FB0A-4DB2-A01D-F65360A4BA5C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 111.344, + 25.316, + -44.213 + ], + "size": [ + 24.469, + 16.684, + 18.764 + ], + "groundY": 16.974, + "roofY": 33.658, + "wallCount": 23, + "roofCount": 10 + }, + { + "id": "sion_1298", + "uuid": "{02B3CAE2-9339-4A8A-9762-345B9A6241E9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -361.402, + 54.829, + -518.294 + ], + "size": [ + 26.766, + 19.635, + 20.538 + ], + "groundY": 45.012, + "roofY": 64.647, + "wallCount": 17, + "roofCount": 20 + }, + { + "id": "sion_1299", + "uuid": "{FFC6A1FC-F46B-409C-8EC8-F6C2FF94BCFB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1242.754, + 12.466, + 268.656 + ], + "size": [ + 30.281, + 10.551, + 11.62 + ], + "groundY": 7.191, + "roofY": 17.742, + "wallCount": 25, + "roofCount": 24 + }, + { + "id": "sion_1300", + "uuid": "{8BE68F4B-2A71-4D0E-8C8C-45A43643B61B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 23.527, + 69.932, + -321.695 + ], + "size": [ + 21.445, + 21.787, + 20.11 + ], + "groundY": 59.038, + "roofY": 80.825, + "wallCount": 24, + "roofCount": 12 + }, + { + "id": "sion_1301", + "uuid": "{0E9E24D5-F43F-4B41-B13B-D53C5271D2D7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1165.529, + 12.064, + 341.494 + ], + "size": [ + 15.059, + 10.438, + 12.116 + ], + "groundY": 6.845, + "roofY": 17.283, + "wallCount": 27, + "roofCount": 32 + }, + { + "id": "sion_1302", + "uuid": "{DA536C7A-2F98-41B4-93BA-F0DCBABBE896}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 197.035, + 64.463, + -842.772 + ], + "size": [ + 16.078, + 12.974, + 15.884 + ], + "groundY": 57.976, + "roofY": 70.95, + "wallCount": 43, + "roofCount": 24 + }, + { + "id": "sion_1303", + "uuid": "{84B357B3-AFB2-4B74-94AC-59698DFE1F5E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -142.309, + 69.42, + -801.276 + ], + "size": [ + 12.773, + 11.456, + 10.187 + ], + "groundY": 63.692, + "roofY": 75.148, + "wallCount": 57, + "roofCount": 27 + }, + { + "id": "sion_1304", + "uuid": "{9399060B-06A3-47FA-9B7D-EF04A4698CBE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 457.557, + 219.599, + -1432.193 + ], + "size": [ + 13.082, + 10.9, + 13.5 + ], + "groundY": 214.149, + "roofY": 225.049, + "wallCount": 22, + "roofCount": 32 + }, + { + "id": "sion_1305", + "uuid": "{033A9579-18AF-405B-97D3-2504AF7C024B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 30.965, + 62.192, + -755.871 + ], + "size": [ + 12.781, + 10.635, + 12.508 + ], + "groundY": 56.874, + "roofY": 67.509, + "wallCount": 48, + "roofCount": 7 + }, + { + "id": "sion_1306", + "uuid": "{BD975460-C515-4594-82EF-7B74DE48C88B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -370.955, + 10.313, + 689.94 + ], + "size": [ + 15.566, + 22.987, + 27.414 + ], + "groundY": -1.18, + "roofY": 21.807, + "wallCount": 43, + "roofCount": 4 + }, + { + "id": "sion_1307", + "uuid": "{84344A67-D7FE-4DC1-B812-2554C35F5B01}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -346.51, + 70.783, + -864.831 + ], + "size": [ + 9.348, + 5.726, + 10.438 + ], + "groundY": 67.92, + "roofY": 73.646, + "wallCount": 24, + "roofCount": 17 + }, + { + "id": "sion_1308", + "uuid": "{DEE051AF-1E40-4572-ADB2-F824BC0E5157}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 49.881, + 142.549, + -1190.576 + ], + "size": [ + 4.551, + 5.261, + 6.326 + ], + "groundY": 139.918, + "roofY": 145.179, + "wallCount": 31, + "roofCount": 6 + }, + { + "id": "sion_1309", + "uuid": "{AD36DF39-1227-46FD-A324-E2DEFB2568BB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 613.398, + 13.037, + 22.092 + ], + "size": [ + 16.094, + 17.802, + 29.996 + ], + "groundY": 4.136, + "roofY": 21.938, + "wallCount": 10, + "roofCount": 40 + }, + { + "id": "sion_1310", + "uuid": "{4BD6C061-F429-4FF6-92F8-B992EB30F3B1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 76.375, + 7.415, + 548.484 + ], + "size": [ + 52.516, + 10.276, + 28.694 + ], + "groundY": 2.277, + "roofY": 12.553, + "wallCount": 41, + "roofCount": 14 + }, + { + "id": "sion_1311", + "uuid": "{1BF3C8B0-CD01-421F-8BD7-D911AD3457C8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 169.211, + 22.232, + 7.735 + ], + "size": [ + 14.781, + 15.674, + 13.403 + ], + "groundY": 14.395, + "roofY": 30.069, + "wallCount": 17, + "roofCount": 27 + }, + { + "id": "sion_1312", + "uuid": "{C4607174-59C3-4C48-9144-C7FF12661601}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 238.828, + 21.002, + 121.617 + ], + "size": [ + 19.5, + 17.855, + 19.254 + ], + "groundY": 12.075, + "roofY": 29.93, + "wallCount": 23, + "roofCount": 9 + }, + { + "id": "sion_1313", + "uuid": "{1957CFFC-7073-4A75-BDEF-C9328F1F7F99}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 137.812, + 6.437, + 608.062 + ], + "size": [ + 17.242, + 12.174, + 16.892 + ], + "groundY": 0.35, + "roofY": 12.524, + "wallCount": 38, + "roofCount": 18 + }, + { + "id": "sion_1314", + "uuid": "{5AB77217-7C9F-4C06-A100-7320FE24D4F6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 958.93, + 11.51, + 377.362 + ], + "size": [ + 19.93, + 17.204, + 35.13 + ], + "groundY": 2.908, + "roofY": 20.112, + "wallCount": 130, + "roofCount": 28 + }, + { + "id": "sion_1315", + "uuid": "{686AEF0F-C187-42BD-ACEE-257ED7E1E88C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -10.422, + 71.033, + -244.433 + ], + "size": [ + 16.438, + 15.59, + 18.952 + ], + "groundY": 63.238, + "roofY": 78.828, + "wallCount": 21, + "roofCount": 13 + }, + { + "id": "sion_1316", + "uuid": "{53984E0D-F1D1-4566-8624-EE1459AAA7CD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 177.031, + 64.686, + -834.816 + ], + "size": [ + 17.164, + 15.75, + 16.944 + ], + "groundY": 56.811, + "roofY": 72.561, + "wallCount": 45, + "roofCount": 25 + }, + { + "id": "sion_1317", + "uuid": "{3E30AEEE-21C0-45C2-9DE9-33F497F43D5C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 458.852, + 177.78, + -1259.786 + ], + "size": [ + 6.914, + 6.474, + 5.178 + ], + "groundY": 174.543, + "roofY": 181.017, + "wallCount": 34, + "roofCount": 9 + }, + { + "id": "sion_1318", + "uuid": "{275105F2-5E34-4CF9-840E-F167334F058B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -4.793, + 65.115, + -751.554 + ], + "size": [ + 23.047, + 13.15, + 18.15 + ], + "groundY": 58.54, + "roofY": 71.69, + "wallCount": 33, + "roofCount": 44 + }, + { + "id": "sion_1319", + "uuid": "{1D748D30-5147-4721-AC97-F0BCD4AA8A07}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 152.865, + 20.222, + 65.841 + ], + "size": [ + 18.941, + 10.266, + 18.076 + ], + "groundY": 15.089, + "roofY": 25.355, + "wallCount": 8, + "roofCount": 26 + }, + { + "id": "sion_1320", + "uuid": "{91C1DF80-2A43-4670-A20D-AE28D12D3BC9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 466.818, + 7.078, + 571.2 + ], + "size": [ + 49.254, + 10.769, + 57.322 + ], + "groundY": 1.694, + "roofY": 12.463, + "wallCount": 35, + "roofCount": 21 + }, + { + "id": "sion_1321", + "uuid": "{043F6B6E-8D43-479F-A27A-A6991FDAFC65}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 200.293, + 187.064, + -1447.923 + ], + "size": [ + 13.297, + 8.444, + 12.014 + ], + "groundY": 182.842, + "roofY": 191.286, + "wallCount": 37, + "roofCount": 12 + }, + { + "id": "sion_1322", + "uuid": "{7E5A54A0-2EF7-4E69-8D72-2F25F0C9AEED}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 291.945, + 71.13, + -624.266 + ], + "size": [ + 15.93, + 12.618, + 16.416 + ], + "groundY": 64.821, + "roofY": 77.439, + "wallCount": 45, + "roofCount": 21 + }, + { + "id": "sion_1323", + "uuid": "{F1F723A5-E572-4F9F-851A-D2A5A4E25B21}", + "name": "", + "class": "Lagertank", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 640.455, + 14.618, + 791.925 + ], + "size": [ + 19.535, + 24.995, + 19.534 + ], + "groundY": 2.121, + "roofY": 27.116, + "wallCount": 409, + "roofCount": 94 + }, + { + "id": "sion_1324", + "uuid": "{05B75BB3-742B-4836-9B33-9D216D94F3BA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 422.625, + 214.854, + -1431.715 + ], + "size": [ + 18.438, + 7.449, + 16.068 + ], + "groundY": 211.13, + "roofY": 218.579, + "wallCount": 34, + "roofCount": 26 + }, + { + "id": "sion_1325", + "uuid": "{3ECEE38F-F216-4C89-828D-5E6A78699ADA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 775.023, + 10.545, + 452.43 + ], + "size": [ + 16.219, + 15.052, + 17.147 + ], + "groundY": 3.019, + "roofY": 18.071, + "wallCount": 68, + "roofCount": 19 + }, + { + "id": "sion_1326", + "uuid": "{472281E2-2581-42F6-BC74-228E2EB783BC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 797.352, + 12.353, + -88.092 + ], + "size": [ + 70.891, + 18.957, + 52.64 + ], + "groundY": 2.875, + "roofY": 21.832, + "wallCount": 82, + "roofCount": 32 + }, + { + "id": "sion_1327", + "uuid": "{C10EE620-BC81-4BD3-A9B4-09E0711D0B68}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 305.004, + 7.279, + 495.851 + ], + "size": [ + 31.93, + 12.243, + 23.418 + ], + "groundY": 1.157, + "roofY": 13.4, + "wallCount": 27, + "roofCount": 4 + }, + { + "id": "sion_1328", + "uuid": "{89B8A8F1-EAE6-429A-8536-9C9FF901425F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 756.266, + 8.942, + 552.698 + ], + "size": [ + 19.602, + 9.362, + 22.204 + ], + "groundY": 4.261, + "roofY": 13.623, + "wallCount": 25, + "roofCount": 12 + }, + { + "id": "sion_1329", + "uuid": "{4D230BF4-FF05-471A-839D-5457533DBBDE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 111.852, + 10.061, + 995.933 + ], + "size": [ + 39.945, + 13.118, + 36.796 + ], + "groundY": 3.502, + "roofY": 16.62, + "wallCount": 37, + "roofCount": 14 + }, + { + "id": "sion_1330", + "uuid": "{25917771-87CF-4B00-BFDD-8109BB68ADFB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 798.195, + 16.23, + -424.733 + ], + "size": [ + 19.609, + 25.178, + 15.108 + ], + "groundY": 3.641, + "roofY": 28.819, + "wallCount": 101, + "roofCount": 16 + }, + { + "id": "sion_1331", + "uuid": "{08119BB1-A6FB-4D3E-B138-0942D3C70DB8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 947.342, + 13.927, + 457.551 + ], + "size": [ + 26.676, + 18.517, + 19.71 + ], + "groundY": 4.668, + "roofY": 23.185, + "wallCount": 41, + "roofCount": 30 + }, + { + "id": "sion_1332", + "uuid": "{15DD0831-790F-4347-A0A5-43D0602CF032}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -132.895, + 68.93, + -765.651 + ], + "size": [ + 14.453, + 14.477, + 11.813 + ], + "groundY": 61.692, + "roofY": 76.169, + "wallCount": 52, + "roofCount": 58 + }, + { + "id": "sion_1333", + "uuid": "{1706D08D-0543-4317-A3C6-F9D18E483F72}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 488.096, + 9.477, + 702.084 + ], + "size": [ + 35.559, + 13.085, + 48.305 + ], + "groundY": 2.935, + "roofY": 16.02, + "wallCount": 11, + "roofCount": 15 + }, + { + "id": "sion_1334", + "uuid": "{75A9B5AA-C29F-4E1D-BF13-78D8A615A7B0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 158.113, + 60.981, + -787.318 + ], + "size": [ + 15.75, + 11.616, + 14.948 + ], + "groundY": 55.173, + "roofY": 66.789, + "wallCount": 46, + "roofCount": 48 + }, + { + "id": "sion_1335", + "uuid": "{5F4199AB-2A51-41EB-8E07-9F058C1F4F44}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 215.283, + 23.733, + 160.7 + ], + "size": [ + 45.746, + 22.51, + 39.482 + ], + "groundY": 12.478, + "roofY": 34.988, + "wallCount": 22, + "roofCount": 36 + }, + { + "id": "sion_1336", + "uuid": "{F73EB63C-1BC5-46BA-8462-9AB19D10892D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 402.635, + 7.194, + 902.28 + ], + "size": [ + 43.59, + 9.727, + 74.256 + ], + "groundY": 2.33, + "roofY": 12.057, + "wallCount": 14, + "roofCount": 58 + }, + { + "id": "sion_1337", + "uuid": "{9CC88C6C-11C0-4E69-A91C-C17E12840938}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 647.396, + 15.784, + 158.88 + ], + "size": [ + 24.613, + 27.018, + 16.168 + ], + "groundY": 2.275, + "roofY": 29.293, + "wallCount": 177, + "roofCount": 20 + }, + { + "id": "sion_1338", + "uuid": "{82444C57-2FE9-412D-8749-C7AEA4115143}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -234.271, + 74.614, + -901.167 + ], + "size": [ + 15.715, + 14.263, + 22.49 + ], + "groundY": 67.482, + "roofY": 81.745, + "wallCount": 29, + "roofCount": 31 + }, + { + "id": "sion_1339", + "uuid": "{10084B26-A99B-4560-93D1-2403B7562B1C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 306.979, + 17.964, + 132.316 + ], + "size": [ + 23.129, + 16.087, + 22.19 + ], + "groundY": 9.921, + "roofY": 26.008, + "wallCount": 19, + "roofCount": 12 + }, + { + "id": "sion_1340", + "uuid": "{D3198120-D7D2-4A2F-8602-AD1932D93DA5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -18.768, + 13.059, + 292.63 + ], + "size": [ + 17.027, + 7.007, + 24.124 + ], + "groundY": 9.556, + "roofY": 16.562, + "wallCount": 10, + "roofCount": 4 + }, + { + "id": "sion_1341", + "uuid": "{5EDF66AE-2C58-4451-A245-8BFEA6E4A929}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -45.869, + 31.328, + -117.071 + ], + "size": [ + 12.051, + 15.736, + 19.481 + ], + "groundY": 23.46, + "roofY": 39.196, + "wallCount": 72, + "roofCount": 25 + }, + { + "id": "sion_1342", + "uuid": "{DC6AF291-537C-4888-87F2-9C4301A15FE8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -82.205, + 36.864, + -134.94 + ], + "size": [ + 20.441, + 13.765, + 16.341 + ], + "groundY": 29.981, + "roofY": 43.746, + "wallCount": 14, + "roofCount": 7 + }, + { + "id": "sion_1343", + "uuid": "{7AE3FE74-6F49-4C6B-B9D3-93394D2E1653}", + "name": "", + "class": "Sakrales Gebaeude", + "archStyle": "fortress", + "tile": [ + 4, + 3 + ], + "center": [ + 876.293, + 10.688, + 225.858 + ], + "size": [ + 25.297, + 13.33, + 24.192 + ], + "groundY": 4.023, + "roofY": 17.353, + "wallCount": 185, + "roofCount": 94 + }, + { + "id": "sion_1344", + "uuid": "{D0607AB0-E0E7-462A-AAA7-EFE3C4DB2498}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 414.479, + 8.043, + 469.391 + ], + "size": [ + 22.715, + 11.804, + 30.252 + ], + "groundY": 2.141, + "roofY": 13.945, + "wallCount": 37, + "roofCount": 24 + }, + { + "id": "sion_1345", + "uuid": "{B5F3F5B9-C723-4750-9E78-5BBE97820453}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 324.236, + 210.849, + -1412.35 + ], + "size": [ + 18.41, + 10.62, + 18.416 + ], + "groundY": 205.539, + "roofY": 216.159, + "wallCount": 31, + "roofCount": 8 + }, + { + "id": "sion_1346", + "uuid": "{5DC4DED6-800A-46FD-8433-3A993B20E013}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 434.668, + 61.617, + -688.779 + ], + "size": [ + 58.367, + 10.431, + 26.526 + ], + "groundY": 56.401, + "roofY": 66.832, + "wallCount": 51, + "roofCount": 20 + }, + { + "id": "sion_1347", + "uuid": "{19A8916D-0C1D-40DA-9087-97ACC2854F9A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 2 + ], + "center": [ + 1290.719, + 13.963, + -67.074 + ], + "size": [ + 54.969, + 13.126, + 47.756 + ], + "groundY": 7.4, + "roofY": 20.526, + "wallCount": 63, + "roofCount": 31 + }, + { + "id": "sion_1348", + "uuid": "{C4BF0F34-71FC-4BEF-989D-555F6F2DEFB7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -227.066, + 56.209, + -514.969 + ], + "size": [ + 13.984, + 17.046, + 17.596 + ], + "groundY": 47.686, + "roofY": 64.732, + "wallCount": 64, + "roofCount": 49 + }, + { + "id": "sion_1349", + "uuid": "{0B9DBB61-B6D9-42A8-9E9E-B3C95E51471A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 597.078, + 236.865, + -1369.78 + ], + "size": [ + 5.602, + 7.018, + 4.774 + ], + "groundY": 233.356, + "roofY": 240.374, + "wallCount": 25, + "roofCount": 3 + }, + { + "id": "sion_1350", + "uuid": "{02CD52D4-3C5D-4107-AE0B-22FF28A76986}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 862.803, + 11.35, + 1020.578 + ], + "size": [ + 42.629, + 11.944, + 30.922 + ], + "groundY": 5.378, + "roofY": 17.322, + "wallCount": 22, + "roofCount": 4 + }, + { + "id": "sion_1351", + "uuid": "{97935E98-AC18-4C70-8728-B0026DB2393F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 86.105, + 53.893, + -681.967 + ], + "size": [ + 41.883, + 5.532, + 32.16 + ], + "groundY": 51.127, + "roofY": 56.659, + "wallCount": 12, + "roofCount": 9 + }, + { + "id": "sion_1352", + "uuid": "{CA9F52B2-7C1A-4237-B393-F7C8EC48A437}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 9.086, + 59.055, + -294.717 + ], + "size": [ + 7.633, + 5.263, + 6.977 + ], + "groundY": 56.424, + "roofY": 61.687, + "wallCount": 24, + "roofCount": 12 + }, + { + "id": "sion_1353", + "uuid": "{B6D8CA09-EC34-48B9-8D36-BE5B0E5E9D9B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 475.486, + 15.505, + 258.258 + ], + "size": [ + 25.793, + 19.942, + 66.474 + ], + "groundY": 5.534, + "roofY": 25.476, + "wallCount": 63, + "roofCount": 19 + }, + { + "id": "sion_1354", + "uuid": "{52BBB18E-3252-417B-ADF1-E17A91E345F4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 944.945, + 13.148, + 490.594 + ], + "size": [ + 23.586, + 17.551, + 15.004 + ], + "groundY": 4.373, + "roofY": 21.924, + "wallCount": 37, + "roofCount": 71 + }, + { + "id": "sion_1355", + "uuid": "{8C6BD0DB-C57E-4E7B-AC82-169780CA309C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -133.611, + 44.995, + -159.478 + ], + "size": [ + 61.066, + 33.65, + 36.216 + ], + "groundY": 28.17, + "roofY": 61.82, + "wallCount": 250, + "roofCount": 160 + }, + { + "id": "sion_1356", + "uuid": "{815C6A9D-2E8B-4527-A031-6E8A1BC7EF61}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -317.75, + 51.058, + -412.242 + ], + "size": [ + 39.727, + 20.738, + 35.196 + ], + "groundY": 40.689, + "roofY": 61.427, + "wallCount": 25, + "roofCount": 44 + }, + { + "id": "sion_1357", + "uuid": "{62304780-C913-4AEB-AC43-54CD4374CDFB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -391.283, + 51.311, + -418.074 + ], + "size": [ + 29.871, + 26.059, + 40.856 + ], + "groundY": 38.282, + "roofY": 64.341, + "wallCount": 66, + "roofCount": 22 + }, + { + "id": "sion_1358", + "uuid": "{AA10BB08-60DC-43DA-BE78-39AE70FFCEF9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 201.768, + 6.475, + 902.771 + ], + "size": [ + 25.418, + 7.36, + 25.392 + ], + "groundY": 2.795, + "roofY": 10.155, + "wallCount": 18, + "roofCount": 12 + }, + { + "id": "sion_1359", + "uuid": "{8726A433-AB61-434D-8246-83C66A7A297D}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 3, + 1 + ], + "center": [ + 511.092, + 160.077, + -561.525 + ], + "size": [ + 18.762, + 6.434, + 7.202 + ], + "groundY": 156.86, + "roofY": 163.294, + "wallCount": 90, + "roofCount": 35 + }, + { + "id": "sion_1360", + "uuid": "{A214FBDC-AD8D-4C77-AE62-B2F45E45EC82}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -266.703, + 18.566, + 373.228 + ], + "size": [ + 37.734, + 26.526, + 55.407 + ], + "groundY": 5.303, + "roofY": 31.829, + "wallCount": 88, + "roofCount": 60 + }, + { + "id": "sion_1361", + "uuid": "{92BF4AA6-DCA8-4637-B33A-0B234ADD5B04}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -247.463, + 42.642, + -293.423 + ], + "size": [ + 28.691, + 14.624, + 19.147 + ], + "groundY": 35.33, + "roofY": 49.954, + "wallCount": 80, + "roofCount": 45 + }, + { + "id": "sion_1362", + "uuid": "{1B76F221-3C57-4696-AD40-AD53C51753D1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -325.715, + 47.36, + -448.581 + ], + "size": [ + 33.414, + 10.317, + 32.792 + ], + "groundY": 42.202, + "roofY": 52.519, + "wallCount": 40, + "roofCount": 38 + }, + { + "id": "sion_1363", + "uuid": "{615E15CD-F965-4D1D-86C8-C57B671AE995}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 187.471, + 25.292, + 141.279 + ], + "size": [ + 46.871, + 23.888, + 38.244 + ], + "groundY": 13.348, + "roofY": 37.236, + "wallCount": 72, + "roofCount": 16 + }, + { + "id": "sion_1364", + "uuid": "{9ECD326E-04E6-4DCB-AA0B-B1F93F3FE011}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 365.561, + 17.184, + 203.933 + ], + "size": [ + 31.629, + 22.297, + 30.786 + ], + "groundY": 6.036, + "roofY": 28.333, + "wallCount": 59, + "roofCount": 21 + }, + { + "id": "sion_1365", + "uuid": "{31B6313D-CF84-4D36-868E-FA292B71308A}", + "name": "Basilique de Val\u00e8re", + "class": "Sakrales Gebaeude", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 113.117, + 127.612, + -210.714 + ], + "size": [ + 148.617, + 69.03, + 115.92 + ], + "groundY": 93.097, + "roofY": 162.127, + "wallCount": 1339, + "roofCount": 501 + }, + { + "id": "sion_1366", + "uuid": "{97ECC9D6-9EA1-4B2F-99CF-304E04155367}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -90.424, + 47.571, + -158.134 + ], + "size": [ + 22.285, + 18.24, + 19.792 + ], + "groundY": 38.451, + "roofY": 56.691, + "wallCount": 79, + "roofCount": 36 + }, + { + "id": "sion_1367", + "uuid": "{E2482005-81AB-4445-889A-6C33FB36C0A0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1407.141, + 10.854, + 379.861 + ], + "size": [ + 7.414, + 6.334, + 12.408 + ], + "groundY": 7.687, + "roofY": 14.021, + "wallCount": 16, + "roofCount": 2 + }, + { + "id": "sion_1368", + "uuid": "{7ACE96ED-332E-4AA3-A7E0-9858E629050F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 1 + ], + "center": [ + 698.84, + 45.208, + -867.183 + ], + "size": [ + 7.469, + 11.572, + 10.817 + ], + "groundY": 39.422, + "roofY": 50.994, + "wallCount": 66, + "roofCount": 15 + }, + { + "id": "sion_1369", + "uuid": "{45B776E0-97C5-40D9-B776-E55FB19FA98C}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 43.629, + 89.202, + -373.002 + ], + "size": [ + 68.242, + 9.715, + 11.746 + ], + "groundY": 84.345, + "roofY": 94.06, + "wallCount": 125, + "roofCount": 50 + }, + { + "id": "sion_1370", + "uuid": "{D9484F9A-8A0B-413E-8D28-31127AC12DC7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 92.193, + 60.76, + -749.854 + ], + "size": [ + 14.957, + 10.916, + 14.382 + ], + "groundY": 55.302, + "roofY": 66.218, + "wallCount": 39, + "roofCount": 7 + }, + { + "id": "sion_1371", + "uuid": "{A01445E6-262B-4B2E-9419-8E0798CF8F18}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 892.326, + 8.914, + 756.253 + ], + "size": [ + 55.395, + 8.884, + 50.572 + ], + "groundY": 4.472, + "roofY": 13.356, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1372", + "uuid": "{37BC563B-64C1-4671-957A-06021814AD10}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1532.559, + 16.248, + 386.571 + ], + "size": [ + 21.023, + 16.99, + 12.572 + ], + "groundY": 7.753, + "roofY": 24.743, + "wallCount": 18, + "roofCount": 26 + }, + { + "id": "sion_1373", + "uuid": "{03753997-F474-4E7F-9599-30A1D8FB2643}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -367.416, + 24.917, + 230.157 + ], + "size": [ + 23.816, + 23.16, + 25.769 + ], + "groundY": 13.337, + "roofY": 36.497, + "wallCount": 20, + "roofCount": 43 + }, + { + "id": "sion_1374", + "uuid": "{FA2188AF-8313-4B36-8676-6B3F7FF1D88E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 169.703, + 71.538, + -934.172 + ], + "size": [ + 37.758, + 17.692, + 20.902 + ], + "groundY": 62.692, + "roofY": 80.384, + "wallCount": 48, + "roofCount": 29 + }, + { + "id": "sion_1375", + "uuid": "{866AC5D1-E1C3-4332-BB9E-2D77D8BBD297}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -230.293, + 35.26, + -89.677 + ], + "size": [ + 46.992, + 17.823, + 33.372 + ], + "groundY": 26.349, + "roofY": 44.172, + "wallCount": 49, + "roofCount": 25 + }, + { + "id": "sion_1376", + "uuid": "{35AA14F2-162B-4E66-AB41-1F0F5FFF4737}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -220.752, + 18.182, + 281.689 + ], + "size": [ + 16.965, + 10.248, + 13.772 + ], + "groundY": 13.058, + "roofY": 23.306, + "wallCount": 36, + "roofCount": 23 + }, + { + "id": "sion_1377", + "uuid": "{87C372EB-C45C-4C4D-A4FF-96F7FCDBA53E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 851.408, + 12.363, + -249.089 + ], + "size": [ + 20.012, + 19.462, + 39.893 + ], + "groundY": 2.632, + "roofY": 22.094, + "wallCount": 110, + "roofCount": 20 + }, + { + "id": "sion_1378", + "uuid": "{DC2CBA79-BABF-49A0-9461-FE52D86260B3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 305.033, + 17.129, + 64.889 + ], + "size": [ + 22.871, + 16.747, + 13.414 + ], + "groundY": 8.756, + "roofY": 25.503, + "wallCount": 32, + "roofCount": 9 + }, + { + "id": "sion_1379", + "uuid": "{6D90B091-681A-45E2-8E93-3DCC70E816C5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -247.227, + 42.142, + -324.736 + ], + "size": [ + 15.734, + 11.01, + 12.718 + ], + "groundY": 36.637, + "roofY": 47.647, + "wallCount": 10, + "roofCount": 15 + }, + { + "id": "sion_1380", + "uuid": "{B670AD0D-FA24-44F5-86B0-02C0440EC8B3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 692.127, + 14.473, + 969.532 + ], + "size": [ + 20.488, + 15.684, + 21.55 + ], + "groundY": 6.631, + "roofY": 22.315, + "wallCount": 48, + "roofCount": 12 + }, + { + "id": "sion_1381", + "uuid": "{87EF1DF3-6D2A-4C9F-A232-83E535D7C3A3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1035.205, + 11.498, + 272.063 + ], + "size": [ + 12.465, + 14.228, + 17.093 + ], + "groundY": 4.384, + "roofY": 18.612, + "wallCount": 53, + "roofCount": 20 + }, + { + "id": "sion_1382", + "uuid": "{8FA31D67-2A6F-4539-8387-2A8AF692B05D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -240.604, + 39.32, + -131.45 + ], + "size": [ + 32.246, + 23.546, + 43.752 + ], + "groundY": 27.547, + "roofY": 51.093, + "wallCount": 76, + "roofCount": 108 + }, + { + "id": "sion_1383", + "uuid": "{291434C2-26EC-4B41-9117-40A3ECC124FA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -130.641, + 49.205, + -374.911 + ], + "size": [ + 75.016, + 25.78, + 118.795 + ], + "groundY": 36.315, + "roofY": 62.095, + "wallCount": 243, + "roofCount": 220 + }, + { + "id": "sion_1384", + "uuid": "{7C13F8EF-7ECD-421A-B1EB-9E6AADB77280}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 898.662, + 8.268, + 493.406 + ], + "size": [ + 46.004, + 8.046, + 58.042 + ], + "groundY": 4.245, + "roofY": 12.291, + "wallCount": 57, + "roofCount": 24 + }, + { + "id": "sion_1385", + "uuid": "{C098363C-AFB7-4C64-A078-5FF51AC9BDDE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 180.334, + 7.775, + 932.092 + ], + "size": [ + 29.09, + 8.536, + 29.75 + ], + "groundY": 3.507, + "roofY": 12.043, + "wallCount": 27, + "roofCount": 28 + }, + { + "id": "sion_1386", + "uuid": "{CE9F78AD-54DB-4C47-A7BC-92CC420B129F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 6.279, + 66.856, + -338.025 + ], + "size": [ + 12.402, + 16.144, + 17.664 + ], + "groundY": 58.784, + "roofY": 74.928, + "wallCount": 43, + "roofCount": 13 + }, + { + "id": "sion_1387", + "uuid": "{458F5285-DF8E-4CA9-999A-F683B9C990E3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 640.277, + 8.354, + 589.079 + ], + "size": [ + 59.031, + 11.039, + 44.736 + ], + "groundY": 2.835, + "roofY": 13.874, + "wallCount": 28, + "roofCount": 14 + }, + { + "id": "sion_1388", + "uuid": "{6E04E76F-BEA0-4512-9169-CEF55DBA447E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -58.85, + 56.825, + -253.977 + ], + "size": [ + 59.566, + 27.65, + 68.405 + ], + "groundY": 43.0, + "roofY": 70.65, + "wallCount": 134, + "roofCount": 137 + }, + { + "id": "sion_1389", + "uuid": "{1A2914A5-17A1-4033-8202-5AB917A3CB81}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 60.846, + 132.855, + -1141.907 + ], + "size": [ + 4.551, + 6.728, + 3.967 + ], + "groundY": 129.491, + "roofY": 136.219, + "wallCount": 36, + "roofCount": 4 + }, + { + "id": "sion_1390", + "uuid": "{2FBEDE60-3794-4DDA-AA31-B194E1FB4300}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -228.516, + 15.49, + 640.906 + ], + "size": [ + 37.836, + 30.642, + 52.4 + ], + "groundY": 0.169, + "roofY": 30.811, + "wallCount": 94, + "roofCount": 30 + }, + { + "id": "sion_1391", + "uuid": "{1B367FBE-C959-4014-AC61-4976BAFE6DB3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -26.559, + 61.95, + -759.929 + ], + "size": [ + 11.852, + 5.232, + 11.229 + ], + "groundY": 59.334, + "roofY": 64.566, + "wallCount": 39, + "roofCount": 17 + }, + { + "id": "sion_1392", + "uuid": "{2611F3E9-003E-4C9C-8160-FD77E3E154BB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 131.674, + 59.584, + -682.991 + ], + "size": [ + 16.301, + 12.776, + 19.268 + ], + "groundY": 53.196, + "roofY": 65.972, + "wallCount": 23, + "roofCount": 8 + }, + { + "id": "sion_1393", + "uuid": "{C354BB7E-311C-48E1-95BD-EB7D8E8670E9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 2 + ], + "center": [ + 1466.414, + 11.642, + -33.462 + ], + "size": [ + 12.023, + 9.959, + 16.964 + ], + "groundY": 6.663, + "roofY": 16.622, + "wallCount": 54, + "roofCount": 24 + }, + { + "id": "sion_1394", + "uuid": "{BB7263AB-81A4-4F50-96C3-8B61904D0043}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 0.258, + 85.2, + -370.261 + ], + "size": [ + 33.422, + 9.334, + 31.24 + ], + "groundY": 80.533, + "roofY": 89.867, + "wallCount": 37, + "roofCount": 14 + }, + { + "id": "sion_1395", + "uuid": "{79E0D712-0AF5-437C-98C8-35B3F5EB09FD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 536.199, + 6.632, + 471.571 + ], + "size": [ + 28.188, + 8.306, + 41.95 + ], + "groundY": 2.479, + "roofY": 10.785, + "wallCount": 43, + "roofCount": 20 + }, + { + "id": "sion_1396", + "uuid": "{4DC7A988-3A99-4E74-8ADF-64C3B6453022}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -111.035, + 195.026, + -1485.697 + ], + "size": [ + 19.555, + 13.576, + 28.472 + ], + "groundY": 188.238, + "roofY": 201.814, + "wallCount": 78, + "roofCount": 26 + }, + { + "id": "sion_1397", + "uuid": "{7AE4BEB0-13A8-4338-B5CE-CD68C14191B2}", + "name": "", + "class": "Flugdach", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -126.574, + 10.013, + 603.272 + ], + "size": [ + 28.484, + 0.101, + 18.813 + ], + "groundY": 9.963, + "roofY": 10.063, + "wallCount": 2, + "roofCount": 2 + }, + { + "id": "sion_1398", + "uuid": "{C20010E1-7B99-4CED-853F-CA711756E40B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 487.227, + 7.61, + 913.411 + ], + "size": [ + 10.461, + 7.374, + 14.468 + ], + "groundY": 3.923, + "roofY": 11.297, + "wallCount": 35, + "roofCount": 4 + }, + { + "id": "sion_1399", + "uuid": "{32419A30-F7C6-4E46-AEEF-5D67F9ED1345}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -274.729, + 76.32, + -931.477 + ], + "size": [ + 45.606, + 10.169, + 41.832 + ], + "groundY": 71.236, + "roofY": 81.405, + "wallCount": 20, + "roofCount": 31 + }, + { + "id": "sion_1400", + "uuid": "{4E9052ED-0473-4CA7-A0A6-42EB068A2253}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 129.176, + 64.823, + -887.086 + ], + "size": [ + 33.078, + 7.843, + 17.897 + ], + "groundY": 60.902, + "roofY": 68.745, + "wallCount": 10, + "roofCount": 26 + }, + { + "id": "sion_1401", + "uuid": "{73FD8DA1-50B9-4CDD-896D-8A9F3974DFCF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 2 + ], + "center": [ + 1497.082, + 12.276, + -23.431 + ], + "size": [ + 11.234, + 9.706, + 11.924 + ], + "groundY": 7.423, + "roofY": 17.129, + "wallCount": 60, + "roofCount": 25 + }, + { + "id": "sion_1402", + "uuid": "{A0118980-4FDF-4F4C-BCED-74E010D8A77C}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 947.266, + 9.551, + 583.958 + ], + "size": [ + 34.102, + 11.619, + 51.549 + ], + "groundY": 3.741, + "roofY": 15.36, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1403", + "uuid": "{F7E019B1-D1D8-4CAB-855D-2ADDD6923966}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 244.256, + 56.06, + -722.618 + ], + "size": [ + 18.082, + 8.397, + 16.176 + ], + "groundY": 51.862, + "roofY": 60.259, + "wallCount": 23, + "roofCount": 14 + }, + { + "id": "sion_1404", + "uuid": "{5B89650A-836C-4036-8181-E2E8153D425B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 828.225, + 10.866, + 818.005 + ], + "size": [ + 58.582, + 12.283, + 75.928 + ], + "groundY": 4.725, + "roofY": 17.007, + "wallCount": 29, + "roofCount": 18 + }, + { + "id": "sion_1405", + "uuid": "{C1529F0A-163F-4388-B26F-6A1D710C4B4B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 223.717, + 9.765, + 1028.028 + ], + "size": [ + 87.527, + 14.512, + 81.328 + ], + "groundY": 2.509, + "roofY": 17.021, + "wallCount": 35, + "roofCount": 15 + }, + { + "id": "sion_1406", + "uuid": "{77414659-4ABD-4486-BF9B-F7B0A0014D85}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 647.227, + 14.502, + -8.461 + ], + "size": [ + 20.469, + 22.768, + 21.484 + ], + "groundY": 3.118, + "roofY": 25.886, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1407", + "uuid": "{11E3BE0F-9018-42C6-A4A8-5FBA46339BD7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 588.949, + 98.8, + -1114.822 + ], + "size": [ + 4.93, + 5.412, + 4.466 + ], + "groundY": 96.094, + "roofY": 101.506, + "wallCount": 16, + "roofCount": 8 + }, + { + "id": "sion_1408", + "uuid": "{1EB683B1-1519-4941-9FCE-F763612D340B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 304.805, + 13.594, + 378.379 + ], + "size": [ + 81.078, + 22.372, + 54.273 + ], + "groundY": 2.408, + "roofY": 24.78, + "wallCount": 43, + "roofCount": 13 + }, + { + "id": "sion_1409", + "uuid": "{FE9D4039-35EE-4014-BDA6-A4AF6B458DA4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 359.529, + 7.651, + 785.858 + ], + "size": [ + 48.91, + 10.859, + 37.882 + ], + "groundY": 2.222, + "roofY": 13.081, + "wallCount": 10, + "roofCount": 9 + }, + { + "id": "sion_1410", + "uuid": "{B51A65D3-6F41-4067-93C4-813192C3602B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 273.615, + 13.946, + 186.109 + ], + "size": [ + 19.574, + 6.67, + 22.263 + ], + "groundY": 10.611, + "roofY": 17.281, + "wallCount": 15, + "roofCount": 4 + }, + { + "id": "sion_1411", + "uuid": "{A2254719-9E41-4F43-9B26-3DDE2675D1F8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 429.74, + 8.312, + 1038.155 + ], + "size": [ + 44.496, + 10.096, + 40.738 + ], + "groundY": 3.264, + "roofY": 13.36, + "wallCount": 44, + "roofCount": 16 + }, + { + "id": "sion_1412", + "uuid": "{54A64E36-D0A9-4340-8820-95ACE764194D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -210.844, + 76.007, + -988.57 + ], + "size": [ + 14.906, + 5.542, + 17.128 + ], + "groundY": 73.236, + "roofY": 78.778, + "wallCount": 18, + "roofCount": 3 + }, + { + "id": "sion_1413", + "uuid": "{90B03667-C36E-4813-BA1D-493881C2221B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 180.434, + 19.501, + 279.26 + ], + "size": [ + 71.617, + 27.592, + 101.302 + ], + "groundY": 5.705, + "roofY": 33.297, + "wallCount": 87, + "roofCount": 45 + }, + { + "id": "sion_1414", + "uuid": "{F0D128EA-10E8-433A-92A8-17F486DA3BB9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 463.818, + 11.576, + 392.17 + ], + "size": [ + 42.606, + 13.483, + 51.848 + ], + "groundY": 4.835, + "roofY": 18.318, + "wallCount": 23, + "roofCount": 26 + }, + { + "id": "sion_1415", + "uuid": "{4D2B6D53-48EB-443A-99BF-4874A541E067}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1442.023, + 25.276, + 189.925 + ], + "size": [ + 14.641, + 34.324, + 20.698 + ], + "groundY": 8.114, + "roofY": 42.438, + "wallCount": 119, + "roofCount": 32 + }, + { + "id": "sion_1416", + "uuid": "{5EFDBEA1-1990-4E31-82AB-AF2BFD418081}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 613.018, + 228.585, + -1482.908 + ], + "size": [ + 50.887, + 18.113, + 28.864 + ], + "groundY": 219.529, + "roofY": 237.642, + "wallCount": 69, + "roofCount": 59 + }, + { + "id": "sion_1417", + "uuid": "{F3BD8EF3-AC0B-4034-AFF0-C4DEBE3B4C5B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 248.145, + 62.462, + -840.269 + ], + "size": [ + 24.445, + 9.987, + 13.128 + ], + "groundY": 57.469, + "roofY": 67.456, + "wallCount": 27, + "roofCount": 32 + }, + { + "id": "sion_1418", + "uuid": "{15387AD5-FE81-4D82-A21F-C3903F53FDF3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 249.658, + 19.47, + 194.575 + ], + "size": [ + 17.027, + 15.692, + 17.988 + ], + "groundY": 11.624, + "roofY": 27.316, + "wallCount": 20, + "roofCount": 11 + }, + { + "id": "sion_1419", + "uuid": "{FCC1FE1D-872E-4CDC-9517-43B747FCF41B}", + "name": "", + "class": "Unterirdisches Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 824.357, + 17.675, + -454.813 + ], + "size": [ + 32.301, + 27.949, + 24.286 + ], + "groundY": 3.7, + "roofY": 31.649, + "wallCount": 109, + "roofCount": 29 + }, + { + "id": "sion_1420", + "uuid": "{3762A0F3-1F8F-4452-A1E1-1F548F91859F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 535.674, + 106.845, + -1118.521 + ], + "size": [ + 5.965, + 8.31, + 5.513 + ], + "groundY": 102.69, + "roofY": 110.999, + "wallCount": 49, + "roofCount": 6 + }, + { + "id": "sion_1421", + "uuid": "{DAB4C98F-3A8F-4145-B36D-1E5C89717CDC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -201.68, + 45.54, + -310.102 + ], + "size": [ + 28.281, + 23.646, + 51.448 + ], + "groundY": 33.717, + "roofY": 57.363, + "wallCount": 122, + "roofCount": 86 + }, + { + "id": "sion_1422", + "uuid": "{47CCB510-8B10-4C5C-8C7F-5A51C9212B24}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 448.016, + 56.248, + -882.812 + ], + "size": [ + 11.461, + 11.209, + 13.628 + ], + "groundY": 50.644, + "roofY": 61.853, + "wallCount": 28, + "roofCount": 12 + }, + { + "id": "sion_1423", + "uuid": "{213314B4-9AC7-4275-BBB9-9B735BD12CD7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -217.853, + 41.529, + -326.805 + ], + "size": [ + 13.824, + 11.293, + 20.492 + ], + "groundY": 35.883, + "roofY": 47.176, + "wallCount": 44, + "roofCount": 19 + }, + { + "id": "sion_1424", + "uuid": "{E36A1C8D-27B2-44B3-BF96-6561DD1BEAE1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 174.193, + 11.864, + 576.446 + ], + "size": [ + 51.809, + 22.67, + 70.438 + ], + "groundY": 0.529, + "roofY": 23.199, + "wallCount": 64, + "roofCount": 36 + }, + { + "id": "sion_1425", + "uuid": "{8AF3FFD5-4ED6-4014-A42C-11DD54471B8A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 330.918, + 213.463, + -1319.296 + ], + "size": [ + 19.156, + 11.314, + 12.154 + ], + "groundY": 207.806, + "roofY": 219.12, + "wallCount": 34, + "roofCount": 26 + }, + { + "id": "sion_1426", + "uuid": "{82F5F61D-8F13-4EC7-978B-910BB7F9B4B1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -299.816, + 43.643, + -289.654 + ], + "size": [ + 20.242, + 17.047, + 18.348 + ], + "groundY": 35.12, + "roofY": 52.167, + "wallCount": 21, + "roofCount": 25 + }, + { + "id": "sion_1427", + "uuid": "{4F044913-6246-4270-BBF7-47155C504136}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 503.746, + 150.565, + -1206.089 + ], + "size": [ + 3.945, + 6.923, + 4.102 + ], + "groundY": 147.103, + "roofY": 154.026, + "wallCount": 24, + "roofCount": 3 + }, + { + "id": "sion_1428", + "uuid": "{75EE7C64-4669-4BC4-B25B-2716D891E42F}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 2, + 2 + ], + "center": [ + -16.164, + 76.202, + -348.612 + ], + "size": [ + 5.398, + 3.822, + 2.773 + ], + "groundY": 74.291, + "roofY": 78.113, + "wallCount": 26, + "roofCount": 10 + }, + { + "id": "sion_1429", + "uuid": "{C4FE8319-C533-4177-B4E5-5BEF0E1B579D}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 3, + 0 + ], + "center": [ + 312.029, + 208.887, + -1335.239 + ], + "size": [ + 22.215, + 7.179, + 14.776 + ], + "groundY": 205.298, + "roofY": 212.477, + "wallCount": 24, + "roofCount": 8 + }, + { + "id": "sion_1430", + "uuid": "{1B7DD818-E83D-46FF-A655-3548B117FF2D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 250.795, + 81.736, + -987.728 + ], + "size": [ + 58.652, + 17.943, + 22.007 + ], + "groundY": 72.764, + "roofY": 90.707, + "wallCount": 37, + "roofCount": 29 + }, + { + "id": "sion_1431", + "uuid": "{DA0DA9B5-9427-46A2-8C8E-6080B544D4A4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 4 + ], + "center": [ + 1396.701, + 19.135, + 889.835 + ], + "size": [ + 45.738, + 14.304, + 30.863 + ], + "groundY": 11.983, + "roofY": 26.287, + "wallCount": 25, + "roofCount": 31 + }, + { + "id": "sion_1432", + "uuid": "{7C72E624-2356-4106-B60C-68E0C634995F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -284.373, + 67.22, + -728.909 + ], + "size": [ + 40.199, + 16.278, + 35.55 + ], + "groundY": 59.081, + "roofY": 75.359, + "wallCount": 25, + "roofCount": 53 + }, + { + "id": "sion_1433", + "uuid": "{226F2CC9-D1C2-4986-9F25-0F55A38415BE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 169.33, + 23.822, + 38.06 + ], + "size": [ + 16.426, + 18.804, + 12.935 + ], + "groundY": 14.42, + "roofY": 33.223, + "wallCount": 29, + "roofCount": 34 + }, + { + "id": "sion_1434", + "uuid": "{85036972-9173-4508-9B22-1F20534C196A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 428.701, + 69.841, + -759.824 + ], + "size": [ + 20.543, + 13.832, + 18.916 + ], + "groundY": 62.925, + "roofY": 76.757, + "wallCount": 32, + "roofCount": 11 + }, + { + "id": "sion_1435", + "uuid": "{79C73373-92B9-48D9-ACE6-7F5C772FECFF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -364.836, + 48.204, + -388.484 + ], + "size": [ + 18.023, + 19.013, + 17.162 + ], + "groundY": 38.697, + "roofY": 57.71, + "wallCount": 25, + "roofCount": 15 + }, + { + "id": "sion_1436", + "uuid": "{3C33FC3B-9B16-4FB0-AC88-1A636CAE5DCF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 273.713, + 95.059, + -1052.164 + ], + "size": [ + 24.184, + 16.344, + 25.969 + ], + "groundY": 86.887, + "roofY": 103.231, + "wallCount": 53, + "roofCount": 28 + }, + { + "id": "sion_1437", + "uuid": "{B14AE262-7295-4415-8B10-988D40246873}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 258.129, + 59.083, + -640.902 + ], + "size": [ + 18.742, + 12.301, + 13.292 + ], + "groundY": 52.933, + "roofY": 65.234, + "wallCount": 39, + "roofCount": 19 + }, + { + "id": "sion_1438", + "uuid": "{3B0272E3-BFF3-43BB-B23B-E8CC24F4FF0E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 249.291, + 21.092, + 35.94 + ], + "size": [ + 47.551, + 20.203, + 15.757 + ], + "groundY": 10.991, + "roofY": 31.194, + "wallCount": 14, + "roofCount": 7 + }, + { + "id": "sion_1439", + "uuid": "{3364E7F9-02C0-470F-9C75-10CEA4224A24}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -95.881, + 49.676, + -345.558 + ], + "size": [ + 27.856, + 17.115, + 24.1 + ], + "groundY": 41.119, + "roofY": 58.234, + "wallCount": 62, + "roofCount": 33 + }, + { + "id": "sion_1440", + "uuid": "{3891C628-70F7-47CF-89AF-85FBD831E116}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1201.934, + 12.124, + 377.125 + ], + "size": [ + 30.594, + 10.492, + 12.803 + ], + "groundY": 6.878, + "roofY": 17.37, + "wallCount": 25, + "roofCount": 22 + }, + { + "id": "sion_1441", + "uuid": "{6018C750-2B19-4CFF-BE28-497E731C813D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 909.504, + 9.154, + -347.787 + ], + "size": [ + 15.922, + 11.078, + 15.445 + ], + "groundY": 3.615, + "roofY": 14.693, + "wallCount": 25, + "roofCount": 10 + }, + { + "id": "sion_1442", + "uuid": "{5FF85C99-BE9D-41D5-B50F-454C5C4D561C}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 609.291, + 21.084, + 340.237 + ], + "size": [ + 16.731, + 31.752, + 20.99 + ], + "groundY": 5.208, + "roofY": 36.96, + "wallCount": 100, + "roofCount": 16 + }, + { + "id": "sion_1443", + "uuid": "{0F3CD28E-ABBC-491E-BFD9-72451D5046EF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 362.617, + 13.669, + 131.811 + ], + "size": [ + 17.445, + 14.736, + 18.517 + ], + "groundY": 6.301, + "roofY": 21.037, + "wallCount": 37, + "roofCount": 37 + }, + { + "id": "sion_1444", + "uuid": "{E413E9A2-472A-4A57-8A0A-E156559D0826}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 4 + ], + "center": [ + 1313.484, + 14.725, + 934.963 + ], + "size": [ + 23.68, + 6.368, + 11.704 + ], + "groundY": 11.541, + "roofY": 17.909, + "wallCount": 31, + "roofCount": 14 + }, + { + "id": "sion_1445", + "uuid": "{2152A75A-67E9-4260-B89C-0B213BEC0A49}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 490.105, + 213.535, + -1530.61 + ], + "size": [ + 24.211, + 12.23, + 38.167 + ], + "groundY": 207.42, + "roofY": 219.65, + "wallCount": 26, + "roofCount": 10 + }, + { + "id": "sion_1446", + "uuid": "{2E99BC3E-86F0-44A1-92E3-CB9487CC6FD0}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 494.732, + 75.164, + -367.407 + ], + "size": [ + 16.457, + 13.674, + 91.506 + ], + "groundY": 68.327, + "roofY": 82.001, + "wallCount": 68, + "roofCount": 24 + }, + { + "id": "sion_1447", + "uuid": "{E5588E05-3819-4AF4-A95E-C36FB84B5BD5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1287.316, + 12.612, + 267.091 + ], + "size": [ + 30.281, + 10.615, + 11.618 + ], + "groundY": 7.305, + "roofY": 17.92, + "wallCount": 29, + "roofCount": 29 + }, + { + "id": "sion_1448", + "uuid": "{23309891-7482-4FBD-B929-92BEFB9CB37C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -265.201, + 54.564, + -512.156 + ], + "size": [ + 15.543, + 14.889, + 12.86 + ], + "groundY": 47.12, + "roofY": 62.008, + "wallCount": 38, + "roofCount": 81 + }, + { + "id": "sion_1449", + "uuid": "{6E5267F3-C0EC-46BF-84AE-CDB1634246B9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1141.807, + 10.791, + 344.123 + ], + "size": [ + 13.418, + 9.273, + 11.803 + ], + "groundY": 6.155, + "roofY": 15.427, + "wallCount": 27, + "roofCount": 41 + }, + { + "id": "sion_1450", + "uuid": "{38596A7E-6022-4F81-80C6-660D15109412}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 250.713, + 7.445, + 991.114 + ], + "size": [ + 77.121, + 10.042, + 71.822 + ], + "groundY": 2.424, + "roofY": 12.466, + "wallCount": 10, + "roofCount": 17 + }, + { + "id": "sion_1451", + "uuid": "{79664448-F3F6-4C5E-9381-E6433ACE522D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 37.889, + 19.547, + 508.317 + ], + "size": [ + 40.613, + 34.148, + 32.787 + ], + "groundY": 2.473, + "roofY": 36.621, + "wallCount": 29, + "roofCount": 6 + }, + { + "id": "sion_1452", + "uuid": "{672E7B2A-1806-483C-98F7-F06A78E14728}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1417.127, + 18.398, + 316.414 + ], + "size": [ + 20.324, + 21.424, + 55.727 + ], + "groundY": 7.686, + "roofY": 29.11, + "wallCount": 61, + "roofCount": 30 + }, + { + "id": "sion_1453", + "uuid": "{9672E47F-2B6B-44A0-8FF8-F71706756617}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 457.139, + 70.299, + -990.987 + ], + "size": [ + 24.191, + 17.8, + 36.602 + ], + "groundY": 61.399, + "roofY": 79.199, + "wallCount": 72, + "roofCount": 40 + }, + { + "id": "sion_1454", + "uuid": "{43DDC23C-142D-461C-9B6C-FBB1F096D318}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 586.299, + 6.307, + 613.615 + ], + "size": [ + 32.598, + 7.056, + 30.556 + ], + "groundY": 2.779, + "roofY": 9.835, + "wallCount": 32, + "roofCount": 29 + }, + { + "id": "sion_1455", + "uuid": "{8CA58EDD-94BF-4150-953A-38CFCB96FAF0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -264.393, + 36.897, + -70.855 + ], + "size": [ + 53.566, + 23.262, + 39.849 + ], + "groundY": 25.266, + "roofY": 48.528, + "wallCount": 68, + "roofCount": 77 + }, + { + "id": "sion_1456", + "uuid": "{D122B4CA-2959-43E0-8933-3BA5A01672BC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 610.168, + 14.901, + 100.694 + ], + "size": [ + 23.664, + 23.633, + 66.94 + ], + "groundY": 3.085, + "roofY": 26.718, + "wallCount": 146, + "roofCount": 24 + }, + { + "id": "sion_1457", + "uuid": "{85EC80DF-1E1A-46CB-8A8B-E3936AE1A233}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1392.035, + 19.314, + 53.07 + ], + "size": [ + 40.18, + 26.108, + 12.242 + ], + "groundY": 6.26, + "roofY": 32.368, + "wallCount": 30, + "roofCount": 4 + }, + { + "id": "sion_1458", + "uuid": "{9E1A3761-FC25-47C0-AED4-DD6942281322}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 2 + ], + "center": [ + 1502.361, + 12.118, + -49.329 + ], + "size": [ + 15.676, + 10.158, + 21.912 + ], + "groundY": 7.039, + "roofY": 17.197, + "wallCount": 30, + "roofCount": 12 + }, + { + "id": "sion_1459", + "uuid": "{D2726F0A-E2C6-494A-ACBD-3A6A9467C82D}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1440.908, + 24.211, + 266.294 + ], + "size": [ + 18.824, + 33.578, + 20.697 + ], + "groundY": 7.422, + "roofY": 41.0, + "wallCount": 170, + "roofCount": 19 + }, + { + "id": "sion_1460", + "uuid": "{012999DB-AF9E-4EA7-A9D2-3DC3FD836511}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 19.018, + 19.959, + 280.265 + ], + "size": [ + 99.707, + 23.058, + 87.705 + ], + "groundY": 8.43, + "roofY": 31.488, + "wallCount": 150, + "roofCount": 118 + }, + { + "id": "sion_1461", + "uuid": "{2BF1B004-6DD5-4425-817D-EDC0C9283352}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 2 + ], + "center": [ + 1481.34, + 12.625, + -54.893 + ], + "size": [ + 21.312, + 11.025, + 18.538 + ], + "groundY": 7.113, + "roofY": 18.138, + "wallCount": 63, + "roofCount": 31 + }, + { + "id": "sion_1462", + "uuid": "{934CEB5D-1123-48B2-81DB-DBA79B3753B8}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 786.748, + 19.439, + 147.003 + ], + "size": [ + 25.301, + 32.394, + 24.422 + ], + "groundY": 3.242, + "roofY": 35.636, + "wallCount": 141, + "roofCount": 12 + }, + { + "id": "sion_1463", + "uuid": "{1C4A069D-5F68-4DE5-A0D1-5C66CED5AAE6}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 2, + 2 + ], + "center": [ + -26.045, + 44.739, + -134.802 + ], + "size": [ + 49.301, + 11.464, + 6.794 + ], + "groundY": 39.007, + "roofY": 50.471, + "wallCount": 62, + "roofCount": 26 + }, + { + "id": "sion_1464", + "uuid": "{6B4F087E-B690-4DD3-8074-2E9164B8FE62}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -245.785, + 34.091, + 47.396 + ], + "size": [ + 80.484, + 27.85, + 87.485 + ], + "groundY": 20.166, + "roofY": 48.016, + "wallCount": 156, + "roofCount": 118 + }, + { + "id": "sion_1465", + "uuid": "{E4F7E4BD-DB8C-402D-96A7-F831C1B4E6C6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 200.869, + 6.466, + 558.893 + ], + "size": [ + 28.637, + 11.599, + 37.662 + ], + "groundY": 0.667, + "roofY": 12.266, + "wallCount": 12, + "roofCount": 12 + }, + { + "id": "sion_1466", + "uuid": "{AB2EABED-9B14-46A9-B578-1A918CF5720B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 56.951, + 62.954, + -782.187 + ], + "size": [ + 10.059, + 9.926, + 9.696 + ], + "groundY": 57.991, + "roofY": 67.917, + "wallCount": 27, + "roofCount": 26 + }, + { + "id": "sion_1467", + "uuid": "{A363926C-74CB-4135-9774-3A3E0599EAFE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 319.057, + 65.771, + -855.603 + ], + "size": [ + 18.731, + 10.567, + 14.89 + ], + "groundY": 60.487, + "roofY": 71.054, + "wallCount": 28, + "roofCount": 41 + }, + { + "id": "sion_1468", + "uuid": "{385C96D1-F74C-4614-A79E-2AC9DEF2AD3E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -115.781, + 85.381, + -989.968 + ], + "size": [ + 15.101, + 15.34, + 11.03 + ], + "groundY": 77.711, + "roofY": 93.05, + "wallCount": 50, + "roofCount": 32 + }, + { + "id": "sion_1469", + "uuid": "{C7675116-1724-4FED-B172-7B5F8EDB3CA3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 378.77, + 206.335, + -1504.45 + ], + "size": [ + 18.18, + 12.443, + 23.836 + ], + "groundY": 200.114, + "roofY": 212.557, + "wallCount": 56, + "roofCount": 25 + }, + { + "id": "sion_1470", + "uuid": "{0CF39C01-716C-4AEA-B653-712FA36091A3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 244.637, + 20.425, + -34.209 + ], + "size": [ + 45.938, + 21.193, + 28.168 + ], + "groundY": 9.829, + "roofY": 31.022, + "wallCount": 17, + "roofCount": 45 + }, + { + "id": "sion_1471", + "uuid": "{A0DDFAE6-1221-4483-BBA3-36FE1AEDEEB1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1439.471, + 21.182, + 152.975 + ], + "size": [ + 14.332, + 24.925, + 21.548 + ], + "groundY": 8.72, + "roofY": 33.645, + "wallCount": 132, + "roofCount": 21 + }, + { + "id": "sion_1472", + "uuid": "{AAD1C63D-6F96-4CB2-8EC5-AC6987A820BD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 676.283, + 12.631, + 105.678 + ], + "size": [ + 14.746, + 20.253, + 50.186 + ], + "groundY": 2.505, + "roofY": 22.758, + "wallCount": 105, + "roofCount": 13 + }, + { + "id": "sion_1473", + "uuid": "{E4CBAEE2-4F3E-44B0-88FE-C8667D4A8E2A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1399.936, + 14.298, + 421.197 + ], + "size": [ + 60.559, + 13.657, + 109.977 + ], + "groundY": 7.47, + "roofY": 21.127, + "wallCount": 75, + "roofCount": 69 + }, + { + "id": "sion_1474", + "uuid": "{6456C51F-7D1A-40D9-A431-5108CFC0EC06}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1127.061, + 13.792, + 261.967 + ], + "size": [ + 30.176, + 18.744, + 32.864 + ], + "groundY": 4.42, + "roofY": 23.164, + "wallCount": 86, + "roofCount": 26 + }, + { + "id": "sion_1475", + "uuid": "{CA5A4095-402C-4580-AD57-9FEB790829B5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -65.865, + 50.869, + -342.448 + ], + "size": [ + 12.981, + 12.809, + 15.776 + ], + "groundY": 44.465, + "roofY": 57.274, + "wallCount": 19, + "roofCount": 15 + }, + { + "id": "sion_1476", + "uuid": "{8165B912-A2E3-47CE-8EF2-C8899B4DD9BC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 188.566, + 68.513, + -872.376 + ], + "size": [ + 40.094, + 18.932, + 23.477 + ], + "groundY": 59.047, + "roofY": 77.979, + "wallCount": 20, + "roofCount": 25 + }, + { + "id": "sion_1477", + "uuid": "{76DFBE44-0733-4840-BC84-C3C982D5FA14}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 238.969, + 19.607, + 183.471 + ], + "size": [ + 18.266, + 15.413, + 17.584 + ], + "groundY": 11.901, + "roofY": 27.314, + "wallCount": 25, + "roofCount": 8 + }, + { + "id": "sion_1478", + "uuid": "{2BA144EC-753C-4110-A582-762570F7B941}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -256.791, + 43.0, + -345.028 + ], + "size": [ + 16.207, + 12.33, + 19.412 + ], + "groundY": 36.835, + "roofY": 49.165, + "wallCount": 35, + "roofCount": 10 + }, + { + "id": "sion_1479", + "uuid": "{F62F90D5-7D72-4AA2-B990-AF19E7366697}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -253.162, + 74.863, + -869.268 + ], + "size": [ + 15.145, + 11.412, + 13.836 + ], + "groundY": 69.157, + "roofY": 80.569, + "wallCount": 49, + "roofCount": 22 + }, + { + "id": "sion_1480", + "uuid": "{F482CD9C-CA98-4E9D-9CA9-FF295D5A86E4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 613.701, + 9.248, + -23.685 + ], + "size": [ + 14.887, + 10.928, + 34.8 + ], + "groundY": 3.784, + "roofY": 14.712, + "wallCount": 14, + "roofCount": 20 + }, + { + "id": "sion_1481", + "uuid": "{17FB3350-AFE1-457F-918A-9C69A3B108BA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 158.748, + 58.834, + -664.159 + ], + "size": [ + 23.246, + 9.149, + 15.696 + ], + "groundY": 54.26, + "roofY": 63.408, + "wallCount": 32, + "roofCount": 8 + }, + { + "id": "sion_1482", + "uuid": "{D78CB542-5B80-46A0-82D0-39B93D0723BC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 231.053, + 58.872, + -807.954 + ], + "size": [ + 22.449, + 12.884, + 17.637 + ], + "groundY": 52.43, + "roofY": 65.314, + "wallCount": 31, + "roofCount": 16 + }, + { + "id": "sion_1483", + "uuid": "{F3802D7B-165F-414A-BCF2-4C12314C3402}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 588.25, + 9.556, + 517.314 + ], + "size": [ + 88.344, + 13.986, + 92.007 + ], + "groundY": 2.563, + "roofY": 16.549, + "wallCount": 16, + "roofCount": 15 + }, + { + "id": "sion_1484", + "uuid": "{DC16CC61-6191-4D4A-B812-AEB50EEBF870}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 711.252, + 6.899, + 266.086 + ], + "size": [ + 14.387, + 9.667, + 13.932 + ], + "groundY": 2.066, + "roofY": 11.733, + "wallCount": 20, + "roofCount": 10 + }, + { + "id": "sion_1485", + "uuid": "{D86448D0-C4D2-4EEC-8A51-CCFEC21BA5DA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 336.268, + 204.992, + -1521.652 + ], + "size": [ + 27.77, + 9.78, + 12.569 + ], + "groundY": 200.102, + "roofY": 209.882, + "wallCount": 33, + "roofCount": 33 + }, + { + "id": "sion_1486", + "uuid": "{6C69E93E-AE29-4544-9CF3-946C6D6E5C7B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 331.105, + 214.419, + -1357.434 + ], + "size": [ + 18.18, + 12.822, + 19.644 + ], + "groundY": 208.008, + "roofY": 220.83, + "wallCount": 38, + "roofCount": 20 + }, + { + "id": "sion_1487", + "uuid": "{004861AD-AE97-4105-A405-C10C4D23E963}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -323.883, + 33.285, + 12.93 + ], + "size": [ + 51.836, + 24.778, + 39.94 + ], + "groundY": 20.896, + "roofY": 45.674, + "wallCount": 36, + "roofCount": 48 + }, + { + "id": "sion_1488", + "uuid": "{74D54D48-3FF5-4863-BC43-93240988755C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -95.768, + 48.341, + -321.595 + ], + "size": [ + 23.871, + 12.4, + 20.54 + ], + "groundY": 42.141, + "roofY": 54.541, + "wallCount": 25, + "roofCount": 7 + }, + { + "id": "sion_1489", + "uuid": "{23A34EFB-AB32-40E6-AC14-3EE275F38E72}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 2 + ], + "center": [ + 1483.625, + 12.293, + -27.263 + ], + "size": [ + 10.984, + 9.668, + 12.731 + ], + "groundY": 7.459, + "roofY": 17.127, + "wallCount": 43, + "roofCount": 16 + }, + { + "id": "sion_1490", + "uuid": "{8D5BAB38-255D-426A-940F-EA327CF9C18C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 1 + ], + "center": [ + 956.098, + 16.535, + -585.41 + ], + "size": [ + 41.148, + 23.946, + 30.854 + ], + "groundY": 4.562, + "roofY": 28.508, + "wallCount": 132, + "roofCount": 25 + }, + { + "id": "sion_1491", + "uuid": "{AE95EEAA-40B7-4909-9A5B-51774A6B43FB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -216.201, + 79.509, + -974.271 + ], + "size": [ + 14.246, + 14.019, + 16.733 + ], + "groundY": 72.5, + "roofY": 86.519, + "wallCount": 58, + "roofCount": 34 + }, + { + "id": "sion_1492", + "uuid": "{D188BFFB-6060-4B59-AF81-AAC83C1E0490}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -169.703, + 59.248, + -606.571 + ], + "size": [ + 30.531, + 21.875, + 46.23 + ], + "groundY": 48.311, + "roofY": 70.185, + "wallCount": 76, + "roofCount": 39 + }, + { + "id": "sion_1493", + "uuid": "{7029AD5A-027E-4961-9221-FA9149CC5870}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -206.4, + 46.452, + -383.401 + ], + "size": [ + 50.488, + 19.777, + 19.731 + ], + "groundY": 36.564, + "roofY": 56.341, + "wallCount": 110, + "roofCount": 60 + }, + { + "id": "sion_1494", + "uuid": "{AA133F8E-FB2F-4A79-AB45-59B061DC2359}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 4.473, + 62.733, + -310.83 + ], + "size": [ + 25.0, + 14.103, + 27.992 + ], + "groundY": 55.682, + "roofY": 69.785, + "wallCount": 69, + "roofCount": 33 + }, + { + "id": "sion_1495", + "uuid": "{13A82603-F75B-41E2-9655-4721078EE19E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 670.25, + 14.276, + 235.882 + ], + "size": [ + 20.672, + 24.768, + 20.565 + ], + "groundY": 1.892, + "roofY": 26.66, + "wallCount": 60, + "roofCount": 8 + }, + { + "id": "sion_1496", + "uuid": "{1E980E19-C3B6-4A43-B89A-96CD03D8DE18}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1065.729, + 9.023, + 271.413 + ], + "size": [ + 22.316, + 11.521, + 17.868 + ], + "groundY": 3.263, + "roofY": 14.784, + "wallCount": 71, + "roofCount": 32 + }, + { + "id": "sion_1497", + "uuid": "{22347373-7953-467C-A9A2-9F8D686A7032}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 83.055, + 19.111, + 261.365 + ], + "size": [ + 18.789, + 19.174, + 17.85 + ], + "groundY": 9.524, + "roofY": 28.698, + "wallCount": 54, + "roofCount": 56 + }, + { + "id": "sion_1498", + "uuid": "{7F1F74EE-1DC4-4FF7-8283-0F5158CAD122}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -275.391, + 4.467, + 885.428 + ], + "size": [ + 22.984, + 8.82, + 42.622 + ], + "groundY": 0.057, + "roofY": 8.877, + "wallCount": 35, + "roofCount": 20 + }, + { + "id": "sion_1499", + "uuid": "{A60519A4-3B9C-4418-80CB-B65A4C65F57B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -366.826, + 4.327, + 712.955 + ], + "size": [ + 20.637, + 10.988, + 14.635 + ], + "groundY": -1.167, + "roofY": 9.821, + "wallCount": 23, + "roofCount": 16 + }, + { + "id": "sion_1500", + "uuid": "{D0356BE8-CA59-42D0-BABC-7C95FFDC0E5E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -347.113, + 18.869, + 387.625 + ], + "size": [ + 95.297, + 29.372, + 52.645 + ], + "groundY": 4.183, + "roofY": 33.555, + "wallCount": 154, + "roofCount": 183 + }, + { + "id": "sion_1501", + "uuid": "{BF5746AA-34D3-4675-A880-017213D963C1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 482.145, + 223.196, + -1456.011 + ], + "size": [ + 47.07, + 16.534, + 34.584 + ], + "groundY": 214.929, + "roofY": 231.463, + "wallCount": 30, + "roofCount": 23 + }, + { + "id": "sion_1502", + "uuid": "{C8027298-1DF8-4106-9556-AA7D4490511C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 1 + ], + "center": [ + 689.367, + 44.198, + -873.336 + ], + "size": [ + 11.695, + 8.116, + 23.574 + ], + "groundY": 40.14, + "roofY": 48.256, + "wallCount": 42, + "roofCount": 9 + }, + { + "id": "sion_1503", + "uuid": "{54D1BDD1-5A47-4FC3-95D4-21AB4FF3DF39}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -35.377, + 78.108, + -934.463 + ], + "size": [ + 18.902, + 18.851, + 32.91 + ], + "groundY": 68.683, + "roofY": 87.534, + "wallCount": 20, + "roofCount": 25 + }, + { + "id": "sion_1504", + "uuid": "{4645CE4E-9145-48BC-AEFD-BBB03E37DA3F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 821.506, + 7.781, + 421.12 + ], + "size": [ + 10.426, + 9.246, + 9.221 + ], + "groundY": 3.158, + "roofY": 12.404, + "wallCount": 57, + "roofCount": 2 + }, + { + "id": "sion_1505", + "uuid": "{27916786-6A8D-43C7-90B7-30B3F6FFE86D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1065.232, + 11.611, + 234.136 + ], + "size": [ + 34.832, + 15.109, + 34.138 + ], + "groundY": 4.057, + "roofY": 19.166, + "wallCount": 63, + "roofCount": 24 + }, + { + "id": "sion_1506", + "uuid": "{AE9E1D85-B797-4685-A43B-1B63B8C345BF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 0 + ], + "center": [ + 1074.875, + 10.294, + -1093.668 + ], + "size": [ + 57.422, + 10.381, + 55.771 + ], + "groundY": 5.103, + "roofY": 15.484, + "wallCount": 38, + "roofCount": 16 + }, + { + "id": "sion_1507", + "uuid": "{A9185167-0F99-49D7-92D7-8737EAA3703C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 64.895, + 61.983, + -748.663 + ], + "size": [ + 28.805, + 13.41, + 26.248 + ], + "groundY": 55.278, + "roofY": 68.688, + "wallCount": 31, + "roofCount": 15 + }, + { + "id": "sion_1508", + "uuid": "{A585213C-0701-47BA-BAE7-10DE02B64314}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -358.955, + 7.437, + 512.377 + ], + "size": [ + 15.754, + 5.15, + 9.154 + ], + "groundY": 4.862, + "roofY": 10.012, + "wallCount": 20, + "roofCount": 2 + }, + { + "id": "sion_1509", + "uuid": "{8CCF369F-0992-42F3-833E-5B8AE9D9D5B4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -87.951, + 71.117, + -758.806 + ], + "size": [ + 16.02, + 19.684, + 14.156 + ], + "groundY": 61.275, + "roofY": 80.959, + "wallCount": 67, + "roofCount": 81 + }, + { + "id": "sion_1510", + "uuid": "{0BDE05D8-BBBB-4728-961A-D2926D5779F3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 332.535, + 19.925, + 121.216 + ], + "size": [ + 35.703, + 24.21, + 30.768 + ], + "groundY": 7.82, + "roofY": 32.03, + "wallCount": 42, + "roofCount": 13 + }, + { + "id": "sion_1511", + "uuid": "{2333E4F7-7F06-4F58-B25F-F63AAD2191BA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 411.223, + 93.956, + -1076.316 + ], + "size": [ + 22.742, + 7.86, + 11.679 + ], + "groundY": 90.026, + "roofY": 97.886, + "wallCount": 46, + "roofCount": 14 + }, + { + "id": "sion_1512", + "uuid": "{74DC5BAA-2970-4A29-9E77-E136A5649226}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 836.662, + 14.404, + -347.814 + ], + "size": [ + 21.676, + 22.268, + 15.923 + ], + "groundY": 3.27, + "roofY": 25.538, + "wallCount": 104, + "roofCount": 31 + }, + { + "id": "sion_1513", + "uuid": "{CF43E5C1-A235-419B-B5D2-F0A9E4FB7285}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1481.18, + 16.112, + 29.308 + ], + "size": [ + 23.383, + 15.61, + 41.172 + ], + "groundY": 8.307, + "roofY": 23.916, + "wallCount": 26, + "roofCount": 30 + }, + { + "id": "sion_1514", + "uuid": "{3396500E-35A3-488B-8BC9-D91237545849}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 938.08, + 7.528, + 188.243 + ], + "size": [ + 18.418, + 6.644, + 19.668 + ], + "groundY": 4.206, + "roofY": 10.85, + "wallCount": 12, + "roofCount": 2 + }, + { + "id": "sion_1515", + "uuid": "{BE4E76CB-FE03-4CB2-9E02-471BD7F7C9D7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -181.213, + 79.29, + -954.702 + ], + "size": [ + 11.941, + 15.144, + 14.49 + ], + "groundY": 71.718, + "roofY": 86.862, + "wallCount": 45, + "roofCount": 46 + }, + { + "id": "sion_1516", + "uuid": "{11210E62-3F65-47EA-8E2C-CAC6EA86178B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -253.619, + 26.962, + 214.357 + ], + "size": [ + 23.035, + 24.156, + 19.61 + ], + "groundY": 14.884, + "roofY": 39.04, + "wallCount": 66, + "roofCount": 73 + }, + { + "id": "sion_1517", + "uuid": "{FB181C8A-A456-4C59-9EAB-0AEB242674A5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 345.945, + 14.225, + 162.217 + ], + "size": [ + 17.18, + 13.093, + 17.29 + ], + "groundY": 7.679, + "roofY": 20.772, + "wallCount": 13, + "roofCount": 18 + }, + { + "id": "sion_1518", + "uuid": "{A1EB1532-B9D3-4C40-BD00-19571856BBFE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 803.736, + 8.998, + 572.032 + ], + "size": [ + 23.84, + 8.986, + 24.196 + ], + "groundY": 4.505, + "roofY": 13.491, + "wallCount": 30, + "roofCount": 7 + }, + { + "id": "sion_1519", + "uuid": "{DAFD0B6F-2A15-4CC2-8A5E-8FBB738BA76F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -65.389, + 60.026, + -579.584 + ], + "size": [ + 29.957, + 20.91, + 34.393 + ], + "groundY": 49.571, + "roofY": 70.481, + "wallCount": 32, + "roofCount": 17 + }, + { + "id": "sion_1520", + "uuid": "{DE824821-50B2-4283-B8E4-CB17F73B8F1D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -104.357, + 34.588, + -63.588 + ], + "size": [ + 51.23, + 23.037, + 58.08 + ], + "groundY": 23.07, + "roofY": 46.106, + "wallCount": 206, + "roofCount": 128 + }, + { + "id": "sion_1521", + "uuid": "{D91B59AB-3DD9-44E0-A5D9-A7EFED8C230E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 477.779, + 218.507, + -1329.62 + ], + "size": [ + 19.949, + 12.021, + 18.113 + ], + "groundY": 212.497, + "roofY": 224.518, + "wallCount": 44, + "roofCount": 23 + }, + { + "id": "sion_1522", + "uuid": "{9759B46C-9782-4A38-8F7D-D7BBD5260B15}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 221.861, + 185.418, + -1490.767 + ], + "size": [ + 23.02, + 7.678, + 16.886 + ], + "groundY": 181.579, + "roofY": 189.257, + "wallCount": 36, + "roofCount": 22 + }, + { + "id": "sion_1523", + "uuid": "{17AA068B-61B9-499B-9B61-AC1A1FAC8B3C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -27.049, + 65.994, + -243.751 + ], + "size": [ + 25.113, + 18.285, + 32.104 + ], + "groundY": 56.852, + "roofY": 75.137, + "wallCount": 96, + "roofCount": 46 + }, + { + "id": "sion_1524", + "uuid": "{B9A925B1-0173-4471-8B5F-A43EB7ACE157}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 67.283, + 26.342, + 124.124 + ], + "size": [ + 69.199, + 23.919, + 70.356 + ], + "groundY": 14.383, + "roofY": 38.302, + "wallCount": 72, + "roofCount": 61 + }, + { + "id": "sion_1525", + "uuid": "{30C5A5F5-F199-4DA1-8370-4EB236DC0656}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -323.018, + 75.887, + -816.681 + ], + "size": [ + 73.418, + 25.271, + 52.576 + ], + "groundY": 63.251, + "roofY": 88.522, + "wallCount": 197, + "roofCount": 140 + }, + { + "id": "sion_1526", + "uuid": "{961082D9-444B-4312-B056-5D1D1AAF3F0C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 268.791, + 9.953, + 458.693 + ], + "size": [ + 44.863, + 11.774, + 28.013 + ], + "groundY": 4.066, + "roofY": 15.84, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1527", + "uuid": "{22F19D2A-5C63-42EC-963B-82F520B1B1BD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -215.434, + 58.13, + -603.182 + ], + "size": [ + 14.102, + 15.837, + 14.151 + ], + "groundY": 50.212, + "roofY": 66.048, + "wallCount": 35, + "roofCount": 32 + }, + { + "id": "sion_1528", + "uuid": "{CF6059BE-D230-4A71-8A96-8AAD51BBCB0A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1346.221, + 15.62, + 257.601 + ], + "size": [ + 48.012, + 14.866, + 15.79 + ], + "groundY": 8.187, + "roofY": 23.053, + "wallCount": 18, + "roofCount": 32 + }, + { + "id": "sion_1529", + "uuid": "{57D900BD-A280-4829-AD9D-B2760D6D91F7}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 5, + 2 + ], + "center": [ + 1434.303, + 15.58, + -127.959 + ], + "size": [ + 24.207, + 18.098, + 29.492 + ], + "groundY": 6.531, + "roofY": 24.629, + "wallCount": 36, + "roofCount": 6 + }, + { + "id": "sion_1530", + "uuid": "{405364F7-CBA0-444E-A5C2-10783EE81297}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 74.654, + 63.278, + -788.813 + ], + "size": [ + 14.191, + 10.263, + 13.308 + ], + "groundY": 58.147, + "roofY": 68.41, + "wallCount": 17, + "roofCount": 9 + }, + { + "id": "sion_1531", + "uuid": "{C76C7B24-1C6B-477B-82D7-AF0076ED14D4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 350.479, + 94.321, + -1064.66 + ], + "size": [ + 13.269, + 9.338, + 8.75 + ], + "groundY": 89.652, + "roofY": 98.99, + "wallCount": 43, + "roofCount": 10 + }, + { + "id": "sion_1532", + "uuid": "{A4CE49EB-FFB1-4783-BA9A-367A62962DF2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -348.111, + 34.548, + -176.635 + ], + "size": [ + 26.285, + 9.977, + 14.662 + ], + "groundY": 29.559, + "roofY": 39.536, + "wallCount": 18, + "roofCount": 18 + }, + { + "id": "sion_1533", + "uuid": "{473104FF-6C48-4FE4-9348-B0412BD4B272}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -174.545, + 66.585, + -763.994 + ], + "size": [ + 15.738, + 13.51, + 12.63 + ], + "groundY": 59.83, + "roofY": 73.34, + "wallCount": 47, + "roofCount": 23 + }, + { + "id": "sion_1534", + "uuid": "{CBCE1BEC-8DC7-4B65-9AAB-AA894B4D8AC5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -68.291, + 70.371, + -328.651 + ], + "size": [ + 82.238, + 23.733, + 63.373 + ], + "groundY": 58.504, + "roofY": 82.237, + "wallCount": 115, + "roofCount": 26 + }, + { + "id": "sion_1535", + "uuid": "{5A663B7B-6D96-484D-A8E4-9B187BC885A0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 1 + ], + "center": [ + 936.855, + 21.314, + -530.763 + ], + "size": [ + 56.695, + 35.22, + 53.452 + ], + "groundY": 3.704, + "roofY": 38.924, + "wallCount": 52, + "roofCount": 14 + }, + { + "id": "sion_1536", + "uuid": "{6A6DC013-F993-4C77-B552-0DE24D412AD1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1106.92, + 9.235, + 195.826 + ], + "size": [ + 15.801, + 8.589, + 14.5 + ], + "groundY": 4.94, + "roofY": 13.529, + "wallCount": 39, + "roofCount": 21 + }, + { + "id": "sion_1537", + "uuid": "{2587D2D3-117C-4CBD-B4F3-331ADAB20A03}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 1 + ], + "center": [ + 1336.908, + 8.529, + -684.818 + ], + "size": [ + 25.746, + 7.724, + 22.364 + ], + "groundY": 4.667, + "roofY": 12.391, + "wallCount": 27, + "roofCount": 12 + }, + { + "id": "sion_1538", + "uuid": "{43814612-A5F4-4A2F-9F55-1F8810D8FE22}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -217.109, + 56.564, + -552.574 + ], + "size": [ + 17.727, + 21.214, + 13.802 + ], + "groundY": 45.957, + "roofY": 67.171, + "wallCount": 70, + "roofCount": 24 + }, + { + "id": "sion_1539", + "uuid": "{F87E18FD-E28F-46AF-9A4B-7BA5B5DDADA0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 968.061, + 13.031, + 419.073 + ], + "size": [ + 21.629, + 19.629, + 21.826 + ], + "groundY": 3.217, + "roofY": 22.846, + "wallCount": 50, + "roofCount": 32 + }, + { + "id": "sion_1540", + "uuid": "{CA13A583-21F7-4087-A329-E3D9B18930DE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 985.682, + 13.696, + 470.249 + ], + "size": [ + 36.66, + 17.965, + 30.537 + ], + "groundY": 4.713, + "roofY": 22.678, + "wallCount": 46, + "roofCount": 21 + }, + { + "id": "sion_1541", + "uuid": "{55A46B6D-BDA6-45FF-8C45-B40A65AC875D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 995.529, + 11.965, + 421.981 + ], + "size": [ + 19.621, + 16.701, + 18.036 + ], + "groundY": 3.614, + "roofY": 20.315, + "wallCount": 45, + "roofCount": 18 + }, + { + "id": "sion_1542", + "uuid": "{9578D88C-5A39-46E4-98C6-A2E52AABB5E8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1288.23, + 12.723, + 318.308 + ], + "size": [ + 30.984, + 10.436, + 11.618 + ], + "groundY": 7.505, + "roofY": 17.941, + "wallCount": 24, + "roofCount": 21 + }, + { + "id": "sion_1543", + "uuid": "{94F6B88E-7BEE-4A8D-A4C0-C3E402AC4E78}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -239.738, + 17.894, + 381.184 + ], + "size": [ + 26.852, + 22.752, + 21.694 + ], + "groundY": 6.518, + "roofY": 29.27, + "wallCount": 25, + "roofCount": 17 + }, + { + "id": "sion_1544", + "uuid": "{B231ED03-F5E1-4917-9563-9BABDF06BAFA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 427.988, + 8.311, + 384.898 + ], + "size": [ + 14.141, + 8.017, + 37.126 + ], + "groundY": 4.302, + "roofY": 12.319, + "wallCount": 30, + "roofCount": 8 + }, + { + "id": "sion_1545", + "uuid": "{FA813B37-8D9C-4DBC-AE07-D3CBC28F1520}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 666.916, + 4.556, + 200.247 + ], + "size": [ + 11.715, + 4.86, + 15.135 + ], + "groundY": 2.126, + "roofY": 6.986, + "wallCount": 14, + "roofCount": 2 + }, + { + "id": "sion_1546", + "uuid": "{B5C9CBF1-2127-459F-8677-259B76C6EF1D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1489.645, + 15.951, + 385.115 + ], + "size": [ + 45.461, + 20.294, + 17.868 + ], + "groundY": 5.804, + "roofY": 26.098, + "wallCount": 69, + "roofCount": 28 + }, + { + "id": "sion_1547", + "uuid": "{9A9DBFC1-5398-4335-AB9F-B7B7B5B1098A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -153.705, + 37.352, + -88.698 + ], + "size": [ + 50.871, + 22.96, + 80.33 + ], + "groundY": 25.872, + "roofY": 48.832, + "wallCount": 226, + "roofCount": 166 + }, + { + "id": "sion_1548", + "uuid": "{2A7D5925-1872-48C4-8289-EAF3BF3E57E1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 4 + ], + "center": [ + 1033.336, + 9.267, + 783.671 + ], + "size": [ + 23.812, + 8.536, + 17.092 + ], + "groundY": 4.999, + "roofY": 13.535, + "wallCount": 31, + "roofCount": 19 + }, + { + "id": "sion_1549", + "uuid": "{3C9AAEF1-6130-4D1C-A868-A4EEC128805C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -279.268, + 21.287, + 331.372 + ], + "size": [ + 28.699, + 23.401, + 19.04 + ], + "groundY": 9.586, + "roofY": 32.987, + "wallCount": 32, + "roofCount": 18 + }, + { + "id": "sion_1550", + "uuid": "{75E40156-F0E7-46AB-A8E3-00CC7EB71B57}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -307.32, + 57.993, + -561.202 + ], + "size": [ + 18.109, + 14.309, + 18.393 + ], + "groundY": 50.839, + "roofY": 65.148, + "wallCount": 10, + "roofCount": 18 + }, + { + "id": "sion_1551", + "uuid": "{0E949BDF-84CF-4EB8-ABE9-2EDBE5362666}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 150.668, + 78.152, + -382.799 + ], + "size": [ + 3.602, + 5.208, + 4.422 + ], + "groundY": 75.548, + "roofY": 80.756, + "wallCount": 62, + "roofCount": 20 + }, + { + "id": "sion_1552", + "uuid": "{26E913F0-DC3D-42BA-9809-9391B73BDAFB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 132.699, + 6.656, + 532.197 + ], + "size": [ + 36.859, + 8.092, + 19.356 + ], + "groundY": 2.61, + "roofY": 10.702, + "wallCount": 28, + "roofCount": 33 + }, + { + "id": "sion_1553", + "uuid": "{877DBB1D-A1EA-45AF-8446-5EB7F23BF78E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -26.992, + 4.685, + 796.254 + ], + "size": [ + 51.219, + 8.736, + 44.21 + ], + "groundY": 0.317, + "roofY": 9.053, + "wallCount": 24, + "roofCount": 8 + }, + { + "id": "sion_1554", + "uuid": "{B4CD2AEA-54A6-48D2-A57B-FFEB48874723}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 443.932, + 215.71, + -1491.923 + ], + "size": [ + 13.512, + 7.258, + 21.458 + ], + "groundY": 212.081, + "roofY": 219.339, + "wallCount": 37, + "roofCount": 31 + }, + { + "id": "sion_1555", + "uuid": "{1F610BBA-A9C5-4632-AF20-124B43F83984}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -190.166, + 38.846, + -114.984 + ], + "size": [ + 17.684, + 21.673, + 19.397 + ], + "groundY": 28.009, + "roofY": 49.682, + "wallCount": 16, + "roofCount": 16 + }, + { + "id": "sion_1556", + "uuid": "{85DE49EB-8550-4A3F-9ED3-44901D2507CB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 350.146, + 72.418, + -925.019 + ], + "size": [ + 25.816, + 13.929, + 16.124 + ], + "groundY": 65.454, + "roofY": 79.383, + "wallCount": 66, + "roofCount": 27 + }, + { + "id": "sion_1557", + "uuid": "{C1F317D4-4CCF-44FE-905B-0B374E1FD8C1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -224.85, + 10.261, + 808.896 + ], + "size": [ + 68.418, + 22.796, + 57.513 + ], + "groundY": -1.137, + "roofY": 21.659, + "wallCount": 64, + "roofCount": 67 + }, + { + "id": "sion_1558", + "uuid": "{3A538E26-856C-48CE-ABB4-4EAA38A3EF5A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 103.822, + 6.054, + 693.226 + ], + "size": [ + 16.152, + 9.505, + 22.561 + ], + "groundY": 1.301, + "roofY": 10.806, + "wallCount": 32, + "roofCount": 5 + }, + { + "id": "sion_1559", + "uuid": "{CE05B55F-7470-4D81-A54C-37C6C49DBC51}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 155.248, + 63.833, + -829.922 + ], + "size": [ + 16.91, + 11.81, + 14.355 + ], + "groundY": 57.928, + "roofY": 69.738, + "wallCount": 21, + "roofCount": 11 + }, + { + "id": "sion_1560", + "uuid": "{C2EE2C37-7629-417E-A876-E1AA9C648DE8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 3 + ], + "center": [ + -15.275, + 20.276, + 190.326 + ], + "size": [ + 107.332, + 14.699, + 72.338 + ], + "groundY": 12.927, + "roofY": 27.626, + "wallCount": 159, + "roofCount": 82 + }, + { + "id": "sion_1561", + "uuid": "{57DE203A-FD3C-4B80-ABCD-F7D26B7A5D9E}", + "name": "", + "class": "Flugdach", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 854.252, + 8.642, + 406.713 + ], + "size": [ + 32.777, + 8.174, + 29.23 + ], + "groundY": 4.555, + "roofY": 12.729, + "wallCount": 11, + "roofCount": 8 + }, + { + "id": "sion_1562", + "uuid": "{9836D1ED-2B36-4F05-90E0-AF89427DAC09}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 717.75, + 22.521, + -275.526 + ], + "size": [ + 27.805, + 36.257, + 23.888 + ], + "groundY": 4.393, + "roofY": 40.65, + "wallCount": 253, + "roofCount": 20 + }, + { + "id": "sion_1563", + "uuid": "{4E64E220-4C5F-4C65-BA40-871A8C115F45}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -95.098, + 92.103, + -1172.61 + ], + "size": [ + 18.359, + 11.286, + 14.644 + ], + "groundY": 86.46, + "roofY": 97.746, + "wallCount": 50, + "roofCount": 44 + }, + { + "id": "sion_1564", + "uuid": "{D20C3B49-7221-4C02-902A-C880AB961D1A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 265.352, + 56.951, + -772.674 + ], + "size": [ + 16.602, + 10.871, + 22.816 + ], + "groundY": 51.516, + "roofY": 62.387, + "wallCount": 40, + "roofCount": 37 + }, + { + "id": "sion_1565", + "uuid": "{ED418114-2E68-4149-A866-5F3CA14FE81D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 729.959, + 14.881, + 1012.305 + ], + "size": [ + 10.27, + 6.361, + 10.3 + ], + "groundY": 11.7, + "roofY": 18.061, + "wallCount": 51, + "roofCount": 20 + }, + { + "id": "sion_1566", + "uuid": "{2BB62266-CEEE-4CBC-9538-10B5437B512B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 316.381, + 5.692, + 1033.279 + ], + "size": [ + 18.527, + 7.103, + 18.976 + ], + "groundY": 2.14, + "roofY": 9.243, + "wallCount": 19, + "roofCount": 29 + }, + { + "id": "sion_1567", + "uuid": "{334B3B17-DBA6-4F94-A183-348558E4361A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 664.062, + 9.92, + 933.261 + ], + "size": [ + 44.781, + 11.8, + 87.869 + ], + "groundY": 4.02, + "roofY": 15.82, + "wallCount": 61, + "roofCount": 38 + }, + { + "id": "sion_1568", + "uuid": "{724F3E24-BF9F-45B4-BE4C-C5B4BC6FFC3E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 32.566, + 72.815, + -885.992 + ], + "size": [ + 38.039, + 20.124, + 29.362 + ], + "groundY": 62.753, + "roofY": 82.877, + "wallCount": 79, + "roofCount": 29 + }, + { + "id": "sion_1569", + "uuid": "{6A7E8CE1-D2BA-4A9A-A3E4-F670B98DFF41}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1148.582, + 14.029, + 295.524 + ], + "size": [ + 30.711, + 18.274, + 32.864 + ], + "groundY": 4.892, + "roofY": 23.166, + "wallCount": 91, + "roofCount": 26 + }, + { + "id": "sion_1570", + "uuid": "{405AD8E0-4FA4-469F-A3FA-30A892B97218}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -131.621, + 65.026, + -723.431 + ], + "size": [ + 22.625, + 16.316, + 19.811 + ], + "groundY": 56.868, + "roofY": 73.184, + "wallCount": 12, + "roofCount": 35 + }, + { + "id": "sion_1571", + "uuid": "{8E444B06-CB36-4F6F-A3FE-22D9B0B91E43}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 274.562, + 205.044, + -1376.443 + ], + "size": [ + 20.859, + 9.756, + 21.727 + ], + "groundY": 200.166, + "roofY": 209.922, + "wallCount": 34, + "roofCount": 25 + }, + { + "id": "sion_1572", + "uuid": "{5B8E054D-F6A9-4CAC-BED9-8C2EE90C6F24}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -16.721, + 61.603, + -707.129 + ], + "size": [ + 33.98, + 13.426, + 39.639 + ], + "groundY": 54.89, + "roofY": 68.316, + "wallCount": 38, + "roofCount": 37 + }, + { + "id": "sion_1573", + "uuid": "{BDAD647F-78B7-4E49-88B6-2EAE2E0EC98D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 4 + ], + "center": [ + 1401.688, + 21.854, + 923.718 + ], + "size": [ + 14.359, + 10.614, + 12.622 + ], + "groundY": 16.547, + "roofY": 27.161, + "wallCount": 56, + "roofCount": 27 + }, + { + "id": "sion_1574", + "uuid": "{80B024C3-5F1A-4E0D-B0FE-1DC843C4B236}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -202.471, + 47.394, + -405.241 + ], + "size": [ + 45.348, + 20.56, + 23.044 + ], + "groundY": 37.114, + "roofY": 57.674, + "wallCount": 77, + "roofCount": 94 + }, + { + "id": "sion_1575", + "uuid": "{7231C256-7AE1-401E-B866-85DBBDD31C83}", + "name": "", + "class": "Lagertank", + "archStyle": "industrial", + "tile": [ + 5, + 4 + ], + "center": [ + 1435.875, + 16.887, + 892.391 + ], + "size": [ + 3.492, + 8.602, + 3.485 + ], + "groundY": 12.586, + "roofY": 21.188, + "wallCount": 1, + "roofCount": 3 + }, + { + "id": "sion_1576", + "uuid": "{4BF957BD-7E60-4FDA-9295-96990704D340}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 75.934, + 61.328, + -695.723 + ], + "size": [ + 48.93, + 19.97, + 39.168 + ], + "groundY": 51.343, + "roofY": 71.313, + "wallCount": 14, + "roofCount": 20 + }, + { + "id": "sion_1577", + "uuid": "{00A56440-BB6A-46C7-9ABC-7EEB3E9A2562}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -285.414, + 5.339, + 849.703 + ], + "size": [ + 17.461, + 10.198, + 13.193 + ], + "groundY": 0.24, + "roofY": 10.438, + "wallCount": 20, + "roofCount": 18 + }, + { + "id": "sion_1578", + "uuid": "{BAF1DE84-8961-47E0-8C80-AD514CA89998}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 157.508, + 10.048, + 1026.975 + ], + "size": [ + 52.156, + 13.42, + 49.754 + ], + "groundY": 3.338, + "roofY": 16.758, + "wallCount": 10, + "roofCount": 20 + }, + { + "id": "sion_1579", + "uuid": "{29FED1AE-4E7E-43A4-A5A1-A164B9D12A9D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -48.477, + 7.319, + 758.934 + ], + "size": [ + 24.234, + 15.495, + 21.124 + ], + "groundY": -0.428, + "roofY": 15.066, + "wallCount": 29, + "roofCount": 7 + }, + { + "id": "sion_1580", + "uuid": "{E259E211-8F85-4365-B1A7-7CC973DEE540}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -83.801, + 53.654, + -537.699 + ], + "size": [ + 32.383, + 14.241, + 45.736 + ], + "groundY": 46.534, + "roofY": 60.775, + "wallCount": 64, + "roofCount": 65 + }, + { + "id": "sion_1581", + "uuid": "{68C59F4A-EE4B-48E4-B5A8-51D0BD9A2C15}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 1 + ], + "center": [ + 1363.994, + 7.757, + -664.947 + ], + "size": [ + 5.887, + 5.912, + 5.894 + ], + "groundY": 4.801, + "roofY": 10.713, + "wallCount": 16, + "roofCount": 6 + }, + { + "id": "sion_1582", + "uuid": "{78F138E5-ADD5-415C-8109-0E491949E272}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 224.461, + 60.482, + -832.414 + ], + "size": [ + 17.891, + 9.806, + 12.592 + ], + "groundY": 55.579, + "roofY": 65.385, + "wallCount": 35, + "roofCount": 6 + }, + { + "id": "sion_1583", + "uuid": "{67B1F16B-C3A0-40D3-9C48-F08904678E26}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 472.436, + 15.367, + 198.459 + ], + "size": [ + 18.527, + 21.94, + 31.268 + ], + "groundY": 4.397, + "roofY": 26.337, + "wallCount": 54, + "roofCount": 6 + }, + { + "id": "sion_1584", + "uuid": "{E7FF7D19-CB27-437B-910C-D87D92E1496F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -88.135, + 14.573, + 655.895 + ], + "size": [ + 167.379, + 28.734, + 181.452 + ], + "groundY": 0.206, + "roofY": 28.94, + "wallCount": 131, + "roofCount": 63 + }, + { + "id": "sion_1585", + "uuid": "{2F86D91A-E28D-4421-9CE6-1C3B4BCD7B83}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 359.943, + 10.921, + 283.179 + ], + "size": [ + 56.332, + 8.567, + 46.908 + ], + "groundY": 6.638, + "roofY": 15.204, + "wallCount": 22, + "roofCount": 9 + }, + { + "id": "sion_1586", + "uuid": "{D50DE1B8-B7F1-422D-8919-A9811803E1B0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -323.15, + 20.737, + 341.863 + ], + "size": [ + 24.504, + 23.085, + 38.922 + ], + "groundY": 9.194, + "roofY": 32.279, + "wallCount": 67, + "roofCount": 22 + }, + { + "id": "sion_1587", + "uuid": "{3CEAC42E-1AD3-40C6-9C4E-2D499F478EB7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -16.137, + 33.88, + -15.015 + ], + "size": [ + 68.047, + 26.407, + 58.61 + ], + "groundY": 20.677, + "roofY": 47.084, + "wallCount": 109, + "roofCount": 109 + }, + { + "id": "sion_1588", + "uuid": "{87FA8524-7717-46CD-84F5-A83D5FBB575A}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 3, + 1 + ], + "center": [ + 323.463, + 144.72, + -523.954 + ], + "size": [ + 7.02, + 50.001, + 4.958 + ], + "groundY": 119.72, + "roofY": 169.721, + "wallCount": 63, + "roofCount": 41 + }, + { + "id": "sion_1589", + "uuid": "{74737D53-8FBB-4CE5-9DDF-3F0D0D9DE733}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -113.455, + 88.602, + -1019.489 + ], + "size": [ + 14.293, + 11.765, + 11.012 + ], + "groundY": 82.719, + "roofY": 94.484, + "wallCount": 26, + "roofCount": 26 + }, + { + "id": "sion_1590", + "uuid": "{54CBE97B-95CD-41F7-88CF-58B4F207925B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 872.688, + 8.476, + -311.407 + ], + "size": [ + 22.32, + 10.833, + 18.292 + ], + "groundY": 3.059, + "roofY": 13.892, + "wallCount": 39, + "roofCount": 18 + }, + { + "id": "sion_1591", + "uuid": "{54438023-2B72-46BF-8194-95344D580529}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 851.539, + 11.885, + -380.91 + ], + "size": [ + 22.188, + 16.906, + 18.641 + ], + "groundY": 3.432, + "roofY": 20.338, + "wallCount": 114, + "roofCount": 35 + }, + { + "id": "sion_1592", + "uuid": "{F20D7CA8-3661-4171-8F75-B58E928AECEF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 336.432, + 80.051, + -994.628 + ], + "size": [ + 26.356, + 11.757, + 18.529 + ], + "groundY": 74.173, + "roofY": 85.93, + "wallCount": 36, + "roofCount": 14 + }, + { + "id": "sion_1593", + "uuid": "{F05EC607-BAC2-4EEE-A848-B166E473F148}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -134.686, + 37.422, + -118.515 + ], + "size": [ + 50.699, + 22.103, + 50.483 + ], + "groundY": 26.371, + "roofY": 48.474, + "wallCount": 221, + "roofCount": 148 + }, + { + "id": "sion_1594", + "uuid": "{8F70E6AF-5A5E-4906-93DC-BF1072BCA1AD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 199.475, + 8.265, + 951.543 + ], + "size": [ + 13.387, + 9.904, + 13.111 + ], + "groundY": 3.313, + "roofY": 13.217, + "wallCount": 40, + "roofCount": 27 + }, + { + "id": "sion_1595", + "uuid": "{A35E7376-7A7D-4CF3-824E-CACC47BBB79C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 430.311, + 8.126, + 884.233 + ], + "size": [ + 28.895, + 11.382, + 53.534 + ], + "groundY": 2.435, + "roofY": 13.817, + "wallCount": 38, + "roofCount": 21 + }, + { + "id": "sion_1596", + "uuid": "{1B0D4AB9-2F2F-4CB4-AD00-425B7F0EAADE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 393.272, + 10.257, + 371.976 + ], + "size": [ + 48.723, + 13.4, + 64.407 + ], + "groundY": 3.557, + "roofY": 16.957, + "wallCount": 68, + "roofCount": 67 + }, + { + "id": "sion_1597", + "uuid": "{68BDFE47-F033-4057-B997-22644698B420}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -102.689, + 47.914, + -445.047 + ], + "size": [ + 13.887, + 7.957, + 17.846 + ], + "groundY": 43.935, + "roofY": 51.892, + "wallCount": 65, + "roofCount": 32 + }, + { + "id": "sion_1598", + "uuid": "{FEDD0988-80F2-449D-AA31-CF0EBB106E7C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 869.438, + 15.426, + 82.238 + ], + "size": [ + 48.664, + 24.82, + 62.126 + ], + "groundY": 3.016, + "roofY": 27.836, + "wallCount": 8, + "roofCount": 7 + }, + { + "id": "sion_1599", + "uuid": "{984BCF8F-D23E-4ECC-B8AC-6CCE644C7C2B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 16.09, + 36.119, + 46.774 + ], + "size": [ + 103.773, + 36.826, + 96.896 + ], + "groundY": 17.706, + "roofY": 54.532, + "wallCount": 108, + "roofCount": 35 + }, + { + "id": "sion_1600", + "uuid": "{33BC99E7-AC8D-4FB1-87F5-AD7ABE36CF1E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 431.051, + 16.853, + 28.807 + ], + "size": [ + 106.883, + 28.002, + 126.235 + ], + "groundY": 2.852, + "roofY": 30.854, + "wallCount": 84, + "roofCount": 34 + }, + { + "id": "sion_1601", + "uuid": "{0A7B6DB8-BB1C-4885-8ECE-A7FCB0DDDF9A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 494.768, + 126.991, + -1154.776 + ], + "size": [ + 8.746, + 8.75, + 7.326 + ], + "groundY": 122.616, + "roofY": 131.366, + "wallCount": 40, + "roofCount": 18 + }, + { + "id": "sion_1602", + "uuid": "{87E1E412-96FA-4498-9B4D-5AFC15361E4C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -391.129, + 19.722, + 336.61 + ], + "size": [ + 120.742, + 27.882, + 71.168 + ], + "groundY": 5.781, + "roofY": 33.663, + "wallCount": 205, + "roofCount": 173 + }, + { + "id": "sion_1603", + "uuid": "{A25A001F-501A-4CF5-8A24-377819A23EC8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 192.98, + 60.41, + -650.229 + ], + "size": [ + 24.898, + 10.03, + 15.315 + ], + "groundY": 55.395, + "roofY": 65.425, + "wallCount": 30, + "roofCount": 19 + }, + { + "id": "sion_1604", + "uuid": "{47B11935-CA6F-4AE7-A217-3E352310C9B1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 353.728, + 19.239, + -142.851 + ], + "size": [ + 18.293, + 24.148, + 18.244 + ], + "groundY": 7.165, + "roofY": 31.313, + "wallCount": 20, + "roofCount": 14 + }, + { + "id": "sion_1605", + "uuid": "{2DE60B06-5DFF-4C82-9DD0-FEAA5B77251A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 0 + ], + "center": [ + 1346.902, + 24.538, + -1334.704 + ], + "size": [ + 5.484, + 8.443, + 5.7 + ], + "groundY": 20.317, + "roofY": 28.76, + "wallCount": 31, + "roofCount": 16 + }, + { + "id": "sion_1606", + "uuid": "{F5726269-D3C2-4A49-BEC0-0408F3E67D48}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1391.484, + 16.042, + 223.536 + ], + "size": [ + 61.586, + 14.988, + 17.052 + ], + "groundY": 8.548, + "roofY": 23.536, + "wallCount": 12, + "roofCount": 33 + }, + { + "id": "sion_1607", + "uuid": "{BE2A59E5-B28C-4CA7-B1E8-C09619FDE5EB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 237.025, + 194.293, + -1508.876 + ], + "size": [ + 14.09, + 12.2, + 16.121 + ], + "groundY": 188.193, + "roofY": 200.393, + "wallCount": 81, + "roofCount": 20 + }, + { + "id": "sion_1608", + "uuid": "{99616B5A-E78A-4271-85EC-4E413E95A67F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -42.156, + 18.203, + 295.234 + ], + "size": [ + 16.016, + 14.846, + 13.483 + ], + "groundY": 10.78, + "roofY": 25.626, + "wallCount": 53, + "roofCount": 30 + }, + { + "id": "sion_1609", + "uuid": "{09578D72-A494-4674-A84D-6EBD50EA46FC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 479.273, + 15.7, + 146.237 + ], + "size": [ + 26.492, + 22.106, + 53.017 + ], + "groundY": 4.647, + "roofY": 26.753, + "wallCount": 109, + "roofCount": 24 + }, + { + "id": "sion_1610", + "uuid": "{265C05FF-4F2D-4580-8D6E-750D4B1D6084}", + "name": "", + "class": "Unterirdisches Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 819.1, + 11.071, + -272.483 + ], + "size": [ + 44.41, + 17.13, + 54.179 + ], + "groundY": 2.506, + "roofY": 19.636, + "wallCount": 60, + "roofCount": 24 + }, + { + "id": "sion_1611", + "uuid": "{0AF002E7-9E42-49D1-AE58-FFEDAF967BF9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 347.326, + 67.8, + -880.814 + ], + "size": [ + 22.402, + 10.079, + 21.368 + ], + "groundY": 62.76, + "roofY": 72.839, + "wallCount": 41, + "roofCount": 25 + }, + { + "id": "sion_1612", + "uuid": "{42D53C0D-949D-4A95-9E9C-3657A25D497C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 353.033, + 215.601, + -1380.165 + ], + "size": [ + 16.191, + 12.359, + 17.262 + ], + "groundY": 209.422, + "roofY": 221.781, + "wallCount": 31, + "roofCount": 12 + }, + { + "id": "sion_1613", + "uuid": "{D91944B8-D4B5-45CD-BF3A-3D9CF2344632}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 847.621, + 9.059, + 681.371 + ], + "size": [ + 49.883, + 9.13, + 48.984 + ], + "groundY": 4.494, + "roofY": 13.624, + "wallCount": 21, + "roofCount": 4 + }, + { + "id": "sion_1614", + "uuid": "{B380CEE3-AEAA-4D58-B610-73DD8C7A8782}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 392.857, + 16.872, + 168.111 + ], + "size": [ + 31.652, + 22.264, + 30.492 + ], + "groundY": 5.74, + "roofY": 28.004, + "wallCount": 71, + "roofCount": 28 + }, + { + "id": "sion_1615", + "uuid": "{DBA6B12C-DB20-47F1-B289-007BCC2C1922}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1212.961, + 13.796, + 226.132 + ], + "size": [ + 20.578, + 16.896, + 37.038 + ], + "groundY": 5.348, + "roofY": 22.244, + "wallCount": 32, + "roofCount": 39 + }, + { + "id": "sion_1616", + "uuid": "{58D01AB7-DAB8-46DB-A97A-7EA7B144182D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 481.629, + 225.066, + -1419.401 + ], + "size": [ + 23.75, + 17.369, + 21.983 + ], + "groundY": 216.382, + "roofY": 233.751, + "wallCount": 49, + "roofCount": 17 + }, + { + "id": "sion_1617", + "uuid": "{1277D6E3-F735-4DF8-97AF-C32E6D4F63E8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -177.016, + 60.511, + -651.367 + ], + "size": [ + 24.297, + 20.083, + 28.316 + ], + "groundY": 50.47, + "roofY": 70.553, + "wallCount": 41, + "roofCount": 20 + }, + { + "id": "sion_1618", + "uuid": "{93DD3605-4A8D-4F6A-A49E-EA7390166159}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 996.139, + 13.241, + 283.897 + ], + "size": [ + 29.887, + 19.204, + 33.063 + ], + "groundY": 3.639, + "roofY": 22.842, + "wallCount": 36, + "roofCount": 7 + }, + { + "id": "sion_1619", + "uuid": "{C326F39A-1231-479C-ADC2-B1E85FB12A3B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1063.852, + 14.405, + 492.948 + ], + "size": [ + 53.391, + 18.524, + 36.924 + ], + "groundY": 5.143, + "roofY": 23.666, + "wallCount": 64, + "roofCount": 27 + }, + { + "id": "sion_1620", + "uuid": "{C94C5B26-0A89-407A-B796-1F0F072813AA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 187.232, + 7.011, + 1048.726 + ], + "size": [ + 11.465, + 8.671, + 10.058 + ], + "groundY": 2.675, + "roofY": 11.346, + "wallCount": 37, + "roofCount": 12 + }, + { + "id": "sion_1621", + "uuid": "{11A44272-5447-4691-8EF8-2B0B3C3CBE96}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 991.229, + 12.263, + 798.155 + ], + "size": [ + 26.629, + 12.618, + 56.136 + ], + "groundY": 5.954, + "roofY": 18.572, + "wallCount": 18, + "roofCount": 19 + }, + { + "id": "sion_1622", + "uuid": "{5C25EFB1-BE87-4980-BC0C-F213C4AB665F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -300.68, + 5.385, + 958.965 + ], + "size": [ + 111.398, + 11.101, + 48.422 + ], + "groundY": -0.165, + "roofY": 10.936, + "wallCount": 26, + "roofCount": 29 + }, + { + "id": "sion_1623", + "uuid": "{50F5CF65-2F31-4657-901C-E50D8BD82BBE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 882.428, + 15.687, + -67.501 + ], + "size": [ + 30.16, + 25.856, + 27.783 + ], + "groundY": 2.759, + "roofY": 28.615, + "wallCount": 46, + "roofCount": 6 + }, + { + "id": "sion_1624", + "uuid": "{36326B67-B6B5-4A85-BE35-B873D66F5075}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1413.947, + 19.385, + 89.475 + ], + "size": [ + 16.191, + 25.859, + 30.397 + ], + "groundY": 6.456, + "roofY": 32.315, + "wallCount": 55, + "roofCount": 10 + }, + { + "id": "sion_1625", + "uuid": "{1A75B455-1CEC-4254-9A5C-89FE642B84B3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -355.576, + 23.092, + 262.22 + ], + "size": [ + 24.48, + 23.103, + 32.218 + ], + "groundY": 11.54, + "roofY": 34.643, + "wallCount": 8, + "roofCount": 15 + }, + { + "id": "sion_1626", + "uuid": "{103C0FAE-6E17-47D2-B311-77E42068FDDB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 118.857, + 66.375, + -813.0 + ], + "size": [ + 25.801, + 17.114, + 22.066 + ], + "groundY": 57.818, + "roofY": 74.931, + "wallCount": 14, + "roofCount": 17 + }, + { + "id": "sion_1627", + "uuid": "{EE4F99BA-5F04-4242-8918-326D6D97C25E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 988.186, + 12.148, + 362.102 + ], + "size": [ + 23.332, + 16.328, + 17.204 + ], + "groundY": 3.984, + "roofY": 20.312, + "wallCount": 71, + "roofCount": 24 + }, + { + "id": "sion_1628", + "uuid": "{0DB992E4-7A0F-4FA8-8E6F-51A87196E450}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1276.07, + 16.742, + 87.755 + ], + "size": [ + 32.867, + 22.758, + 25.382 + ], + "groundY": 5.363, + "roofY": 28.121, + "wallCount": 85, + "roofCount": 23 + }, + { + "id": "sion_1629", + "uuid": "{29764B9D-F6C5-4EEB-88D1-1734554691D7}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 128.645, + 129.411, + -222.362 + ], + "size": [ + 15.227, + 8.417, + 4.742 + ], + "groundY": 125.202, + "roofY": 133.619, + "wallCount": 71, + "roofCount": 12 + }, + { + "id": "sion_1630", + "uuid": "{A9617A2D-C27B-43AA-82BE-AE2735355011}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 275.135, + 54.967, + -730.24 + ], + "size": [ + 14.199, + 7.002, + 14.29 + ], + "groundY": 51.466, + "roofY": 58.468, + "wallCount": 55, + "roofCount": 22 + }, + { + "id": "sion_1631", + "uuid": "{A4909F55-4EA4-42F3-8769-6121F1940C9C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 29.352, + 107.088, + -1334.389 + ], + "size": [ + 16.078, + 10.889, + 20.202 + ], + "groundY": 101.644, + "roofY": 112.533, + "wallCount": 31, + "roofCount": 11 + }, + { + "id": "sion_1632", + "uuid": "{8D0DD86D-0DE7-493E-B196-00B7B8641A67}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 106.834, + 30.286, + 14.737 + ], + "size": [ + 36.816, + 26.72, + 37.231 + ], + "groundY": 16.926, + "roofY": 43.646, + "wallCount": 61, + "roofCount": 66 + }, + { + "id": "sion_1633", + "uuid": "{EBC51DBD-F128-465C-81E0-3BFBF3422D26}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 46.566, + 55.554, + -659.211 + ], + "size": [ + 9.453, + 3.708, + 9.615 + ], + "groundY": 53.7, + "roofY": 57.408, + "wallCount": 13, + "roofCount": 2 + }, + { + "id": "sion_1634", + "uuid": "{E1A3F4F7-E926-4C18-AA1D-A2550BA074AE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 198.139, + 76.095, + -974.876 + ], + "size": [ + 40.465, + 21.838, + 25.926 + ], + "groundY": 65.176, + "roofY": 87.014, + "wallCount": 56, + "roofCount": 23 + }, + { + "id": "sion_1635", + "uuid": "{978B5249-EB98-4529-9BA4-37F39CF99CD6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -292.652, + 68.141, + -771.029 + ], + "size": [ + 13.508, + 10.966, + 11.762 + ], + "groundY": 62.658, + "roofY": 73.624, + "wallCount": 49, + "roofCount": 19 + }, + { + "id": "sion_1636", + "uuid": "{95D10E23-03BB-4A31-AA8F-0EBBC4C62040}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 760.01, + 9.385, + 584.928 + ], + "size": [ + 17.473, + 10.818, + 17.592 + ], + "groundY": 3.976, + "roofY": 14.794, + "wallCount": 23, + "roofCount": 10 + }, + { + "id": "sion_1637", + "uuid": "{50935F62-C359-404E-A588-FB38AC5DEB44}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 62.9, + 73.989, + -935.085 + ], + "size": [ + 30.332, + 19.017, + 23.199 + ], + "groundY": 64.48, + "roofY": 83.497, + "wallCount": 27, + "roofCount": 13 + }, + { + "id": "sion_1638", + "uuid": "{35E06D91-FCBC-4F4A-BC9D-C64E0A67AB5B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -104.557, + 34.578, + 4.893 + ], + "size": [ + 35.762, + 23.095, + 34.976 + ], + "groundY": 23.031, + "roofY": 46.126, + "wallCount": 85, + "roofCount": 89 + }, + { + "id": "sion_1639", + "uuid": "{1418E62B-12DA-4B74-8191-58B688907ED9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1084.574, + 8.932, + 208.173 + ], + "size": [ + 24.008, + 10.348, + 20.852 + ], + "groundY": 3.758, + "roofY": 14.106, + "wallCount": 61, + "roofCount": 35 + }, + { + "id": "sion_1640", + "uuid": "{30AF093C-0924-47AF-BEA0-A48833FBC724}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -183.379, + 77.501, + -932.381 + ], + "size": [ + 12.109, + 15.228, + 14.477 + ], + "groundY": 69.887, + "roofY": 85.116, + "wallCount": 77, + "roofCount": 46 + }, + { + "id": "sion_1641", + "uuid": "{279A7757-A834-461A-97B4-4EB58BDF3E5D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 373.986, + 58.663, + -848.603 + ], + "size": [ + 15.051, + 12.019, + 13.418 + ], + "groundY": 52.653, + "roofY": 64.672, + "wallCount": 42, + "roofCount": 18 + }, + { + "id": "sion_1642", + "uuid": "{85ACD3F1-5B3D-4CDB-BDDF-4CAEB616C71D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 1 + ], + "center": [ + 652.299, + 53.977, + -539.516 + ], + "size": [ + 7.254, + 6.156, + 7.494 + ], + "groundY": 50.899, + "roofY": 57.055, + "wallCount": 26, + "roofCount": 8 + }, + { + "id": "sion_1643", + "uuid": "{A25ACC80-9239-45F2-B660-D86A133D2FA6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -173.496, + 51.927, + -523.094 + ], + "size": [ + 21.383, + 20.572, + 57.706 + ], + "groundY": 41.641, + "roofY": 62.213, + "wallCount": 100, + "roofCount": 138 + }, + { + "id": "sion_1644", + "uuid": "{BB2B5559-A376-4013-AC44-AD79E9241C1A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -62.678, + 69.883, + -796.031 + ], + "size": [ + 16.441, + 14.292, + 11.676 + ], + "groundY": 62.737, + "roofY": 77.029, + "wallCount": 40, + "roofCount": 46 + }, + { + "id": "sion_1645", + "uuid": "{1571E2E2-EFA1-4A46-B3FC-34158361F1C0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 252.436, + 6.874, + 530.59 + ], + "size": [ + 26.793, + 10.029, + 30.12 + ], + "groundY": 1.86, + "roofY": 11.889, + "wallCount": 23, + "roofCount": 17 + }, + { + "id": "sion_1646", + "uuid": "{0C8E954E-C2EA-411B-A97B-A5F78FC3C3D9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 238.572, + 9.036, + 417.972 + ], + "size": [ + 34.613, + 9.268, + 19.974 + ], + "groundY": 4.402, + "roofY": 13.67, + "wallCount": 18, + "roofCount": 4 + }, + { + "id": "sion_1647", + "uuid": "{03040486-8259-4CEF-A651-B6E71A0F85D3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 250.379, + 5.836, + 617.244 + ], + "size": [ + 15.391, + 8.51, + 13.734 + ], + "groundY": 1.581, + "roofY": 10.091, + "wallCount": 32, + "roofCount": 19 + }, + { + "id": "sion_1648", + "uuid": "{11F594B7-606E-4B5B-801D-987766F634F4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -332.766, + 50.347, + -462.373 + ], + "size": [ + 14.719, + 13.143, + 15.949 + ], + "groundY": 43.775, + "roofY": 56.918, + "wallCount": 44, + "roofCount": 40 + }, + { + "id": "sion_1649", + "uuid": "{857315A0-6E98-4326-8A4D-7FC0D3860908}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 862.561, + 8.345, + 618.338 + ], + "size": [ + 58.051, + 8.183, + 63.104 + ], + "groundY": 4.254, + "roofY": 12.437, + "wallCount": 22, + "roofCount": 8 + }, + { + "id": "sion_1650", + "uuid": "{54B35928-2EEA-4C93-8C0D-E3AF0E4283B5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 42.877, + 71.725, + -987.089 + ], + "size": [ + 34.957, + 6.706, + 8.688 + ], + "groundY": 68.372, + "roofY": 75.078, + "wallCount": 60, + "roofCount": 26 + }, + { + "id": "sion_1651", + "uuid": "{6FFECB41-0102-4187-9FF2-DE54CC1E4F97}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 778.711, + 5.639, + 116.879 + ], + "size": [ + 10.68, + 4.844, + 13.414 + ], + "groundY": 3.217, + "roofY": 8.061, + "wallCount": 22, + "roofCount": 2 + }, + { + "id": "sion_1652", + "uuid": "{A0D1D410-4BFC-4D23-94B7-7AD1629845F9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 0 + ], + "center": [ + 1497.639, + 44.713, + -1466.13 + ], + "size": [ + 9.48, + 9.324, + 9.496 + ], + "groundY": 40.051, + "roofY": 49.375, + "wallCount": 30, + "roofCount": 12 + }, + { + "id": "sion_1653", + "uuid": "{632B7CF6-1A09-4B5C-B1E9-03025744E151}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 402.022, + 5.879, + 648.151 + ], + "size": [ + 12.223, + 6.71, + 13.106 + ], + "groundY": 2.524, + "roofY": 9.234, + "wallCount": 33, + "roofCount": 4 + }, + { + "id": "sion_1654", + "uuid": "{6C1FA16D-1366-40FE-8154-B08C7DB7B889}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -106.219, + 64.686, + -762.197 + ], + "size": [ + 14.656, + 6.316, + 6.664 + ], + "groundY": 61.528, + "roofY": 67.844, + "wallCount": 10, + "roofCount": 16 + }, + { + "id": "sion_1655", + "uuid": "{836D3348-AD29-4C90-96ED-CB0095DDB8C5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 424.74, + 65.129, + -910.031 + ], + "size": [ + 20.871, + 10.339, + 17.882 + ], + "groundY": 59.96, + "roofY": 70.298, + "wallCount": 29, + "roofCount": 33 + }, + { + "id": "sion_1656", + "uuid": "{820AD434-E9C4-418B-A82A-74D835E39265}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -325.518, + 18.009, + 182.483 + ], + "size": [ + 8.746, + 7.374, + 8.752 + ], + "groundY": 14.322, + "roofY": 21.696, + "wallCount": 29, + "roofCount": 2 + }, + { + "id": "sion_1657", + "uuid": "{F75E8668-1D63-40C3-BB3C-9994C81625E3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 3 + ], + "center": [ + -74.992, + 16.85, + 236.273 + ], + "size": [ + 31.531, + 7.95, + 27.288 + ], + "groundY": 12.875, + "roofY": 20.825, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1658", + "uuid": "{5793E4FD-A9B4-47B8-BD32-3D5A3F95E0E2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 439.824, + 65.913, + -952.987 + ], + "size": [ + 26.641, + 10.164, + 16.136 + ], + "groundY": 60.831, + "roofY": 70.995, + "wallCount": 35, + "roofCount": 33 + }, + { + "id": "sion_1659", + "uuid": "{40E011F3-0B19-4221-8D99-CB32F3D430F2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 1 + ], + "center": [ + 696.031, + 43.706, + -889.195 + ], + "size": [ + 36.726, + 10.618, + 22.828 + ], + "groundY": 38.397, + "roofY": 49.015, + "wallCount": 56, + "roofCount": 15 + }, + { + "id": "sion_1660", + "uuid": "{3D393953-983D-491C-91AD-1C982342EC5E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -305.549, + 40.072, + -321.012 + ], + "size": [ + 17.426, + 6.257, + 16.848 + ], + "groundY": 36.944, + "roofY": 43.201, + "wallCount": 12, + "roofCount": 4 + }, + { + "id": "sion_1661", + "uuid": "{885B4CB8-487C-4D38-AD77-08E7AFD181C0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 263.199, + 6.477, + 910.415 + ], + "size": [ + 45.531, + 11.002, + 41.238 + ], + "groundY": 0.976, + "roofY": 11.978, + "wallCount": 16, + "roofCount": 9 + }, + { + "id": "sion_1662", + "uuid": "{3A36C039-1CCF-4FD0-A1B6-A8F6B5473D4F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 190.309, + 24.07, + -72.535 + ], + "size": [ + 21.695, + 22.201, + 14.428 + ], + "groundY": 12.97, + "roofY": 35.171, + "wallCount": 11, + "roofCount": 36 + }, + { + "id": "sion_1663", + "uuid": "{8B46DA6D-F633-46F2-BF8E-C2EB7FA9F3F0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -16.727, + 30.326, + 1.68 + ], + "size": [ + 17.711, + 18.334, + 16.848 + ], + "groundY": 21.159, + "roofY": 39.493, + "wallCount": 24, + "roofCount": 12 + }, + { + "id": "sion_1664", + "uuid": "{E4187588-6530-46A8-AD8E-53436D313AFE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -169.176, + 22.954, + 321.287 + ], + "size": [ + 22.594, + 27.718, + 27.688 + ], + "groundY": 9.095, + "roofY": 36.813, + "wallCount": 88, + "roofCount": 58 + }, + { + "id": "sion_1665", + "uuid": "{569122E5-F856-4F88-B57C-299E371856C1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 316.344, + 12.216, + -9.579 + ], + "size": [ + 27.57, + 8.466, + 9.861 + ], + "groundY": 7.983, + "roofY": 16.449, + "wallCount": 18, + "roofCount": 10 + }, + { + "id": "sion_1666", + "uuid": "{7D7CC42E-84AB-414C-A6AA-966F507DD3CB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 1 + ], + "center": [ + 1119.465, + 9.893, + -828.231 + ], + "size": [ + 14.078, + 10.25, + 14.086 + ], + "groundY": 4.768, + "roofY": 15.018, + "wallCount": 26, + "roofCount": 11 + }, + { + "id": "sion_1667", + "uuid": "{A70ABFCD-D6DD-4A1C-8306-BD5B2B83F249}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 318.936, + 7.844, + 546.133 + ], + "size": [ + 36.02, + 11.141, + 40.873 + ], + "groundY": 2.274, + "roofY": 13.415, + "wallCount": 18, + "roofCount": 20 + }, + { + "id": "sion_1668", + "uuid": "{A29FDD4C-C4C6-445E-B3B4-C0AB4A2337A5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 642.129, + 9.636, + 38.626 + ], + "size": [ + 15.219, + 13.889, + 30.943 + ], + "groundY": 2.691, + "roofY": 16.58, + "wallCount": 18, + "roofCount": 20 + }, + { + "id": "sion_1669", + "uuid": "{44E462D2-0FD6-4B51-BDEF-1CE23B06D7C5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 4 + ], + "center": [ + 1171.436, + 17.378, + 516.419 + ], + "size": [ + 113.566, + 24.772, + 31.805 + ], + "groundY": 4.992, + "roofY": 29.764, + "wallCount": 63, + "roofCount": 74 + }, + { + "id": "sion_1670", + "uuid": "{ED87C6A9-326C-4E24-9EA6-1F0F9782A13C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 737.107, + 70.761, + -1092.366 + ], + "size": [ + 5.848, + 7.064, + 6.114 + ], + "groundY": 67.229, + "roofY": 74.293, + "wallCount": 36, + "roofCount": 4 + }, + { + "id": "sion_1671", + "uuid": "{EEC63C63-5340-46ED-9881-B16B3648C315}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 295.844, + 80.575, + -987.917 + ], + "size": [ + 30.141, + 15.547, + 34.982 + ], + "groundY": 72.802, + "roofY": 88.349, + "wallCount": 52, + "roofCount": 16 + }, + { + "id": "sion_1672", + "uuid": "{553DA645-1639-46BE-8D3D-A98E87BEB7D6}", + "name": "", + "class": "Unterirdisches Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 716.906, + 17.768, + -168.963 + ], + "size": [ + 121.547, + 29.773, + 115.324 + ], + "groundY": 2.881, + "roofY": 32.654, + "wallCount": 248, + "roofCount": 106 + }, + { + "id": "sion_1673", + "uuid": "{0F98270C-1240-450B-81D2-FC4754AA4969}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -227.812, + 12.284, + 574.338 + ], + "size": [ + 59.062, + 20.98, + 30.225 + ], + "groundY": 1.794, + "roofY": 22.774, + "wallCount": 55, + "roofCount": 21 + }, + { + "id": "sion_1674", + "uuid": "{F672CC29-08C5-4678-BDC9-1795DE46B0E7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -133.83, + 196.458, + -1471.507 + ], + "size": [ + 17.934, + 12.332, + 20.376 + ], + "groundY": 190.292, + "roofY": 202.624, + "wallCount": 61, + "roofCount": 23 + }, + { + "id": "sion_1675", + "uuid": "{ACDAEAEB-C5F4-431F-95D8-E0602C036865}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -79.889, + 13.592, + 316.522 + ], + "size": [ + 8.957, + 7.559, + 6.29 + ], + "groundY": 9.813, + "roofY": 17.372, + "wallCount": 16, + "roofCount": 16 + }, + { + "id": "sion_1676", + "uuid": "{64C5C007-AF95-4EC3-BC37-38B447979988}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -304.225, + 56.726, + -513.811 + ], + "size": [ + 48.84, + 21.133, + 15.966 + ], + "groundY": 46.159, + "roofY": 67.292, + "wallCount": 34, + "roofCount": 49 + }, + { + "id": "sion_1677", + "uuid": "{129EF01B-E8A2-4DAA-A46D-587AE263E0F7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 364.596, + 214.192, + -1400.148 + ], + "size": [ + 13.457, + 9.805, + 13.85 + ], + "groundY": 209.289, + "roofY": 219.094, + "wallCount": 30, + "roofCount": 10 + }, + { + "id": "sion_1678", + "uuid": "{B7B6A290-A6FA-434B-ADA1-CF9235629259}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 170.832, + 66.497, + -716.916 + ], + "size": [ + 49.477, + 24.994, + 53.215 + ], + "groundY": 54.0, + "roofY": 78.994, + "wallCount": 30, + "roofCount": 8 + }, + { + "id": "sion_1679", + "uuid": "{470BF7A0-D36C-4F0C-B026-147D002BDA15}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1472.152, + 18.635, + 75.148 + ], + "size": [ + 20.453, + 20.764, + 22.265 + ], + "groundY": 8.253, + "roofY": 29.017, + "wallCount": 73, + "roofCount": 54 + }, + { + "id": "sion_1680", + "uuid": "{966A3095-C3A2-4545-8B9A-F61295DC6519}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 2, + 2 + ], + "center": [ + -10.494, + 86.306, + -363.691 + ], + "size": [ + 7.129, + 4.634, + 4.898 + ], + "groundY": 83.989, + "roofY": 88.623, + "wallCount": 41, + "roofCount": 12 + }, + { + "id": "sion_1681", + "uuid": "{B14B92B1-3777-4AFA-AE4E-3632A7CE6AA7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -288.805, + 52.53, + -441.104 + ], + "size": [ + 39.586, + 20.825, + 65.05 + ], + "groundY": 42.118, + "roofY": 62.942, + "wallCount": 78, + "roofCount": 46 + }, + { + "id": "sion_1682", + "uuid": "{FEFA26C8-2BBA-45CE-A3E4-3DB48DC3180F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -140.592, + 80.757, + -951.248 + ], + "size": [ + 28.262, + 10.797, + 14.98 + ], + "groundY": 75.359, + "roofY": 86.156, + "wallCount": 34, + "roofCount": 37 + }, + { + "id": "sion_1683", + "uuid": "{BBA74670-C725-48EA-AC0A-8CE23B83F18F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -271.586, + 44.596, + -279.619 + ], + "size": [ + 21.328, + 20.541, + 27.22 + ], + "groundY": 34.325, + "roofY": 54.866, + "wallCount": 34, + "roofCount": 22 + }, + { + "id": "sion_1684", + "uuid": "{A1D1C694-842B-4C2F-94E5-B77154891ED3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 1 + ], + "center": [ + 706.732, + 34.313, + -976.066 + ], + "size": [ + 4.644, + 5.544, + 4.663 + ], + "groundY": 31.541, + "roofY": 37.085, + "wallCount": 15, + "roofCount": 16 + }, + { + "id": "sion_1685", + "uuid": "{0C55A9A7-E31D-4CCD-BE48-8F4A94C4A30F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 388.863, + 66.284, + -895.191 + ], + "size": [ + 21.898, + 10.426, + 19.403 + ], + "groundY": 61.071, + "roofY": 71.497, + "wallCount": 54, + "roofCount": 29 + }, + { + "id": "sion_1686", + "uuid": "{34EC420E-82D2-4592-A50D-2C67736D8964}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1338.914, + 19.143, + 48.079 + ], + "size": [ + 18.391, + 26.597, + 31.43 + ], + "groundY": 5.845, + "roofY": 32.442, + "wallCount": 87, + "roofCount": 20 + }, + { + "id": "sion_1687", + "uuid": "{CD58FEEE-735D-4087-A25A-F2F8B661D686}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 530.266, + 7.704, + 577.879 + ], + "size": [ + 16.539, + 10.81, + 15.691 + ], + "groundY": 2.299, + "roofY": 13.109, + "wallCount": 47, + "roofCount": 30 + }, + { + "id": "sion_1688", + "uuid": "{4312DECE-B3E8-4969-AE4F-F6471AC3BCDD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 59.645, + 74.723, + -973.414 + ], + "size": [ + 54.211, + 17.367, + 34.416 + ], + "groundY": 66.04, + "roofY": 83.407, + "wallCount": 29, + "roofCount": 26 + }, + { + "id": "sion_1689", + "uuid": "{91E776ED-977F-4962-BE39-D7B0783E374D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1291.07, + 10.096, + 293.521 + ], + "size": [ + 10.078, + 5.038, + 11.005 + ], + "groundY": 7.577, + "roofY": 12.615, + "wallCount": 51, + "roofCount": 8 + }, + { + "id": "sion_1690", + "uuid": "{AFE897E1-4367-4103-AC8B-BF0FA01C9AE6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 2 + ], + "center": [ + 478.598, + 14.26, + -52.371 + ], + "size": [ + 36.875, + 23.574, + 53.145 + ], + "groundY": 2.473, + "roofY": 26.047, + "wallCount": 72, + "roofCount": 24 + }, + { + "id": "sion_1691", + "uuid": "{C35FF25A-0B40-4F51-8FFA-0E934C1ABB92}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 462.777, + 55.512, + -890.416 + ], + "size": [ + 11.68, + 11.564, + 13.772 + ], + "groundY": 49.73, + "roofY": 61.294, + "wallCount": 35, + "roofCount": 15 + }, + { + "id": "sion_1692", + "uuid": "{E9990C6F-C755-4C3F-BE31-8B9E1FC8E9BE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 349.75, + 58.748, + -841.105 + ], + "size": [ + 17.359, + 11.044, + 13.276 + ], + "groundY": 53.226, + "roofY": 64.27, + "wallCount": 40, + "roofCount": 17 + }, + { + "id": "sion_1693", + "uuid": "{84B9A8E2-1EBD-446D-A4EA-A3ABEAB01BF4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 19.895, + 64.223, + -783.888 + ], + "size": [ + 9.711, + 10.208, + 9.388 + ], + "groundY": 59.119, + "roofY": 69.327, + "wallCount": 20, + "roofCount": 30 + }, + { + "id": "sion_1694", + "uuid": "{E33B3CB5-F36C-42D9-A805-6F5A2B6B0D42}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -237.225, + 64.655, + -707.427 + ], + "size": [ + 17.02, + 16.058, + 15.742 + ], + "groundY": 56.626, + "roofY": 72.684, + "wallCount": 39, + "roofCount": 21 + }, + { + "id": "sion_1695", + "uuid": "{BFEAE78F-ACDB-40DA-947E-F22AA909AFCF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 55.475, + 71.573, + -348.981 + ], + "size": [ + 61.824, + 19.742, + 24.354 + ], + "groundY": 61.702, + "roofY": 81.444, + "wallCount": 160, + "roofCount": 80 + }, + { + "id": "sion_1696", + "uuid": "{6B03A258-4341-41DA-99F6-F2EAC7DD7B4D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -24.373, + 60.805, + -295.707 + ], + "size": [ + 24.59, + 20.268, + 25.336 + ], + "groundY": 50.671, + "roofY": 70.939, + "wallCount": 52, + "roofCount": 22 + }, + { + "id": "sion_1697", + "uuid": "{2F31A64A-C9A9-45F2-8BF6-0CA3552F7E8F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 340.848, + 17.929, + -97.187 + ], + "size": [ + 70.539, + 26.424, + 34.103 + ], + "groundY": 4.717, + "roofY": 31.141, + "wallCount": 26, + "roofCount": 20 + }, + { + "id": "sion_1698", + "uuid": "{8B85E773-D464-4C3D-9E03-CF28E4E5CBB0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -155.799, + 8.113, + 639.709 + ], + "size": [ + 58.902, + 12.718, + 92.187 + ], + "groundY": 1.754, + "roofY": 14.472, + "wallCount": 14, + "roofCount": 28 + }, + { + "id": "sion_1699", + "uuid": "{0CC9E1A5-B0D7-4F4F-8500-5FD17522F7C2}", + "name": "", + "class": "Sakrales Gebaeude", + "archStyle": "fortress", + "tile": [ + 2, + 2 + ], + "center": [ + -54.853, + 66.438, + -168.347 + ], + "size": [ + 59.855, + 48.792, + 73.933 + ], + "groundY": 42.042, + "roofY": 90.834, + "wallCount": 465, + "roofCount": 355 + }, + { + "id": "sion_1700", + "uuid": "{823FCBF0-F517-4A30-B4FB-38E6B20E7DF8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1050.996, + 10.018, + 373.157 + ], + "size": [ + 12.727, + 10.434, + 11.184 + ], + "groundY": 4.801, + "roofY": 15.235, + "wallCount": 48, + "roofCount": 31 + }, + { + "id": "sion_1701", + "uuid": "{3DD03334-362E-4F86-BA70-5485C7E7E112}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1390.045, + 19.439, + 7.798 + ], + "size": [ + 31.098, + 26.3, + 35.982 + ], + "groundY": 6.289, + "roofY": 32.589, + "wallCount": 100, + "roofCount": 24 + }, + { + "id": "sion_1702", + "uuid": "{87ECBF11-EA02-4871-9099-ED3CFB073944}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -130.871, + 45.932, + -311.343 + ], + "size": [ + 36.07, + 19.803, + 27.96 + ], + "groundY": 36.031, + "roofY": 55.834, + "wallCount": 68, + "roofCount": 40 + }, + { + "id": "sion_1703", + "uuid": "{2DC301E5-E458-40B3-85CC-AD068C4A6992}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1377.834, + 16.253, + 183.389 + ], + "size": [ + 13.738, + 14.811, + 25.466 + ], + "groundY": 8.848, + "roofY": 23.659, + "wallCount": 38, + "roofCount": 34 + }, + { + "id": "sion_1704", + "uuid": "{431CEB6B-4765-42C0-8489-099AD2B63A87}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -161.539, + 44.937, + -319.924 + ], + "size": [ + 23.594, + 20.844, + 23.41 + ], + "groundY": 34.515, + "roofY": 55.359, + "wallCount": 75, + "roofCount": 46 + }, + { + "id": "sion_1705", + "uuid": "{304FFB92-DC72-4A3E-B031-AC66824B3F96}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 960.254, + 15.561, + 18.829 + ], + "size": [ + 52.992, + 24.38, + 66.456 + ], + "groundY": 3.371, + "roofY": 27.751, + "wallCount": 10, + "roofCount": 2 + }, + { + "id": "sion_1706", + "uuid": "{5C97675A-8F4D-4364-AB74-9AAB15513C2D}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 639.918, + 17.053, + 280.717 + ], + "size": [ + 24.719, + 28.032, + 31.78 + ], + "groundY": 3.037, + "roofY": 31.069, + "wallCount": 25, + "roofCount": 2 + }, + { + "id": "sion_1707", + "uuid": "{B4DA4597-30E1-41E3-B427-FC0CDA183A02}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 213.709, + 58.409, + -726.946 + ], + "size": [ + 17.316, + 13.389, + 15.67 + ], + "groundY": 51.715, + "roofY": 65.104, + "wallCount": 40, + "roofCount": 12 + }, + { + "id": "sion_1708", + "uuid": "{7460E20C-5DB5-47F1-A588-29F8CA0CD2D2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 179.619, + 69.548, + -902.997 + ], + "size": [ + 44.824, + 16.975, + 25.932 + ], + "groundY": 61.061, + "roofY": 78.036, + "wallCount": 26, + "roofCount": 28 + }, + { + "id": "sion_1709", + "uuid": "{54C40375-8CF8-4409-B4D4-97BA5AA486B9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -206.574, + 44.919, + -351.323 + ], + "size": [ + 40.398, + 19.102, + 45.652 + ], + "groundY": 35.368, + "roofY": 54.47, + "wallCount": 95, + "roofCount": 62 + }, + { + "id": "sion_1710", + "uuid": "{837A2C45-1913-456B-A621-3F08D998DFAE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 468.619, + 60.582, + -699.607 + ], + "size": [ + 10.699, + 7.101, + 5.597 + ], + "groundY": 57.031, + "roofY": 64.132, + "wallCount": 36, + "roofCount": 23 + }, + { + "id": "sion_1711", + "uuid": "{02D69022-6DC4-4A66-A797-6788D5989AF0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1258.852, + 12.52, + 245.86 + ], + "size": [ + 30.281, + 10.622, + 11.618 + ], + "groundY": 7.209, + "roofY": 17.831, + "wallCount": 28, + "roofCount": 28 + }, + { + "id": "sion_1712", + "uuid": "{72CD113C-DD02-480C-B2B1-058F3B8A906D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 201.391, + 7.994, + 519.203 + ], + "size": [ + 64.375, + 12.153, + 32.884 + ], + "groundY": 1.918, + "roofY": 14.071, + "wallCount": 53, + "roofCount": 26 + }, + { + "id": "sion_1713", + "uuid": "{FEEA4FEA-CE36-4E02-B0FC-E152A28BAFD7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -70.529, + 50.673, + -362.468 + ], + "size": [ + 15.559, + 12.873, + 17.344 + ], + "groundY": 44.236, + "roofY": 57.109, + "wallCount": 48, + "roofCount": 27 + }, + { + "id": "sion_1714", + "uuid": "{285036DC-98E8-45FE-8E3C-45DB24948D18}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 2 + ], + "center": [ + 1435.688, + 15.409, + -32.769 + ], + "size": [ + 29.227, + 16.415, + 24.536 + ], + "groundY": 7.201, + "roofY": 23.616, + "wallCount": 88, + "roofCount": 18 + }, + { + "id": "sion_1715", + "uuid": "{3F0255F1-6F28-4303-85D4-F12C019E45FD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1314.949, + 12.879, + 287.688 + ], + "size": [ + 30.281, + 10.612, + 11.616 + ], + "groundY": 7.573, + "roofY": 18.185, + "wallCount": 22, + "roofCount": 22 + }, + { + "id": "sion_1716", + "uuid": "{7513A248-E3B3-41F9-8BB4-5935D701071C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -280.33, + 52.531, + -487.038 + ], + "size": [ + 25.894, + 18.503, + 19.486 + ], + "groundY": 43.279, + "roofY": 61.782, + "wallCount": 13, + "roofCount": 16 + }, + { + "id": "sion_1717", + "uuid": "{5C04409E-EACE-4899-AC89-8B763FC0D44E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 161.0, + 24.524, + -69.128 + ], + "size": [ + 24.812, + 21.411, + 19.414 + ], + "groundY": 13.818, + "roofY": 35.229, + "wallCount": 8, + "roofCount": 29 + }, + { + "id": "sion_1718", + "uuid": "{A23A7DBC-5FC6-45C3-A3CA-0F42AD098C06}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 1 + ], + "center": [ + 636.619, + 80.429, + -580.692 + ], + "size": [ + 5.301, + 6.222, + 5.544 + ], + "groundY": 77.318, + "roofY": 83.54, + "wallCount": 12, + "roofCount": 8 + }, + { + "id": "sion_1719", + "uuid": "{0ADB15E0-BFE8-4533-999B-85C705D37E69}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 303.91, + 13.675, + 170.132 + ], + "size": [ + 31.352, + 7.454, + 24.268 + ], + "groundY": 9.948, + "roofY": 17.402, + "wallCount": 15, + "roofCount": 9 + }, + { + "id": "sion_1720", + "uuid": "{7558AA5F-4FED-4DAC-8B0A-279ECCE8E1B2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 248.035, + 4.459, + 593.493 + ], + "size": [ + 17.273, + 5.072, + 20.065 + ], + "groundY": 1.923, + "roofY": 6.995, + "wallCount": 15, + "roofCount": 2 + }, + { + "id": "sion_1721", + "uuid": "{E02457F7-9C74-49E6-AC33-B71B9F9D5524}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 240.279, + 73.252, + -912.235 + ], + "size": [ + 59.746, + 20.49, + 57.153 + ], + "groundY": 63.007, + "roofY": 83.497, + "wallCount": 55, + "roofCount": 16 + }, + { + "id": "sion_1722", + "uuid": "{0192894D-C7A1-4134-B139-FAAC131AB892}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 4 + ], + "center": [ + 1282.436, + 13.617, + 611.511 + ], + "size": [ + 51.957, + 12.79, + 30.442 + ], + "groundY": 7.222, + "roofY": 20.012, + "wallCount": 12, + "roofCount": 22 + }, + { + "id": "sion_1723", + "uuid": "{B548338C-B590-4E82-9587-C4772A48A173}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -297.213, + 48.568, + -348.917 + ], + "size": [ + 43.066, + 23.142, + 41.672 + ], + "groundY": 36.997, + "roofY": 60.139, + "wallCount": 102, + "roofCount": 64 + }, + { + "id": "sion_1724", + "uuid": "{D8B671B5-0DDA-4E1F-A2C7-1B5BF51A6FA1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 396.445, + 219.787, + -1372.774 + ], + "size": [ + 23.641, + 10.229, + 23.146 + ], + "groundY": 214.673, + "roofY": 224.901, + "wallCount": 38, + "roofCount": 26 + }, + { + "id": "sion_1725", + "uuid": "{EB75E232-468A-4ED5-A880-B50375765875}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 398.353, + 58.2, + -717.867 + ], + "size": [ + 20.918, + 6.066, + 11.738 + ], + "groundY": 55.167, + "roofY": 61.233, + "wallCount": 21, + "roofCount": 29 + }, + { + "id": "sion_1726", + "uuid": "{2611CC66-4F5F-4D99-BB10-75732ACF9172}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 615.615, + 8.46, + 875.956 + ], + "size": [ + 43.41, + 10.105, + 34.275 + ], + "groundY": 3.408, + "roofY": 13.513, + "wallCount": 10, + "roofCount": 23 + }, + { + "id": "sion_1727", + "uuid": "{13DBA8E4-1DEA-4CAC-8F36-81ED46710A30}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 910.434, + 15.599, + 16.996 + ], + "size": [ + 30.43, + 25.97, + 27.939 + ], + "groundY": 2.614, + "roofY": 28.584, + "wallCount": 50, + "roofCount": 6 + }, + { + "id": "sion_1728", + "uuid": "{C9EB0AB5-1E8B-44E3-A89A-679298EBC319}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1528.744, + 14.029, + 406.92 + ], + "size": [ + 13.816, + 9.918, + 13.736 + ], + "groundY": 9.07, + "roofY": 18.988, + "wallCount": 29, + "roofCount": 18 + }, + { + "id": "sion_1729", + "uuid": "{238B6CB3-E0DA-407E-86F8-436960A2271A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 229.125, + 57.002, + -766.9 + ], + "size": [ + 20.273, + 9.836, + 14.987 + ], + "groundY": 52.084, + "roofY": 61.92, + "wallCount": 28, + "roofCount": 11 + }, + { + "id": "sion_1730", + "uuid": "{101B7BDC-7235-4B7A-B9C0-EE5C70ED03F2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1259.592, + 12.429, + 337.88 + ], + "size": [ + 30.41, + 10.49, + 11.784 + ], + "groundY": 7.184, + "roofY": 17.674, + "wallCount": 24, + "roofCount": 21 + }, + { + "id": "sion_1731", + "uuid": "{24D11C28-88F6-4FFE-9532-C4AB7E0DDC9F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 333.533, + 19.33, + 188.136 + ], + "size": [ + 29.488, + 22.24, + 24.608 + ], + "groundY": 8.21, + "roofY": 30.45, + "wallCount": 14, + "roofCount": 17 + }, + { + "id": "sion_1732", + "uuid": "{284CB4B6-4CB8-4713-BFF7-77D453F6E653}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -123.648, + 89.661, + -1045.903 + ], + "size": [ + 12.203, + 9.917, + 18.826 + ], + "groundY": 84.703, + "roofY": 94.62, + "wallCount": 32, + "roofCount": 36 + }, + { + "id": "sion_1733", + "uuid": "{9B95E703-DF62-4740-BCFE-5D5C633023AF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 561.113, + 10.193, + 425.145 + ], + "size": [ + 30.758, + 14.692, + 26.013 + ], + "groundY": 2.847, + "roofY": 17.539, + "wallCount": 38, + "roofCount": 21 + }, + { + "id": "sion_1734", + "uuid": "{8885341C-7760-453F-B1E8-E90A71CBEE2D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 2 + ], + "center": [ + 1258.65, + 12.708, + -41.995 + ], + "size": [ + 43.918, + 9.986, + 43.934 + ], + "groundY": 7.715, + "roofY": 17.7, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1735", + "uuid": "{D7A8BE4F-D269-4778-8C89-EB7344417F9F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 721.904, + 15.706, + 133.813 + ], + "size": [ + 29.848, + 26.779, + 21.632 + ], + "groundY": 2.317, + "roofY": 29.095, + "wallCount": 98, + "roofCount": 21 + }, + { + "id": "sion_1736", + "uuid": "{959E07B5-C9D1-4558-9D41-EB43FC5F2424}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -228.027, + 32.797, + 122.987 + ], + "size": [ + 35.156, + 27.529, + 54.114 + ], + "groundY": 19.032, + "roofY": 46.561, + "wallCount": 39, + "roofCount": 28 + }, + { + "id": "sion_1737", + "uuid": "{B916510A-C96B-47DC-842E-2B81FC231EAE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 783.869, + 9.239, + 617.252 + ], + "size": [ + 27.527, + 9.681, + 29.951 + ], + "groundY": 4.398, + "roofY": 14.079, + "wallCount": 20, + "roofCount": 10 + }, + { + "id": "sion_1738", + "uuid": "{06B61ACF-F7EA-46C7-AFB6-580260AC2429}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -70.451, + 8.322, + 995.725 + ], + "size": [ + 26.379, + 8.476, + 27.494 + ], + "groundY": 4.084, + "roofY": 12.56, + "wallCount": 30, + "roofCount": 26 + }, + { + "id": "sion_1739", + "uuid": "{B1E659EA-A0A1-411D-A455-DBA788649B75}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 4 + ], + "center": [ + 1050.799, + 11.994, + 605.102 + ], + "size": [ + 41.637, + 13.236, + 22.04 + ], + "groundY": 5.376, + "roofY": 18.612, + "wallCount": 37, + "roofCount": 18 + }, + { + "id": "sion_1740", + "uuid": "{B2098EA1-D5C2-4424-A6C7-B55F0808BB04}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 132.062, + 61.383, + -648.84 + ], + "size": [ + 23.805, + 9.982, + 15.574 + ], + "groundY": 56.392, + "roofY": 66.374, + "wallCount": 40, + "roofCount": 12 + }, + { + "id": "sion_1741", + "uuid": "{C60CC4C9-AE69-4766-900E-4C0C75C35EF1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 0.766, + 30.671, + 130.079 + ], + "size": [ + 67.125, + 29.22, + 65.475 + ], + "groundY": 16.061, + "roofY": 45.281, + "wallCount": 71, + "roofCount": 161 + }, + { + "id": "sion_1742", + "uuid": "{33CB4745-9C39-4064-99E6-5B96FB05157F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -13.803, + 61.556, + -322.847 + ], + "size": [ + 23.543, + 14.546, + 14.78 + ], + "groundY": 54.283, + "roofY": 68.829, + "wallCount": 52, + "roofCount": 23 + }, + { + "id": "sion_1743", + "uuid": "{380BFBAB-A554-4AB3-A708-A9DF6C80D424}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -143.781, + 82.413, + -1042.93 + ], + "size": [ + 12.609, + 8.167, + 21.704 + ], + "groundY": 78.33, + "roofY": 86.497, + "wallCount": 30, + "roofCount": 5 + }, + { + "id": "sion_1744", + "uuid": "{D70AA9BC-C236-4622-B9B5-4DA85A125748}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1494.039, + 12.558, + 336.169 + ], + "size": [ + 19.93, + 10.582, + 21.906 + ], + "groundY": 7.267, + "roofY": 17.849, + "wallCount": 48, + "roofCount": 4 + }, + { + "id": "sion_1745", + "uuid": "{DD9289EE-27CC-4E81-A34A-3B903A430812}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 465.641, + 215.933, + -1516.344 + ], + "size": [ + 21.875, + 12.792, + 16.468 + ], + "groundY": 209.537, + "roofY": 222.329, + "wallCount": 68, + "roofCount": 32 + }, + { + "id": "sion_1746", + "uuid": "{9CEDA920-89A6-426F-9328-2B79D5A9D986}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 736.447, + 13.325, + 103.515 + ], + "size": [ + 35.793, + 22.077, + 29.382 + ], + "groundY": 2.287, + "roofY": 24.364, + "wallCount": 74, + "roofCount": 20 + }, + { + "id": "sion_1747", + "uuid": "{989E993F-992B-4195-B69D-12184452C29C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 849.98, + 155.398, + -1250.641 + ], + "size": [ + 8.008, + 8.964, + 8.742 + ], + "groundY": 150.916, + "roofY": 159.88, + "wallCount": 55, + "roofCount": 2 + }, + { + "id": "sion_1748", + "uuid": "{CCBC4529-B48A-4552-A33B-8855362A8F0D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -157.57, + 65.183, + -711.385 + ], + "size": [ + 17.992, + 16.133, + 16.882 + ], + "groundY": 57.116, + "roofY": 73.249, + "wallCount": 41, + "roofCount": 59 + }, + { + "id": "sion_1749", + "uuid": "{DF092E47-D9D8-4361-AABC-07D14E506E12}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1092.022, + 11.234, + 347.671 + ], + "size": [ + 21.324, + 11.832, + 11.418 + ], + "groundY": 5.318, + "roofY": 17.15, + "wallCount": 27, + "roofCount": 27 + }, + { + "id": "sion_1750", + "uuid": "{E359F952-082C-4021-8852-C78CB64F057C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 312.978, + 73.06, + -912.763 + ], + "size": [ + 23.824, + 8.46, + 13.188 + ], + "groundY": 68.83, + "roofY": 77.29, + "wallCount": 35, + "roofCount": 16 + }, + { + "id": "sion_1751", + "uuid": "{A4361D91-B957-4B70-9781-A1967FD7F1E5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 191.199, + 21.563, + 8.641 + ], + "size": [ + 15.141, + 15.633, + 12.628 + ], + "groundY": 13.747, + "roofY": 29.38, + "wallCount": 19, + "roofCount": 30 + }, + { + "id": "sion_1752", + "uuid": "{D5F6432B-801C-4CEB-8721-0ADC46F8EAD8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1113.041, + 9.599, + 227.278 + ], + "size": [ + 36.481, + 8.902, + 28.206 + ], + "groundY": 5.148, + "roofY": 14.05, + "wallCount": 59, + "roofCount": 36 + }, + { + "id": "sion_1753", + "uuid": "{68C1F590-C90E-4DBA-ADD8-18A8C35CF6C8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 364.313, + 211.991, + -1441.437 + ], + "size": [ + 11.688, + 8.597, + 16.933 + ], + "groundY": 207.693, + "roofY": 216.29, + "wallCount": 11, + "roofCount": 41 + }, + { + "id": "sion_1754", + "uuid": "{105A31B4-DE59-4861-9E4E-D6C69DB81895}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 967.807, + 9.491, + 872.213 + ], + "size": [ + 57.91, + 9.476, + 27.502 + ], + "groundY": 4.753, + "roofY": 14.229, + "wallCount": 20, + "roofCount": 15 + }, + { + "id": "sion_1755", + "uuid": "{0EC21C04-58FB-4296-9CC0-512C208D42C9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 807.123, + 13.036, + -367.003 + ], + "size": [ + 19.793, + 19.446, + 15.178 + ], + "groundY": 3.313, + "roofY": 22.758, + "wallCount": 116, + "roofCount": 31 + }, + { + "id": "sion_1756", + "uuid": "{081016C9-A7B7-4468-859F-64662E0E864B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 672.953, + 8.78, + 521.828 + ], + "size": [ + 33.336, + 10.23, + 35.395 + ], + "groundY": 3.665, + "roofY": 13.895, + "wallCount": 10, + "roofCount": 0 + }, + { + "id": "sion_1757", + "uuid": "{3D1270CF-4B1E-4CD9-9426-D82DB45CCFAC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1531.475, + 17.909, + 193.31 + ], + "size": [ + 48.605, + 20.14, + 65.091 + ], + "groundY": 7.839, + "roofY": 27.979, + "wallCount": 55, + "roofCount": 63 + }, + { + "id": "sion_1758", + "uuid": "{93C23476-31A4-4DB5-A88E-27AF58163B9C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 226.834, + 88.563, + -1030.627 + ], + "size": [ + 26.957, + 14.081, + 17.344 + ], + "groundY": 81.523, + "roofY": 95.604, + "wallCount": 69, + "roofCount": 25 + }, + { + "id": "sion_1759", + "uuid": "{AD211BA7-353A-4BFA-B107-96CE158CD443}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -270.486, + 76.15, + -899.819 + ], + "size": [ + 15.363, + 12.226, + 13.899 + ], + "groundY": 70.037, + "roofY": 82.263, + "wallCount": 37, + "roofCount": 22 + }, + { + "id": "sion_1760", + "uuid": "{3761B5EC-9DF0-47CE-9F3A-8CE494195DE0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -372.801, + 67.815, + -756.23 + ], + "size": [ + 13.258, + 13.303, + 14.485 + ], + "groundY": 61.164, + "roofY": 74.467, + "wallCount": 32, + "roofCount": 35 + }, + { + "id": "sion_1761", + "uuid": "{3DE372D3-02BC-4181-A58C-18A049DEB2FE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -246.717, + 58.968, + -605.603 + ], + "size": [ + 4.973, + 6.088, + 4.962 + ], + "groundY": 55.924, + "roofY": 62.012, + "wallCount": 25, + "roofCount": 8 + }, + { + "id": "sion_1762", + "uuid": "{3B3B9CCA-5AD1-4C39-9D8E-5F0DD20AF912}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -343.441, + 13.394, + 361.44 + ], + "size": [ + 7.516, + 10.01, + 8.227 + ], + "groundY": 8.389, + "roofY": 18.399, + "wallCount": 59, + "roofCount": 19 + }, + { + "id": "sion_1763", + "uuid": "{098DF08B-635D-4FD8-9C4F-26F5CCA94644}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 324.936, + 17.979, + -44.375 + ], + "size": [ + 89.895, + 23.08, + 17.359 + ], + "groundY": 6.439, + "roofY": 29.518, + "wallCount": 28, + "roofCount": 47 + }, + { + "id": "sion_1764", + "uuid": "{D17B9A00-217F-4996-BC88-BE4FF54633F0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -85.35, + 54.856, + -501.198 + ], + "size": [ + 17.996, + 20.156, + 21.288 + ], + "groundY": 44.778, + "roofY": 64.934, + "wallCount": 50, + "roofCount": 55 + }, + { + "id": "sion_1765", + "uuid": "{75CA65F6-9C05-4A21-A516-AB08D9E8CF63}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 424.676, + 6.749, + 825.054 + ], + "size": [ + 30.547, + 8.674, + 28.4 + ], + "groundY": 2.412, + "roofY": 11.086, + "wallCount": 34, + "roofCount": 45 + }, + { + "id": "sion_1766", + "uuid": "{441802C9-CE3C-40EE-9F37-5A09A1B261A3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -265.736, + 30.906, + -50.669 + ], + "size": [ + 27.043, + 12.07, + 25.451 + ], + "groundY": 24.871, + "roofY": 36.941, + "wallCount": 42, + "roofCount": 47 + }, + { + "id": "sion_1767", + "uuid": "{71A190EC-D826-4F83-92CB-878A3D13A81F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 354.211, + 219.25, + -1343.016 + ], + "size": [ + 18.445, + 11.64, + 15.998 + ], + "groundY": 213.43, + "roofY": 225.07, + "wallCount": 38, + "roofCount": 20 + }, + { + "id": "sion_1768", + "uuid": "{859D6BDE-6F5D-4AAF-A116-D21B413C7F87}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 0 + ], + "center": [ + 1362.957, + 132.06, + -1520.947 + ], + "size": [ + 7.562, + 9.986, + 7.355 + ], + "groundY": 127.067, + "roofY": 137.053, + "wallCount": 50, + "roofCount": 13 + }, + { + "id": "sion_1769", + "uuid": "{EA21774E-CFCF-42E2-AB47-EE57DBE27B0E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -47.478, + 62.304, + -212.063 + ], + "size": [ + 34.645, + 23.591, + 31.769 + ], + "groundY": 50.509, + "roofY": 74.1, + "wallCount": 66, + "roofCount": 31 + }, + { + "id": "sion_1770", + "uuid": "{73D09D86-8C47-44EC-B03C-59638CC6D5F0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -165.834, + 79.065, + -911.587 + ], + "size": [ + 12.199, + 15.08, + 11.562 + ], + "groundY": 71.525, + "roofY": 86.605, + "wallCount": 57, + "roofCount": 28 + }, + { + "id": "sion_1771", + "uuid": "{7C420A26-B33B-473E-A4BD-94C886FD210A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 1 + ], + "center": [ + 1025.863, + 8.501, + -706.734 + ], + "size": [ + 25.086, + 7.95, + 20.558 + ], + "groundY": 4.526, + "roofY": 12.476, + "wallCount": 23, + "roofCount": 15 + }, + { + "id": "sion_1772", + "uuid": "{B2487815-AFF3-4850-BDCF-609E6F1825CA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -274.691, + 20.286, + 290.672 + ], + "size": [ + 26.992, + 17.615, + 27.027 + ], + "groundY": 11.478, + "roofY": 29.093, + "wallCount": 52, + "roofCount": 28 + }, + { + "id": "sion_1773", + "uuid": "{7C2AA1F7-6E91-4A09-A0E9-0BDF71DE4410}", + "name": "Tous les Saints", + "class": "Kapelle", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 184.65, + 99.716, + -310.617 + ], + "size": [ + 12.855, + 22.212, + 10.424 + ], + "groundY": 88.61, + "roofY": 110.822, + "wallCount": 95, + "roofCount": 36 + }, + { + "id": "sion_1774", + "uuid": "{933D2225-8E19-4DA1-B97B-9721A74D1EDF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 460.943, + 8.463, + 896.956 + ], + "size": [ + 34.684, + 10.923, + 63.051 + ], + "groundY": 3.002, + "roofY": 13.924, + "wallCount": 20, + "roofCount": 34 + }, + { + "id": "sion_1775", + "uuid": "{795299A1-9129-4966-AB50-204CC5EDDDB3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 280.912, + 74.275, + -902.801 + ], + "size": [ + 14.613, + 11.448, + 14.94 + ], + "groundY": 68.551, + "roofY": 79.999, + "wallCount": 59, + "roofCount": 25 + }, + { + "id": "sion_1776", + "uuid": "{FEA709D9-6CCC-4255-A398-8DC13AEDA264}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -381.82, + 2.487, + 658.801 + ], + "size": [ + 9.578, + 5.95, + 10.912 + ], + "groundY": -0.488, + "roofY": 5.462, + "wallCount": 28, + "roofCount": 2 + }, + { + "id": "sion_1777", + "uuid": "{A42195F7-F3A5-4466-B608-C85D97FAEBEA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 2 + ], + "center": [ + 1530.674, + 11.086, + -145.719 + ], + "size": [ + 28.848, + 8.836, + 35.25 + ], + "groundY": 6.668, + "roofY": 15.504, + "wallCount": 23, + "roofCount": 13 + }, + { + "id": "sion_1778", + "uuid": "{C155966E-A685-4FF1-B135-D4951217F389}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 969.336, + 11.275, + 911.38 + ], + "size": [ + 24.578, + 10.749, + 25.975 + ], + "groundY": 5.9, + "roofY": 16.649, + "wallCount": 37, + "roofCount": 26 + }, + { + "id": "sion_1779", + "uuid": "{95905DAA-CF85-4D7D-8C65-5BFD9378958D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 363.053, + 87.728, + -1028.839 + ], + "size": [ + 51.512, + 15.056, + 30.268 + ], + "groundY": 80.2, + "roofY": 95.256, + "wallCount": 106, + "roofCount": 51 + }, + { + "id": "sion_1780", + "uuid": "{38BE2AA6-3BAA-4609-AAC9-B3F9ACF0E00A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 707.635, + 10.905, + 168.73 + ], + "size": [ + 17.059, + 16.835, + 19.476 + ], + "groundY": 2.488, + "roofY": 19.323, + "wallCount": 53, + "roofCount": 6 + }, + { + "id": "sion_1781", + "uuid": "{8FC744BC-C0BC-405A-80B8-1D006B260F30}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -248.297, + 18.064, + 340.845 + ], + "size": [ + 18.055, + 16.11, + 18.772 + ], + "groundY": 10.009, + "roofY": 26.119, + "wallCount": 24, + "roofCount": 13 + }, + { + "id": "sion_1782", + "uuid": "{0A88AB36-AC6C-473B-B8CD-0B6B6EFCF636}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 443.91, + 94.111, + -1082.816 + ], + "size": [ + 23.031, + 10.168, + 16.886 + ], + "groundY": 89.027, + "roofY": 99.195, + "wallCount": 56, + "roofCount": 28 + }, + { + "id": "sion_1783", + "uuid": "{233D7EE5-0A6F-4D05-9D5A-C27792105D4A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 477.562, + 54.775, + -897.822 + ], + "size": [ + 11.797, + 11.153, + 13.696 + ], + "groundY": 49.198, + "roofY": 60.351, + "wallCount": 36, + "roofCount": 21 + }, + { + "id": "sion_1784", + "uuid": "{90CE9D8F-18B7-4951-A77A-D5B2BC87FE09}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 286.117, + 58.985, + -823.747 + ], + "size": [ + 43.617, + 20.0, + 19.482 + ], + "groundY": 48.985, + "roofY": 68.985, + "wallCount": 94, + "roofCount": 39 + }, + { + "id": "sion_1785", + "uuid": "{81C8DE74-2DF6-476F-92B6-89D0DB31E31F}", + "name": "", + "class": "Lagertank", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 603.228, + 14.666, + 778.849 + ], + "size": [ + 18.973, + 24.895, + 18.974 + ], + "groundY": 2.219, + "roofY": 27.114, + "wallCount": 372, + "roofCount": 117 + }, + { + "id": "sion_1786", + "uuid": "{937F14FC-6B3B-4096-84D7-112F5018187E}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 4, + 1 + ], + "center": [ + 524.133, + 154.548, + -559.721 + ], + "size": [ + 11.789, + 5.795, + 15.392 + ], + "groundY": 151.651, + "roofY": 157.446, + "wallCount": 60, + "roofCount": 26 + }, + { + "id": "sion_1787", + "uuid": "{394F7E34-282B-481E-A6B6-1CBCA53B0E3F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -303.258, + 23.18, + 250.754 + ], + "size": [ + 48.234, + 24.557, + 69.697 + ], + "groundY": 10.902, + "roofY": 35.459, + "wallCount": 68, + "roofCount": 63 + }, + { + "id": "sion_1788", + "uuid": "{04188005-FBA2-4409-8701-CE9BB39D4BED}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -285.791, + 28.082, + 161.303 + ], + "size": [ + 104.527, + 28.554, + 100.768 + ], + "groundY": 13.805, + "roofY": 42.359, + "wallCount": 199, + "roofCount": 132 + }, + { + "id": "sion_1789", + "uuid": "{F4B8BD39-3E3D-4DAA-BF04-AADA6D977AD0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 654.258, + 8.096, + 853.457 + ], + "size": [ + 29.062, + 9.484, + 23.607 + ], + "groundY": 3.354, + "roofY": 12.838, + "wallCount": 19, + "roofCount": 24 + }, + { + "id": "sion_1790", + "uuid": "{83B01A1F-D20A-4FC2-B123-714E90F06CC5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1455.768, + 11.808, + 16.287 + ], + "size": [ + 13.473, + 9.75, + 13.529 + ], + "groundY": 6.933, + "roofY": 16.683, + "wallCount": 46, + "roofCount": 22 + }, + { + "id": "sion_1791", + "uuid": "{04AF6F35-F52C-4546-9513-ED5D9CBDC9AC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 425.652, + 90.921, + -315.175 + ], + "size": [ + 10.844, + 12.894, + 10.304 + ], + "groundY": 84.474, + "roofY": 97.368, + "wallCount": 47, + "roofCount": 14 + }, + { + "id": "sion_1792", + "uuid": "{0B7ABEB4-EC9B-40AF-8BD0-936B2CD96CD9}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 82.16, + 95.154, + -393.199 + ], + "size": [ + 12.555, + 14.919, + 29.67 + ], + "groundY": 87.695, + "roofY": 102.614, + "wallCount": 106, + "roofCount": 20 + }, + { + "id": "sion_1793", + "uuid": "{276F25D3-3262-4A88-A86A-3C7CA9A37CDB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -203.879, + 53.669, + -497.873 + ], + "size": [ + 16.422, + 16.286, + 22.193 + ], + "groundY": 45.526, + "roofY": 61.812, + "wallCount": 62, + "roofCount": 109 + }, + { + "id": "sion_1794", + "uuid": "{D70043E8-66B3-42A9-807A-DB53CCD1D713}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 949.484, + 15.759, + 1011.76 + ], + "size": [ + 84.844, + 21.634, + 90.05 + ], + "groundY": 4.942, + "roofY": 26.576, + "wallCount": 101, + "roofCount": 31 + }, + { + "id": "sion_1795", + "uuid": "{37FAE508-84A2-4995-907C-4FB57531CA6C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 47.961, + 64.792, + -806.737 + ], + "size": [ + 12.492, + 10.348, + 12.132 + ], + "groundY": 59.618, + "roofY": 69.966, + "wallCount": 31, + "roofCount": 10 + }, + { + "id": "sion_1796", + "uuid": "{693CC8C0-D2EE-4C6A-9142-95A7B1C4775E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 275.434, + 64.568, + -850.859 + ], + "size": [ + 17.219, + 8.497, + 15.452 + ], + "groundY": 60.319, + "roofY": 68.816, + "wallCount": 34, + "roofCount": 17 + }, + { + "id": "sion_1797", + "uuid": "{2E769E3C-18A4-4B28-AD79-D50DEFAA42A4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -169.285, + 70.449, + -802.054 + ], + "size": [ + 14.258, + 14.589, + 12.272 + ], + "groundY": 63.155, + "roofY": 77.744, + "wallCount": 56, + "roofCount": 72 + }, + { + "id": "sion_1798", + "uuid": "{15E1459C-71E8-4BBD-BED3-9EB89B37C776}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 300.064, + 69.033, + -872.461 + ], + "size": [ + 18.277, + 10.57, + 16.486 + ], + "groundY": 63.748, + "roofY": 74.318, + "wallCount": 30, + "roofCount": 33 + }, + { + "id": "sion_1799", + "uuid": "{8813BC4A-D901-45E6-9DFE-30DFCE57C2BE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 360.744, + 6.595, + 509.404 + ], + "size": [ + 31.207, + 8.016, + 33.224 + ], + "groundY": 2.587, + "roofY": 10.603, + "wallCount": 31, + "roofCount": 27 + }, + { + "id": "sion_1800", + "uuid": "{571306BF-5642-40CA-B0B8-1B4ECF3FAB8F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -227.02, + 78.791, + -935.172 + ], + "size": [ + 15.883, + 17.009, + 16.586 + ], + "groundY": 70.287, + "roofY": 87.296, + "wallCount": 50, + "roofCount": 53 + }, + { + "id": "sion_1801", + "uuid": "{A593064F-09F6-459F-9BC7-B7400D98D968}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 192.699, + 25.127, + 37.141 + ], + "size": [ + 25.703, + 23.735, + 21.922 + ], + "groundY": 13.259, + "roofY": 36.994, + "wallCount": 21, + "roofCount": 26 + }, + { + "id": "sion_1802", + "uuid": "{B377B430-356D-49DD-B844-1270106795CE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 457.172, + 132.725, + -1163.717 + ], + "size": [ + 4.266, + 8.2, + 5.466 + ], + "groundY": 128.625, + "roofY": 136.825, + "wallCount": 41, + "roofCount": 5 + }, + { + "id": "sion_1803", + "uuid": "{70F11EC1-05AA-4815-A439-912EDAAB3947}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 757.52, + 16.845, + -361.363 + ], + "size": [ + 23.359, + 27.044, + 24.61 + ], + "groundY": 3.323, + "roofY": 30.367, + "wallCount": 162, + "roofCount": 16 + }, + { + "id": "sion_1804", + "uuid": "{CDB51B3C-F6A6-461F-9A22-4D193C89F024}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 167.061, + 8.287, + 743.031 + ], + "size": [ + 88.098, + 14.476, + 82.9 + ], + "groundY": 1.049, + "roofY": 15.525, + "wallCount": 80, + "roofCount": 37 + }, + { + "id": "sion_1805", + "uuid": "{B299CEAF-3C72-40F4-8F11-5F3DBBE33CC0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 703.652, + 9.048, + 814.89 + ], + "size": [ + 24.078, + 10.521, + 22.019 + ], + "groundY": 3.787, + "roofY": 14.308, + "wallCount": 48, + "roofCount": 8 + }, + { + "id": "sion_1806", + "uuid": "{97EAF4FB-3D8A-4693-8934-863A2AB4C6D0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 597.957, + 235.792, + -1361.634 + ], + "size": [ + 5.57, + 7.023, + 6.16 + ], + "groundY": 232.281, + "roofY": 239.304, + "wallCount": 47, + "roofCount": 10 + }, + { + "id": "sion_1807", + "uuid": "{C4E7A973-395A-4578-8AD7-C9355CD91566}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 712.641, + 212.369, + -1322.604 + ], + "size": [ + 4.375, + 8.185, + 4.129 + ], + "groundY": 208.276, + "roofY": 216.461, + "wallCount": 43, + "roofCount": 4 + }, + { + "id": "sion_1808", + "uuid": "{CAF206A9-AFEF-49F3-ACB0-0C98F2EA825C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 370.471, + 57.568, + -666.639 + ], + "size": [ + 17.832, + 6.068, + 10.479 + ], + "groundY": 54.534, + "roofY": 60.602, + "wallCount": 29, + "roofCount": 6 + }, + { + "id": "sion_1809", + "uuid": "{43FB2FC5-90C2-4E31-9179-FF1FB02F8D33}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -185.869, + 34.654, + 51.251 + ], + "size": [ + 27.731, + 23.688, + 15.197 + ], + "groundY": 22.81, + "roofY": 46.498, + "wallCount": 97, + "roofCount": 68 + }, + { + "id": "sion_1810", + "uuid": "{962C69B4-6081-4BB0-8B06-CA1B98ECE7B9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 196.691, + 10.363, + 621.961 + ], + "size": [ + 61.328, + 17.632, + 45.67 + ], + "groundY": 1.547, + "roofY": 19.179, + "wallCount": 35, + "roofCount": 43 + }, + { + "id": "sion_1811", + "uuid": "{18777F59-61B9-427E-A264-3BD2C434E159}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 934.555, + 8.883, + -393.767 + ], + "size": [ + 52.195, + 13.149, + 65.56 + ], + "groundY": 2.308, + "roofY": 15.457, + "wallCount": 72, + "roofCount": 65 + }, + { + "id": "sion_1812", + "uuid": "{67A2D5CB-1808-49ED-BF5F-F528FC84981F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -204.805, + 64.998, + -751.483 + ], + "size": [ + 13.43, + 15.073, + 21.648 + ], + "groundY": 57.462, + "roofY": 72.535, + "wallCount": 43, + "roofCount": 33 + }, + { + "id": "sion_1813", + "uuid": "{266F7C97-35F9-418C-9805-E31A2884B80D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 433.264, + 57.371, + -875.373 + ], + "size": [ + 11.762, + 11.647, + 13.876 + ], + "groundY": 51.547, + "roofY": 63.194, + "wallCount": 45, + "roofCount": 13 + }, + { + "id": "sion_1814", + "uuid": "{1880FA04-7E89-44BE-9C63-956B7E67CA99}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 21.104, + 5.959, + 564.391 + ], + "size": [ + 17.863, + 7.531, + 15.66 + ], + "groundY": 2.193, + "roofY": 9.724, + "wallCount": 11, + "roofCount": 2 + }, + { + "id": "sion_1815", + "uuid": "{D4949926-C23B-4F3E-932F-ECD086E8AFFD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 146.541, + 27.857, + 33.318 + ], + "size": [ + 25.371, + 24.838, + 14.796 + ], + "groundY": 15.438, + "roofY": 40.276, + "wallCount": 13, + "roofCount": 15 + }, + { + "id": "sion_1816", + "uuid": "{BDCC4F98-EE3D-463C-8BE5-9F5191F77FCB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -247.951, + 54.032, + -512.816 + ], + "size": [ + 15.16, + 14.241, + 13.196 + ], + "groundY": 46.912, + "roofY": 61.153, + "wallCount": 58, + "roofCount": 55 + }, + { + "id": "sion_1817", + "uuid": "{0ED9B746-D9B5-4D61-8346-68DC7175F87B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1351.129, + 17.68, + 92.83 + ], + "size": [ + 41.102, + 23.71, + 13.867 + ], + "groundY": 5.825, + "roofY": 29.535, + "wallCount": 37, + "roofCount": 10 + }, + { + "id": "sion_1818", + "uuid": "{01BD7D28-CA6A-4164-B97B-07FE7BF91D82}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -88.498, + 32.998, + -96.321 + ], + "size": [ + 61.754, + 18.537, + 34.66 + ], + "groundY": 23.73, + "roofY": 42.267, + "wallCount": 110, + "roofCount": 71 + }, + { + "id": "sion_1819", + "uuid": "{AEFAC067-929C-4C84-B699-A2DE1B9B88B1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -350.561, + 9.155, + 599.715 + ], + "size": [ + 33.027, + 17.314, + 14.646 + ], + "groundY": 0.498, + "roofY": 17.812, + "wallCount": 49, + "roofCount": 12 + }, + { + "id": "sion_1820", + "uuid": "{90A636D2-83CA-4624-81DD-702B0AD9EEE7}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 2, + 2 + ], + "center": [ + -9.463, + 86.736, + -360.359 + ], + "size": [ + 8.785, + 5.588, + 4.89 + ], + "groundY": 83.942, + "roofY": 89.53, + "wallCount": 53, + "roofCount": 6 + }, + { + "id": "sion_1821", + "uuid": "{49A497DC-FAFF-46E8-A2C8-7FB9EB920A9E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1031.09, + 7.383, + 255.678 + ], + "size": [ + 6.539, + 5.418, + 10.561 + ], + "groundY": 4.674, + "roofY": 10.092, + "wallCount": 43, + "roofCount": 30 + }, + { + "id": "sion_1822", + "uuid": "{7361957A-26D0-4FEF-BAFC-9F796159D8FD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 510.256, + 7.888, + 517.893 + ], + "size": [ + 55.059, + 10.804, + 61.347 + ], + "groundY": 2.486, + "roofY": 13.29, + "wallCount": 31, + "roofCount": 12 + }, + { + "id": "sion_1823", + "uuid": "{B2FB40B3-A160-481A-ADC0-D9774E1433B3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -289.756, + 37.672, + -109.225 + ], + "size": [ + 85.16, + 24.034, + 67.05 + ], + "groundY": 25.655, + "roofY": 49.689, + "wallCount": 240, + "roofCount": 177 + }, + { + "id": "sion_1824", + "uuid": "{63557910-3845-42DA-9F47-3E69B34CF32C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -394.826, + 65.31, + -703.56 + ], + "size": [ + 19.473, + 16.617, + 21.034 + ], + "groundY": 57.001, + "roofY": 73.618, + "wallCount": 74, + "roofCount": 35 + }, + { + "id": "sion_1825", + "uuid": "{C9F172AD-471D-4C57-85DE-B2651747748B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 136.637, + 130.659, + -231.921 + ], + "size": [ + 9.617, + 12.279, + 11.385 + ], + "groundY": 124.52, + "roofY": 136.799, + "wallCount": 37, + "roofCount": 23 + }, + { + "id": "sion_1826", + "uuid": "{5D6D20C6-547C-435A-B39F-2938FFE59D5D}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -314.383, + 13.868, + 639.566 + ], + "size": [ + 90.625, + 30.216, + 33.858 + ], + "groundY": -1.24, + "roofY": 28.976, + "wallCount": 106, + "roofCount": 36 + }, + { + "id": "sion_1827", + "uuid": "{D9EC9BFD-50CE-4D01-B66C-4A93A2314950}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 142.051, + 78.196, + -335.422 + ], + "size": [ + 12.055, + 8.679, + 11.874 + ], + "groundY": 73.856, + "roofY": 82.535, + "wallCount": 32, + "roofCount": 15 + }, + { + "id": "sion_1828", + "uuid": "{41FBBD9F-07B9-48A7-A282-A7B0232CA9C9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 355.156, + 10.151, + 365.626 + ], + "size": [ + 16.594, + 14.564, + 26.17 + ], + "groundY": 2.869, + "roofY": 17.433, + "wallCount": 26, + "roofCount": 23 + }, + { + "id": "sion_1829", + "uuid": "{981D9D26-3472-4F20-BA74-CD22BFF94827}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -210.705, + 65.84, + -787.474 + ], + "size": [ + 14.582, + 11.777, + 16.458 + ], + "groundY": 59.952, + "roofY": 71.729, + "wallCount": 51, + "roofCount": 20 + }, + { + "id": "sion_1830", + "uuid": "{F0B14ECB-E8D5-453E-8E4B-AB8129E599CE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 405.691, + 57.896, + -861.788 + ], + "size": [ + 30.992, + 11.989, + 21.07 + ], + "groundY": 51.901, + "roofY": 63.89, + "wallCount": 20, + "roofCount": 18 + }, + { + "id": "sion_1831", + "uuid": "{1870DED5-43E1-48D4-98D9-923D8946862E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 357.0, + 209.147, + -1472.217 + ], + "size": [ + 8.438, + 7.273, + 6.974 + ], + "groundY": 205.511, + "roofY": 212.784, + "wallCount": 53, + "roofCount": 2 + }, + { + "id": "sion_1832", + "uuid": "{66FB7AE5-2A01-47AE-94FA-AE0E6107634F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 221.523, + 56.659, + -668.84 + ], + "size": [ + 22.0, + 9.491, + 35.332 + ], + "groundY": 51.914, + "roofY": 61.405, + "wallCount": 37, + "roofCount": 33 + }, + { + "id": "sion_1833", + "uuid": "{A0A2BF28-84B9-4056-BD56-040E0799161A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 82.211, + 8.72, + 1027.369 + ], + "size": [ + 31.43, + 10.588, + 28.548 + ], + "groundY": 3.426, + "roofY": 14.014, + "wallCount": 37, + "roofCount": 23 + }, + { + "id": "sion_1834", + "uuid": "{47DD4104-02E3-4F92-8938-EA1F7E1D8CF1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -189.24, + 76.283, + -881.819 + ], + "size": [ + 13.535, + 18.246, + 14.769 + ], + "groundY": 67.16, + "roofY": 85.406, + "wallCount": 54, + "roofCount": 52 + }, + { + "id": "sion_1835", + "uuid": "{019F32F5-2C35-4D09-9F59-AE81F18D3A27}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -31.465, + 85.688, + -348.636 + ], + "size": [ + 10.836, + 22.051, + 9.906 + ], + "groundY": 74.663, + "roofY": 96.714, + "wallCount": 49, + "roofCount": 4 + }, + { + "id": "sion_1836", + "uuid": "{8A9D1E91-9852-4C6A-8F36-6067538C8957}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 388.068, + 81.358, + -1016.764 + ], + "size": [ + 6.738, + 8.198, + 5.706 + ], + "groundY": 77.259, + "roofY": 85.457, + "wallCount": 38, + "roofCount": 18 + }, + { + "id": "sion_1837", + "uuid": "{7777C6A3-71AE-43DF-A6E7-478B6C1137A9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -87.098, + 58.337, + -222.318 + ], + "size": [ + 26.18, + 23.158, + 19.112 + ], + "groundY": 46.758, + "roofY": 69.916, + "wallCount": 22, + "roofCount": 28 + }, + { + "id": "sion_1838", + "uuid": "{7F2BF8B3-1E84-4DA7-B70A-AE67806899CF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -230.949, + 51.813, + -451.054 + ], + "size": [ + 83.633, + 24.358, + 54.262 + ], + "groundY": 39.634, + "roofY": 63.992, + "wallCount": 108, + "roofCount": 119 + }, + { + "id": "sion_1839", + "uuid": "{96232927-A4B4-4478-ABAB-779BFCD2E28D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 264.949, + 22.186, + 264.745 + ], + "size": [ + 44.477, + 32.95, + 56.055 + ], + "groundY": 5.711, + "roofY": 38.661, + "wallCount": 83, + "roofCount": 57 + }, + { + "id": "sion_1840", + "uuid": "{C938FACD-8646-4D7E-B070-8F1C4EEB1729}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -290.482, + 39.122, + -165.845 + ], + "size": [ + 23.199, + 16.311, + 17.636 + ], + "groundY": 30.967, + "roofY": 47.278, + "wallCount": 36, + "roofCount": 14 + }, + { + "id": "sion_1841", + "uuid": "{8674A569-BE29-41C8-BAFC-9D48890F2901}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 1019.713, + 16.039, + 27.166 + ], + "size": [ + 43.559, + 23.196, + 36.406 + ], + "groundY": 4.441, + "roofY": 27.637, + "wallCount": 26, + "roofCount": 2 + }, + { + "id": "sion_1842", + "uuid": "{77B76909-930A-49FC-A739-2AF6A337B137}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -295.32, + 44.634, + -369.152 + ], + "size": [ + 16.977, + 10.382, + 15.061 + ], + "groundY": 39.443, + "roofY": 49.824, + "wallCount": 30, + "roofCount": 9 + }, + { + "id": "sion_1843", + "uuid": "{154F176A-2853-4E1F-86E4-168C9D9666E3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 817.168, + 11.885, + 993.743 + ], + "size": [ + 14.117, + 11.006, + 14.93 + ], + "groundY": 6.382, + "roofY": 17.388, + "wallCount": 25, + "roofCount": 11 + }, + { + "id": "sion_1844", + "uuid": "{6E0FDD16-FA37-45C1-BE0E-50A96386B22D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 1 + ], + "center": [ + 1116.24, + 11.336, + -852.513 + ], + "size": [ + 21.074, + 8.045, + 26.76 + ], + "groundY": 7.314, + "roofY": 15.359, + "wallCount": 18, + "roofCount": 26 + }, + { + "id": "sion_1845", + "uuid": "{D6F80474-826D-411F-9941-3AD80D1CD16A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 278.359, + 7.319, + 501.581 + ], + "size": [ + 30.609, + 11.994, + 22.841 + ], + "groundY": 1.322, + "roofY": 13.316, + "wallCount": 32, + "roofCount": 16 + }, + { + "id": "sion_1846", + "uuid": "{E4A5906D-18E1-45C0-9E48-0C7682957A7C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 119.865, + 8.091, + 1041.402 + ], + "size": [ + 24.066, + 8.722, + 28.174 + ], + "groundY": 3.73, + "roofY": 12.452, + "wallCount": 14, + "roofCount": 2 + }, + { + "id": "sion_1847", + "uuid": "{34DAE8EA-016C-4132-95A4-959B1C6679D3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1197.27, + 12.205, + 313.944 + ], + "size": [ + 29.969, + 10.369, + 11.614 + ], + "groundY": 7.021, + "roofY": 17.389, + "wallCount": 31, + "roofCount": 28 + }, + { + "id": "sion_1848", + "uuid": "{5F0D543E-0D96-48D5-87D3-3B067BDA7618}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -236.561, + 62.053, + -635.858 + ], + "size": [ + 16.77, + 17.355, + 15.292 + ], + "groundY": 53.375, + "roofY": 70.73, + "wallCount": 53, + "roofCount": 57 + }, + { + "id": "sion_1849", + "uuid": "{A258F022-32AD-4A3E-BE4F-92BED2FEDB20}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 270.709, + 56.355, + -748.494 + ], + "size": [ + 16.27, + 10.734, + 14.473 + ], + "groundY": 50.988, + "roofY": 61.722, + "wallCount": 22, + "roofCount": 12 + }, + { + "id": "sion_1850", + "uuid": "{137AC709-7E44-4827-A08C-2D3AE71B84AC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -56.223, + 30.812, + -84.939 + ], + "size": [ + 31.898, + 15.573, + 40.343 + ], + "groundY": 23.025, + "roofY": 38.598, + "wallCount": 101, + "roofCount": 32 + }, + { + "id": "sion_1851", + "uuid": "{186D3953-3B6E-4DFB-9260-0478B9D7DB33}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1058.83, + 10.999, + 350.308 + ], + "size": [ + 15.184, + 10.364, + 12.198 + ], + "groundY": 5.817, + "roofY": 16.181, + "wallCount": 18, + "roofCount": 15 + }, + { + "id": "sion_1852", + "uuid": "{56904E4D-9710-4BF0-A87F-F395345C0B10}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 221.289, + 188.758, + -1463.221 + ], + "size": [ + 23.031, + 13.504, + 19.226 + ], + "groundY": 182.006, + "roofY": 195.51, + "wallCount": 42, + "roofCount": 15 + }, + { + "id": "sion_1853", + "uuid": "{776D2F45-169E-4AC0-BC52-95AB79EECD3B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 635.549, + 6.899, + 772.231 + ], + "size": [ + 9.098, + 9.25, + 8.356 + ], + "groundY": 2.274, + "roofY": 11.524, + "wallCount": 64, + "roofCount": 6 + }, + { + "id": "sion_1854", + "uuid": "{2FF13B8B-3AEB-45E1-9CE8-469CCAE82610}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 1 + ], + "center": [ + 1213.279, + 11.858, + -905.597 + ], + "size": [ + 98.434, + 13.158, + 82.056 + ], + "groundY": 5.279, + "roofY": 18.437, + "wallCount": 126, + "roofCount": 83 + }, + { + "id": "sion_1855", + "uuid": "{842534AA-6E52-43A4-9B28-B5A7B940CE08}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 351.475, + 6.913, + 815.336 + ], + "size": [ + 64.777, + 9.944, + 57.12 + ], + "groundY": 1.941, + "roofY": 11.885, + "wallCount": 60, + "roofCount": 22 + }, + { + "id": "sion_1856", + "uuid": "{31DF100C-9ED6-44E3-AA72-5ED42828C77C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -186.303, + 76.258, + -906.88 + ], + "size": [ + 12.934, + 14.714, + 15.468 + ], + "groundY": 68.901, + "roofY": 83.615, + "wallCount": 58, + "roofCount": 54 + }, + { + "id": "sion_1857", + "uuid": "{BC63E732-2FC4-495A-9602-3481769661B7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 323.602, + 21.614, + -127.585 + ], + "size": [ + 19.867, + 27.705, + 27.615 + ], + "groundY": 7.762, + "roofY": 35.467, + "wallCount": 59, + "roofCount": 6 + }, + { + "id": "sion_1858", + "uuid": "{02B3DCC2-48B6-468D-B721-F9D539523EB2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1041.637, + 13.492, + 306.838 + ], + "size": [ + 51.211, + 18.898, + 28.102 + ], + "groundY": 4.043, + "roofY": 22.941, + "wallCount": 37, + "roofCount": 17 + }, + { + "id": "sion_1859", + "uuid": "{ACE82AEB-68EE-4699-9268-54CBED9C9731}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 175.518, + 15.683, + -120.43 + ], + "size": [ + 7.762, + 5.284, + 9.798 + ], + "groundY": 13.041, + "roofY": 18.325, + "wallCount": 10, + "roofCount": 2 + }, + { + "id": "sion_1860", + "uuid": "{49C840A0-F392-456E-8F93-5402B718FC76}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 383.986, + 213.262, + -1477.853 + ], + "size": [ + 19.98, + 9.026, + 20.827 + ], + "groundY": 208.749, + "roofY": 217.775, + "wallCount": 42, + "roofCount": 27 + }, + { + "id": "sion_1861", + "uuid": "{23DBD7EC-4DEE-4B6C-A224-337A4C689724}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 395.15, + 63.48, + -667.427 + ], + "size": [ + 16.238, + 5.668, + 10.304 + ], + "groundY": 60.646, + "roofY": 66.314, + "wallCount": 29, + "roofCount": 10 + }, + { + "id": "sion_1862", + "uuid": "{C5E5118D-B365-42C2-ACB9-5D2B3968D5BD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -304.295, + 39.604, + -143.129 + ], + "size": [ + 83.84, + 23.205, + 36.566 + ], + "groundY": 28.002, + "roofY": 51.207, + "wallCount": 70, + "roofCount": 78 + }, + { + "id": "sion_1863", + "uuid": "{65409139-BA7C-4238-8C44-25323097C142}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 233.641, + 15.005, + 223.745 + ], + "size": [ + 17.266, + 11.394, + 15.454 + ], + "groundY": 9.308, + "roofY": 20.702, + "wallCount": 14, + "roofCount": 4 + }, + { + "id": "sion_1864", + "uuid": "{41F1CBDC-CBF3-47BD-87B3-14738B86F59B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 132.176, + 63.29, + -785.037 + ], + "size": [ + 30.836, + 16.94, + 31.531 + ], + "groundY": 54.82, + "roofY": 71.76, + "wallCount": 79, + "roofCount": 47 + }, + { + "id": "sion_1865", + "uuid": "{8136091F-4073-49C5-B969-3EE5129B7EBC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -383.664, + 247.844, + -1521.707 + ], + "size": [ + 2.953, + 4.535, + 2.896 + ], + "groundY": 245.577, + "roofY": 250.112, + "wallCount": 10, + "roofCount": 2 + }, + { + "id": "sion_1866", + "uuid": "{C5CB2DB8-9C43-4EA7-980F-F468D43E1B58}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 4, + 2 + ], + "center": [ + 528.148, + 82.8, + -451.849 + ], + "size": [ + 57.641, + 13.296, + 77.962 + ], + "groundY": 76.152, + "roofY": 89.448, + "wallCount": 60, + "roofCount": 27 + }, + { + "id": "sion_1867", + "uuid": "{9FD8C2E6-E921-43E9-AEA0-E68A1B14EE60}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -393.314, + 27.094, + 152.301 + ], + "size": [ + 25.817, + 22.547, + 31.858 + ], + "groundY": 15.821, + "roofY": 38.368, + "wallCount": 20, + "roofCount": 26 + }, + { + "id": "sion_1868", + "uuid": "{28DBCAC6-64D8-4CF8-9326-BC0813924104}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -393.219, + 68.536, + -757.878 + ], + "size": [ + 14.625, + 14.076, + 13.828 + ], + "groundY": 61.498, + "roofY": 75.574, + "wallCount": 31, + "roofCount": 41 + }, + { + "id": "sion_1869", + "uuid": "{90442474-8869-41CB-8700-18AE9DDE06A7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 71.166, + 70.764, + -816.58 + ], + "size": [ + 33.238, + 22.205, + 32.109 + ], + "groundY": 59.662, + "roofY": 81.867, + "wallCount": 45, + "roofCount": 23 + }, + { + "id": "sion_1870", + "uuid": "{9D02E08D-EB36-41D8-B507-596D41964A19}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1222.73, + 15.764, + 415.213 + ], + "size": [ + 61.281, + 19.308, + 77.632 + ], + "groundY": 6.11, + "roofY": 25.418, + "wallCount": 136, + "roofCount": 65 + }, + { + "id": "sion_1871", + "uuid": "{8241824B-5912-4343-9BEC-B518BE823B54}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -116.969, + 59.215, + -273.727 + ], + "size": [ + 124.172, + 53.996, + 101.683 + ], + "groundY": 32.216, + "roofY": 86.213, + "wallCount": 689, + "roofCount": 330 + }, + { + "id": "sion_1872", + "uuid": "{CFF85E70-D1D7-432F-AC64-3F6B2198AC82}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 390.617, + 215.274, + -1421.612 + ], + "size": [ + 17.969, + 9.542, + 16.815 + ], + "groundY": 210.503, + "roofY": 220.045, + "wallCount": 46, + "roofCount": 24 + }, + { + "id": "sion_1873", + "uuid": "{93000D43-E2A3-4ACF-93BE-0010FA5EC385}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -397.75, + 47.811, + -477.718 + ], + "size": [ + 25.562, + 8.69, + 30.952 + ], + "groundY": 43.466, + "roofY": 52.156, + "wallCount": 19, + "roofCount": 24 + }, + { + "id": "sion_1874", + "uuid": "{3A7E59BF-395B-4CD3-B535-E506B550C47C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 148.725, + 82.483, + -1016.584 + ], + "size": [ + 21.223, + 22.138, + 21.092 + ], + "groundY": 71.414, + "roofY": 93.552, + "wallCount": 32, + "roofCount": 21 + }, + { + "id": "sion_1875", + "uuid": "{2DBECF33-3795-4A9C-B6A5-F01BECE8BB15}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 174.115, + 4.634, + 672.326 + ], + "size": [ + 13.223, + 5.571, + 11.607 + ], + "groundY": 1.848, + "roofY": 7.419, + "wallCount": 10, + "roofCount": 2 + }, + { + "id": "sion_1876", + "uuid": "{70A15B2D-BA79-4E73-8859-EC15085F099D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 318.49, + 6.283, + 940.952 + ], + "size": [ + 42.129, + 11.2, + 40.1 + ], + "groundY": 0.683, + "roofY": 11.883, + "wallCount": 18, + "roofCount": 28 + }, + { + "id": "sion_1877", + "uuid": "{27F03AFC-E099-4925-AC4C-DC281352BB5C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -127.311, + 22.134, + 302.373 + ], + "size": [ + 56.652, + 21.433, + 30.145 + ], + "groundY": 11.417, + "roofY": 32.85, + "wallCount": 14, + "roofCount": 22 + }, + { + "id": "sion_1878", + "uuid": "{A2EC7D87-CFF3-465C-8EB5-137F6184A902}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 1 + ], + "center": [ + 532.316, + 59.629, + -954.933 + ], + "size": [ + 74.578, + 24.79, + 31.582 + ], + "groundY": 47.234, + "roofY": 72.024, + "wallCount": 68, + "roofCount": 22 + }, + { + "id": "sion_1879", + "uuid": "{2EDACA40-F9A2-4140-A36A-93030322015A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 2 + ], + "center": [ + 215.004, + 15.217, + -128.614 + ], + "size": [ + 57.266, + 5.094, + 15.521 + ], + "groundY": 12.67, + "roofY": 17.764, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1880", + "uuid": "{C560AD54-1ADD-41D3-9EC6-CBAC43A0AE72}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 13.264, + 74.747, + -914.928 + ], + "size": [ + 43.285, + 18.646, + 30.598 + ], + "groundY": 65.424, + "roofY": 84.07, + "wallCount": 14, + "roofCount": 42 + }, + { + "id": "sion_1881", + "uuid": "{3DEA6156-0889-4FCF-AA83-EA9CEBB523F6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 116.424, + 17.164, + 496.31 + ], + "size": [ + 101.121, + 30.152, + 42.571 + ], + "groundY": 2.088, + "roofY": 32.24, + "wallCount": 10, + "roofCount": 2 + }, + { + "id": "sion_1882", + "uuid": "{358232B3-9F04-4CA0-B4AC-CC901204DBCF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -227.582, + 44.621, + -222.145 + ], + "size": [ + 92.367, + 24.836, + 147.958 + ], + "groundY": 32.203, + "roofY": 57.039, + "wallCount": 121, + "roofCount": 579 + }, + { + "id": "sion_1883", + "uuid": "{327FDE3B-440C-40A4-B133-9AE188C9B9C0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -169.285, + 65.422, + -736.243 + ], + "size": [ + 21.531, + 15.57, + 24.258 + ], + "groundY": 57.637, + "roofY": 73.207, + "wallCount": 34, + "roofCount": 10 + }, + { + "id": "sion_1884", + "uuid": "{978091D1-4976-4BB8-8F31-EFC2056BB859}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 194.998, + 187.847, + -1435.358 + ], + "size": [ + 15.676, + 9.996, + 17.989 + ], + "groundY": 182.849, + "roofY": 192.845, + "wallCount": 27, + "roofCount": 18 + }, + { + "id": "sion_1885", + "uuid": "{6DA4E2E9-8502-4A7E-9192-5E78469E622A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -202.471, + 21.599, + 351.118 + ], + "size": [ + 52.387, + 28.142, + 66.018 + ], + "groundY": 7.528, + "roofY": 35.67, + "wallCount": 62, + "roofCount": 80 + }, + { + "id": "sion_1886", + "uuid": "{76A7B6ED-316D-481A-817C-BA2C45323A33}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1461.518, + 10.021, + 4.283 + ], + "size": [ + 8.691, + 5.159, + 13.092 + ], + "groundY": 7.442, + "roofY": 12.601, + "wallCount": 17, + "roofCount": 31 + }, + { + "id": "sion_1887", + "uuid": "{309738DF-3704-4EE3-9E36-A5C80AB57A49}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 300.52, + 57.713, + -761.958 + ], + "size": [ + 33.664, + 17.579, + 62.984 + ], + "groundY": 48.924, + "roofY": 66.503, + "wallCount": 69, + "roofCount": 43 + }, + { + "id": "sion_1888", + "uuid": "{7679A78E-7122-4EDB-8E77-27F234BBE374}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -104.475, + 5.201, + 873.146 + ], + "size": [ + 92.973, + 9.724, + 72.579 + ], + "groundY": 0.339, + "roofY": 10.063, + "wallCount": 42, + "roofCount": 15 + }, + { + "id": "sion_1889", + "uuid": "{2A3E5E00-3A72-46EA-8020-A9E81109802A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 238.371, + 56.336, + -746.066 + ], + "size": [ + 13.094, + 9.313, + 16.22 + ], + "groundY": 51.68, + "roofY": 60.993, + "wallCount": 26, + "roofCount": 11 + }, + { + "id": "sion_1890", + "uuid": "{A1F0FA6B-9ECA-41B8-87BE-2E9D7D6856F7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 805.373, + 9.493, + 927.708 + ], + "size": [ + 16.512, + 9.339, + 17.936 + ], + "groundY": 4.824, + "roofY": 14.163, + "wallCount": 32, + "roofCount": 20 + }, + { + "id": "sion_1891", + "uuid": "{33B44B2D-8E17-4132-A191-6579A8C8E965}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 5.762, + 61.465, + -644.525 + ], + "size": [ + 16.82, + 18.024, + 18.998 + ], + "groundY": 52.453, + "roofY": 70.477, + "wallCount": 41, + "roofCount": 18 + }, + { + "id": "sion_1892", + "uuid": "{A2C376AD-E4DB-4579-9441-5AD0F1551BF5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 760.615, + 7.6, + 869.542 + ], + "size": [ + 11.691, + 5.906, + 15.287 + ], + "groundY": 4.647, + "roofY": 10.553, + "wallCount": 24, + "roofCount": 2 + }, + { + "id": "sion_1893", + "uuid": "{645B8A97-DE44-4541-9737-55F307A4CE91}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1223.988, + 12.349, + 345.338 + ], + "size": [ + 29.969, + 10.611, + 11.613 + ], + "groundY": 7.043, + "roofY": 17.654, + "wallCount": 30, + "roofCount": 21 + }, + { + "id": "sion_1894", + "uuid": "{68D3244B-268F-4CD3-AE27-1C1D4E383150}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -398.662, + 50.198, + -336.674 + ], + "size": [ + 12.051, + 27.062, + 12.632 + ], + "groundY": 36.667, + "roofY": 63.729, + "wallCount": 186, + "roofCount": 43 + }, + { + "id": "sion_1895", + "uuid": "{52F8AF5F-098B-483A-BD8D-160BC4CF2F24}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 566.484, + 221.926, + -1502.348 + ], + "size": [ + 32.641, + 10.265, + 39.431 + ], + "groundY": 216.793, + "roofY": 227.058, + "wallCount": 31, + "roofCount": 12 + }, + { + "id": "sion_1896", + "uuid": "{8279A159-5B05-4332-A5B9-1D78A85885C8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -18.531, + 101.573, + -1240.39 + ], + "size": [ + 51.601, + 22.83, + 102.454 + ], + "groundY": 90.158, + "roofY": 112.988, + "wallCount": 38, + "roofCount": 24 + }, + { + "id": "sion_1897", + "uuid": "{70F4882D-A374-4653-9E9C-1201CB762B83}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 126.582, + 77.759, + -332.088 + ], + "size": [ + 10.555, + 5.634, + 7.62 + ], + "groundY": 74.942, + "roofY": 80.576, + "wallCount": 25, + "roofCount": 31 + }, + { + "id": "sion_1898", + "uuid": "{41D0107C-4E32-4161-B0BD-8124010762DB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -185.01, + 63.664, + -686.886 + ], + "size": [ + 24.129, + 22.667, + 27.874 + ], + "groundY": 52.331, + "roofY": 74.998, + "wallCount": 32, + "roofCount": 8 + }, + { + "id": "sion_1899", + "uuid": "{898E18A6-BC60-4BE0-B8F1-3F0EAFDC60CD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 3 + ], + "center": [ + -306.553, + 17.482, + 447.329 + ], + "size": [ + 44.856, + 25.532, + 38.006 + ], + "groundY": 4.716, + "roofY": 30.248, + "wallCount": 19, + "roofCount": 4 + }, + { + "id": "sion_1900", + "uuid": "{33D31220-0678-47A0-8522-366506815A43}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 822.959, + 10.488, + -400.818 + ], + "size": [ + 26.285, + 13.556, + 24.75 + ], + "groundY": 3.71, + "roofY": 17.266, + "wallCount": 28, + "roofCount": 8 + }, + { + "id": "sion_1901", + "uuid": "{2C90D0E9-134B-44EC-A8E5-279A6EB095AB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -325.506, + 29.648, + 76.567 + ], + "size": [ + 115.66, + 26.474, + 113.14 + ], + "groundY": 16.411, + "roofY": 42.885, + "wallCount": 257, + "roofCount": 235 + }, + { + "id": "sion_1902", + "uuid": "{70E4743C-5A50-485D-A1C3-E3E3661DF046}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 438.652, + 214.779, + -1467.205 + ], + "size": [ + 9.227, + 5.791, + 8.533 + ], + "groundY": 211.883, + "roofY": 217.674, + "wallCount": 58, + "roofCount": 11 + }, + { + "id": "sion_1903", + "uuid": "{EEF518E1-D81F-4D80-B77C-B3581E79A127}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 751.291, + 9.983, + 237.485 + ], + "size": [ + 71.699, + 14.934, + 68.444 + ], + "groundY": 2.516, + "roofY": 17.45, + "wallCount": 39, + "roofCount": 21 + }, + { + "id": "sion_1904", + "uuid": "{BC9B9FC7-D363-4305-9A8C-14035D69B5FB}", + "name": "", + "class": "Sakrales Gebaeude", + "archStyle": "fortress", + "tile": [ + 2, + 2 + ], + "center": [ + -146.412, + 52.747, + -478.588 + ], + "size": [ + 23.715, + 24.51, + 32.398 + ], + "groundY": 40.492, + "roofY": 65.002, + "wallCount": 81, + "roofCount": 43 + }, + { + "id": "sion_1905", + "uuid": "{5CBC9BEE-71AD-437C-867E-017F6A922DA9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -281.1, + 58.476, + -582.338 + ], + "size": [ + 24.566, + 9.117, + 15.529 + ], + "groundY": 53.918, + "roofY": 63.034, + "wallCount": 18, + "roofCount": 31 + }, + { + "id": "sion_1906", + "uuid": "{E4FDEAF7-EF67-4986-A051-039578A9F6E5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 447.744, + 63.654, + -921.506 + ], + "size": [ + 21.715, + 9.988, + 20.496 + ], + "groundY": 58.66, + "roofY": 68.648, + "wallCount": 42, + "roofCount": 27 + }, + { + "id": "sion_1907", + "uuid": "{1EA20069-220D-48F1-8A69-FD162A2864E7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 206.057, + 8.992, + 383.753 + ], + "size": [ + 24.316, + 7.143, + 15.88 + ], + "groundY": 5.42, + "roofY": 12.563, + "wallCount": 10, + "roofCount": 2 + }, + { + "id": "sion_1908", + "uuid": "{653F73E1-7140-4F7F-8697-B4747DC1295C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -55.678, + 59.513, + -653.847 + ], + "size": [ + 24.473, + 19.098, + 27.236 + ], + "groundY": 49.964, + "roofY": 69.062, + "wallCount": 41, + "roofCount": 55 + }, + { + "id": "sion_1909", + "uuid": "{5D8C69C5-AB10-43AD-9A0E-F20B2C99008C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 146.383, + 72.393, + -960.009 + ], + "size": [ + 56.25, + 18.051, + 25.26 + ], + "groundY": 63.368, + "roofY": 81.419, + "wallCount": 27, + "roofCount": 27 + }, + { + "id": "sion_1910", + "uuid": "{620A53A1-86AD-42E1-BC46-B9151BCDD10F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1301.646, + 15.43, + 238.918 + ], + "size": [ + 13.738, + 14.731, + 25.297 + ], + "groundY": 8.065, + "roofY": 22.796, + "wallCount": 37, + "roofCount": 36 + }, + { + "id": "sion_1911", + "uuid": "{DD928247-CE45-44E7-9492-AE0619A5435F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -229.152, + 62.045, + -663.712 + ], + "size": [ + 14.148, + 14.883, + 12.542 + ], + "groundY": 54.604, + "roofY": 69.487, + "wallCount": 54, + "roofCount": 55 + }, + { + "id": "sion_1912", + "uuid": "{ADD6EE31-1D9C-4A92-AC36-B757ECB7901E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 441.771, + 6.629, + 970.291 + ], + "size": [ + 25.113, + 7.114, + 20.51 + ], + "groundY": 3.072, + "roofY": 10.185, + "wallCount": 27, + "roofCount": 20 + }, + { + "id": "sion_1913", + "uuid": "{E69044D0-2322-4D74-965B-4B68929F349A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 372.582, + 73.017, + -944.029 + ], + "size": [ + 20.586, + 13.51, + 18.561 + ], + "groundY": 66.262, + "roofY": 79.772, + "wallCount": 25, + "roofCount": 29 + }, + { + "id": "sion_1914", + "uuid": "{75AC8F7B-4203-461E-BE55-C46C96B0BFD3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -141.982, + 22.542, + 557.111 + ], + "size": [ + 108.262, + 42.758, + 46.218 + ], + "groundY": 1.163, + "roofY": 43.921, + "wallCount": 110, + "roofCount": 53 + }, + { + "id": "sion_1915", + "uuid": "{9C3ED28F-4737-430D-898A-F31411E3EF00}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -364.064, + 7.515, + 618.802 + ], + "size": [ + 14.652, + 14.484, + 11.914 + ], + "groundY": 0.273, + "roofY": 14.757, + "wallCount": 59, + "roofCount": 25 + }, + { + "id": "sion_1916", + "uuid": "{DA2A2B02-881C-40E3-9032-6075F351A76D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 384.035, + 7.383, + 500.863 + ], + "size": [ + 20.453, + 9.297, + 21.882 + ], + "groundY": 2.735, + "roofY": 12.032, + "wallCount": 22, + "roofCount": 30 + }, + { + "id": "sion_1917", + "uuid": "{3587C5F5-45E2-47F9-A8D8-9E8E11E274AF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -120.443, + 50.805, + -483.604 + ], + "size": [ + 41.41, + 17.209, + 46.663 + ], + "groundY": 42.201, + "roofY": 59.409, + "wallCount": 38, + "roofCount": 30 + }, + { + "id": "sion_1918", + "uuid": "{23D37DD7-8240-4E2C-9BDC-FD5BDF1A6B65}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 671.633, + 5.134, + 151.144 + ], + "size": [ + 13.547, + 5.222, + 16.708 + ], + "groundY": 2.523, + "roofY": 7.745, + "wallCount": 50, + "roofCount": 20 + }, + { + "id": "sion_1919", + "uuid": "{8DB818B1-E1EB-4902-9ED6-2D54D88248E1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 56.467, + 71.525, + -320.588 + ], + "size": [ + 29.418, + 19.27, + 23.174 + ], + "groundY": 61.89, + "roofY": 81.159, + "wallCount": 51, + "roofCount": 21 + }, + { + "id": "sion_1920", + "uuid": "{543248F5-6DF3-4E63-B071-7C3D4D56C983}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 834.283, + 14.08, + -197.646 + ], + "size": [ + 39.566, + 22.334, + 19.935 + ], + "groundY": 2.913, + "roofY": 25.247, + "wallCount": 113, + "roofCount": 24 + }, + { + "id": "sion_1921", + "uuid": "{F7486D12-9819-4715-BCC3-EF2CB17703DC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1193.535, + 12.527, + 47.642 + ], + "size": [ + 68.977, + 11.922, + 64.188 + ], + "groundY": 6.566, + "roofY": 18.488, + "wallCount": 16, + "roofCount": 26 + }, + { + "id": "sion_1922", + "uuid": "{348A7D9A-22EB-4515-A1A2-CF372A937881}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 642.92, + 9.119, + 828.501 + ], + "size": [ + 32.418, + 10.866, + 27.44 + ], + "groundY": 3.686, + "roofY": 14.552, + "wallCount": 12, + "roofCount": 2 + }, + { + "id": "sion_1923", + "uuid": "{337C0340-A041-42BC-A637-4C6E434C5466}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 467.156, + 6.407, + 714.329 + ], + "size": [ + 14.383, + 6.964, + 11.37 + ], + "groundY": 2.925, + "roofY": 9.889, + "wallCount": 23, + "roofCount": 29 + }, + { + "id": "sion_1924", + "uuid": "{4AC12F30-E1AC-478B-919F-30D269E5AF22}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1243.367, + 13.053, + 62.07 + ], + "size": [ + 25.797, + 15.404, + 23.08 + ], + "groundY": 5.351, + "roofY": 20.755, + "wallCount": 26, + "roofCount": 28 + }, + { + "id": "sion_1925", + "uuid": "{B5699D26-E8DE-459E-82A9-CF8CCC962B9D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 779.096, + 15.613, + -391.987 + ], + "size": [ + 22.012, + 24.759, + 14.642 + ], + "groundY": 3.234, + "roofY": 27.993, + "wallCount": 111, + "roofCount": 14 + }, + { + "id": "sion_1926", + "uuid": "{EAC03E9B-3220-45AA-8E3B-56ADD7C7A52A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 881.203, + 11.972, + -363.802 + ], + "size": [ + 22.188, + 19.504, + 18.642 + ], + "groundY": 2.22, + "roofY": 21.724, + "wallCount": 104, + "roofCount": 26 + }, + { + "id": "sion_1927", + "uuid": "{BF83A74A-BA38-44F9-861A-B5B9C95290F2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -366.887, + 35.297, + -233.085 + ], + "size": [ + 26.766, + 8.602, + 15.094 + ], + "groundY": 30.996, + "roofY": 39.598, + "wallCount": 13, + "roofCount": 25 + }, + { + "id": "sion_1928", + "uuid": "{C231B86C-1F81-4EE3-B17B-F7E6B6B372C6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 57.596, + 70.367, + -855.303 + ], + "size": [ + 27.613, + 19.36, + 38.678 + ], + "groundY": 60.687, + "roofY": 80.047, + "wallCount": 44, + "roofCount": 17 + }, + { + "id": "sion_1929", + "uuid": "{C5D94C33-B8AF-45F6-9D73-7DFB3BF6C0AA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 752.934, + 13.268, + 952.191 + ], + "size": [ + 74.641, + 16.569, + 42.741 + ], + "groundY": 4.983, + "roofY": 21.552, + "wallCount": 18, + "roofCount": 40 + }, + { + "id": "sion_1930", + "uuid": "{702758E9-86B7-46BB-B0FC-459A494CBA84}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 595.844, + 8.934, + 847.745 + ], + "size": [ + 34.203, + 11.56, + 28.812 + ], + "groundY": 3.154, + "roofY": 14.714, + "wallCount": 12, + "roofCount": 2 + }, + { + "id": "sion_1931", + "uuid": "{F11D3289-13A7-4CEC-B3E9-879E26454899}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 79.988, + 3.836, + 718.163 + ], + "size": [ + 19.258, + 6.266, + 18.977 + ], + "groundY": 0.703, + "roofY": 6.969, + "wallCount": 22, + "roofCount": 19 + }, + { + "id": "sion_1932", + "uuid": "{808E0BC8-AC1B-41C2-8C2F-3A390C41AF89}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -120.613, + 60.646, + -651.484 + ], + "size": [ + 65.727, + 20.535, + 90.569 + ], + "groundY": 50.378, + "roofY": 70.913, + "wallCount": 22, + "roofCount": 24 + }, + { + "id": "sion_1933", + "uuid": "{42662535-71F7-41DD-ACCF-68CF1D713091}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1043.105, + 10.21, + 244.543 + ], + "size": [ + 11.758, + 11.414, + 14.502 + ], + "groundY": 4.503, + "roofY": 15.917, + "wallCount": 26, + "roofCount": 24 + }, + { + "id": "sion_1934", + "uuid": "{B0EBB3E9-E1AF-41A1-BEDA-68F860F3A266}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 724.316, + 13.147, + 63.543 + ], + "size": [ + 40.602, + 24.016, + 20.338 + ], + "groundY": 1.139, + "roofY": 25.155, + "wallCount": 123, + "roofCount": 36 + }, + { + "id": "sion_1935", + "uuid": "{8B3BF6BF-3672-4848-89BB-3E2A0A4593B6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -5.092, + 76.791, + -943.706 + ], + "size": [ + 18.676, + 18.508, + 25.246 + ], + "groundY": 67.537, + "roofY": 86.045, + "wallCount": 40, + "roofCount": 31 + }, + { + "id": "sion_1936", + "uuid": "{E80A2749-E750-4010-8F59-07C968C275B7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -341.854, + 26.136, + 161.106 + ], + "size": [ + 27.934, + 22.146, + 37.63 + ], + "groundY": 15.063, + "roofY": 37.209, + "wallCount": 24, + "roofCount": 36 + }, + { + "id": "sion_1937", + "uuid": "{54052681-EAFE-403D-B5C6-91E58B1FCD50}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 229.723, + 65.155, + -857.881 + ], + "size": [ + 15.93, + 11.28, + 13.647 + ], + "groundY": 59.515, + "roofY": 70.795, + "wallCount": 42, + "roofCount": 36 + }, + { + "id": "sion_1938", + "uuid": "{D353490B-C451-4227-AD1F-BD14A788F286}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 141.902, + 23.813, + 197.916 + ], + "size": [ + 92.352, + 27.921, + 73.697 + ], + "groundY": 9.853, + "roofY": 37.774, + "wallCount": 130, + "roofCount": 63 + }, + { + "id": "sion_1939", + "uuid": "{1228E97F-4B4D-44E2-95C7-D2A3E96EA457}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 68.262, + 19.666, + 310.203 + ], + "size": [ + 51.766, + 24.86, + 43.456 + ], + "groundY": 7.236, + "roofY": 32.096, + "wallCount": 102, + "roofCount": 32 + }, + { + "id": "sion_1940", + "uuid": "{0EC370A8-8F7A-4D31-B52A-BFCA55E3AE8F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 445.022, + 6.991, + 805.965 + ], + "size": [ + 38.574, + 8.713, + 21.322 + ], + "groundY": 2.634, + "roofY": 11.347, + "wallCount": 41, + "roofCount": 16 + }, + { + "id": "sion_1941", + "uuid": "{71912629-7C6D-4D68-B278-2676FEA6351F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 93.016, + 26.56, + -12.98 + ], + "size": [ + 21.516, + 16.626, + 21.267 + ], + "groundY": 18.247, + "roofY": 34.873, + "wallCount": 19, + "roofCount": 15 + }, + { + "id": "sion_1942", + "uuid": "{B5E7FC11-1506-4D95-AAD0-C3D8CCBF0846}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -137.447, + 54.06, + -523.185 + ], + "size": [ + 30.16, + 23.948, + 57.153 + ], + "groundY": 42.086, + "roofY": 66.034, + "wallCount": 69, + "roofCount": 47 + }, + { + "id": "sion_1943", + "uuid": "{FB57DE28-36CA-4DFC-A2DD-0739C56265D6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 2 + ], + "center": [ + 1493.982, + 11.064, + -111.586 + ], + "size": [ + 32.731, + 8.566, + 50.523 + ], + "groundY": 6.781, + "roofY": 15.347, + "wallCount": 35, + "roofCount": 14 + }, + { + "id": "sion_1944", + "uuid": "{A48B434A-94DA-4A14-A18C-CA9192C48E37}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -103.084, + 81.15, + -932.866 + ], + "size": [ + 32.496, + 17.235, + 16.316 + ], + "groundY": 72.532, + "roofY": 89.767, + "wallCount": 37, + "roofCount": 47 + }, + { + "id": "sion_1945", + "uuid": "{14A0B6B1-4C90-4FA3-9C8C-0F426B8147A4}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 126.096, + 122.862, + -236.178 + ], + "size": [ + 20.113, + 5.962, + 12.416 + ], + "groundY": 119.881, + "roofY": 125.843, + "wallCount": 30, + "roofCount": 8 + }, + { + "id": "sion_1946", + "uuid": "{3677962F-9FFE-4B92-AC1C-0FEEDC464605}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -140.102, + 34.781, + 25.506 + ], + "size": [ + 49.602, + 23.752, + 43.848 + ], + "groundY": 22.905, + "roofY": 46.657, + "wallCount": 79, + "roofCount": 61 + }, + { + "id": "sion_1947", + "uuid": "{54D99972-AAE7-4CA7-9C4B-023CE9328498}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 766.648, + 17.349, + 4.772 + ], + "size": [ + 28.742, + 29.088, + 22.073 + ], + "groundY": 2.805, + "roofY": 31.893, + "wallCount": 142, + "roofCount": 19 + }, + { + "id": "sion_1948", + "uuid": "{9349D0AC-05A8-4476-8847-FA802F2DDD14}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 252.816, + 58.25, + -814.58 + ], + "size": [ + 16.867, + 12.779, + 15.878 + ], + "groundY": 51.861, + "roofY": 64.64, + "wallCount": 44, + "roofCount": 8 + }, + { + "id": "sion_1949", + "uuid": "{A97A4665-058D-421E-B806-3E42E045AF06}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -224.164, + 19.212, + 335.165 + ], + "size": [ + 18.477, + 16.584, + 17.484 + ], + "groundY": 10.92, + "roofY": 27.504, + "wallCount": 21, + "roofCount": 65 + }, + { + "id": "sion_1950", + "uuid": "{42508E99-B594-4425-98F4-423A2C7C17B1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 2 + ], + "center": [ + 1450.902, + 14.832, + -80.22 + ], + "size": [ + 22.984, + 16.897, + 28.544 + ], + "groundY": 6.384, + "roofY": 23.28, + "wallCount": 92, + "roofCount": 21 + }, + { + "id": "sion_1951", + "uuid": "{721859D4-7F7B-4BD4-9D1C-4F1D812CE469}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 3, + 1 + ], + "center": [ + 489.699, + 161.132, + -556.637 + ], + "size": [ + 17.781, + 6.584, + 5.048 + ], + "groundY": 157.84, + "roofY": 164.424, + "wallCount": 72, + "roofCount": 18 + }, + { + "id": "sion_1952", + "uuid": "{A739737F-71CD-48C3-8892-13C730066FE0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 288.932, + 14.143, + 974.641 + ], + "size": [ + 85.488, + 23.358, + 91.378 + ], + "groundY": 2.464, + "roofY": 25.821, + "wallCount": 61, + "roofCount": 68 + }, + { + "id": "sion_1953", + "uuid": "{A57219A4-013F-4931-B894-8EF8FDABB4F4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 0 + ], + "center": [ + 1260.443, + 23.916, + -1276.905 + ], + "size": [ + 6.394, + 7.889, + 6.26 + ], + "groundY": 19.971, + "roofY": 27.86, + "wallCount": 46, + "roofCount": 4 + }, + { + "id": "sion_1954", + "uuid": "{14F0658A-0AB0-4F3D-A911-E945952B7918}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 772.906, + 10.807, + -281.785 + ], + "size": [ + 38.508, + 16.426, + 23.981 + ], + "groundY": 2.594, + "roofY": 19.02, + "wallCount": 86, + "roofCount": 12 + }, + { + "id": "sion_1955", + "uuid": "{8EB95BB3-8323-4161-AA9C-507FED6897A9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 379.74, + 6.617, + 1043.975 + ], + "size": [ + 41.684, + 7.696, + 25.21 + ], + "groundY": 2.769, + "roofY": 10.465, + "wallCount": 18, + "roofCount": 29 + }, + { + "id": "sion_1956", + "uuid": "{0E1A2B6F-12AB-43CE-A192-3EB8C6CE8045}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 2 + ], + "center": [ + 1211.949, + 9.516, + -291.063 + ], + "size": [ + 88.734, + 13.694, + 72.431 + ], + "groundY": 2.669, + "roofY": 16.363, + "wallCount": 64, + "roofCount": 34 + }, + { + "id": "sion_1957", + "uuid": "{F7775B06-A34C-4A11-8B7E-1DD920FF36F8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 58.418, + 25.203, + 226.948 + ], + "size": [ + 106.258, + 27.614, + 66.838 + ], + "groundY": 11.396, + "roofY": 39.01, + "wallCount": 63, + "roofCount": 55 + }, + { + "id": "sion_1958", + "uuid": "{5BBFE66B-C365-4A6C-8067-BBC6F9518C95}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 889.643, + 15.239, + 129.973 + ], + "size": [ + 30.441, + 25.298, + 27.847 + ], + "groundY": 2.59, + "roofY": 27.888, + "wallCount": 96, + "roofCount": 10 + }, + { + "id": "sion_1959", + "uuid": "{5096FC99-6AA3-4072-9363-6125F30ACCB4}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 8.611, + 83.432, + -359.852 + ], + "size": [ + 48.598, + 9.104, + 12.974 + ], + "groundY": 78.88, + "roofY": 87.984, + "wallCount": 75, + "roofCount": 29 + }, + { + "id": "sion_1960", + "uuid": "{60131913-5F52-49B3-BE17-A733BF680F2F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 37.824, + 107.223, + -1368.709 + ], + "size": [ + 93.859, + 18.847, + 138.178 + ], + "groundY": 97.799, + "roofY": 116.646, + "wallCount": 109, + "roofCount": 63 + }, + { + "id": "sion_1961", + "uuid": "{5D781D52-B64D-43F9-AB63-E89DA61CC43A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 440.811, + 219.88, + -1409.546 + ], + "size": [ + 19.121, + 11.74, + 21.014 + ], + "groundY": 214.01, + "roofY": 225.75, + "wallCount": 67, + "roofCount": 25 + }, + { + "id": "sion_1962", + "uuid": "{BFA80E2D-72D1-437D-B6D4-D160E1E28C63}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -261.439, + 69.111, + -782.263 + ], + "size": [ + 41.699, + 19.578, + 27.904 + ], + "groundY": 59.322, + "roofY": 78.9, + "wallCount": 34, + "roofCount": 65 + }, + { + "id": "sion_1963", + "uuid": "{C16ECC60-56FF-49AD-B4B7-E4D9F6E4A69E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 230.299, + 195.976, + -1531.662 + ], + "size": [ + 18.762, + 12.888, + 13.607 + ], + "groundY": 189.532, + "roofY": 202.42, + "wallCount": 47, + "roofCount": 22 + }, + { + "id": "sion_1964", + "uuid": "{313D4FBD-4950-489D-A50F-5348966A8D76}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 366.258, + 212.61, + -1413.149 + ], + "size": [ + 6.359, + 7.326, + 6.442 + ], + "groundY": 208.947, + "roofY": 216.273, + "wallCount": 16, + "roofCount": 8 + }, + { + "id": "sion_1965", + "uuid": "{CE1F9A7F-2C3B-4DEA-ACB4-32528FAC7226}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 866.926, + 9.397, + -282.186 + ], + "size": [ + 14.258, + 12.742, + 14.351 + ], + "groundY": 3.026, + "roofY": 15.768, + "wallCount": 45, + "roofCount": 10 + }, + { + "id": "sion_1966", + "uuid": "{E0AE3620-76CA-4559-BC05-85F09EE9B144}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -358.947, + 23.306, + 291.159 + ], + "size": [ + 46.442, + 25.449, + 26.39 + ], + "groundY": 10.582, + "roofY": 36.031, + "wallCount": 47, + "roofCount": 21 + }, + { + "id": "sion_1967", + "uuid": "{1B26BD52-E12A-4788-9EE2-98B8582BE537}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 524.93, + 8.57, + 906.455 + ], + "size": [ + 39.141, + 16.27, + 56.178 + ], + "groundY": 0.435, + "roofY": 16.705, + "wallCount": 41, + "roofCount": 14 + }, + { + "id": "sion_1968", + "uuid": "{2F06A2AF-2CA0-450F-BFCD-BB5EE36EFBA7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1118.43, + 11.737, + 346.766 + ], + "size": [ + 12.594, + 12.152, + 10.34 + ], + "groundY": 5.661, + "roofY": 17.813, + "wallCount": 49, + "roofCount": 30 + }, + { + "id": "sion_1969", + "uuid": "{C27EC73E-3747-4D9D-A434-CD8F10E61797}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -255.896, + 19.467, + 269.159 + ], + "size": [ + 13.191, + 13.638, + 17.086 + ], + "groundY": 12.648, + "roofY": 26.286, + "wallCount": 59, + "roofCount": 36 + }, + { + "id": "sion_1970", + "uuid": "{E574867B-606B-4AA3-9028-740A9181CD30}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 199.498, + 21.09, + 216.573 + ], + "size": [ + 44.27, + 20.815, + 38.742 + ], + "groundY": 10.682, + "roofY": 31.497, + "wallCount": 12, + "roofCount": 37 + }, + { + "id": "sion_1971", + "uuid": "{778158D0-4884-4870-AF5D-D3BC02E68AA1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -200.914, + 72.054, + -818.204 + ], + "size": [ + 37.266, + 22.024, + 49.727 + ], + "groundY": 61.042, + "roofY": 83.066, + "wallCount": 90, + "roofCount": 28 + }, + { + "id": "sion_1972", + "uuid": "{CF99713B-AF8B-4181-A243-9271EA97C7FE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 397.398, + 5.726, + 955.487 + ], + "size": [ + 13.555, + 6.151, + 15.34 + ], + "groundY": 2.651, + "roofY": 8.802, + "wallCount": 28, + "roofCount": 4 + }, + { + "id": "sion_1973", + "uuid": "{178E094C-C9B9-4F7F-97FA-F97033B0BEC9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 1013.619, + 9.922, + 465.454 + ], + "size": [ + 18.668, + 7.491, + 15.844 + ], + "groundY": 6.176, + "roofY": 13.667, + "wallCount": 29, + "roofCount": 4 + }, + { + "id": "sion_1974", + "uuid": "{67D51070-125B-4EFA-A966-B72594909DF4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 1009.748, + 8.947, + -305.151 + ], + "size": [ + 48.442, + 12.278, + 53.716 + ], + "groundY": 2.808, + "roofY": 15.086, + "wallCount": 32, + "roofCount": 41 + }, + { + "id": "sion_1975", + "uuid": "{9F7E94E4-D242-4E31-BFA5-CA742AB1A0E1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 679.727, + 4.544, + 209.9 + ], + "size": [ + 8.609, + 5.006, + 9.794 + ], + "groundY": 2.041, + "roofY": 7.047, + "wallCount": 10, + "roofCount": 2 + }, + { + "id": "sion_1976", + "uuid": "{24117C78-FDFD-4609-B675-2F205AC7025F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 797.086, + 12.491, + -324.905 + ], + "size": [ + 38.031, + 19.642, + 23.764 + ], + "groundY": 2.67, + "roofY": 22.312, + "wallCount": 81, + "roofCount": 14 + }, + { + "id": "sion_1977", + "uuid": "{8AA09CC1-E609-4E00-83AE-A52687C3A414}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -40.174, + 16.826, + 533.798 + ], + "size": [ + 78.676, + 30.219, + 37.102 + ], + "groundY": 1.716, + "roofY": 31.935, + "wallCount": 8, + "roofCount": 2 + }, + { + "id": "sion_1978", + "uuid": "{E6167B5E-05EA-4CA3-BFEE-781774C7804C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -113.809, + 42.106, + -183.235 + ], + "size": [ + 10.602, + 11.324, + 9.431 + ], + "groundY": 36.444, + "roofY": 47.768, + "wallCount": 38, + "roofCount": 17 + }, + { + "id": "sion_1979", + "uuid": "{AAB38644-A330-49B0-86DE-95512724A452}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -39.787, + 54.995, + -373.242 + ], + "size": [ + 22.379, + 19.935, + 20.46 + ], + "groundY": 45.027, + "roofY": 64.962, + "wallCount": 57, + "roofCount": 16 + }, + { + "id": "sion_1980", + "uuid": "{4FADC621-1ED5-4C56-9863-575F397D689A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 512.822, + 7.991, + 1003.604 + ], + "size": [ + 72.004, + 13.672, + 71.962 + ], + "groundY": 1.155, + "roofY": 14.826, + "wallCount": 71, + "roofCount": 41 + }, + { + "id": "sion_1981", + "uuid": "{6BC5A2C1-4859-43C1-B8B3-B10B8BAACC63}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 429.785, + 88.488, + -1049.646 + ], + "size": [ + 64.93, + 9.13, + 21.87 + ], + "groundY": 83.923, + "roofY": 93.052, + "wallCount": 76, + "roofCount": 29 + }, + { + "id": "sion_1982", + "uuid": "{CBBC4A97-5149-4DF0-90F9-B5CF4C0E14A7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -353.742, + 43.197, + -206.065 + ], + "size": [ + 30.961, + 21.69, + 44.31 + ], + "groundY": 32.352, + "roofY": 54.042, + "wallCount": 36, + "roofCount": 64 + }, + { + "id": "sion_1983", + "uuid": "{43173533-CDF7-4AB7-8EDE-6823799E0C16}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1137.193, + 9.273, + 45.585 + ], + "size": [ + 28.41, + 9.912, + 25.322 + ], + "groundY": 4.317, + "roofY": 14.229, + "wallCount": 18, + "roofCount": 10 + }, + { + "id": "sion_1984", + "uuid": "{001D4FC2-9D88-4C49-B30B-FA11D809F8BB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 4 + ], + "center": [ + 1446.182, + 16.966, + 877.746 + ], + "size": [ + 21.301, + 12.032, + 20.891 + ], + "groundY": 10.95, + "roofY": 22.982, + "wallCount": 38, + "roofCount": 23 + }, + { + "id": "sion_1985", + "uuid": "{12124017-2227-461F-9C82-42AB23CF85A9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 74.783, + 17.264, + 348.458 + ], + "size": [ + 112.48, + 24.906, + 79.385 + ], + "groundY": 4.811, + "roofY": 29.717, + "wallCount": 148, + "roofCount": 83 + }, + { + "id": "sion_1986", + "uuid": "{8786D399-B630-4A00-957F-23440C7406F3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -222.146, + 35.812, + -47.093 + ], + "size": [ + 84.012, + 23.594, + 110.722 + ], + "groundY": 24.015, + "roofY": 47.609, + "wallCount": 311, + "roofCount": 328 + }, + { + "id": "sion_1987", + "uuid": "{15F86722-B75A-431E-98DA-DF616D2DE94C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -50.527, + 59.82, + -301.243 + ], + "size": [ + 24.398, + 21.612, + 24.038 + ], + "groundY": 49.014, + "roofY": 70.626, + "wallCount": 61, + "roofCount": 41 + }, + { + "id": "sion_1988", + "uuid": "{43ED597D-E516-4F46-8FBB-8DE30A8D976D}", + "name": "", + "class": "Unterirdisches Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 807.635, + 13.381, + -135.087 + ], + "size": [ + 75.277, + 22.394, + 68.904 + ], + "groundY": 2.184, + "roofY": 24.578, + "wallCount": 72, + "roofCount": 33 + }, + { + "id": "sion_1989", + "uuid": "{AE4AA09C-C05D-46A4-A45B-DD0A64D65D73}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 176.52, + 173.95, + -1232.274 + ], + "size": [ + 17.641, + 9.822, + 8.136 + ], + "groundY": 169.039, + "roofY": 178.861, + "wallCount": 39, + "roofCount": 17 + }, + { + "id": "sion_1990", + "uuid": "{916ACC88-E05A-48D8-8B57-567DDC313962}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 364.496, + 5.995, + 859.547 + ], + "size": [ + 13.969, + 7.742, + 22.152 + ], + "groundY": 2.124, + "roofY": 9.866, + "wallCount": 24, + "roofCount": 33 + }, + { + "id": "sion_1991", + "uuid": "{91EE520D-0124-4117-B6C6-307B49A57DE0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -358.158, + 33.284, + -3.394 + ], + "size": [ + 98.98, + 27.122, + 102.636 + ], + "groundY": 19.723, + "roofY": 46.845, + "wallCount": 199, + "roofCount": 154 + }, + { + "id": "sion_1992", + "uuid": "{AB89DF95-3AC7-41DA-92EF-29894D75B789}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 114.168, + 80.197, + -1006.086 + ], + "size": [ + 29.086, + 18.997, + 21.984 + ], + "groundY": 70.699, + "roofY": 89.696, + "wallCount": 38, + "roofCount": 25 + }, + { + "id": "sion_1993", + "uuid": "{9AA84D69-6D75-4AEB-9B04-9094A40EFD8F}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 2, + 2 + ], + "center": [ + -21.602, + 75.377, + -347.441 + ], + "size": [ + 5.992, + 5.468, + 4.912 + ], + "groundY": 72.643, + "roofY": 78.111, + "wallCount": 55, + "roofCount": 4 + }, + { + "id": "sion_1994", + "uuid": "{956B3F6F-4B13-4B45-B55C-534D0E8BA4D4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 150.268, + 180.574, + -1253.742 + ], + "size": [ + 5.769, + 10.0, + 6.395 + ], + "groundY": 175.574, + "roofY": 185.574, + "wallCount": 66, + "roofCount": 12 + }, + { + "id": "sion_1995", + "uuid": "{D4EE0420-9B82-4D5C-AA31-C8DDB1E6849A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -303.43, + 37.333, + -57.289 + ], + "size": [ + 31.289, + 25.776, + 30.359 + ], + "groundY": 24.445, + "roofY": 50.221, + "wallCount": 31, + "roofCount": 18 + }, + { + "id": "sion_1996", + "uuid": "{486C4C8A-13CD-495D-935A-008571F01D2F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 332.637, + 197.029, + -1501.067 + ], + "size": [ + 26.18, + 9.696, + 15.246 + ], + "groundY": 192.181, + "roofY": 201.877, + "wallCount": 29, + "roofCount": 8 + }, + { + "id": "sion_1997", + "uuid": "{1690A534-3E01-40B3-9613-4AEC58D4C2CA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -6.371, + 62.515, + -631.463 + ], + "size": [ + 24.672, + 20.436, + 26.498 + ], + "groundY": 52.297, + "roofY": 72.733, + "wallCount": 81, + "roofCount": 32 + }, + { + "id": "sion_1998", + "uuid": "{7A0F83CF-63A5-437E-8088-DD359C7CBFFA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 311.826, + 14.514, + 230.517 + ], + "size": [ + 92.246, + 16.606, + 91.038 + ], + "groundY": 6.211, + "roofY": 22.817, + "wallCount": 153, + "roofCount": 178 + }, + { + "id": "sion_1999", + "uuid": "{56E8D619-4240-47EE-832F-60AE5D2ACC33}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 379.051, + 94.226, + -1072.389 + ], + "size": [ + 20.938, + 6.961, + 10.492 + ], + "groundY": 90.746, + "roofY": 97.706, + "wallCount": 22, + "roofCount": 4 + }, + { + "id": "sion_2000", + "uuid": "{4D33D054-E9D1-4816-8BB8-A1DB4120E444}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 237.49, + 6.828, + 881.069 + ], + "size": [ + 51.809, + 9.522, + 40.156 + ], + "groundY": 2.067, + "roofY": 11.589, + "wallCount": 15, + "roofCount": 21 + }, + { + "id": "sion_2001", + "uuid": "{F81A4FE1-AE6A-46C8-8AF9-803E6D75E2F4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -389.045, + 25.544, + 184.678 + ], + "size": [ + 33.488, + 23.018, + 22.106 + ], + "groundY": 14.035, + "roofY": 37.052, + "wallCount": 69, + "roofCount": 117 + }, + { + "id": "sion_2002", + "uuid": "{20A7B36F-A491-4789-8DFF-45833FE4700F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 346.863, + 8.299, + 527.664 + ], + "size": [ + 40.688, + 11.55, + 37.32 + ], + "groundY": 2.524, + "roofY": 14.074, + "wallCount": 8, + "roofCount": 5 + }, + { + "id": "sion_2003", + "uuid": "{255A1E46-6A68-45AF-A3F4-E59DA9FB8D60}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 4 + ], + "center": [ + 1075.397, + 12.628, + 817.296 + ], + "size": [ + 46.949, + 12.418, + 30.939 + ], + "groundY": 6.419, + "roofY": 18.837, + "wallCount": 23, + "roofCount": 42 + }, + { + "id": "sion_2004", + "uuid": "{0BC605EA-C5AB-4987-A4E2-1B58E77C604C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -196.689, + 27.404, + 221.389 + ], + "size": [ + 69.223, + 26.311, + 77.334 + ], + "groundY": 14.249, + "roofY": 40.559, + "wallCount": 43, + "roofCount": 31 + }, + { + "id": "sion_2005", + "uuid": "{3457E9CD-BAF3-4AE2-BC04-1D16F0B9029F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 737.996, + 10.063, + 740.372 + ], + "size": [ + 54.781, + 11.15, + 97.857 + ], + "groundY": 4.488, + "roofY": 15.638, + "wallCount": 41, + "roofCount": 23 + }, + { + "id": "sion_2006", + "uuid": "{40BD895E-825F-4F8D-8024-38716E87E78C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 230.592, + 21.17, + 2.252 + ], + "size": [ + 14.473, + 20.219, + 32.492 + ], + "groundY": 11.061, + "roofY": 31.28, + "wallCount": 8, + "roofCount": 25 + }, + { + "id": "sion_2007", + "uuid": "{2A20AB08-B63C-41E2-8322-6484023DD13B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 428.693, + 15.403, + 226.706 + ], + "size": [ + 51.231, + 21.656, + 62.001 + ], + "groundY": 4.575, + "roofY": 26.231, + "wallCount": 84, + "roofCount": 24 + }, + { + "id": "sion_2008", + "uuid": "{EABCD282-3085-455A-9568-DB1BF230488E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 37.146, + 63.749, + -782.908 + ], + "size": [ + 9.684, + 10.082, + 8.854 + ], + "groundY": 58.708, + "roofY": 68.79, + "wallCount": 22, + "roofCount": 28 + }, + { + "id": "sion_2009", + "uuid": "{8D70DDDA-B9BE-4A12-B5CF-7521D8E6ABDC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 314.67, + 56.574, + -653.238 + ], + "size": [ + 54.293, + 6.486, + 18.55 + ], + "groundY": 53.331, + "roofY": 59.817, + "wallCount": 36, + "roofCount": 15 + }, + { + "id": "sion_2010", + "uuid": "{32E05008-ADC1-4F5B-A42B-73F65850686D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 285.094, + 17.572, + 147.742 + ], + "size": [ + 19.82, + 12.627, + 18.894 + ], + "groundY": 11.258, + "roofY": 23.885, + "wallCount": 11, + "roofCount": 10 + }, + { + "id": "sion_2011", + "uuid": "{4F58F6AF-3DC7-45EA-80C0-203375189CAB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -11.988, + 21.608, + 248.465 + ], + "size": [ + 40.227, + 19.781, + 30.218 + ], + "groundY": 11.717, + "roofY": 31.498, + "wallCount": 13, + "roofCount": 12 + }, + { + "id": "sion_2012", + "uuid": "{C65C12C2-35D1-4C1A-9B2F-4A3196C8B524}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 4 + ], + "center": [ + 1044.422, + 11.793, + 701.577 + ], + "size": [ + 27.414, + 12.776, + 86.22 + ], + "groundY": 5.405, + "roofY": 18.181, + "wallCount": 25, + "roofCount": 38 + }, + { + "id": "sion_2013", + "uuid": "{97308E46-CADC-4918-B7C1-FB19CB932653}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -349.531, + 45.956, + -321.883 + ], + "size": [ + 50.367, + 20.585, + 45.581 + ], + "groundY": 35.664, + "roofY": 56.249, + "wallCount": 62, + "roofCount": 76 + }, + { + "id": "sion_2014", + "uuid": "{FAFE8FEF-3BF4-44CC-ACC9-03254BF8A28A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -112.186, + 47.604, + -217.322 + ], + "size": [ + 25.004, + 23.112, + 25.944 + ], + "groundY": 36.048, + "roofY": 59.16, + "wallCount": 28, + "roofCount": 23 + }, + { + "id": "sion_2015", + "uuid": "{3577B5C6-8EAA-46F0-8360-8FCE45C241D1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 844.1, + 16.696, + -489.936 + ], + "size": [ + 30.082, + 26.322, + 25.827 + ], + "groundY": 3.535, + "roofY": 29.857, + "wallCount": 76, + "roofCount": 25 + }, + { + "id": "sion_2016", + "uuid": "{F1183402-0CB2-4696-9F43-DB1A2FD4C68C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -160.709, + 47.142, + -356.222 + ], + "size": [ + 22.543, + 23.946, + 49.992 + ], + "groundY": 35.169, + "roofY": 59.114, + "wallCount": 162, + "roofCount": 73 + }, + { + "id": "sion_2017", + "uuid": "{19C14512-B8F5-4936-9C98-808FCDE21A10}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -162.654, + 43.798, + -213.386 + ], + "size": [ + 15.785, + 25.473, + 25.294 + ], + "groundY": 31.061, + "roofY": 56.534, + "wallCount": 32, + "roofCount": 29 + }, + { + "id": "sion_2018", + "uuid": "{8BB987CD-E714-47F1-971D-9FB0A6EF5E8E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 248.545, + 6.366, + 579.191 + ], + "size": [ + 12.059, + 8.464, + 11.479 + ], + "groundY": 2.134, + "roofY": 10.598, + "wallCount": 10, + "roofCount": 2 + }, + { + "id": "sion_2019", + "uuid": "{1BD31419-F13B-4E08-ACA1-3D78F51C926A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 365.293, + 16.304, + -6.352 + ], + "size": [ + 15.188, + 19.526, + 39.233 + ], + "groundY": 6.541, + "roofY": 26.067, + "wallCount": 14, + "roofCount": 33 + }, + { + "id": "sion_2020", + "uuid": "{D642DA03-51A7-45E6-9550-263C62C048FB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 115.045, + 62.241, + -712.171 + ], + "size": [ + 35.457, + 15.823, + 38.206 + ], + "groundY": 54.33, + "roofY": 70.153, + "wallCount": 48, + "roofCount": 40 + }, + { + "id": "sion_2021", + "uuid": "{0F6D1263-CE51-459E-B181-B55C48EAB020}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -125.381, + 44.37, + -196.37 + ], + "size": [ + 85.473, + 28.429, + 48.098 + ], + "groundY": 30.155, + "roofY": 58.584, + "wallCount": 292, + "roofCount": 159 + }, + { + "id": "sion_2022", + "uuid": "{9E56A9C0-C23B-49E6-B754-B6CA83665F5E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 189.195, + 174.904, + -1236.667 + ], + "size": [ + 7.062, + 7.509, + 5.275 + ], + "groundY": 171.149, + "roofY": 178.658, + "wallCount": 21, + "roofCount": 11 + }, + { + "id": "sion_2023", + "uuid": "{26EFD633-8C99-4A25-A8D0-0F4CE47417DF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 720.256, + 8.565, + 865.755 + ], + "size": [ + 27.379, + 9.538, + 22.208 + ], + "groundY": 3.796, + "roofY": 13.334, + "wallCount": 27, + "roofCount": 30 + }, + { + "id": "sion_2024", + "uuid": "{CCD7B16F-F27B-4B7C-9C80-8B79323C661E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -277.937, + 44.425, + -302.257 + ], + "size": [ + 24.68, + 17.685, + 23.307 + ], + "groundY": 35.583, + "roofY": 53.268, + "wallCount": 21, + "roofCount": 18 + }, + { + "id": "sion_2025", + "uuid": "{16608281-E75D-4F5F-9ABC-5D1267451C6A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 251.572, + 140.944, + -1145.792 + ], + "size": [ + 3.754, + 7.132, + 4.362 + ], + "groundY": 137.378, + "roofY": 144.51, + "wallCount": 36, + "roofCount": 9 + }, + { + "id": "sion_2026", + "uuid": "{817ED20C-7F22-41F4-94B2-268C78DEDADC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -137.559, + 95.912, + -1162.957 + ], + "size": [ + 21.578, + 10.066, + 22.076 + ], + "groundY": 90.879, + "roofY": 100.945, + "wallCount": 47, + "roofCount": 25 + }, + { + "id": "sion_2027", + "uuid": "{89977434-0F6B-4F22-9C84-07130A857768}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -139.701, + 35.486, + -18.259 + ], + "size": [ + 67.465, + 24.393, + 90.952 + ], + "groundY": 23.289, + "roofY": 47.682, + "wallCount": 297, + "roofCount": 179 + }, + { + "id": "sion_2028", + "uuid": "{6481A135-C86F-4ED2-93C7-C6180E827833}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -137.939, + 79.537, + -917.5 + ], + "size": [ + 22.238, + 12.467, + 12.141 + ], + "groundY": 73.304, + "roofY": 85.771, + "wallCount": 36, + "roofCount": 29 + }, + { + "id": "sion_2029", + "uuid": "{BD3F9A61-B7AB-4A46-A84B-392175F54CF8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -29.004, + 61.076, + -673.889 + ], + "size": [ + 26.844, + 11.509, + 24.435 + ], + "groundY": 55.322, + "roofY": 66.831, + "wallCount": 56, + "roofCount": 40 + }, + { + "id": "sion_2030", + "uuid": "{57F9B937-E873-441C-B52E-5289261E0D4C}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 4, + 1 + ], + "center": [ + 554.525, + 130.85, + -546.225 + ], + "size": [ + 28.824, + 23.212, + 8.735 + ], + "groundY": 119.244, + "roofY": 142.456, + "wallCount": 81, + "roofCount": 14 + }, + { + "id": "sion_2031", + "uuid": "{1C6E1329-5E8C-4E69-A6E1-C385968D4523}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -81.695, + 32.548, + 88.381 + ], + "size": [ + 131.773, + 27.38, + 109.312 + ], + "groundY": 18.858, + "roofY": 46.238, + "wallCount": 183, + "roofCount": 203 + }, + { + "id": "sion_2032", + "uuid": "{ABA6DCAE-E952-410E-8557-F2B16AEC4649}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -100.662, + 69.527, + -799.026 + ], + "size": [ + 12.668, + 11.42, + 10.164 + ], + "groundY": 63.817, + "roofY": 75.237, + "wallCount": 42, + "roofCount": 28 + }, + { + "id": "sion_2033", + "uuid": "{44664914-C00E-49CC-A1D1-54FF8A5743EE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 817.869, + 10.966, + 468.21 + ], + "size": [ + 52.387, + 16.555, + 33.895 + ], + "groundY": 2.688, + "roofY": 19.243, + "wallCount": 76, + "roofCount": 52 + }, + { + "id": "sion_2034", + "uuid": "{FABD6F7F-7B6B-4157-B9F2-C6E527D44106}", + "name": "", + "class": "Hochhaus", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -386.627, + 12.847, + 747.214 + ], + "size": [ + 53.668, + 27.763, + 17.206 + ], + "groundY": -1.034, + "roofY": 26.729, + "wallCount": 73, + "roofCount": 12 + }, + { + "id": "sion_2035", + "uuid": "{2EB107C1-13D7-43A5-80B6-5A9E763C93A5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 253.768, + 20.283, + 68.524 + ], + "size": [ + 54.707, + 19.067, + 16.694 + ], + "groundY": 10.75, + "roofY": 29.817, + "wallCount": 35, + "roofCount": 23 + }, + { + "id": "sion_2036", + "uuid": "{86D46C63-ED80-4E8C-A613-F3273DCAF379}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 647.473, + 7.505, + 652.937 + ], + "size": [ + 48.859, + 9.891, + 64.548 + ], + "groundY": 2.56, + "roofY": 12.451, + "wallCount": 43, + "roofCount": 40 + }, + { + "id": "sion_2037", + "uuid": "{44B13B2E-39A2-43C8-A713-2402EAE66E7F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 339.551, + 211.452, + -1396.251 + ], + "size": [ + 15.281, + 5.122, + 14.96 + ], + "groundY": 208.891, + "roofY": 214.013, + "wallCount": 15, + "roofCount": 2 + }, + { + "id": "sion_2038", + "uuid": "{7C15E1BF-983B-4D8B-B181-5E80778C2E35}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -174.871, + 187.373, + -1386.754 + ], + "size": [ + 7.82, + 5.716, + 7.838 + ], + "groundY": 184.515, + "roofY": 190.231, + "wallCount": 27, + "roofCount": 16 + }, + { + "id": "sion_2039", + "uuid": "{E3887671-2CAB-4635-BF9C-5649A4C48529}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1030.756, + 12.84, + 428.909 + ], + "size": [ + 38.043, + 16.765, + 18.246 + ], + "groundY": 4.457, + "roofY": 21.222, + "wallCount": 36, + "roofCount": 33 + }, + { + "id": "sion_2040", + "uuid": "{A3536D74-A553-4CDB-9FD1-29D32BAEEC1A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -162.051, + 79.968, + -943.497 + ], + "size": [ + 12.992, + 13.685, + 23.336 + ], + "groundY": 73.126, + "roofY": 86.81, + "wallCount": 47, + "roofCount": 35 + }, + { + "id": "sion_2041", + "uuid": "{507D5991-9A52-4510-8D4F-060BCA2ACC46}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -167.51, + 5.322, + 1031.394 + ], + "size": [ + 18.871, + 9.702, + 19.046 + ], + "groundY": 0.471, + "roofY": 10.173, + "wallCount": 35, + "roofCount": 7 + }, + { + "id": "sion_2042", + "uuid": "{C60C00A6-8EA5-4AA3-9E31-84C5A5BCED46}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 449.52, + 8.11, + 706.754 + ], + "size": [ + 20.047, + 10.332, + 16.712 + ], + "groundY": 2.944, + "roofY": 13.276, + "wallCount": 22, + "roofCount": 27 + }, + { + "id": "sion_2043", + "uuid": "{88AB9BBB-5050-4580-928D-32472EEFAA34}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1113.557, + 14.663, + 379.641 + ], + "size": [ + 26.856, + 16.797, + 16.897 + ], + "groundY": 6.265, + "roofY": 23.062, + "wallCount": 103, + "roofCount": 16 + }, + { + "id": "sion_2044", + "uuid": "{F209A91F-830C-4B80-AF0F-42C349DE5266}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -145.051, + 26.918, + 198.274 + ], + "size": [ + 47.055, + 28.599, + 66.729 + ], + "groundY": 12.619, + "roofY": 41.218, + "wallCount": 38, + "roofCount": 64 + }, + { + "id": "sion_2045", + "uuid": "{0E72201A-D461-4A9E-9302-F786F312E723}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -273.33, + 22.856, + 240.099 + ], + "size": [ + 27.902, + 18.387, + 20.574 + ], + "groundY": 13.663, + "roofY": 32.05, + "wallCount": 25, + "roofCount": 59 + }, + { + "id": "sion_2046", + "uuid": "{2D07772A-15A5-440E-9D37-2DC566A65B0D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 872.141, + 269.885, + -1458.897 + ], + "size": [ + 10.445, + 8.82, + 9.337 + ], + "groundY": 265.475, + "roofY": 274.295, + "wallCount": 54, + "roofCount": 18 + }, + { + "id": "sion_2047", + "uuid": "{E425D519-C24E-429C-952D-86C25775C86A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 210.43, + 25.241, + 101.449 + ], + "size": [ + 33.836, + 23.542, + 30.316 + ], + "groundY": 13.47, + "roofY": 37.013, + "wallCount": 36, + "roofCount": 38 + }, + { + "id": "sion_2048", + "uuid": "{21A7FAA4-8FD4-4867-B022-CFC371F87678}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 331.717, + 208.95, + -1443.626 + ], + "size": [ + 16.895, + 12.896, + 17.021 + ], + "groundY": 202.502, + "roofY": 215.398, + "wallCount": 42, + "roofCount": 13 + }, + { + "id": "sion_2049", + "uuid": "{268996FD-29D1-44B8-8B17-83B74A8139C8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 1 + ], + "center": [ + 596.982, + 45.561, + -958.13 + ], + "size": [ + 34.16, + 13.916, + 34.628 + ], + "groundY": 38.603, + "roofY": 52.519, + "wallCount": 44, + "roofCount": 14 + }, + { + "id": "sion_2050", + "uuid": "{ED437F04-3DA6-453E-84FC-7B37915DD070}", + "name": "", + "class": "Kapelle", + "archStyle": "fortress", + "tile": [ + 2, + 1 + ], + "center": [ + -347.055, + 78.639, + -902.003 + ], + "size": [ + 24.562, + 9.668, + 23.494 + ], + "groundY": 73.805, + "roofY": 83.473, + "wallCount": 152, + "roofCount": 70 + }, + { + "id": "sion_2051", + "uuid": "{C4F5CD5E-AC57-4CB3-B680-9ED9CB72493F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 260.82, + 67.702, + -867.381 + ], + "size": [ + 14.281, + 9.475, + 13.3 + ], + "groundY": 62.965, + "roofY": 72.44, + "wallCount": 31, + "roofCount": 22 + }, + { + "id": "sion_2052", + "uuid": "{51FDAF9D-FC25-477A-8D1F-E8A4D6BDA2AF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 75.545, + 71.767, + -904.702 + ], + "size": [ + 26.184, + 18.326, + 21.312 + ], + "groundY": 62.604, + "roofY": 80.93, + "wallCount": 18, + "roofCount": 11 + }, + { + "id": "sion_2053", + "uuid": "{6A45CC7D-CC7D-40A3-902A-EFD7E1F69805}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 152.311, + 27.424, + -18.245 + ], + "size": [ + 101.613, + 31.586, + 51.75 + ], + "groundY": 11.631, + "roofY": 43.217, + "wallCount": 89, + "roofCount": 98 + }, + { + "id": "sion_2054", + "uuid": "{FC078F20-BBC1-44AB-8E20-A067DC82D33F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -64.592, + 31.328, + -123.216 + ], + "size": [ + 22.41, + 13.514, + 20.624 + ], + "groundY": 24.571, + "roofY": 38.085, + "wallCount": 12, + "roofCount": 7 + }, + { + "id": "sion_2055", + "uuid": "{2C0C4B55-18C5-4DFE-8BD5-2D0BF5B01FA7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 2 + ], + "center": [ + 11.102, + 33.007, + -87.03 + ], + "size": [ + 73.438, + 27.666, + 43.364 + ], + "groundY": 19.174, + "roofY": 46.84, + "wallCount": 81, + "roofCount": 44 + }, + { + "id": "sion_2056", + "uuid": "{12ACF6C2-4C2C-4EE0-848C-C1F78AEC1732}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 328.096, + 58.359, + -691.705 + ], + "size": [ + 138.082, + 14.611, + 59.644 + ], + "groundY": 51.054, + "roofY": 65.665, + "wallCount": 67, + "roofCount": 46 + }, + { + "id": "sion_2057", + "uuid": "{93FCAC1C-FDFC-4D1A-A6AE-D552AA903C2D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1299.049, + 15.516, + 197.748 + ], + "size": [ + 38.777, + 14.876, + 14.951 + ], + "groundY": 8.078, + "roofY": 22.954, + "wallCount": 31, + "roofCount": 14 + }, + { + "id": "sion_2058", + "uuid": "{00FA0574-6165-4D9D-8D3B-AC1D8FEB6569}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -94.221, + 51.68, + -252.744 + ], + "size": [ + 44.746, + 24.654, + 47.061 + ], + "groundY": 39.353, + "roofY": 64.007, + "wallCount": 94, + "roofCount": 80 + }, + { + "id": "sion_2059", + "uuid": "{EF55BB24-210D-40E0-AFDF-1B906962B66A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 654.443, + 5.255, + 21.325 + ], + "size": [ + 10.879, + 5.14, + 13.246 + ], + "groundY": 2.685, + "roofY": 7.825, + "wallCount": 22, + "roofCount": 10 + }, + { + "id": "sion_2060", + "uuid": "{A9B83C29-34E4-4C27-BA0A-0126C54EB0DB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 858.783, + 15.642, + -18.652 + ], + "size": [ + 30.309, + 26.104, + 27.748 + ], + "groundY": 2.59, + "roofY": 28.694, + "wallCount": 49, + "roofCount": 10 + }, + { + "id": "sion_2061", + "uuid": "{87EF8E34-6F8C-496F-9C4F-4D82CAB8417E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -104.941, + 39.693, + -144.079 + ], + "size": [ + 28.289, + 19.958, + 22.4 + ], + "groundY": 29.714, + "roofY": 49.672, + "wallCount": 81, + "roofCount": 37 + }, + { + "id": "sion_2062", + "uuid": "{98D98B99-3320-441A-BDF2-3F5320D7F1E7}", + "name": "", + "class": "Mauer gross", + "archStyle": "fortress", + "tile": [ + 3, + 2 + ], + "center": [ + 177.906, + 135.147, + -458.851 + ], + "size": [ + 32.078, + 22.466, + 33.12 + ], + "groundY": 123.914, + "roofY": 146.38, + "wallCount": 246, + "roofCount": 44 + }, + { + "id": "sion_2063", + "uuid": "{D13C20C7-4D11-410A-85CA-4C1D756E337E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 4 + ], + "center": [ + 918.383, + 12.121, + 809.461 + ], + "size": [ + 53.328, + 12.375, + 56.106 + ], + "groundY": 5.934, + "roofY": 18.309, + "wallCount": 12, + "roofCount": 17 + }, + { + "id": "sion_2064", + "uuid": "{9E8F4CD2-5D51-44B9-B29D-04EB1DEB2D38}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 2 + ], + "center": [ + 18.787, + 64.437, + -334.213 + ], + "size": [ + 12.387, + 10.455, + 9.202 + ], + "groundY": 59.209, + "roofY": 69.664, + "wallCount": 27, + "roofCount": 14 + }, + { + "id": "sion_2065", + "uuid": "{1E52DEBC-3234-46D4-9449-B62A9621CC7E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 414.51, + 217.029, + -1386.924 + ], + "size": [ + 20.356, + 7.862, + 16.643 + ], + "groundY": 213.098, + "roofY": 220.96, + "wallCount": 30, + "roofCount": 14 + }, + { + "id": "sion_2066", + "uuid": "{3CE3BF37-CFBE-4500-93E4-2923AAF4967D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 681.398, + 11.176, + 29.776 + ], + "size": [ + 28.531, + 16.858, + 16.996 + ], + "groundY": 2.747, + "roofY": 19.605, + "wallCount": 44, + "roofCount": 8 + }, + { + "id": "sion_2067", + "uuid": "{D5721A36-5AE8-4A73-9571-500977BB5937}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 31.572, + 62.634, + -735.471 + ], + "size": [ + 21.223, + 11.62, + 20.204 + ], + "groundY": 56.824, + "roofY": 68.444, + "wallCount": 20, + "roofCount": 7 + }, + { + "id": "sion_2068", + "uuid": "{BE5D1850-4310-458E-92F5-0BAB48554669}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -299.777, + 84.323, + -962.685 + ], + "size": [ + 223.531, + 21.774, + 165.852 + ], + "groundY": 73.436, + "roofY": 95.21, + "wallCount": 156, + "roofCount": 150 + }, + { + "id": "sion_2069", + "uuid": "{DCF1835D-B353-49F6-88FA-80503D3E0802}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -270.344, + 45.955, + -326.51 + ], + "size": [ + 27.547, + 18.965, + 26.624 + ], + "groundY": 36.473, + "roofY": 55.438, + "wallCount": 35, + "roofCount": 28 + }, + { + "id": "sion_2070", + "uuid": "{D9055046-B1B6-4E96-9E4F-13B241EFE751}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -293.606, + 77.356, + -939.776 + ], + "size": [ + 16.25, + 6.008, + 15.544 + ], + "groundY": 74.352, + "roofY": 80.36, + "wallCount": 12, + "roofCount": 13 + }, + { + "id": "sion_2071", + "uuid": "{2346D3D3-3021-48B5-8813-E815E7D39695}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 0 + ], + "center": [ + -40.09, + 91.743, + -1032.971 + ], + "size": [ + 17.766, + 9.986, + 17.812 + ], + "groundY": 86.75, + "roofY": 96.736, + "wallCount": 29, + "roofCount": 2 + }, + { + "id": "sion_2072", + "uuid": "{C958EF7A-F31F-4EC6-B8B2-7CDFB91B37AF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1396.537, + 20.666, + 147.089 + ], + "size": [ + 21.402, + 25.222, + 14.18 + ], + "groundY": 8.055, + "roofY": 33.277, + "wallCount": 137, + "roofCount": 28 + }, + { + "id": "sion_2073", + "uuid": "{D1089D2D-BB5D-49AE-8910-BFBE45D1C054}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -323.709, + 65.305, + -726.433 + ], + "size": [ + 27.473, + 14.857, + 15.86 + ], + "groundY": 57.877, + "roofY": 72.734, + "wallCount": 48, + "roofCount": 51 + }, + { + "id": "sion_2074", + "uuid": "{DB7EA172-8CE8-428B-AA81-3191E70EE53E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 892.967, + 10.796, + 330.383 + ], + "size": [ + 46.621, + 15.83, + 67.729 + ], + "groundY": 2.881, + "roofY": 18.711, + "wallCount": 66, + "roofCount": 19 + }, + { + "id": "sion_2075", + "uuid": "{E119B007-69CD-4B6C-BFC7-BBA2EFDFC649}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -117.855, + 80.825, + -880.501 + ], + "size": [ + 85.461, + 23.949, + 30.496 + ], + "groundY": 68.851, + "roofY": 92.8, + "wallCount": 116, + "roofCount": 63 + }, + { + "id": "sion_2076", + "uuid": "{9F3C5C29-B3F4-4CB4-A300-AED07CC16004}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 306.904, + 9.152, + 577.391 + ], + "size": [ + 67.074, + 15.666, + 53.14 + ], + "groundY": 1.319, + "roofY": 16.985, + "wallCount": 54, + "roofCount": 22 + }, + { + "id": "sion_2077", + "uuid": "{685E401E-86FA-4557-9A8C-BFD43BBB36D4}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 2 + ], + "center": [ + 248.348, + 23.881, + -97.689 + ], + "size": [ + 87.734, + 29.535, + 44.888 + ], + "groundY": 9.113, + "roofY": 38.648, + "wallCount": 84, + "roofCount": 38 + }, + { + "id": "sion_2078", + "uuid": "{FD679571-14D2-4F25-A2BD-2B0F47A18429}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 503.82, + 225.264, + -1435.109 + ], + "size": [ + 24.945, + 16.305, + 20.418 + ], + "groundY": 217.112, + "roofY": 233.417, + "wallCount": 45, + "roofCount": 20 + }, + { + "id": "sion_2079", + "uuid": "{EB16EA76-1BD0-4CEA-8FD2-ED7F5885CBC6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 522.6, + 10.144, + 740.617 + ], + "size": [ + 84.566, + 12.931, + 75.49 + ], + "groundY": 3.679, + "roofY": 16.61, + "wallCount": 65, + "roofCount": 110 + }, + { + "id": "sion_2080", + "uuid": "{5DB4BFC7-F693-4571-AA73-863FC0E6A3D1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 3 + ], + "center": [ + 328.305, + 17.863, + 71.835 + ], + "size": [ + 22.789, + 19.58, + 31.066 + ], + "groundY": 8.073, + "roofY": 27.653, + "wallCount": 33, + "roofCount": 24 + }, + { + "id": "sion_2081", + "uuid": "{06790E57-7E2B-4C07-AFA9-5A2EFB7ED812}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 1 + ], + "center": [ + 865.197, + 12.305, + -515.824 + ], + "size": [ + 21.035, + 17.494, + 21.019 + ], + "groundY": 3.558, + "roofY": 21.052, + "wallCount": 11, + "roofCount": 16 + }, + { + "id": "sion_2082", + "uuid": "{83DC9EA2-90C0-43DE-BE45-11C2266A1F9E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 952.059, + 15.376, + 107.683 + ], + "size": [ + 29.938, + 25.574, + 27.59 + ], + "groundY": 2.589, + "roofY": 28.163, + "wallCount": 42, + "roofCount": 10 + }, + { + "id": "sion_2083", + "uuid": "{891F6F11-F39E-4FDD-933C-13071779CEA9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 4 + ], + "center": [ + 282.947, + 8.728, + 859.813 + ], + "size": [ + 41.426, + 12.366, + 46.073 + ], + "groundY": 2.545, + "roofY": 14.911, + "wallCount": 20, + "roofCount": 16 + }, + { + "id": "sion_2084", + "uuid": "{FFD088F9-D5F1-4283-A8E2-34327A1992F5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1084.914, + 10.915, + 373.05 + ], + "size": [ + 12.383, + 10.996, + 10.68 + ], + "groundY": 5.417, + "roofY": 16.413, + "wallCount": 50, + "roofCount": 31 + }, + { + "id": "sion_2085", + "uuid": "{74C2A4B9-4A06-4A1C-A497-E801705310BE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -20.082, + 64.785, + -258.117 + ], + "size": [ + 15.891, + 13.124, + 17.876 + ], + "groundY": 58.223, + "roofY": 71.347, + "wallCount": 40, + "roofCount": 14 + }, + { + "id": "sion_2086", + "uuid": "{F057C4A2-802E-40FF-84E1-6FC7D8ED9F48}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 2 + ], + "center": [ + 406.969, + 18.988, + -27.35 + ], + "size": [ + 48.726, + 30.588, + 64.397 + ], + "groundY": 3.694, + "roofY": 34.282, + "wallCount": 79, + "roofCount": 31 + }, + { + "id": "sion_2087", + "uuid": "{D65FB98C-D138-4755-BC65-14282ABB4C1F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -68.82, + 28.061, + 103.427 + ], + "size": [ + 30.117, + 20.503, + 26.588 + ], + "groundY": 17.809, + "roofY": 38.312, + "wallCount": 25, + "roofCount": 19 + }, + { + "id": "sion_2088", + "uuid": "{4E383523-1BDE-4670-B1D5-9D92AA3E7FCA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 423.795, + 6.61, + 984.163 + ], + "size": [ + 34.238, + 7.251, + 24.012 + ], + "groundY": 2.984, + "roofY": 10.235, + "wallCount": 30, + "roofCount": 24 + }, + { + "id": "sion_2089", + "uuid": "{3D109C0C-0B53-4C7D-BBCA-2D603C96BD7E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -244.266, + 48.805, + -384.353 + ], + "size": [ + 37.625, + 20.658, + 43.3 + ], + "groundY": 38.476, + "roofY": 59.133, + "wallCount": 37, + "roofCount": 35 + }, + { + "id": "sion_2090", + "uuid": "{B82417F5-B632-4A76-B42E-19398870D81C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 2 + ], + "center": [ + 982.215, + 6.223, + -352.032 + ], + "size": [ + 29.219, + 6.51, + 45.534 + ], + "groundY": 2.968, + "roofY": 9.478, + "wallCount": 32, + "roofCount": 31 + }, + { + "id": "sion_2091", + "uuid": "{5B0A44B1-B0B5-4E1E-B85C-89023F075493}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 1 + ], + "center": [ + 550.705, + 76.372, + -798.996 + ], + "size": [ + 9.621, + 10.166, + 14.596 + ], + "groundY": 71.289, + "roofY": 81.455, + "wallCount": 52, + "roofCount": 23 + }, + { + "id": "sion_2092", + "uuid": "{B225B770-C158-415D-8546-2FC54D34A52F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1113.961, + 9.977, + 118.432 + ], + "size": [ + 102.867, + 9.856, + 80.226 + ], + "groundY": 5.049, + "roofY": 14.905, + "wallCount": 16, + "roofCount": 20 + }, + { + "id": "sion_2093", + "uuid": "{0472BBA6-CE96-4E44-9DDC-49BAD94BAF94}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 2 + ], + "center": [ + -363.492, + 29.672, + -67.235 + ], + "size": [ + 52.5, + 11.292, + 27.689 + ], + "groundY": 24.026, + "roofY": 35.317, + "wallCount": 89, + "roofCount": 45 + }, + { + "id": "sion_2094", + "uuid": "{D3C07C49-30BF-40A6-8F6D-F3ADF7F87B5F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1333.516, + 18.866, + 167.347 + ], + "size": [ + 47.992, + 20.31, + 15.874 + ], + "groundY": 8.711, + "roofY": 29.021, + "wallCount": 34, + "roofCount": 42 + }, + { + "id": "sion_2095", + "uuid": "{9C5E7F04-8B5F-4431-B9EF-A06B711E21EA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -115.387, + 57.829, + -558.937 + ], + "size": [ + 33.992, + 22.176, + 53.435 + ], + "groundY": 46.741, + "roofY": 68.917, + "wallCount": 53, + "roofCount": 24 + }, + { + "id": "sion_2096", + "uuid": "{CF5863B8-E09E-4F43-895C-34BE5923FED1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -187.723, + 5.761, + 734.859 + ], + "size": [ + 17.359, + 11.468, + 29.851 + ], + "groundY": 0.027, + "roofY": 11.495, + "wallCount": 21, + "roofCount": 17 + }, + { + "id": "sion_2097", + "uuid": "{0BD7026B-A689-480F-B67A-0AEDC9D3F0AA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 4 + ], + "center": [ + -389.846, + 8.578, + 606.153 + ], + "size": [ + 14.129, + 15.274, + 13.078 + ], + "groundY": 0.941, + "roofY": 16.215, + "wallCount": 76, + "roofCount": 54 + }, + { + "id": "sion_2098", + "uuid": "{67AC4F12-E30D-4C49-AEC8-513FF781BA6E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 0 + ], + "center": [ + 713.195, + 197.233, + -1293.34 + ], + "size": [ + 5.094, + 6.177, + 4.068 + ], + "groundY": 194.145, + "roofY": 200.322, + "wallCount": 17, + "roofCount": 4 + }, + { + "id": "sion_2099", + "uuid": "{84F4E342-9E46-43FA-9562-B92F1542B25C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -108.189, + 51.249, + -395.984 + ], + "size": [ + 27.684, + 20.498, + 74.218 + ], + "groundY": 41.0, + "roofY": 61.498, + "wallCount": 35, + "roofCount": 0 + }, + { + "id": "sion_2100", + "uuid": "{E15D2391-162C-47B0-AD29-089DDFC951B5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 474.254, + 83.156, + -1038.579 + ], + "size": [ + 5.719, + 7.586, + 4.758 + ], + "groundY": 79.363, + "roofY": 86.948, + "wallCount": 36, + "roofCount": 9 + }, + { + "id": "sion_2101", + "uuid": "{A3C835AE-28D3-46C3-B8E2-A3CC9289A832}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 1 + ], + "center": [ + 93.336, + 69.85, + -875.853 + ], + "size": [ + 32.367, + 18.417, + 24.899 + ], + "groundY": 60.641, + "roofY": 79.059, + "wallCount": 10, + "roofCount": 10 + }, + { + "id": "sion_2102", + "uuid": "{235B6BB5-F61E-45C8-9E10-634FA2AE6C9A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 3 + ], + "center": [ + 1355.344, + 17.807, + 335.091 + ], + "size": [ + 56.406, + 22.152, + 13.602 + ], + "groundY": 6.731, + "roofY": 28.883, + "wallCount": 90, + "roofCount": 32 + }, + { + "id": "sion_2103", + "uuid": "{52089DF5-05D4-4285-83FF-FC5E6F7397DD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 0 + ], + "center": [ + 256.498, + 203.852, + -1342.301 + ], + "size": [ + 28.957, + 9.469, + 20.268 + ], + "groundY": 199.118, + "roofY": 208.587, + "wallCount": 44, + "roofCount": 32 + }, + { + "id": "sion_2104", + "uuid": "{360AF491-8605-451D-A089-4CBE10B3D16C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 1 + ], + "center": [ + -401.645, + 54.584, + -512.838 + ], + "size": [ + 24.438, + 20.086, + 15.07 + ], + "groundY": 44.541, + "roofY": 64.627, + "wallCount": 28, + "roofCount": 35 + }, + { + "id": "sion_2105", + "uuid": "{682D8ADF-5126-4823-ACCE-BCDE135DACD8}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 3 + ], + "center": [ + -402.195, + 22.896, + 237.381 + ], + "size": [ + 36.727, + 22.726, + 23.973 + ], + "groundY": 11.533, + "roofY": 34.258, + "wallCount": 22, + "roofCount": 19 + }, + { + "id": "sion_2106", + "uuid": "{318ED595-63BB-49C0-8CA6-E6FFA1352874}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1171.367, + 201.896, + 1458.638 + ], + "size": [ + 17.109, + 9.516, + 13.968 + ], + "groundY": 197.138, + "roofY": 206.654, + "wallCount": 25, + "roofCount": 20 + }, + { + "id": "sion_2107", + "uuid": "{259C7D4E-87EF-43F7-AA5E-F06272380D67}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -19.926, + 7.737, + 1191.88 + ], + "size": [ + 29.383, + 9.905, + 35.857 + ], + "groundY": 2.785, + "roofY": 12.69, + "wallCount": 21, + "roofCount": 7 + }, + { + "id": "sion_2108", + "uuid": "{62B20CDF-A3D4-41CD-BC41-98786B558046}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1041.57, + 78.874, + 1223.235 + ], + "size": [ + 26.43, + 14.482, + 20.094 + ], + "groundY": 71.633, + "roofY": 86.115, + "wallCount": 56, + "roofCount": 26 + }, + { + "id": "sion_2109", + "uuid": "{335FF65F-FCBD-4210-962E-EC9D0FED8826}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -216.01, + 5.089, + 1088.642 + ], + "size": [ + 51.262, + 9.563, + 32.13 + ], + "groundY": 0.308, + "roofY": 9.871, + "wallCount": 36, + "roofCount": 30 + }, + { + "id": "sion_2110", + "uuid": "{DF0A0D40-5CFB-49B6-9DCD-BE0ABC45CD33}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 223.488, + 95.136, + 1398.256 + ], + "size": [ + 17.594, + 8.452, + 10.498 + ], + "groundY": 90.91, + "roofY": 99.362, + "wallCount": 27, + "roofCount": 20 + }, + { + "id": "sion_2111", + "uuid": "{ECDCEC46-255A-4E92-8843-C297D53A1AD9}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 151.137, + 6.745, + 1077.146 + ], + "size": [ + 35.164, + 8.035, + 29.757 + ], + "groundY": 2.728, + "roofY": 10.763, + "wallCount": 35, + "roofCount": 39 + }, + { + "id": "sion_2112", + "uuid": "{6698D73A-9687-4E03-8EDB-623E0802066C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -107.553, + 8.475, + 1315.661 + ], + "size": [ + 120.488, + 10.04, + 71.998 + ], + "groundY": 3.455, + "roofY": 13.495, + "wallCount": 35, + "roofCount": 41 + }, + { + "id": "sion_2113", + "uuid": "{E7D0C612-0665-4EB5-BA1F-1631B77AEEBC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -378.43, + 4.612, + 1155.788 + ], + "size": [ + 38.18, + 9.699, + 24.706 + ], + "groundY": -0.237, + "roofY": 9.461, + "wallCount": 25, + "roofCount": 24 + }, + { + "id": "sion_2114", + "uuid": "{1C90C78F-CE96-4003-823C-6AF061E5E92D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 464.836, + 10.156, + 1162.766 + ], + "size": [ + 53.227, + 15.82, + 45.608 + ], + "groundY": 2.246, + "roofY": 18.066, + "wallCount": 66, + "roofCount": 23 + }, + { + "id": "sion_2115", + "uuid": "{92039373-033D-47DD-B10D-407C129FE819}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -110.488, + 116.788, + 1533.101 + ], + "size": [ + 16.016, + 12.94, + 17.424 + ], + "groundY": 110.318, + "roofY": 123.258, + "wallCount": 22, + "roofCount": 9 + }, + { + "id": "sion_2116", + "uuid": "{D7C0C5DE-FC15-469C-9AA4-F7839DA09AEE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1322.211, + 234.563, + 1476.054 + ], + "size": [ + 13.07, + 9.938, + 11.952 + ], + "groundY": 229.594, + "roofY": 239.532, + "wallCount": 32, + "roofCount": 18 + }, + { + "id": "sion_2117", + "uuid": "{DAD55D2E-C6E7-44D9-A49C-726053A72467}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -108.646, + 108.034, + 1501.319 + ], + "size": [ + 7.629, + 6.178, + 5.144 + ], + "groundY": 104.945, + "roofY": 111.123, + "wallCount": 14, + "roofCount": 14 + }, + { + "id": "sion_2118", + "uuid": "{DEB2C4F3-AB4C-41E7-B3DC-905520E98DC4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -342.645, + 6.008, + 1151.312 + ], + "size": [ + 17.547, + 11.384, + 21.841 + ], + "groundY": 0.316, + "roofY": 11.7, + "wallCount": 36, + "roofCount": 12 + }, + { + "id": "sion_2119", + "uuid": "{FB7D77BC-C370-42A8-AF04-9EBA157F7BBD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 95.51, + 39.271, + 1342.667 + ], + "size": [ + 21.707, + 8.172, + 9.588 + ], + "groundY": 35.185, + "roofY": 43.357, + "wallCount": 16, + "roofCount": 28 + }, + { + "id": "sion_2120", + "uuid": "{F1A671DD-E91E-4475-949A-7A94BA462EC1}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 5 + ], + "center": [ + 523.023, + 11.371, + 1108.546 + ], + "size": [ + 32.859, + 13.507, + 38.126 + ], + "groundY": 4.618, + "roofY": 18.125, + "wallCount": 17, + "roofCount": 12 + }, + { + "id": "sion_2121", + "uuid": "{45E25FCC-5038-4827-9596-6139D890F573}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 5 + ], + "center": [ + 548.029, + 29.381, + 1223.844 + ], + "size": [ + 14.988, + 12.88, + 13.872 + ], + "groundY": 22.941, + "roofY": 35.821, + "wallCount": 37, + "roofCount": 19 + }, + { + "id": "sion_2122", + "uuid": "{B367EFD1-51B8-47CF-A6B9-780E6FFF044B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 5 + ], + "center": [ + 758.353, + 31.031, + 1120.568 + ], + "size": [ + 6.949, + 10.842, + 9.576 + ], + "groundY": 25.61, + "roofY": 36.452, + "wallCount": 63, + "roofCount": 23 + }, + { + "id": "sion_2123", + "uuid": "{FB684055-5874-4C91-B1EF-83FA7206999D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 5 + ], + "center": [ + 571.02, + 30.286, + 1236.701 + ], + "size": [ + 17.039, + 10.163, + 10.229 + ], + "groundY": 25.205, + "roofY": 35.367, + "wallCount": 29, + "roofCount": 37 + }, + { + "id": "sion_2124", + "uuid": "{D7A6F175-AE92-45F7-8250-83DCDDF5B266}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1068.057, + 197.174, + 1462.181 + ], + "size": [ + 12.754, + 11.688, + 15.267 + ], + "groundY": 191.33, + "roofY": 203.018, + "wallCount": 47, + "roofCount": 13 + }, + { + "id": "sion_2125", + "uuid": "{694BF2B8-CF68-41D6-A57F-F549271F6AA6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 5 + ], + "center": [ + 983.533, + 64.002, + 1193.149 + ], + "size": [ + 24.082, + 13.288, + 13.916 + ], + "groundY": 57.358, + "roofY": 70.646, + "wallCount": 71, + "roofCount": 26 + }, + { + "id": "sion_2126", + "uuid": "{BE073200-D99E-4FDB-9771-5670872221F4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1311.43, + 124.991, + 1227.58 + ], + "size": [ + 19.914, + 8.714, + 13.367 + ], + "groundY": 120.634, + "roofY": 129.348, + "wallCount": 34, + "roofCount": 26 + }, + { + "id": "sion_2127", + "uuid": "{62F77940-B8C9-4D42-8DB7-90C4F4AAC6DE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 222.617, + 101.794, + 1408.864 + ], + "size": [ + 9.742, + 12.075, + 12.792 + ], + "groundY": 95.757, + "roofY": 107.832, + "wallCount": 20, + "roofCount": 19 + }, + { + "id": "sion_2128", + "uuid": "{6E982AE3-4792-4A21-8760-AAEDE6BEDCA3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 149.473, + 7.806, + 1194.261 + ], + "size": [ + 56.07, + 9.921, + 50.376 + ], + "groundY": 2.845, + "roofY": 12.766, + "wallCount": 43, + "roofCount": 16 + }, + { + "id": "sion_2129", + "uuid": "{BC3FD928-D332-459F-8A79-5669B81F67BD}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -137.397, + 95.538, + 1457.882 + ], + "size": [ + 24.324, + 15.768, + 18.382 + ], + "groundY": 87.654, + "roofY": 103.422, + "wallCount": 78, + "roofCount": 29 + }, + { + "id": "sion_2130", + "uuid": "{42F152CC-06B8-4CE6-9DBF-30AAF6D568BA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -81.482, + 108.998, + 1481.798 + ], + "size": [ + 14.863, + 11.963, + 12.874 + ], + "groundY": 103.016, + "roofY": 114.979, + "wallCount": 49, + "roofCount": 22 + }, + { + "id": "sion_2131", + "uuid": "{CAC0D9D7-953B-42E9-9441-FB1E040FA18A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 60.793, + 9.569, + 1076.128 + ], + "size": [ + 33.938, + 11.838, + 46.553 + ], + "groundY": 3.65, + "roofY": 15.488, + "wallCount": 13, + "roofCount": 38 + }, + { + "id": "sion_2132", + "uuid": "{21FE7538-955C-49F5-A203-0990CB199779}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 64.85, + 80.87, + 1431.872 + ], + "size": [ + 73.223, + 14.687, + 30.734 + ], + "groundY": 73.526, + "roofY": 88.213, + "wallCount": 38, + "roofCount": 19 + }, + { + "id": "sion_2133", + "uuid": "{16ED8E6D-8B75-4285-8144-DC0A7122097B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -369.596, + 60.499, + 1477.323 + ], + "size": [ + 29.082, + 10.931, + 19.072 + ], + "groundY": 55.034, + "roofY": 65.965, + "wallCount": 27, + "roofCount": 14 + }, + { + "id": "sion_2134", + "uuid": "{0CB21514-9A88-4EB7-9575-16EFB3070784}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 5 + ], + "center": [ + 981.297, + 21.015, + 1081.168 + ], + "size": [ + 26.859, + 14.036, + 22.973 + ], + "groundY": 13.997, + "roofY": 28.033, + "wallCount": 57, + "roofCount": 20 + }, + { + "id": "sion_2135", + "uuid": "{2DCCF333-771B-463C-B5B1-EAF3AF214DCC}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -226.146, + 79.028, + 1466.725 + ], + "size": [ + 23.34, + 11.604, + 15.506 + ], + "groundY": 73.226, + "roofY": 84.83, + "wallCount": 20, + "roofCount": 29 + }, + { + "id": "sion_2136", + "uuid": "{F422A866-C5CB-4E3D-991A-20C559B0B820}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 233.85, + 7.119, + 1171.164 + ], + "size": [ + 30.543, + 10.283, + 85.736 + ], + "groundY": 1.978, + "roofY": 12.261, + "wallCount": 28, + "roofCount": 24 + }, + { + "id": "sion_2137", + "uuid": "{EE7AF132-B807-45C0-853B-541030C32B15}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 298.029, + 10.045, + 1199.78 + ], + "size": [ + 71.973, + 15.353, + 43.468 + ], + "groundY": 2.368, + "roofY": 17.721, + "wallCount": 55, + "roofCount": 35 + }, + { + "id": "sion_2138", + "uuid": "{C2D9E6E5-270C-42A3-AB00-3CC7E4A1C148}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 5 + ], + "center": [ + 615.229, + 117.669, + 1415.293 + ], + "size": [ + 14.887, + 12.796, + 13.486 + ], + "groundY": 111.271, + "roofY": 124.067, + "wallCount": 44, + "roofCount": 20 + }, + { + "id": "sion_2139", + "uuid": "{2720EE54-2ECC-4D86-AECA-8137CE3BB27F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -283.889, + 3.861, + 1174.812 + ], + "size": [ + 17.684, + 7.052, + 17.407 + ], + "groundY": 0.335, + "roofY": 7.387, + "wallCount": 39, + "roofCount": 0 + }, + { + "id": "sion_2140", + "uuid": "{10B2EE8B-03BF-4E20-A50E-A66BF6BFFC6F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -275.742, + 3.591, + 1119.442 + ], + "size": [ + 17.539, + 6.202, + 18.72 + ], + "groundY": 0.49, + "roofY": 6.692, + "wallCount": 45, + "roofCount": 8 + }, + { + "id": "sion_2141", + "uuid": "{7A4EA621-9340-4690-9D35-F03A7D0BBC2B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -29.484, + 7.701, + 1168.111 + ], + "size": [ + 18.891, + 10.901, + 18.428 + ], + "groundY": 2.251, + "roofY": 13.152, + "wallCount": 46, + "roofCount": 6 + }, + { + "id": "sion_2142", + "uuid": "{EB87D8E1-61FA-4BBC-9633-792BD7EE4649}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1351.764, + 117.083, + 1192.515 + ], + "size": [ + 20.074, + 12.264, + 15.782 + ], + "groundY": 110.951, + "roofY": 123.215, + "wallCount": 35, + "roofCount": 14 + }, + { + "id": "sion_2143", + "uuid": "{4C2087AA-F2E5-44C2-A2EB-09075547689E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 38.178, + 8.041, + 1090.632 + ], + "size": [ + 31.816, + 8.446, + 41.738 + ], + "groundY": 3.818, + "roofY": 12.264, + "wallCount": 14, + "roofCount": 31 + }, + { + "id": "sion_2144", + "uuid": "{40DB5E52-D748-410D-A926-43789C43AD64}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1507.518, + 223.919, + 1375.147 + ], + "size": [ + 12.371, + 9.518, + 10.907 + ], + "groundY": 219.16, + "roofY": 228.678, + "wallCount": 44, + "roofCount": 19 + }, + { + "id": "sion_2145", + "uuid": "{648AB307-C5CF-452E-9117-FBBAA311A787}", + "name": "", + "class": "Lagertank", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -189.209, + 9.004, + 1084.683 + ], + "size": [ + 3.551, + 16.522, + 3.548 + ], + "groundY": 0.743, + "roofY": 17.265, + "wallCount": 40, + "roofCount": 3 + }, + { + "id": "sion_2146", + "uuid": "{22E3C1A3-00BA-4B00-B4C6-86CFD1187B3E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 377.389, + 10.764, + 1192.509 + ], + "size": [ + 40.379, + 15.789, + 33.324 + ], + "groundY": 2.869, + "roofY": 18.658, + "wallCount": 92, + "roofCount": 55 + }, + { + "id": "sion_2147", + "uuid": "{A46B9C88-63AE-4F0A-AA85-1468F70AAC35}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 5 + ], + "center": [ + 665.295, + 69.688, + 1269.284 + ], + "size": [ + 9.16, + 5.65, + 7.506 + ], + "groundY": 66.863, + "roofY": 72.513, + "wallCount": 31, + "roofCount": 11 + }, + { + "id": "sion_2148", + "uuid": "{48CC406E-A11D-4D55-9979-36ECB53C40F5}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -209.109, + 7.875, + 1189.72 + ], + "size": [ + 31.68, + 8.451, + 31.008 + ], + "groundY": 3.649, + "roofY": 12.1, + "wallCount": 27, + "roofCount": 37 + }, + { + "id": "sion_2149", + "uuid": "{8A8C14B2-2910-4F07-B60B-39F572EAC33D}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 330.686, + 8.399, + 1189.301 + ], + "size": [ + 35.926, + 11.657, + 39.508 + ], + "groundY": 2.571, + "roofY": 14.228, + "wallCount": 19, + "roofCount": 30 + }, + { + "id": "sion_2150", + "uuid": "{0DAA755E-CB37-4EC4-9893-030D492450E6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 5 + ], + "center": [ + 559.844, + 14.731, + 1131.884 + ], + "size": [ + 94.492, + 17.066, + 98.096 + ], + "groundY": 6.198, + "roofY": 23.264, + "wallCount": 46, + "roofCount": 18 + }, + { + "id": "sion_2151", + "uuid": "{FAB3B8FC-1103-42CB-A4AA-4D6B94F66559}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 227.346, + 136.162, + 1505.547 + ], + "size": [ + 7.785, + 8.296, + 7.09 + ], + "groundY": 132.014, + "roofY": 140.31, + "wallCount": 30, + "roofCount": 15 + }, + { + "id": "sion_2152", + "uuid": "{C64CD000-0528-4608-AB70-4CD43AFC3253}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -364.688, + 4.936, + 1064.917 + ], + "size": [ + 49.82, + 9.27, + 35.148 + ], + "groundY": 0.301, + "roofY": 9.571, + "wallCount": 10, + "roofCount": 24 + }, + { + "id": "sion_2153", + "uuid": "{D8298C0F-ED59-4651-B8A1-8604C96041B6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -253.133, + 5.699, + 1106.407 + ], + "size": [ + 19.141, + 11.464, + 16.814 + ], + "groundY": -0.033, + "roofY": 11.431, + "wallCount": 24, + "roofCount": 9 + }, + { + "id": "sion_2154", + "uuid": "{DB19D9DC-6B36-42FD-A1DA-8C1601D47290}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 17.467, + 12.75, + 1322.362 + ], + "size": [ + 11.957, + 8.244, + 10.524 + ], + "groundY": 8.628, + "roofY": 16.872, + "wallCount": 47, + "roofCount": 21 + }, + { + "id": "sion_2155", + "uuid": "{5FD9807A-C3BC-44AC-A5BE-5F1CE02CEC00}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1286.711, + 120.908, + 1210.708 + ], + "size": [ + 14.891, + 11.064, + 15.672 + ], + "groundY": 115.376, + "roofY": 126.44, + "wallCount": 43, + "roofCount": 41 + }, + { + "id": "sion_2156", + "uuid": "{DD1ACB25-D472-49C7-8FD5-62BF382EA60F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 253.639, + 6.82, + 1175.726 + ], + "size": [ + 13.574, + 8.315, + 21.122 + ], + "groundY": 2.662, + "roofY": 10.977, + "wallCount": 27, + "roofCount": 109 + }, + { + "id": "sion_2157", + "uuid": "{56A3259B-BD6A-483C-92F9-5E8EAD6AE924}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -388.781, + 6.824, + 1273.616 + ], + "size": [ + 28.594, + 13.326, + 22.156 + ], + "groundY": 0.161, + "roofY": 13.487, + "wallCount": 26, + "roofCount": 24 + }, + { + "id": "sion_2158", + "uuid": "{5BAD80B3-4A31-475E-AF51-634B1CE28691}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 67.832, + 7.729, + 1151.838 + ], + "size": [ + 35.781, + 9.164, + 31.326 + ], + "groundY": 3.147, + "roofY": 12.311, + "wallCount": 20, + "roofCount": 64 + }, + { + "id": "sion_2159", + "uuid": "{413D3969-149D-40F0-A9BB-139F3B0C80E2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 65.961, + 14.637, + 1296.173 + ], + "size": [ + 18.219, + 11.122, + 21.5 + ], + "groundY": 9.076, + "roofY": 20.198, + "wallCount": 37, + "roofCount": 13 + }, + { + "id": "sion_2160", + "uuid": "{89362BFE-8AA6-4D5E-AFAD-71C96E362A22}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1474.75, + 123.405, + 1162.135 + ], + "size": [ + 19.281, + 11.906, + 16.008 + ], + "groundY": 117.452, + "roofY": 129.358, + "wallCount": 49, + "roofCount": 17 + }, + { + "id": "sion_2161", + "uuid": "{95D4022B-52F1-4448-B8F1-D257F3411E40}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 210.242, + 7.927, + 1171.171 + ], + "size": [ + 31.203, + 12.63, + 63.96 + ], + "groundY": 1.612, + "roofY": 14.242, + "wallCount": 22, + "roofCount": 15 + }, + { + "id": "sion_2162", + "uuid": "{ED628BC4-90D0-43CB-9313-649D14AB1AB0}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 364.26, + 89.142, + 1361.666 + ], + "size": [ + 9.496, + 10.215, + 9.826 + ], + "groundY": 84.034, + "roofY": 94.249, + "wallCount": 27, + "roofCount": 28 + }, + { + "id": "sion_2163", + "uuid": "{AAE0A9D6-1441-43EC-81A9-BCE189E908C7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 353.328, + 5.971, + 1057.483 + ], + "size": [ + 20.891, + 6.712, + 15.222 + ], + "groundY": 2.615, + "roofY": 9.327, + "wallCount": 10, + "roofCount": 26 + }, + { + "id": "sion_2164", + "uuid": "{3311BB6A-CF0D-4943-AB42-154D2E2FE087}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -358.816, + 5.922, + 1091.37 + ], + "size": [ + 125.68, + 11.096, + 81.884 + ], + "groundY": 0.374, + "roofY": 11.47, + "wallCount": 40, + "roofCount": 6 + }, + { + "id": "sion_2165", + "uuid": "{F2C65D55-9099-42FC-A9C2-FCEAE0E23336}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1131.816, + 185.125, + 1399.186 + ], + "size": [ + 15.727, + 10.636, + 13.082 + ], + "groundY": 179.807, + "roofY": 190.443, + "wallCount": 33, + "roofCount": 22 + }, + { + "id": "sion_2166", + "uuid": "{360FF648-539B-4181-BCAA-4B98D0514A4F}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 245.641, + 136.586, + 1495.693 + ], + "size": [ + 33.195, + 12.756, + 23.435 + ], + "groundY": 130.208, + "roofY": 142.964, + "wallCount": 61, + "roofCount": 34 + }, + { + "id": "sion_2167", + "uuid": "{98031FDE-827D-4214-87EA-67CE1FCD9D47}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -30.82, + 123.402, + 1511.572 + ], + "size": [ + 15.492, + 12.981, + 16.329 + ], + "groundY": 116.912, + "roofY": 129.893, + "wallCount": 54, + "roofCount": 32 + }, + { + "id": "sion_2168", + "uuid": "{C91500D5-FD2B-4D61-B289-63F7DE47C2FF}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -171.709, + 14.754, + 1089.65 + ], + "size": [ + 10.762, + 27.746, + 24.599 + ], + "groundY": 0.881, + "roofY": 28.627, + "wallCount": 47, + "roofCount": 22 + }, + { + "id": "sion_2169", + "uuid": "{91303D7B-C4F2-4C2C-A7B9-7E52978FBD89}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -42.596, + 109.762, + 1479.494 + ], + "size": [ + 14.168, + 11.944, + 13.376 + ], + "groundY": 103.79, + "roofY": 115.734, + "wallCount": 48, + "roofCount": 9 + }, + { + "id": "sion_2170", + "uuid": "{6C342B9E-1742-4485-92CB-CC17E628721E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1065.504, + 191.848, + 1436.072 + ], + "size": [ + 12.5, + 10.934, + 12.05 + ], + "groundY": 186.381, + "roofY": 197.315, + "wallCount": 49, + "roofCount": 20 + }, + { + "id": "sion_2171", + "uuid": "{9AD520B6-4291-4606-9262-3B38CB7D02E3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 5 + ], + "center": [ + 636.17, + 76.669, + 1331.713 + ], + "size": [ + 13.731, + 10.714, + 14.238 + ], + "groundY": 71.312, + "roofY": 82.026, + "wallCount": 34, + "roofCount": 28 + }, + { + "id": "sion_2172", + "uuid": "{BA63D42A-4505-44D6-834D-68CFD79F1AB0}", + "name": "", + "class": "Lagertank", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 107.223, + 61.77, + 1386.232 + ], + "size": [ + 3.273, + 12.48, + 3.275 + ], + "groundY": 55.53, + "roofY": 68.01, + "wallCount": 7, + "roofCount": 2 + }, + { + "id": "sion_2173", + "uuid": "{13A7DFCD-8F88-4F5E-9817-B608C8BF053E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 5, + 5 + ], + "center": [ + 1078.062, + 26.114, + 1073.999 + ], + "size": [ + 83.625, + 22.347, + 64.465 + ], + "groundY": 14.941, + "roofY": 37.288, + "wallCount": 74, + "roofCount": 25 + }, + { + "id": "sion_2174", + "uuid": "{C8EBC1A4-3791-4FAC-889C-4A65B578C228}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 30.283, + 7.753, + 1165.373 + ], + "size": [ + 32.98, + 9.022, + 36.553 + ], + "groundY": 3.242, + "roofY": 12.264, + "wallCount": 30, + "roofCount": 53 + }, + { + "id": "sion_2175", + "uuid": "{EC153C56-D906-403E-BDFF-87FD790A973A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 343.721, + 153.182, + 1512.904 + ], + "size": [ + 11.918, + 12.462, + 12.492 + ], + "groundY": 146.951, + "roofY": 159.413, + "wallCount": 38, + "roofCount": 26 + }, + { + "id": "sion_2176", + "uuid": "{BCD1CF01-C27A-4E17-8220-4A9597371E36}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1395.541, + 66.09, + 1064.161 + ], + "size": [ + 18.457, + 13.11, + 9.13 + ], + "groundY": 59.535, + "roofY": 72.645, + "wallCount": 52, + "roofCount": 21 + }, + { + "id": "sion_2177", + "uuid": "{F071D0E7-2C46-4C4D-B4DC-AB68C6257D78}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -64.27, + 108.761, + 1477.394 + ], + "size": [ + 10.188, + 10.414, + 9.233 + ], + "groundY": 103.554, + "roofY": 113.968, + "wallCount": 52, + "roofCount": 31 + }, + { + "id": "sion_2178", + "uuid": "{F4F48BF0-63D5-4A2B-AEBE-B74F965765FA}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 24.084, + 7.175, + 1104.423 + ], + "size": [ + 25.105, + 7.144, + 39.482 + ], + "groundY": 3.603, + "roofY": 10.747, + "wallCount": 20, + "roofCount": 27 + }, + { + "id": "sion_2179", + "uuid": "{F0E8C09E-94DC-4D09-A2A4-CB368CAEF26B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 5 + ], + "center": [ + 712.094, + 40.517, + 1183.813 + ], + "size": [ + 20.266, + 10.53, + 22.105 + ], + "groundY": 35.252, + "roofY": 45.782, + "wallCount": 32, + "roofCount": 23 + }, + { + "id": "sion_2180", + "uuid": "{D57203E6-415A-4FC1-9727-8DF346014450}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1452.668, + 71.029, + 1066.859 + ], + "size": [ + 13.227, + 13.408, + 10.422 + ], + "groundY": 64.325, + "roofY": 77.733, + "wallCount": 60, + "roofCount": 38 + }, + { + "id": "sion_2181", + "uuid": "{DCC2EF3F-869C-4771-8323-FF47DEF241DE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 361.715, + 4.674, + 1150.139 + ], + "size": [ + 41.055, + 7.593, + 35.696 + ], + "groundY": 0.877, + "roofY": 8.47, + "wallCount": 34, + "roofCount": 27 + }, + { + "id": "sion_2182", + "uuid": "{D50982B9-78E9-42E6-883A-A54FAB29B4FE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 5 + ], + "center": [ + 722.037, + 46.447, + 1200.524 + ], + "size": [ + 21.707, + 15.354, + 16.644 + ], + "groundY": 38.77, + "roofY": 54.124, + "wallCount": 23, + "roofCount": 9 + }, + { + "id": "sion_2183", + "uuid": "{968D0827-C15E-4480-A331-697135291278}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1438.77, + 120.011, + 1172.192 + ], + "size": [ + 16.898, + 11.868, + 14.927 + ], + "groundY": 114.077, + "roofY": 125.945, + "wallCount": 38, + "roofCount": 20 + }, + { + "id": "sion_2184", + "uuid": "{A581C60F-346C-4B7C-AC3F-5937AFF2E2DE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 235.617, + 100.522, + 1403.926 + ], + "size": [ + 18.461, + 10.83, + 11.884 + ], + "groundY": 95.107, + "roofY": 105.937, + "wallCount": 30, + "roofCount": 45 + }, + { + "id": "sion_2185", + "uuid": "{57233294-50FC-49C0-A989-D7013A8DCE5C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 5 + ], + "center": [ + 610.818, + 22.625, + 1186.649 + ], + "size": [ + 12.019, + 11.866, + 12.006 + ], + "groundY": 16.692, + "roofY": 28.558, + "wallCount": 54, + "roofCount": 15 + }, + { + "id": "sion_2186", + "uuid": "{9821D1B4-F496-4026-AF0A-46FB20992891}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -226.322, + 73.466, + 1451.379 + ], + "size": [ + 15.246, + 4.524, + 15.645 + ], + "groundY": 71.204, + "roofY": 75.728, + "wallCount": 22, + "roofCount": 6 + }, + { + "id": "sion_2187", + "uuid": "{A9DE322C-BE6F-4A6D-BB0D-E74C991F2976}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -27.096, + 8.173, + 1289.697 + ], + "size": [ + 46.473, + 9.434, + 54.47 + ], + "groundY": 3.456, + "roofY": 12.89, + "wallCount": 17, + "roofCount": 48 + }, + { + "id": "sion_2188", + "uuid": "{AEE00D44-8C36-442C-B81A-97D6035B0CEE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 182.568, + 7.424, + 1067.195 + ], + "size": [ + 27.699, + 10.499, + 39.75 + ], + "groundY": 2.175, + "roofY": 12.674, + "wallCount": 31, + "roofCount": 18 + }, + { + "id": "sion_2189", + "uuid": "{6C110108-A113-449B-8A4F-4266D279BD81}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -28.82, + 7.876, + 1323.149 + ], + "size": [ + 24.5, + 8.134, + 16.819 + ], + "groundY": 3.809, + "roofY": 11.943, + "wallCount": 16, + "roofCount": 30 + }, + { + "id": "sion_2190", + "uuid": "{78302DA1-7609-4DDA-AAD8-8C33FC19B509}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -329.15, + 5.342, + 1220.61 + ], + "size": [ + 17.91, + 10.44, + 20.315 + ], + "groundY": 0.122, + "roofY": 10.562, + "wallCount": 44, + "roofCount": 34 + }, + { + "id": "sion_2191", + "uuid": "{C5B6E431-698C-4571-9680-88CC0025727C}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 391.715, + 7.997, + 1069.392 + ], + "size": [ + 20.961, + 10.747, + 32.614 + ], + "groundY": 2.624, + "roofY": 13.371, + "wallCount": 18, + "roofCount": 2 + }, + { + "id": "sion_2192", + "uuid": "{5B09F44E-EC85-4DA2-A040-04F883C50945}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1208.541, + 154.221, + 1313.788 + ], + "size": [ + 8.191, + 7.62, + 6.934 + ], + "groundY": 150.411, + "roofY": 158.031, + "wallCount": 55, + "roofCount": 24 + }, + { + "id": "sion_2193", + "uuid": "{3378C6A0-7FF6-4FA5-B397-5EBA6DC437AB}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 399.812, + 88.808, + 1345.818 + ], + "size": [ + 16.234, + 12.262, + 13.792 + ], + "groundY": 82.677, + "roofY": 94.938, + "wallCount": 58, + "roofCount": 31 + }, + { + "id": "sion_2194", + "uuid": "{67B1FF0D-827E-4E6A-A14D-E663BE8674B3}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -295.156, + 3.904, + 1145.77 + ], + "size": [ + 36.601, + 7.346, + 50.349 + ], + "groundY": 0.231, + "roofY": 7.577, + "wallCount": 46, + "roofCount": 21 + }, + { + "id": "sion_2195", + "uuid": "{0D13FE38-7C23-462F-8E65-A9AC08DFC956}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1467.412, + 71.262, + 1069.08 + ], + "size": [ + 14.035, + 11.681, + 18.594 + ], + "groundY": 65.421, + "roofY": 77.102, + "wallCount": 49, + "roofCount": 31 + }, + { + "id": "sion_2196", + "uuid": "{672F34D7-819B-4C08-8C8E-BDD5E02F4EA2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 485.932, + 16.279, + 1222.081 + ], + "size": [ + 19.113, + 12.608, + 13.346 + ], + "groundY": 9.975, + "roofY": 22.583, + "wallCount": 31, + "roofCount": 19 + }, + { + "id": "sion_2197", + "uuid": "{C6FA7E84-1BC2-456C-AA65-F10E63AA499B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 189.832, + 9.665, + 1225.027 + ], + "size": [ + 30.633, + 15.303, + 34.817 + ], + "groundY": 2.014, + "roofY": 17.317, + "wallCount": 168, + "roofCount": 23 + }, + { + "id": "sion_2198", + "uuid": "{2E6CEB44-569F-47E9-8A11-E800BA36EE2B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1510.574, + 235.066, + 1399.573 + ], + "size": [ + 26.133, + 6.437, + 12.152 + ], + "groundY": 231.848, + "roofY": 238.285, + "wallCount": 20, + "roofCount": 14 + }, + { + "id": "sion_2199", + "uuid": "{86702FC9-41EC-4D07-B236-539B6D636F50}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 195.562, + 5.448, + 1059.444 + ], + "size": [ + 16.211, + 6.488, + 25.626 + ], + "groundY": 2.204, + "roofY": 8.692, + "wallCount": 18, + "roofCount": 15 + }, + { + "id": "sion_2200", + "uuid": "{27B111B1-8741-4468-AD53-B1777675071A}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1188.83, + 206.033, + 1465.784 + ], + "size": [ + 17.512, + 12.362, + 19.023 + ], + "groundY": 199.852, + "roofY": 212.214, + "wallCount": 37, + "roofCount": 17 + }, + { + "id": "sion_2201", + "uuid": "{304CDA18-1B7A-4FA3-8B76-2661F6D22DE6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -92.084, + 8.243, + 1240.59 + ], + "size": [ + 84.902, + 10.789, + 59.578 + ], + "groundY": 2.848, + "roofY": 13.637, + "wallCount": 35, + "roofCount": 25 + }, + { + "id": "sion_2202", + "uuid": "{EEA3906B-6877-4082-8770-268DA4609AC4}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 5 + ], + "center": [ + 598.406, + 112.329, + 1400.14 + ], + "size": [ + 11.453, + 11.723, + 8.038 + ], + "groundY": 106.467, + "roofY": 118.19, + "wallCount": 63, + "roofCount": 38 + }, + { + "id": "sion_2203", + "uuid": "{75FE8C39-817A-48C6-9214-B603AAA82B7E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 106.58, + 9.297, + 1073.958 + ], + "size": [ + 60.074, + 11.778, + 62.143 + ], + "groundY": 3.408, + "roofY": 15.186, + "wallCount": 82, + "roofCount": 46 + }, + { + "id": "sion_2204", + "uuid": "{78D6AFB4-27B6-4E24-AC6E-EB80E3392E2E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 5, + 5 + ], + "center": [ + 1264.666, + 124.155, + 1222.564 + ], + "size": [ + 15.254, + 12.156, + 14.252 + ], + "groundY": 118.077, + "roofY": 130.233, + "wallCount": 50, + "roofCount": 16 + }, + { + "id": "sion_2205", + "uuid": "{CB6CE6E2-39AB-420E-9AE3-DDA84D9E57A2}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -389.957, + 3.854, + 1221.705 + ], + "size": [ + 22.562, + 7.796, + 19.44 + ], + "groundY": -0.044, + "roofY": 7.752, + "wallCount": 16, + "roofCount": 20 + }, + { + "id": "sion_2206", + "uuid": "{DE25EC74-67C2-4C9A-BA91-86EBB65A8D67}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 5 + ], + "center": [ + 686.551, + 97.824, + 1362.901 + ], + "size": [ + 7.812, + 9.681, + 6.929 + ], + "groundY": 92.984, + "roofY": 102.665, + "wallCount": 73, + "roofCount": 22 + }, + { + "id": "sion_2207", + "uuid": "{3B2F319E-D257-41C9-8E04-71E95A9C10BE}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 4, + 5 + ], + "center": [ + 551.061, + 8.157, + 1069.662 + ], + "size": [ + 34.621, + 8.023, + 39.622 + ], + "groundY": 4.145, + "roofY": 12.168, + "wallCount": 8, + "roofCount": 12 + }, + { + "id": "sion_2208", + "uuid": "{189A4786-0C28-44C0-941D-396943CF4472}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 437.826, + 6.813, + 1118.936 + ], + "size": [ + 77.512, + 9.732, + 88.159 + ], + "groundY": 1.947, + "roofY": 11.678, + "wallCount": 28, + "roofCount": 52 + }, + { + "id": "sion_2209", + "uuid": "{1E3E3A2D-8E74-48D8-844F-E553FF204595}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 5 + ], + "center": [ + -45.875, + 7.882, + 1178.813 + ], + "size": [ + 12.891, + 10.94, + 13.802 + ], + "groundY": 2.412, + "roofY": 13.352, + "wallCount": 34, + "roofCount": 23 + }, + { + "id": "sion_2210", + "uuid": "{BD6FA21B-1BD8-4D3F-9864-1623FA607B74}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 339.707, + 11.841, + 1120.849 + ], + "size": [ + 36.719, + 21.57, + 24.784 + ], + "groundY": 1.056, + "roofY": 22.626, + "wallCount": 103, + "roofCount": 46 + }, + { + "id": "sion_2211", + "uuid": "{FCDBAEB2-9467-4207-B384-3F8623F85584}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 3, + 5 + ], + "center": [ + 26.672, + 62.375, + 1391.147 + ], + "size": [ + 36.867, + 14.45, + 18.632 + ], + "groundY": 55.15, + "roofY": 69.6, + "wallCount": 28, + "roofCount": 35 + }, + { + "id": "sion_2212", + "uuid": "{4977C76D-916D-40CE-B3B6-1619EEB4483E}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -195.23, + 8.695, + 1353.507 + ], + "size": [ + 50.992, + 9.6, + 33.815 + ], + "groundY": 3.895, + "roofY": 13.495, + "wallCount": 14, + "roofCount": 26 + }, + { + "id": "sion_2213", + "uuid": "{26E1AB06-86B0-40C3-B30D-32F13C3ADFBA}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 1 + ], + "center": [ + -1345.205, + 243.015, + -849.786 + ], + "size": [ + 7.387, + 0.942, + 12.864 + ], + "groundY": 242.544, + "roofY": 243.486, + "wallCount": 0, + "roofCount": 18 + }, + { + "id": "sion_2214", + "uuid": "{BCDFB512-E9C1-4D72-8136-11BD8497DCF7}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 2 + ], + "center": [ + -1207.662, + 74.667, + -74.03 + ], + "size": [ + 18.918, + 2.554, + 20.432 + ], + "groundY": 73.39, + "roofY": 75.943, + "wallCount": 0, + "roofCount": 17 + }, + { + "id": "sion_2215", + "uuid": "{E2BA0166-6C60-4BAA-8980-AC02935392D5}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 1, + 1 + ], + "center": [ + -610.453, + 131.041, + -861.236 + ], + "size": [ + 8.0, + 0.82, + 8.034 + ], + "groundY": 130.632, + "roofY": 131.451, + "wallCount": 0, + "roofCount": 16 + }, + { + "id": "sion_2216", + "uuid": "{CA4EC701-9ECE-4B2F-AEBB-CB62CC61CCD4}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 2 + ], + "center": [ + -411.805, + 32.73, + -100.264 + ], + "size": [ + 7.68, + 0.0, + 7.648 + ], + "groundY": 32.73, + "roofY": 32.73, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2217", + "uuid": "{23DEBCDD-950F-4FA4-8285-2DDDB0E36576}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 1, + 1 + ], + "center": [ + -1018.678, + 188.098, + -703.944 + ], + "size": [ + 5.387, + 0.43, + 5.542 + ], + "groundY": 187.883, + "roofY": 188.313, + "wallCount": 0, + "roofCount": 6 + }, + { + "id": "sion_2218", + "uuid": "{EF32638B-CE16-403B-80A8-21553AEB7CD7}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 2, + 2 + ], + "center": [ + -477.109, + 47.951, + -275.196 + ], + "size": [ + 32.797, + 2.986, + 21.306 + ], + "groundY": 46.458, + "roofY": 49.444, + "wallCount": 0, + "roofCount": 19 + }, + { + "id": "sion_2219", + "uuid": "{69709FAC-5269-4D42-A71A-2984DB4034B3}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 2 + ], + "center": [ + -416.758, + 30.048, + -40.723 + ], + "size": [ + 7.328, + 0.0, + 7.262 + ], + "groundY": 30.048, + "roofY": 30.048, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2220", + "uuid": "{FAB52561-5672-4CB1-8190-926B9F721922}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -898.986, + 19.171, + 15.154 + ], + "size": [ + 18.754, + 1.99, + 18.784 + ], + "groundY": 18.176, + "roofY": 20.166, + "wallCount": 0, + "roofCount": 11 + }, + { + "id": "sion_2221", + "uuid": "{5DAB1A36-242A-4881-B63A-D138FE2A1FC9}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 1, + 1 + ], + "center": [ + -698.84, + 141.753, + -814.122 + ], + "size": [ + 4.031, + 0.0, + 4.007 + ], + "groundY": 141.753, + "roofY": 141.753, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2222", + "uuid": "{299A316A-1A0E-40D0-B238-365A07AD1A8B}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 3 + ], + "center": [ + -1331.023, + 63.045, + 97.664 + ], + "size": [ + 25.922, + 4.699, + 23.926 + ], + "groundY": 60.696, + "roofY": 65.395, + "wallCount": 0, + "roofCount": 59 + }, + { + "id": "sion_2223", + "uuid": "{0376A254-1F4B-4BAD-B610-1011D4F11BF5}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 2 + ], + "center": [ + -404.947, + 47.476, + -457.473 + ], + "size": [ + 19.738, + 0.927, + 23.916 + ], + "groundY": 47.013, + "roofY": 47.939, + "wallCount": 0, + "roofCount": 11 + }, + { + "id": "sion_2224", + "uuid": "{DDB995CE-F373-4040-9657-3E8B442C4205}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 1, + 3 + ], + "center": [ + -924.988, + 17.734, + 71.428 + ], + "size": [ + 18.289, + 0.0, + 17.004 + ], + "groundY": 17.734, + "roofY": 17.734, + "wallCount": 0, + "roofCount": 4 + }, + { + "id": "sion_2225", + "uuid": "{5308E0A7-1634-4FD5-85A1-979F6DE29D13}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 0 + ], + "center": [ + -1131.781, + 293.736, + -1401.39 + ], + "size": [ + 9.211, + 0.638, + 4.649 + ], + "groundY": 293.417, + "roofY": 294.055, + "wallCount": 0, + "roofCount": 12 + }, + { + "id": "sion_2226", + "uuid": "{BE0D386B-795D-466E-805C-76E44AB2AD56}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 0 + ], + "center": [ + -1412.158, + 285.485, + -1320.379 + ], + "size": [ + 18.168, + 1.138, + 15.641 + ], + "groundY": 284.916, + "roofY": 286.054, + "wallCount": 0, + "roofCount": 31 + }, + { + "id": "sion_2227", + "uuid": "{53C03CB5-98F0-49F1-885A-6391AB0EE3D0}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 1, + 0 + ], + "center": [ + -1006.1, + 294.62, + -1341.76 + ], + "size": [ + 31.48, + 0.6, + 17.046 + ], + "groundY": 294.32, + "roofY": 294.92, + "wallCount": 0, + "roofCount": 58 + }, + { + "id": "sion_2228", + "uuid": "{04D46CC3-2E77-43AF-8FB2-093085728AE7}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 1 + ], + "center": [ + -1378.855, + 203.366, + -527.334 + ], + "size": [ + 17.43, + 1.262, + 10.647 + ], + "groundY": 202.735, + "roofY": 203.996, + "wallCount": 0, + "roofCount": 16 + }, + { + "id": "sion_2229", + "uuid": "{A9949487-EC1A-423A-A5E3-ED58092E14D8}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 0 + ], + "center": [ + -1453.197, + 275.214, + -1433.765 + ], + "size": [ + 12.457, + 0.664, + 8.578 + ], + "groundY": 274.882, + "roofY": 275.546, + "wallCount": 0, + "roofCount": 6 + }, + { + "id": "sion_2230", + "uuid": "{BB4F2610-E8DB-4690-8F42-C0B26A22F5B0}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 1, + 0 + ], + "center": [ + -842.541, + 296.644, + -1485.662 + ], + "size": [ + 7.816, + 0.0, + 9.382 + ], + "groundY": 296.644, + "roofY": 296.644, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2231", + "uuid": "{52F554D7-AAB6-49B1-BADE-9051FB9B6682}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 0 + ], + "center": [ + -1450.352, + 276.002, + -1441.182 + ], + "size": [ + 8.82, + 0.91, + 8.892 + ], + "groundY": 275.547, + "roofY": 276.457, + "wallCount": 0, + "roofCount": 12 + }, + { + "id": "sion_2232", + "uuid": "{04B518A1-9FC6-4136-82A1-8FDB505CED9D}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 1, + 0 + ], + "center": [ + -972.617, + 294.5, + -1353.911 + ], + "size": [ + 31.977, + 0.3, + 14.731 + ], + "groundY": 294.35, + "roofY": 294.65, + "wallCount": 0, + "roofCount": 55 + }, + { + "id": "sion_2233", + "uuid": "{C499238C-B980-4837-9A5B-CF37AA837BDC}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 2 + ], + "center": [ + -406.928, + 32.421, + -85.506 + ], + "size": [ + 8.106, + 0.0, + 8.0 + ], + "groundY": 32.421, + "roofY": 32.421, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2234", + "uuid": "{A5706B62-D38D-495F-A00D-F40A84157379}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 0, + 1 + ], + "center": [ + -1243.904, + 203.962, + -601.225 + ], + "size": [ + 23.551, + 1.266, + 18.216 + ], + "groundY": 203.329, + "roofY": 204.595, + "wallCount": 0, + "roofCount": 19 + }, + { + "id": "sion_2235", + "uuid": "{354E9794-7921-4358-AB80-629805FFCFD0}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1441.295, + 3.029, + 732.995 + ], + "size": [ + 27.801, + 1.66, + 60.018 + ], + "groundY": 2.199, + "roofY": 3.859, + "wallCount": 0, + "roofCount": 22 + }, + { + "id": "sion_2236", + "uuid": "{D5381173-7B55-49E7-8225-8A06B5A31586}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 1, + 0 + ], + "center": [ + -852.223, + 296.078, + -1522.629 + ], + "size": [ + 12.977, + 1.326, + 13.057 + ], + "groundY": 295.416, + "roofY": 296.741, + "wallCount": 0, + "roofCount": 14 + }, + { + "id": "sion_2237", + "uuid": "{9AEC6645-4A19-440F-934B-58B7574B5ECF}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 4 + ], + "center": [ + -1292.334, + 1.921, + 695.959 + ], + "size": [ + 5.863, + 0.884, + 11.332 + ], + "groundY": 1.479, + "roofY": 2.363, + "wallCount": 0, + "roofCount": 18 + }, + { + "id": "sion_2238", + "uuid": "{97B78878-DFE2-4EA9-A3D4-0EF1966C507E}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 2 + ], + "center": [ + -1065.412, + 99.805, + -364.017 + ], + "size": [ + 9.152, + 0.392, + 9.491 + ], + "groundY": 99.609, + "roofY": 100.002, + "wallCount": 0, + "roofCount": 11 + }, + { + "id": "sion_2239", + "uuid": "{D72E07B1-E79F-46A8-A7C3-840EE8ECEBEA}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 1 + ], + "center": [ + -1052.49, + 164.411, + -600.865 + ], + "size": [ + 3.723, + 0.569, + 3.638 + ], + "groundY": 164.127, + "roofY": 164.696, + "wallCount": 0, + "roofCount": 16 + }, + { + "id": "sion_2240", + "uuid": "{34B88EBE-121E-4127-84C1-B84943135C20}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 2 + ], + "center": [ + -421.617, + 35.331, + -142.456 + ], + "size": [ + 7.648, + 0.0, + 7.626 + ], + "groundY": 35.331, + "roofY": 35.331, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2241", + "uuid": "{7022424E-11E8-43D0-A232-C09F207A5B01}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 0 + ], + "center": [ + -1126.088, + 289.696, + -1225.736 + ], + "size": [ + 9.309, + 1.068, + 9.324 + ], + "groundY": 289.162, + "roofY": 290.23, + "wallCount": 0, + "roofCount": 19 + }, + { + "id": "sion_2242", + "uuid": "{7EAE4C89-03A7-4617-ABA5-1F5F9294A3A1}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -734.074, + 4.946, + 1450.496 + ], + "size": [ + 15.227, + 0.0, + 22.506 + ], + "groundY": 4.946, + "roofY": 4.946, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2243", + "uuid": "{EE46ED15-6066-4075-BD0A-8095578C692F}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1195.328, + 10.848, + 1263.554 + ], + "size": [ + 75.266, + 2.42, + 38.818 + ], + "groundY": 9.639, + "roofY": 12.058, + "wallCount": 0, + "roofCount": 10 + }, + { + "id": "sion_2244", + "uuid": "{BF5A1DA0-FA10-48A7-B4EA-32150ABA5493}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -767.07, + 5.162, + 1272.153 + ], + "size": [ + 24.094, + 0.332, + 16.392 + ], + "groundY": 4.996, + "roofY": 5.328, + "wallCount": 0, + "roofCount": 13 + }, + { + "id": "sion_2245", + "uuid": "{A79F30DA-5AE3-4B15-A463-CF0B3343F2B8}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1207.682, + 3.743, + 1417.259 + ], + "size": [ + 20.918, + 0.472, + 27.346 + ], + "groundY": 3.507, + "roofY": 3.979, + "wallCount": 0, + "roofCount": 17 + }, + { + "id": "sion_2246", + "uuid": "{B2DA95A6-A020-4EBD-A01D-A7E54BAE9C51}", + "name": "", + "class": "Flugdach", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1465.391, + 2.657, + 1485.938 + ], + "size": [ + 16.898, + 0.53, + 15.007 + ], + "groundY": 2.392, + "roofY": 2.922, + "wallCount": 0, + "roofCount": 22 + }, + { + "id": "sion_2247", + "uuid": "{78C77E6C-D4CD-4C16-B86A-84300523F70F}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 1, + 5 + ], + "center": [ + -604.461, + 5.469, + 1207.095 + ], + "size": [ + 9.992, + 0.554, + 13.33 + ], + "groundY": 5.192, + "roofY": 5.746, + "wallCount": 0, + "roofCount": 15 + }, + { + "id": "sion_2248", + "uuid": "{9490E9D2-789F-45A0-BA74-F692003A084A}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1510.664, + 2.8, + 1406.877 + ], + "size": [ + 20.273, + 0.886, + 13.719 + ], + "groundY": 2.357, + "roofY": 3.243, + "wallCount": 0, + "roofCount": 14 + }, + { + "id": "sion_2249", + "uuid": "{B77D84BF-3D4C-434F-A88E-6A94FBEC60AE}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 0, + 5 + ], + "center": [ + -1049.828, + 4.424, + 1448.212 + ], + "size": [ + 31.008, + 0.0, + 19.68 + ], + "groundY": 4.424, + "roofY": 4.424, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2250", + "uuid": "{669D5552-0DBC-452B-8B1A-DA862D38C061}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 953.658, + 13.617, + -200.14 + ], + "size": [ + 60.027, + 8.053, + 70.694 + ], + "groundY": 9.591, + "roofY": 17.643, + "wallCount": 0, + "roofCount": 288 + }, + { + "id": "sion_2251", + "uuid": "{5E748601-4889-4093-8575-DB40015CFA37}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 2 + ], + "center": [ + 66.336, + 25.987, + -39.158 + ], + "size": [ + 18.734, + 0.0, + 17.264 + ], + "groundY": 25.987, + "roofY": 25.987, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2252", + "uuid": "{DC9BD2C8-7D34-4764-8BFA-008F4378B687}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 5, + 2 + ], + "center": [ + 1285.027, + 13.124, + -25.267 + ], + "size": [ + 29.531, + 1.21, + 16.946 + ], + "groundY": 12.519, + "roofY": 13.729, + "wallCount": 0, + "roofCount": 12 + }, + { + "id": "sion_2253", + "uuid": "{769BE557-2A2A-44EF-A611-61AD82F346E0}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 5, + 4 + ], + "center": [ + 1122.527, + 11.779, + 747.935 + ], + "size": [ + 5.984, + 0.798, + 10.364 + ], + "groundY": 11.38, + "roofY": 12.178, + "wallCount": 0, + "roofCount": 22 + }, + { + "id": "sion_2254", + "uuid": "{42108FA0-55B1-4DA7-9CA3-131AAC855960}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 3 + ], + "center": [ + -21.592, + 13.616, + 424.352 + ], + "size": [ + 91.316, + 1.396, + 26.894 + ], + "groundY": 12.918, + "roofY": 14.314, + "wallCount": 0, + "roofCount": 32 + }, + { + "id": "sion_2255", + "uuid": "{C9DC1FC2-EC14-40CA-BF17-CED59AAC20B5}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 615.201, + 9.004, + 49.036 + ], + "size": [ + 12.066, + 0.114, + 6.042 + ], + "groundY": 8.947, + "roofY": 9.061, + "wallCount": 0, + "roofCount": 16 + }, + { + "id": "sion_2256", + "uuid": "{0B779C12-3A47-4B6D-8388-E7158ADA5715}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 524.393, + 10.68, + 789.229 + ], + "size": [ + 18.098, + 0.52, + 16.3 + ], + "groundY": 10.42, + "roofY": 10.94, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2257", + "uuid": "{76330F68-FD7C-40B9-9E7C-EBF1C5F35EAC}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 378.301, + 9.435, + 1009.953 + ], + "size": [ + 30.438, + 0.784, + 20.214 + ], + "groundY": 9.043, + "roofY": 9.827, + "wallCount": 0, + "roofCount": 26 + }, + { + "id": "sion_2258", + "uuid": "{3E1C3747-5071-471F-847E-83A78FA0F2A6}", + "name": "", + "class": "Gebaeude Einzelhaus", + "archStyle": "residential", + "tile": [ + 4, + 3 + ], + "center": [ + 1020.342, + 18.494, + 393.424 + ], + "size": [ + 17.168, + 3.626, + 23.014 + ], + "groundY": 16.681, + "roofY": 20.307, + "wallCount": 0, + "roofCount": 29 + }, + { + "id": "sion_2259", + "uuid": "{CA22BFBB-7431-40DA-ABC6-612EB0C90FE1}", + "name": "", + "class": "Flugdach", + "archStyle": "industrial", + "tile": [ + 2, + 1 + ], + "center": [ + -97.66, + 54.905, + -587.993 + ], + "size": [ + 9.797, + 0.0, + 9.229 + ], + "groundY": 54.905, + "roofY": 54.905, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2260", + "uuid": "{AA235EC0-BAC4-4510-8D60-33F5A5C6717E}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -193.055, + 6.036, + 931.932 + ], + "size": [ + 50.25, + 0.672, + 19.868 + ], + "groundY": 5.7, + "roofY": 6.372, + "wallCount": 0, + "roofCount": 14 + }, + { + "id": "sion_2261", + "uuid": "{7E2F265B-C1B3-47D6-823C-D3E80C69C639}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 54.371, + 9.772, + 613.361 + ], + "size": [ + 8.414, + 0.562, + 20.756 + ], + "groundY": 9.491, + "roofY": 10.053, + "wallCount": 0, + "roofCount": 13 + }, + { + "id": "sion_2262", + "uuid": "{33F44224-A457-4DC4-BAF6-D7E39C99086B}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 5, + 4 + ], + "center": [ + 1454.082, + 18.255, + 897.623 + ], + "size": [ + 16.594, + 1.182, + 10.378 + ], + "groundY": 17.664, + "roofY": 18.846, + "wallCount": 0, + "roofCount": 15 + }, + { + "id": "sion_2263", + "uuid": "{50302CFE-03F4-4819-8C65-BB7F6B70A7BC}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 872.025, + 9.696, + 376.682 + ], + "size": [ + 17.605, + 0.0, + 8.237 + ], + "groundY": 9.696, + "roofY": 9.696, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2264", + "uuid": "{201FEDF1-2774-4DBD-BB90-9E19F2E6E142}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 5, + 4 + ], + "center": [ + 1034.967, + 11.919, + 576.93 + ], + "size": [ + 6.988, + 0.0, + 12.458 + ], + "groundY": 11.919, + "roofY": 11.919, + "wallCount": 0, + "roofCount": 6 + }, + { + "id": "sion_2265", + "uuid": "{9E701664-D19A-41F6-B671-AA887CBF7ADA}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 211.857, + 8.592, + 919.925 + ], + "size": [ + 22.293, + 0.782, + 18.904 + ], + "groundY": 8.201, + "roofY": 8.983, + "wallCount": 0, + "roofCount": 12 + }, + { + "id": "sion_2266", + "uuid": "{B0A9AC56-DACE-4FEC-9299-13CDC3892D48}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 599.643, + 8.522, + 152.675 + ], + "size": [ + 6.988, + 0.0, + 14.848 + ], + "groundY": 8.522, + "roofY": 8.522, + "wallCount": 0, + "roofCount": 5 + }, + { + "id": "sion_2267", + "uuid": "{AA591171-EEDB-4841-8C95-70F7E9DCB757}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 2 + ], + "center": [ + -337.408, + 33.794, + -108.724 + ], + "size": [ + 7.777, + 0.0, + 7.812 + ], + "groundY": 33.794, + "roofY": 33.794, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2268", + "uuid": "{C57C5F5A-6708-449B-9100-0D9BE5F16E7E}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1245.689, + 12.015, + 488.864 + ], + "size": [ + 25.527, + 0.886, + 11.148 + ], + "groundY": 11.572, + "roofY": 12.458, + "wallCount": 0, + "roofCount": 10 + }, + { + "id": "sion_2269", + "uuid": "{C40F6898-B93C-4A66-9847-9AB7FC2A0E70}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 678.043, + 13.231, + 547.59 + ], + "size": [ + 54.492, + 2.384, + 86.918 + ], + "groundY": 12.04, + "roofY": 14.423, + "wallCount": 0, + "roofCount": 14 + }, + { + "id": "sion_2270", + "uuid": "{281C1431-0591-4B90-878C-32492A64FE7F}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 5, + 2 + ], + "center": [ + 1042.926, + 17.268, + -204.862 + ], + "size": [ + 105.336, + 1.264, + 78.01 + ], + "groundY": 16.636, + "roofY": 17.9, + "wallCount": 0, + "roofCount": 503 + }, + { + "id": "sion_2271", + "uuid": "{FC094713-6238-463D-9D5C-41BE46470307}", + "name": "", + "class": "Flugdach", + "archStyle": "industrial", + "tile": [ + 5, + 4 + ], + "center": [ + 1077.66, + 12.899, + 857.962 + ], + "size": [ + 13.766, + 1.102, + 12.988 + ], + "groundY": 12.348, + "roofY": 13.45, + "wallCount": 0, + "roofCount": 21 + }, + { + "id": "sion_2272", + "uuid": "{CE28A67C-3256-4B5D-91C6-BBA939AE17C5}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 0 + ], + "center": [ + 486.535, + 218.568, + -1494.539 + ], + "size": [ + 5.188, + 1.354, + 9.512 + ], + "groundY": 217.892, + "roofY": 219.245, + "wallCount": 0, + "roofCount": 10 + }, + { + "id": "sion_2273", + "uuid": "{E2C4CC0A-2735-4F06-98B7-D1548B8FE270}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 657.971, + 8.078, + 216.326 + ], + "size": [ + 11.418, + 0.4, + 15.546 + ], + "groundY": 7.878, + "roofY": 8.279, + "wallCount": 0, + "roofCount": 13 + }, + { + "id": "sion_2274", + "uuid": "{6FFC2302-E123-431F-9C69-4A7AAD39755F}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 1 + ], + "center": [ + -32.924, + 66.327, + -786.162 + ], + "size": [ + 7.48, + 0.538, + 7.622 + ], + "groundY": 66.058, + "roofY": 66.596, + "wallCount": 0, + "roofCount": 8 + }, + { + "id": "sion_2275", + "uuid": "{2B546147-91B0-49C0-948E-59BCCA660CEE}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 5, + 4 + ], + "center": [ + 1246.91, + 13.807, + 541.838 + ], + "size": [ + 13.688, + 4.11, + 84.053 + ], + "groundY": 11.752, + "roofY": 15.863, + "wallCount": 0, + "roofCount": 26 + }, + { + "id": "sion_2276", + "uuid": "{66312B78-D3CF-44BD-97A1-AD1639EFDA40}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 598.547, + 9.29, + 55.403 + ], + "size": [ + 7.484, + 0.344, + 18.368 + ], + "groundY": 9.118, + "roofY": 9.462, + "wallCount": 0, + "roofCount": 20 + }, + { + "id": "sion_2277", + "uuid": "{A49EA6D9-3D9C-405E-A40B-8B9873AEFD69}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 2, + 3 + ], + "center": [ + -119.152, + 3.865, + 337.454 + ], + "size": [ + 43.023, + 0.0, + 21.232 + ], + "groundY": 3.864, + "roofY": 3.865, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2278", + "uuid": "{6CB7409C-7F41-42C6-87F4-6323A923278C}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 42.896, + 7.029, + 772.194 + ], + "size": [ + 11.465, + 0.0, + 15.906 + ], + "groundY": 7.029, + "roofY": 7.029, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2279", + "uuid": "{E0CC01EB-E9C2-4B29-9D99-836A63FEA5CB}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 1 + ], + "center": [ + -117.066, + 72.698, + -845.356 + ], + "size": [ + 31.141, + 2.418, + 9.552 + ], + "groundY": 71.489, + "roofY": 73.907, + "wallCount": 0, + "roofCount": 28 + }, + { + "id": "sion_2280", + "uuid": "{B6C160AC-1725-4781-879E-41AE0868017A}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 374.922, + 8.865, + 974.866 + ], + "size": [ + 14.172, + 1.044, + 20.55 + ], + "groundY": 8.343, + "roofY": 9.387, + "wallCount": 0, + "roofCount": 11 + }, + { + "id": "sion_2281", + "uuid": "{0DCE46A1-58FD-4983-A0D9-40DDFB241862}", + "name": "", + "class": "Im Bau", + "archStyle": "industrial", + "tile": [ + 3, + 1 + ], + "center": [ + 184.496, + 70.64, + -1013.21 + ], + "size": [ + 26.562, + 0.256, + 20.926 + ], + "groundY": 70.512, + "roofY": 70.768, + "wallCount": 0, + "roofCount": 14 + }, + { + "id": "sion_2282", + "uuid": "{3A737AB8-73E9-4224-8518-A8C9F35A8080}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 223.568, + 8.256, + 688.767 + ], + "size": [ + 19.402, + 0.896, + 16.37 + ], + "groundY": 7.808, + "roofY": 8.704, + "wallCount": 0, + "roofCount": 15 + }, + { + "id": "sion_2283", + "uuid": "{56E9E15E-D044-47BD-BD65-7642B83FAAC1}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 418.666, + 9.011, + 962.814 + ], + "size": [ + 14.816, + 0.782, + 16.584 + ], + "groundY": 8.62, + "roofY": 9.402, + "wallCount": 0, + "roofCount": 10 + }, + { + "id": "sion_2284", + "uuid": "{4DDFB37D-317C-4CD3-83E4-7538559CBB40}", + "name": "Stade de Tourbillon", + "class": "Offenes Gebaeude", + "archStyle": "fortress", + "tile": [ + 4, + 2 + ], + "center": [ + 983.69, + 20.215, + -114.714 + ], + "size": [ + 100.332, + 0.944, + 74.32 + ], + "groundY": 19.743, + "roofY": 20.688, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2285", + "uuid": "{85548A1D-62A6-4DCC-A2C1-3B36B2EF60E8}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 2 + ], + "center": [ + -230.314, + 39.217, + -266.239 + ], + "size": [ + 14.34, + 0.0, + 9.242 + ], + "groundY": 39.217, + "roofY": 39.217, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2286", + "uuid": "{17003154-BEB0-4880-A342-644701A8AA24}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 5, + 4 + ], + "center": [ + 1433.619, + 19.174, + 911.498 + ], + "size": [ + 9.527, + 1.576, + 11.428 + ], + "groundY": 18.386, + "roofY": 19.961, + "wallCount": 0, + "roofCount": 8 + }, + { + "id": "sion_2287", + "uuid": "{352A84C5-AEF5-4707-88B3-8E4D7BADADC4}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 4 + ], + "center": [ + 57.772, + 9.996, + 593.839 + ], + "size": [ + 10.418, + 0.334, + 30.807 + ], + "groundY": 9.829, + "roofY": 10.163, + "wallCount": 0, + "roofCount": 30 + }, + { + "id": "sion_2288", + "uuid": "{C1A824A8-639C-4309-A6A0-27D56373A167}", + "name": "", + "class": "Flugdach", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -372.117, + 5.426, + 923.302 + ], + "size": [ + 27.773, + 0.532, + 46.968 + ], + "groundY": 5.16, + "roofY": 5.692, + "wallCount": 0, + "roofCount": 54 + }, + { + "id": "sion_2289", + "uuid": "{7B2AE0B0-2E46-4C4D-905F-08D13AEE8561}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 2 + ], + "center": [ + 860.047, + 8.451, + -299.514 + ], + "size": [ + 9.148, + 0.41, + 8.56 + ], + "groundY": 8.246, + "roofY": 8.656, + "wallCount": 0, + "roofCount": 14 + }, + { + "id": "sion_2290", + "uuid": "{D5BC60C8-C090-483B-840C-98A07FBA89A8}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 1 + ], + "center": [ + -46.668, + 62.307, + -689.205 + ], + "size": [ + 17.953, + 0.934, + 14.454 + ], + "groundY": 61.84, + "roofY": 62.775, + "wallCount": 0, + "roofCount": 13 + }, + { + "id": "sion_2291", + "uuid": "{C6FF453A-94CF-4EBD-9CC6-31BE1CB5D630}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 0 + ], + "center": [ + -187.699, + 214.873, + -1524.463 + ], + "size": [ + 6.977, + 0.44, + 14.51 + ], + "groundY": 214.653, + "roofY": 215.093, + "wallCount": 0, + "roofCount": 17 + }, + { + "id": "sion_2292", + "uuid": "{DBB9666E-894E-4C80-A449-223A94E79295}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 5, + 3 + ], + "center": [ + 1183.256, + 15.106, + 7.288 + ], + "size": [ + 26.207, + 1.186, + 26.471 + ], + "groundY": 14.513, + "roofY": 15.699, + "wallCount": 0, + "roofCount": 7 + }, + { + "id": "sion_2293", + "uuid": "{5698FF45-1A17-438C-B7F1-CD120CA4C50F}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 3 + ], + "center": [ + 991.633, + 9.081, + 395.269 + ], + "size": [ + 31.641, + 0.398, + 11.271 + ], + "groundY": 8.882, + "roofY": 9.28, + "wallCount": 0, + "roofCount": 14 + }, + { + "id": "sion_2294", + "uuid": "{E57093C2-84AA-4687-B4F6-FFBC40872891}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 1 + ], + "center": [ + 136.469, + 64.052, + -824.927 + ], + "size": [ + 14.5, + 0.134, + 11.044 + ], + "groundY": 63.985, + "roofY": 64.12, + "wallCount": 0, + "roofCount": 13 + }, + { + "id": "sion_2295", + "uuid": "{CE50B37C-B231-4550-BC6A-7B5961FDD937}", + "name": "", + "class": "Flugdach", + "archStyle": "industrial", + "tile": [ + 5, + 4 + ], + "center": [ + 1094.186, + 12.9, + 859.109 + ], + "size": [ + 8.058, + 1.098, + 12.854 + ], + "groundY": 12.351, + "roofY": 13.449, + "wallCount": 0, + "roofCount": 20 + }, + { + "id": "sion_2296", + "uuid": "{727056CA-B604-4692-9AF4-8E66F15BDB28}", + "name": "", + "class": "Flugdach", + "archStyle": "industrial", + "tile": [ + 2, + 4 + ], + "center": [ + -289.818, + 11.851, + 515.269 + ], + "size": [ + 78.715, + 0.0, + 24.998 + ], + "groundY": 11.851, + "roofY": 11.851, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2297", + "uuid": "{365C3191-FE3D-40C2-AE92-88BBD2B44DB0}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 3 + ], + "center": [ + 454.215, + 11.175, + 155.916 + ], + "size": [ + 16.25, + 0.446, + 24.701 + ], + "groundY": 10.952, + "roofY": 11.398, + "wallCount": 0, + "roofCount": 11 + }, + { + "id": "sion_2298", + "uuid": "{6783DCEC-0F34-47A2-93F7-CEAD6FAA40AA}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 5, + 2 + ], + "center": [ + 1075.283, + 13.608, + -122.335 + ], + "size": [ + 59.293, + 8.533, + 72.273 + ], + "groundY": 9.342, + "roofY": 17.875, + "wallCount": 0, + "roofCount": 293 + }, + { + "id": "sion_2299", + "uuid": "{893BC4A9-AFB9-4444-8F4E-4176352C751E}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 4, + 4 + ], + "center": [ + 753.527, + 21.216, + 991.246 + ], + "size": [ + 5.664, + 1.346, + 15.164 + ], + "groundY": 20.543, + "roofY": 21.889, + "wallCount": 0, + "roofCount": 26 + }, + { + "id": "sion_2300", + "uuid": "{1720748C-7040-4DBE-9D14-04A7BC56E047}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 3 + ], + "center": [ + -343.326, + 14.051, + 460.612 + ], + "size": [ + 36.168, + 0.0, + 57.06 + ], + "groundY": 14.05, + "roofY": 14.051, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2301", + "uuid": "{331729A2-5F3E-46F3-8E0A-9EEB0B44750C}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 1 + ], + "center": [ + 46.734, + 62.211, + -757.367 + ], + "size": [ + 6.688, + 0.358, + 10.138 + ], + "groundY": 62.032, + "roofY": 62.39, + "wallCount": 0, + "roofCount": 16 + }, + { + "id": "sion_2302", + "uuid": "{9256F720-7969-4F98-9021-09D856E13868}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 12.623, + 14.887, + 1312.762 + ], + "size": [ + 9.207, + 1.042, + 5.84 + ], + "groundY": 14.366, + "roofY": 15.408, + "wallCount": 0, + "roofCount": 12 + }, + { + "id": "sion_2303", + "uuid": "{F68771C7-4FB7-4738-AE79-D5DF84AFCB7E}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 49.805, + 10.434, + 1126.131 + ], + "size": [ + 19.086, + 1.32, + 13.775 + ], + "groundY": 9.775, + "roofY": 11.094, + "wallCount": 0, + "roofCount": 8 + }, + { + "id": "sion_2304", + "uuid": "{E4CCFFAE-0E3D-4D86-BE6D-320E4151F157}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 5, + 5 + ], + "center": [ + 1489.172, + 122.375, + 1147.885 + ], + "size": [ + 7.062, + 1.77, + 7.304 + ], + "groundY": 121.49, + "roofY": 123.26, + "wallCount": 0, + "roofCount": 11 + }, + { + "id": "sion_2305", + "uuid": "{B1B2C14E-4D14-4E05-88BE-01B437CC708A}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -257.145, + 6.536, + 1151.29 + ], + "size": [ + 18.914, + 0.252, + 27.555 + ], + "groundY": 6.41, + "roofY": 6.662, + "wallCount": 0, + "roofCount": 4 + }, + { + "id": "sion_2306", + "uuid": "{3F2164B1-B756-4088-B74D-E19EB815166C}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 230.879, + 66.381, + 1322.349 + ], + "size": [ + 7.969, + 0.672, + 6.624 + ], + "groundY": 66.046, + "roofY": 66.717, + "wallCount": 0, + "roofCount": 16 + }, + { + "id": "sion_2307", + "uuid": "{6AC15C6D-4AF7-4F5F-83A5-D9C07C4D0D57}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -222.691, + 7.16, + 1107.963 + ], + "size": [ + 15.078, + 0.772, + 11.656 + ], + "groundY": 6.774, + "roofY": 7.546, + "wallCount": 0, + "roofCount": 32 + }, + { + "id": "sion_2308", + "uuid": "{01F458AF-D927-4103-A5F4-5CB509AAD98D}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 480.408, + 15.126, + 1209.774 + ], + "size": [ + 11.98, + 0.0, + 10.494 + ], + "groundY": 15.126, + "roofY": 15.127, + "wallCount": 0, + "roofCount": 13 + }, + { + "id": "sion_2309", + "uuid": "{148752B5-DF43-4A01-941E-64F4183E7036}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -316.061, + 8.666, + 1153.321 + ], + "size": [ + 14.168, + 0.76, + 13.09 + ], + "groundY": 8.286, + "roofY": 9.046, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2310", + "uuid": "{0946E73B-7A7A-46D8-BF6E-792B726BFCA2}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 420.936, + 8.014, + 1204.528 + ], + "size": [ + 13.496, + 0.0, + 10.108 + ], + "groundY": 8.014, + "roofY": 8.014, + "wallCount": 0, + "roofCount": 2 + }, + { + "id": "sion_2311", + "uuid": "{B1BA3747-6D8C-4A61-A5C4-B560531AD406}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -351.623, + 6.72, + 1231.644 + ], + "size": [ + 16.066, + 1.352, + 26.202 + ], + "groundY": 6.044, + "roofY": 7.396, + "wallCount": 0, + "roofCount": 54 + }, + { + "id": "sion_2312", + "uuid": "{007BD679-C858-4EE9-8031-E6E0A8D27EAD}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 393.496, + 8.64, + 1101.021 + ], + "size": [ + 41.172, + 3.418, + 27.767 + ], + "groundY": 6.931, + "roofY": 10.348, + "wallCount": 0, + "roofCount": 4 + }, + { + "id": "sion_2313", + "uuid": "{CFE569C3-41FC-4698-9959-CB0F5BEBF4CC}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 3, + 5 + ], + "center": [ + 258.732, + 8.607, + 1147.918 + ], + "size": [ + 14.496, + 1.708, + 10.736 + ], + "groundY": 7.753, + "roofY": 9.461, + "wallCount": 0, + "roofCount": 29 + }, + { + "id": "sion_2314", + "uuid": "{0C0A0DE7-ED73-4EF8-9862-1857533569C0}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -301.1, + 6.058, + 1184.477 + ], + "size": [ + 53.488, + 2.654, + 38.116 + ], + "groundY": 4.731, + "roofY": 7.385, + "wallCount": 0, + "roofCount": 43 + }, + { + "id": "sion_2315", + "uuid": "{19982D1F-3CB4-4C72-9417-603B9A0EF66C}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -320.732, + 6.296, + 1180.996 + ], + "size": [ + 12.535, + 1.328, + 10.506 + ], + "groundY": 5.632, + "roofY": 6.96, + "wallCount": 0, + "roofCount": 19 + }, + { + "id": "sion_2316", + "uuid": "{0B920794-58EE-4ECC-942E-AC57007FA9F2}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -343.147, + 7.143, + 1224.559 + ], + "size": [ + 14.973, + 1.68, + 21.994 + ], + "groundY": 6.303, + "roofY": 7.983, + "wallCount": 0, + "roofCount": 17 + }, + { + "id": "sion_2317", + "uuid": "{5F4F483D-ADE3-4E41-91E4-97D8C5C07D93}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -354.162, + 6.123, + 1264.596 + ], + "size": [ + 10.27, + 0.63, + 8.466 + ], + "groundY": 5.808, + "roofY": 6.438, + "wallCount": 0, + "roofCount": 14 + }, + { + "id": "sion_2318", + "uuid": "{FC0CC0FC-15E4-4320-8C0A-2A315B58709F}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -322.492, + 5.538, + 1169.796 + ], + "size": [ + 24.633, + 1.328, + 22.078 + ], + "groundY": 4.874, + "roofY": 6.202, + "wallCount": 0, + "roofCount": 19 + }, + { + "id": "sion_2319", + "uuid": "{A645D567-B4AF-4469-AF02-85DEEBAB4DA2}", + "name": "", + "class": "Offenes Gebaeude", + "archStyle": "industrial", + "tile": [ + 2, + 5 + ], + "center": [ + -288.17, + 6.534, + 1199.79 + ], + "size": [ + 15.551, + 0.57, + 25.193 + ], + "groundY": 6.249, + "roofY": 6.819, + "wallCount": 0, + "roofCount": 15 + } + ] +} \ No newline at end of file diff --git a/assets/maps/sion/heightmap_05m.u16z b/assets/maps/sion/heightmap_05m.u16z new file mode 100644 index 0000000..3c2dd63 Binary files /dev/null and b/assets/maps/sion/heightmap_05m.u16z differ diff --git a/assets/maps/sion/metadata.json b/assets/maps/sion/metadata.json new file mode 100644 index 0000000..ac7c1c7 --- /dev/null +++ b/assets/maps/sion/metadata.json @@ -0,0 +1,1155 @@ +{ + "name": "Sion, Valais, Switzerland", + "attribution": "Federal Office of Topography swisstopo", + "sources": [ + "ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)", + "ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)" + ], + "stacItems": [ + "swissalti3d_2024_2592-1118", + "swissalti3d_2024_2592-1119", + "swissalti3d_2024_2592-1120", + "swissalti3d_2024_2592-1121", + "swissalti3d_2024_2593-1118", + "swissalti3d_2024_2593-1119", + "swissalti3d_2024_2593-1120", + "swissalti3d_2024_2593-1121", + "swissalti3d_2024_2594-1118", + "swissalti3d_2024_2594-1119", + "swissalti3d_2024_2594-1120", + "swissalti3d_2024_2594-1121", + "swissalti3d_2024_2595-1118", + "swissalti3d_2024_2595-1119", + "swissalti3d_2024_2595-1120", + "swissalti3d_2024_2595-1121", + "swissbuildings3d_3_0_2020_1306-12", + "swissbuildings3d_3_0_2020_1306-14", + "swissbuildings3d_3_0_2020_1306-21", + "swissbuildings3d_3_0_2020_1306-23" + ], + "demAssetHash": "a0dae3310058004e43a071290b3972ae4e0919e0958be5ec56320ea1a204c5de", + "crs": "EPSG:2056", + "originE": 2592614.0, + "originN": 1118514.0, + "centerE": 2594150.0, + "centerN": 1120050.0, + "baseElevationM": 483.41, + "minY": -5.885, + "maxY": 304.957, + "reliefM": 310.841, + "sizeMeters": 3072.0, + "tileGrid": 16, + "tileSizeMeters": 192.0, + "buildingTileGrid": 6, + "buildingTileSizeMeters": 512.0, + "gridRes": 6145, + "cellSizeMeters": 0.5, + "heightmapFile": "heightmap_05m.u16z", + "heightmapFormat": "rdhm_v2_u16_zigzag_zlib", + "heightmapMinY": -5.884674072265625, + "heightmapScale": 0.004743136931210756, + "surfaceTexture": "terrain_surface.png", + "surfaceTextureSize": 4096, + "surfaceTextureFormat": "png_rgb_north_to_south_west_to_east", + "surfaceMaskTexture": "terrain_surface_mask.png", + "surfaceMaskTextureSize": 2048, + "surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water", + "collisionFormat": { + "magic": "RCOL", + "version": 1, + "headerBytes": 48, + "headerLayout": "magic[4], uint32 version, int32 tx, int32 tz, uint32 vertexCount, uint32 indexCount, float32[3] boundsMin, float32[3] boundsMax", + "vertexLayout": "float32[vertexCount * 3] (X, Y, Z in arena glTF space)", + "indexLayout": "int32[indexCount] (CCW outward triangles)" + }, + "rowOrder": "north_to_south_z_neg_to_pos", + "colOrder": "west_to_east_x_neg_to_pos", + "coordinateTransform": { + "X": "E - centerE (East = +X)", + "Y": "Z_asl - baseElevationM (Up = +Y)", + "Z": "-(N - centerN) (North = -Z)" + }, + "tileCount": 36, + "tiles": [ + { + "tx": 0, + "tz": 0, + "lod2": "tiles/lod2_0_0.glb", + "lod1": "tiles/lod1_0_0.glb", + "collision": "tiles/col_0_0.bin", + "buildingCount": 166, + "lod2Tris": 11394, + "lod2Bytes": 588932, + "colVerts": 14880, + "colTris": 11268, + "colBytes": 313824, + "center": [ + -1280.0, + 0.0, + -1280.0 + ], + "boundsMin": [ + -1546.056, + 260.242, + -1542.931 + ], + "boundsMax": [ + -1010.277, + 305.043, + -1010.118 + ], + "lod1Tris": 13480, + "lod1Bytes": 688656 + }, + { + "tx": 0, + "tz": 1, + "lod2": "tiles/lod2_0_1.glb", + "lod1": "tiles/lod1_0_1.glb", + "collision": "tiles/col_0_1.bin", + "buildingCount": 144, + "lod2Tris": 8665, + "lod2Bytes": 440804, + "colVerts": 11107, + "colTris": 8559, + "colBytes": 236040, + "center": [ + -1280.0, + 0.0, + -768.0 + ], + "boundsMin": [ + -1547.395, + 164.126, + -1030.299 + ], + "boundsMax": [ + -1031.902, + 282.001, + -506.363 + ], + "lod1Tris": 9756, + "lod1Bytes": 492256 + }, + { + "tx": 0, + "tz": 2, + "lod2": "tiles/lod2_0_2.glb", + "lod1": "tiles/lod1_0_2.glb", + "collision": "tiles/col_0_2.bin", + "buildingCount": 88, + "lod2Tris": 6119, + "lod2Bytes": 321308, + "colVerts": 7885, + "colTris": 5710, + "colBytes": 163188, + "center": [ + -1280.0, + 0.0, + -256.0 + ], + "boundsMin": [ + -1539.297, + 12.895, + -512.019 + ], + "boundsMax": [ + -1011.797, + 207.918, + 16.535 + ], + "lod1Tris": 7246, + "lod1Bytes": 375504 + }, + { + "tx": 0, + "tz": 3, + "lod2": "tiles/lod2_0_3.glb", + "lod1": "tiles/lod1_0_3.glb", + "collision": "tiles/col_0_3.bin", + "buildingCount": 113, + "lod2Tris": 9586, + "lod2Bytes": 500104, + "colVerts": 12640, + "colTris": 9120, + "colBytes": 261168, + "center": [ + -1280.0, + 0.0, + 256.0 + ], + "boundsMin": [ + -1545.137, + -4.677, + -20.359 + ], + "boundsMax": [ + -1012.152, + 98.628, + 522.141 + ], + "lod1Tris": 11660, + "lod1Bytes": 598628 + }, + { + "tx": 0, + "tz": 4, + "lod2": "tiles/lod2_0_4.glb", + "lod1": "tiles/lod1_0_4.glb", + "collision": "tiles/col_0_4.bin", + "buildingCount": 55, + "lod2Tris": 3285, + "lod2Bytes": 165796, + "colVerts": 4232, + "colTris": 3277, + "colBytes": 90156, + "center": [ + -1280.0, + 0.0, + 768.0 + ], + "boundsMin": [ + -1542.234, + -5.68, + 491.398 + ], + "boundsMax": [ + -1035.621, + 42.218, + 1047.621 + ], + "lod1Tris": 3720, + "lod1Bytes": 184348 + }, + { + "tx": 0, + "tz": 5, + "lod2": "tiles/lod2_0_5.glb", + "lod1": "tiles/lod1_0_5.glb", + "collision": "tiles/col_0_5.bin", + "buildingCount": 34, + "lod2Tris": 1641, + "lod2Bytes": 84044, + "colVerts": 1976, + "colTris": 1641, + "colBytes": 43452, + "center": [ + -1280.0, + 0.0, + 1280.0 + ], + "boundsMin": [ + -1566.132, + -3.427, + 1073.149 + ], + "boundsMax": [ + -1023.434, + 23.29, + 1529.117 + ], + "lod1Tris": 2381, + "lod1Bytes": 122052 + }, + { + "tx": 1, + "tz": 0, + "lod2": "tiles/lod2_1_0.glb", + "lod1": "tiles/lod1_1_0.glb", + "collision": "tiles/col_1_0.bin", + "buildingCount": 50, + "lod2Tris": 2626, + "lod2Bytes": 137832, + "colVerts": 3543, + "colTris": 2626, + "colBytes": 74076, + "center": [ + -768.0, + 0.0, + -1280.0 + ], + "boundsMin": [ + -1032.996, + 280.451, + -1540.333 + ], + "boundsMax": [ + -564.015, + 305.354, + -1187.799 + ], + "lod1Tris": 3376, + "lod1Bytes": 172152 + }, + { + "tx": 1, + "tz": 1, + "lod2": "tiles/lod2_1_1.glb", + "lod1": "tiles/lod1_1_1.glb", + "collision": "tiles/col_1_1.bin", + "buildingCount": 41, + "lod2Tris": 2085, + "lod2Bytes": 112644, + "colVerts": 2718, + "colTris": 1965, + "colBytes": 56244, + "center": [ + -768.0, + 0.0, + -768.0 + ], + "boundsMin": [ + -1021.371, + 49.525, + -898.786 + ], + "boundsMax": [ + -501.414, + 208.412, + -503.779 + ], + "lod1Tris": 2652, + "lod1Bytes": 139388 + }, + { + "tx": 1, + "tz": 2, + "lod2": "tiles/lod2_1_2.glb", + "lod1": "tiles/lod1_1_2.glb", + "collision": "tiles/col_1_2.bin", + "buildingCount": 164, + "lod2Tris": 11715, + "lod2Bytes": 614372, + "colVerts": 15712, + "colTris": 11068, + "colBytes": 321408, + "center": [ + -768.0, + 0.0, + -256.0 + ], + "boundsMin": [ + -1034.941, + 11.698, + -526.488 + ], + "boundsMax": [ + -504.941, + 125.997, + 17.166 + ], + "lod1Tris": 16285, + "lod1Bytes": 846908 + }, + { + "tx": 1, + "tz": 3, + "lod2": "tiles/lod2_1_3.glb", + "lod1": "tiles/lod1_1_3.glb", + "collision": "tiles/col_1_3.bin", + "buildingCount": 138, + "lod2Tris": 10546, + "lod2Bytes": 543092, + "colVerts": 14382, + "colTris": 10509, + "colBytes": 298740, + "center": [ + -768.0, + 0.0, + 256.0 + ], + "boundsMin": [ + -1037.914, + -4.639, + -37.108 + ], + "boundsMax": [ + -443.449, + 40.721, + 537.126 + ], + "lod1Tris": 15651, + "lod1Bytes": 803884 + }, + { + "tx": 1, + "tz": 4, + "lod2": "tiles/lod2_1_4.glb", + "lod1": "tiles/lod1_1_4.glb", + "collision": "tiles/col_1_4.bin", + "buildingCount": 38, + "lod2Tris": 2524, + "lod2Bytes": 128996, + "colVerts": 3296, + "colTris": 2502, + "colBytes": 69624, + "center": [ + -768.0, + 0.0, + 768.0 + ], + "boundsMin": [ + -1099.73, + -2.707, + 479.377 + ], + "boundsMax": [ + -525.465, + 23.422, + 1055.034 + ], + "lod1Tris": 2974, + "lod1Bytes": 147548 + }, + { + "tx": 1, + "tz": 5, + "lod2": "tiles/lod2_1_5.glb", + "lod1": "tiles/lod1_1_5.glb", + "collision": "tiles/col_1_5.bin", + "buildingCount": 42, + "lod2Tris": 1912, + "lod2Bytes": 99916, + "colVerts": 2530, + "colTris": 1912, + "colBytes": 53352, + "center": [ + -768.0, + 0.0, + 1280.0 + ], + "boundsMin": [ + -1024.523, + -2.51, + 1013.78 + ], + "boundsMax": [ + -488.918, + 26.437, + 1530.035 + ], + "lod1Tris": 2617, + "lod1Bytes": 127840 + }, + { + "tx": 2, + "tz": 0, + "lod2": "tiles/lod2_2_0.glb", + "lod1": "tiles/lod1_2_0.glb", + "collision": "tiles/col_2_0.bin", + "buildingCount": 16, + "lod2Tris": 847, + "lod2Bytes": 48024, + "colVerts": 1191, + "colTris": 835, + "colBytes": 24360, + "center": [ + -256.0, + 0.0, + -1280.0 + ], + "boundsMin": [ + -500.015, + 78.33, + -1531.718 + ], + "boundsMax": [ + 7.269, + 279.265, + -1024.065 + ], + "lod1Tris": 1102, + "lod1Bytes": 60608 + }, + { + "tx": 2, + "tz": 1, + "lod2": "tiles/lod2_2_1.glb", + "lod1": "tiles/lod1_2_1.glb", + "collision": "tiles/col_2_1.bin", + "buildingCount": 121, + "lod2Tris": 10933, + "lod2Bytes": 587944, + "colVerts": 15353, + "colTris": 10700, + "colBytes": 312684, + "center": [ + -256.0, + 0.0, + -768.0 + ], + "boundsMin": [ + -526.844, + 41.641, + -1045.61 + ], + "boundsMax": [ + 6.731, + 108.915, + -494.241 + ], + "lod1Tris": 14860, + "lod1Bytes": 791384 + }, + { + "tx": 2, + "tz": 2, + "lod2": "tiles/lod2_2_2.glb", + "lod1": "tiles/lod1_2_2.glb", + "collision": "tiles/col_2_2.bin", + "buildingCount": 130, + "lod2Tris": 18764, + "lod2Bytes": 1056476, + "colVerts": 27755, + "colTris": 18493, + "colBytes": 555024, + "center": [ + -256.0, + 0.0, + -256.0 + ], + "boundsMin": [ + -580.315, + 18.195, + -528.981 + ], + "boundsMax": [ + 17.887, + 96.714, + 47.924 + ], + "lod1Tris": 36633, + "lod1Bytes": 1962212 + }, + { + "tx": 2, + "tz": 3, + "lod2": "tiles/lod2_2_3.glb", + "lod1": "tiles/lod1_2_3.glb", + "collision": "tiles/col_2_3.bin", + "buildingCount": 81, + "lod2Tris": 9035, + "lod2Bytes": 493852, + "colVerts": 13240, + "colTris": 8851, + "colBytes": 265140, + "center": [ + -256.0, + 0.0, + 256.0 + ], + "boundsMin": [ + -539.387, + 0.845, + -12.595 + ], + "boundsMax": [ + 38.391, + 48.016, + 522.511 + ], + "lod1Tris": 24340, + "lod1Bytes": 1303228 + }, + { + "tx": 2, + "tz": 4, + "lod2": "tiles/lod2_2_4.glb", + "lod1": "tiles/lod1_2_4.glb", + "collision": "tiles/col_2_4.bin", + "buildingCount": 44, + "lod2Tris": 3315, + "lod2Bytes": 172488, + "colVerts": 4388, + "colTris": 3293, + "colBytes": 92220, + "center": [ + -256.0, + 0.0, + 768.0 + ], + "boundsMin": [ + -558.116, + -2.247, + 485.877 + ], + "boundsMax": [ + 23.758, + 43.921, + 1009.472 + ], + "lod1Tris": 4691, + "lod1Bytes": 242564 + }, + { + "tx": 2, + "tz": 5, + "lod2": "tiles/lod2_2_5.glb", + "lod1": "tiles/lod1_2_5.glb", + "collision": "tiles/col_2_5.bin", + "buildingCount": 50, + "lod2Tris": 2651, + "lod2Bytes": 143948, + "colVerts": 3700, + "colTris": 2571, + "colBytes": 75300, + "center": [ + -256.0, + 0.0, + 1280.0 + ], + "boundsMin": [ + -499.758, + -0.287, + 1021.871 + ], + "boundsMax": [ + -3.859, + 129.895, + 1541.812 + ], + "lod1Tris": 4289, + "lod1Bytes": 224972 + }, + { + "tx": 3, + "tz": 0, + "lod2": "tiles/lod2_3_0.glb", + "lod1": "tiles/lod1_3_0.glb", + "collision": "tiles/col_3_0.bin", + "buildingCount": 72, + "lod2Tris": 4455, + "lod2Bytes": 230360, + "colVerts": 5687, + "colTris": 4307, + "colBytes": 119976, + "center": [ + 256.0, + 0.0, + -1280.0 + ], + "boundsMin": [ + -9.106, + 79.363, + -1549.693 + ], + "boundsMax": [ + 516.293, + 233.751, + -1013.705 + ], + "lod1Tris": 5251, + "lod1Bytes": 268936 + }, + { + "tx": 3, + "tz": 1, + "lod2": "tiles/lod2_3_1.glb", + "lod1": "tiles/lod1_3_1.glb", + "collision": "tiles/col_3_1.bin", + "buildingCount": 118, + "lod2Tris": 6833, + "lod2Bytes": 349856, + "colVerts": 9021, + "colTris": 6677, + "colBytes": 188424, + "center": [ + 256.0, + 0.0, + -768.0 + ], + "boundsMin": [ + -8.379, + 48.924, + -1027.13 + ], + "boundsMax": [ + 520.473, + 169.722, + -521.475 + ], + "lod1Tris": 9073, + "lod1Bytes": 450952 + }, + { + "tx": 3, + "tz": 2, + "lod2": "tiles/lod2_3_2.glb", + "lod1": "tiles/lod1_3_2.glb", + "collision": "tiles/col_3_2.bin", + "buildingCount": 50, + "lod2Tris": 7192, + "lod2Bytes": 393472, + "colVerts": 7102, + "colTris": 5960, + "colBytes": 156792, + "center": [ + 256.0, + 0.0, + -256.0 + ], + "boundsMin": [ + -25.629, + 2.473, + -532.988 + ], + "boundsMax": [ + 502.961, + 189.352, + 16.267 + ], + "lod1Tris": 21458, + "lod1Bytes": 1157012 + }, + { + "tx": 3, + "tz": 3, + "lod2": "tiles/lod2_3_3.glb", + "lod1": "tiles/lod1_3_3.glb", + "collision": "tiles/col_3_3.bin", + "buildingCount": 82, + "lod2Tris": 6359, + "lod2Bytes": 339760, + "colVerts": 9108, + "colTris": 6253, + "colBytes": 184380, + "center": [ + 256.0, + 0.0, + 256.0 + ], + "boundsMin": [ + -35.797, + 1.157, + -34.311 + ], + "boundsMax": [ + 492.52, + 54.532, + 526.016 + ], + "lod1Tris": 15755, + "lod1Bytes": 822616 + }, + { + "tx": 3, + "tz": 4, + "lod2": "tiles/lod2_3_4.glb", + "lod1": "tiles/lod1_3_4.glb", + "collision": "tiles/col_3_4.bin", + "buildingCount": 65, + "lod2Tris": 3002, + "lod2Bytes": 157176, + "colVerts": 3991, + "colTris": 2894, + "colBytes": 82668, + "center": [ + 256.0, + 0.0, + 768.0 + ], + "boundsMin": [ + -1.326, + 0.35, + 487.22 + ], + "boundsMax": [ + 537.785, + 25.822, + 1027.025 + ], + "lod1Tris": 4296, + "lod1Bytes": 212216 + }, + { + "tx": 3, + "tz": 5, + "lod2": "tiles/lod2_3_5.glb", + "lod1": "tiles/lod1_3_5.glb", + "collision": "tiles/col_3_5.bin", + "buildingCount": 53, + "lod2Tris": 3123, + "lod2Bytes": 163036, + "colVerts": 4126, + "colTris": 3078, + "colBytes": 86496, + "center": [ + 256.0, + 0.0, + 1280.0 + ], + "boundsMin": [ + 8.019, + 0.877, + 987.364 + ], + "boundsMax": [ + 495.488, + 159.415, + 1519.15 + ], + "lod1Tris": 4109, + "lod1Bytes": 205840 + }, + { + "tx": 4, + "tz": 0, + "lod2": "tiles/lod2_4_0.glb", + "lod1": "tiles/lod1_4_0.glb", + "collision": "tiles/col_4_0.bin", + "buildingCount": 18, + "lod2Tris": 1113, + "lod2Bytes": 58452, + "colVerts": 1496, + "colTris": 1113, + "colBytes": 31356, + "center": [ + 768.0, + 0.0, + -1280.0 + ], + "boundsMin": [ + 505.684, + 67.229, + -1537.321 + ], + "boundsMax": [ + 877.363, + 274.295, + -1086.908 + ], + "lod1Tris": 1444, + "lod1Bytes": 74984 + }, + { + "tx": 4, + "tz": 1, + "lod2": "tiles/lod2_4_1.glb", + "lod1": "tiles/lod1_4_1.glb", + "collision": "tiles/col_4_1.bin", + "buildingCount": 14, + "lod2Tris": 1018, + "lod2Bytes": 58300, + "colVerts": 1210, + "colTris": 942, + "colBytes": 25872, + "center": [ + 768.0, + 0.0, + -768.0 + ], + "boundsMin": [ + 495.027, + 3.558, + -978.398 + ], + "boundsMax": [ + 976.672, + 157.446, + -504.037 + ], + "lod1Tris": 1365, + "lod1Bytes": 75608 + }, + { + "tx": 4, + "tz": 2, + "lod2": "tiles/lod2_4_2.glb", + "lod1": "tiles/lod1_4_2.glb", + "collision": "tiles/col_4_2.bin", + "buildingCount": 42, + "lod2Tris": 4425, + "lod2Bytes": 233824, + "colVerts": 5522, + "colTris": 4386, + "colBytes": 118944, + "center": [ + 768.0, + 0.0, + -256.0 + ], + "boundsMin": [ + 499.328, + 2.184, + -502.85 + ], + "boundsMax": [ + 1033.969, + 89.448, + 2.281 + ], + "lod1Tris": 5054, + "lod1Bytes": 263828 + }, + { + "tx": 4, + "tz": 3, + "lod2": "tiles/lod2_4_3.glb", + "lod1": "tiles/lod1_4_3.glb", + "collision": "tiles/col_4_3.bin", + "buildingCount": 65, + "lod2Tris": 4567, + "lod2Bytes": 236272, + "colVerts": 5959, + "colTris": 4556, + "colBytes": 126228, + "center": [ + 768.0, + 0.0, + 256.0 + ], + "boundsMin": [ + 522.107, + 1.139, + -14.4 + ], + "boundsMax": [ + 1041.492, + 36.96, + 522.428 + ], + "lod1Tris": 5382, + "lod1Bytes": 278840 + }, + { + "tx": 4, + "tz": 4, + "lod2": "tiles/lod2_4_4.glb", + "lod1": "tiles/lod1_4_4.glb", + "collision": "tiles/col_4_4.bin", + "buildingCount": 52, + "lod2Tris": 3923, + "lod2Bytes": 210284, + "colVerts": 5094, + "colTris": 3903, + "colBytes": 108012, + "center": [ + 768.0, + 0.0, + 768.0 + ], + "boundsMin": [ + 476.82, + 0.435, + 471.31 + ], + "boundsMax": [ + 1004.543, + 27.116, + 1056.785 + ], + "lod1Tris": 4688, + "lod1Bytes": 241548 + }, + { + "tx": 4, + "tz": 5, + "lod2": "tiles/lod2_4_5.glb", + "lod1": "tiles/lod1_4_5.glb", + "collision": "tiles/col_4_5.bin", + "buildingCount": 16, + "lod2Tris": 1067, + "lod2Bytes": 57904, + "colVerts": 1363, + "colTris": 1015, + "colBytes": 28584, + "center": [ + 768.0, + 0.0, + 1280.0 + ], + "boundsMin": [ + 506.594, + 4.145, + 1049.851 + ], + "boundsMax": [ + 995.574, + 124.069, + 1422.036 + ], + "lod1Tris": 1264, + "lod1Bytes": 67056 + }, + { + "tx": 5, + "tz": 0, + "lod2": "tiles/lod2_5_0.glb", + "lod1": "tiles/lod1_5_0.glb", + "collision": "tiles/col_5_0.bin", + "buildingCount": 7, + "lod2Tris": 345, + "lod2Bytes": 22080, + "colVerts": 471, + "colTris": 345, + "colBytes": 9840, + "center": [ + 1280.0, + 0.0, + -1280.0 + ], + "boundsMin": [ + 1046.164, + 5.103, + -1524.624 + ], + "boundsMax": [ + 1502.379, + 137.053, + -1026.293 + ], + "lod1Tris": 511, + "lod1Bytes": 29780 + }, + { + "tx": 5, + "tz": 1, + "lod2": "tiles/lod2_5_1.glb", + "lod1": "tiles/lod1_5_1.glb", + "collision": "tiles/col_5_1.bin", + "buildingCount": 7, + "lod2Tris": 406, + "lod2Bytes": 24384, + "colVerts": 557, + "colTris": 398, + "colBytes": 11508, + "center": [ + 1280.0, + 0.0, + -768.0 + ], + "boundsMin": [ + 1013.32, + 4.526, + -946.625 + ], + "boundsMax": [ + 1502.84, + 18.437, + -613.109 + ], + "lod1Tris": 692, + "lod1Bytes": 37412 + }, + { + "tx": 5, + "tz": 2, + "lod2": "tiles/lod2_5_2.glb", + "lod1": "tiles/lod1_5_2.glb", + "collision": "tiles/col_5_2.bin", + "buildingCount": 19, + "lod2Tris": 1832, + "lod2Bytes": 108660, + "colVerts": 2431, + "colTris": 1832, + "colBytes": 51204, + "center": [ + 1280.0, + 0.0, + -256.0 + ], + "boundsMin": [ + 990.258, + 2.669, + -327.278 + ], + "boundsMax": [ + 1545.097, + 24.902, + 5.311 + ], + "lod1Tris": 2096, + "lod1Bytes": 119508 + }, + { + "tx": 5, + "tz": 3, + "lod2": "tiles/lod2_5_3.glb", + "lod1": "tiles/lod1_5_3.glb", + "collision": "tiles/col_5_3.bin", + "buildingCount": 82, + "lod2Tris": 6318, + "lod2Bytes": 321316, + "colVerts": 8411, + "colTris": 6278, + "colBytes": 176316, + "center": [ + 1280.0, + 0.0, + 256.0 + ], + "boundsMin": [ + 1011.734, + 3.263, + -10.193 + ], + "boundsMax": [ + 1555.777, + 42.438, + 511.41 + ], + "lod1Tris": 8052, + "lod1Bytes": 398600 + }, + { + "tx": 5, + "tz": 4, + "lod2": "tiles/lod2_5_4.glb", + "lod1": "tiles/lod1_5_4.glb", + "collision": "tiles/col_5_4.bin", + "buildingCount": 21, + "lod2Tris": 903, + "lod2Bytes": 47420, + "colVerts": 1177, + "colTris": 901, + "colBytes": 24984, + "center": [ + 1280.0, + 0.0, + 768.0 + ], + "boundsMin": [ + 1021.43, + 4.992, + 499.811 + ], + "boundsMax": [ + 1462.379, + 29.764, + 949.481 + ], + "lod1Tris": 1504, + "lod1Bytes": 73524 + }, + { + "tx": 5, + "tz": 5, + "lod2": "tiles/lod2_5_5.glb", + "lod1": "tiles/lod1_5_5.glb", + "collision": "tiles/col_5_5.bin", + "buildingCount": 21, + "lod2Tris": 1363, + "lod2Bytes": 72584, + "colVerts": 1767, + "colTris": 1335, + "colBytes": 37272, + "center": [ + 1280.0, + 0.0, + 1280.0 + ], + "boundsMin": [ + 1028.355, + 14.941, + 1041.767 + ], + "boundsMax": [ + 1523.641, + 239.532, + 1482.03 + ], + "lod1Tris": 1523, + "lod1Bytes": 81284 + } + ] +} \ No newline at end of file diff --git a/assets/maps/sion/terrain_surface.png b/assets/maps/sion/terrain_surface.png new file mode 100644 index 0000000..88ec3f2 Binary files /dev/null and b/assets/maps/sion/terrain_surface.png differ diff --git a/assets/maps/sion/terrain_surface_mask.png b/assets/maps/sion/terrain_surface_mask.png new file mode 100644 index 0000000..eeac085 Binary files /dev/null and b/assets/maps/sion/terrain_surface_mask.png differ diff --git a/assets/maps/sion/tiles/col_0_0.bin b/assets/maps/sion/tiles/col_0_0.bin new file mode 100644 index 0000000..f3e074f Binary files /dev/null and b/assets/maps/sion/tiles/col_0_0.bin differ diff --git a/assets/maps/sion/tiles/col_0_1.bin b/assets/maps/sion/tiles/col_0_1.bin new file mode 100644 index 0000000..ff8eafd Binary files /dev/null and b/assets/maps/sion/tiles/col_0_1.bin differ diff --git a/assets/maps/sion/tiles/col_0_2.bin b/assets/maps/sion/tiles/col_0_2.bin new file mode 100644 index 0000000..2416d76 Binary files /dev/null and b/assets/maps/sion/tiles/col_0_2.bin differ diff --git a/assets/maps/sion/tiles/col_0_3.bin b/assets/maps/sion/tiles/col_0_3.bin new file mode 100644 index 0000000..7c35dea Binary files /dev/null and b/assets/maps/sion/tiles/col_0_3.bin differ diff --git a/assets/maps/sion/tiles/col_0_4.bin b/assets/maps/sion/tiles/col_0_4.bin new file mode 100644 index 0000000..64806cb Binary files /dev/null and b/assets/maps/sion/tiles/col_0_4.bin differ diff --git a/assets/maps/sion/tiles/col_0_5.bin b/assets/maps/sion/tiles/col_0_5.bin new file mode 100644 index 0000000..8080b0a Binary files /dev/null and b/assets/maps/sion/tiles/col_0_5.bin differ diff --git a/assets/maps/sion/tiles/col_1_0.bin b/assets/maps/sion/tiles/col_1_0.bin new file mode 100644 index 0000000..4b13a18 Binary files /dev/null and b/assets/maps/sion/tiles/col_1_0.bin differ diff --git a/assets/maps/sion/tiles/col_1_1.bin b/assets/maps/sion/tiles/col_1_1.bin new file mode 100644 index 0000000..5ca3724 Binary files /dev/null and b/assets/maps/sion/tiles/col_1_1.bin differ diff --git a/assets/maps/sion/tiles/col_1_2.bin b/assets/maps/sion/tiles/col_1_2.bin new file mode 100644 index 0000000..b9f0931 Binary files /dev/null and b/assets/maps/sion/tiles/col_1_2.bin differ diff --git a/assets/maps/sion/tiles/col_1_3.bin b/assets/maps/sion/tiles/col_1_3.bin new file mode 100644 index 0000000..43ec020 Binary files /dev/null and b/assets/maps/sion/tiles/col_1_3.bin differ diff --git a/assets/maps/sion/tiles/col_1_4.bin b/assets/maps/sion/tiles/col_1_4.bin new file mode 100644 index 0000000..1d75f14 Binary files /dev/null and b/assets/maps/sion/tiles/col_1_4.bin differ diff --git a/assets/maps/sion/tiles/col_1_5.bin b/assets/maps/sion/tiles/col_1_5.bin new file mode 100644 index 0000000..2437d62 Binary files /dev/null and b/assets/maps/sion/tiles/col_1_5.bin differ diff --git a/assets/maps/sion/tiles/col_2_0.bin b/assets/maps/sion/tiles/col_2_0.bin new file mode 100644 index 0000000..f331bbc Binary files /dev/null and b/assets/maps/sion/tiles/col_2_0.bin differ diff --git a/assets/maps/sion/tiles/col_2_1.bin b/assets/maps/sion/tiles/col_2_1.bin new file mode 100644 index 0000000..c4d4767 Binary files /dev/null and b/assets/maps/sion/tiles/col_2_1.bin differ diff --git a/assets/maps/sion/tiles/col_2_2.bin b/assets/maps/sion/tiles/col_2_2.bin new file mode 100644 index 0000000..f36f928 Binary files /dev/null and b/assets/maps/sion/tiles/col_2_2.bin differ diff --git a/assets/maps/sion/tiles/col_2_3.bin b/assets/maps/sion/tiles/col_2_3.bin new file mode 100644 index 0000000..163e14e Binary files /dev/null and b/assets/maps/sion/tiles/col_2_3.bin differ diff --git a/assets/maps/sion/tiles/col_2_4.bin b/assets/maps/sion/tiles/col_2_4.bin new file mode 100644 index 0000000..84f06ee Binary files /dev/null and b/assets/maps/sion/tiles/col_2_4.bin differ diff --git a/assets/maps/sion/tiles/col_2_5.bin b/assets/maps/sion/tiles/col_2_5.bin new file mode 100644 index 0000000..608f243 Binary files /dev/null and b/assets/maps/sion/tiles/col_2_5.bin differ diff --git a/assets/maps/sion/tiles/col_3_0.bin b/assets/maps/sion/tiles/col_3_0.bin new file mode 100644 index 0000000..1fb3546 Binary files /dev/null and b/assets/maps/sion/tiles/col_3_0.bin differ diff --git a/assets/maps/sion/tiles/col_3_1.bin b/assets/maps/sion/tiles/col_3_1.bin new file mode 100644 index 0000000..71581c1 Binary files /dev/null and b/assets/maps/sion/tiles/col_3_1.bin differ diff --git a/assets/maps/sion/tiles/col_3_2.bin b/assets/maps/sion/tiles/col_3_2.bin new file mode 100644 index 0000000..deaa8ea Binary files /dev/null and b/assets/maps/sion/tiles/col_3_2.bin differ diff --git a/assets/maps/sion/tiles/col_3_3.bin b/assets/maps/sion/tiles/col_3_3.bin new file mode 100644 index 0000000..7c5248e Binary files /dev/null and b/assets/maps/sion/tiles/col_3_3.bin differ diff --git a/assets/maps/sion/tiles/col_3_4.bin b/assets/maps/sion/tiles/col_3_4.bin new file mode 100644 index 0000000..6804ab4 Binary files /dev/null and b/assets/maps/sion/tiles/col_3_4.bin differ diff --git a/assets/maps/sion/tiles/col_3_5.bin b/assets/maps/sion/tiles/col_3_5.bin new file mode 100644 index 0000000..f7b4a53 Binary files /dev/null and b/assets/maps/sion/tiles/col_3_5.bin differ diff --git a/assets/maps/sion/tiles/col_4_0.bin b/assets/maps/sion/tiles/col_4_0.bin new file mode 100644 index 0000000..8a1aae3 Binary files /dev/null and b/assets/maps/sion/tiles/col_4_0.bin differ diff --git a/assets/maps/sion/tiles/col_4_1.bin b/assets/maps/sion/tiles/col_4_1.bin new file mode 100644 index 0000000..7343251 Binary files /dev/null and b/assets/maps/sion/tiles/col_4_1.bin differ diff --git a/assets/maps/sion/tiles/col_4_2.bin b/assets/maps/sion/tiles/col_4_2.bin new file mode 100644 index 0000000..36aabf3 Binary files /dev/null and b/assets/maps/sion/tiles/col_4_2.bin differ diff --git a/assets/maps/sion/tiles/col_4_3.bin b/assets/maps/sion/tiles/col_4_3.bin new file mode 100644 index 0000000..4a42dd2 Binary files /dev/null and b/assets/maps/sion/tiles/col_4_3.bin differ diff --git a/assets/maps/sion/tiles/col_4_4.bin b/assets/maps/sion/tiles/col_4_4.bin new file mode 100644 index 0000000..626d86a Binary files /dev/null and b/assets/maps/sion/tiles/col_4_4.bin differ diff --git a/assets/maps/sion/tiles/col_4_5.bin b/assets/maps/sion/tiles/col_4_5.bin new file mode 100644 index 0000000..f83b2d3 Binary files /dev/null and b/assets/maps/sion/tiles/col_4_5.bin differ diff --git a/assets/maps/sion/tiles/col_5_0.bin b/assets/maps/sion/tiles/col_5_0.bin new file mode 100644 index 0000000..aa68fe1 Binary files /dev/null and b/assets/maps/sion/tiles/col_5_0.bin differ diff --git a/assets/maps/sion/tiles/col_5_1.bin b/assets/maps/sion/tiles/col_5_1.bin new file mode 100644 index 0000000..1de0ff7 Binary files /dev/null and b/assets/maps/sion/tiles/col_5_1.bin differ diff --git a/assets/maps/sion/tiles/col_5_2.bin b/assets/maps/sion/tiles/col_5_2.bin new file mode 100644 index 0000000..b684c5c Binary files /dev/null and b/assets/maps/sion/tiles/col_5_2.bin differ diff --git a/assets/maps/sion/tiles/col_5_3.bin b/assets/maps/sion/tiles/col_5_3.bin new file mode 100644 index 0000000..82b2c17 Binary files /dev/null and b/assets/maps/sion/tiles/col_5_3.bin differ diff --git a/assets/maps/sion/tiles/col_5_4.bin b/assets/maps/sion/tiles/col_5_4.bin new file mode 100644 index 0000000..f63023c Binary files /dev/null and b/assets/maps/sion/tiles/col_5_4.bin differ diff --git a/assets/maps/sion/tiles/col_5_5.bin b/assets/maps/sion/tiles/col_5_5.bin new file mode 100644 index 0000000..a7996e5 Binary files /dev/null and b/assets/maps/sion/tiles/col_5_5.bin differ diff --git a/assets/maps/sion/tiles/lod1_0_0.glb b/assets/maps/sion/tiles/lod1_0_0.glb new file mode 100644 index 0000000..2a69056 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_0_0.glb differ diff --git a/assets/maps/sion/tiles/lod1_0_1.glb b/assets/maps/sion/tiles/lod1_0_1.glb new file mode 100644 index 0000000..02cf0cf Binary files /dev/null and b/assets/maps/sion/tiles/lod1_0_1.glb differ diff --git a/assets/maps/sion/tiles/lod1_0_2.glb b/assets/maps/sion/tiles/lod1_0_2.glb new file mode 100644 index 0000000..7aec268 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_0_2.glb differ diff --git a/assets/maps/sion/tiles/lod1_0_3.glb b/assets/maps/sion/tiles/lod1_0_3.glb new file mode 100644 index 0000000..889deb8 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_0_3.glb differ diff --git a/assets/maps/sion/tiles/lod1_0_4.glb b/assets/maps/sion/tiles/lod1_0_4.glb new file mode 100644 index 0000000..811c681 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_0_4.glb differ diff --git a/assets/maps/sion/tiles/lod1_0_5.glb b/assets/maps/sion/tiles/lod1_0_5.glb new file mode 100644 index 0000000..d27d9ec Binary files /dev/null and b/assets/maps/sion/tiles/lod1_0_5.glb differ diff --git a/assets/maps/sion/tiles/lod1_1_0.glb b/assets/maps/sion/tiles/lod1_1_0.glb new file mode 100644 index 0000000..331c745 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_1_0.glb differ diff --git a/assets/maps/sion/tiles/lod1_1_1.glb b/assets/maps/sion/tiles/lod1_1_1.glb new file mode 100644 index 0000000..bad21f7 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_1_1.glb differ diff --git a/assets/maps/sion/tiles/lod1_1_2.glb b/assets/maps/sion/tiles/lod1_1_2.glb new file mode 100644 index 0000000..ce23413 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_1_2.glb differ diff --git a/assets/maps/sion/tiles/lod1_1_3.glb b/assets/maps/sion/tiles/lod1_1_3.glb new file mode 100644 index 0000000..68d2774 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_1_3.glb differ diff --git a/assets/maps/sion/tiles/lod1_1_4.glb b/assets/maps/sion/tiles/lod1_1_4.glb new file mode 100644 index 0000000..79815fd Binary files /dev/null and b/assets/maps/sion/tiles/lod1_1_4.glb differ diff --git a/assets/maps/sion/tiles/lod1_1_5.glb b/assets/maps/sion/tiles/lod1_1_5.glb new file mode 100644 index 0000000..b1d082c Binary files /dev/null and b/assets/maps/sion/tiles/lod1_1_5.glb differ diff --git a/assets/maps/sion/tiles/lod1_2_0.glb b/assets/maps/sion/tiles/lod1_2_0.glb new file mode 100644 index 0000000..cabd681 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_2_0.glb differ diff --git a/assets/maps/sion/tiles/lod1_2_1.glb b/assets/maps/sion/tiles/lod1_2_1.glb new file mode 100644 index 0000000..ca1ed6d Binary files /dev/null and b/assets/maps/sion/tiles/lod1_2_1.glb differ diff --git a/assets/maps/sion/tiles/lod1_2_2.glb b/assets/maps/sion/tiles/lod1_2_2.glb new file mode 100644 index 0000000..042db7c Binary files /dev/null and b/assets/maps/sion/tiles/lod1_2_2.glb differ diff --git a/assets/maps/sion/tiles/lod1_2_3.glb b/assets/maps/sion/tiles/lod1_2_3.glb new file mode 100644 index 0000000..acce327 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_2_3.glb differ diff --git a/assets/maps/sion/tiles/lod1_2_4.glb b/assets/maps/sion/tiles/lod1_2_4.glb new file mode 100644 index 0000000..680e1e2 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_2_4.glb differ diff --git a/assets/maps/sion/tiles/lod1_2_5.glb b/assets/maps/sion/tiles/lod1_2_5.glb new file mode 100644 index 0000000..bd12150 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_2_5.glb differ diff --git a/assets/maps/sion/tiles/lod1_3_0.glb b/assets/maps/sion/tiles/lod1_3_0.glb new file mode 100644 index 0000000..f51e062 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_3_0.glb differ diff --git a/assets/maps/sion/tiles/lod1_3_1.glb b/assets/maps/sion/tiles/lod1_3_1.glb new file mode 100644 index 0000000..dd59248 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_3_1.glb differ diff --git a/assets/maps/sion/tiles/lod1_3_2.glb b/assets/maps/sion/tiles/lod1_3_2.glb new file mode 100644 index 0000000..b8e6407 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_3_2.glb differ diff --git a/assets/maps/sion/tiles/lod1_3_3.glb b/assets/maps/sion/tiles/lod1_3_3.glb new file mode 100644 index 0000000..aa4898e Binary files /dev/null and b/assets/maps/sion/tiles/lod1_3_3.glb differ diff --git a/assets/maps/sion/tiles/lod1_3_4.glb b/assets/maps/sion/tiles/lod1_3_4.glb new file mode 100644 index 0000000..ccd6102 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_3_4.glb differ diff --git a/assets/maps/sion/tiles/lod1_3_5.glb b/assets/maps/sion/tiles/lod1_3_5.glb new file mode 100644 index 0000000..b26af8c Binary files /dev/null and b/assets/maps/sion/tiles/lod1_3_5.glb differ diff --git a/assets/maps/sion/tiles/lod1_4_0.glb b/assets/maps/sion/tiles/lod1_4_0.glb new file mode 100644 index 0000000..cf26d11 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_4_0.glb differ diff --git a/assets/maps/sion/tiles/lod1_4_1.glb b/assets/maps/sion/tiles/lod1_4_1.glb new file mode 100644 index 0000000..fe68920 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_4_1.glb differ diff --git a/assets/maps/sion/tiles/lod1_4_2.glb b/assets/maps/sion/tiles/lod1_4_2.glb new file mode 100644 index 0000000..66c89ef Binary files /dev/null and b/assets/maps/sion/tiles/lod1_4_2.glb differ diff --git a/assets/maps/sion/tiles/lod1_4_3.glb b/assets/maps/sion/tiles/lod1_4_3.glb new file mode 100644 index 0000000..2afb855 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_4_3.glb differ diff --git a/assets/maps/sion/tiles/lod1_4_4.glb b/assets/maps/sion/tiles/lod1_4_4.glb new file mode 100644 index 0000000..da0c1d0 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_4_4.glb differ diff --git a/assets/maps/sion/tiles/lod1_4_5.glb b/assets/maps/sion/tiles/lod1_4_5.glb new file mode 100644 index 0000000..07f85d1 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_4_5.glb differ diff --git a/assets/maps/sion/tiles/lod1_5_0.glb b/assets/maps/sion/tiles/lod1_5_0.glb new file mode 100644 index 0000000..7c1d792 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_5_0.glb differ diff --git a/assets/maps/sion/tiles/lod1_5_1.glb b/assets/maps/sion/tiles/lod1_5_1.glb new file mode 100644 index 0000000..f759198 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_5_1.glb differ diff --git a/assets/maps/sion/tiles/lod1_5_2.glb b/assets/maps/sion/tiles/lod1_5_2.glb new file mode 100644 index 0000000..061b8ee Binary files /dev/null and b/assets/maps/sion/tiles/lod1_5_2.glb differ diff --git a/assets/maps/sion/tiles/lod1_5_3.glb b/assets/maps/sion/tiles/lod1_5_3.glb new file mode 100644 index 0000000..5b03a11 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_5_3.glb differ diff --git a/assets/maps/sion/tiles/lod1_5_4.glb b/assets/maps/sion/tiles/lod1_5_4.glb new file mode 100644 index 0000000..4392f0a Binary files /dev/null and b/assets/maps/sion/tiles/lod1_5_4.glb differ diff --git a/assets/maps/sion/tiles/lod1_5_5.glb b/assets/maps/sion/tiles/lod1_5_5.glb new file mode 100644 index 0000000..d8d7c98 Binary files /dev/null and b/assets/maps/sion/tiles/lod1_5_5.glb differ diff --git a/assets/maps/sion/tiles/lod2_0_0.glb b/assets/maps/sion/tiles/lod2_0_0.glb new file mode 100644 index 0000000..6e74f63 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_0_0.glb differ diff --git a/assets/maps/sion/tiles/lod2_0_1.glb b/assets/maps/sion/tiles/lod2_0_1.glb new file mode 100644 index 0000000..c340cd7 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_0_1.glb differ diff --git a/assets/maps/sion/tiles/lod2_0_2.glb b/assets/maps/sion/tiles/lod2_0_2.glb new file mode 100644 index 0000000..e321d54 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_0_2.glb differ diff --git a/assets/maps/sion/tiles/lod2_0_3.glb b/assets/maps/sion/tiles/lod2_0_3.glb new file mode 100644 index 0000000..5fa8a3f Binary files /dev/null and b/assets/maps/sion/tiles/lod2_0_3.glb differ diff --git a/assets/maps/sion/tiles/lod2_0_4.glb b/assets/maps/sion/tiles/lod2_0_4.glb new file mode 100644 index 0000000..dc74855 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_0_4.glb differ diff --git a/assets/maps/sion/tiles/lod2_0_5.glb b/assets/maps/sion/tiles/lod2_0_5.glb new file mode 100644 index 0000000..792a4b5 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_0_5.glb differ diff --git a/assets/maps/sion/tiles/lod2_1_0.glb b/assets/maps/sion/tiles/lod2_1_0.glb new file mode 100644 index 0000000..7d34192 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_1_0.glb differ diff --git a/assets/maps/sion/tiles/lod2_1_1.glb b/assets/maps/sion/tiles/lod2_1_1.glb new file mode 100644 index 0000000..2ac70fa Binary files /dev/null and b/assets/maps/sion/tiles/lod2_1_1.glb differ diff --git a/assets/maps/sion/tiles/lod2_1_2.glb b/assets/maps/sion/tiles/lod2_1_2.glb new file mode 100644 index 0000000..712aa0e Binary files /dev/null and b/assets/maps/sion/tiles/lod2_1_2.glb differ diff --git a/assets/maps/sion/tiles/lod2_1_3.glb b/assets/maps/sion/tiles/lod2_1_3.glb new file mode 100644 index 0000000..2a11380 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_1_3.glb differ diff --git a/assets/maps/sion/tiles/lod2_1_4.glb b/assets/maps/sion/tiles/lod2_1_4.glb new file mode 100644 index 0000000..97fa611 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_1_4.glb differ diff --git a/assets/maps/sion/tiles/lod2_1_5.glb b/assets/maps/sion/tiles/lod2_1_5.glb new file mode 100644 index 0000000..1e98452 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_1_5.glb differ diff --git a/assets/maps/sion/tiles/lod2_2_0.glb b/assets/maps/sion/tiles/lod2_2_0.glb new file mode 100644 index 0000000..f2b0170 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_2_0.glb differ diff --git a/assets/maps/sion/tiles/lod2_2_1.glb b/assets/maps/sion/tiles/lod2_2_1.glb new file mode 100644 index 0000000..573e972 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_2_1.glb differ diff --git a/assets/maps/sion/tiles/lod2_2_2.glb b/assets/maps/sion/tiles/lod2_2_2.glb new file mode 100644 index 0000000..ee86ac0 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_2_2.glb differ diff --git a/assets/maps/sion/tiles/lod2_2_3.glb b/assets/maps/sion/tiles/lod2_2_3.glb new file mode 100644 index 0000000..a164434 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_2_3.glb differ diff --git a/assets/maps/sion/tiles/lod2_2_4.glb b/assets/maps/sion/tiles/lod2_2_4.glb new file mode 100644 index 0000000..08a8fb6 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_2_4.glb differ diff --git a/assets/maps/sion/tiles/lod2_2_5.glb b/assets/maps/sion/tiles/lod2_2_5.glb new file mode 100644 index 0000000..743d184 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_2_5.glb differ diff --git a/assets/maps/sion/tiles/lod2_3_0.glb b/assets/maps/sion/tiles/lod2_3_0.glb new file mode 100644 index 0000000..48ba85e Binary files /dev/null and b/assets/maps/sion/tiles/lod2_3_0.glb differ diff --git a/assets/maps/sion/tiles/lod2_3_1.glb b/assets/maps/sion/tiles/lod2_3_1.glb new file mode 100644 index 0000000..bb2464e Binary files /dev/null and b/assets/maps/sion/tiles/lod2_3_1.glb differ diff --git a/assets/maps/sion/tiles/lod2_3_2.glb b/assets/maps/sion/tiles/lod2_3_2.glb new file mode 100644 index 0000000..bc9d01b Binary files /dev/null and b/assets/maps/sion/tiles/lod2_3_2.glb differ diff --git a/assets/maps/sion/tiles/lod2_3_3.glb b/assets/maps/sion/tiles/lod2_3_3.glb new file mode 100644 index 0000000..110a43c Binary files /dev/null and b/assets/maps/sion/tiles/lod2_3_3.glb differ diff --git a/assets/maps/sion/tiles/lod2_3_4.glb b/assets/maps/sion/tiles/lod2_3_4.glb new file mode 100644 index 0000000..192472d Binary files /dev/null and b/assets/maps/sion/tiles/lod2_3_4.glb differ diff --git a/assets/maps/sion/tiles/lod2_3_5.glb b/assets/maps/sion/tiles/lod2_3_5.glb new file mode 100644 index 0000000..630d67e Binary files /dev/null and b/assets/maps/sion/tiles/lod2_3_5.glb differ diff --git a/assets/maps/sion/tiles/lod2_4_0.glb b/assets/maps/sion/tiles/lod2_4_0.glb new file mode 100644 index 0000000..d9e8895 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_4_0.glb differ diff --git a/assets/maps/sion/tiles/lod2_4_1.glb b/assets/maps/sion/tiles/lod2_4_1.glb new file mode 100644 index 0000000..538fa53 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_4_1.glb differ diff --git a/assets/maps/sion/tiles/lod2_4_2.glb b/assets/maps/sion/tiles/lod2_4_2.glb new file mode 100644 index 0000000..5d7c947 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_4_2.glb differ diff --git a/assets/maps/sion/tiles/lod2_4_3.glb b/assets/maps/sion/tiles/lod2_4_3.glb new file mode 100644 index 0000000..0ba74f0 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_4_3.glb differ diff --git a/assets/maps/sion/tiles/lod2_4_4.glb b/assets/maps/sion/tiles/lod2_4_4.glb new file mode 100644 index 0000000..86c207a Binary files /dev/null and b/assets/maps/sion/tiles/lod2_4_4.glb differ diff --git a/assets/maps/sion/tiles/lod2_4_5.glb b/assets/maps/sion/tiles/lod2_4_5.glb new file mode 100644 index 0000000..a5bd499 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_4_5.glb differ diff --git a/assets/maps/sion/tiles/lod2_5_0.glb b/assets/maps/sion/tiles/lod2_5_0.glb new file mode 100644 index 0000000..4c63395 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_5_0.glb differ diff --git a/assets/maps/sion/tiles/lod2_5_1.glb b/assets/maps/sion/tiles/lod2_5_1.glb new file mode 100644 index 0000000..5a1e7e9 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_5_1.glb differ diff --git a/assets/maps/sion/tiles/lod2_5_2.glb b/assets/maps/sion/tiles/lod2_5_2.glb new file mode 100644 index 0000000..50661d1 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_5_2.glb differ diff --git a/assets/maps/sion/tiles/lod2_5_3.glb b/assets/maps/sion/tiles/lod2_5_3.glb new file mode 100644 index 0000000..333ed5c Binary files /dev/null and b/assets/maps/sion/tiles/lod2_5_3.glb differ diff --git a/assets/maps/sion/tiles/lod2_5_4.glb b/assets/maps/sion/tiles/lod2_5_4.glb new file mode 100644 index 0000000..27f75c9 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_5_4.glb differ diff --git a/assets/maps/sion/tiles/lod2_5_5.glb b/assets/maps/sion/tiles/lod2_5_5.glb new file mode 100644 index 0000000..e842870 Binary files /dev/null and b/assets/maps/sion/tiles/lod2_5_5.glb differ diff --git a/assets/vehicles/anvil/anvil.glb b/assets/vehicles/anvil/anvil.glb new file mode 100644 index 0000000..25b367c Binary files /dev/null and b/assets/vehicles/anvil/anvil.glb differ diff --git a/assets/vehicles/anvil/manifest.json b/assets/vehicles/anvil/manifest.json new file mode 100644 index 0000000..ca8cff5 --- /dev/null +++ b/assets/vehicles/anvil/manifest.json @@ -0,0 +1,154 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "anvil", + "name": "Anvil", + "class": "Heavy Quad-Track Siege Tank", + "plane": "Dorsal", + "gridWidth": 5, + "gridHeight": 6, + "mask": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "hardpoints": [ + { + "id": "hp.armor.front", + "kind": "armor", + "x": 0, + "y": 0, + "w": 5, + "h": 1, + "modelNodeId": "hp.armor.front" + }, + { + "id": "hp.weapon.sponson_l", + "kind": "weapon", + "x": 0, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.sponson_l" + }, + { + "id": "hp.weapon.siege_l", + "kind": "weapon", + "x": 1, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.siege_l" + }, + { + "id": "hp.armor.sides", + "kind": "armor", + "x": 2, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.armor.sides" + }, + { + "id": "hp.weapon.siege_r", + "kind": "weapon", + "x": 3, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.siege_r" + }, + { + "id": "hp.weapon.sponson_r", + "kind": "weapon", + "x": 4, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.sponson_r" + }, + { + "id": "hp.engine.rear", + "kind": "engine", + "x": 1, + "y": 3, + "w": 3, + "h": 2, + "modelNodeId": "hp.engine.rear" + }, + { + "id": "hp.radiator.l", + "kind": "radiator", + "x": 0, + "y": 4, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.l" + }, + { + "id": "hp.radiator.r", + "kind": "radiator", + "x": 4, + "y": 4, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.r" + } + ], + "joints": [ + { + "id": "joint.turret_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -180.0, + "max": 180.0 + } + ], + "bounds": { + "min": [ + -1.93, + 0.0, + -2.8252 + ], + "max": [ + 1.93, + 3.0266, + 2.8252 + ], + "size": [ + 3.86, + 3.0266, + 5.6504 + ] + }, + "triCount": 18044 +} diff --git a/assets/vehicles/anvil/vehicle.cc b/assets/vehicles/anvil/vehicle.cc new file mode 100644 index 0000000..1e82918 Binary files /dev/null and b/assets/vehicles/anvil/vehicle.cc differ diff --git a/assets/vehicles/bastion/bastion.glb b/assets/vehicles/bastion/bastion.glb new file mode 100644 index 0000000..0711977 Binary files /dev/null and b/assets/vehicles/bastion/bastion.glb differ diff --git a/assets/vehicles/bastion/manifest.json b/assets/vehicles/bastion/manifest.json new file mode 100644 index 0000000..43f8d8a --- /dev/null +++ b/assets/vehicles/bastion/manifest.json @@ -0,0 +1,151 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "bastion", + "name": "Bastion", + "class": "Heavy Siege Quadruped", + "plane": "Dorsal", + "gridWidth": 6, + "gridHeight": 6, + "mask": [ + false, + false, + true, + true, + false, + false, + false, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + false, + false, + true, + false, + false, + true, + false + ], + "hardpoints": [ + { + "id": "hp.armor.prow", + "kind": "armor", + "x": 2, + "y": 0, + "w": 2, + "h": 1, + "modelNodeId": "hp.armor.prow" + }, + { + "id": "hp.weapon.turret_pd", + "kind": "weapon", + "x": 1, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.turret_pd" + }, + { + "id": "hp.weapon.turret_main", + "kind": "weapon", + "x": 2, + "y": 1, + "w": 2, + "h": 2, + "modelNodeId": "hp.weapon.turret_main" + }, + { + "id": "hp.weapon.flank_l", + "kind": "weapon", + "x": 0, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.flank_l" + }, + { + "id": "hp.weapon.flank_r", + "kind": "weapon", + "x": 5, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.flank_r" + }, + { + "id": "hp.engine.core", + "kind": "engine", + "x": 2, + "y": 3, + "w": 2, + "h": 2, + "modelNodeId": "hp.engine.core" + }, + { + "id": "hp.radiator.rear_l", + "kind": "radiator", + "x": 1, + "y": 4, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.rear_l" + }, + { + "id": "hp.radiator.rear_r", + "kind": "radiator", + "x": 4, + "y": 4, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.rear_r" + } + ], + "joints": [ + { + "id": "joint.turret_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -180.0, + "max": 180.0 + } + ], + "bounds": { + "min": [ + -6.6043, + 0.0, + -8.043 + ], + "max": [ + 6.6094, + 9.625, + 6.7519 + ], + "size": [ + 13.2137, + 9.625, + 14.7949 + ] + }, + "triCount": 36656 +} diff --git a/assets/vehicles/bastion/vehicle.cc b/assets/vehicles/bastion/vehicle.cc new file mode 100644 index 0000000..db90253 Binary files /dev/null and b/assets/vehicles/bastion/vehicle.cc differ diff --git a/assets/vehicles/breaker/breaker.glb b/assets/vehicles/breaker/breaker.glb new file mode 100644 index 0000000..510d874 Binary files /dev/null and b/assets/vehicles/breaker/breaker.glb differ diff --git a/assets/vehicles/breaker/manifest.json b/assets/vehicles/breaker/manifest.json new file mode 100644 index 0000000..0d7d940 --- /dev/null +++ b/assets/vehicles/breaker/manifest.json @@ -0,0 +1,1084 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "breaker", + "name": "Breaker", + "class": "Heavy Assault Biped", + "plane": "Coronal", + "gridWidth": 5, + "gridHeight": 6, + "mask": [ + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + false, + true, + false, + false, + true, + false, + true, + false + ], + "hardpoints": [ + { + "id": "hp.weapon.arm_l", + "kind": "weapon", + "x": 0, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_l" + }, + { + "id": "hp.weapon.arm_r", + "kind": "weapon", + "x": 4, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_r" + }, + { + "id": "hp.weapon.shoulder_l", + "kind": "weapon", + "x": 1, + "y": 0, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.shoulder_l" + }, + { + "id": "hp.armor.torso", + "kind": "armor", + "x": 2, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.armor.torso" + }, + { + "id": "hp.engine.chest", + "kind": "engine", + "x": 2, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.chest" + }, + { + "id": "hp.radiator.back_l", + "kind": "radiator", + "x": 1, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back_l" + }, + { + "id": "hp.radiator.back_r", + "kind": "radiator", + "x": 3, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back_r" + } + ], + "joints": [ + { + "id": "joint.torso_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -90.0, + "max": 90.0 + }, + { + "id": "joint.arm_l_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 60.0 + }, + { + "id": "joint.arm_r_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 60.0 + } + ], + "bounds": { + "min": [ + -2.3356, + -0.0, + -1.274 + ], + "max": [ + 2.3808, + 6.2911, + 1.8859 + ], + "size": [ + 4.7164, + 6.2911, + 3.1599 + ] + }, + "triCount": 35967, + "mechanisms": { + "frame": "gltf (+Y up, +Z forward, +X left, meters)", + "rootOrigin": [ + -0.0, + 3.362557, + 0.0 + ], + "dofs": [ + { + "name": "LegL.Hip", + "parent": -1, + "kind": "slew", + "mechanism": "hip", + "side": "L", + "origin": [ + 0.6209, + 3.362557, + 0.0 + ], + "axis": [ + 1.0, + -0.0, + 0.0 + ], + "lo": -1.0471975511965976, + "hi": 1.0471975511965976, + "depth": 0 + }, + { + "name": "LegL.Thigh", + "parent": 0, + "kind": "slew", + "mechanism": "hip yaw", + "side": "L", + "origin": [ + 1.0809, + 2.71148, + 0.173509 + ], + "axis": [ + -0.0, + -0.966276, + 0.257508 + ], + "lo": -0.6108652381980153, + "hi": 0.6108652381980153, + "depth": 1 + }, + { + "name": "LegL.Shin", + "parent": 1, + "kind": "hinge", + "mechanism": "knee", + "side": "L", + "origin": [ + 1.0809, + 2.086744, + 0.339999 + ], + "axis": [ + -0.0, + -0.970991, + -0.239116 + ], + "lo": -1.7453292519943295, + "hi": 1.7453292519943295, + "depth": 2 + }, + { + "name": "LegL.Oleo", + "parent": 2, + "kind": "slide", + "mechanism": "oleo", + "side": "L", + "origin": [ + 1.0809, + 1.021033, + 0.077557 + ], + "axis": [ + -0.0, + -0.970991, + -0.239116 + ], + "lo": -0.2, + "hi": 0.0, + "depth": 3, + "compliance": { + "damping_ratio": 0.45, + "hertz": 1.6 + } + }, + { + "name": "LegL.Foot", + "parent": 3, + "kind": "hinge", + "mechanism": "ankle", + "side": "L", + "origin": [ + 1.0809, + 0.624869, + -0.020002 + ], + "axis": [ + -0.0, + -1.0, + 0.0 + ], + "lo": -0.6981317007977318, + "hi": 0.6981317007977318, + "depth": 4, + "stopped_by": "ram" + }, + { + "name": "LegL.Foot.Toe0.Seg0", + "parent": 4, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 0.753334, + 0.252079, + 0.237904 + ], + "axis": [ + -0.08495, + -0.223571, + 0.970979 + ], + "lo": -0.1745329183221527, + "hi": 0.5235987824755791, + "depth": 5 + }, + { + "name": "LegL.Foot.Toe0.Seg1", + "parent": 5, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 0.719354, + 0.162651, + 0.626296 + ], + "axis": [ + -0.087156, + 0.0, + 0.996195 + ], + "lo": -0.2094395171165998, + "hi": 0.8377580340799979, + "depth": 6 + }, + { + "name": "LegL.Foot.Toe1.Seg0", + "parent": 4, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 1.408466, + 0.252079, + 0.237904 + ], + "axis": [ + 0.08495, + -0.223571, + 0.970979 + ], + "lo": -0.1745329183221527, + "hi": 0.5235987824755791, + "depth": 5 + }, + { + "name": "LegL.Foot.Toe1.Seg1", + "parent": 7, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 1.442446, + 0.162651, + 0.626296 + ], + "axis": [ + 0.087156, + 0.0, + 0.996195 + ], + "lo": -0.2094395171165998, + "hi": 0.8377580340799979, + "depth": 6 + }, + { + "name": "LegL.Foot.Toe2.Seg0", + "parent": 4, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 0.353393, + 0.252079, + 0.057444 + ], + "axis": [ + -0.58406, + -0.316267, + 0.747562 + ], + "lo": -0.17453293312755827, + "hi": 0.5235987676701735, + "depth": 5 + }, + { + "name": "LegL.Foot.Toe3.Seg0", + "parent": 4, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 1.808407, + 0.252079, + 0.057444 + ], + "axis": [ + 0.58406, + -0.316267, + 0.747562 + ], + "lo": -0.17453293312755827, + "hi": 0.5235987676701735, + "depth": 5 + }, + { + "name": "LegL.Foot.Toe4.Seg0", + "parent": 4, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 0.694624, + 0.252079, + -0.387362 + ], + "axis": [ + -0.225859, + -0.358307, + -0.905872 + ], + "lo": -0.20943950039479836, + "hi": 0.4188790303231602, + "depth": 5 + }, + { + "name": "LegL.Foot.Toe5.Seg0", + "parent": 4, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 1.467176, + 0.252079, + -0.387362 + ], + "axis": [ + 0.225859, + -0.358307, + -0.905872 + ], + "lo": -0.20943950039479836, + "hi": 0.4188790303231602, + "depth": 5 + }, + { + "name": "LegR.Hip", + "parent": -1, + "kind": "slew", + "mechanism": "hip", + "side": "R", + "origin": [ + -0.6209, + 3.362557, + 0.0 + ], + "axis": [ + -1.0, + -0.0, + -0.0 + ], + "lo": -1.0471975511965976, + "hi": 1.0471975511965976, + "depth": 0 + }, + { + "name": "LegR.Thigh", + "parent": 13, + "kind": "slew", + "mechanism": "hip yaw", + "side": "R", + "origin": [ + -1.0809, + 2.690817, + 0.052652 + ], + "axis": [ + 0.0, + -0.996942, + 0.078142 + ], + "lo": -0.6108652381980153, + "hi": 0.6108652381980153, + "depth": 1 + }, + { + "name": "LegR.Shin", + "parent": 14, + "kind": "hinge", + "mechanism": "knee", + "side": "R", + "origin": [ + -1.0809, + 2.046254, + 0.103173 + ], + "axis": [ + 0.0, + -0.944097, + -0.329667 + ], + "lo": -1.7453292519943295, + "hi": 1.7453292519943295, + "depth": 2 + }, + { + "name": "LegR.Oleo", + "parent": 15, + "kind": "slide", + "mechanism": "oleo", + "side": "R", + "origin": [ + -1.0809, + 1.01006, + -0.258652 + ], + "axis": [ + 0.0, + -0.944097, + -0.329667 + ], + "lo": -0.2, + "hi": 0.0, + "depth": 3, + "compliance": { + "damping_ratio": 0.45, + "hertz": 1.6 + } + }, + { + "name": "LegR.Foot", + "parent": 16, + "kind": "hinge", + "mechanism": "ankle", + "side": "R", + "origin": [ + -1.0809, + 0.624868, + -0.393156 + ], + "axis": [ + 0.0, + -1.0, + 0.0 + ], + "lo": -0.6981317007977318, + "hi": 0.6981317007977318, + "depth": 4, + "stopped_by": "ram" + }, + { + "name": "LegR.Foot.Toe0.Seg0", + "parent": 17, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -1.408466, + 0.252079, + -0.13525 + ], + "axis": [ + -0.08495, + -0.223571, + 0.970979 + ], + "lo": -0.1745329183221527, + "hi": 0.5235987824755791, + "depth": 5 + }, + { + "name": "LegR.Foot.Toe0.Seg1", + "parent": 18, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -1.442446, + 0.16265, + 0.253141 + ], + "axis": [ + -0.087156, + 0.0, + 0.996195 + ], + "lo": -0.2094395171165998, + "hi": 0.8377580340799979, + "depth": 6 + }, + { + "name": "LegR.Foot.Toe1.Seg0", + "parent": 17, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -0.753334, + 0.252079, + -0.135251 + ], + "axis": [ + 0.08495, + -0.223571, + 0.970979 + ], + "lo": -0.1745329183221527, + "hi": 0.5235987824755791, + "depth": 5 + }, + { + "name": "LegR.Foot.Toe1.Seg1", + "parent": 20, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -0.719354, + 0.16265, + 0.253141 + ], + "axis": [ + 0.087156, + 0.0, + 0.996195 + ], + "lo": -0.2094395171165998, + "hi": 0.8377580340799979, + "depth": 6 + }, + { + "name": "LegR.Foot.Toe2.Seg0", + "parent": 17, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -1.808407, + 0.252079, + -0.315711 + ], + "axis": [ + -0.58406, + -0.316267, + 0.747562 + ], + "lo": -0.17453293312755827, + "hi": 0.5235987676701735, + "depth": 5 + }, + { + "name": "LegR.Foot.Toe3.Seg0", + "parent": 17, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -0.353393, + 0.252079, + -0.315711 + ], + "axis": [ + 0.58406, + -0.316267, + 0.747562 + ], + "lo": -0.17453293312755827, + "hi": 0.5235987676701735, + "depth": 5 + }, + { + "name": "LegR.Foot.Toe4.Seg0", + "parent": 17, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -1.467176, + 0.252079, + -0.760517 + ], + "axis": [ + -0.225859, + -0.358307, + -0.905872 + ], + "lo": -0.20943950039479836, + "hi": 0.4188790303231602, + "depth": 5 + }, + { + "name": "LegR.Foot.Toe5.Seg0", + "parent": 17, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -0.694624, + 0.252079, + -0.760517 + ], + "axis": [ + 0.225859, + -0.358307, + -0.905872 + ], + "lo": -0.20943950039479836, + "hi": 0.4188790303231602, + "depth": 5 + }, + { + "name": "Core", + "parent": -1, + "kind": "slew", + "mechanism": "waist", + "side": "", + "origin": [ + -0.0, + 3.721381, + 0.0 + ], + "axis": [ + -0.0, + 1.0, + 0.0 + ], + "lo": -1.9198621771937625, + "hi": 1.9198621771937625, + "depth": 0 + }, + { + "name": "ShoulderYokeL", + "parent": 26, + "kind": "slew", + "mechanism": "shoulder slew", + "side": "L", + "origin": [ + 0.819255, + 4.983909, + 0.0 + ], + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "lo": -1.7453292519943295, + "hi": 1.7453292519943295, + "depth": 1 + }, + { + "name": "UpperArmL", + "parent": 27, + "kind": "hinge", + "mechanism": "shoulder hinge", + "side": "L", + "origin": [ + 1.488455, + 4.983909, + 0.0 + ], + "axis": [ + 0.087165, + -0.991212, + 0.0995 + ], + "lo": -0.7853981633974483, + "hi": 0.7853981633974483, + "depth": 2 + }, + { + "name": "ElbowYokeL", + "parent": 28, + "kind": "slew", + "mechanism": "arm twist", + "side": "L", + "origin": [ + 1.556551, + 4.209545, + 0.077732 + ], + "axis": [ + 0.087165, + -0.991212, + 0.0995 + ], + "lo": -1.5707963267948966, + "hi": 1.5707963267948966, + "depth": 3 + }, + { + "name": "ForearmL", + "parent": 29, + "kind": "hinge", + "mechanism": "elbow", + "side": "L", + "origin": [ + 1.601947, + 3.693322, + 0.129552 + ], + "axis": [ + 0.1199, + -0.441691, + 0.889119 + ], + "lo": -1.7453292519943295, + "hi": 1.7453292519943295, + "depth": 4 + }, + { + "name": "ShoulderYokeR", + "parent": 26, + "kind": "slew", + "mechanism": "shoulder slew", + "side": "R", + "origin": [ + -0.819255, + 4.983909, + 0.0 + ], + "axis": [ + -1.0, + -0.0, + -0.0 + ], + "lo": -1.7453292519943295, + "hi": 1.7453292519943295, + "depth": 1 + }, + { + "name": "UpperArmR", + "parent": 31, + "kind": "hinge", + "mechanism": "shoulder hinge", + "side": "R", + "origin": [ + -1.488455, + 4.983909, + -0.0 + ], + "axis": [ + -0.061315, + -0.978592, + 0.196466 + ], + "lo": -0.7853981633974483, + "hi": 0.7853981633974483, + "depth": 2 + }, + { + "name": "ElbowYokeR", + "parent": 32, + "kind": "slew", + "mechanism": "arm twist", + "side": "R", + "origin": [ + -1.536356, + 4.219404, + 0.153485 + ], + "axis": [ + -0.061315, + -0.978592, + 0.196466 + ], + "lo": -1.5707963267948966, + "hi": 1.5707963267948966, + "depth": 3 + }, + { + "name": "ForearmR", + "parent": 33, + "kind": "hinge", + "mechanism": "elbow", + "side": "R", + "origin": [ + -1.56829, + 3.709754, + 0.255804 + ], + "axis": [ + 0.03822, + -0.374104, + 0.926599 + ], + "lo": -1.7453292519943295, + "hi": 1.7453292519943295, + "depth": 4 + } + ], + "rams": [ + { + "name": "LegL.RecessRam0", + "barrel_bone": "LegL.RecessRam0.barrel", + "rod_bone": "LegL.RecessRam0.rod", + "spans": [ + "LegL.Oleo", + "LegL.Foot" + ], + "bore": 0.09, + "body": 0.664775, + "inner": 0.8131586697281079, + "extension": 0.407443, + "rest": 1.3782174197281079, + "stroke": [ + -0.407443, + 0.514775 + ], + "a_parent_dof": 2, + "a_pos": [ + 0.9109, + 2.117333, + -0.202422 + ], + "b_parent_dof": 4, + "b_pos": [ + 0.9109, + 0.745732, + -0.337304 + ], + "pin_dir": [ + 1.0, + -0.0, + -0.0 + ] + }, + { + "name": "LegL.RecessRam1", + "barrel_bone": "LegL.RecessRam1.barrel", + "rod_bone": "LegL.RecessRam1.rod", + "spans": [ + "LegL.Oleo", + "LegL.Foot" + ], + "bore": 0.09, + "body": 0.664775, + "inner": 0.8131586697281079, + "extension": 0.407443, + "rest": 1.3782174197281079, + "stroke": [ + -0.407443, + 0.514775 + ], + "a_parent_dof": 2, + "a_pos": [ + 1.2509, + 2.117333, + -0.202422 + ], + "b_parent_dof": 4, + "b_pos": [ + 1.2509, + 0.745732, + -0.337304 + ], + "pin_dir": [ + 1.0, + -0.0, + -0.0 + ] + }, + { + "name": "LegR.RecessRam0", + "barrel_bone": "LegR.RecessRam0.barrel", + "rod_bone": "LegR.RecessRam0.rod", + "spans": [ + "LegR.Oleo", + "LegR.Foot" + ], + "bore": 0.09, + "body": 0.684197, + "inner": 0.8279768098379127, + "extension": 0.419347, + "rest": 1.4095442598379126, + "stroke": [ + -0.419347, + 0.534197 + ], + "a_parent_dof": 15, + "a_pos": [ + -1.2509, + 2.127887, + -0.433941 + ], + "b_parent_dof": 17, + "b_pos": [ + -1.2509, + 0.745731, + -0.710458 + ], + "pin_dir": [ + 1.0, + 0.0, + -0.0 + ] + }, + { + "name": "LegR.RecessRam1", + "barrel_bone": "LegR.RecessRam1.barrel", + "rod_bone": "LegR.RecessRam1.rod", + "spans": [ + "LegR.Oleo", + "LegR.Foot" + ], + "bore": 0.09, + "body": 0.684197, + "inner": 0.8279768098379127, + "extension": 0.419347, + "rest": 1.4095442598379126, + "stroke": [ + -0.419347, + 0.534197 + ], + "a_parent_dof": 15, + "a_pos": [ + -0.9109, + 2.127887, + -0.433941 + ], + "b_parent_dof": 17, + "b_pos": [ + -0.9109, + 0.745731, + -0.710458 + ], + "pin_dir": [ + 1.0, + 0.0, + -0.0 + ] + } + ], + "scissors": [ + { + "name": "LegL.Torque", + "upper_bone": "LegL.Torque.upper", + "lower_bone": "LegL.Torque.lower", + "arm": 0.3087611656677239, + "a_parent_dof": 2, + "a_pos": [ + 1.0809, + 1.240598, + 0.44059 + ], + "b_parent_dof": 3, + "b_pos": [ + 1.0809, + 0.757042, + 0.32151 + ], + "out_dir": [ + 0.0, + -0.239116, + 0.970991 + ] + }, + { + "name": "LegR.Torque", + "upper_bone": "LegR.Torque.upper", + "lower_bone": "LegR.Torque.lower", + "arm": 0.30876125639651403, + "a_parent_dof": 15, + "a_pos": [ + -1.0809, + 1.194391, + 0.123477 + ], + "b_parent_dof": 16, + "b_pos": [ + -1.0809, + 0.724229, + -0.040697 + ], + "out_dir": [ + 0.0, + -0.329667, + 0.944097 + ] + } + ], + "struts": [ + { + "name": "LegL.Oleo", + "side": "L", + "dof": "LegL.Oleo", + "travel": 0.2, + "hertz": 1.6, + "damping_ratio": 0.45 + }, + { + "name": "LegR.Oleo", + "side": "R", + "dof": "LegR.Oleo", + "travel": 0.2, + "hertz": 1.6, + "damping_ratio": 0.45 + } + ] + } +} diff --git a/assets/vehicles/breaker/vehicle.cc b/assets/vehicles/breaker/vehicle.cc new file mode 100644 index 0000000..e6e6c58 Binary files /dev/null and b/assets/vehicles/breaker/vehicle.cc differ diff --git a/assets/vehicles/condor/condor.glb b/assets/vehicles/condor/condor.glb new file mode 100644 index 0000000..482c6cb Binary files /dev/null and b/assets/vehicles/condor/condor.glb differ diff --git a/assets/vehicles/condor/manifest.json b/assets/vehicles/condor/manifest.json new file mode 100644 index 0000000..8b056e5 --- /dev/null +++ b/assets/vehicles/condor/manifest.json @@ -0,0 +1,225 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "condor", + "name": "Condor", + "class": "Heavy Quad-Thruster Assault VTOL", + "plane": "Dorsal", + "gridWidth": 5, + "gridHeight": 6, + "mask": [ + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + false, + true, + false, + false + ], + "hardpoints": [ + { + "id": "hp.weapon.nose", + "kind": "weapon", + "x": 1, + "y": 0, + "w": 2, + "h": 1, + "modelNodeId": "hp.weapon.nose" + }, + { + "id": "hp.armor.hull", + "kind": "armor", + "x": 3, + "y": 0, + "w": 1, + "h": 1, + "modelNodeId": "hp.armor.hull" + }, + { + "id": "hp.weapon.sponson_l", + "kind": "weapon", + "x": 0, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.sponson_l" + }, + { + "id": "hp.weapon.dorsal", + "kind": "weapon", + "x": 2, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.dorsal" + }, + { + "id": "hp.weapon.sponson_r", + "kind": "weapon", + "x": 4, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.sponson_r" + }, + { + "id": "hp.engine.core", + "kind": "engine", + "x": 1, + "y": 2, + "w": 3, + "h": 2, + "modelNodeId": "hp.engine.core" + }, + { + "id": "hp.radiator.spine_l", + "kind": "radiator", + "x": 0, + "y": 3, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.spine_l" + }, + { + "id": "hp.radiator.spine_r", + "kind": "radiator", + "x": 4, + "y": 3, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.spine_r" + } + ], + "joints": [ + { + "id": "joint.nacelle_fl", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 75.0 + }, + { + "id": "joint.rotor_fl", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.nacelle_fr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 75.0 + }, + { + "id": "joint.rotor_fr", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.nacelle_rl", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 75.0 + }, + { + "id": "joint.rotor_rl", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.nacelle_rr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 75.0 + }, + { + "id": "joint.rotor_rr", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.turret_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -180.0, + "max": 180.0 + } + ], + "bounds": { + "min": [ + -2.3586, + 0.0, + -3.1 + ], + "max": [ + 2.3586, + 2.2046, + 2.7758 + ], + "size": [ + 4.7172, + 2.2046, + 5.8758 + ] + }, + "triCount": 12960 +} diff --git a/assets/vehicles/condor/vehicle.cc b/assets/vehicles/condor/vehicle.cc new file mode 100644 index 0000000..ba2ef62 Binary files /dev/null and b/assets/vehicles/condor/vehicle.cc differ diff --git a/assets/vehicles/drop_pod/drop_pod.glb b/assets/vehicles/drop_pod/drop_pod.glb new file mode 100644 index 0000000..8bec65a Binary files /dev/null and b/assets/vehicles/drop_pod/drop_pod.glb differ diff --git a/assets/vehicles/ferret/ferret.glb b/assets/vehicles/ferret/ferret.glb new file mode 100644 index 0000000..b8dff09 Binary files /dev/null and b/assets/vehicles/ferret/ferret.glb differ diff --git a/assets/vehicles/ferret/manifest.json b/assets/vehicles/ferret/manifest.json new file mode 100644 index 0000000..77052ab --- /dev/null +++ b/assets/vehicles/ferret/manifest.json @@ -0,0 +1,100 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "ferret", + "name": "Ferret", + "class": "Light Tracked Scout Tankette", + "plane": "Dorsal", + "gridWidth": 3, + "gridHeight": 4, + "mask": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "hardpoints": [ + { + "id": "hp.armor.glacis", + "kind": "armor", + "x": 0, + "y": 0, + "w": 3, + "h": 1, + "modelNodeId": "hp.armor.glacis" + }, + { + "id": "hp.weapon.pod", + "kind": "weapon", + "x": 0, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.pod" + }, + { + "id": "hp.weapon.turret", + "kind": "weapon", + "x": 1, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.turret" + }, + { + "id": "hp.engine.rear", + "kind": "engine", + "x": 2, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.rear" + }, + { + "id": "hp.radiator.deck", + "kind": "radiator", + "x": 1, + "y": 3, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.deck" + } + ], + "joints": [ + { + "id": "joint.turret_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -180.0, + "max": 180.0 + } + ], + "bounds": { + "min": [ + -1.1075, + 0.0, + -1.8009 + ], + "max": [ + 1.1075, + 1.5523, + 1.869 + ], + "size": [ + 2.215, + 1.5523, + 3.6699 + ] + }, + "triCount": 7612 +} diff --git a/assets/vehicles/ferret/vehicle.cc b/assets/vehicles/ferret/vehicle.cc new file mode 100644 index 0000000..d2a9452 Binary files /dev/null and b/assets/vehicles/ferret/vehicle.cc differ diff --git a/assets/vehicles/hornet/hornet.glb b/assets/vehicles/hornet/hornet.glb new file mode 100644 index 0000000..3ff4378 Binary files /dev/null and b/assets/vehicles/hornet/hornet.glb differ diff --git a/assets/vehicles/hornet/manifest.json b/assets/vehicles/hornet/manifest.json new file mode 100644 index 0000000..bfe246a --- /dev/null +++ b/assets/vehicles/hornet/manifest.json @@ -0,0 +1,143 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "hornet", + "name": "Hornet", + "class": "Light Ducted-Fan VTOL Gunship", + "plane": "Dorsal", + "gridWidth": 4, + "gridHeight": 4, + "mask": [ + false, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + false + ], + "hardpoints": [ + { + "id": "hp.weapon.chin", + "kind": "weapon", + "x": 1, + "y": 0, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.chin" + }, + { + "id": "hp.radiator.nacelle_l", + "kind": "radiator", + "x": 0, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.nacelle_l" + }, + { + "id": "hp.radiator.nacelle_r", + "kind": "radiator", + "x": 3, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.nacelle_r" + }, + { + "id": "hp.weapon.wing_l", + "kind": "weapon", + "x": 0, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.wing_l" + }, + { + "id": "hp.engine.core", + "kind": "engine", + "x": 1, + "y": 2, + "w": 2, + "h": 2, + "modelNodeId": "hp.engine.core" + }, + { + "id": "hp.weapon.wing_r", + "kind": "weapon", + "x": 3, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.wing_r" + } + ], + "joints": [ + { + "id": "joint.nacelle_l", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 75.0 + }, + { + "id": "joint.rotor_l", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.nacelle_r", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 75.0 + }, + { + "id": "joint.rotor_r", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + } + ], + "bounds": { + "min": [ + -1.65, + -0.0, + -2.6715 + ], + "max": [ + 1.65, + 1.8235, + 2.0 + ], + "size": [ + 3.3, + 1.8235, + 4.6715 + ] + }, + "triCount": 7252 +} diff --git a/assets/vehicles/hornet/vehicle.cc b/assets/vehicles/hornet/vehicle.cc new file mode 100644 index 0000000..e3321d1 Binary files /dev/null and b/assets/vehicles/hornet/vehicle.cc differ diff --git a/assets/vehicles/ironclad/ironclad.glb b/assets/vehicles/ironclad/ironclad.glb new file mode 100644 index 0000000..0c266c6 Binary files /dev/null and b/assets/vehicles/ironclad/ironclad.glb differ diff --git a/assets/vehicles/ironclad/manifest.json b/assets/vehicles/ironclad/manifest.json new file mode 100644 index 0000000..f3b5bfa --- /dev/null +++ b/assets/vehicles/ironclad/manifest.json @@ -0,0 +1,126 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "ironclad", + "name": "Ironclad", + "class": "Medium Tracked Battle Tank", + "plane": "Dorsal", + "gridWidth": 4, + "gridHeight": 5, + "mask": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "hardpoints": [ + { + "id": "hp.armor.front", + "kind": "armor", + "x": 0, + "y": 0, + "w": 4, + "h": 1, + "modelNodeId": "hp.armor.front" + }, + { + "id": "hp.weapon.coax", + "kind": "weapon", + "x": 0, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.coax" + }, + { + "id": "hp.weapon.main", + "kind": "weapon", + "x": 1, + "y": 1, + "w": 2, + "h": 2, + "modelNodeId": "hp.weapon.main" + }, + { + "id": "hp.armor.skirts", + "kind": "armor", + "x": 3, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.armor.skirts" + }, + { + "id": "hp.radiator.l", + "kind": "radiator", + "x": 0, + "y": 3, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.l" + }, + { + "id": "hp.engine.rear", + "kind": "engine", + "x": 1, + "y": 3, + "w": 2, + "h": 2, + "modelNodeId": "hp.engine.rear" + }, + { + "id": "hp.radiator.r", + "kind": "radiator", + "x": 3, + "y": 3, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.r" + } + ], + "joints": [ + { + "id": "joint.turret_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -180.0, + "max": 180.0 + } + ], + "bounds": { + "min": [ + -1.5272, + 0.0, + -2.4115 + ], + "max": [ + 1.4934, + 1.792, + 2.3554 + ], + "size": [ + 3.0206, + 1.792, + 4.7669 + ] + }, + "triCount": 16840 +} diff --git a/assets/vehicles/ironclad/vehicle.cc b/assets/vehicles/ironclad/vehicle.cc new file mode 100644 index 0000000..b121484 Binary files /dev/null and b/assets/vehicles/ironclad/vehicle.cc differ diff --git a/assets/vehicles/jackal/jackal.glb b/assets/vehicles/jackal/jackal.glb new file mode 100644 index 0000000..73444df Binary files /dev/null and b/assets/vehicles/jackal/jackal.glb differ diff --git a/assets/vehicles/jackal/manifest.json b/assets/vehicles/jackal/manifest.json new file mode 100644 index 0000000..fc9934c --- /dev/null +++ b/assets/vehicles/jackal/manifest.json @@ -0,0 +1,132 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "jackal", + "name": "Jackal", + "class": "Light Wheeled Dune Buggy", + "plane": "Dorsal", + "gridWidth": 3, + "gridHeight": 4, + "mask": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "hardpoints": [ + { + "id": "hp.weapon.roof", + "kind": "weapon", + "x": 1, + "y": 0, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.roof" + }, + { + "id": "hp.engine.rear", + "kind": "engine", + "x": 1, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.rear" + }, + { + "id": "hp.radiator.rear", + "kind": "radiator", + "x": 2, + "y": 3, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.rear" + } + ], + "joints": [ + { + "id": "joint.steer_fl", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -32.0, + "max": 32.0 + }, + { + "id": "joint.wheel_fl", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.steer_fr", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -32.0, + "max": 32.0 + }, + { + "id": "joint.wheel_fr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rl", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + } + ], + "bounds": { + "min": [ + -0.9778, + 0.0, + -1.5461 + ], + "max": [ + 0.9778, + 1.5457, + 1.705 + ], + "size": [ + 1.9556, + 1.5457, + 3.2511 + ] + }, + "triCount": 16068 +} diff --git a/assets/vehicles/jackal/vehicle.cc b/assets/vehicles/jackal/vehicle.cc new file mode 100644 index 0000000..86378ee Binary files /dev/null and b/assets/vehicles/jackal/vehicle.cc differ diff --git a/assets/vehicles/kestrel/kestrel.glb b/assets/vehicles/kestrel/kestrel.glb new file mode 100644 index 0000000..8ad6ddb Binary files /dev/null and b/assets/vehicles/kestrel/kestrel.glb differ diff --git a/assets/vehicles/kestrel/manifest.json b/assets/vehicles/kestrel/manifest.json new file mode 100644 index 0000000..cd3739f --- /dev/null +++ b/assets/vehicles/kestrel/manifest.json @@ -0,0 +1,133 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "kestrel", + "name": "Kestrel", + "class": "Light Scout Biped", + "plane": "Coronal", + "gridWidth": 5, + "gridHeight": 5, + "mask": [ + false, + false, + true, + false, + false, + false, + true, + true, + true, + false, + false, + true, + true, + true, + true, + false, + true, + true, + true, + true, + false, + true, + false, + true, + false + ], + "hardpoints": [ + { + "id": "hp.weapon.dorsal", + "kind": "weapon", + "x": 2, + "y": 0, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.dorsal" + }, + { + "id": "hp.armor.chest", + "kind": "armor", + "x": 2, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.armor.chest" + }, + { + "id": "hp.radiator.back", + "kind": "radiator", + "x": 1, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back" + }, + { + "id": "hp.engine.core", + "kind": "engine", + "x": 2, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.core" + }, + { + "id": "hp.weapon.arm_r", + "kind": "weapon", + "x": 4, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_r" + } + ], + "joints": [ + { + "id": "joint.torso_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -90.0, + "max": 90.0 + }, + { + "id": "joint.arm_l_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 60.0 + }, + { + "id": "joint.arm_r_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 60.0 + } + ], + "bounds": { + "min": [ + -2.6628, + 0.0, + -2.0753 + ], + "max": [ + 2.6048, + 9.7815, + 2.378 + ], + "size": [ + 5.2676, + 9.7815, + 4.4533 + ] + }, + "triCount": 41382 +} diff --git a/assets/vehicles/kestrel/vehicle.cc b/assets/vehicles/kestrel/vehicle.cc new file mode 100644 index 0000000..231a8ed Binary files /dev/null and b/assets/vehicles/kestrel/vehicle.cc differ diff --git a/assets/vehicles/mammoth/mammoth.glb b/assets/vehicles/mammoth/mammoth.glb new file mode 100644 index 0000000..4747dd4 Binary files /dev/null and b/assets/vehicles/mammoth/mammoth.glb differ diff --git a/assets/vehicles/mammoth/manifest.json b/assets/vehicles/mammoth/manifest.json new file mode 100644 index 0000000..c57615a --- /dev/null +++ b/assets/vehicles/mammoth/manifest.json @@ -0,0 +1,259 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "mammoth", + "name": "Mammoth", + "class": "Heavy 8x8 Armored Fire Support Rig", + "plane": "Dorsal", + "gridWidth": 4, + "gridHeight": 6, + "mask": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "hardpoints": [ + { + "id": "hp.armor.glacis", + "kind": "armor", + "x": 0, + "y": 0, + "w": 4, + "h": 1, + "modelNodeId": "hp.armor.glacis" + }, + { + "id": "hp.weapon.bow", + "kind": "weapon", + "x": 0, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.bow" + }, + { + "id": "hp.weapon.turret_l", + "kind": "weapon", + "x": 1, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.turret_l" + }, + { + "id": "hp.weapon.turret_r", + "kind": "weapon", + "x": 2, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.turret_r" + }, + { + "id": "hp.armor.flanks", + "kind": "armor", + "x": 3, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.armor.flanks" + }, + { + "id": "hp.engine.rear", + "kind": "engine", + "x": 1, + "y": 3, + "w": 2, + "h": 2, + "modelNodeId": "hp.engine.rear" + }, + { + "id": "hp.radiator.l", + "kind": "radiator", + "x": 0, + "y": 4, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.l" + }, + { + "id": "hp.radiator.r", + "kind": "radiator", + "x": 3, + "y": 4, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.r" + } + ], + "joints": [ + { + "id": "joint.steer_fl1", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -28.0, + "max": 28.0 + }, + { + "id": "joint.wheel_fl1", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.steer_fr1", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -28.0, + "max": 28.0 + }, + { + "id": "joint.wheel_fr1", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.steer_fl2", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -28.0, + "max": 28.0 + }, + { + "id": "joint.wheel_fl2", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.steer_fr2", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -28.0, + "max": 28.0 + }, + { + "id": "joint.wheel_fr2", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rl1", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rr1", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rl2", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rr2", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.turret_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -180.0, + "max": 180.0 + } + ], + "bounds": { + "min": [ + -1.46, + 0.0, + -2.64 + ], + "max": [ + 1.46, + 2.3467, + 3.2249 + ], + "size": [ + 2.92, + 2.3467, + 5.8649 + ] + }, + "triCount": 20512 +} diff --git a/assets/vehicles/mammoth/vehicle.cc b/assets/vehicles/mammoth/vehicle.cc new file mode 100644 index 0000000..00c244d Binary files /dev/null and b/assets/vehicles/mammoth/vehicle.cc differ diff --git a/assets/vehicles/manticore/manifest.json b/assets/vehicles/manticore/manifest.json new file mode 100644 index 0000000..d47831b --- /dev/null +++ b/assets/vehicles/manticore/manifest.json @@ -0,0 +1,171 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "manticore", + "name": "Manticore", + "class": "Heavy Quadruped Scorpion", + "plane": "Dorsal", + "gridWidth": 5, + "gridHeight": 5, + "mask": [ + true, + true, + true, + true, + true, + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + true, + true, + true, + false, + true, + false, + true, + false, + true + ], + "hardpoints": [ + { + "id": "hp.weapon.chin", + "kind": "weapon", + "x": 2, + "y": 0, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.chin" + }, + { + "id": "hp.radiator.flank_l", + "kind": "radiator", + "x": 1, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.flank_l" + }, + { + "id": "hp.engine.core", + "kind": "engine", + "x": 2, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.core" + }, + { + "id": "hp.radiator.flank_r", + "kind": "radiator", + "x": 3, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.flank_r" + }, + { + "id": "hp.weapon.l", + "kind": "weapon", + "x": 0, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.l" + }, + { + "id": "hp.weapon.r", + "kind": "weapon", + "x": 4, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.r" + }, + { + "id": "hp.armor.prow", + "kind": "armor", + "x": 2, + "y": 3, + "w": 1, + "h": 1, + "modelNodeId": "hp.armor.prow" + } + ], + "joints": [ + { + "id": "joint.tail_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -75.0, + "max": 75.0 + }, + { + "id": "joint.tail_s1", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -60.0, + "max": 60.0 + }, + { + "id": "joint.tail_s2", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -75.0, + "max": 15.0 + }, + { + "id": "joint.tail_s3", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -80.0, + "max": 10.0 + }, + { + "id": "joint.tail_elev", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -40.0, + "max": 30.0 + } + ], + "bounds": { + "min": [ + -3.4374, + 0.0, + -4.5621 + ], + "max": [ + 3.4358, + 6.5001, + 4.547 + ], + "size": [ + 6.8732, + 6.5001, + 9.1091 + ] + }, + "triCount": 33517 +} diff --git a/assets/vehicles/manticore/manticore.glb b/assets/vehicles/manticore/manticore.glb new file mode 100644 index 0000000..01bad1c Binary files /dev/null and b/assets/vehicles/manticore/manticore.glb differ diff --git a/assets/vehicles/manticore/vehicle.cc b/assets/vehicles/manticore/vehicle.cc new file mode 100644 index 0000000..d740b50 Binary files /dev/null and b/assets/vehicles/manticore/vehicle.cc differ diff --git a/assets/vehicles/mule/manifest.json b/assets/vehicles/mule/manifest.json new file mode 100644 index 0000000..a646428 --- /dev/null +++ b/assets/vehicles/mule/manifest.json @@ -0,0 +1,182 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "mule", + "name": "Mule", + "class": "Medium 6x6 Armored Gun Truck", + "plane": "Dorsal", + "gridWidth": 3, + "gridHeight": 5, + "mask": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "hardpoints": [ + { + "id": "hp.armor.front", + "kind": "armor", + "x": 0, + "y": 0, + "w": 3, + "h": 1, + "modelNodeId": "hp.armor.front" + }, + { + "id": "hp.radiator.left", + "kind": "radiator", + "x": 0, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.left" + }, + { + "id": "hp.engine.front", + "kind": "engine", + "x": 1, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.front" + }, + { + "id": "hp.radiator.right", + "kind": "radiator", + "x": 2, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.right" + }, + { + "id": "hp.weapon.cab", + "kind": "weapon", + "x": 0, + "y": 3, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.cab" + }, + { + "id": "hp.weapon.bed_main", + "kind": "weapon", + "x": 1, + "y": 3, + "w": 2, + "h": 2, + "modelNodeId": "hp.weapon.bed_main" + } + ], + "joints": [ + { + "id": "joint.steer_fl", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -30.0, + "max": 30.0 + }, + { + "id": "joint.wheel_fl", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.steer_fr", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -30.0, + "max": 30.0 + }, + { + "id": "joint.wheel_fr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_ml", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_mr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rl", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + } + ], + "bounds": { + "min": [ + -1.1938, + 0.0, + -2.4067 + ], + "max": [ + 1.1938, + 2.0889, + 2.46 + ], + "size": [ + 2.3876, + 2.0889, + 4.8667 + ] + }, + "triCount": 13772 +} diff --git a/assets/vehicles/mule/mule.glb b/assets/vehicles/mule/mule.glb new file mode 100644 index 0000000..cd2d258 Binary files /dev/null and b/assets/vehicles/mule/mule.glb differ diff --git a/assets/vehicles/mule/vehicle.cc b/assets/vehicles/mule/vehicle.cc new file mode 100644 index 0000000..043b8f1 Binary files /dev/null and b/assets/vehicles/mule/vehicle.cc differ diff --git a/assets/vehicles/paladin/manifest.json b/assets/vehicles/paladin/manifest.json new file mode 100644 index 0000000..dd6df5f --- /dev/null +++ b/assets/vehicles/paladin/manifest.json @@ -0,0 +1,186 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "paladin", + "name": "Paladin", + "class": "Heavy Assault Biped", + "plane": "Coronal", + "gridWidth": 6, + "gridHeight": 7, + "mask": [ + false, + false, + true, + true, + false, + false, + false, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + false, + false, + true, + false, + false, + true, + false, + false, + true, + false, + false, + true, + false + ], + "hardpoints": [ + { + "id": "hp.weapon.sh_l", + "kind": "weapon", + "x": 1, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.sh_l" + }, + { + "id": "hp.armor.torso", + "kind": "armor", + "x": 2, + "y": 1, + "w": 2, + "h": 1, + "modelNodeId": "hp.armor.torso" + }, + { + "id": "hp.weapon.sh_r", + "kind": "weapon", + "x": 4, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.sh_r" + }, + { + "id": "hp.weapon.arm_l", + "kind": "weapon", + "x": 0, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_l" + }, + { + "id": "hp.engine.chest", + "kind": "engine", + "x": 2, + "y": 2, + "w": 2, + "h": 2, + "modelNodeId": "hp.engine.chest" + }, + { + "id": "hp.weapon.arm_r", + "kind": "weapon", + "x": 5, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_r" + }, + { + "id": "hp.radiator.back_l", + "kind": "radiator", + "x": 1, + "y": 4, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back_l" + }, + { + "id": "hp.armor.legs", + "kind": "armor", + "x": 2, + "y": 4, + "w": 2, + "h": 1, + "modelNodeId": "hp.armor.legs" + }, + { + "id": "hp.radiator.back_r", + "kind": "radiator", + "x": 4, + "y": 4, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back_r" + } + ], + "joints": [ + { + "id": "joint.torso_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -90.0, + "max": 90.0 + }, + { + "id": "joint.arm_l_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -40.0, + "max": 70.0 + }, + { + "id": "joint.arm_r_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -40.0, + "max": 70.0 + } + ], + "bounds": { + "min": [ + -4.4388, + -0.0, + -1.5109 + ], + "max": [ + 4.4387, + 11.3161, + 2.4514 + ], + "size": [ + 8.8775, + 11.3161, + 3.9623 + ] + }, + "triCount": 36463 +} diff --git a/assets/vehicles/paladin/paladin.glb b/assets/vehicles/paladin/paladin.glb new file mode 100644 index 0000000..5a0c2ab Binary files /dev/null and b/assets/vehicles/paladin/paladin.glb differ diff --git a/assets/vehicles/paladin/vehicle.cc b/assets/vehicles/paladin/vehicle.cc new file mode 100644 index 0000000..460cd19 Binary files /dev/null and b/assets/vehicles/paladin/vehicle.cc differ diff --git a/assets/vehicles/raptor/manifest.json b/assets/vehicles/raptor/manifest.json new file mode 100644 index 0000000..29f6590 --- /dev/null +++ b/assets/vehicles/raptor/manifest.json @@ -0,0 +1,128 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "raptor", + "name": "Raptor", + "class": "Medium Theropod Biped", + "plane": "Coronal", + "gridWidth": 5, + "gridHeight": 6, + "mask": [ + false, + false, + true, + false, + false, + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + false, + true, + false, + true, + false, + true, + false, + true, + false, + false, + true, + false, + true, + false + ], + "hardpoints": [ + { + "id": "hp.radiator.sh_l", + "kind": "radiator", + "x": 1, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.sh_l" + }, + { + "id": "hp.radiator.sh_r", + "kind": "radiator", + "x": 3, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.sh_r" + }, + { + "id": "hp.weapon.arm_l", + "kind": "weapon", + "x": 0, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_l" + }, + { + "id": "hp.engine.chest", + "kind": "engine", + "x": 2, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.chest" + }, + { + "id": "hp.weapon.arm_r", + "kind": "weapon", + "x": 4, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_r" + } + ], + "joints": [ + { + "id": "joint.arm_l_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 45.0 + }, + { + "id": "joint.arm_r_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 45.0 + } + ], + "bounds": { + "min": [ + -2.3822, + 0.0, + -4.422 + ], + "max": [ + 2.3822, + 6.9873, + 4.5553 + ], + "size": [ + 4.7644, + 6.9873, + 8.9773 + ] + }, + "triCount": 36156 +} diff --git a/assets/vehicles/raptor/raptor.glb b/assets/vehicles/raptor/raptor.glb new file mode 100644 index 0000000..cd874db Binary files /dev/null and b/assets/vehicles/raptor/raptor.glb differ diff --git a/assets/vehicles/raptor/vehicle.cc b/assets/vehicles/raptor/vehicle.cc new file mode 100644 index 0000000..faa2ec4 Binary files /dev/null and b/assets/vehicles/raptor/vehicle.cc differ diff --git a/assets/vehicles/spectre/manifest.json b/assets/vehicles/spectre/manifest.json new file mode 100644 index 0000000..83922ea --- /dev/null +++ b/assets/vehicles/spectre/manifest.json @@ -0,0 +1,156 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "spectre", + "name": "Spectre", + "class": "Medium Recon/Skirmisher Biped", + "plane": "Coronal", + "gridWidth": 5, + "gridHeight": 6, + "mask": [ + false, + true, + false, + false, + false, + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + false, + true, + false, + false, + true, + false, + true, + false + ], + "hardpoints": [ + { + "id": "hp.weapon.shoulder_l", + "kind": "weapon", + "x": 1, + "y": 0, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.shoulder_l" + }, + { + "id": "hp.armor.torso", + "kind": "armor", + "x": 2, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.armor.torso" + }, + { + "id": "hp.weapon.arm_l", + "kind": "weapon", + "x": 0, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_l" + }, + { + "id": "hp.radiator.back_l", + "kind": "radiator", + "x": 1, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back_l" + }, + { + "id": "hp.engine.core", + "kind": "engine", + "x": 2, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.core" + }, + { + "id": "hp.radiator.back_r", + "kind": "radiator", + "x": 3, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back_r" + }, + { + "id": "hp.weapon.arm_r", + "kind": "weapon", + "x": 4, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_r" + } + ], + "joints": [ + { + "id": "joint.torso_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -90.0, + "max": 90.0 + }, + { + "id": "joint.arm_l_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 60.0 + }, + { + "id": "joint.arm_r_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 60.0 + } + ], + "bounds": { + "min": [ + -3.4467, + -0.0, + -2.442 + ], + "max": [ + 3.8332, + 8.9891, + 3.6426 + ], + "size": [ + 7.2799, + 8.9891, + 6.0846 + ] + }, + "triCount": 40696 +} diff --git a/assets/vehicles/spectre/spectre.glb b/assets/vehicles/spectre/spectre.glb new file mode 100644 index 0000000..e271f7d Binary files /dev/null and b/assets/vehicles/spectre/spectre.glb differ diff --git a/assets/vehicles/spectre/vehicle.cc b/assets/vehicles/spectre/vehicle.cc new file mode 100644 index 0000000..831aaeb Binary files /dev/null and b/assets/vehicles/spectre/vehicle.cc differ diff --git a/client/ArenaAudioSystem.cs b/client/ArenaAudioSystem.cs new file mode 100644 index 0000000..0e80ad1 --- /dev/null +++ b/client/ArenaAudioSystem.cs @@ -0,0 +1,1394 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; +using RustToDust.Ymir; + +namespace RustToDust.Client; + +/// +/// Owns the fixed 24 pool (5 continuous vehicle/servo +/// loops + 19 priority-stealing one-shots) and 4 2D UI +/// voices on a dynamically registered SFX bus with . +/// 100% crash-free under --headless / Dummy audio driver. +/// +public partial class ArenaAudioSystem : Node3D +{ + public const int LoopVoiceCount = 5; + public const int OneShotVoiceCount = 19; + public const int Total3DVoiceCount = LoopVoiceCount + OneShotVoiceCount; // 24 + public const int UiVoiceCount = 4; + + public const float MaxAudioDistance = 260f; + public const float MaxLoopDistance = 160f; + public const float LoopHysteresisMeters = 12f; + public const float ShotDedupeWindowSec = 0.035f; + public const float ImpactDedupeWindowSec = 0.045f; + public const float OverheatAlarmPeriodSec = 0.90f; + + public const int PriorityLocalAction = 10; + public const int PriorityLocalImpactOrKill = 8; + public const int PriorityNearCombat = 5; + public const int PriorityDistantCombat = 1; + + private struct LoopSlot + { + public AudioStreamPlayer3D Player; + public bool Active; + public bool IsContender; + public int EntityId; + public string ClipKey; + public float DistSq; + public float VolumeDb; + public float PitchScale; + } + + private struct OneShotSlot + { + public AudioStreamPlayer3D Player; + public bool Active; + public int Priority; + public long AssignedSeq; + public float RemainingSec; + public float DurationSec; + public string ClipKey; + public bool IsLocalSource; + public int SourceEntityId; + public float LastPitch; + public float LastVolumeDb; + } + + private struct UiSlot + { + public AudioStreamPlayer Player; + public bool Active; + public float RemainingSec; + public long AssignedSeq; + public string ClipKey; + } + + private readonly struct LoopCandidate + { + public readonly bool IsContender; + public readonly int EntityId; + public readonly string ClipKey; + public readonly Vector3 Position; + public readonly float DistSq; + public readonly float VolumeDb; + public readonly float PitchScale; + + public LoopCandidate( + bool isContender, + int entityId, + string clipKey, + Vector3 position, + float distSq, + float volumeDb, + float pitchScale) + { + IsContender = isContender; + EntityId = entityId; + ClipKey = clipKey; + Position = position; + DistSq = distSq; + VolumeDb = volumeDb; + PitchScale = pitchScale; + } + } + + private ProceduralAudioBank _bank = null!; + private readonly LoopSlot[] _loopSlots = new LoopSlot[LoopVoiceCount]; + private readonly OneShotSlot[] _oneShotSlots = new OneShotSlot[OneShotVoiceCount]; + private readonly UiSlot[] _uiSlots = new UiSlot[UiVoiceCount]; + + private readonly Dictionary<(bool IsSpectator, int ShooterId, string WeaponId), float> _shotDedupeExpiry = new(); + private readonly Dictionary<(byte TargetKind, int TargetId), float> _impactDedupeExpiry = new(); + private readonly Dictionary<(byte Kind, int ShooterId, byte NodeIdx), float> _ordnanceDedupeExpiry = new(); + private readonly Dictionary _lastContenderChassis = new(); + private readonly Dictionary _lastContenderLoadoutVer = new(); + private readonly List<(float X, float Z, float Expiry)> _recentExplosionPoints = new(16); + private readonly List _pendingCraterStamps = new(8); + private readonly List _loopCandidates = new(32); + + private bool _initialized; + private bool _isDummyAudio; + private float _audioTime; + private float _overheatAlarmCooldown; + private long _voiceSeq = 1; + private uint _variantCounter; + private uint _rng = 0x9E3779B9u; + + public ProceduralAudioBank Bank => _bank; + public bool IsDummyAudio => _isDummyAudio; + public bool WetMixMode => _bank?.WetMixMode ?? true; + + public int Total3DPlaysRequested { get; private set; } + public int RejectedDistanceCount { get; private set; } + public int DedupedCount { get; private set; } + public int StolenVoiceCount { get; private set; } + public string LastAllocatedClipKey { get; private set; } = string.Empty; + public float LastAllocatedPitch { get; private set; } = 1f; + + public int ActiveLoopVoiceCount + { + get + { + int count = 0; + for (int i = 0; i < _loopSlots.Length; i++) + { + if (_loopSlots[i].Active) count++; + } + return count; + } + } + + public int ActiveOneShotVoiceCount + { + get + { + int count = 0; + for (int i = 0; i < _oneShotSlots.Length; i++) + { + if (_oneShotSlots[i].Active) count++; + } + return count; + } + } + + public int Active3DVoiceCount => ActiveLoopVoiceCount + ActiveOneShotVoiceCount; + + public int ActiveUiVoiceCount + { + get + { + int count = 0; + for (int i = 0; i < _uiSlots.Length; i++) + { + if (_uiSlots[i].Active) count++; + } + return count; + } + } + + public override void _Ready() + { + EnsureInitialized(); + } + + public void EnsureInitialized() + { + if (_initialized) + { + return; + } + _initialized = true; + + _isDummyAudio = DisplayServer.GetName().Equals("headless", StringComparison.OrdinalIgnoreCase) + || AudioServer.GetDriverName().Equals("Dummy", StringComparison.OrdinalIgnoreCase); + + EnsureSfxBusAndLimiter(); + _bank = new ProceduralAudioBank(wetMixMode: true); + + for (int i = 0; i < LoopVoiceCount; i++) + { + var p = Create3DPlayer($"AudioLoop3D_{i}"); + AddChild(p); + _loopSlots[i] = new LoopSlot { Player = p, ClipKey = string.Empty }; + } + + for (int i = 0; i < OneShotVoiceCount; i++) + { + var p = Create3DPlayer($"AudioOneShot3D_{i}"); + AddChild(p); + _oneShotSlots[i] = new OneShotSlot { Player = p, ClipKey = string.Empty }; + } + + for (int i = 0; i < UiVoiceCount; i++) + { + var p = new AudioStreamPlayer + { + Name = $"AudioUi2D_{i}", + Bus = "SFX" + }; + AddChild(p); + _uiSlots[i] = new UiSlot { Player = p, ClipKey = string.Empty }; + } + } + + private static AudioStreamPlayer3D Create3DPlayer(string name) => new() + { + Name = name, + Bus = "SFX", + UnitSize = 24f, + MaxDistance = MaxAudioDistance, + AttenuationModel = AudioStreamPlayer3D.AttenuationModelEnum.InverseDistance, + MaxDb = 3f + }; + + private static void EnsureSfxBusAndLimiter() + { + int busIdx = AudioServer.GetBusIndex("SFX"); + if (busIdx < 0) + { + busIdx = AudioServer.BusCount; + AudioServer.AddBus(busIdx); + AudioServer.SetBusName(busIdx, "SFX"); + AudioServer.SetBusSend(busIdx, "Master"); + } + + bool hasLimiter = false; + int effectCount = AudioServer.GetBusEffectCount(busIdx); + for (int i = 0; i < effectCount; i++) + { + if (AudioServer.GetBusEffect(busIdx, i) is AudioEffectHardLimiter) + { + hasLimiter = true; + break; + } + } + if (!hasLimiter) + { + AudioServer.AddBusEffect(busIdx, new AudioEffectHardLimiter + { + CeilingDb = -1.0f + }); + } + } + + public void ClearAll() + { + EnsureInitialized(); + for (int i = 0; i < _loopSlots.Length; i++) + { + if (!_isDummyAudio && _loopSlots[i].Player.Playing) + { + _loopSlots[i].Player.Stop(); + } + _loopSlots[i].Active = false; + _loopSlots[i].EntityId = -1; + _loopSlots[i].ClipKey = string.Empty; + } + for (int i = 0; i < _oneShotSlots.Length; i++) + { + if (!_isDummyAudio && _oneShotSlots[i].Player.Playing) + { + _oneShotSlots[i].Player.Stop(); + } + _oneShotSlots[i].Active = false; + _oneShotSlots[i].Priority = 0; + _oneShotSlots[i].RemainingSec = 0f; + _oneShotSlots[i].ClipKey = string.Empty; + _oneShotSlots[i].IsLocalSource = false; + _oneShotSlots[i].SourceEntityId = -1; + } + for (int i = 0; i < _uiSlots.Length; i++) + { + if (!_isDummyAudio && _uiSlots[i].Player.Playing) + { + _uiSlots[i].Player.Stop(); + } + _uiSlots[i].Active = false; + _uiSlots[i].RemainingSec = 0f; + _uiSlots[i].ClipKey = string.Empty; + } + + _shotDedupeExpiry.Clear(); + _impactDedupeExpiry.Clear(); + _ordnanceDedupeExpiry.Clear(); + _lastContenderChassis.Clear(); + _lastContenderLoadoutVer.Clear(); + _recentExplosionPoints.Clear(); + _pendingCraterStamps.Clear(); + _overheatAlarmCooldown = 0f; + } + + public void ResetForSession(IClientArenaSession? session) + { + ClearAll(); + SeedLoadoutBaselines(session); + } + + private void SeedLoadoutBaselines(IClientArenaSession? session) + { + if (session is null) + { + return; + } + var contenders = session.ViewState.Contenders; + for (int i = 0; i < contenders.Count; i++) + { + var c = contenders[i]; + if (string.IsNullOrEmpty(c.Grid.Spec.Id)) + { + continue; + } + if (!_lastContenderChassis.ContainsKey(c.Id)) + { + _lastContenderChassis[c.Id] = c.Grid.Spec.Id; + } + if (!_lastContenderLoadoutVer.ContainsKey(c.Id)) + { + _lastContenderLoadoutVer[c.Id] = c.LoadoutVersion; + } + } + } + + public void ResetStatsForTest() + { + Total3DPlaysRequested = 0; + RejectedDistanceCount = 0; + DedupedCount = 0; + StolenVoiceCount = 0; + LastAllocatedClipKey = string.Empty; + LastAllocatedPitch = 1f; + } + + public bool HasActiveVoiceForSource(bool isLocalSource, int sourceEntityId) + { + for (int i = 0; i < _oneShotSlots.Length; i++) + { + ref readonly var slot = ref _oneShotSlots[i]; + if (slot.Active && slot.IsLocalSource == isLocalSource && slot.SourceEntityId == sourceEntityId) + { + return true; + } + } + return false; + } + + public int CountActiveVoicesForClip(string clipKey) + { + int count = 0; + for (int i = 0; i < _oneShotSlots.Length; i++) + { + if (_oneShotSlots[i].Active && string.Equals(_oneShotSlots[i].ClipKey, clipKey, StringComparison.Ordinal)) + { + count++; + } + } + return count; + } + + public int CountActiveUiVoicesForClip(string clipKey) + { + int count = 0; + for (int i = 0; i < _uiSlots.Length; i++) + { + if (_uiSlots[i].Active && string.Equals(_uiSlots[i].ClipKey, clipKey, StringComparison.Ordinal)) + { + count++; + } + } + return count; + } + + public float? GetLastPitchForClipPrefix(string prefix) + { + for (int i = _oneShotSlots.Length - 1; i >= 0; i--) + { + if (_oneShotSlots[i].Active && _oneShotSlots[i].ClipKey.StartsWith(prefix, StringComparison.Ordinal)) + { + return _oneShotSlots[i].LastPitch; + } + } + return null; + } + + public void UpdateFrame( + IClientArenaSession session, + IReadOnlyList events, + IReadOnlyList footsteps, + Vector3 listenerPos, + float dt, + float alpha) + { + EnsureInitialized(); + + float stepDt = MathF.Max(0f, dt); + _audioTime += stepDt; + AdvanceVoices(stepDt); + + if (_overheatAlarmCooldown > 0f) + { + _overheatAlarmCooldown = MathF.Max(0f, _overheatAlarmCooldown - stepDt); + } + + var local = session.LocalContender; + int localId = session.LocalContenderId; + SeedLoadoutBaselines(session); + UpdateLoopSlots(session, listenerPos, alpha); + ConsumeSimEvents(session, events, listenerPos); + ConsumeFootsteps(footsteps, localId, listenerPos); + + if (local.Alive && local.MaxThermalRatio >= 0.85f && _overheatAlarmCooldown <= 0f) + { + PlayUi("ui_overheat_alarm", volumeDb: -4.5f, pitchScale: 1f); + _overheatAlarmCooldown = OverheatAlarmPeriodSec; + } + } + + public void ConsumeSimEvents( + IClientArenaSession session, + IReadOnlyList events, + Vector3 listenerPos) + { + EnsureInitialized(); + int localId = session.LocalContenderId; + var state = session.ViewState; + _pendingCraterStamps.Clear(); + + for (int i = 0; i < events.Count; i++) + { + switch (events[i]) + { + case MatchResetEvent: + ClearAll(); + SeedLoadoutBaselines(session); + break; + + case ShotFiredEvent shot: + HandleShotFired(shot, localId, listenerPos); + break; + + case HitImpactEvent hit: + HandleHitImpact(hit, localId, listenerPos); + break; + + case ContenderEliminatedEvent elim: + HandleContenderEliminated(session, state, elim, listenerPos); + break; + + case SpectatorDestroyedEvent sdet: + HandleSpectatorDestroyed(session, state, sdet, listenerPos); + break; + + case TerrainStampEvent stamp: + if (stamp.Kind == (byte)TerrainStampKind.Crater && stamp.Radius >= 3.0f) + { + _pendingCraterStamps.Add(stamp); + } + break; + + case DropPickedUpEvent pickup: + if (pickup.ContenderId == localId) + { + bool imperial = IsImperialDrop(state, pickup.DropId); + PlayUi(imperial ? "ui_pickup_imperial" : "ui_pickup_module", volumeDb: -3.0f, pitchScale: 1f); + } + break; + + case OverheatAlertEvent overheat: + if (overheat.ContenderId == localId && overheat.IsOverheating && _overheatAlarmCooldown <= 0f) + { + PlayUi("ui_overheat_alarm", volumeDb: -4.0f, pitchScale: 1f); + _overheatAlarmCooldown = OverheatAlarmPeriodSec; + } + break; + + case ContenderLoadoutEvent loadout: + HandleLoadoutChanged(session, state, loadout, localId, listenerPos); + break; + + case DropPodEvent dpe: + HandleDropPodEvent(dpe, localId, listenerPos); + break; + + case OrdnanceNodeEvent ord: + HandleOrdnanceNodeEvent(ord, localId, listenerPos); + break; + } + } + + for (int i = 0; i < _pendingCraterStamps.Count; i++) + { + var stamp = _pendingCraterStamps[i]; + if (!HasRecentExplosionNear(stamp.X, stamp.Z, 12f)) + { + float y = state.Terrain.SampleHeight(stamp.X, stamp.Z); + PlayOneShot3D( + "impact_explosion", + new Vector3(stamp.X, y, stamp.Z), + listenerPos, + PriorityNearCombat, + volumeDb: -4.0f, + pitchScale: NextPitchJitter(0.94f, 1.06f), + isLocalSource: false, + sourceEntityId: -1); + } + } + _pendingCraterStamps.Clear(); + } + + public void ConsumeFootsteps(IReadOnlyList footsteps, int localId, Vector3 listenerPos) + { + EnsureInitialized(); + for (int i = 0; i < footsteps.Count; i++) + { + FootstepPulse pulse = footsteps[i]; + string clipKey = pulse.MassKg > 3600f + ? "footstep_heavy_thud" + : (pulse.MassKg > 2200f ? "footstep_med_step" : "footstep_light_step"); + + float pitch = Math.Clamp(1.18f - (pulse.MassKg - 1650f) / 6000f, 0.58f, 1.22f) + + Math.Clamp(0.08f * (pulse.LoadG - 1f), -0.06f, 0.08f); + float massNorm = Math.Clamp((pulse.MassKg - 1500f) / 3500f, 0f, 1f); + float loadNorm = Math.Clamp(pulse.LoadG, 0.4f, 2.2f); + float volDb = Math.Clamp(-12f + massNorm * 6f + (loadNorm - 1f) * 3.5f, -14f, 0f); + + bool isLocal = pulse.IsContender && pulse.EntityId == localId; + var pos = new Vector3(pulse.WorldPos.X, pulse.WorldPos.Y, pulse.WorldPos.Z); + float distSq = pos.DistanceSquaredTo(listenerPos); + int priority = isLocal + ? PriorityLocalAction + : (distSq <= 90f * 90f ? PriorityNearCombat : PriorityDistantCombat); + + PlayOneShot3D( + clipKey, + pos, + listenerPos, + priority, + volDb, + pitch, + isLocalSource: isLocal, + sourceEntityId: pulse.EntityId); + } + } + + private void HandleShotFired(ShotFiredEvent shot, int localId, Vector3 listenerPos) + { + var dedupeKey = (shot.IsSpectatorShooter, shot.ShooterId, shot.WeaponId ?? string.Empty); + if (_shotDedupeExpiry.TryGetValue(dedupeKey, out float expiry) && _audioTime < expiry) + { + DedupedCount++; + return; + } + _shotDedupeExpiry[dedupeKey] = _audioTime + ShotDedupeWindowSec; + PruneExpiredMap(_shotDedupeExpiry); + + string clipKey = SelectWeaponClipKey(shot.WeaponId, (WeaponVisualClass)shot.WeaponClass); + bool isLocal = !shot.IsSpectatorShooter && shot.ShooterId == localId; + Vector3 pos = new(shot.StartX, shot.StartY, shot.StartZ); + float distSq = pos.DistanceSquaredTo(listenerPos); + + int priority = isLocal + ? PriorityLocalAction + : (distSq <= 90f * 90f ? PriorityNearCombat : PriorityDistantCombat); + float volDb = isLocal ? -1.5f : -3.5f; + float pitch = NextPitchJitter(0.95f, 1.05f); + + PlayOneShot3D(clipKey, pos, listenerPos, priority, volDb, pitch, isLocal, shot.ShooterId); + } + + private void HandleHitImpact(HitImpactEvent hit, int localId, Vector3 listenerPos) + { + bool isLocalShooter = hit.IsContenderShooter && hit.ShooterId == localId; + bool isLocalTarget = hit.TargetKind == (byte)HitTargetKind.Contender && hit.TargetId == localId; + bool targetIsVehicle = hit.TargetKind == (byte)HitTargetKind.Contender || hit.TargetKind == (byte)HitTargetKind.Spectator; + + if (isLocalShooter && targetIsVehicle) + { + string uiKey = hit.Killed + ? "ui_hit_kill" + : (hit.CoreDamage > 0f ? "ui_hit_core" : "ui_hit_armor"); + PlayUi(uiKey, volumeDb: hit.Killed ? -2.0f : -4.0f, pitchScale: 1f); + } + + var impactKey = (hit.TargetKind, hit.TargetId); + if (_impactDedupeExpiry.TryGetValue(impactKey, out float expiry) && _audioTime < expiry) + { + return; + } + _impactDedupeExpiry[impactKey] = _audioTime + ImpactDedupeWindowSec; + PruneExpiredMap(_impactDedupeExpiry); + + Vector3 pos = new(hit.HitX, hit.HitY, hit.HitZ); + float distSq = pos.DistanceSquaredTo(listenerPos); + int priority = (isLocalShooter || isLocalTarget) + ? PriorityLocalImpactOrKill + : (distSq <= 90f * 90f ? PriorityNearCombat : PriorityDistantCombat); + + string clipKey; + float volDb; + if (targetIsVehicle) + { + if (hit.CoreDamage > 0f) + { + clipKey = "impact_core"; + volDb = isLocalTarget ? -1.0f : -3.5f; + } + else if (hit.ArmorDamage > 0f) + { + clipKey = "impact_armor_crunch"; + volDb = isLocalTarget ? -2.0f : -4.5f; + } + else + { + clipKey = "impact_ricochet"; + volDb = -6.0f; + } + } + else if (hit.IsAirburst || hit.WeaponClass == (byte)WeaponVisualClass.Explosive) + { + clipKey = "impact_explosion"; + volDb = -4.0f; + RecordExplosionPoint(hit.HitX, hit.HitZ); + } + else + { + clipKey = "impact_ricochet"; + volDb = -8.5f; + } + + PlayOneShot3D(clipKey, pos, listenerPos, priority, volDb, NextPitchJitter(0.92f, 1.08f), isLocalTarget, hit.TargetId); + } + + private void HandleContenderEliminated(IClientArenaSession session, MatchState state, ContenderEliminatedEvent elim, Vector3 listenerPos) + { + if (elim.VictimId != session.LocalContenderId && !session.IsContenderVisible(elim.VictimId)) return; + if (elim.VictimId < 0 || elim.VictimId >= state.Contenders.Count) return; + var v = state.Contenders[elim.VictimId]; + Vector3 pos = new(v.X, v.Y, v.Z); + RecordExplosionPoint(v.X, v.Z); + + PlayOneShot3D("impact_explosion", pos, listenerPos, PriorityLocalImpactOrKill, volumeDb: -0.5f, pitchScale: NextPitchJitter(0.92f, 1.02f), isLocalSource: false, sourceEntityId: elim.VictimId); + PlayOneShot3D("mech_eject", pos, listenerPos, PriorityNearCombat, volumeDb: -3.5f, pitchScale: NextPitchJitter(0.96f, 1.04f), isLocalSource: false, sourceEntityId: elim.VictimId); + + if (!elim.IsSpectatorKiller && elim.KillerId == _localKillerFallback(state, elim.KillerId)) + { + // Local kill chime is already handled on HitImpactEvent.Killed, no double chime needed. + } + } + + private static int _localKillerFallback(MatchState state, int killerId) => killerId; + + private void HandleSpectatorDestroyed(IClientArenaSession session, MatchState state, SpectatorDestroyedEvent sdet, Vector3 listenerPos) + { + if (!session.IsSpectatorVisible(sdet.SpectatorId)) return; + SpectatorState? s = null; + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + if (specs[i].Id == sdet.SpectatorId) + { + s = specs[i]; + break; + } + } + if (s is null) + { + int sIdx = sdet.SpectatorId >= 1000 ? sdet.SpectatorId - 1000 : sdet.SpectatorId; + if (sIdx >= 0 && sIdx < specs.Count) + { + s = specs[sIdx]; + } + } + if (s is null) return; + + Vector3 pos = new(s.X, s.Y, s.Z); + RecordExplosionPoint(s.X, s.Z); + + PlayOneShot3D("impact_explosion", pos, listenerPos, PriorityLocalImpactOrKill, volumeDb: -1.5f, pitchScale: NextPitchJitter(0.94f, 1.04f), isLocalSource: false, sourceEntityId: sdet.SpectatorId); + PlayOneShot3D("mech_eject", pos, listenerPos, PriorityNearCombat, volumeDb: -4.5f, pitchScale: 1f, isLocalSource: false, sourceEntityId: sdet.SpectatorId); + } + + private void HandleLoadoutChanged(IClientArenaSession session, MatchState state, ContenderLoadoutEvent loadout, int localId, Vector3 listenerPos) + { + int id = loadout.ContenderId; + bool hadPrevChassis = _lastContenderChassis.TryGetValue(id, out string? prevChassis); + bool hadPrevVer = _lastContenderLoadoutVer.TryGetValue(id, out int prevVer); + + _lastContenderChassis[id] = loadout.ChassisId; + _lastContenderLoadoutVer[id] = loadout.LoadoutVersion; + + if (!hadPrevChassis || !hadPrevVer || loadout.LoadoutVersion <= prevVer) + { + return; + } + + bool chassisChanged = !string.Equals(prevChassis, loadout.ChassisId, StringComparison.OrdinalIgnoreCase); + string clipKey = chassisChanged ? "mech_reload_bolt" : "mech_quick_bolt"; + + if (id == localId) + { + PlayUi(clipKey, volumeDb: -3.5f, pitchScale: 1f); + } + else if (session.IsContenderVisible(id) && id >= 0 && id < state.Contenders.Count) + { + var c = state.Contenders[id]; + PlayOneShot3D(clipKey, new Vector3(c.X, c.Y, c.Z), listenerPos, PriorityNearCombat, volumeDb: -5.0f, pitchScale: 1f, isLocalSource: false, sourceEntityId: id); + } + } + + private void HandleDropPodEvent(DropPodEvent dpe, int localId, Vector3 listenerPos) + { + var kind = (DropPodEventKind)dpe.Kind; + Vector3 pos = new(dpe.X, dpe.Y, dpe.Z); + bool isLocal = dpe.ContenderId == localId; + + switch (kind) + { + case DropPodEventKind.WaveAnnounced: + if (dpe.WaveIndex > 0 || dpe.RespawnsClosed) + { + PlayUi("ui_drop_wave", volumeDb: -3.5f, pitchScale: dpe.RespawnsClosed ? 0.85f : 1.0f); + } + break; + + case DropPodEventKind.PodLaunched: + if (isLocal) + { + PlayUi("pod_petal_pop", volumeDb: -7.5f, pitchScale: 0.72f); + } + break; + + case DropPodEventKind.PodRetroBurnStart: + PlayOneShot3D( + "impact_explosion", + pos, + listenerPos, + isLocal ? PriorityLocalAction : PriorityNearCombat, + volumeDb: isLocal ? -3.0f : -6.5f, + pitchScale: 0.68f, + isLocalSource: isLocal, + sourceEntityId: dpe.PodId); + break; + + case DropPodEventKind.PodTouchdownBlowPetals: + RecordExplosionPoint(dpe.X, dpe.Z); + int prio = isLocal ? PriorityLocalAction : PriorityLocalImpactOrKill; + PlayOneShot3D( + "pod_slam", + pos, + listenerPos, + prio, + volumeDb: isLocal ? -0.5f : -4.0f, + pitchScale: NextPitchJitter(0.94f, 1.06f), + isLocalSource: isLocal, + sourceEntityId: dpe.PodId); + PlayOneShot3D( + "pod_petal_pop", + pos, + listenerPos, + prio, + volumeDb: isLocal ? -1.5f : -5.5f, + pitchScale: NextPitchJitter(0.95f, 1.05f), + isLocalSource: isLocal, + sourceEntityId: dpe.PodId); + break; + } + } + + private void HandleOrdnanceNodeEvent(OrdnanceNodeEvent ord, int localId, Vector3 listenerPos) + { + var dedupeKey = (ord.Kind, ord.ShooterId, ord.NodeDefIndex); + if (_ordnanceDedupeExpiry.TryGetValue(dedupeKey, out float expiry) && _audioTime < expiry) + { + DedupedCount++; + return; + } + _ordnanceDedupeExpiry[dedupeKey] = _audioTime + 0.065f; + PruneExpiredMap(_ordnanceDedupeExpiry); + + OrdnanceNodeDef? def = null; + if (ord.WeaponKey is { } wk) + { + var spec = ProceduralWeaponGenerator.Generate(wk); + def = ord.NodeDefIndex < spec.FlattenedNodes.Length ? spec.FlattenedNodes[ord.NodeDefIndex] : spec.RootNode; + } + + var kind = (OrdnanceEventKind)ord.Kind; + bool isLocal = !ord.IsSpectatorShooter && ord.ShooterId == localId; + Vector3 pos = new(ord.PosX, ord.PosY, ord.PosZ); + float distSq = pos.DistanceSquaredTo(listenerPos); + int priority = isLocal + ? PriorityLocalAction + : (distSq <= 90f * 90f ? PriorityNearCombat : PriorityDistantCombat); + + string? clipKey = null; + float volDb = isLocal ? -2.0f : -4.2f; + float pitch = NextPitchJitter(0.94f, 1.06f); + uint v = _variantCounter++; + + switch (kind) + { + case OrdnanceEventKind.Spawned: + if (ord.ParentOrdnanceId != 0) + { + return; // Split event already provides audio cue + } + clipKey = SelectAudioClassClip(def?.AudioClass ?? OrdnanceAudioClass.RocketSalvo, v); + break; + + case OrdnanceEventKind.StageTransition: + if (def?.Motion is OrdnanceMotion.RocketBoosted or OrdnanceMotion.HomingMissile) + { + clipKey = (v & 1) == 0 ? "rocket_salvo_01" : "rocket_salvo_02"; + volDb = isLocal ? -1.5f : -3.5f; + } + else if (def?.Motion == OrdnanceMotion.LoiterOrbit) + { + clipKey = "pd_laser"; + pitch = NextPitchJitter(1.12f, 1.24f); + volDb = -5.5f; + } + else if (def?.Motion == OrdnanceMotion.StationaryMine) + { + clipKey = "mech_quick_bolt"; + pitch = NextPitchJitter(1.25f, 1.38f); + volDb = -6.5f; + } + break; + + case OrdnanceEventKind.Split: + clipKey = (v & 1) == 0 ? "flak_blast_01" : "pod_petal_pop"; + volDb = isLocal ? -2.5f : -4.5f; + break; + + case OrdnanceEventKind.Detonated: + if (def?.AudioClass == OrdnanceAudioClass.PlasmaPpc) + { + clipKey = "plasma_ppc_02"; + } + else + { + clipKey = "impact_explosion"; + RecordExplosionPoint(pos.X, pos.Z); + } + volDb = isLocal ? -2.0f : -3.8f; + break; + + case OrdnanceEventKind.Intercepted: + clipKey = "mech_eject"; + volDb = -5.5f; + break; + } + + if (!string.IsNullOrEmpty(clipKey)) + { + PlayOneShot3D(clipKey, pos, listenerPos, priority, volDb, pitch, isLocal, ord.ShooterId); + } + } + + private static string SelectAudioClassClip(OrdnanceAudioClass audioClass, uint variant) => audioClass switch + { + OrdnanceAudioClass.CannonLight => (variant & 1) == 0 ? "ac_light_01" : "ac_light_02", + OrdnanceAudioClass.CannonHeavy => (variant & 1) == 0 ? "cannon_heavy_01" : "cannon_heavy_02", + OrdnanceAudioClass.RocketSalvo => (variant & 1) == 0 ? "rocket_salvo_01" : "rocket_salvo_02", + OrdnanceAudioClass.LaserHeavy => "laser_heavy_01", + OrdnanceAudioClass.GaussRail => "gauss_rail_01", + OrdnanceAudioClass.PlasmaPpc => (variant & 1) == 0 ? "plasma_ppc_01" : "plasma_ppc_02", + _ => "rocket_salvo_01" + }; + + private void UpdateLoopSlots(IClientArenaSession session, Vector3 listenerPos, float alpha) + { + var state = session.ViewState; + int localId = session.LocalContenderId; + + // Slot 0: Local player continuous engine / rotor / mech servo / drop-pod retro loop + var local = session.LocalContender; + if (local.IsInDropPod) + { + var (pPos, _, _) = session.GetInterpolatedContenderPose(localId, alpha); + Vector3 pos = new(pPos.X, pPos.Y, pPos.Z); + OrbitalPod? localPod = null; + var pods = session.ActivePods; + for (int i = 0; i < pods.Count; i++) + { + if (pods[i].PodKind == OrbitalPodKind.Contender && pods[i].ContenderId == localId) + { + localPod = pods[i]; + break; + } + } + bool burning = localPod?.Phase == OrbitalPodPhase.RetroBurn; + AssignLoopSlot( + 0, + isContender: true, + localId, + "pod_retro_burn", + pos, + distSq: 0f, + volumeDb: burning ? -1.5f : -13.5f, + pitchScale: burning ? 0.96f : 1.42f); + } + else if (local.IsGroundedActive) + { + var (pPos, _, pVel) = session.GetInterpolatedContenderPose(localId, alpha); + Vector3 pos = new(pPos.X, pPos.Y, pPos.Z); + float speed = MathF.Sqrt(pVel.X * pVel.X + pVel.Z * pVel.Z); + ComputeLoopParams(local.Grid.Spec, speed, local.ThrottleCmd, local.VerticalThrottleCmd, out string clipKey, out float volDb, out float pitch); + AssignLoopSlot(0, isContender: true, localId, clipKey, pos, distSq: 0f, volDb, pitch); + } + else + { + SilenceLoopSlot(0); + } + + // Slots 1..4: nearest 4 live rivals/spectators/burning-pods within 160m (with 12m hysteresis) + _loopCandidates.Clear(); + float maxDistSq = MaxLoopDistance * MaxLoopDistance; + + var contenders = state.Contenders; + for (int i = 0; i < contenders.Count; i++) + { + var c = contenders[i]; + if (c.Id == localId || !c.IsGroundedActive || !session.IsContenderVisible(c.Id)) continue; + var (cPos, _, cVel) = session.GetInterpolatedContenderPose(c.Id, alpha); + Vector3 pos = new(cPos.X, cPos.Y, cPos.Z); + float distSq = pos.DistanceSquaredTo(listenerPos); + if (distSq > maxDistSq) continue; + + float speed = MathF.Sqrt(cVel.X * cVel.X + cVel.Z * cVel.Z); + ComputeLoopParams(c.Grid.Spec, speed, c.ThrottleCmd, c.VerticalThrottleCmd, out string clipKey, out float volDb, out float pitch); + if (volDb <= -50f) continue; + + // Apply 12m hysteresis bonus if currently held in slots 1..4 + float scoreDistSq = IsHeldInRemoteLoopSlots(true, c.Id) + ? MathF.Max(0f, distSq - LoopHysteresisMeters * LoopHysteresisMeters) + : distSq; + _loopCandidates.Add(new LoopCandidate(true, c.Id, clipKey, pos, scoreDistSq, volDb - 3.5f, pitch)); + } + + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive || !session.IsSpectatorVisible(s.Id)) continue; + var (sPos, _, sVel) = session.GetInterpolatedSpectatorPose(s.Id, alpha); + Vector3 pos = new(sPos.X, sPos.Y, sPos.Z); + float distSq = pos.DistanceSquaredTo(listenerPos); + if (distSq > maxDistSq) continue; + + float speed = MathF.Sqrt(sVel.X * sVel.X + sVel.Z * sVel.Z); + ComputeLoopParams(s.Grid.Spec, speed, 0.5f, 0f, out string clipKey, out float volDb, out float pitch); + if (volDb <= -50f) continue; + + float scoreDistSq = IsHeldInRemoteLoopSlots(false, s.Id) + ? MathF.Max(0f, distSq - LoopHysteresisMeters * LoopHysteresisMeters) + : distSq; + _loopCandidates.Add(new LoopCandidate(false, s.Id, clipKey, pos, scoreDistSq, volDb - 4.0f, pitch)); + } + + var activePods = session.ActivePods; + for (int i = 0; i < activePods.Count; i++) + { + var pod = activePods[i]; + if (pod.Phase != OrbitalPodPhase.RetroBurn || (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId == localId)) + { + continue; + } + Vector3 pos = new(pod.X, pod.Y, pod.Z); + float distSq = pos.DistanceSquaredTo(listenerPos); + if (distSq > maxDistSq) continue; + int candId = 100000 + pod.PodId; + float scoreDistSq = IsHeldInRemoteLoopSlots(false, candId) + ? MathF.Max(0f, distSq - LoopHysteresisMeters * LoopHysteresisMeters) + : distSq; + _loopCandidates.Add(new LoopCandidate(false, candId, "pod_retro_burn", pos, scoreDistSq, -4.5f, 1.0f)); + } + + _loopCandidates.Sort((a, b) => a.DistSq.CompareTo(b.DistSq)); + int assigned = Math.Min(LoopVoiceCount - 1, _loopCandidates.Count); + for (int i = 0; i < assigned; i++) + { + var cand = _loopCandidates[i]; + AssignLoopSlot(1 + i, cand.IsContender, cand.EntityId, cand.ClipKey, cand.Position, cand.DistSq, cand.VolumeDb, cand.PitchScale); + } + for (int i = assigned; i < LoopVoiceCount - 1; i++) + { + SilenceLoopSlot(1 + i); + } + } + + private bool IsHeldInRemoteLoopSlots(bool isContender, int entityId) + { + for (int i = 1; i < LoopVoiceCount; i++) + { + if (_loopSlots[i].Active && _loopSlots[i].IsContender == isContender && _loopSlots[i].EntityId == entityId) + { + return true; + } + } + return false; + } + + private static void ComputeLoopParams( + ChassisSpec spec, + float speed, + float throttle, + float verticalThrottle, + out string clipKey, + out float volumeDb, + out float pitchScale) + { + float maxSpd = MathF.Max(6f, spec.MaxSpeed); + float speedRatio = Math.Clamp(speed / maxSpd, 0f, 1.3f); + float load = MathF.Max(speedRatio, MathF.Abs(throttle) * 0.65f); + + if (spec.IsWalker) + { + clipKey = "loop_mech_servo"; + // Fade mech hydraulic servo cleanly toward -60 dB when stationary + volumeDb = load < 0.04f ? -60f : Math.Clamp(-22f + load * 12f, -45f, -9f); + pitchScale = Math.Clamp(0.86f + speedRatio * 0.36f, 0.78f, 1.32f); + } + else if (spec.IsVtol) + { + clipKey = "loop_rotor_vtol"; + float liftBoost = MathF.Abs(verticalThrottle) * 0.35f; + volumeDb = Math.Clamp(-13f + (load + liftBoost) * 6.5f, -15f, -4f); + pitchScale = Math.Clamp(0.92f + speedRatio * 0.25f + liftBoost * 0.16f, 0.85f, 1.35f); + } + else if (spec.Mobility == MobilityKind.Tracked) + { + clipKey = "loop_engine_tracked"; + volumeDb = Math.Clamp(-16f + load * 8.5f, -18f, -6f); + pitchScale = Math.Clamp(0.78f + speedRatio * 0.50f, 0.72f, 1.42f); + } + else + { + clipKey = "loop_engine_wheeled"; + volumeDb = Math.Clamp(-17f + load * 8.5f, -19f, -7f); + pitchScale = Math.Clamp(0.80f + speedRatio * 0.56f, 0.74f, 1.48f); + } + } + + private void AssignLoopSlot( + int slotIdx, + bool isContender, + int entityId, + string clipKey, + Vector3 pos, + float distSq, + float volumeDb, + float pitchScale) + { + ref LoopSlot slot = ref _loopSlots[slotIdx]; + if (!_bank.TryGetStream(clipKey, out var stream)) + { + return; + } + + bool streamChanged = !slot.Active || !string.Equals(slot.ClipKey, clipKey, StringComparison.Ordinal); + slot.Active = true; + slot.IsContender = isContender; + slot.EntityId = entityId; + slot.ClipKey = clipKey; + slot.DistSq = distSq; + slot.VolumeDb = volumeDb; + slot.PitchScale = pitchScale; + + slot.Player.GlobalPosition = pos; + slot.Player.VolumeDb = volumeDb; + slot.Player.PitchScale = pitchScale; + if (streamChanged) + { + slot.Player.Stream = stream; + } + if (!_isDummyAudio && (streamChanged || !slot.Player.Playing)) + { + slot.Player.Play(); + } + } + + private void SilenceLoopSlot(int slotIdx) + { + ref LoopSlot slot = ref _loopSlots[slotIdx]; + if (!slot.Active) + { + return; + } + slot.Active = false; + slot.EntityId = -1; + slot.ClipKey = string.Empty; + slot.VolumeDb = -60f; + if (!_isDummyAudio && slot.Player.Playing) + { + slot.Player.Stop(); + } + } + + public bool PlayOneShot3D( + string clipKey, + Vector3 worldPos, + Vector3 listenerPos, + int priority, + float volumeDb, + float pitchScale, + bool isLocalSource, + int sourceEntityId) + { + EnsureInitialized(); + Total3DPlaysRequested++; + + float distSq = worldPos.DistanceSquaredTo(listenerPos); + if (distSq > MaxAudioDistance * MaxAudioDistance) + { + RejectedDistanceCount++; + return false; + } + + if (!_bank.TryGetStream(clipKey, out var stream)) + { + return false; + } + + int chosenIdx = -1; + long oldestIdleOrStealableSeq = long.MaxValue; + int lowestStealablePriority = priority; + + // First look for an inactive slot + for (int i = 0; i < _oneShotSlots.Length; i++) + { + if (!_oneShotSlots[i].Active) + { + chosenIdx = i; + break; + } + } + + // If full, strictly steal ONLY from a lower-priority slot (never steals from >= priority) + bool stealing = false; + if (chosenIdx < 0) + { + for (int i = 0; i < _oneShotSlots.Length; i++) + { + int slotPrio = _oneShotSlots[i].Priority; + if (slotPrio < lowestStealablePriority || + (slotPrio == lowestStealablePriority && slotPrio < priority && _oneShotSlots[i].AssignedSeq < oldestIdleOrStealableSeq)) + { + lowestStealablePriority = slotPrio; + oldestIdleOrStealableSeq = _oneShotSlots[i].AssignedSeq; + chosenIdx = i; + stealing = true; + } + } + } + + if (chosenIdx < 0) + { + return false; + } + + if (stealing) + { + StolenVoiceCount++; + } + + float dur = MathF.Max(0.10f, (float)stream.GetLength()); + ref OneShotSlot slot = ref _oneShotSlots[chosenIdx]; + slot.Active = true; + slot.Priority = priority; + slot.AssignedSeq = _voiceSeq++; + slot.DurationSec = dur; + slot.RemainingSec = dur / MathF.Max(0.25f, pitchScale); + slot.ClipKey = clipKey; + slot.IsLocalSource = isLocalSource; + slot.SourceEntityId = sourceEntityId; + slot.LastPitch = pitchScale; + slot.LastVolumeDb = volumeDb; + + slot.Player.Stream = stream; + slot.Player.GlobalPosition = worldPos; + slot.Player.VolumeDb = volumeDb; + slot.Player.PitchScale = pitchScale; + if (!_isDummyAudio) + { + slot.Player.Play(); + } + + LastAllocatedClipKey = clipKey; + LastAllocatedPitch = pitchScale; + return true; + } + + public bool PlayUi(string clipKey, float volumeDb = -3.0f, float pitchScale = 1.0f) + { + EnsureInitialized(); + if (!_bank.TryGetStream(clipKey, out var stream)) + { + return false; + } + + int chosenIdx = -1; + long oldestSeq = long.MaxValue; + for (int i = 0; i < _uiSlots.Length; i++) + { + if (!_uiSlots[i].Active) + { + chosenIdx = i; + break; + } + if (_uiSlots[i].AssignedSeq < oldestSeq) + { + oldestSeq = _uiSlots[i].AssignedSeq; + chosenIdx = i; + } + } + + if (chosenIdx < 0) + { + chosenIdx = 0; + } + + float dur = MathF.Max(0.08f, (float)stream.GetLength()); + ref UiSlot slot = ref _uiSlots[chosenIdx]; + slot.Active = true; + slot.AssignedSeq = _voiceSeq++; + slot.RemainingSec = dur / MathF.Max(0.25f, pitchScale); + slot.ClipKey = clipKey; + + slot.Player.Stream = stream; + slot.Player.VolumeDb = volumeDb; + slot.Player.PitchScale = pitchScale; + if (!_isDummyAudio) + { + slot.Player.Play(); + } + return true; + } + + private void AdvanceVoices(float dt) + { + if (dt <= 0f) + { + return; + } + + for (int i = 0; i < _oneShotSlots.Length; i++) + { + ref OneShotSlot slot = ref _oneShotSlots[i]; + if (!slot.Active) continue; + slot.RemainingSec -= dt; + if (slot.RemainingSec <= 0f || (!_isDummyAudio && !slot.Player.Playing && slot.RemainingSec < slot.DurationSec - 0.05f)) + { + slot.Active = false; + slot.Priority = 0; + slot.RemainingSec = 0f; + } + } + + for (int i = 0; i < _uiSlots.Length; i++) + { + ref UiSlot slot = ref _uiSlots[i]; + if (!slot.Active) continue; + slot.RemainingSec -= dt; + if (slot.RemainingSec <= 0f || (!_isDummyAudio && !slot.Player.Playing)) + { + slot.Active = false; + slot.RemainingSec = 0f; + } + } + } + + private string SelectWeaponClipKey(string? weaponId, WeaponVisualClass weaponClass) + { + uint v = _variantCounter++; + if (ProceduralWeaponGenerator.TryParseId(weaponId, out ProceduralWeaponKey pKey)) + { + var spec = ProceduralWeaponGenerator.Generate(pKey); + return SelectAudioClassClip(spec.AudioClass, v); + } + + string id = (weaponId ?? string.Empty).ToLowerInvariant(); + return id switch + { + "mg_762" => (v & 1) == 0 ? "mg_shot_01" : "mg_shot_02", + "autocannon" => (v % 4) switch + { + 0 => "ac_light_01", + 1 => "ac_light_02", + 2 => "ac_med_01", + _ => "ac_rotary" + }, + "flak" => (v & 1) == 0 ? "flak_blast_01" : "flak_blast_02", + "pd_flak" => (v & 1) == 0 ? "pd_bark_01" : "pd_bark_02", + "aegis_pd" => "pd_laser", + "recoilless" => (v & 1) == 0 ? "cannon_heavy_01" : "cannon_heavy_02", + "touring_plasma" => (v & 1) == 0 ? "plasma_ppc_01" : "plasma_ppc_02", + "gilded_lance" => "lance_beam_01", + "rocket_pod" or "missile_pod" or "srm" or "mrm" => (v & 1) == 0 ? "rocket_salvo_01" : "rocket_salvo_02", + "laser_heavy" or "heavy_laser" => "laser_heavy_01", + "gauss" or "gauss_rifle" => "gauss_rail_01", + _ => weaponClass switch + { + WeaponVisualClass.Autocannon => "ac_light_01", + WeaponVisualClass.Explosive => "cannon_heavy_01", + WeaponVisualClass.ThermalBeam => "lance_beam_01", + WeaponVisualClass.GaussRail => "gauss_rail_01", + WeaponVisualClass.PlasmaPpc => (v & 1) == 0 ? "plasma_ppc_01" : "plasma_ppc_02", + WeaponVisualClass.RocketSalvo => (v & 1) == 0 ? "rocket_salvo_01" : "rocket_salvo_02", + WeaponVisualClass.SwarmSmart => "pd_laser", + _ => "mg_shot_01" + } + }; + } + + private static bool IsImperialDrop(MatchState state, int dropId) + { + for (int i = 0; i < state.GroundDrops.Count; i++) + { + var d = state.GroundDrops[i]; + if (d.Id == dropId) + { + return d.Module is { IsImperial: true } || + (d.Chassis is { } cs && (cs.Id == "paladin" || cs.Id == "spectre" || cs.Id == "kestrel" || cs.Id == "condor")); + } + } + return false; + } + + private void RecordExplosionPoint(float x, float z) + { + _recentExplosionPoints.Add((x, z, _audioTime + 0.08f)); + if (_recentExplosionPoints.Count > 24) + { + _recentExplosionPoints.RemoveAt(0); + } + } + + private bool HasRecentExplosionNear(float x, float z, float radius) + { + float rSq = radius * radius; + for (int i = _recentExplosionPoints.Count - 1; i >= 0; i--) + { + var p = _recentExplosionPoints[i]; + if (_audioTime > p.Expiry) + { + _recentExplosionPoints.RemoveAt(i); + continue; + } + float dx = p.X - x; + float dz = p.Z - z; + if (dx * dx + dz * dz <= rSq) + { + return true; + } + } + return false; + } + + private void PruneExpiredMap(Dictionary dict) where TKey : notnull + { + if (dict.Count <= 64) return; + var toRemove = new List(); + foreach (var kv in dict) + { + if (_audioTime >= kv.Value) toRemove.Add(kv.Key); + } + for (int i = 0; i < toRemove.Count; i++) + { + dict.Remove(toRemove[i]); + } + } + + private float NextPitchJitter(float min, float max) + { + _rng ^= _rng << 13; + _rng ^= _rng >> 17; + _rng ^= _rng << 5; + float u = (_rng & 0xFFFFu) / 65535f; + return min + (max - min) * u; + } +} diff --git a/client/ArenaRenderer.cs b/client/ArenaRenderer.cs new file mode 100644 index 0000000..e7d6e46 --- /dev/null +++ b/client/ArenaRenderer.cs @@ -0,0 +1,1663 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Renders the 3D arena entities from : +/// cover ruins, shrinking Safe Circle ring, unified for all +/// 15 Brokkr vehicles/mechs, mounted gear, salvage drops, and tumbling debris, +/// live 1-draw-call combat scars, and pooled multi-class weapon VFX. +/// +public partial class ArenaRenderer : Node3D +{ + private static readonly Color OlivePaint = Color.FromHtml("#9bb06a"); + private static readonly Color TouristGold = Color.FromHtml("#e6b838"); + private static readonly Color CyanSalvage = Color.FromHtml("#44d9e8"); + private static readonly Color CoverRust = Color.FromHtml("#4d433b"); + private static readonly Color BermDark = Color.FromHtml("#2c2723"); + + private sealed class ActorVisual + { + public required VehicleVisualInstance Visual; + public MeshInstance3D? HaloMesh; + public StandardMaterial3D? HaloMat; + public SpectatorStance? LastHaloStance; + public float RigDtAccum; + public int RigSkipFrames; + } + + private sealed class DropVisualEntry + { + public VehicleVisualInstance? ChassisVisual; + public ArrayMesh? GearMesh; + public VehicleVisualInstance.ModularWeaponPartBinding[]? ModularParts; + public float ManufacturerRoleIndex; + public Color DropBeaconColor; + public Vector3 GearScale; + public float GearYOffset; + public bool IsModule; + public bool IsImperial; + public float BaseY; + public int TileX; + public int TileZ; + public int TileVersion; + } + + private enum VfxShape + { + Beam, + Sphere, + Ring + } + + private struct TransientVfx + { + public VfxShape Shape; + public Vector3 Position; + public Vector3 Velocity; + public Basis BaseRotation; + public Vector3 StartScale; + public Vector3 EndScale; + public Color ColorStart; + public Color ColorEnd; + public float Age; + public float Lifetime; + } + + private const int MaxVfxBeams = 512; + private const int MaxVfxSpheres = 64; + private const int MaxVfxRings = 128; + + private VehicleAssetCache _assetCache = null!; + private Node3D _staticGroup = null!; + private Node3D _actorsGroup = null!; + private MultiMeshPartPool _partPool = null!; + private PomDecalPool _pomDecals = null!; + private DebrisSystem _debris = null!; + private ParticlePool _particles = null!; + private readonly VolumetricEmitterPool _volumetrics = new(); + private GpuSparksSystem _gpuSparks = null!; + private MeshInstance3D _safeRingMesh = null!; + private ImmediateMesh _safeRingImm = null!; + + // Pooled GroundDrop beacons & pillars + private MultiMesh _dropDiscMm = null!; + private MultiMeshInstance3D _dropDiscMmi = null!; + private MultiMesh _dropPillarMm = null!; + private MultiMeshInstance3D _dropPillarMmi = null!; + + // Pooled weapon VFX MultiMeshes (analytic volumetric capsule beams, optional spheres, shockwave rings) + private ShaderMaterial _vfxMat = null!; + private ShaderMaterial _vfxBeamMat = null!; + private MultiMesh _vfxBeamMm = null!; + private MultiMeshInstance3D _vfxBeamMmi = null!; + private MultiMesh _vfxSphereMm = null!; + private MultiMeshInstance3D _vfxSphereMmi = null!; + private MultiMesh _vfxRingMm = null!; + private MultiMeshInstance3D _vfxRingMmi = null!; + private readonly List _transientVfx = new(128); + private readonly ClientOrdnanceMirror _ordnanceMirror = new(); + private readonly List<(Transform3D Xf, Color Col)> _mirrorSpheres = new(32); + private readonly List<(Transform3D Xf, Color Col)> _mirrorRings = new(128); + private readonly List _mirrorBeams = new(64); + private int _activeBeamCount; + + // Continuous emitter rate limiters (keyed by (IsContender, EntityId)) + private readonly Dictionary<(bool IsContender, int Id), float> _tireDustNextTime = new(); + private readonly Dictionary<(bool IsContender, int Id), float> _thermalVentNextTime = new(); + private readonly Dictionary<(bool IsContender, int Id), float> _damageSmokeNextTime = new(); + private readonly Dictionary _podStreakNextTime = new(); + private readonly Dictionary _podRetroNextTime = new(); + private long _lastPodEventId; + private float _vfxClock; + + private readonly Dictionary _contenderVisuals = new(); + private readonly Dictionary _spectatorVisuals = new(); + private readonly Dictionary _dropVisuals = new(); + + private StandardMaterial3D _safeRingMat = null!; + private StandardMaterial3D _coverMat = null!; + private StandardMaterial3D _bermMat = null!; + private StandardMaterial3D _imperialBeaconMat = null!; + private MatchState? _builtForState; + private float _lastSafeRingRadius = -1f; + + public VehicleAssetCache AssetCache => _assetCache; + public DebrisSystem Debris => _debris; + public ParticlePool Particles => _particles; + public VolumetricEmitterPool Volumetrics => _volumetrics; + public GpuSparksSystem GpuSparks => _gpuSparks; + internal MultiMeshPartPool PartPool => _partPool; + internal PomDecalPool PomDecals => _pomDecals; + internal ClientOrdnanceMirror OrdnanceMirror => _ordnanceMirror; + + public VehicleVisualInstance? GetContenderVisual(int contenderId) => + _contenderVisuals.TryGetValue(contenderId, out var vis) ? vis.Visual : null; + + public VehicleVisualInstance? GetSpectatorVisual(int spectatorId) => + _spectatorVisuals.TryGetValue(spectatorId, out var vis) ? vis.Visual : null; + + internal float? GetSpectatorHaloLocalY(int spectatorId) => + _spectatorVisuals.TryGetValue(spectatorId, out var vis) && vis.HaloMesh is not null + ? vis.HaloMesh.Position.Y + : null; + + internal int ActiveDropVisualCount => _dropVisuals.Count; + internal int TransientVfxCount => _transientVfx.Count; + + internal bool TryGetChassisDropVisual(int dropId, out VehicleVisualInstance? visual, out float baseY) + { + if (_dropVisuals.TryGetValue(dropId, out var entry) && entry.ChassisVisual is not null) + { + visual = entry.ChassisVisual; + baseY = entry.BaseY; + return true; + } + visual = null; + baseY = 0f; + return false; + } + + public override void _Ready() + { + _assetCache = new VehicleAssetCache(); + + _staticGroup = new Node3D { Name = "StaticArena" }; + _actorsGroup = new Node3D { Name = "Actors" }; + _partPool = new MultiMeshPartPool { Name = "PartPool" }; + _pomDecals = new PomDecalPool { Name = "PomDecals" }; + _debris = new DebrisSystem { Name = "Debris" }; + _particles = new ParticlePool { Name = "ParticlePool" }; + _gpuSparks = new GpuSparksSystem { Name = "GpuSparks" }; + _particles.BindTargets(_volumetrics, _gpuSparks); + AddChild(_staticGroup); + AddChild(_actorsGroup); + AddChild(_partPool); + AddChild(_pomDecals); + AddChild(_debris); + AddChild(_particles); + AddChild(_gpuSparks); + + _coverMat = new StandardMaterial3D { AlbedoColor = CoverRust, Roughness = 0.88f, Metallic = 0.25f }; + _bermMat = new StandardMaterial3D { AlbedoColor = BermDark, Roughness = 0.94f, Metallic = 0.1f }; + _imperialBeaconMat = new StandardMaterial3D + { + AlbedoColor = new Color(TouristGold.R, TouristGold.G, TouristGold.B, 0.82f), + Roughness = 0.35f, + Metallic = 0.8f, + EmissionEnabled = true, + Emission = TouristGold, + EmissionEnergyMultiplier = 1.4f, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha + }; + + _safeRingImm = new ImmediateMesh(); + _safeRingMat = new StandardMaterial3D + { + AlbedoColor = new Color(1.0f, 0.38f, 0.14f, 0.78f), + EmissionEnabled = true, + Emission = new Color(1.0f, 0.32f, 0.08f), + EmissionEnergyMultiplier = 1.6f, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha, + ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, + CullMode = BaseMaterial3D.CullModeEnum.Disabled + }; + _safeRingMesh = new MeshInstance3D + { + Name = "SafeRing", + Mesh = _safeRingImm, + MaterialOverride = _safeRingMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + AddChild(_safeRingMesh); + + InitPooledVfxAndBeacons(); + } + + private void InitPooledVfxAndBeacons() + { + var vfxShader = new Shader + { + Code = """ + shader_type spatial; + render_mode unshaded, cull_back, blend_mix, depth_draw_never; + varying vec4 v_inst; + void vertex() { + v_inst = INSTANCE_CUSTOM; + } + void fragment() { + ALBEDO = max(v_inst.rgb, vec3(0.0)); + ALPHA = clamp(v_inst.a, 0.0, 1.0); + } + """ + }; + _vfxMat = new ShaderMaterial { Shader = vfxShader }; + + Shader beamShader = GD.Load("res://volumetric_capsule_beam.gdshader") + ?? throw new InvalidOperationException("Failed to load res://volumetric_capsule_beam.gdshader"); + _vfxBeamMat = new ShaderMaterial { Shader = beamShader }; + + _vfxBeamMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseColors = true, + UseCustomData = true, + Mesh = new BoxMesh { Size = Vector3.One }, + InstanceCount = MaxVfxBeams, + VisibleInstanceCount = 0 + }; + _vfxBeamMmi = new MultiMeshInstance3D + { + Name = "VfxBeams", + Multimesh = _vfxBeamMm, + MaterialOverride = _vfxBeamMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + Visible = false + }; + AddChild(_vfxBeamMmi); + + _vfxSphereMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = new SphereMesh { Radius = 0.5f, Height = 1.0f, RadialSegments = 10, Rings = 5 }, + InstanceCount = MaxVfxSpheres, + VisibleInstanceCount = 0 + }; + _vfxSphereMmi = new MultiMeshInstance3D + { + Name = "VfxSpheres", + Multimesh = _vfxSphereMm, + MaterialOverride = _vfxMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + Visible = false + }; + AddChild(_vfxSphereMmi); + + _vfxRingMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = new TorusMesh { InnerRadius = 0.38f, OuterRadius = 0.50f, Rings = 16, RingSegments = 6 }, + InstanceCount = MaxVfxRings, + VisibleInstanceCount = 0 + }; + _vfxRingMmi = new MultiMeshInstance3D + { + Name = "VfxRings", + Multimesh = _vfxRingMm, + MaterialOverride = _vfxMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + Visible = false + }; + AddChild(_vfxRingMmi); + + _dropDiscMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = new CylinderMesh { TopRadius = 0.72f, BottomRadius = 0.85f, Height = 0.14f, RadialSegments = 14 }, + InstanceCount = 128, + VisibleInstanceCount = 0 + }; + _dropDiscMmi = new MultiMeshInstance3D + { + Name = "DropBeaconDiscs", + Multimesh = _dropDiscMm, + MaterialOverride = _vfxMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + Visible = false + }; + AddChild(_dropDiscMmi); + + _dropPillarMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = false, + Mesh = new CylinderMesh { TopRadius = 0.06f, BottomRadius = 0.22f, Height = 5.5f, RadialSegments = 8 }, + InstanceCount = 64, + VisibleInstanceCount = 0 + }; + _dropPillarMmi = new MultiMeshInstance3D + { + Name = "ImperialDropPillars", + Multimesh = _dropPillarMm, + MaterialOverride = _imperialBeaconMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + Visible = false + }; + AddChild(_dropPillarMmi); + } + + public override void _ExitTree() + { + _assetCache?.Dispose(); + } + + public void Sync(IClientArenaSession session, float elapsedSeconds, float dt = 1f / 60f, float alpha = 1f) + { + var state = session.ViewState; + if (!ReferenceEquals(_builtForState, state)) + { + RebuildStaticArena(state); + ClearDynamicVisuals(); + _builtForState = state; + } + + Camera3D? cam = GetViewport()?.GetCamera3D(); + bool hasCam = cam is not null && cam.IsInsideTree(); + Vector3 camPos = hasCam ? cam!.GlobalPosition : Vector3.Zero; + + _partPool.BeginFrame(hasCam ? cam : null); + UpdateSafeCircleRing(state.Terrain, state.Spectators.SafeRadius); + SyncContenders(session, dt, alpha, hasCam, camPos); + SyncSpectators(session, elapsedSeconds, dt, alpha, hasCam, camPos); + SyncGroundDrops(state, elapsedSeconds, hasCam, camPos); + SyncOrbitalPods(session, alpha, hasCam, camPos); + _mirrorSpheres.Clear(); + _mirrorRings.Clear(); + _mirrorBeams.Clear(); + _ordnanceMirror.StepAndSubmit( + dt, + session, + _assetCache, + _partPool, + _particles, + _volumetrics, + state.Terrain, + hasCam, + camPos, + (xf, col) => _mirrorRings.Add((xf, col)), + beam => _mirrorBeams.Add(beam)); + _debris.Step(dt, state.Terrain); + _debris.SubmitToPool(_partPool); + _partPool.EndFrame(); + + SyncTracerBeams(state); + } + + public void ConsumeEvents( + IClientArenaSession session, + IReadOnlyList events, + IReadOnlyList footsteps, + float dt, + Func sampleGroundTint) + { + Camera3D? cam = GetViewport()?.GetCamera3D(); + bool hasCam = cam is not null && cam.IsInsideTree(); + Vector3 camPos = hasCam ? cam!.GlobalPosition : Vector3.Zero; + + float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; + _vfxClock += stepDt; + + var state = session.ViewState; + _pomDecals.ConsumeEvents(session, events, stepDt, ResolveEntityVisual); + _particles.ConsumeEvents(session, events, camPos, hasCam, sampleGroundTint); + _ordnanceMirror.ConsumeEvents( + events, + _assetCache, + _debris, + _particles, + _volumetrics, + hasCam, + camPos, + spec => AddTransient(new TransientVfx + { + Shape = spec.IsSphere ? VfxShape.Sphere : VfxShape.Ring, + Position = spec.Position, + Velocity = spec.Velocity, + BaseRotation = spec.Rotation, + StartScale = spec.StartScale, + EndScale = spec.EndScale, + ColorStart = spec.ColorStart, + ColorEnd = spec.ColorEnd, + Age = 0f, + Lifetime = spec.Lifetime + })); + + for (int i = 0; i < footsteps.Count; i++) + { + FootstepPulse pulse = footsteps[i]; + Color gTint = sampleGroundTint(pulse.WorldPos.X, pulse.WorldPos.Z); + _particles.EmitFootstepDust(in pulse, gTint, camPos, hasCam); + } + + EmitContinuousActorParticles(session, hasCam, camPos, sampleGroundTint); + ConsumeDropPodEvents(session, events, camPos, hasCam); + UpdateExplosiveRingsAndCores(events, stepDt); + _particles.AdvanceAndCommit(stepDt); + _volumetrics.Step(stepDt); + } + + private VehicleVisualInstance? ResolveEntityVisual(bool isContender, int id) => + isContender ? GetContenderVisual(id) : GetSpectatorVisual(id); + + private void RebuildStaticArena(MatchState state) + { + ClearChildren(_staticGroup); + + var quadArrays = new SurfaceTool[4]; + for (int i = 0; i < state.ArenaCoverBoxes.Count; i++) + { + var b = state.ArenaCoverBoxes[i]; + int qIdx = (b.X >= 0f ? 1 : 0) | (b.Z >= 0f ? 2 : 0); + var st = quadArrays[qIdx]; + if (st is null) + { + st = new SurfaceTool(); + st.Begin(Mesh.PrimitiveType.Triangles); + quadArrays[qIdx] = st; + } + AppendBoxToSurfaceTool(st, new Vector3(b.X, b.Y, b.Z), new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f)); + } + + for (int q = 0; q < 4; q++) + { + if (quadArrays[q] is null) continue; + quadArrays[q].GenerateNormals(); + _staticGroup.AddChild(new MeshInstance3D + { + Name = $"CoverQuad_{q}", + Mesh = quadArrays[q].Commit(), + MaterialOverride = _coverMat + }); + } + + if (state.ArenaBoundaryBoxes.Count > 0) + { + var bermSt = new SurfaceTool(); + bermSt.Begin(Mesh.PrimitiveType.Triangles); + for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++) + { + var b = state.ArenaBoundaryBoxes[i]; + AppendBoxToSurfaceTool(bermSt, new Vector3(b.X, b.Y, b.Z), new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f)); + } + bermSt.GenerateNormals(); + _staticGroup.AddChild(new MeshInstance3D + { + Name = "BoundaryBerms", + Mesh = bermSt.Commit(), + MaterialOverride = _bermMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }); + } + } + + private static void AppendBoxToSurfaceTool(SurfaceTool st, Vector3 center, Vector3 size) + { + Vector3 h = size * 0.5f; + Vector3 p000 = center + new Vector3(-h.X, -h.Y, -h.Z); + Vector3 p100 = center + new Vector3( h.X, -h.Y, -h.Z); + Vector3 p110 = center + new Vector3( h.X, h.Y, -h.Z); + Vector3 p010 = center + new Vector3(-h.X, h.Y, -h.Z); + Vector3 p001 = center + new Vector3(-h.X, -h.Y, h.Z); + Vector3 p101 = center + new Vector3( h.X, -h.Y, h.Z); + Vector3 p111 = center + new Vector3( h.X, h.Y, h.Z); + Vector3 p011 = center + new Vector3(-h.X, h.Y, h.Z); + + AddQuad(st, p001, p101, p111, p011); + AddQuad(st, p100, p000, p010, p110); + AddQuad(st, p101, p100, p110, p111); + AddQuad(st, p000, p001, p011, p010); + AddQuad(st, p011, p111, p110, p010); + AddQuad(st, p000, p100, p101, p001); + } + + private static void AddQuad(SurfaceTool st, Vector3 a, Vector3 b, Vector3 c, Vector3 d) + { + st.AddVertex(a); st.AddVertex(b); st.AddVertex(c); + st.AddVertex(a); st.AddVertex(c); st.AddVertex(d); + } + + private void ClearDynamicVisuals() + { + ClearChildren(_actorsGroup); + _partPool.ClearAll(); + _pomDecals.ClearAll(); + _debris.ClearAll(); + _particles.ClearAll(); + _volumetrics.ClearAll(); + _gpuSparks.ClearAll(); + _transientVfx.Clear(); + _ordnanceMirror.Clear(); + _mirrorSpheres.Clear(); + _mirrorRings.Clear(); + _mirrorBeams.Clear(); + _tireDustNextTime.Clear(); + _thermalVentNextTime.Clear(); + _damageSmokeNextTime.Clear(); + _podStreakNextTime.Clear(); + _podRetroNextTime.Clear(); + _lastPodEventId = 0; + _vfxClock = 0f; + _activeBeamCount = 0; + if (_vfxBeamMm is not null) + { + _vfxBeamMm.VisibleInstanceCount = 0; + _vfxBeamMmi.Visible = false; + } + if (_vfxSphereMm is not null) + { + _vfxSphereMm.VisibleInstanceCount = 0; + _vfxSphereMmi.Visible = false; + } + if (_vfxRingMm is not null) + { + _vfxRingMm.VisibleInstanceCount = 0; + _vfxRingMmi.Visible = false; + } + _contenderVisuals.Clear(); + _spectatorVisuals.Clear(); + foreach (var kv in _dropVisuals) + { + if (kv.Value.ChassisVisual is { } cv && GodotObject.IsInstanceValid(cv.Root)) + { + cv.Root.QueueFree(); + } + } + _dropVisuals.Clear(); + _lastSafeRingRadius = -1f; + } + + private void UpdateSafeCircleRing(TerrainField terrain, float safeRadius) + { + if (_lastSafeRingRadius >= 0f && MathF.Abs(safeRadius - _lastSafeRingRadius) < 0.15f) + { + return; + } + _lastSafeRingRadius = safeRadius; + + _safeRingImm.ClearSurfaces(); + _safeRingImm.SurfaceBegin(Mesh.PrimitiveType.Triangles); + + const int segments = 160; + float halfThick = terrain.MapSize > 2000f ? 2.2f : 1.1f; + float rInner = MathF.Max(2f, safeRadius - halfThick); + float rOuter = safeRadius + halfThick; + + for (int i = 0; i < segments; i++) + { + float a0 = (i / (float)segments) * MathF.Tau; + float a1 = ((i + 1) / (float)segments) * MathF.Tau; + float c0 = MathF.Cos(a0), s0 = MathF.Sin(a0); + float c1 = MathF.Cos(a1), s1 = MathF.Sin(a1); + + float x0i = c0 * rInner, z0i = s0 * rInner; + float x0o = c0 * rOuter, z0o = s0 * rOuter; + float x1i = c1 * rInner, z1i = s1 * rInner; + float x1o = c1 * rOuter, z1o = s1 * rOuter; + + float y0 = terrain.SampleHeight(c0 * safeRadius, s0 * safeRadius) + 0.42f; + float y1 = terrain.SampleHeight(c1 * safeRadius, s1 * safeRadius) + 0.42f; + + var p0i = new Vector3(x0i, y0, z0i); + var p0o = new Vector3(x0o, y0, z0o); + var p1i = new Vector3(x1i, y1, z1i); + var p1o = new Vector3(x1o, y1, z1o); + + _safeRingImm.SurfaceAddVertex(p0i); + _safeRingImm.SurfaceAddVertex(p0o); + _safeRingImm.SurfaceAddVertex(p1o); + + _safeRingImm.SurfaceAddVertex(p0i); + _safeRingImm.SurfaceAddVertex(p1o); + _safeRingImm.SurfaceAddVertex(p1i); + } + + _safeRingImm.SurfaceEnd(); + } + + private void SyncContenders(IClientArenaSession session, float dt, float alpha, bool hasCam, Vector3 camPos) + { + var contenders = session.ViewState.Contenders; + int localId = session.LocalContenderId; + + for (int i = 0; i < contenders.Count; i++) + { + var c = contenders[i]; + if (!c.IsGroundedActive || !session.IsContenderVisible(c.Id)) + { + if (_contenderVisuals.TryGetValue(c.Id, out var hiddenVis)) + { + if (!c.IsGroundedActive) + { + hiddenVis.Visual.SyncDamageAndHeat(c.Grid, _debris, Vector3.Zero); + } + hiddenVis.Visual.Root.Visible = false; + } + continue; + } + + if (!_contenderVisuals.TryGetValue(c.Id, out var vis) || vis.Visual.ChassisId != c.Grid.Spec.Id) + { + if (vis is not null) + { + vis.Visual.Root.QueueFree(); + } + + var role = c.Id == localId ? VehicleVisualRole.Player : VehicleVisualRole.Rival; + var instance = VehicleVisualInstance.Create(_assetCache, c.Grid.Spec.Id, role); + instance.SyncMountedGear(c.Grid); + _actorsGroup.AddChild(instance.Root); + vis = new ActorVisual { Visual = instance }; + _contenderVisuals[c.Id] = vis; + } + + vis.Visual.Root.Visible = true; + + var (interpPos, interpRot, interpVel) = session.GetInterpolatedContenderPose(c.Id, alpha); + Vector3 pos = new Vector3(interpPos.X, interpPos.Y, interpPos.Z); + Vector3 vel = new Vector3(interpVel.X, interpVel.Y, interpVel.Z); + var q = new Quaternion(interpRot.X, interpRot.Y, interpRot.Z, interpRot.W); + vis.Visual.Root.Transform = new Transform3D(new Basis(q), pos); + + float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f; + bool castShadows = !hasCam || c.Id == localId || distSq <= 120f * 120f; + bool useStaticLod = hasCam && c.Id != localId && !vis.Visual.HasAnyStrippedCell && + (vis.Visual.IsStaticLod ? distSq > 64f * 64f : distSq > 68f * 68f); + vis.Visual.SetLodState(useStaticLod, castShadows); + + vis.Visual.SyncMountedGear(c.Grid); + if (!useStaticLod) + { + if (!hasCam || c.Id == localId || distSq <= 55f * 55f) + { + vis.RigDtAccum = 0f; + vis.RigSkipFrames = 0; + if (c.Grid.Spec.IsWalker && session.TrySampleInterpolatedWalkerPose(true, c.Id, alpha, out var walkerSnap)) + { + VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, dt, in walkerSnap); + } + else + { + VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, dt); + } + } + else + { + vis.RigDtAccum += dt; + vis.RigSkipFrames++; + if (vis.RigSkipFrames >= 2) + { + if (c.Grid.Spec.IsWalker && session.TrySampleInterpolatedWalkerPose(true, c.Id, alpha, out var walkerSnap)) + { + VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, vis.RigDtAccum, in walkerSnap); + } + else + { + VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, vis.RigDtAccum); + } + vis.RigDtAccum = 0f; + vis.RigSkipFrames = 0; + } + } + } + vis.Visual.SyncDamageAndHeat(c.Grid, _debris, vel); + vis.Visual.SubmitToPool(_partPool); + } + } + + private void SyncSpectators(IClientArenaSession session, float elapsedSeconds, float dt, float alpha, bool hasCam, Vector3 camPos) + { + var specs = session.ViewState.Spectators.Spectators; + + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive || !session.IsSpectatorVisible(s.Id)) + { + if (_spectatorVisuals.TryGetValue(s.Id, out var hiddenVis)) + { + if (!s.Alive) + { + hiddenVis.Visual.SyncDamageAndHeat(s.Grid, _debris, Vector3.Zero); + } + hiddenVis.Visual.Root.Visible = false; + } + continue; + } + + if (!_spectatorVisuals.TryGetValue(s.Id, out var vis)) + { + var role = s.Tier switch + { + SpectatorTier.Tourist => VehicleVisualRole.SpectatorTourist, + SpectatorTier.Patron => VehicleVisualRole.SpectatorPatron, + _ => VehicleVisualRole.SpectatorExemplar + }; + var instance = VehicleVisualInstance.Create( + _assetCache, + s.Grid.Spec.Id, + role, + visualScale: 1f, + targetHalfHeight: s.Grid.Spec.HalfHeight); + instance.SyncMountedGear(s.Grid); + _actorsGroup.AddChild(instance.Root); + vis = CreateSpectatorVisualWrapper(instance); + _spectatorVisuals[s.Id] = vis; + } + + vis.Visual.Root.Visible = true; + var (interpPos, interpRot, interpVel) = session.GetInterpolatedSpectatorPose(s.Id, alpha); + Vector3 specPos = new Vector3(interpPos.X, interpPos.Y, interpPos.Z); + Vector3 vel = new Vector3(interpVel.X, interpVel.Y, interpVel.Z); + var q = new Quaternion(interpRot.X, interpRot.Y, interpRot.Z, interpRot.W); + vis.Visual.Root.Transform = new Transform3D(new Basis(q), specPos); + + vis.Visual.SyncDamageAndHeat(s.Grid, _debris, vel); + + bool useStaticLod = false; + bool castShadows = true; + if (hasCam) + { + float distSq = specPos.DistanceSquaredTo(camPos); + castShadows = distSq <= 120f * 120f; + if (!vis.Visual.HasAnyStrippedCell) + { + useStaticLod = vis.Visual.IsStaticLod ? distSq > 50f * 50f : distSq > 55f * 55f; + } + } + vis.Visual.SetLodState(useStaticLod, castShadows); + + ContenderState? target = s.TargetContenderId.HasValue && + s.TargetContenderId.Value >= 0 && + s.TargetContenderId.Value < session.ViewState.Contenders.Count + ? session.ViewState.Contenders[s.TargetContenderId.Value] + : null; + + if (!useStaticLod) + { + float aimYawWorld = s.Yaw; + float aimPitchDeg = 0f; + if (s.Stance != SpectatorStance.Neutral && target is { Alive: true } && + (target.Id == session.LocalContenderId || session.IsContenderVisible(target.Id))) + { + float tdx = target.X - s.X; + float tdz = target.Z - s.Z; + if (tdx * tdx + tdz * tdz > 0.01f) + { + aimYawWorld = MathF.Atan2(tdx, tdz); + float horiz = MathF.Sqrt(tdx * tdx + tdz * tdz); + float eyeY = MatchRules.GetObserverEyeY(s.Y, s.Grid.Spec.HalfHeight); + float targetY = MatchRules.GetTargetAimY(target.Y, target.Grid.Spec.HalfHeight); + aimPitchDeg = Mathf.RadToDeg(MathF.Atan2(targetY - eyeY, horiz)); + } + } + + var rigInput = new VehicleRigDriveInput( + Velocity: vel, + Yaw: s.Yaw, + AimYawWorld: aimYawWorld, + AimPitchDeg: aimPitchDeg, + SteerCmd: 0f, + ThrottleCmd: vel.Length() > 0.5f ? 0.6f : 0f, + VerticalThrottleCmd: 0f, + EngineThermalPerf: s.Grid.ComputeEngineThermalPerformance(), + DeltaTime: dt, + IsGrounded: !s.Grid.Spec.IsVtol); + + vis.Visual.SyncMountedGear(s.Grid); + if (s.Grid.Spec.IsWalker && session.TrySampleInterpolatedWalkerPose(false, s.Id, alpha, out var walkerSnap)) + { + VehicleRigAnimator.Update(vis.Visual, in rigInput, vis.Visual.Root.Basis, in walkerSnap); + } + else + { + VehicleRigAnimator.Update(vis.Visual, in rigInput, vis.Visual.Root.Basis); + } + } + + vis.Visual.SubmitToPool(_partPool); + + // Status halo + if (vis.HaloMat is not null && vis.HaloMesh is not null && + (vis.LastHaloStance != s.Stance || s.Stance == SpectatorStance.Provoked)) + { + vis.LastHaloStance = s.Stance; + if (s.Stance == SpectatorStance.Neutral) + { + vis.HaloMat.AlbedoColor = new Color(0.88f, 0.65f, 0.25f, 0.45f); + vis.HaloMat.Emission = new Color(0.88f, 0.65f, 0.25f); + vis.HaloMat.EmissionEnergyMultiplier = 0.6f; + } + else if (s.Stance == SpectatorStance.Cleared) + { + vis.HaloMat.AlbedoColor = new Color(1.8f, 0.32f, 0.24f, 0.9f); + vis.HaloMat.Emission = new Color(1.0f, 0.2f, 0.15f); + vis.HaloMat.EmissionEnergyMultiplier = 2.0f; + } + else + { + float pulse = 1.6f + 1.2f * MathF.Sin(elapsedSeconds * 10f); + vis.HaloMat.AlbedoColor = new Color(pulse, 0.14f, 0.12f, 0.95f); + vis.HaloMat.Emission = new Color(1.0f, 0.08f, 0.08f); + vis.HaloMat.EmissionEnergyMultiplier = pulse; + } + } + } + } + + private ActorVisual CreateSpectatorVisualWrapper(VehicleVisualInstance instance) + { + float haloY = MathF.Max(2.4f, instance.ComputeMountedMaxY() + 1.15f); + var haloMat = new StandardMaterial3D + { + ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, + EmissionEnabled = true, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha + }; + var halo = new MeshInstance3D + { + Mesh = new CylinderMesh { TopRadius = 2.4f, BottomRadius = 2.4f, Height = 0.1f, RadialSegments = 16 }, + MaterialOverride = haloMat, + Position = new Vector3(0f, haloY, 0f), + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + instance.Root.AddChild(halo); + + return new ActorVisual + { + Visual = instance, + HaloMesh = halo, + HaloMat = haloMat + }; + } + + private void SyncGroundDrops(MatchState state, float elapsedSeconds, bool hasCam, Vector3 camPos) + { + int discCount = 0; + int pillarCount = 0; + + for (int i = 0; i < state.GroundDrops.Count; i++) + { + var d = state.GroundDrops[i]; + if (d.PickedUp) + { + if (_dropVisuals.TryGetValue(d.Id, out var pickedEntry)) + { + if (pickedEntry.ChassisVisual is { } cv && GodotObject.IsInstanceValid(cv.Root)) + { + cv.Root.GetParent()?.RemoveChild(cv.Root); + cv.Root.QueueFree(); + } + _dropVisuals.Remove(d.Id); + } + continue; + } + + if (!_dropVisuals.TryGetValue(d.Id, out var entry)) + { + state.Terrain.MapWorldToTile(d.X, d.Z, out int tx, out int tz); + float baseY = state.Terrain.SampleHeight(d.X, d.Z); + if (d.Module is { } mod) + { + if (mod.Procedural is { } proc) + { + VehicleVisualInstance.BuildModularWeaponAssembly( + _assetCache, + proc.Assembly, + out var modParts, + out _, + out _, + out float minY); + float sc = proc.Assembly.VisualScale * 1.45f; + entry = new DropVisualEntry + { + IsModule = true, + IsImperial = mod.IsImperial, + ModularParts = modParts, + ManufacturerRoleIndex = 10f + (float)proc.Manufacturer, + DropBeaconColor = ResolveManufacturerBeaconColor(proc.Manufacturer), + GearScale = Vector3.One * sc, + GearYOffset = -minY * sc + 0.35f, + BaseY = baseY, + TileX = tx, + TileZ = tz, + TileVersion = state.Terrain.TileVersions[tx, tz] + }; + } + else + { + VehicleVisualInstance.ResolveDropGearVisual(_assetCache, mod, out ArrayMesh gMesh, out Vector3 gScale, out float gYOff); + entry = new DropVisualEntry + { + IsModule = true, + IsImperial = mod.IsImperial, + GearMesh = gMesh, + DropBeaconColor = mod.IsImperial ? TouristGold * 2.2f : OlivePaint * 1.5f, + GearScale = gScale * 1.45f, + GearYOffset = gYOff * 1.45f + 0.35f, + BaseY = baseY, + TileX = tx, + TileZ = tz, + TileVersion = state.Terrain.TileVersions[tx, tz] + }; + } + } + else + { + var spec = d.Chassis!; + var vis = VehicleVisualInstance.Create( + _assetCache, + spec.Id, + VehicleVisualRole.SalvageDrop, + visualScale: 0.72f); + vis.Root.Position = new Vector3(d.X, baseY + spec.HalfHeight * 0.72f, d.Z); + _actorsGroup.AddChild(vis.Root); + entry = new DropVisualEntry + { + IsModule = false, + ChassisVisual = vis, + BaseY = baseY, + TileX = tx, + TileZ = tz, + TileVersion = state.Terrain.TileVersions[tx, tz] + }; + } + _dropVisuals[d.Id] = entry; + } + else + { + int ver = state.Terrain.TileVersions[entry.TileX, entry.TileZ]; + if (ver != entry.TileVersion) + { + entry.TileVersion = ver; + entry.BaseY = state.Terrain.SampleHeight(d.X, d.Z); + if (entry.ChassisVisual is { } cv) + { + cv.Root.Position = new Vector3(d.X, entry.BaseY + d.Chassis!.HalfHeight * 0.72f, d.Z); + } + } + } + + float distSq = hasCam ? new Vector3(d.X, entry.BaseY, d.Z).DistanceSquaredTo(camPos) : 0f; + if (entry.IsModule) + { + if (hasCam && distSq > 240f * 240f) + { + continue; + } + + float bob = MathF.Sin(elapsedSeconds * 2.5f + d.Id) * 0.12f; + float yaw = elapsedSeconds * 0.9f + d.Id; + + var gearXf = new Transform3D( + new Basis(Vector3.Up, yaw) * Basis.FromScale(entry.GearScale), + new Vector3(d.X, entry.BaseY + bob + entry.GearYOffset, d.Z)); + if (entry.ModularParts is { } modParts) + { + Color custom = new(0f, 0f, entry.ManufacturerRoleIndex, 1f); + for (int p = 0; p < modParts.Length; p++) + { + Transform3D partXf = gearXf * modParts[p].LocalToGearPivot; + _partPool.Submit(modParts[p].Mesh, in partXf, in custom, wantsShadow: false); + } + } + else if (entry.GearMesh is not null) + { + _partPool.Submit(entry.GearMesh, in gearXf, new Color(0f, 0f, 5f, 1f), wantsShadow: false); + } + + if (discCount < _dropDiscMm.InstanceCount) + { + _dropDiscMm.SetInstanceTransform(discCount, new Transform3D(Basis.Identity, new Vector3(d.X, entry.BaseY + bob + 0.08f, d.Z))); + Color beaconLin = entry.DropBeaconColor.SrgbToLinear(); + float boost = entry.IsImperial ? 2.2f : 1.35f; + Color dCol = new(beaconLin.R * boost, beaconLin.G * boost, beaconLin.B * boost, entry.IsImperial ? 0.82f : 0.72f); + _dropDiscMm.SetInstanceCustomData(discCount, dCol); + discCount++; + } + + if (entry.IsImperial && pillarCount < _dropPillarMm.InstanceCount) + { + _dropPillarMm.SetInstanceTransform(pillarCount, new Transform3D(Basis.Identity, new Vector3(d.X, entry.BaseY + bob + 2.9f, d.Z))); + pillarCount++; + } + } + else if (entry.ChassisVisual is { } cv) + { + bool useFarLod = false; + bool castShadows = true; + if (hasCam) + { + useFarLod = cv.IsStaticLod ? distSq > 50f * 50f : distSq > 55f * 55f; + castShadows = distSq <= 120f * 120f; + } + cv.SetLodState(useFarLod, castShadows); + cv.SubmitToPool(_partPool); + + if (discCount < _dropDiscMm.InstanceCount) + { + _dropDiscMm.SetInstanceTransform(discCount, new Transform3D(Basis.FromScale(new Vector3(2.4f, 1f, 2.4f)), new Vector3(d.X, entry.BaseY + 0.06f, d.Z))); + Color cyanLin = CyanSalvage.SrgbToLinear(); + _dropDiscMm.SetInstanceCustomData(discCount, new Color(cyanLin.R * 1.8f, cyanLin.G * 1.8f, cyanLin.B * 1.8f, 0.65f)); + discCount++; + } + } + } + + _dropDiscMm.VisibleInstanceCount = discCount; + _dropDiscMmi.Visible = discCount > 0; + _dropPillarMm.VisibleInstanceCount = pillarCount; + _dropPillarMmi.Visible = pillarCount > 0; + } + + private void SyncOrbitalPods(IClientArenaSession session, float alpha, bool hasCam, Vector3 camPos) + { + var pods = session.ActivePods; + if (pods.Count == 0) + { + return; + } + + var podTpl = _assetCache.GetOrLoadDropPod(); + int localId = session.LocalContenderId; + + for (int i = 0; i < pods.Count; i++) + { + var pod = pods[i]; + if (pod.Phase == OrbitalPodPhase.Popped) + { + continue; + } + + Vector3 pos = new Vector3( + Mathf.Lerp(pod.PrevX, pod.X, alpha), + Mathf.Lerp(pod.PrevY, pod.Y, alpha), + Mathf.Lerp(pod.PrevZ, pod.Z, alpha)); + + var qPrev = new Quaternion(pod.PrevRotX, pod.PrevRotY, pod.PrevRotZ, pod.PrevRotW).Normalized(); + var qCurr = new Quaternion(pod.CurrRotX, pod.CurrRotY, pod.CurrRotZ, pod.CurrRotW).Normalized(); + Quaternion q = qPrev.Slerp(qCurr, alpha); + + Transform3D podXf = BuildPodTransform(pos, q, pod.VelX, pod.VelZ, pod.PodKind); + float roleIdx = ResolvePodRoleIndex(pod.PodKind, pod.ContenderId, localId, pod.WaveIndex, pod.Module?.IsImperial == true); + float heat = pod.Phase == OrbitalPodPhase.RetroBurn + ? 0.28f + : Math.Clamp(pod.HeatGlow * 0.16f, 0f, 0.18f); + float scorch = Math.Clamp(pod.Scorch * 0.7f, 0f, 0.55f); + Color custom = new(scorch, heat, roleIdx, 1f); + + bool wantsShadow = !hasCam || pos.DistanceSquaredTo(camPos) <= 160f * 160f; + _partPool.Submit(podTpl.CoreMesh, in podXf, in custom, wantsShadow); + + for (int p = 0; p < 4; p++) + { + Transform3D petalXf = podXf * podTpl.PetalLocalTransforms[p]; + _partPool.Submit(podTpl.PetalMesh, in petalXf, in custom, wantsShadow: false); + } + } + } + + private static Transform3D BuildPodTransform( + Vector3 pos, + Quaternion baseRot, + float velX, + float velZ, + OrbitalPodKind podKind) + { + Basis basis = new(baseRot); + float horizSpeed = MathF.Sqrt(velX * velX + velZ * velZ); + if (horizSpeed > 0.5f) + { + Vector3 horizDir = new Vector3(velX / horizSpeed, 0f, velZ / horizSpeed); + Vector3 tiltAxis = Vector3.Up.Cross(horizDir); + if (tiltAxis.LengthSquared() > 1e-4f) + { + float tiltRad = Math.Clamp(horizSpeed * 0.0085f, 0f, Mathf.DegToRad(14f)); + basis = new Basis(tiltAxis.Normalized(), tiltRad) * basis; + } + } + float scale = podKind == OrbitalPodKind.Contender ? 1.0f : 0.72f; + if (MathF.Abs(scale - 1.0f) > 1e-3f) + { + basis *= Basis.FromScale(Vector3.One * scale); + } + return new Transform3D(basis, pos); + } + + private static float ResolvePodRoleIndex( + OrbitalPodKind podKind, + int contenderId, + int localId, + int waveIndex, + bool isImperialGear) + { + if (podKind == OrbitalPodKind.Contender) + { + return contenderId == localId ? 0f : 1f; + } + return (waveIndex > 0 || isImperialGear) ? 2f : 5f; + } + + private void ConsumeDropPodEvents( + IClientArenaSession session, + IReadOnlyList events, + Vector3 camPos, + bool hasCam) + { + var state = session.ViewState; + int localId = session.LocalContenderId; + VehicleAssetCache.DropPodTemplate? podTpl = null; + + for (int i = 0; i < events.Count; i++) + { + if (events[i] is not DropPodEvent dpe) + { + continue; + } + if (dpe.EventId <= _lastPodEventId) + { + continue; + } + _lastPodEventId = dpe.EventId; + + if ((DropPodEventKind)dpe.Kind != DropPodEventKind.PodTouchdownBlowPetals) + { + continue; + } + + bool isContender = dpe.PodKind == (byte)OrbitalPodKind.Contender; + bool isLocal = isContender && dpe.ContenderId == localId; + if (isContender && !isLocal && !session.IsContenderVisible(dpe.ContenderId)) + { + continue; + } + + Vector3 pos = new(dpe.X, dpe.Y, dpe.Z); + if (!isLocal && hasCam && pos.DistanceSquaredTo(camPos) > 420f * 420f) + { + continue; + } + + Vector3 normal = new(dpe.NormalX, dpe.NormalY, dpe.NormalZ); + if (normal.LengthSquared() < 1e-4f) normal = Vector3.Up; + normal = normal.Normalized(); + + podTpl ??= _assetCache.GetOrLoadDropPod(); + float yaw = isContender && dpe.ContenderId >= 0 && dpe.ContenderId < state.Contenders.Count + ? state.Contenders[dpe.ContenderId].Yaw + : (dpe.PodId * 1.17f); + Quaternion q = Quaternion.FromEuler(new Vector3(0f, yaw, 0f)); + Transform3D podXf = BuildPodTransform(pos, q, 0f, 0f, (OrbitalPodKind)dpe.PodKind); + + bool isImperial = dpe.WaveIndex > 0 + || (dpe.ModuleId is not null && Catalog.ModulesById.TryGetValue(dpe.ModuleId, out var ms) && ms.IsImperial); + float roleIdx = ResolvePodRoleIndex((OrbitalPodKind)dpe.PodKind, dpe.ContenderId, localId, dpe.WaveIndex, isImperial); + + Vector3 blastOrigin = pos + normal * (isContender ? 1.4f : 1.0f); + float impulseScale = isContender ? 1.15f : 1.65f; + float petalLife = isContender ? 8.0f : 4.5f; + + for (int p = 0; p < 4; p++) + { + Transform3D petalXf = podXf * podTpl.PetalLocalTransforms[p]; + _debris.SpawnDetachedPart( + podTpl.PetalMesh, + petalXf, + blastOrigin, + Vector3.Zero, + roleIdx, + impulseScale: impulseScale, + applyScorch: true, + lifetime: petalLife); + } + + // Touchdown retro shockwave ring (fireball & radial dust handled by VolumetricEmitterPool + GpuSparksSystem) + Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up; + Vector3 right = upRef.Cross(normal).Normalized(); + Vector3 fwd = normal.Cross(right).Normalized(); + Basis ringBasis = new(right, normal, fwd); + AddTransient(new TransientVfx + { + Shape = VfxShape.Ring, + Position = pos + normal * 0.22f, + Velocity = Vector3.Zero, + BaseRotation = ringBasis, + StartScale = new Vector3(1.4f, 1.0f, 1.4f), + EndScale = new Vector3(isContender ? 11.5f : 6.8f, 0.5f, isContender ? 11.5f : 6.8f), + ColorStart = new Color(3.4f, 1.85f, 0.55f, 0.94f), + ColorEnd = new Color(1.1f, 0.45f, 0.16f, 0.0f), + Age = 0f, + Lifetime = isContender ? 0.42f : 0.30f + }); + } + } + + private void SyncTracerBeams(MatchState state) + { + int beamIdx = 0; + var tracers = state.Tracers; + for (int i = 0; i < tracers.Count; i++) + { + var t = tracers[i]; + Vector3 start = new(t.StartX, t.StartY, t.StartZ); + Vector3 end = new(t.EndX, t.EndY, t.EndZ); + if (start.DistanceSquaredTo(end) < 0.01f) + { + continue; + } + + switch (t.WeaponClass) + { + case WeaponVisualClass.KineticLight: + { + bool isPd = string.Equals(t.WeaponId, "pd_flak", StringComparison.Ordinal); + Color col = isPd + ? new Color(3.2f, 1.55f, 0.42f, 0.94f) + : new Color(3.0f, 2.55f, 1.25f, 0.92f); + SubmitCapsuleBeam(ref beamIdx, start, end, isPd ? 0.075f : 0.055f, col, coreSharpness: 3.0f, coreRadiusFrac: 0.36f, tailFade: 1.0f); + break; + } + + case WeaponVisualClass.Autocannon: + SubmitCapsuleBeam(ref beamIdx, start, end, 0.14f, new Color(3.4f, 1.35f, 0.28f, 0.96f), coreSharpness: 2.8f, coreRadiusFrac: 0.36f, tailFade: 1.0f); + break; + + case WeaponVisualClass.Explosive: + { + bool isRecoilless = string.Equals(t.WeaponId, "recoilless", StringComparison.Ordinal); + SubmitCapsuleBeam(ref beamIdx, start, end, isRecoilless ? 0.17f : 0.10f, new Color(3.6f, 1.45f, 0.32f, 0.96f), coreSharpness: 2.6f, coreRadiusFrac: 0.34f, tailFade: 1.0f); + break; + } + + case WeaponVisualClass.ThermalBeam: + { + bool isLance = string.Equals(t.WeaponId, "gilded_lance", StringComparison.Ordinal); + float outerR = isLance ? 0.24f : 0.15f; + Color beamCol = isLance + ? new Color(3.4f, 2.35f, 0.55f, 0.96f) + : new Color(0.55f, 2.80f, 3.60f, 0.96f); + SubmitCapsuleBeam(ref beamIdx, start, end, outerR, beamCol, coreSharpness: 3.2f, coreRadiusFrac: 0.38f, tailFade: 0.0f, pulsePhase: 12f); + break; + } + + case WeaponVisualClass.GaussRail: + SubmitCapsuleBeam(ref beamIdx, start, end, 0.22f, new Color(0.42f, 2.45f, 3.80f, 0.98f), coreSharpness: 3.6f, coreRadiusFrac: 0.34f, tailFade: 0.0f, pulsePhase: 18f); + break; + + case WeaponVisualClass.PlasmaPpc: + SubmitCapsuleBeam(ref beamIdx, start, end, 0.25f, new Color(0.28f, 2.85f, 3.40f, 0.96f), coreSharpness: 2.6f, coreRadiusFrac: 0.40f, tailFade: 0.0f, pulsePhase: 14f); + break; + + case WeaponVisualClass.RocketSalvo: + SubmitCapsuleBeam(ref beamIdx, start, end, 0.16f, new Color(3.6f, 1.65f, 0.38f, 0.94f), coreSharpness: 2.6f, coreRadiusFrac: 0.36f, tailFade: 1.0f); + break; + + case WeaponVisualClass.SwarmSmart: + SubmitCapsuleBeam(ref beamIdx, start, end, 0.12f, new Color(1.65f, 3.20f, 0.58f, 0.95f), coreSharpness: 2.8f, coreRadiusFrac: 0.36f, tailFade: 1.0f); + break; + } + } + + for (int i = 0; i < _mirrorBeams.Count; i++) + { + var b = _mirrorBeams[i]; + SubmitCapsuleBeam(ref beamIdx, b.Start, b.End, b.Radius, b.HdrTint, b.CoreSharpness, b.CoreRadiusFrac, b.TailFade); + } + + _activeBeamCount = beamIdx; + _vfxBeamMm.VisibleInstanceCount = beamIdx; + _vfxBeamMmi.Visible = beamIdx > 0; + } + + private void UpdateExplosiveRingsAndCores(IReadOnlyList events, float stepDt) + { + for (int i = _transientVfx.Count - 1; i >= 0; i--) + { + TransientVfx v = _transientVfx[i]; + v.Age += stepDt; + if (v.Age >= v.Lifetime) + { + _transientVfx.RemoveAt(i); + continue; + } + v.Position += v.Velocity * stepDt; + _transientVfx[i] = v; + } + + for (int i = 0; i < events.Count; i++) + { + if (events[i] is not HitImpactEvent ev) + { + continue; + } + var wClass = (WeaponVisualClass)ev.WeaponClass; + if (ev.IsAirburst || wClass is not (WeaponVisualClass.Explosive or WeaponVisualClass.RocketSalvo or WeaponVisualClass.PlasmaPpc or WeaponVisualClass.SwarmSmart)) + { + continue; + } + + Vector3 pos = new(ev.HitX, ev.HitY, ev.HitZ); + Vector3 normal = new(ev.NormalX, ev.NormalY, ev.NormalZ); + if (normal.LengthSquared() < 1e-4f) normal = Vector3.Up; + normal = normal.Normalized(); + + bool isRecoilless = string.Equals(ev.WeaponId, "recoilless", StringComparison.Ordinal); + float ringSize = isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 6.2f : 3.4f; + Color coreStart = wClass switch + { + WeaponVisualClass.PlasmaPpc => new Color(0.35f, 3.2f, 3.6f, 0.92f), + WeaponVisualClass.SwarmSmart => new Color(1.9f, 3.2f, 0.6f, 0.90f), + _ => new Color(3.6f, 2.0f, 0.55f, 0.92f) + }; + Color coreEnd = wClass switch + { + WeaponVisualClass.PlasmaPpc => new Color(0.10f, 0.55f, 0.85f, 0f), + WeaponVisualClass.SwarmSmart => new Color(0.55f, 0.25f, 0.85f, 0f), + _ => new Color(0.85f, 0.28f, 0.08f, 0f) + }; + + Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up; + Vector3 right = upRef.Cross(normal).Normalized(); + Vector3 fwd = normal.Cross(right).Normalized(); + Basis ringBasis = new(right, normal, fwd); + AddTransient(new TransientVfx + { + Shape = VfxShape.Ring, + Position = pos + normal * 0.18f, + Velocity = Vector3.Zero, + BaseRotation = ringBasis, + StartScale = new Vector3(0.7f, 1.0f, 0.7f), + EndScale = new Vector3(ringSize, 0.4f, ringSize), + ColorStart = coreStart, + ColorEnd = coreEnd, + Age = 0f, + Lifetime = isRecoilless ? 0.32f : 0.24f + }); + } + + int sphereIdx = 0; + int ringIdx = 0; + for (int i = 0; i < _mirrorSpheres.Count && sphereIdx < MaxVfxSpheres; i++) + { + _vfxSphereMm.SetInstanceTransform(sphereIdx, _mirrorSpheres[i].Xf); + _vfxSphereMm.SetInstanceCustomData(sphereIdx, _mirrorSpheres[i].Col); + sphereIdx++; + } + for (int i = 0; i < _mirrorRings.Count && ringIdx < MaxVfxRings; i++) + { + _vfxRingMm.SetInstanceTransform(ringIdx, _mirrorRings[i].Xf); + _vfxRingMm.SetInstanceCustomData(ringIdx, _mirrorRings[i].Col); + ringIdx++; + } + + for (int i = 0; i < _transientVfx.Count; i++) + { + TransientVfx v = _transientVfx[i]; + float frac = Math.Clamp(v.Age / MathF.Max(0.01f, v.Lifetime), 0f, 1f); + Vector3 sc = v.StartScale.Lerp(v.EndScale, frac); + Color col = v.ColorStart.Lerp(v.ColorEnd, frac); + Transform3D xf = new(v.BaseRotation * Basis.FromScale(sc), v.Position); + + if (v.Shape == VfxShape.Sphere && sphereIdx < MaxVfxSpheres) + { + _vfxSphereMm.SetInstanceTransform(sphereIdx, xf); + _vfxSphereMm.SetInstanceCustomData(sphereIdx, col); + sphereIdx++; + } + else if (v.Shape == VfxShape.Ring && ringIdx < MaxVfxRings) + { + _vfxRingMm.SetInstanceTransform(ringIdx, xf); + _vfxRingMm.SetInstanceCustomData(ringIdx, col); + ringIdx++; + } + } + + _vfxSphereMm.VisibleInstanceCount = sphereIdx; + _vfxSphereMmi.Visible = sphereIdx > 0; + _vfxRingMm.VisibleInstanceCount = ringIdx; + _vfxRingMmi.Visible = ringIdx > 0; + } + + private void EmitContinuousActorParticles( + IClientArenaSession session, + bool hasCam, + Vector3 camPos, + Func sampleGroundTint) + { + var state = session.ViewState; + var contenders = state.Contenders; + for (int i = 0; i < contenders.Count; i++) + { + var c = contenders[i]; + if (!c.IsGroundedActive || !session.IsContenderVisible(c.Id)) + { + continue; + } + + Vector3 pos = _contenderVisuals.TryGetValue(c.Id, out var av) + ? av.Visual.Root.GlobalPosition + : new Vector3(c.X, c.Y, c.Z); + if (hasCam && pos.DistanceSquaredTo(camPos) > 125f * 125f) + { + continue; + } + + var key = (true, c.Id); + float coreHpRatio = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 1f; + float thermalRatio = c.MaxThermalRatio > 0f ? c.MaxThermalRatio : c.Grid.ComputeMaxThermalRatio(); + + if ((c.Grid.Spec.Mobility == MobilityKind.Wheeled || c.Grid.Spec.Mobility == MobilityKind.Tracked) && + c.Speed > 8.5f) + { + float nextDust = _tireDustNextTime.GetValueOrDefault(key); + if (_vfxClock >= nextDust) + { + _tireDustNextTime[key] = _vfxClock + 0.09f; // ~11 Hz + float sinY = MathF.Sin(c.Yaw); + float cosY = MathF.Cos(c.Yaw); + Vector3 rearPos = pos - new Vector3(sinY, 0f, cosY) * (c.Grid.Spec.HalfLength * 0.72f); + rearPos.Y = state.Terrain.SampleHeight(rearPos.X, rearPos.Z) + 0.12f; + Vector3 vel = new(c.VelX, 0f, c.VelZ); + _particles.EmitTireDust( + rearPos, + vel, + sampleGroundTint(rearPos.X, rearPos.Z), + Math.Clamp(c.Speed / 16f, 0.7f, 1.35f), + camPos, + hasCam); + } + } + + if (thermalRatio >= 0.85f) + { + float nextVent = _thermalVentNextTime.GetValueOrDefault(key); + if (_vfxClock >= nextVent) + { + _thermalVentNextTime[key] = _vfxClock + 0.13f; // ~7.7 Hz + Vector3 ventPos = ResolveHotAnchorWorld(av?.Visual, c.Grid, pos, c.Grid.Spec.HalfHeight); + _particles.EmitThermalVent(ventPos, thermalRatio, camPos, hasCam); + } + } + + if (coreHpRatio < 0.35f) + { + float nextSmoke = _damageSmokeNextTime.GetValueOrDefault(key); + if (_vfxClock >= nextSmoke) + { + _damageSmokeNextTime[key] = _vfxClock + 0.13f; // ~7.7 Hz + Vector3 dmgPos = pos + new Vector3(0f, c.Grid.Spec.HalfHeight * 0.6f, 0f); + _particles.EmitDamageSmokeAndFire(dmgPos, coreHpRatio, camPos, hasCam); + } + } + } + + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive || !session.IsSpectatorVisible(s.Id)) + { + continue; + } + + Vector3 pos = _spectatorVisuals.TryGetValue(s.Id, out var av) + ? av.Visual.Root.GlobalPosition + : new Vector3(s.X, s.Y, s.Z); + if (hasCam && pos.DistanceSquaredTo(camPos) > 125f * 125f) + { + continue; + } + + var key = (false, s.Id); + float coreHpRatio = s.Grid.MaxCoreHp > 0f ? s.Grid.CoreHp / s.Grid.MaxCoreHp : 1f; + float thermalRatio = s.Grid.ComputeMaxThermalRatio(); + + if (thermalRatio >= 0.85f) + { + float nextVent = _thermalVentNextTime.GetValueOrDefault(key); + if (_vfxClock >= nextVent) + { + _thermalVentNextTime[key] = _vfxClock + 0.11f; + Vector3 ventPos = ResolveHotAnchorWorld(av?.Visual, s.Grid, pos, s.Grid.Spec.HalfHeight); + _particles.EmitThermalVent(ventPos, thermalRatio, camPos, hasCam); + } + } + + if (coreHpRatio < 0.35f) + { + float nextSmoke = _damageSmokeNextTime.GetValueOrDefault(key); + if (_vfxClock >= nextSmoke) + { + _damageSmokeNextTime[key] = _vfxClock + 0.11f; + Vector3 dmgPos = pos + new Vector3(0f, s.Grid.Spec.HalfHeight * 0.6f, 0f); + _particles.EmitDamageSmokeAndFire(dmgPos, coreHpRatio, camPos, hasCam); + } + } + } + + var pods = session.ActivePods; + int localId = session.LocalContenderId; + for (int i = 0; i < pods.Count; i++) + { + var pod = pods[i]; + if (pod.Phase == OrbitalPodPhase.Popped) + { + continue; + } + bool isContender = pod.PodKind == OrbitalPodKind.Contender; + bool isLocal = isContender && pod.ContenderId == localId; + Vector3 podPos = new(pod.X, pod.Y, pod.Z); + if (pod.Phase == OrbitalPodPhase.RetroBurn) + { + float nextBurn = _podRetroNextTime.GetValueOrDefault(pod.PodId); + if (_vfxClock >= nextBurn) + { + _podRetroNextTime[pod.PodId] = _vfxClock + (isLocal ? 0.045f : 0.065f); + _particles.EmitPodRetroBurn( + podPos, + pod.LastAgl, + sampleGroundTint(pod.X, pod.Z), + isContender, + isLocal, + camPos, + hasCam); + } + } + else if (pod.HeatGlow > 0.12f) + { + float nextStreak = _podStreakNextTime.GetValueOrDefault(pod.PodId); + if (_vfxClock >= nextStreak) + { + _podStreakNextTime[pod.PodId] = _vfxClock + 0.085f; + Vector3 podVel = new(pod.VelX, pod.VelY, pod.VelZ); + _particles.EmitPodReentryStreak(podPos, podVel, pod.HeatGlow, isContender, camPos, hasCam); + } + } + } + } + + private static Vector3 ResolveHotAnchorWorld(VehicleVisualInstance? vis, ChassisGrid grid, Vector3 fallbackPos, float halfHeight) + { + if (vis is not null && !vis.IsStaticLod) + { + var hps = grid.Spec.Hardpoints; + for (int i = 0; i < hps.Length; i++) + { + if (hps[i].Kind == HardpointKind.Radiator || hps[i].Kind == HardpointKind.Engine) + { + Node3D? anchor = vis.GetHardpointAnchorNode(hps[i].Id); + if (anchor is not null && GodotObject.IsInstanceValid(anchor) && anchor.IsInsideTree()) + { + return anchor.GlobalPosition; + } + } + } + } + return fallbackPos + new Vector3(0f, halfHeight * 0.7f, 0f); + } + + private void SubmitCapsuleBeam( + ref int beamIdx, + Vector3 start, + Vector3 end, + float outerRadius, + Color hdrTint, + float coreSharpness, + float coreRadiusFrac, + float tailFade, + float pulsePhase = 0f) + { + if (beamIdx >= MaxVfxBeams) + { + return; + } + + Vector3 delta = end - start; + float len = delta.Length(); + Vector3 dir = len > 0.01f ? delta / len : Vector3.Forward; + Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; + Basis lookBasis = Basis.LookingAt(dir, up); + Vector3 mid = (start + end) * 0.5f; + float r = MathF.Max(0.01f, outerRadius); + Vector3 scale = new(2f * r, 2f * r, len + 2f * r); + + _vfxBeamMm.SetInstanceTransform(beamIdx, new Transform3D(lookBasis * Basis.FromScale(scale), mid)); + _vfxBeamMm.SetInstanceColor(beamIdx, hdrTint); + _vfxBeamMm.SetInstanceCustomData(beamIdx, new Color(coreSharpness, coreRadiusFrac, tailFade, pulsePhase)); + beamIdx++; + } + + private void AddTransient(in TransientVfx vfx) + { + if (_transientVfx.Count >= 256) + { + _transientVfx.RemoveAt(0); + } + _transientVfx.Add(vfx); + } + + private static Color ResolveManufacturerBeaconColor(ManufacturerId mfg) => mfg switch + { + ManufacturerId.ScrapFrontier => new Color(2.1f, 1.35f, 0.40f, 0.82f), + ManufacturerId.KorrathiIronworks => new Color(2.6f, 1.15f, 0.22f, 0.86f), + ManufacturerId.AuralianOptics => new Color(0.55f, 2.25f, 2.65f, 0.86f), + ManufacturerId.VexNineCollective => new Color(1.45f, 2.55f, 0.45f, 0.86f), + ManufacturerId.ThalassanForge => new Color(0.35f, 1.95f, 2.85f, 0.86f), + _ => TouristGold * 2.2f + }; + + private static void ClearChildren(Node parent) + { + for (int i = parent.GetChildCount() - 1; i >= 0; i--) + { + Node ch = parent.GetChild(i); + parent.RemoveChild(ch); + ch.QueueFree(); + } + } +} diff --git a/client/AtmosphereLutBaker.cs b/client/AtmosphereLutBaker.cs new file mode 100644 index 0000000..5d18af7 --- /dev/null +++ b/client/AtmosphereLutBaker.cs @@ -0,0 +1,684 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Deterministic CPU precomputation of Bruneton / Hillaire planetary atmospheric scattering LUTs +/// (Transmittance 256x64, MultiScattering 32x32, SkyView 256x128 in +/// ), plus matching solar irradiance and horizon haze evaluation. +/// Zero Vulkan compute dependency so headless (Dummy) tests and Forward+ share identical data. +/// +public static class AtmosphereLutBaker +{ + public const int TransmittanceWidth = 256; + public const int TransmittanceHeight = 64; + public const int MultiScatteringSize = 32; + public const int SkyViewWidth = 256; + public const int SkyViewHeight = 128; + + public const float PlanetRadiusM = 6_360_000f; + public const float AtmosphereRadiusM = 6_460_000f; + public const float AtmosphereHeightM = AtmosphereRadiusM - PlanetRadiusM; + + private const float RayleighScaleHeightM = 8_000f; + private static readonly Vector3 RayleighScattering = new(5.802e-6f, 13.558e-6f, 33.100e-6f); + private const float MieSingleScatterAlbedo = 0.90f; + private static readonly Vector3 OzoneAbsorption = new(0.650e-6f, 1.881e-6f, 0.085e-6f); + private static readonly Vector3 GroundAlbedo = new(0.28f, 0.24f, 0.20f); + + public sealed record AtmospherePreset( + ArenaMapKind MapKind, + float AltitudeMeters, + float SunPitchDeg, + float SunYawDeg, + float MieScaleHeightMeters, + Vector3 MieScattering, + float MieG, + float SolarIrradiance, + float CalibratedSunEnergy, + float FogMaxLengthMeters, + float VolumetricFogDensity, + float VolumetricFogDetailSpread, + float VolumetricFogAnisotropy, + float VolumetricFogEmissionEnergy, + Vector3 ValleyVolumeSize, + Vector3 ValleyVolumePosition, + float ValleyVolumeDensity, + float ValleyVolumeHeightFalloff, + float ValleyVolumeEdgeFade, + float DepthFogBegin, + float DepthFogEnd, + float DepthFogCurve, + float DepthFogDensity, + float DepthFogAerialPerspective, + float DepthFogSunScatter, + float ShadowMaxDistance, + float AmbientLightEnergy, + float SunDiscIntensity, + float MieAureoleStrength); + + public sealed class BakedAtmosphere + { + public required AtmospherePreset Preset { get; init; } + public required Image TransmittanceImage { get; init; } + public required Image MultiScatteringImage { get; init; } + public required Image SkyViewImage { get; init; } + public required ImageTexture TransmittanceTexture { get; init; } + public required ImageTexture MultiScatteringTexture { get; init; } + public required ImageTexture SkyViewTexture { get; init; } + public required Vector3 SunDirection { get; init; } + public required Vector3 SunTransmittance { get; init; } + public required Color SunLightColor { get; init; } + public required float SunLightEnergy { get; init; } + public required Color HazeColor { get; init; } + public required float ZenithTransmittanceMean { get; init; } + public required float HorizonElevationRad { get; init; } + } + + private static readonly Dictionary Cache = new(); + + public static AtmospherePreset GetPreset(ArenaMapKind mapKind) => mapKind == ArenaMapKind.Sion + ? new AtmospherePreset( + MapKind: ArenaMapKind.Sion, + AltitudeMeters: 490f, + SunPitchDeg: -36f, + SunYawDeg: 28f, + MieScaleHeightMeters: 1_200f, + MieScattering: new Vector3(3.2e-6f, 3.2e-6f, 3.2e-6f), + MieG: 0.78f, + SolarIrradiance: 17.5f, + CalibratedSunEnergy: 2.85f, + FogMaxLengthMeters: 460f, + VolumetricFogDensity: 0.0008f, + VolumetricFogDetailSpread: 2.4f, + VolumetricFogAnisotropy: 0.62f, + VolumetricFogEmissionEnergy: 0f, + ValleyVolumeSize: new Vector3(3100f, 110f, 3100f), + ValleyVolumePosition: new Vector3(0f, 20f, 0f), + ValleyVolumeDensity: 0.0038f, + ValleyVolumeHeightFalloff: 1.65f, + ValleyVolumeEdgeFade: 0.12f, + DepthFogBegin: 400f, + DepthFogEnd: 2950f, + DepthFogCurve: 0.85f, + DepthFogDensity: 0.36f, + DepthFogAerialPerspective: 0.88f, + DepthFogSunScatter: 0.45f, + ShadowMaxDistance: 320f, + AmbientLightEnergy: 0.0f, + SunDiscIntensity: 8.5f, + MieAureoleStrength: 0.24f) + : new AtmospherePreset( + MapKind: ArenaMapKind.Desert, + AltitudeMeters: 200f, + SunPitchDeg: -22f, + SunYawDeg: 36f, + MieScaleHeightMeters: 1_800f, + MieScattering: new Vector3(10.5e-6f, 8.8e-6f, 6.6e-6f), + MieG: 0.74f, + SolarIrradiance: 16.0f, + CalibratedSunEnergy: 2.55f, + FogMaxLengthMeters: 380f, + VolumetricFogDensity: 0.0012f, + VolumetricFogDetailSpread: 2.2f, + VolumetricFogAnisotropy: 0.68f, + VolumetricFogEmissionEnergy: 0f, + ValleyVolumeSize: new Vector3(1600f, 56f, 1600f), + ValleyVolumePosition: new Vector3(0f, 2f, 0f), + ValleyVolumeDensity: 0.0052f, + ValleyVolumeHeightFalloff: 1.85f, + ValleyVolumeEdgeFade: 0.15f, + DepthFogBegin: 260f, + DepthFogEnd: 840f, + DepthFogCurve: 0.85f, + DepthFogDensity: 0.84f, + DepthFogAerialPerspective: 0.22f, + DepthFogSunScatter: 0.65f, + ShadowMaxDistance: 280f, + AmbientLightEnergy: 0.0f, + SunDiscIntensity: 8.0f, + MieAureoleStrength: 0.30f); + + public static BakedAtmosphere GetOrBake(ArenaMapKind mapKind) + { + if (Cache.TryGetValue(mapKind, out var cached)) + { + return cached; + } + + var baked = BakePreset(GetPreset(mapKind)); + Cache[mapKind] = baked; + return baked; + } + + public static Vector3 ComputeSunDirection(float pitchDeg, float yawDeg) + { + Basis basis = Basis.FromEuler(new Vector3(Mathf.DegToRad(pitchDeg), Mathf.DegToRad(yawDeg), 0f), EulerOrder.Yxz); + // DirectionalLight3D shines along -Z; direction toward the sun is +Z. + return basis.Z.Normalized(); + } + + private static BakedAtmosphere BakePreset(AtmospherePreset preset) + { + Vector3[] transmittanceBuf = BakeTransmittanceBuffer(preset); + Vector3[] multiScatterBuf = BakeMultiScatteringBuffer(preset, transmittanceBuf); + Vector3 sunDir = ComputeSunDirection(preset.SunPitchDeg, preset.SunYawDeg); + float r0 = PlanetRadiusM + preset.AltitudeMeters; + float horizonElev = -MathF.Acos(Math.Clamp(PlanetRadiusM / r0, -1f, 1f)); + Vector3[] skyViewBuf = BakeSkyViewBuffer(preset, transmittanceBuf, multiScatterBuf, sunDir, r0, horizonElev); + + Image transImg = CreateRgbahImage(TransmittanceWidth, TransmittanceHeight, transmittanceBuf); + Image msImg = CreateRgbahImage(MultiScatteringSize, MultiScatteringSize, multiScatterBuf); + Image skyImg = CreateRgbahImage(SkyViewWidth, SkyViewHeight, skyViewBuf); + + Vector3 sunT = SampleTransmittanceLut(transmittanceBuf, r0, sunDir.Y); + Vector3 zenithT = SampleTransmittanceLut(transmittanceBuf, r0, 1.0f); + float zenithMean = (zenithT.X + zenithT.Y + zenithT.Z) / 3f; + + Color sunColor = DeriveSunLightColor(sunT); + float sunEnergy = DeriveSunLightEnergy(preset, sunT); + Color hazeColor = DeriveHorizonHazeColor(preset, skyViewBuf, sunT); + + return new BakedAtmosphere + { + Preset = preset, + TransmittanceImage = transImg, + MultiScatteringImage = msImg, + SkyViewImage = skyImg, + TransmittanceTexture = ImageTexture.CreateFromImage(transImg), + MultiScatteringTexture = ImageTexture.CreateFromImage(msImg), + SkyViewTexture = ImageTexture.CreateFromImage(skyImg), + SunDirection = sunDir, + SunTransmittance = sunT, + SunLightColor = sunColor, + SunLightEnergy = sunEnergy, + HazeColor = hazeColor, + ZenithTransmittanceMean = zenithMean, + HorizonElevationRad = horizonElev + }; + } + + private static Color DeriveSunLightColor(Vector3 sunT) + { + float maxC = MathF.Max(1e-4f, MathF.Max(sunT.X, MathF.Max(sunT.Y, sunT.Z))); + Vector3 norm = sunT / maxC; + return new Color( + Math.Clamp(norm.X, 0.1f, 1.0f), + Math.Clamp(norm.Y, 0.1f, 1.0f), + Math.Clamp(norm.Z, 0.1f, 1.0f), + 1.0f); + } + + private static float DeriveSunLightEnergy(AtmospherePreset preset, Vector3 sunT) + { + float luma = sunT.X * 0.2126f + sunT.Y * 0.7152f + sunT.Z * 0.0722f; + float refLuma = preset.MapKind == ArenaMapKind.Sion ? 0.86f : 0.68f; + float ratio = Math.Clamp(luma / refLuma, 0.92f, 1.08f); + return preset.CalibratedSunEnergy * ratio; + } + + private static Color DeriveHorizonHazeColor(AtmospherePreset preset, Vector3[] skyViewBuf, Vector3 sunT) + { + // Integrate SkyView across the low horizon dust/haze band (+0.5 deg .. +3.5 deg above horizon) + // weighting solar-side Mie scatter slightly higher so chromaticity reflects mineral dust vs alpine air, + // then scale uniformly to <= 0.88 without channel clipping. + Vector3 accum = Vector3.Zero; + float weightSum = 0f; + int yStart = SkyViewHeight / 2 + 2; + int yEnd = Math.Min(SkyViewHeight - 1, SkyViewHeight / 2 + 12); + bool warmDust = preset.MieScattering.X > preset.MieScattering.Z * 1.15f; + + for (int y = yStart; y <= yEnd; y++) + { + for (int x = 0; x < SkyViewWidth; x++) + { + float dphi = ((x + 0.5f) / SkyViewWidth) * 2f * MathF.PI; + float solarBias = warmDust ? (0.65f + 1.35f * MathF.Max(0f, MathF.Cos(dphi))) : 1.0f; + accum += skyViewBuf[y * SkyViewWidth + x] * solarBias; + weightSum += solarBias; + } + } + + Vector3 mean = weightSum > 0f ? accum / weightSum : new Vector3(0.55f, 0.62f, 0.72f); + if (warmDust) + { + // Blend in forward-scattered Mie dust + attenuated solar spectrum so dusty air keeps warm R > G > B chromaticity + float mieMax = MathF.Max(1e-6f, MathF.Max(preset.MieScattering.X, MathF.Max(preset.MieScattering.Y, preset.MieScattering.Z))); + Vector3 mieTint = preset.MieScattering / mieMax; + Vector3 dustChroma = new Vector3(mieTint.X * sunT.X, mieTint.Y * sunT.Y, mieTint.Z * sunT.Z); + float meanMax = MathF.Max(1e-4f, MathF.Max(mean.X, MathF.Max(mean.Y, mean.Z))); + float dustMax = MathF.Max(1e-4f, MathF.Max(dustChroma.X, MathF.Max(dustChroma.Y, dustChroma.Z))); + Vector3 meanUnit = mean / meanMax; + Vector3 dustUnit = dustChroma / dustMax; + mean = meanUnit.Lerp(dustUnit, 0.52f); + } + + float peak = MathF.Max(1e-4f, MathF.Max(mean.X, MathF.Max(mean.Y, mean.Z))); + Vector3 norm = mean * (0.88f / peak); + return new Color( + Math.Clamp(norm.X, 0.18f, 0.90f), + Math.Clamp(norm.Y, 0.18f, 0.90f), + Math.Clamp(norm.Z, 0.18f, 0.90f), + 1.0f); + } + + private static Vector3[] BakeTransmittanceBuffer(AtmospherePreset preset) + { + var buf = new Vector3[TransmittanceWidth * TransmittanceHeight]; + float H = MathF.Sqrt(AtmosphereRadiusM * AtmosphereRadiusM - PlanetRadiusM * PlanetRadiusM); + const int steps = 36; + + for (int y = 0; y < TransmittanceHeight; y++) + { + float v = (y + 0.5f) / TransmittanceHeight; + float rho = H * v; + float r = MathF.Sqrt(rho * rho + PlanetRadiusM * PlanetRadiusM); + float dMin = AtmosphereRadiusM - r; + float dMax = rho + H; + + for (int x = 0; x < TransmittanceWidth; x++) + { + float u = (x + 0.5f) / TransmittanceWidth; + float d = dMin + u * (dMax - dMin); + float mu = d <= 1e-3f ? 1f : Math.Clamp((H * H - rho * rho - d * d) / (2f * r * d), -1f, 1f); + + float stepLen = d / steps; + Vector3 opticalDepth = Vector3.Zero; + for (int i = 0; i < steps; i++) + { + float t = (i + 0.5f) * stepLen; + float ri = MathF.Sqrt(MathF.Max(PlanetRadiusM * PlanetRadiusM, r * r + t * t + 2f * r * t * mu)); + float hi = MathF.Max(0f, ri - PlanetRadiusM); + opticalDepth += EvaluateExtinction(preset, hi) * stepLen; + } + + buf[y * TransmittanceWidth + x] = new Vector3( + MathF.Exp(-opticalDepth.X), + MathF.Exp(-opticalDepth.Y), + MathF.Exp(-opticalDepth.Z)); + } + } + + return buf; + } + + private static Vector3[] BakeMultiScatteringBuffer(AtmospherePreset preset, Vector3[] transBuf) + { + var buf = new Vector3[MultiScatteringSize * MultiScatteringSize]; + const int dirCount = 64; + const int marchSteps = 20; + const float goldenRatio = 1.618033988749895f; + + Vector3[] dirs = new Vector3[dirCount]; + for (int i = 0; i < dirCount; i++) + { + float theta = 2f * MathF.PI * i / goldenRatio; + float z = 1f - 2f * (i + 0.5f) / dirCount; + float rxy = MathF.Sqrt(MathF.Max(0f, 1f - z * z)); + dirs[i] = new Vector3(rxy * MathF.Cos(theta), z, rxy * MathF.Sin(theta)); + } + + for (int y = 0; y < MultiScatteringSize; y++) + { + float v = (y + 0.5f) / MultiScatteringSize; + float r = PlanetRadiusM + v * AtmosphereHeightM; + Vector3 pos = new(0f, r, 0f); + + for (int x = 0; x < MultiScatteringSize; x++) + { + float u = (x + 0.5f) / MultiScatteringSize; + float muS = u * 2f - 1f; + Vector3 sunDir = new(MathF.Sqrt(MathF.Max(0f, 1f - muS * muS)), muS, 0f); + + Vector3 l2Sum = Vector3.Zero; + Vector3 fmsSum = Vector3.Zero; + + for (int d = 0; d < dirCount; d++) + { + Vector3 rayDir = dirs[d]; + float maxDist = RaySphereExit(r, rayDir.Y, out bool hitGround); + if (maxDist <= 0f) + { + continue; + } + + float dt = maxDist / marchSteps; + Vector3 throughput = Vector3.One; + Vector3 l2 = Vector3.Zero; + Vector3 fms = Vector3.Zero; + + for (int s = 0; s < marchSteps; s++) + { + float t = (s + 0.5f) * dt; + Vector3 p = pos + rayDir * t; + float ri = p.Length(); + float hi = MathF.Max(0f, ri - PlanetRadiusM); + + SampleMedia(preset, hi, out Vector3 sigmaS, out Vector3 sigmaE); + Vector3 stepT = new( + MathF.Exp(-sigmaE.X * dt), + MathF.Exp(-sigmaE.Y * dt), + MathF.Exp(-sigmaE.Z * dt)); + + Vector3 up = p / MathF.Max(1f, ri); + float muSunAtP = up.Dot(sunDir); + if (!HitsPlanet(ri, muSunAtP)) + { + Vector3 tSun = SampleTransmittanceLut(transBuf, ri, muSunAtP); + // Hillaire 2020 §5.2: 1st-bounce isotropic phase 1/(4*PI); 2nd-bounce 1/(4*PI) cancels 4*PI/dirCount + const float phaseIso = 1f / (4f * MathF.PI); + Vector3 scatterIn = sigmaS * tSun * phaseIso; + Vector3 sInt = SafeScatterIntegral(scatterIn, stepT, sigmaE, dt); + l2 += throughput * sInt; + } + + Vector3 fmsInt = SafeScatterIntegral(sigmaS, stepT, sigmaE, dt); + fms += throughput * fmsInt; + throughput *= stepT; + } + + if (hitGround) + { + Vector3 gp = pos + rayDir * maxDist; + Vector3 gUp = gp.Normalized(); + float nDotL = MathF.Max(0f, gUp.Dot(sunDir)); + if (nDotL > 0f) + { + Vector3 tGroundSun = SampleTransmittanceLut(transBuf, PlanetRadiusM, nDotL); + l2 += throughput * tGroundSun * GroundAlbedo * (nDotL / MathF.PI); + } + } + + l2Sum += l2; + fmsSum += fms; + } + + Vector3 l2Avg = l2Sum / dirCount; + Vector3 fmsAvg = fmsSum / dirCount; + Vector3 psi = new( + l2Avg.X / MathF.Max(0.02f, 1f - MathF.Min(0.98f, fmsAvg.X)), + l2Avg.Y / MathF.Max(0.02f, 1f - MathF.Min(0.98f, fmsAvg.Y)), + l2Avg.Z / MathF.Max(0.02f, 1f - MathF.Min(0.98f, fmsAvg.Z))); + buf[y * MultiScatteringSize + x] = psi; + } + } + + return buf; + } + + private static Vector3[] BakeSkyViewBuffer( + AtmospherePreset preset, + Vector3[] transBuf, + Vector3[] msBuf, + Vector3 sunDir, + float r0, + float horizonElev) + { + var buf = new Vector3[SkyViewWidth * SkyViewHeight]; + const int steps = 28; + Vector3 viewPos = new(0f, r0, 0f); + + Vector2 sunXz = new(sunDir.X, sunDir.Z); + if (sunXz.LengthSquared() < 1e-6f) + { + sunXz = new Vector2(0f, 1f); + } + else + { + sunXz = sunXz.Normalized(); + } + Vector2 sunPerp = new(sunXz.Y, -sunXz.X); + + Vector3 horizonGroundAlbedo = preset.MapKind == ArenaMapKind.Desert + ? new Vector3(0.48f, 0.33f, 0.20f) + : GroundAlbedo; + + // Bake upper hemisphere first (y = SkyViewHeight/2 .. SkyViewHeight-1) so below-horizon rows + // can smoothly transition from exact horizon limb radiance without a hard shoreline step. + for (int pass = 0; pass < 2; pass++) + { + int yBegin = pass == 0 ? SkyViewHeight / 2 : 0; + int yFinish = pass == 0 ? SkyViewHeight : SkyViewHeight / 2; + + for (int y = yBegin; y < yFinish; y++) + { + float v = (y + 0.5f) / SkyViewHeight; + float elev; + if (v >= 0.5f) + { + float l = 2f * v - 1f; + elev = horizonElev + l * l * (MathF.PI * 0.5f - horizonElev); + } + else + { + float l = 1f - 2f * v; + elev = horizonElev - l * l * (MathF.PI * 0.5f + horizonElev); + } + + float cosElev = MathF.Cos(elev); + float sinElev = MathF.Sin(elev); + + for (int x = 0; x < SkyViewWidth; x++) + { + float u = (x + 0.5f) / SkyViewWidth; + float dphi = u * 2f * MathF.PI; + Vector2 dirXz = sunXz * MathF.Cos(dphi) + sunPerp * MathF.Sin(dphi); + Vector3 rayDir = new Vector3(dirXz.X * cosElev, sinElev, dirXz.Y * cosElev).Normalized(); + + float maxDist = RaySphereExit(r0, rayDir.Y, out bool hitGround); + if (maxDist <= 0f) + { + buf[y * SkyViewWidth + x] = Vector3.Zero; + continue; + } + + float cosTheta = rayDir.Dot(sunDir); + float phaseR = RayleighPhase(cosTheta); + float phaseM = CornetteShanksPhase(cosTheta, preset.MieG); + + float dt = maxDist / steps; + Vector3 throughput = Vector3.One; + Vector3 luminance = Vector3.Zero; + + for (int s = 0; s < steps; s++) + { + float t = (s + 0.5f) * dt; + Vector3 p = viewPos + rayDir * t; + float ri = p.Length(); + float hi = MathF.Max(0f, ri - PlanetRadiusM); + + SampleRayleighMie(preset, hi, out Vector3 sigR, out Vector3 sigM, out Vector3 sigE); + Vector3 stepT = new( + MathF.Exp(-sigE.X * dt), + MathF.Exp(-sigE.Y * dt), + MathF.Exp(-sigE.Z * dt)); + + Vector3 up = p / MathF.Max(1f, ri); + float muSun = up.Dot(sunDir); + + Vector3 sunVis = HitsPlanet(ri, muSun) + ? Vector3.Zero + : SampleTransmittanceLut(transBuf, ri, muSun); + Vector3 multiScatter = SampleMultiScatteringLut(msBuf, ri, muSun); + + Vector3 sigS = sigR + sigM; + Vector3 phaseS = sigR * phaseR + sigM * phaseM; + Vector3 inScatter = sunVis * phaseS + multiScatter * sigS; + luminance += throughput * SafeScatterIntegral(inScatter, stepT, sigE, dt); + throughput *= stepT; + } + + if (hitGround) + { + Vector3 gp = viewPos + rayDir * maxDist; + Vector3 gUp = gp.Normalized(); + float nDotL = MathF.Max(0f, gUp.Dot(sunDir)); + if (nDotL > 0f) + { + Vector3 tSunG = SampleTransmittanceLut(transBuf, PlanetRadiusM, nDotL); + luminance += throughput * tSunG * horizonGroundAlbedo * (nDotL / MathF.PI); + } + } + + Vector3 rad = luminance * preset.SolarIrradiance; + if (v < 0.5f) + { + // Smoothly bridge the -0.45 deg sphere-intersection cliff from exact horizon limb radiance + // into warm horizon haze / ground bounce over ~6 degrees below horizon. + Vector3 horizonLimb = buf[(SkyViewHeight / 2) * SkyViewWidth + x]; + float dipDeg = MathF.Max(0f, (horizonElev - elev) * (180f / MathF.PI)); + float sBlend = Math.Clamp(dipDeg / 6.0f, 0f, 1f); + sBlend = sBlend * sBlend * (3f - 2f * sBlend); + Vector3 warmBounce = new Vector3( + horizonLimb.X * (preset.MapKind == ArenaMapKind.Desert ? 0.92f : 0.75f), + horizonLimb.Y * (preset.MapKind == ArenaMapKind.Desert ? 0.80f : 0.75f), + horizonLimb.Z * (preset.MapKind == ArenaMapKind.Desert ? 0.65f : 0.78f)); + Vector3 deepGround = rad.Lerp(warmBounce, 0.65f); + rad = horizonLimb.Lerp(deepGround, sBlend); + } + + buf[y * SkyViewWidth + x] = rad; + } + } + } + + return buf; + } + + private static Vector3 EvaluateExtinction(AtmospherePreset preset, float altitudeM) + { + SampleMedia(preset, altitudeM, out _, out Vector3 sigmaE); + return sigmaE; + } + + private static void SampleMedia(AtmospherePreset preset, float altitudeM, out Vector3 sigmaS, out Vector3 sigmaE) + { + SampleRayleighMie(preset, altitudeM, out Vector3 sigR, out Vector3 sigM, out sigmaE); + sigmaS = sigR + sigM; + } + + private static void SampleRayleighMie( + AtmospherePreset preset, + float altitudeM, + out Vector3 sigR, + out Vector3 sigM, + out Vector3 sigE) + { + float h = MathF.Max(0f, altitudeM); + float dR = MathF.Exp(-h / RayleighScaleHeightM); + float dM = MathF.Exp(-h / preset.MieScaleHeightMeters); + float dO = MathF.Max(0f, 1f - MathF.Abs(h - 25_000f) / 15_000f); + + sigR = RayleighScattering * dR; + sigM = preset.MieScattering * dM; + Vector3 extM = sigM / MieSingleScatterAlbedo; + Vector3 absO = OzoneAbsorption * dO; + sigE = sigR + extM + absO; + } + + private static float RayleighPhase(float cosTheta) + { + return (3f / (16f * MathF.PI)) * (1f + cosTheta * cosTheta); + } + + private static float CornetteShanksPhase(float cosTheta, float g) + { + float g2 = g * g; + float num = 3f * (1f - g2) * (1f + cosTheta * cosTheta); + float denom = 8f * MathF.PI * (2f + g2) * MathF.Pow(MathF.Max(1e-4f, 1f + g2 - 2f * g * cosTheta), 1.5f); + return num / denom; + } + + private static Vector3 SafeScatterIntegral(Vector3 inScatter, Vector3 stepT, Vector3 sigmaE, float dt) + { + return new Vector3( + sigmaE.X > 1e-8f ? inScatter.X * (1f - stepT.X) / sigmaE.X : inScatter.X * dt, + sigmaE.Y > 1e-8f ? inScatter.Y * (1f - stepT.Y) / sigmaE.Y : inScatter.Y * dt, + sigmaE.Z > 1e-8f ? inScatter.Z * (1f - stepT.Z) / sigmaE.Z : inScatter.Z * dt); + } + + private static bool HitsPlanet(float r, float mu) + { + float disc = r * r * (mu * mu - 1f) + PlanetRadiusM * PlanetRadiusM; + return mu < 0f && disc >= 0f; + } + + private static float RaySphereExit(float r, float mu, out bool hitGround) + { + float discGround = r * r * (mu * mu - 1f) + PlanetRadiusM * PlanetRadiusM; + if (mu < 0f && discGround >= 0f) + { + hitGround = true; + return MathF.Max(0f, -r * mu - MathF.Sqrt(MathF.Max(0f, discGround))); + } + + hitGround = false; + float discAtmo = r * r * (mu * mu - 1f) + AtmosphereRadiusM * AtmosphereRadiusM; + return MathF.Max(0f, -r * mu + MathF.Sqrt(MathF.Max(0f, discAtmo))); + } + + private static Vector3 SampleTransmittanceLut(Vector3[] buf, float r, float mu) + { + float clampedR = Math.Clamp(r, PlanetRadiusM, AtmosphereRadiusM); + float H = MathF.Sqrt(AtmosphereRadiusM * AtmosphereRadiusM - PlanetRadiusM * PlanetRadiusM); + float rho = MathF.Sqrt(MathF.Max(0f, clampedR * clampedR - PlanetRadiusM * PlanetRadiusM)); + float v = rho / H; + + float disc = clampedR * clampedR * (mu * mu - 1f) + AtmosphereRadiusM * AtmosphereRadiusM; + float d = MathF.Max(0f, -clampedR * mu + MathF.Sqrt(MathF.Max(0f, disc))); + float dMin = AtmosphereRadiusM - clampedR; + float dMax = rho + H; + float u = (d - dMin) / MathF.Max(1e-4f, dMax - dMin); + + return SampleBilinear(buf, TransmittanceWidth, TransmittanceHeight, u, v); + } + + private static Vector3 SampleMultiScatteringLut(Vector3[] buf, float r, float muS) + { + float u = 0.5f + 0.5f * Math.Clamp(muS, -1f, 1f); + float v = Math.Clamp((r - PlanetRadiusM) / AtmosphereHeightM, 0f, 1f); + return SampleBilinear(buf, MultiScatteringSize, MultiScatteringSize, u, v); + } + + private static Vector3 SampleBilinear(Vector3[] buf, int w, int h, float u, float v) + { + float fx = Math.Clamp(u, 0f, 1f) * w - 0.5f; + float fy = Math.Clamp(v, 0f, 1f) * h - 0.5f; + int x0 = Math.Clamp((int)MathF.Floor(fx), 0, w - 1); + int y0 = Math.Clamp((int)MathF.Floor(fy), 0, h - 1); + int x1 = Math.Min(x0 + 1, w - 1); + int y1 = Math.Min(y0 + 1, h - 1); + float tx = Math.Clamp(fx - x0, 0f, 1f); + float ty = Math.Clamp(fy - y0, 0f, 1f); + + Vector3 c00 = buf[y0 * w + x0]; + Vector3 c10 = buf[y0 * w + x1]; + Vector3 c01 = buf[y1 * w + x0]; + Vector3 c11 = buf[y1 * w + x1]; + Vector3 c0 = c00.Lerp(c10, tx); + Vector3 c1 = c01.Lerp(c11, tx); + return c0.Lerp(c1, ty); + } + + private static Image CreateRgbahImage(int w, int h, Vector3[] pixels) + { + Image img = Image.CreateEmpty(w, h, false, Image.Format.Rgbah); + for (int y = 0; y < h; y++) + { + int row = y * w; + for (int x = 0; x < w; x++) + { + Vector3 c = pixels[row + x]; + img.SetPixel(x, y, new Color( + MathF.Max(0f, c.X), + MathF.Max(0f, c.Y), + MathF.Max(0f, c.Z), + 1.0f)); + } + } + return img; + } +} diff --git a/client/AtmosphereSystem.cs b/client/AtmosphereSystem.cs new file mode 100644 index 0000000..17bda3b --- /dev/null +++ b/client/AtmosphereSystem.cs @@ -0,0 +1,388 @@ +using System; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Single authority for Forward+ Vulkan atmospheric skybox, Sky IBL, 4-split PSSM sun light, +/// two-tier volumetric valley fog + aerial perspective, SSR, SSAO, AgX tonemapping, +/// normalized additive HDR bloom, and post-tonemap film grain ( Layer 5). +/// +public partial class AtmosphereSystem : Node +{ + private WorldEnvironment _worldEnv = null!; + private Godot.Environment _env = null!; + private Sky _sky = null!; + private ShaderMaterial _skyMat = null!; + private DirectionalLight3D _sun = null!; + private FogVolume _valleyFog = null!; + private FogMaterial _valleyFogMat = null!; + private CanvasLayer _filmGrainLayer = null!; + private ColorRect _filmGrainRect = null!; + private ShaderMaterial _filmGrainMat = null!; + private Texture3Drd? _flowTexRd; + private ImageTexture3D? _dummyFlowTex; + private VolumetricCompositorEffect? _volumetricEffect; + private Compositor? _compositor; + private VolumetricEmitterPool _emitterPool = new(); + private bool _initialized; + + public WorldEnvironment WorldEnvironment => _worldEnv; + public Godot.Environment Environment => _env; + public DirectionalLight3D Sun => _sun; + public FogVolume ValleyFogVolume => _valleyFog; + public CanvasLayer FilmGrainLayer => _filmGrainLayer; + public AtmosphereLutBaker.BakedAtmosphere? CurrentBaked { get; private set; } + public VolumetricCompositorEffect? VolumetricEffect => _volumetricEffect; + public VolumetricEmitterPool EmitterPool => _emitterPool; + + public override void _Ready() + { + EnsureInitialized(); + } + + public void EnsureInitialized() + { + if (_initialized) + { + return; + } + _initialized = true; + + Shader skyShader = GD.Load("res://sky_atmosphere.gdshader") + ?? throw new InvalidOperationException("Failed to load res://sky_atmosphere.gdshader"); + _skyMat = new ShaderMaterial { Shader = skyShader }; + + _sky = new Sky + { + SkyMaterial = _skyMat, + ProcessMode = Sky.ProcessModeEnum.Quality, + RadianceSize = Sky.RadianceSizeEnum.Size128 + }; + + _env = new Godot.Environment + { + BackgroundMode = Godot.Environment.BGMode.Sky, + Sky = _sky, + AmbientLightSource = Godot.Environment.AmbientSource.Disabled, + AmbientLightEnergy = 0.0f, + + // Option 1 (Low-Gamma): SDFGI multi-bounce + occlusion with zero flat ambient + SdfgiEnabled = true, + SdfgiUseOcclusion = true, + SdfgiReadSkyLight = true, + SdfgiBounceFeedback = 0.60f, + SdfgiCascades = 3, + SdfgiMinCellSize = 0.8f, + SdfgiYScale = Godot.Environment.SdfgiyScale.Scale75Percent, + SdfgiEnergy = 0.85f, + + // AgX tonemapping preserves orange/amber combat hues while rolling off HDR emitters smoothly + TonemapMode = Godot.Environment.ToneMapper.Agx, + TonemapAgxWhite = 6.0f, + TonemapAgxContrast = 1.50f, + TonemapExposure = 0.84f, + + // Normalized additive bloom strictly above GlowHdrThreshold=1.0 (zero diffuse screen smear) + GlowEnabled = true, + GlowNormalized = true, + GlowBlendMode = Godot.Environment.GlowBlendModeEnum.Additive, + GlowHdrThreshold = 1.0f, + GlowHdrScale = 1.8f, + GlowHdrLuminanceCap = 12.0f, + GlowBloom = 0.0f, + GlowIntensity = 0.40f, + GlowStrength = 0.72f, + + // Screen-space reflections for visors, optics, bare steel, and Sion window_glass + SsrEnabled = true, + SsrMaxSteps = 32, + SsrFadeIn = 0.15f, + SsrFadeOut = 2.0f, + SsrDepthTolerance = 0.22f, + + // Screen-space ambient occlusion for mech foot & building contact grounding + SsaoEnabled = true, + SsaoRadius = 1.15f, + SsaoIntensity = 1.85f, + SsaoPower = 1.5f, + SsaoDetail = 0.45f, + SsaoHorizon = 0.06f, + SsaoSharpness = 0.98f, + SsaoLightAffect = 0.12f, + SsaoAOChannelAffect = 0.5f, + + // Tier 1: Froxel volumetric fog (0..380/460m) + VolumetricFogEnabled = true, + VolumetricFogTemporalReprojectionEnabled = true, + VolumetricFogTemporalReprojectionAmount = 0.88f, + VolumetricFogAmbientInject = 0.0f, + VolumetricFogSkyAffect = 0.10f, + + // Tier 2: Far aerial perspective (340/400m .. horizon peaks) + FogEnabled = true, + FogMode = Godot.Environment.FogModeEnum.Depth, + FogSkyAffect = 0.0f + }; + + _env.SetGlowLevel(0, 0.0f); + _env.SetGlowLevel(1, 0.25f); + _env.SetGlowLevel(2, 0.55f); + _env.SetGlowLevel(3, 0.85f); + _env.SetGlowLevel(4, 0.65f); + _env.SetGlowLevel(5, 0.35f); + _env.SetGlowLevel(6, 0.15f); + + _worldEnv = new WorldEnvironment + { + Name = "WorldEnv", + Environment = _env + }; + + Vector3 defaultInvExtent = new( + 1f / (VolumetricCompositorEffect.FlowDimX * VolumetricCompositorEffect.FlowVoxelSizeMeters), + 1f / (VolumetricCompositorEffect.FlowDimY * VolumetricCompositorEffect.FlowVoxelSizeMeters), + 1f / (VolumetricCompositorEffect.FlowDimZ * VolumetricCompositorEffect.FlowVoxelSizeMeters)); + RegisterGlobalParamIfMissing("rtd_flow_origin", RenderingServer.GlobalShaderParameterType.Vec3, Vector3.Zero); + RegisterGlobalParamIfMissing("rtd_flow_inv_extent", RenderingServer.GlobalShaderParameterType.Vec3, defaultInvExtent); + + if (RenderingServer.GetRenderingDevice() is not null) + { + RenderingServer.GISetUseHalfResolution(true); + RenderingServer.EnvironmentSetSdfgiRayCount(RenderingServer.EnvironmentSdfgiRayCount.Count4); + RenderingServer.EnvironmentSetSdfgiFramesToConverge(RenderingServer.EnvironmentSdfgiFramesToConverge.In10Frames); + RenderingServer.EnvironmentSetSdfgiFramesToUpdateLight(RenderingServer.EnvironmentSdfgiFramesToUpdateLight.In8Frames); + _flowTexRd = new Texture3Drd(); + RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _flowTexRd); + _volumetricEffect = new VolumetricCompositorEffect(_flowTexRd, _emitterPool); + _compositor = new Compositor + { + CompositorEffects = new Godot.Collections.Array { _volumetricEffect } + }; + _worldEnv.Compositor = _compositor; + } + else + { + var dummyImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah); + dummyImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f)); + _dummyFlowTex = new ImageTexture3D(); + _dummyFlowTex.Create(Image.Format.Rgbah, 1, 1, 1, false, new Godot.Collections.Array { dummyImg }); + RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _dummyFlowTex); + } + + AddChild(_worldEnv); + + _sun = new DirectionalLight3D + { + Name = "SunLight", + ShadowEnabled = true, + DirectionalShadowMode = DirectionalLight3D.ShadowMode.Parallel4Splits, + DirectionalShadowMaxDistance = 320f, + DirectionalShadowSplit1 = 0.08f, + DirectionalShadowSplit2 = 0.25f, + DirectionalShadowSplit3 = 0.56f, + DirectionalShadowBlendSplits = true, + DirectionalShadowFadeStart = 0.85f, + DirectionalShadowPancakeSize = 20f, + ShadowBlur = 1.25f, + ShadowBias = 0.06f, + ShadowNormalBias = 1.6f, + LightAngularDistance = 0.53f + }; + AddChild(_sun); + + _valleyFogMat = new FogMaterial + { + Density = 0.0038f, + HeightFalloff = 1.65f, + EdgeFade = 0.12f + }; + _valleyFog = new FogVolume + { + Name = "ValleyMistVolume", + Shape = RenderingServer.FogVolumeShape.Box, + Material = _valleyFogMat + }; + AddChild(_valleyFog); + + Shader grainShader = GD.Load("res://film_grain.gdshader") + ?? throw new InvalidOperationException("Failed to load res://film_grain.gdshader"); + _filmGrainMat = new ShaderMaterial { Shader = grainShader }; + _filmGrainMat.SetShaderParameter("grain_strength", 0.018f); + _filmGrainMat.SetShaderParameter("post_gamma", 1.32f); + + _filmGrainLayer = new CanvasLayer + { + Name = "FilmGrainLayer", + Layer = 5 + }; + _filmGrainRect = new ColorRect + { + Name = "FilmGrainRect", + MouseFilter = Control.MouseFilterEnum.Ignore, + Material = _filmGrainMat, + Color = Colors.White, + AnchorLeft = 0f, + AnchorTop = 0f, + AnchorRight = 1f, + AnchorBottom = 1f, + OffsetLeft = 0f, + OffsetTop = 0f, + OffsetRight = 0f, + OffsetBottom = 0f + }; + _filmGrainLayer.AddChild(_filmGrainRect); + AddChild(_filmGrainLayer); + } + + public void ApplyMap(ArenaMapKind mapKind) + { + EnsureInitialized(); + + AtmosphereLutBaker.BakedAtmosphere baked = AtmosphereLutBaker.GetOrBake(mapKind); + AtmosphereLutBaker.AtmospherePreset preset = baked.Preset; + CurrentBaked = baked; + + _skyMat.SetShaderParameter("skyview_lut", baked.SkyViewTexture); + _skyMat.SetShaderParameter("sun_dir", baked.SunDirection); + _skyMat.SetShaderParameter("sun_transmittance", baked.SunTransmittance); + _skyMat.SetShaderParameter("horizon_elev", baked.HorizonElevationRad); + _skyMat.SetShaderParameter("sun_disc_intensity", preset.SunDiscIntensity); + _skyMat.SetShaderParameter("mie_aureole_strength", preset.MieAureoleStrength); + _skyMat.SetShaderParameter("sky_exposure", 1.0f); + + _sun.RotationDegrees = new Vector3(preset.SunPitchDeg, preset.SunYawDeg, 0f); + _sun.LightColor = baked.SunLightColor; + _sun.LightEnergy = baked.SunLightEnergy; + _sun.DirectionalShadowMaxDistance = preset.ShadowMaxDistance; + + _env.AmbientLightEnergy = preset.AmbientLightEnergy; + + Color haze = baked.HazeColor; + _env.VolumetricFogLength = preset.FogMaxLengthMeters; + _env.VolumetricFogDensity = preset.VolumetricFogDensity; + _env.VolumetricFogDetailSpread = preset.VolumetricFogDetailSpread; + _env.VolumetricFogAnisotropy = preset.VolumetricFogAnisotropy; + _env.VolumetricFogEmissionEnergy = 0f; + _env.VolumetricFogAlbedo = haze; + _env.VolumetricFogEmission = Colors.Black; + + _valleyFog.Size = preset.ValleyVolumeSize; + _valleyFog.Position = preset.ValleyVolumePosition; + _valleyFogMat.Density = preset.ValleyVolumeDensity; + _valleyFogMat.HeightFalloff = preset.ValleyVolumeHeightFalloff; + _valleyFogMat.EdgeFade = preset.ValleyVolumeEdgeFade; + _valleyFogMat.Albedo = haze; + _valleyFogMat.Emission = Colors.Black; + + _env.FogLightColor = haze; + _env.FogDepthBegin = preset.DepthFogBegin; + _env.FogDepthEnd = preset.DepthFogEnd; + _env.FogDepthCurve = preset.DepthFogCurve; + _env.FogDensity = preset.DepthFogDensity; + _env.FogAerialPerspective = preset.DepthFogAerialPerspective; + _env.FogSunScatter = preset.DepthFogSunScatter; + + if (_volumetricEffect is not null) + { + Color ambCol = new( + MathF.Max(0.10f, haze.R * 0.55f), + MathF.Max(0.12f, haze.G * 0.55f), + MathF.Max(0.14f, haze.B * 0.58f)); + _volumetricEffect.SetAtmosphere( + baked.SunDirection, + baked.SunLightEnergy, + baked.SunLightColor, + ambCol, + extinctionScale: mapKind == ArenaMapKind.Sion ? 0.95f : 0.85f); + } + } + + public void BindEmitterPool(VolumetricEmitterPool pool) + { + _emitterPool = pool ?? throw new ArgumentNullException(nameof(pool)); + _volumetricEffect?.SetEmitterPool(pool); + } + + public void ApplyGraphicsSettings(GraphicsSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + EnsureInitialized(); + + _volumetricEffect?.ApplyGraphicsSettings(settings); + + SdfgiSettingsConfig sdfgi = GraphicsSettings.GetSdfgiConfig(settings.SdfgiQuality); + _env.SdfgiEnabled = sdfgi.Enabled; + if (sdfgi.Enabled) + { + _env.SdfgiMinCellSize = sdfgi.MinCellSize; + _env.SdfgiCascades = sdfgi.Cascades; + } + + if (RenderingServer.GetRenderingDevice() is not null) + { + RenderingServer.GISetUseHalfResolution(sdfgi.HalfResolution); + RenderingServer.EnvironmentSetSdfgiRayCount( + sdfgi.RayCount >= 8 + ? RenderingServer.EnvironmentSdfgiRayCount.Count8 + : RenderingServer.EnvironmentSdfgiRayCount.Count4); + } + } + + public override void _ExitTree() + { + if (_worldEnv is not null && GodotObject.IsInstanceValid(_worldEnv)) + { + _worldEnv.Compositor = null; + } + if (_flowTexRd is not null) + { + _flowTexRd.TextureRdRid = new Rid(); + } + if (AreFlowGlobalsRegistered && RenderingServer.Singleton is not null) + { + _dummyFlowTex ??= CreateDummyFlowTexture(); + RenderingServer.GlobalShaderParameterSet("rtd_flow_field", _dummyFlowTex); + } + if (_volumetricEffect is not null) + { + _volumetricEffect.Enabled = false; + if (RenderingServer.GetRenderingDevice() is not null) + { + RenderingServer.CallOnRenderThread(Callable.From(_volumetricEffect.DisposeRdResources)); + RenderingServer.ForceSync(); + } + } + } + + private static ImageTexture3D CreateDummyFlowTexture() + { + var dummyImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah); + dummyImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f)); + var tex = new ImageTexture3D(); + tex.Create(Image.Format.Rgbah, 1, 1, 1, false, new Godot.Collections.Array { dummyImg }); + return tex; + } + + private static readonly System.Collections.Generic.HashSet RegisteredGlobals = new(); + public static bool AreFlowGlobalsRegistered => + RegisteredGlobals.Contains("rtd_flow_field") && + RegisteredGlobals.Contains("rtd_flow_origin") && + RegisteredGlobals.Contains("rtd_flow_inv_extent"); + + private static void RegisterGlobalParamIfMissing( + StringName name, + RenderingServer.GlobalShaderParameterType type, + Variant defaultValue) + { + string key = name.ToString(); + if (RegisteredGlobals.Contains(key)) + { + RenderingServer.GlobalShaderParameterSet(name, defaultValue); + return; + } + RegisteredGlobals.Add(key); + RenderingServer.GlobalShaderParameterAdd(name, type, defaultValue); + } +} diff --git a/client/CameraJuiceState.cs b/client/CameraJuiceState.cs new file mode 100644 index 0000000..2e3ac8a --- /dev/null +++ b/client/CameraJuiceState.cs @@ -0,0 +1,366 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Display-only post-anchor camera juice (recoil kick, quadratic trauma micro-shake, footstep thump, +/// and speed/VTOL FOV punch). Zero simulation authority and zero Godot dependency so unit tests and +/// headless smoke checks exercise the exact same state machine. +/// +/// Invariant: when is true, outputs exact +/// and 0f angles (strictly zero idle camera jitter). +/// +/// +public sealed class CameraJuiceState +{ + public const float BaseFovDeg = 58.0f; + public const float DropFreefallFovDeg = 82.0f; + public const float DropRetroFovDeg = 76.0f; + private const float ZeroEpsilon = 1e-4f; + private const float TraumaDecayPerSec = 1.95f; + private const float RecoilDecayRate = 14.0f; + private const float FootstepDecayRate = 16.0f; + private const float FovBlendRate = 6.0f; + private const float DropFovBlendInRate = 5.0f; + private const float DropFovBlendOutRate = 3.8f; + + private float _time; + + public float Trauma { get; private set; } + public float RecoilPitchRad { get; private set; } + public float RecoilBackMeters { get; private set; } + public float FootstepBumpY { get; private set; } + public float FovOffsetDeg { get; private set; } + + public bool IsIdle => + Trauma <= 0f && + RecoilPitchRad == 0f && + RecoilBackMeters == 0f && + FootstepBumpY == 0f; + + public void Reset() + { + Trauma = 0f; + RecoilPitchRad = 0f; + RecoilBackMeters = 0f; + FootstepBumpY = 0f; + FovOffsetDeg = 0f; + _time = 0f; + } + + public void ConsumeEvents( + IReadOnlyList events, + int localContenderId, + Vector3 localPos, + IClientArenaSession? session = null) + { + ConsumeEvents(events, localContenderId, localPos, session is null ? null : (isContender, id) => + { + if (isContender) + { + var contenders = session.ViewState.Contenders; + if (id >= 0 && id < contenders.Count && (id == session.LocalContenderId || session.IsContenderVisible(id))) + { + var c = contenders[id]; + return (true, new Vector3(c.X, c.Y, c.Z)); + } + return (false, Vector3.Zero); + } + else + { + if (session.IsSpectatorVisible(id)) + { + var specs = session.ViewState.Spectators.Spectators; + for (int s = 0; s < specs.Count; s++) + { + if (specs[s].Id == id) + { + var sp = specs[s]; + return (true, new Vector3(sp.X, sp.Y, sp.Z)); + } + } + int sIdx = id >= 1000 ? id - 1000 : id; + if (sIdx >= 0 && sIdx < specs.Count) + { + var sp = specs[sIdx]; + return (true, new Vector3(sp.X, sp.Y, sp.Z)); + } + } + return (false, Vector3.Zero); + } + }); + } + + public void ConsumeEvents( + IReadOnlyList events, + int localContenderId, + Vector3 localPos, + Func? resolveActor) + { + for (int i = 0; i < events.Count; i++) + { + switch (events[i]) + { + case MatchResetEvent: + Reset(); + break; + + case ShotFiredEvent shot: + if (!shot.IsSpectatorShooter && shot.ShooterId == localContenderId) + { + ApplyWeaponRecoil(shot.WeaponId, (WeaponVisualClass)shot.WeaponClass); + } + break; + + case HitImpactEvent hit: + { + if (hit.TargetKind == (byte)HitTargetKind.Contender && hit.TargetId == localContenderId) + { + float incomingTrauma = (WeaponVisualClass)hit.WeaponClass switch + { + WeaponVisualClass.Explosive => 0.34f, + WeaponVisualClass.Autocannon => 0.22f, + WeaponVisualClass.ThermalBeam => 0.20f, + _ => 0.10f + }; + AddTrauma(incomingTrauma); + } + else if ((WeaponVisualClass)hit.WeaponClass == WeaponVisualClass.Explosive) + { + float dx = hit.HitX - localPos.X; + float dy = hit.HitY - localPos.Y; + float dz = hit.HitZ - localPos.Z; + float distSq = dx * dx + dy * dy + dz * dz; + if (distSq < 36f * 36f) + { + float falloff = 1f - MathF.Sqrt(distSq) / 36f; + AddTrauma(0.24f * falloff); + } + } + break; + } + + case ContenderEliminatedEvent elim: + ApplyDeathTrauma(isContender: true, elim.VictimId, localPos, resolveActor); + break; + + case SpectatorDestroyedEvent sdet: + ApplyDeathTrauma(isContender: false, sdet.SpectatorId, localPos, resolveActor); + break; + + case DropPodEvent dpe: + { + var kind = (DropPodEventKind)dpe.Kind; + if (dpe.ContenderId == localContenderId) + { + if (kind == DropPodEventKind.PodRetroBurnStart) + { + AddTrauma(0.18f); + } + else if (kind == DropPodEventKind.PodTouchdownBlowPetals) + { + AddTrauma(0.36f); + } + } + else if (kind == DropPodEventKind.PodTouchdownBlowPetals) + { + float dx = dpe.X - localPos.X; + float dy = dpe.Y - localPos.Y; + float dz = dpe.Z - localPos.Z; + float distSq = dx * dx + dy * dy + dz * dz; + if (distSq < 48f * 48f) + { + float falloff = 1f - MathF.Sqrt(distSq) / 48f; + AddTrauma(0.18f * falloff); + } + } + break; + } + } + } + } + + public void ApplyOrbitalBurnRumble(float burnIntensity) + { + if (float.IsFinite(burnIntensity) && burnIntensity > 0f) + { + float target = Math.Clamp(burnIntensity, 0f, 1f) * 0.20f; + if (Trauma < target) + { + Trauma = target; + } + } + } + + private void ApplyDeathTrauma( + bool isContender, + int entityId, + Vector3 localPos, + Func? resolveActor) + { + if (resolveActor is null) + { + return; + } + var (visible, pos) = resolveActor(isContender, entityId); + if (!visible) + { + return; + } + float dist = Vector3.Distance(pos, localPos); + if (dist < 90f) + { + AddTrauma(0.14f * (1f - dist / 90f)); + } + } + + public void ConsumeFootsteps(IReadOnlyList footsteps, int localContenderId) + { + for (int i = 0; i < footsteps.Count; i++) + { + FootstepPulse pulse = footsteps[i]; + if (pulse.IsContender && pulse.EntityId == localContenderId) + { + float massFactor = Math.Clamp(pulse.MassKg / 3200f, 0.55f, 1.55f); + float loadFactor = Math.Clamp(pulse.LoadG, 0.5f, 1.8f); + float bump = -0.065f * massFactor * loadFactor; + FootstepBumpY = Math.Clamp(FootstepBumpY + bump, -0.18f, 0f); + } + } + } + + public void AddTrauma(float amount) + { + if (float.IsFinite(amount) && amount > 0f) + { + Trauma = Math.Clamp(Trauma + amount, 0f, 1.0f); + } + } + + public void Update(float dt, float localSpeedMps, bool isVtol, bool isInDropPod = false, OrbitalPodPhase podPhase = OrbitalPodPhase.Freefall) + { + float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.1f) : 0f; + if (stepDt > 0f) + { + _time += stepDt; + + Trauma = MathF.Max(0f, Trauma - stepDt * TraumaDecayPerSec); + if (Trauma < ZeroEpsilon) Trauma = 0f; + + float recoilDecay = MathF.Exp(-RecoilDecayRate * stepDt); + RecoilPitchRad *= recoilDecay; + RecoilBackMeters *= recoilDecay; + if (MathF.Abs(RecoilPitchRad) < ZeroEpsilon) RecoilPitchRad = 0f; + if (MathF.Abs(RecoilBackMeters) < ZeroEpsilon) RecoilBackMeters = 0f; + + float stepDecay = MathF.Exp(-FootstepDecayRate * stepDt); + FootstepBumpY *= stepDecay; + if (MathF.Abs(FootstepBumpY) < ZeroEpsilon) FootstepBumpY = 0f; + } + + float speed = float.IsFinite(localSpeedMps) ? MathF.Max(0f, localSpeedMps) : 0f; + float targetFovOffset; + float blendRate; + if (isInDropPod) + { + targetFovOffset = podPhase == OrbitalPodPhase.RetroBurn + ? (DropRetroFovDeg - BaseFovDeg) + : (DropFreefallFovDeg - BaseFovDeg) + Math.Clamp(speed / 62f, 0f, 2.0f); + blendRate = DropFovBlendInRate; + } + else + { + float speedStart = isVtol ? 14f : 12f; + float speedFull = isVtol ? 46f : 36f; + targetFovOffset = speed > speedStart + ? Math.Clamp((speed - speedStart) / (speedFull - speedStart), 0f, 1f) * (isVtol ? 4.8f : 3.4f) + : 0f; + blendRate = FovOffsetDeg > targetFovOffset + 0.5f ? DropFovBlendOutRate : FovBlendRate; + } + + if (stepDt > 0f) + { + float blend = 1f - MathF.Exp(-blendRate * stepDt); + FovOffsetDeg += (targetFovOffset - FovOffsetDeg) * blend; + if (MathF.Abs(FovOffsetDeg) < 0.002f && targetFovOffset == 0f) + { + FovOffsetDeg = 0f; + } + } + } + + public void ComputeOffsets( + out Vector3 localOffset, + out float pitchOffsetRad, + out float yawOffsetRad, + out float rollOffsetRad) + { + if (IsIdle) + { + localOffset = Vector3.Zero; + pitchOffsetRad = 0f; + yawOffsetRad = 0f; + rollOffsetRad = 0f; + return; + } + + float shake = Trauma * Trauma; + float sx = MathF.Sin(_time * 43.0f) * 0.65f + MathF.Sin(_time * 71.0f) * 0.35f; + float sy = MathF.Cos(_time * 37.0f) * 0.65f + MathF.Sin(_time * 63.0f) * 0.35f; + float sr = MathF.Sin(_time * 29.0f + 1.1f); + + localOffset = new Vector3( + sx * shake * 0.14f, + sy * shake * 0.11f + FootstepBumpY, + RecoilBackMeters); + + pitchOffsetRad = RecoilPitchRad + sy * shake * 0.015f; + yawOffsetRad = sx * shake * 0.012f; + rollOffsetRad = sr * shake * 0.016f; + } + + private void ApplyWeaponRecoil(string weaponId, WeaponVisualClass weaponClass) + { + switch (weaponClass) + { + case WeaponVisualClass.Explosive: + if (string.Equals(weaponId, "recoilless", StringComparison.Ordinal)) + { + RecoilPitchRad = MathF.Min(RecoilPitchRad + 0.022f, 0.042f); + RecoilBackMeters = MathF.Min(RecoilBackMeters + 0.34f, 0.60f); + AddTrauma(0.32f); + } + else + { + RecoilPitchRad = MathF.Min(RecoilPitchRad + 0.011f, 0.030f); + RecoilBackMeters = MathF.Min(RecoilBackMeters + 0.16f, 0.40f); + AddTrauma(0.18f); + } + break; + + case WeaponVisualClass.Autocannon: + RecoilPitchRad = MathF.Min(RecoilPitchRad + 0.010f, 0.026f); + RecoilBackMeters = MathF.Min(RecoilBackMeters + 0.14f, 0.35f); + AddTrauma(0.16f); + break; + + case WeaponVisualClass.ThermalBeam: + { + bool isLance = string.Equals(weaponId, "gilded_lance", StringComparison.Ordinal); + RecoilPitchRad = MathF.Min(RecoilPitchRad + (isLance ? 0.012f : 0.008f), 0.026f); + RecoilBackMeters = MathF.Min(RecoilBackMeters + (isLance ? 0.16f : 0.10f), 0.35f); + AddTrauma(isLance ? 0.18f : 0.12f); + break; + } + + default: // KineticLight (mg_762, pd_flak) + RecoilPitchRad = MathF.Min(RecoilPitchRad + 0.0022f, 0.012f); + RecoilBackMeters = MathF.Min(RecoilBackMeters + 0.030f, 0.15f); + AddTrauma(0.035f); + break; + } + } +} diff --git a/client/ClientAssets.cs b/client/ClientAssets.cs new file mode 100644 index 0000000..8898259 --- /dev/null +++ b/client/ClientAssets.cs @@ -0,0 +1,42 @@ +using System; +using System.IO; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +internal static class ClientAssets +{ + private static bool _registered; + + internal static void EnsureAssetsRootRegistered() + { + if (_registered) + { + return; + } + _registered = true; + + if (OS.HasFeature("template")) + { + string exeAssets = Path.Combine(OS.GetExecutablePath().GetBaseDir(), "assets"); + if (Directory.Exists(exeAssets)) + { + AssetPathResolver.RegisterAssetsRoot(exeAssets); + return; + } + } + + string baseAssets = Path.Combine(AppContext.BaseDirectory, "assets"); + if (Directory.Exists(baseAssets)) + { + AssetPathResolver.RegisterAssetsRoot(baseAssets); + } + } + + internal static string LocateAssetsDirectory() + { + EnsureAssetsRootRegistered(); + return AssetPathResolver.LocateAssetsRoot(); + } +} diff --git a/client/ClientOrdnanceMirror.cs b/client/ClientOrdnanceMirror.cs new file mode 100644 index 0000000..1330924 --- /dev/null +++ b/client/ClientOrdnanceMirror.cs @@ -0,0 +1,651 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; +using RustToDust.Ymir; + +namespace RustToDust.Client; + +/// +/// Client-side kinematic mirror of active projectiles, loitering drones, +/// proximity mines, and thermal pools driven strictly by [Union(13)] +/// (identical behavior in Solo and RemoteClient multiplayer, zero per-projectile s, +/// zero material clones). +/// +public sealed class ClientOrdnanceMirror +{ + public const int PoolCapacity = OrdnanceRuntime.PoolCapacity; + + public readonly record struct TransientVfxSpec( + bool IsSphere, + Vector3 Position, + Vector3 Velocity, + Basis Rotation, + Vector3 StartScale, + Vector3 EndScale, + Color ColorStart, + Color ColorEnd, + float Lifetime); + + public readonly record struct ActiveBeamSpec( + Vector3 Start, + Vector3 End, + float Radius, + Color HdrTint, + float CoreSharpness, + float CoreRadiusFrac, + float TailFade); + + private struct MirroredSlot + { + public bool Active; + public int OrdnanceId; + public int ParentOrdnanceId; + public ProceduralWeaponKey? WeaponKey; + public byte NodeDefIndex; + public OrdnanceNodeDef? Def; + public OrdnanceVisualShape VisualShape; + public Color Color; + public float ManufacturerRoleIndex; + public Vector3 Pos; + public Vector3 TailPos; + public Vector3 Vel; + public Vector3 AnchorPos; + public int TargetEntityId; + public bool TargetIsSpectator; + public float Age; + public float StageAge; + public float OrbitAngle; + public float TrailTimer; + public float EmberTimer; + public bool Armed; + } + + private readonly MirroredSlot[] _slots = new MirroredSlot[PoolCapacity]; + private readonly Dictionary _slotById = new(PoolCapacity); + private int _activeCount; + + public int ActiveCount => _activeCount; + + public void Clear() + { + Array.Clear(_slots, 0, _slots.Length); + _slotById.Clear(); + _activeCount = 0; + } + + public bool TryGetMirroredPose(int ordnanceId, out Vector3 pos, out OrdnanceVisualShape shape) + { + if (_slotById.TryGetValue(ordnanceId, out int idx) && _slots[idx].Active) + { + pos = _slots[idx].Pos; + shape = _slots[idx].VisualShape; + return true; + } + pos = Vector3.Zero; + shape = OrdnanceVisualShape.None; + return false; + } + + public void ConsumeEvents( + IReadOnlyList events, + VehicleAssetCache cache, + DebrisSystem debris, + ParticlePool particles, + VolumetricEmitterPool volumetrics, + bool hasCam, + Vector3 camPos, + Action emitTransient) + { + for (int i = 0; i < events.Count; i++) + { + if (events[i] is MatchResetEvent) + { + Clear(); + continue; + } + if (events[i] is not OrdnanceNodeEvent ev) + { + continue; + } + + var kind = (OrdnanceEventKind)ev.Kind; + Vector3 pos = new(ev.PosX, ev.PosY, ev.PosZ); + Vector3 vel = new(ev.VelX, ev.VelY, ev.VelZ); + Color col = DecodeColorRgba(ev.ColorRgba); + OrdnanceNodeDef? def = ResolveNodeDef(ev.WeaponKey, ev.NodeDefIndex); + var shape = (OrdnanceVisualShape)ev.VisualShape; + if (shape == OrdnanceVisualShape.None && def is not null) + { + shape = def.VisualShape; + } + + switch (kind) + { + case OrdnanceEventKind.Spawned: + UpsertSlot(ev, pos, vel, col, def, shape); + break; + + case OrdnanceEventKind.StageTransition: + { + bool wasSabot = false; + if (ev.ParentOrdnanceId != 0 && _slotById.TryGetValue(ev.ParentOrdnanceId, out int parentIdx) && _slots[parentIdx].Active) + { + wasSabot = _slots[parentIdx].VisualShape == OrdnanceVisualShape.SabotCarrier; + RemoveAtSlot(parentIdx); + } + UpsertSlot(ev, pos, vel, col, def, shape); + + if (wasSabot) + { + float roleIdx = ev.WeaponKey is { } wk ? 10f + Math.Clamp((int)wk.Manufacturer, 0, 4) : 11f; + var petalTpl = cache.GetOrLoadWeaponPart("mz_slotted_brake"); + Vector3 dir = vel.LengthSquared() > 1e-3f ? vel.Normalized() : Vector3.Forward; + Vector3 right = dir.Cross(Vector3.Up); + if (right.LengthSquared() < 1e-4f) right = Vector3.Right; + right = right.Normalized(); + + for (int side = -1; side <= 1; side += 2) + { + Vector3 pPos = pos + right * (side * 0.28f); + Transform3D petalXf = new(Basis.FromScale(Vector3.One * 0.65f), pPos); + debris.SpawnDetachedPart( + petalTpl.SingleSurfaceMesh, + petalXf, + pos - right * (side * 0.45f), + vel * 0.35f, + roleIdx, + impulseScale: 0.75f, + applyScorch: true, + lifetime: 2.2f); + } + particles.EmitOrdnanceBurst(pos, col, sparkCount: 4, radiusScale: 0.65f, camPos, hasCam); + } + else if (def?.Motion == OrdnanceMotion.LoiterOrbit) + { + emitTransient(new TransientVfxSpec( + IsSphere: false, + Position: pos, + Velocity: Vector3.Zero, + Rotation: Basis.Identity, + StartScale: new Vector3(0.6f, 1.0f, 0.6f), + EndScale: new Vector3(3.6f, 0.5f, 3.6f), + ColorStart: (col * 2.4f) with { A = 0.85f }, + ColorEnd: col with { A = 0f }, + Lifetime: 0.30f)); + } + break; + } + + case OrdnanceEventKind.Split: + RemoveById(ev.OrdnanceId); + particles.EmitOrdnanceBurst(pos, col, sparkCount: 6, radiusScale: 1.05f, camPos, hasCam); + emitTransient(new TransientVfxSpec( + IsSphere: false, + Position: pos, + Velocity: Vector3.Zero, + Rotation: Basis.Identity, + StartScale: new Vector3(0.7f, 1.0f, 0.7f), + EndScale: new Vector3(5.2f, 0.5f, 5.2f), + ColorStart: (col * 2.8f) with { A = 0.92f }, + ColorEnd: col with { A = 0f }, + Lifetime: 0.28f)); + break; + + case OrdnanceEventKind.Detonated: + { + RemoveById(ev.OrdnanceId); + float splashR = def is not null && def.SplashRadius > 0.5f ? def.SplashRadius : 4.2f; + particles.EmitOrdnanceBurst(pos, col, sparkCount: 6, radiusScale: Math.Clamp(splashR / 4.5f, 0.7f, 1.6f), camPos, hasCam); + if (!hasCam || pos.DistanceSquaredTo(camPos) <= 280f * 280f) + { + volumetrics.EmitOrdnanceDetonation(pos, col, splashR); + } + emitTransient(new TransientVfxSpec( + IsSphere: false, + Position: pos + Vector3.Up * 0.16f, + Velocity: Vector3.Zero, + Rotation: Basis.Identity, + StartScale: new Vector3(0.7f, 1f, 0.7f), + EndScale: new Vector3(Math.Clamp(splashR * 1.35f, 2.8f, 8.5f), 0.4f, Math.Clamp(splashR * 1.35f, 2.8f, 8.5f)), + ColorStart: new Color(col.R * 2.9f, col.G * 2.9f, col.B * 2.9f, 0.90f), + ColorEnd: col with { A = 0f }, + Lifetime: 0.30f)); + break; + } + + case OrdnanceEventKind.Intercepted: + RemoveById(ev.OrdnanceId); + particles.EmitOrdnanceBurst(pos, new Color(1.0f, 0.75f, 0.28f), sparkCount: 5, radiusScale: 0.7f, camPos, hasCam); + break; + + case OrdnanceEventKind.Expired: + RemoveById(ev.OrdnanceId); + break; + } + } + } + + public void StepAndSubmit( + float dt, + IClientArenaSession session, + VehicleAssetCache cache, + MultiMeshPartPool partPool, + ParticlePool particles, + VolumetricEmitterPool volumetrics, + TerrainField terrain, + bool hasCam, + Vector3 camPos, + Action submitActiveRing, + Action submitActiveBeam) + { + if (_activeCount == 0) + { + return; + } + + float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; + var state = session.ViewState; + + var sabotMesh = cache.GetOrLoadWeaponPart("brl_sabot_rail").SingleSurfaceMesh; + var rocketMesh = cache.GetOrLoadWeaponPart("mz_mirv_warhead").SingleSurfaceMesh; + var droneMesh = cache.GetOrLoadWeaponPart("mz_loiter_aero_fin").SingleSurfaceMesh; + var brakeMesh = cache.GetOrLoadWeaponPart("mz_slotted_brake").SingleSurfaceMesh; + + for (int i = 0; i < PoolCapacity; i++) + { + if (!_slots[i].Active) + { + continue; + } + + ref MirroredSlot s = ref _slots[i]; + var def = s.Def; + float maxLife = def is not null && def.MaxLifetime > 0f ? def.MaxLifetime : 30f; + + if (stepDt > 0f) + { + s.Age += stepDt; + s.StageAge += stepDt; + if (s.Age > maxLife + 2.5f) + { + RemoveAtSlot(i); + continue; + } + + if (def is not null && !s.Armed && s.StageAge >= def.ArmDelay) + { + s.Armed = true; + } + + AdvanceSlotKinematics(ref s, def, state, terrain, stepDt); + float tailLerp = 1f - MathF.Exp(-stepDt * 18f); + s.TailPos = s.TailPos.Lerp(s.Pos, tailLerp); + } + + if (hasCam && s.Pos.DistanceSquaredTo(camPos) > 340f * 340f) + { + continue; + } + + bool isThermalPool = (def?.IsThermalPool == true) || s.VisualShape == OrdnanceVisualShape.Pool; + if (isThermalPool) + { + float radius = def is not null && def.WhileAlive is { RadialRadius: > 0.5f } + ? def.WhileAlive.RadialRadius + : (def is not null && def.SplashRadius > 0.5f ? def.SplashRadius : 5.5f); + float pulse = 0.88f + 0.14f * MathF.Sin(s.StageAge * 7.5f + s.OrdnanceId); + float groundY = terrain.SampleHeight(s.Pos.X, s.Pos.Z); + Vector3 poolPos = new(s.Pos.X, MathF.Max(s.Pos.Y, groundY + 0.14f), s.Pos.Z); + + Transform3D ringXf = new(Basis.FromScale(new Vector3(radius * 2f * pulse, 0.35f, radius * 2f * pulse)), poolPos); + submitActiveRing(ringXf, new Color(s.Color.R * 2.6f, s.Color.G * 2.6f, s.Color.B * 2.6f, 0.78f)); + + if (stepDt > 0f) + { + s.EmberTimer += stepDt; + if (s.EmberTimer >= 0.11f) + { + s.EmberTimer = 0f; + particles.EmitThermalPoolEmber(poolPos, radius, s.Color, camPos, hasCam); + if (!hasCam || poolPos.DistanceSquaredTo(camPos) <= 220f * 220f) + { + volumetrics.EmitThermalPoolPlume(poolPos, radius, s.Color); + } + } + } + continue; + } + + if (s.VisualShape == OrdnanceVisualShape.Mine || def?.Motion == OrdnanceMotion.StationaryMine) + { + float groundY = terrain.SampleHeight(s.Pos.X, s.Pos.Z); + Vector3 minePos = new(s.Pos.X, MathF.Max(s.Pos.Y, groundY + 0.10f), s.Pos.Z); + Basis upright = new Basis(Vector3.Right, -MathF.PI * 0.5f) * Basis.FromScale(Vector3.One * 1.05f); + Transform3D mineXf = new(upright, minePos); + float blink = s.Armed ? (0.45f + 0.55f * MathF.Max(0f, MathF.Sin(s.StageAge * 9.5f + s.OrdnanceId))) : 0f; + partPool.Submit(rocketMesh, in mineXf, new Color(0f, blink * 0.6f, s.ManufacturerRoleIndex, 1f), wantsShadow: false); + + if (s.Armed) + { + float proxR = def is not null && def.ProximityRadius > 0.5f ? def.ProximityRadius : 6.0f; + float ringPulse = 0.92f + 0.08f * MathF.Sin(s.StageAge * 6f); + Transform3D warnXf = new(Basis.FromScale(new Vector3(proxR * 0.55f * ringPulse, 0.18f, proxR * 0.55f * ringPulse)), minePos + new Vector3(0f, 0.08f, 0f)); + submitActiveRing(warnXf, new Color(s.Color.R * 2.2f, s.Color.G * 2.2f, s.Color.B * 2.2f, 0.25f + 0.35f * blink)); + } + continue; + } + + if (s.VisualShape == OrdnanceVisualShape.Drone || def?.Motion == OrdnanceMotion.LoiterOrbit) + { + Vector3 dir = s.Vel.LengthSquared() > 1e-3f ? s.Vel.Normalized() : Vector3.Forward; + Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; + Basis orient = Basis.LookingAt(-dir, up); + if (def?.Motion == OrdnanceMotion.LoiterOrbit) + { + orient *= new Basis(Vector3.Forward, 0.32f); + } + Transform3D droneXf = new(orient * Basis.FromScale(Vector3.One * 2.4f), s.Pos); + partPool.Submit(droneMesh, in droneXf, new Color(0f, 0.35f, s.ManufacturerRoleIndex, 1f), wantsShadow: false); + + if (def?.Motion == OrdnanceMotion.LoiterOrbit) + { + float scanPulse = 0.85f + 0.15f * MathF.Sin(s.StageAge * 8f); + Transform3D haloXf = new(Basis.FromScale(new Vector3(2.4f * scanPulse, 0.25f, 2.4f * scanPulse)), s.Pos - new Vector3(0f, 0.45f, 0f)); + submitActiveRing(haloXf, new Color(s.Color.R * 2.5f, s.Color.G * 2.5f, s.Color.B * 2.5f, 0.58f)); + } + + if (stepDt > 0f) + { + s.TrailTimer += stepDt; + if (s.TrailTimer >= 0.075f) + { + s.TrailTimer = 0f; + if (!hasCam || s.Pos.DistanceSquaredTo(camPos) <= 240f * 240f) + { + volumetrics.EmitOrdnanceTrailCapsule(s.TailPos, s.Pos, s.Vel, s.Color, isRocket: def?.Motion != OrdnanceMotion.LoiterOrbit); + } + } + } + continue; + } + + // Rocket, SabotCarrier, or Bolt projectile in flight + { + Vector3 dir = s.Vel.LengthSquared() > 1e-3f ? s.Vel.Normalized() : Vector3.Forward; + Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; + Basis orient = Basis.LookingAt(-dir, up); + + ArrayMesh projMesh = s.VisualShape switch + { + OrdnanceVisualShape.SabotCarrier => sabotMesh, + OrdnanceVisualShape.Rocket => rocketMesh, + _ => brakeMesh + }; + float projScale = s.VisualShape switch + { + OrdnanceVisualShape.SabotCarrier => 1.15f, + OrdnanceVisualShape.Rocket => 1.55f, + _ => 1.0f + }; + + Transform3D projXf = new(orient * Basis.FromScale(Vector3.One * projScale), s.Pos); + bool isRocket = s.VisualShape == OrdnanceVisualShape.Rocket || + def?.Motion is OrdnanceMotion.RocketBoosted or OrdnanceMotion.HomingMissile; + partPool.Submit(projMesh, in projXf, new Color(0f, isRocket ? 0.65f : 0.25f, s.ManufacturerRoleIndex, 1f), wantsShadow: false); + + // Connected [TailPos, Pos] volumetric capsule streak + Vector3 tailStart = s.Pos.DistanceSquaredTo(s.TailPos) > 0.04f ? s.TailPos : s.Pos - dir * 1.4f; + Color beamCol = isRocket + ? new Color(s.Color.R * 3.4f, s.Color.G * 2.4f, s.Color.B * 1.4f, 0.94f) + : new Color(s.Color.R * 3.0f, s.Color.G * 3.0f, s.Color.B * 3.0f, 0.92f); + submitActiveBeam(new ActiveBeamSpec( + Start: tailStart, + End: s.Pos - dir * 0.16f, + Radius: isRocket ? 0.24f : 0.15f, + HdrTint: beamCol, + CoreSharpness: 2.8f, + CoreRadiusFrac: 0.36f, + TailFade: 1.0f)); + + if (stepDt > 0f) + { + s.TrailTimer += stepDt; + if (s.TrailTimer >= (isRocket ? 0.055f : 0.075f)) + { + s.TrailTimer = 0f; + if (!hasCam || s.Pos.DistanceSquaredTo(camPos) <= 240f * 240f) + { + volumetrics.EmitOrdnanceTrailCapsule(s.TailPos, s.Pos - dir * 0.18f, s.Vel, s.Color, isRocket); + } + } + } + } + } + } + + private static void AdvanceSlotKinematics( + ref MirroredSlot s, + OrdnanceNodeDef? def, + MatchState state, + TerrainField terrain, + float dt) + { + OrdnanceMotion motion = def?.Motion ?? OrdnanceMotion.Ballistic; + switch (motion) + { + case OrdnanceMotion.Ballistic: + s.Vel.Y -= 19.6f * (def?.GravityScale ?? 1f) * dt; + s.Pos += s.Vel * dt; + break; + + case OrdnanceMotion.RocketBoosted: + { + float burnTime = def?.BurnTime ?? 1.4f; + if (s.StageAge <= burnTime && (def?.ThrustAccel ?? 0f) > 0f) + { + Vector3 dir = s.Vel.LengthSquared() > 1e-4f ? s.Vel.Normalized() : Vector3.Forward; + float speed = s.Vel.Length(); + float maxSpd = def!.MaxSpeed > 0f ? def.MaxSpeed : 360f; + float nextSpd = MathF.Min(maxSpd, speed + def.ThrustAccel * dt); + s.Vel = dir * nextSpd; + } + else + { + s.Vel.Y -= 19.6f * (def?.GravityScale ?? 0.25f) * dt; + } + s.Pos += s.Vel * dt; + break; + } + + case OrdnanceMotion.HomingMissile: + { + if (s.TargetEntityId >= 0) + { + Vector3 targetPt = Vector3.Zero; + bool hasTarget = false; + if (!s.TargetIsSpectator && s.TargetEntityId < state.Contenders.Count) + { + var tc = state.Contenders[s.TargetEntityId]; + if (tc.IsGroundedActive) + { + targetPt = new Vector3(tc.X, tc.Y + tc.Grid.Spec.HalfHeight * 0.35f, tc.Z); + hasTarget = true; + } + } + else if (s.TargetIsSpectator) + { + for (int k = 0; k < state.Spectators.Spectators.Count; k++) + { + var sp = state.Spectators.Spectators[k]; + if (sp.Id == s.TargetEntityId && sp.Alive) + { + targetPt = new Vector3(sp.X, sp.Y + sp.Grid.Spec.HalfHeight * 0.35f, sp.Z); + hasTarget = true; + break; + } + } + } + + if (hasTarget && (targetPt - s.Pos).LengthSquared() > 1e-3f) + { + Vector3 desiredDir = (targetPt - s.Pos).Normalized(); + Vector3 curDir = s.Vel.LengthSquared() > 1e-4f ? s.Vel.Normalized() : desiredDir; + float maxTurn = (def?.TurnRateRad ?? 4.5f) * dt; + float dot = Math.Clamp(curDir.Dot(desiredDir), -1f, 1f); + float angle = MathF.Acos(dot); + Vector3 newDir = angle <= maxTurn || angle < 1e-4f + ? desiredDir + : curDir.Lerp(desiredDir, maxTurn / angle).Normalized(); + float spd = s.Vel.Length(); + float maxSpd = def is not null && def.MaxSpeed > 0f ? def.MaxSpeed : MathF.Max(spd, 115f); + spd = MathF.Min(maxSpd, spd + (def?.ThrustAccel ?? 90f) * dt); + s.Vel = newDir * spd; + } + } + s.Pos += s.Vel * dt; + break; + } + + case OrdnanceMotion.LoiterOrbit: + { + float orbitSpeed = def?.LoiterOrbitSpeedRad ?? 1.45f; + float radius = def?.LoiterOrbitRadius ?? 15f; + float agl = def?.LoiterAltitudeAgl ?? 35f; + s.OrbitAngle += orbitSpeed * dt; + float ox = s.AnchorPos.X + MathF.Cos(s.OrbitAngle) * radius; + float oz = s.AnchorPos.Z + MathF.Sin(s.OrbitAngle) * radius; + float oy = terrain.SampleHeight(ox, oz) + agl; + Vector3 nextPos = new(ox, oy, oz); + s.Vel = (nextPos - s.Pos) / MathF.Max(1e-4f, dt); + s.Pos = nextPos; + break; + } + + case OrdnanceMotion.StationaryMine: + break; + } + } + + private void UpsertSlot( + OrdnanceNodeEvent ev, + Vector3 pos, + Vector3 vel, + Color col, + OrdnanceNodeDef? def, + OrdnanceVisualShape shape) + { + if (_slotById.TryGetValue(ev.OrdnanceId, out int existing)) + { + ref var slot = ref _slots[existing]; + slot.Pos = pos; + slot.Vel = vel; + slot.AnchorPos = pos; + slot.TargetEntityId = ev.TargetEntityId; + slot.TargetIsSpectator = ev.TargetIsSpectator; + slot.Def = def; + slot.VisualShape = shape; + slot.Color = col; + return; + } + + int freeIdx = -1; + for (int i = 0; i < PoolCapacity; i++) + { + if (!_slots[i].Active) + { + freeIdx = i; + break; + } + } + if (freeIdx < 0) + { + // Evict oldest slot to stay strictly bounded under PoolCapacity + float maxAge = -1f; + int oldest = 0; + for (int i = 0; i < PoolCapacity; i++) + { + if (_slots[i].Age > maxAge) + { + maxAge = _slots[i].Age; + oldest = i; + } + } + RemoveAtSlot(oldest); + freeIdx = oldest; + } + + float mfgRole = ev.WeaponKey is { } wk ? 10f + Math.Clamp((int)wk.Manufacturer, 0, 4) : 5f; + _slots[freeIdx] = new MirroredSlot + { + Active = true, + OrdnanceId = ev.OrdnanceId, + ParentOrdnanceId = ev.ParentOrdnanceId, + WeaponKey = ev.WeaponKey, + NodeDefIndex = ev.NodeDefIndex, + Def = def, + VisualShape = shape, + Color = col, + ManufacturerRoleIndex = mfgRole, + Pos = pos, + TailPos = pos, + Vel = vel, + AnchorPos = pos, + TargetEntityId = ev.TargetEntityId, + TargetIsSpectator = ev.TargetIsSpectator, + Age = 0f, + StageAge = 0f, + OrbitAngle = 0f, + TrailTimer = 0f, + EmberTimer = 0f, + Armed = def is null || def.ArmDelay <= 0f + }; + _slotById[ev.OrdnanceId] = freeIdx; + _activeCount++; + } + + private void RemoveById(int ordnanceId) + { + if (_slotById.TryGetValue(ordnanceId, out int idx)) + { + RemoveAtSlot(idx); + } + } + + private void RemoveAtSlot(int idx) + { + if (!_slots[idx].Active) + { + return; + } + _slotById.Remove(_slots[idx].OrdnanceId); + _slots[idx] = default; + _activeCount = Math.Max(0, _activeCount - 1); + } + + private static OrdnanceNodeDef? ResolveNodeDef(ProceduralWeaponKey? key, byte nodeDefIndex) + { + if (!key.HasValue) + { + return null; + } + var spec = ProceduralWeaponGenerator.Generate(key.Value); + if (nodeDefIndex < spec.FlattenedNodes.Length) + { + return spec.FlattenedNodes[nodeDefIndex]; + } + return spec.RootNode; + } + + private static Color DecodeColorRgba(uint rgba) + { + if (rgba == 0) + { + return new Color(1.0f, 0.72f, 0.28f, 1.0f); + } + float r = ((rgba >> 24) & 0xFF) / 255f; + float g = ((rgba >> 16) & 0xFF) / 255f; + float b = ((rgba >> 8) & 0xFF) / 255f; + return new Color(r, g, b, 1.0f); + } +} diff --git a/client/DebrisSystem.cs b/client/DebrisSystem.cs new file mode 100644 index 0000000..7171288 --- /dev/null +++ b/client/DebrisSystem.cs @@ -0,0 +1,213 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Manages physically detached armor plates and sheared hardpoint gear as tumbling, +/// terrain-bouncing debris pieces submitted directly into +/// (zero per-piece Node3D/MeshInstance3D/StandardMaterial3D allocations). +/// +public partial class DebrisSystem : Node3D +{ + private const float Gravity = -20f; + private const float DefaultLifetime = 4.5f; + private const float FadeDuration = 1.2f; + private const int MaxActiveDebris = 256; + + private sealed class DebrisPiece + { + public required ArrayMesh Mesh; + public Vector3 Position; + public Basis Rotation; + public Vector3 Scale; + public Vector3 Velocity; + public Vector3 AngularVelocity; + public float RoleIndex; + public float Scorch; + public float HeatGlow; + public float Age; + public float Lifetime; + public bool Settled; + } + + private readonly List _pieces = new(); + private uint _rngState = 0x9E3779B9u; + + public int ActiveCount => _pieces.Count; + + public bool TryGetPiecePosition(int index, out Vector3 position) + { + if (index >= 0 && index < _pieces.Count) + { + position = _pieces[index].Position; + return true; + } + position = Vector3.Zero; + return false; + } + + public void ClearAll() + { + _pieces.Clear(); + } + + /// + /// Registers a detached rigid part or sheared gear mesh at its world transform + /// and launches it with an outward blast impulse and tumble. + /// + public void SpawnDetachedPart( + ArrayMesh mesh, + Transform3D worldXform, + Vector3 blastOriginWorld, + Vector3 inheritedVelocity, + float roleIndex, + float impulseScale = 1.0f, + bool applyScorch = true, + float lifetime = DefaultLifetime) + { + if (mesh is null || mesh.GetSurfaceCount() == 0) + { + return; + } + + while (_pieces.Count >= MaxActiveDebris) + { + _pieces.RemoveAt(0); + } + + Vector3 scale = worldXform.Basis.Scale; + if (!scale.IsFinite() || scale.LengthSquared() < 1e-6f) + { + scale = Vector3.One; + } + Basis rot = worldXform.Basis.Orthonormalized(); + + Vector3 outward = worldXform.Origin - blastOriginWorld; + outward.Y = 0f; + if (outward.LengthSquared() < 1e-4f) + { + float ang = NextFloat() * MathF.Tau; + outward = new Vector3(MathF.Cos(ang), 0f, MathF.Sin(ang)); + } + else + { + outward = outward.Normalized(); + } + + float horizSpeed = (4.2f + NextFloat() * 4.8f) * impulseScale; + float upSpeed = (4.0f + NextFloat() * 4.5f) * impulseScale; + Vector3 vel = inheritedVelocity * 0.45f + outward * horizSpeed + Vector3.Up * upSpeed; + + Vector3 angVel = new( + (NextFloat() * 2f - 1f) * 7.5f, + (NextFloat() * 2f - 1f) * 7.5f, + (NextFloat() * 2f - 1f) * 7.5f); + + _pieces.Add(new DebrisPiece + { + Mesh = mesh, + Position = worldXform.Origin, + Rotation = rot, + Scale = scale, + Velocity = vel, + AngularVelocity = angVel, + RoleIndex = roleIndex, + Scorch = applyScorch ? 0.85f : 0.15f, + HeatGlow = applyScorch ? 0.45f : 0f, + Age = 0f, + Lifetime = lifetime > 0.2f ? lifetime : DefaultLifetime, + Settled = false + }); + } + + public void Step(float dt, TerrainField terrain) + { + if (dt <= 0f || !float.IsFinite(dt)) + { + return; + } + float stepDt = Math.Clamp(dt, 0f, 0.05f); + + for (int i = _pieces.Count - 1; i >= 0; i--) + { + DebrisPiece p = _pieces[i]; + p.Age += stepDt; + if (p.Age >= p.Lifetime) + { + _pieces.RemoveAt(i); + continue; + } + + if (p.HeatGlow > 0f) + { + p.HeatGlow = MathF.Max(0f, p.HeatGlow - stepDt * 0.22f); + } + + if (!p.Settled) + { + p.Velocity += new Vector3(0f, Gravity * stepDt, 0f); + Vector3 pos = p.Position + p.Velocity * stepDt; + + Basis rot = p.Rotation; + float spinLen = p.AngularVelocity.Length(); + if (spinLen > 1e-4f) + { + rot = (new Basis(p.AngularVelocity / spinLen, spinLen * stepDt) * rot).Orthonormalized(); + } + + float floorY = terrain.SampleHeight(pos.X, pos.Z) + 0.10f; + if (pos.Y <= floorY) + { + pos.Y = floorY; + if (p.Velocity.Y < -1.4f) + { + p.Velocity = new Vector3( + p.Velocity.X * 0.62f, + -p.Velocity.Y * 0.32f, + p.Velocity.Z * 0.62f); + p.AngularVelocity *= 0.55f; + } + else + { + p.Velocity = Vector3.Zero; + p.AngularVelocity = Vector3.Zero; + p.Settled = true; + } + } + + p.Position = pos; + p.Rotation = rot; + } + } + } + + public void SubmitToPool(MultiMeshPartPool pool) + { + for (int i = 0; i < _pieces.Count; i++) + { + DebrisPiece p = _pieces[i]; + float remaining = p.Lifetime - p.Age; + float alpha = remaining < FadeDuration + ? Math.Clamp(remaining / FadeDuration, 0.02f, 1f) + : 1f; + float sinkY = remaining < FadeDuration ? (1f - alpha) * 0.65f : 0f; + Vector3 scale = p.Scale * (remaining < FadeDuration ? (0.35f + 0.65f * alpha) : 1f); + Transform3D xf = new(p.Rotation * Basis.FromScale(scale), p.Position - new Vector3(0f, sinkY, 0f)); + Color custom = new(p.Scorch, p.HeatGlow, p.RoleIndex, alpha); + pool.Submit(p.Mesh, in xf, in custom, wantsShadow: false); + } + } + + private float NextFloat() + { + uint x = _rngState; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + _rngState = x; + return (x & 0x00FFFFFFu) / 16777216f; + } +} diff --git a/client/GpuSparksSystem.cs b/client/GpuSparksSystem.cs new file mode 100644 index 0000000..10cea16 --- /dev/null +++ b/client/GpuSparksSystem.cs @@ -0,0 +1,214 @@ +using System; +using Godot; + +namespace RustToDust.Client; + +/// +/// Flow-coupled GPU particle system (, 65,536 capacity) driven by +/// the global rtd_flow_field + Tri3D curl streams for +/// stochastic opaque HDR sparks, buoyant embers, flow-entrained dust motes, and muzzle starbursts. +/// +public partial class GpuSparksSystem : Node3D +{ + public const int Capacity = 65536; + + public const int TypeVelocitySpark = 0; + public const int TypeBuoyantEmber = 1; + public const int TypeDustMote = 2; + public const int TypeMuzzleStarburst = 3; + + private const uint EmitFlagsAll = (uint)( + GpuParticles3D.EmitFlags.Position | + GpuParticles3D.EmitFlags.Velocity | + GpuParticles3D.EmitFlags.Color | + GpuParticles3D.EmitFlags.Custom); + + private GpuParticles3D _particles = null!; + private ShaderMaterial _processMat = null!; + private ShaderMaterial _drawMat = null!; + private bool _initialized; + private uint _rng = 0x9E3779B9u; + + public int TotalEmittedCount { get; private set; } + public GpuParticles3D ParticlesNode => _particles; + + public override void _Ready() + { + EnsureInitialized(); + } + + public void EnsureInitialized() + { + if (_initialized) + { + return; + } + _initialized = true; + + Shader processShader = GD.Load("res://gpu_sparks_process.gdshader") + ?? throw new InvalidOperationException("Failed to load res://gpu_sparks_process.gdshader"); + Shader drawShader = GD.Load("res://gpu_sparks_draw.gdshader") + ?? throw new InvalidOperationException("Failed to load res://gpu_sparks_draw.gdshader"); + + _processMat = new ShaderMaterial { Shader = processShader }; + _drawMat = new ShaderMaterial { Shader = drawShader }; + + var quad = new QuadMesh + { + Size = Vector2.One, + Material = _drawMat + }; + + _particles = new GpuParticles3D + { + Name = "GpuSparks3D", + Amount = Capacity, + LocalCoords = false, + Emitting = true, + AmountRatio = 0.0f, // Keep GPU process active with zero automatic spawns + Lifetime = 2.5f, + FixedFps = 0, + Explosiveness = 0.0f, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + VisibilityAabb = new Aabb(new Vector3(-1800f, -200f, -1800f), new Vector3(3600f, 2200f, 3600f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + ProcessMaterial = _processMat, + DrawPass1 = quad + }; + AddChild(_particles); + } + + public void ClearAll() + { + EnsureInitialized(); + TotalEmittedCount = 0; + _particles.Restart(); + _particles.Emitting = true; + _particles.AmountRatio = 0.0f; + } + + public void Prewarm(Vector3 nearPos) + { + EnsureInitialized(); + EmitRaw(nearPos + new Vector3(0f, -20f, 0f), Vector3.Up * 0.1f, new Color(1f, 1f, 1f, 0.01f), 0.02f, 0.05f, TypeVelocitySpark, 1.0f); + TotalEmittedCount = 0; + } + + public void EmitMuzzleStarburst(Vector3 pos, Color hdrColor, float sizeM, float lifetimeSec) + { + EnsureInitialized(); + EmitRaw(pos, Vector3.Zero, hdrColor, Math.Clamp(sizeM, 0.25f, 0.90f), Math.Clamp(lifetimeSec, 0.05f, 0.14f), TypeMuzzleStarburst, 0f); + } + + public void EmitSparkBurst(Vector3 pos, Vector3 normal, int count, Color hdrColor, float speed, float widthM = 0.026f) + { + EnsureInitialized(); + Vector3 n = normal.LengthSquared() > 1e-4f ? normal.Normalized() : Vector3.Up; + for (int i = 0; i < count; i++) + { + Vector3 rand = new(NextSigned(), MathF.Abs(NextSigned()) + 0.28f, NextSigned()); + Vector3 dir = (n * 0.65f + rand).Normalized(); + float spd = speed * (0.55f + 0.85f * NextFloat()); + float life = 0.24f + 0.34f * NextFloat(); + Vector3 spawnPos = pos + new Vector3(NextSigned() * 0.14f, NextFloat() * 0.12f, NextSigned() * 0.14f); + EmitRaw(spawnPos, dir * spd, hdrColor, widthM, life, TypeVelocitySpark, 0.85f); + } + } + + public void EmitEmberBurst(Vector3 pos, int count, Color hdrColor, float spreadSpeed, float widthM = 0.030f) + { + EnsureInitialized(); + for (int i = 0; i < count; i++) + { + Vector3 vel = new(NextSigned() * spreadSpeed, 2.5f + NextFloat() * 5.5f, NextSigned() * spreadSpeed); + float life = 0.90f + NextFloat() * 1.25f; + EmitRaw(pos + new Vector3(NextSigned() * 0.7f, NextFloat() * 0.6f, NextSigned() * 0.7f), vel, hdrColor, widthM, life, TypeBuoyantEmber, 1.5f); + } + } + + public void EmitDustMotes(Vector3 pos, Vector3 normal, int count, Color dustColor, float speed, float widthM = 0.065f) + { + EnsureInitialized(); + Vector3 n = normal.LengthSquared() > 1e-4f ? normal.Normalized() : Vector3.Up; + for (int i = 0; i < count; i++) + { + float ang = NextFloat() * MathF.Tau; + float spd = speed * (0.55f + 0.70f * NextFloat()); + Vector3 vel = new Vector3(MathF.Cos(ang) * spd, 0.8f + NextFloat() * 1.4f, MathF.Sin(ang) * spd) + n * (0.4f * spd); + float life = 0.45f + NextFloat() * 0.45f; + EmitRaw(pos + new Vector3(NextSigned() * 0.35f, 0.08f, NextSigned() * 0.35f), vel, dustColor, widthM, life, TypeDustMote, 3.6f); + } + } + + public void EmitThermalPoolEmber(Vector3 pos, float radius, Color accentCol) + { + EnsureInitialized(); + float ang = NextFloat() * MathF.Tau; + float r = MathF.Sqrt(NextFloat()) * MathF.Max(0.5f, radius * 0.85f); + Vector3 p = pos + new Vector3(MathF.Cos(ang) * r, 0.18f, MathF.Sin(ang) * r); + Vector3 vel = new(NextSigned() * 0.7f, 2.0f + NextFloat() * 1.8f, NextSigned() * 0.7f); + Color hdr = new(accentCol.R * 3.8f, accentCol.G * 3.8f, accentCol.B * 3.8f, 0.95f); + EmitRaw(p, vel, hdr, 0.055f, 0.65f + NextFloat() * 0.45f, TypeBuoyantEmber, 1.4f); + } + + public void EmitPodRetroSparksAndDust(Vector3 podBasePos, float agl, Color groundTint, bool isContender) + { + EnsureInitialized(); + float scale = isContender ? 1.2f : 0.85f; + Color sparkHdr = new(4.8f, 2.6f, 0.65f, 0.98f); + int sparkCount = isContender ? 14 : 8; + for (int i = 0; i < sparkCount; i++) + { + Vector3 vel = new(NextSigned() * 7.5f, -(11f + NextFloat() * 7f), NextSigned() * 7.5f); + EmitRaw(podBasePos + new Vector3(NextSigned() * 0.7f, 0.1f, NextSigned() * 0.7f), vel, sparkHdr, 0.028f * scale, 0.24f + NextFloat() * 0.16f, TypeVelocitySpark, 1.2f); + } + + if (agl < 60f) + { + float washT = Math.Clamp(1f - agl / 60f, 0.2f, 1f); + Vector3 groundPos = podBasePos - new Vector3(0f, MathF.Max(0f, agl), 0f) + new Vector3(0f, 0.22f, 0f); + Color dustCol = new(groundTint.R * 1.1f, groundTint.G * 1.1f, groundTint.B * 1.1f, 0.78f * washT); + int moteCount = isContender ? 24 : 14; + for (int d = 0; d < moteCount; d++) + { + float ang = NextFloat() * MathF.Tau; + float spd = (7.5f + NextFloat() * 8.5f) * washT * scale; + Vector3 vel = new(MathF.Cos(ang) * spd, 1.0f + NextFloat() * 1.6f, MathF.Sin(ang) * spd); + EmitRaw(groundPos + new Vector3(MathF.Cos(ang) * 0.9f, 0f, MathF.Sin(ang) * 0.9f), vel, dustCol, 0.055f * scale, 0.55f + NextFloat() * 0.30f, TypeDustMote, 3.4f); + } + } + } + + public void EmitPodTouchdownSparksAndDust(Vector3 pos, Vector3 normal, Color groundTint, bool isContender) + { + EnsureInitialized(); + float scale = isContender ? 1.3f : 0.95f; + EmitSparkBurst(pos + normal * 0.45f, normal, isContender ? 160 : 90, new Color(5.2f, 2.8f, 0.70f, 0.98f), 19f * scale, 0.028f); + EmitEmberBurst(pos + normal * 0.45f, isContender ? 85 : 48, new Color(4.0f, 1.6f, 0.35f, 0.95f), 7.5f * scale, 0.032f); + EmitDustMotes(pos + normal * 0.25f, normal, isContender ? 75 : 45, groundTint with { A = 0.82f }, 10f * scale, 0.058f); + } + + private void EmitRaw(Vector3 pos, Vector3 vel, Color hdrColor, float widthM, float lifetimeSec, int type, float drag) + { + float packedTypeAndDrag = type + Math.Clamp(drag, 0f, 19.9f) * 0.05f; + _particles.EmitParticle( + new Transform3D(Basis.Identity, pos), + vel, + hdrColor, + new Color(widthM, 0f, lifetimeSec, packedTypeAndDrag), + EmitFlagsAll); + TotalEmittedCount++; + } + + private float NextFloat() + { + uint x = _rng; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + _rng = x; + return (x & 0x00FFFFFFu) / 16777216f; + } + + private float NextSigned() => NextFloat() * 2f - 1f; +} diff --git a/client/GraphicsSettings.cs b/client/GraphicsSettings.cs new file mode 100644 index 0000000..e8e4e60 --- /dev/null +++ b/client/GraphicsSettings.cs @@ -0,0 +1,270 @@ +using System; +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RustToDust.Client; + +public enum VfxResolutionScale +{ + Half = 0, + ThreeQuarter = 1, + Full = 2 +} + +public enum VolumetricSamples +{ + Low = 0, + Medium = 1, + High = 2, + Ultra = 3 +} + +public enum SdfgiQuality +{ + Off = 0, + Balanced = 1, + High = 2 +} + +public readonly record struct SdfgiSettingsConfig( + bool Enabled, + float MinCellSize, + int Cascades, + bool HalfResolution, + int RayCount); + +public sealed record GraphicsSettingsData +{ + [JsonPropertyName("vfxResolutionScale")] + public VfxResolutionScale VfxResolution { get; init; } = VfxResolutionScale.Half; + + [JsonPropertyName("volumetricSamples")] + public VolumetricSamples VolumetricSamples { get; init; } = VolumetricSamples.Medium; + + [JsonPropertyName("sdfgiQuality")] + public SdfgiQuality SdfgiQuality { get; init; } = SdfgiQuality.Balanced; + + [JsonPropertyName("borderlessFullscreen")] + public bool BorderlessFullscreen { get; init; } = true; +} + +/// +/// Single persisted authority for live graphics and display settings (user://graphics_settings.json). +/// Pure .NET so unit tests and headless runs share the exact same schema, defaults, and event flow. +/// +public sealed class GraphicsSettings +{ + public const string DefaultFileName = "graphics_settings.json"; + + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter() } + }; + + private readonly string? _storagePath; + + public GraphicsSettings(string? storagePath = null) + { + _storagePath = string.IsNullOrWhiteSpace(storagePath) ? null : storagePath; + ResetFieldsToDefaults(); + } + + public VfxResolutionScale VfxResolution { get; private set; } + public VolumetricSamples VolumetricSamples { get; private set; } + public SdfgiQuality SdfgiQuality { get; private set; } + public bool BorderlessFullscreen { get; private set; } + + public string? StoragePath => _storagePath; + + public event Action? Changed; + + public GraphicsSettingsData ToData() => new() + { + VfxResolution = VfxResolution, + VolumetricSamples = VolumetricSamples, + SdfgiQuality = SdfgiQuality, + BorderlessFullscreen = BorderlessFullscreen + }; + + public static GraphicsSettings Load(string? storagePath) + { + var settings = new GraphicsSettings(storagePath); + if (string.IsNullOrWhiteSpace(storagePath)) + { + return settings; + } + + try + { + if (File.Exists(storagePath)) + { + string json = File.ReadAllText(storagePath); + settings.LoadFromJson(json); + } + } + catch + { + settings.ResetFieldsToDefaults(); + } + return settings; + } + + public bool LoadFromJson(string? json) + { + if (string.IsNullOrWhiteSpace(json)) + { + ResetFieldsToDefaults(); + return false; + } + + try + { + var parsed = JsonSerializer.Deserialize(json, JsonOptions); + if (parsed is null) + { + ResetFieldsToDefaults(); + return false; + } + + VfxResolution = Enum.IsDefined(parsed.VfxResolution) + ? parsed.VfxResolution + : VfxResolutionScale.Half; + VolumetricSamples = Enum.IsDefined(parsed.VolumetricSamples) + ? parsed.VolumetricSamples + : VolumetricSamples.Medium; + SdfgiQuality = Enum.IsDefined(parsed.SdfgiQuality) + ? parsed.SdfgiQuality + : SdfgiQuality.Balanced; + BorderlessFullscreen = parsed.BorderlessFullscreen; + return true; + } + catch + { + ResetFieldsToDefaults(); + return false; + } + } + + public string ToJson() => JsonSerializer.Serialize(ToData(), JsonOptions); + + public bool Save() + { + if (string.IsNullOrWhiteSpace(_storagePath)) + { + return false; + } + + try + { + string? dir = Path.GetDirectoryName(_storagePath); + if (!string.IsNullOrEmpty(dir)) + { + Directory.CreateDirectory(dir); + } + string json = ToJson(); + string tempPath = _storagePath + ".tmp"; + File.WriteAllText(tempPath, json); + File.Move(tempPath, _storagePath, overwrite: true); + return true; + } + catch + { + return false; + } + } + + public void Apply( + VfxResolutionScale vfxResolution, + VolumetricSamples volumetricSamples, + SdfgiQuality sdfgiQuality, + bool borderlessFullscreen, + bool persist = true, + bool forcePersist = false) + { + VfxResolutionScale safeRes = Enum.IsDefined(vfxResolution) ? vfxResolution : VfxResolutionScale.Half; + VolumetricSamples safeSamples = Enum.IsDefined(volumetricSamples) ? volumetricSamples : VolumetricSamples.Medium; + SdfgiQuality safeSdfgi = Enum.IsDefined(sdfgiQuality) ? sdfgiQuality : SdfgiQuality.Balanced; + + bool changed = VfxResolution != safeRes + || VolumetricSamples != safeSamples + || SdfgiQuality != safeSdfgi + || BorderlessFullscreen != borderlessFullscreen; + + if (!changed) + { + if (persist && forcePersist) + { + Save(); + } + return; + } + + VfxResolution = safeRes; + VolumetricSamples = safeSamples; + SdfgiQuality = safeSdfgi; + BorderlessFullscreen = borderlessFullscreen; + + if (persist) + { + Save(); + } + Changed?.Invoke(this); + } + + public void SetVfxResolution(VfxResolutionScale value, bool persist = true) => + Apply(value, VolumetricSamples, SdfgiQuality, BorderlessFullscreen, persist); + + public void SetVolumetricSamples(VolumetricSamples value, bool persist = true) => + Apply(VfxResolution, value, SdfgiQuality, BorderlessFullscreen, persist); + + public void SetSdfgiQuality(SdfgiQuality value, bool persist = true) => + Apply(VfxResolution, VolumetricSamples, value, BorderlessFullscreen, persist); + + public void SetBorderlessFullscreen(bool value, bool persist = true) => + Apply(VfxResolution, VolumetricSamples, SdfgiQuality, value, persist); + + public void ResetToDefaults(bool persist = true) => + Apply( + VfxResolutionScale.Half, + VolumetricSamples.Medium, + SdfgiQuality.Balanced, + borderlessFullscreen: true, + persist: persist, + forcePersist: persist); + + public static float GetResolutionScaleFactor(VfxResolutionScale scale) => scale switch + { + VfxResolutionScale.Half => 0.50f, + VfxResolutionScale.ThreeQuarter => 0.75f, + VfxResolutionScale.Full => 1.00f, + _ => 0.50f + }; + + public static (int MaxSteps, int MaxIter) GetVolumetricStepBudget(VolumetricSamples samples) => samples switch + { + VolumetricSamples.Low => (8, 12), + VolumetricSamples.Medium => (10, 15), + VolumetricSamples.High => (16, 24), + VolumetricSamples.Ultra => (24, 36), + _ => (10, 15) + }; + + public static SdfgiSettingsConfig GetSdfgiConfig(SdfgiQuality quality) => quality switch + { + SdfgiQuality.Off => new SdfgiSettingsConfig(false, 0.8f, 3, true, 4), + SdfgiQuality.Balanced => new SdfgiSettingsConfig(true, 0.8f, 3, true, 4), + SdfgiQuality.High => new SdfgiSettingsConfig(true, 0.4f, 4, false, 8), + _ => new SdfgiSettingsConfig(true, 0.8f, 3, true, 4) + }; + + private void ResetFieldsToDefaults() + { + VfxResolution = VfxResolutionScale.Half; + VolumetricSamples = VolumetricSamples.Medium; + SdfgiQuality = SdfgiQuality.Balanced; + BorderlessFullscreen = true; + } +} diff --git a/client/HbGpuCanvas.cs b/client/HbGpuCanvas.cs new file mode 100644 index 0000000..a647c75 --- /dev/null +++ b/client/HbGpuCanvas.cs @@ -0,0 +1,1099 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Godot; +using RustToDust.HbGpu; + +namespace RustToDust.Client; + +/// +/// Single-draw-call HarfBuzz 15.2.0 hb-gpu GLSL renderer on Godot 4.7 Forward+ Vulkan RenderingDevice. +/// Safe in --headless / null-RD mode: preserves CPU shaping/layout without allocating RD resources. +/// +public partial class HbGpuCanvas : Control +{ + public const byte DefaultFontId = 0; + private const int PushConstantBytes = 80; // mat4 (64) + vec2 viewport (8) + vec2 logicalSize (8) + private const int AtlasTexWidth = 1024; + private const int AtlasTexHeight = 256; // 1024 * 256 = 262,144 == HbGpuAtlasAllocator.TotalTexels + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct PushConstants + { + // Column-major mat4 for GLSL: col 0, col 1, col 2, col 3 + public float C0R0, C0R1, C0R2, C0R3; + public float C1R0, C1R1, C1R2, C1R3; + public float C2R0, C2R1, C2R2, C2R3; + public float C3R0, C3R1, C3R2, C3R3; + public float ViewportX, ViewportY; + public float LogicalW, LogicalH; + } + + private readonly HbGpuFontCache _fontCache = new(); + private readonly HbGpuAtlasAllocator _atlas = new(); + private readonly HbGpuBlobCache _blobCache; + private readonly HbGpuCommandWriter _writer = new(); + + private readonly object _syncLock = new(); + private readonly HbGpuQuadInstance[] _stagedQuads = new HbGpuQuadInstance[HbGpuCommandWriter.MaxQuads]; + private readonly byte[] _stagedAtlasMirror = new byte[HbGpuAtlasAllocator.TotalBytes]; + private bool _stagedAtlasDirty; + private int _stagedQuadCount; + private float _stagedLogicalW = 1280f; + private float _stagedLogicalH = 720f; + private int _stagedPhysW = 1280; + private int _stagedPhysH = 720; + private bool _hasStagedFrame; + + private TextureRect? _outputRect; + private Texture2Drd? _outputTexRd; + private HbGpuVulkanBackend? _backend; + private Callable _renderCallable; + private Callable _disposeCallable; + private bool _disposed; + + public bool ProfilingEnabled { get; set; } + public double LastHbGpuMs => _backend?.LastHbGpuMs ?? 0.0; + public int LastDrawCallCount => _backend?.LastDrawCallCount ?? 0; + public int LastQuadCount { get; private set; } + public bool IsVulkanActive => RenderingServer.GetRenderingDevice() is not null; + + public HbGpuFontCache Fonts => _fontCache; + public HbGpuBlobCache Blobs => _blobCache; + public HbGpuCommandWriter Writer => _writer; + + public HbGpuCanvas() + { + _blobCache = new HbGpuBlobCache(_atlas); + MouseFilter = MouseFilterEnum.Ignore; + } + + public override void _Ready() + { + SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); + MouseFilter = MouseFilterEnum.Ignore; + + LoadDefaultKryptonFont(); + + if (RenderingServer.GetRenderingDevice() is not null) + { + _outputTexRd = new Texture2Drd(); + _outputRect = new TextureRect + { + Name = "HbGpuOutput", + MouseFilter = MouseFilterEnum.Ignore, + ExpandMode = TextureRect.ExpandModeEnum.IgnoreSize, + StretchMode = TextureRect.StretchModeEnum.Scale, + Texture = _outputTexRd, + Material = new CanvasItemMaterial + { + BlendMode = CanvasItemMaterial.BlendModeEnum.PremultAlpha + } + }; + AddChild(_outputRect); + _outputRect.SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); + + _backend = new HbGpuVulkanBackend(_outputTexRd); + _renderCallable = Callable.From(RenderOnRenderThread); + _disposeCallable = Callable.From(DisposeOnRenderThread); + } + } + + private void LoadDefaultKryptonFont() + { + if (_fontCache.TryGetMetrics(DefaultFontId, out _)) + { + return; + } + + string path = ResolveKryptonPath(); + _fontCache.RegisterFontFromFile(DefaultFontId, path); + } + + public static string ResolveKryptonPath() + { + ClientAssets.EnsureAssetsRootRegistered(); + string[] candidates = + { + Path.Combine(ClientAssets.LocateAssetsDirectory(), "fonts", "Krypton.ttf"), + Path.GetFullPath(Path.Combine(ProjectSettings.GlobalizePath("res://"), "..", "assets", "fonts", "Krypton.ttf")), + Path.Combine(AppContext.BaseDirectory, "assets", "fonts", "Krypton.ttf") + }; + + foreach (string c in candidates) + { + if (File.Exists(c)) + { + return c; + } + } + + throw new FileNotFoundException("Could not locate assets/fonts/Krypton.ttf."); + } + + public void BeginFrame() + { + _blobCache.EnsureBudgetOrReset(); + _writer.BeginFrame(); + } + + public float DrawText( + ReadOnlySpan text, + float x, + float baselineY, + float fontSizePx, + Color color, + float wght = 200f, + float wdth = 100f, + float slnt = 0f, + HbGpuFeatureFlags features = HbGpuFeatureFlags.Default, + bool stemDarken = true, + uint clipMinPacked = 0, + uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + return _writer.DrawTextUtf16( + text, x, baselineY, fontSizePx, + color.R, color.G, color.B, color.A, + _fontCache, _blobCache, + DefaultFontId, wght, wdth, slnt, + features, stemDarken, clipMinPacked, clipMaxPacked); + } + + public float MeasureTextWidth( + ReadOnlySpan text, + float fontSizePx, + float wght = 200f, + float wdth = 100f, + float slnt = 0f, + HbGpuFeatureFlags features = HbGpuFeatureFlags.Default) + { + return _writer.MeasureTextWidth(text, fontSizePx, _fontCache, DefaultFontId, wght, wdth, slnt, features); + } + + public void DrawRectFilled(float x, float y, float w, float h, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + CachedBlob blob = HbGpuVectorShapes.GetUnitFilledRect(_blobCache); + float cx = x + w * 0.5f; + float cy = y + h * 0.5f; + _writer.DrawBlob( + blob, cx, cy, + w * 0.001f, 0f, 0f, -h * 0.001f, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked, + extraFlags: HbGpuQuadInstance.FlagSolidRect); + } + + public void DrawLineSegment(float x0, float y0, float x1, float y1, float thicknessPx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + float dx = x1 - x0; + float dy = y1 - y0; + float len = MathF.Sqrt(dx * dx + dy * dy); + if (len < 1e-4f || thicknessPx <= 0f) + { + return; + } + + CachedBlob blob = HbGpuVectorShapes.GetUnitFilledRect(_blobCache); + float cos = dx / len; + float sin = dy / len; + float sx = len * 0.001f; + float sy = thicknessPx * 0.001f; + float cx = (x0 + x1) * 0.5f; + float cy = (y0 + y1) * 0.5f; + // Rotate unit rect (X along segment, Y perpendicular) in Y-down screen coords + _writer.DrawBlob( + blob, cx, cy, + cos * sx, -sin * sy, + sin * sx, cos * sy, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked, + extraFlags: HbGpuQuadInstance.FlagSolidRect); + } + + public void DrawCircleFilled(float cx, float cy, float radiusPx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + CachedBlob blob = HbGpuVectorShapes.GetUnitFilledCircle(_blobCache); + float s = radiusPx * 0.002f; + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked); + } + + public void DrawCircleRing(float cx, float cy, float radiusPx, float strokePx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + if (radiusPx <= 0f || strokePx <= 0f) + { + return; + } + + ushort strokeUnits = (ushort)Math.Clamp((int)MathF.Round(strokePx / radiusPx * 500f), 2, 480); + CachedBlob blob = HbGpuVectorShapes.GetUnitRingStroke(_blobCache, strokeUnits); + float s = radiusPx * 0.002f; + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked); + } + + public void DrawTargetBracketCorner(float cornerX, float cornerY, float armPx, float thicknessPx, int quadrant, Color color) + { + if (armPx <= 0f || thicknessPx <= 0f) + { + return; + } + + ushort thickUnits = (ushort)Math.Clamp((int)MathF.Round(thicknessPx / armPx * 1000f), 10, 450); + CachedBlob blob = HbGpuVectorShapes.GetTargetBracketCorner(_blobCache, thickUnits); + float s = armPx * 0.001f; + // Design space: corner at (0,0), X in [0..1000], Y in [-1000..0] (so -emY points down in screen if m11 = -s -> +s). + // Rotate per quadrant: 0=top-left (+X,+Y), 1=top-right (-X,+Y), 2=bottom-right (-X,-Y), 3=bottom-left (+X,-Y) + float sx = (quadrant == 1 || quadrant == 2) ? -s : s; + float sy = (quadrant == 2 || quadrant == 3) ? s : -s; + _writer.DrawBlob( + blob, cornerX, cornerY, + sx, 0f, 0f, sy, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + + public void DrawDirectionalArrow(float cx, float cy, float sizePx, float angleRad, Color color) + { + CachedBlob blob = HbGpuVectorShapes.GetDirectionalArrow(_blobCache); + float s = sizePx * 0.001f; + float cos = MathF.Cos(angleRad); + float sin = MathF.Sin(angleRad); + // Angle 0 points right (+X) in screen space; design arrow points +Y, so rotate by angleRad - PI/2 with Y flip + // Design (0, +500) -> screen (+cos, +sin) * sizePx * 0.5 + _writer.DrawBlob( + blob, cx, cy, + -sin * s, cos * s, + cos * s, sin * s, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + + public void DrawChevron(float cx, float cy, float sizePx, float angleRad, Color color) + { + CachedBlob blob = HbGpuVectorShapes.GetChevronTriangle(_blobCache); + float s = sizePx * 0.001f; + float cos = MathF.Cos(angleRad); + float sin = MathF.Sin(angleRad); + _writer.DrawBlob( + blob, cx, cy, + -sin * s, cos * s, + cos * s, sin * s, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + + public void DrawDiamond(float cx, float cy, float radiusPx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + CachedBlob blob = HbGpuVectorShapes.GetDiamondBlip(_blobCache); + float s = radiusPx * 0.002f; + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked); + } + + public void DrawRectOutline(float x, float y, float w, float h, float thicknessPx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + if (w <= 0f || h <= 0f || thicknessPx <= 0f) + { + return; + } + float t = thicknessPx; + DrawRectFilled(x, y, w, t, color, clipMinPacked, clipMaxPacked); + DrawRectFilled(x, y + h - t, w, t, color, clipMinPacked, clipMaxPacked); + DrawRectFilled(x, y + t, t, MathF.Max(0f, h - 2f * t), color, clipMinPacked, clipMaxPacked); + DrawRectFilled(x + w - t, y + t, t, MathF.Max(0f, h - 2f * t), color, clipMinPacked, clipMaxPacked); + } + + public void DrawPanelFrame(Rect2 rect, Color bgCol, Color borderCol, Color accentCol, + float cornerLen = 12f, float borderPx = 1.5f, bool drawBg = true) + { + float x = rect.Position.X; + float y = rect.Position.Y; + float w = rect.Size.X; + float h = rect.Size.Y; + if (w < 2f || h < 2f) + { + return; + } + if (drawBg) + { + DrawRectFilled(x, y, w, h, bgCol); + } + DrawRectOutline(x, y, w, h, borderPx, borderCol); + + float arm = MathF.Min(cornerLen, MathF.Min(w, h) * 0.4f); + float cThick = MathF.Max(borderPx + 0.5f, 2.0f); + DrawTargetBracketCorner(x, y, arm, cThick, 0, accentCol); + DrawTargetBracketCorner(x + w, y, arm, cThick, 1, accentCol); + DrawTargetBracketCorner(x + w, y + h, arm, cThick, 2, accentCol); + DrawTargetBracketCorner(x, y + h, arm, cThick, 3, accentCol); + } + + public void DrawArcStrokeStatic( + float cx, + float cy, + float radiusPx, + float strokePx, + float startRadScreen, + float endRadScreen, + float rotationRadScreen, + VectorBlobKey key, + Color color) + { + if (radiusPx <= 0f || strokePx <= 0f) + { + return; + } + + float halfThickDesign = Math.Clamp(strokePx / radiusPx * 250f, 2f, 200f); + CachedBlob blob = HbGpuVectorShapes.GetStaticArcStroke( + _blobCache, key, -endRadScreen, -startRadScreen, 500f, halfThickDesign); + float s = radiusPx * 0.002f; + if (MathF.Abs(rotationRadScreen) < 1e-5f) + { + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + else + { + // Rotate Y-up design space clockwise by rotationRadScreen in Y-down screen space: + // Screen X = s * (cos*ex + sin*ey), Screen Y = s * (sin*ex - cos*ey) + float cos = MathF.Cos(rotationRadScreen); + float sin = MathF.Sin(rotationRadScreen); + _writer.DrawBlob( + blob, cx, cy, + cos * s, sin * s, + sin * s, -cos * s, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + } + + public void DrawArcStrokeDynamic(float cx, float cy, float radiusPx, float strokePx, float startRadScreen, float endRadScreen, Color color) + { + if (radiusPx <= 0f || strokePx <= 0f) + { + return; + } + + float halfThickDesign = Math.Clamp(strokePx / radiusPx * 250f, 2f, 200f); + // Screen Y-down angles -> design Y-up angles (negate angles so screen clockwise matches -design angle) + CachedBlob blob = HbGpuVectorShapes.EncodeArcStrokeDynamic(_blobCache, -endRadScreen, -startRadScreen, 500f, halfThickDesign); + float s = radiusPx * 0.002f; + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + + public void EndFrameAndSubmit() + { + LastQuadCount = _writer.QuadCount; + + if (_backend is null || _disposed) + { + _atlas.ClearPending(); + return; + } + + ComputeViewportSizes(out float logicalW, out float logicalH, out int physW, out int physH); + + lock (_syncLock) + { + int count = _writer.QuadCount; + if (count > 0) + { + Array.Copy(_writer.RawBuffer, 0, _stagedQuads, 0, count); + } + if (_atlas.PendingChunkCount > 0) + { + _atlas.DrainToMirror(_stagedAtlasMirror); + _stagedAtlasDirty = true; + } + _stagedQuadCount = count; + _stagedLogicalW = logicalW; + _stagedLogicalH = logicalH; + _stagedPhysW = physW; + _stagedPhysH = physH; + _hasStagedFrame = true; + _backend.ProfilingEnabled = ProfilingEnabled; + } + + RenderingServer.CallOnRenderThread(_renderCallable); + } + + private void ComputeViewportSizes(out float logicalW, out float logicalH, out int physW, out int physH) + { + Viewport? vp = GetViewport(); + if (vp is null) + { + logicalW = MathF.Max(2f, Size.X); + logicalH = MathF.Max(2f, Size.Y); + physW = Math.Max(2, Mathf.RoundToInt(logicalW)); + physH = Math.Max(2, Mathf.RoundToInt(logicalH)); + return; + } + + Vector2 vis = vp.GetVisibleRect().Size; + if (vis.X < 2f || vis.Y < 2f) + { + vis = Size; + } + + logicalW = MathF.Max(2f, vis.X); + logicalH = MathF.Max(2f, vis.Y); + + if (vp is SubViewport sv) + { + physW = Math.Max(2, sv.Size.X); + physH = Math.Max(2, sv.Size.Y); + } + else + { + Vector2 stretchScale = vp.GetStretchTransform().Scale; + physW = Math.Max(2, Mathf.RoundToInt(logicalW * stretchScale.X)); + physH = Math.Max(2, Mathf.RoundToInt(logicalH * stretchScale.Y)); + } + } + + private void RenderOnRenderThread() + { + if (_backend is null || _disposed) + { + return; + } + + lock (_syncLock) + { + if (!_hasStagedFrame) + { + return; + } + _hasStagedFrame = false; + bool atlasDirty = _stagedAtlasDirty; + _stagedAtlasDirty = false; + _backend.RenderFrame( + _stagedQuads, + _stagedQuadCount, + _stagedAtlasMirror, + atlasDirty, + _stagedLogicalW, + _stagedLogicalH, + _stagedPhysW, + _stagedPhysH); + } + } + + private void DisposeOnRenderThread() + { + _backend?.DisposeRdResources(); + } + + /// + /// Synchronously reads back the current offscreen RGBA8 render target from RenderingDevice. + /// Intended strictly for verification probes/tests. + /// + public bool TryReadbackRgba8(out byte[] data, out int width, out int height) + { + byte[]? captured = null; + int w = 0, h = 0; + + if (_backend is null || RenderingServer.GetRenderingDevice() is null) + { + data = Array.Empty(); + width = 0; + height = 0; + return false; + } + + RenderingServer.CallOnRenderThread(Callable.From(() => + { + _backend.TryReadbackOnRenderThread(out captured, out w, out h); + })); + RenderingServer.ForceSync(); + + if (captured is null || w <= 0 || h <= 0) + { + data = Array.Empty(); + width = 0; + height = 0; + return false; + } + + data = captured; + width = w; + height = h; + return true; + } + + public override void _ExitTree() + { + ReleaseResources(disposing: true); + } + + protected override void Dispose(bool disposing) + { + ReleaseResources(disposing); + base.Dispose(disposing); + } + + private void ReleaseResources(bool disposing) + { + if (_disposed) + { + return; + } + _disposed = true; + + if (disposing) + { + if (_outputTexRd is not null) + { + _outputTexRd.TextureRdRid = new Rid(); + } + + if (_backend is not null && RenderingServer.GetRenderingDevice() is not null) + { + RenderingServer.CallOnRenderThread(_disposeCallable); + RenderingServer.ForceSync(); + } + } + + _fontCache.Dispose(); + } + + private sealed class HbGpuVulkanBackend + { + private readonly Texture2Drd _outputTexRd; + + private readonly byte[] _quadUploadBytes = new byte[HbGpuCommandWriter.MaxQuads * 80]; + private readonly byte[] _pushConstantBytes = new byte[PushConstantBytes]; + private static readonly Color[] ClearColors = { new Color(0f, 0f, 0f, 0f) }; + + private RenderingDevice? _rd; + private bool _initialized; + private bool _failed; + + private Rid _shaderRid; + private Rid _pipelineRid; + private Rid _nearestSamplerRid; + private Rid _atlasTexRid; + private Rid _quadSsboRid; + private Rid _uniformSetRid; + private Rid _colorTexRid; + private Rid _framebufferRid; + private int _fbWidth; + private int _fbHeight; + + private ulong _frameIndex; + private ulong _lastSampledTimestampFrame = ulong.MaxValue; + + public bool ProfilingEnabled { get; set; } + public double LastHbGpuMs { get; private set; } + public int LastDrawCallCount { get; private set; } + + public HbGpuVulkanBackend(Texture2Drd outputTexRd) + { + _outputTexRd = outputTexRd; + } + + public void RenderFrame( + HbGpuQuadInstance[] quads, + int quadCount, + byte[] atlasMirrorBytes, + bool atlasDirty, + float logicalW, + float logicalH, + int physW, + int physH) + { + if (_failed) + { + return; + } + + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null) + { + return; + } + + if (!_initialized) + { + if (!TryInitialize(rd, atlasMirrorBytes, physW, physH)) + { + _failed = true; + return; + } + } + else + { + if (atlasDirty) + { + rd.TextureUpdate(_atlasTexRid, 0, atlasMirrorBytes); + } + if (physW != _fbWidth || physH != _fbHeight) + { + RecreateRenderTarget(rd, physW, physH); + } + } + + _rd = rd; + _frameIndex++; + + // Upload quad instances into SSBO + if (quadCount > 0) + { + uint byteLen = (uint)(quadCount * 80); + ReadOnlySpan srcBytes = MemoryMarshal.AsBytes(quads.AsSpan(0, quadCount)); + srcBytes.CopyTo(_quadUploadBytes); + rd.BufferUpdate(_quadSsboRid, 0, byteLen, _quadUploadBytes); + } + + bool captureTs = ProfilingEnabled && rd.GetCapturedTimestampsCount() < 180; + if (ProfilingEnabled) + { + SamplePreviousTimestamps(rd); + } + if (captureTs) + { + rd.CaptureTimestamp("HbGpu_Start"); + } + + long dl = rd.DrawListBegin(_framebufferRid, RenderingDevice.DrawFlags.ClearColorAll, ClearColors); + if (quadCount > 0) + { + var pc = new PushConstants + { + C0R0 = 2.0f / logicalW, + C1R1 = 2.0f / logicalH, + C2R2 = 1.0f, + C3R0 = -1.0f, + C3R1 = -1.0f, + C3R3 = 1.0f, + ViewportX = physW, + ViewportY = physH, + LogicalW = logicalW, + LogicalH = logicalH + }; + MemoryMarshal.Write(_pushConstantBytes, in pc); + + rd.DrawListBindRenderPipeline(dl, _pipelineRid); + rd.DrawListBindUniformSet(dl, _uniformSetRid, 0); + rd.DrawListSetPushConstant(dl, _pushConstantBytes, PushConstantBytes); + rd.DrawListDraw(dl, useIndices: false, instances: (uint)quadCount, proceduralVertexCount: 6u); + LastDrawCallCount = 1; + } + else + { + LastDrawCallCount = 0; + } + rd.DrawListEnd(); + + if (captureTs) + { + rd.CaptureTimestamp("HbGpu_End"); + } + } + + private void CreateAtlasAndUniformSet(RenderingDevice rd, byte[] initialAtlasBytes) + { + var nearestState = new RDSamplerState + { + MinFilter = RenderingDevice.SamplerFilter.Nearest, + MagFilter = RenderingDevice.SamplerFilter.Nearest, + RepeatU = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatV = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatW = RenderingDevice.SamplerRepeatMode.ClampToEdge + }; + _nearestSamplerRid = rd.SamplerCreate(nearestState); + + var atlasFmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R16G16B16A16Sint, + Width = AtlasTexWidth, + Height = AtlasTexHeight, + Depth = 1, + ArrayLayers = 1, + Mipmaps = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit + | RenderingDevice.TextureUsageBits.CanUpdateBit + }; + _atlasTexRid = rd.TextureCreate( + atlasFmt, + new RDTextureView(), + new Godot.Collections.Array { initialAtlasBytes }); + + var u0 = new RDUniform + { + UniformType = RenderingDevice.UniformType.SamplerWithTexture, + Binding = 0 + }; + u0.AddId(_nearestSamplerRid); + u0.AddId(_atlasTexRid); + + var u1 = new RDUniform + { + UniformType = RenderingDevice.UniformType.StorageBuffer, + Binding = 1 + }; + u1.AddId(_quadSsboRid); + + _uniformSetRid = rd.UniformSetCreate(new Godot.Collections.Array { u0, u1 }, _shaderRid, 0); + } + + private void SamplePreviousTimestamps(RenderingDevice rd) + { + uint count = rd.GetCapturedTimestampsCount(); + if (count == 0) + { + return; + } + + ulong tsFrame = rd.GetCapturedTimestampsFrame(); + if (tsFrame == _lastSampledTimestampFrame) + { + return; + } + _lastSampledTimestampFrame = tsFrame; + + ulong tStart = 0, tEnd = 0; + for (uint i = 0; i < count; i++) + { + string name = rd.GetCapturedTimestampName(i); + if (name == "HbGpu_Start") + { + tStart = rd.GetCapturedTimestampGpuTime(i); + } + else if (name == "HbGpu_End") + { + tEnd = rd.GetCapturedTimestampGpuTime(i); + } + } + + if (tStart > 0 && tEnd >= tStart) + { + LastHbGpuMs = (tEnd - tStart) / 1_000_000.0; + } + } + + private bool TryInitialize(RenderingDevice rd, byte[] initialAtlasBytes, int physW, int physH) + { + _rd = rd; + + string vertSrc = BuildVertexShaderSource(); + string fragSrc = BuildFragmentShaderSource(); + + using var rdSrc = new RDShaderSource + { + Language = RenderingDevice.ShaderLanguage.Glsl, + SourceVertex = vertSrc, + SourceFragment = fragSrc + }; + + using RDShaderSpirV spirv = rd.ShaderCompileSpirVFromSource(rdSrc, allowCache: true); + if (!string.IsNullOrEmpty(spirv.CompileErrorVertex)) + { + GD.PrintErr($"HbGpuCanvas vertex SPIR-V error: {spirv.CompileErrorVertex}"); + return false; + } + if (!string.IsNullOrEmpty(spirv.CompileErrorFragment)) + { + GD.PrintErr($"HbGpuCanvas fragment SPIR-V error: {spirv.CompileErrorFragment}"); + return false; + } + + _shaderRid = rd.ShaderCreateFromSpirV(spirv, "HbGpuCanvas"); + if (!_shaderRid.IsValid) + { + GD.PrintErr("HbGpuCanvas: ShaderCreateFromSpirV failed."); + return false; + } + + _quadSsboRid = rd.StorageBufferCreate((uint)(HbGpuCommandWriter.MaxQuads * 80)); + CreateAtlasAndUniformSet(rd, initialAtlasBytes); + + RecreateRenderTarget(rd, physW, physH); + + long fbFormat = rd.FramebufferGetFormat(_framebufferRid); + + var rasterState = new RDPipelineRasterizationState + { + CullMode = RenderingDevice.PolygonCullMode.Disabled + }; + var msState = new RDPipelineMultisampleState + { + SampleCount = RenderingDevice.TextureSamples.Samples1 + }; + var dsState = new RDPipelineDepthStencilState(); + var blendAttachment = new RDPipelineColorBlendStateAttachment + { + EnableBlend = true, + SrcColorBlendFactor = RenderingDevice.BlendFactor.One, + DstColorBlendFactor = RenderingDevice.BlendFactor.OneMinusSrcAlpha, + ColorBlendOp = RenderingDevice.BlendOperation.Add, + SrcAlphaBlendFactor = RenderingDevice.BlendFactor.One, + DstAlphaBlendFactor = RenderingDevice.BlendFactor.OneMinusSrcAlpha, + AlphaBlendOp = RenderingDevice.BlendOperation.Add + }; + var blendState = new RDPipelineColorBlendState(); + blendState.Attachments.Add(blendAttachment); + + _pipelineRid = rd.RenderPipelineCreate( + _shaderRid, + fbFormat, + RenderingDevice.InvalidFormatId, + RenderingDevice.RenderPrimitive.Triangles, + rasterState, + msState, + dsState, + blendState); + + if (!_pipelineRid.IsValid) + { + GD.PrintErr("HbGpuCanvas: RenderPipelineCreate failed."); + return false; + } + + _initialized = true; + return true; + } + + private void RecreateRenderTarget(RenderingDevice rd, int physW, int physH) + { + if (_framebufferRid.IsValid) + { + rd.FreeRid(_framebufferRid); + _framebufferRid = new Rid(); + } + if (_colorTexRid.IsValid) + { + _outputTexRd.TextureRdRid = new Rid(); + rd.FreeRid(_colorTexRid); + _colorTexRid = new Rid(); + } + + var fmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R8G8B8A8Unorm, + Width = (uint)physW, + Height = (uint)physH, + Depth = 1, + ArrayLayers = 1, + Mipmaps = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.ColorAttachmentBit + | RenderingDevice.TextureUsageBits.SamplingBit + | RenderingDevice.TextureUsageBits.CanCopyFromBit + }; + _colorTexRid = rd.TextureCreate(fmt, new RDTextureView()); + _framebufferRid = rd.FramebufferCreate(new Godot.Collections.Array { _colorTexRid }); + _fbWidth = physW; + _fbHeight = physH; + _outputTexRd.TextureRdRid = _colorTexRid; + } + + public void TryReadbackOnRenderThread(out byte[]? data, out int width, out int height) + { + if (_rd is null || !_initialized || !_colorTexRid.IsValid) + { + data = null; + width = 0; + height = 0; + return; + } + + data = _rd.TextureGetData(_colorTexRid, 0); + width = _fbWidth; + height = _fbHeight; + } + + public void DisposeRdResources() + { + if (_rd is null) + { + return; + } + + _outputTexRd.TextureRdRid = new Rid(); + + if (_framebufferRid.IsValid) { _rd.FreeRid(_framebufferRid); _framebufferRid = new Rid(); } + if (_colorTexRid.IsValid) { _rd.FreeRid(_colorTexRid); _colorTexRid = new Rid(); } + if (_uniformSetRid.IsValid) { _rd.FreeRid(_uniformSetRid); _uniformSetRid = new Rid(); } + if (_quadSsboRid.IsValid) { _rd.FreeRid(_quadSsboRid); _quadSsboRid = new Rid(); } + if (_atlasTexRid.IsValid) { _rd.FreeRid(_atlasTexRid); _atlasTexRid = new Rid(); } + if (_nearestSamplerRid.IsValid) { _rd.FreeRid(_nearestSamplerRid); _nearestSamplerRid = new Rid(); } + if (_pipelineRid.IsValid) { _rd.FreeRid(_pipelineRid); _pipelineRid = new Rid(); } + if (_shaderRid.IsValid) { _rd.FreeRid(_shaderRid); _shaderRid = new Rid(); } + + _initialized = false; + _rd = null; + } + + private static string BuildVertexShaderSource() + { + string sharedVert = HbGpuNative.GetShaderSource(HbGpuShaderStage.Vertex, HbGpuShaderKind.Shared); + return $@"#version 450 +{sharedVert} + +struct QuadInstance {{ + vec4 em_box; + vec4 pos_anchor; + vec4 xform; + vec4 color; + uvec4 meta; +}}; + +layout(set = 0, binding = 1, std430) readonly buffer Quads {{ + QuadInstance quads[]; +}}; + +layout(push_constant, std430) uniform Push {{ + mat4 u_mvp; + vec2 u_viewport; + vec2 u_logicalSize; +}} pc; + +layout(location = 0) out vec2 v_em; +layout(location = 1) out vec4 v_color; +layout(location = 2) flat out uint v_blob_loc; +layout(location = 3) flat out uint v_flags; +layout(location = 4) flat out uvec2 v_clip_packed; + +void main() {{ + QuadInstance q = quads[gl_InstanceIndex]; + const uint idxMap[6] = uint[6](0u, 1u, 2u, 0u, 2u, 3u); + uint c = idxMap[gl_VertexIndex]; + vec2 uv = vec2((c == 1u || c == 2u) ? 1.0 : 0.0, (c >= 2u) ? 1.0 : 0.0); + vec2 em = mix(q.em_box.xy, q.em_box.zw, uv); + vec2 emSgn = uv * 2.0 - 1.0; + + vec2 dEm = em - q.pos_anchor.xy; + float m00 = q.xform.x; + float m01 = q.xform.y; + float m10 = q.xform.z; + float m11 = q.xform.w; + vec2 pos = q.pos_anchor.zw + vec2(m00 * dEm.x + m01 * dEm.y, m10 * dEm.x + m11 * dEm.y); + + vec2 ax = vec2(m00, m10); + vec2 ay = vec2(m01, m11); + float lx = length(ax); + float ly = length(ay); + vec2 axisX = lx > 1e-8 ? ax / lx : vec2(1.0, 0.0); + vec2 axisY = ly > 1e-8 ? ay / ly : vec2(0.0, 1.0); + vec2 normal = axisX * emSgn.x + axisY * emSgn.y; + + float det = m00 * m11 - m01 * m10; + float invDet = abs(det) > 1e-12 ? (1.0 / det) : 0.0; + vec4 jac = vec4(m11, -m01, -m10, m00) * invDet; + + hb_gpu_dilate(pos, em, normal, jac, pc.u_mvp, pc.u_viewport); + + gl_Position = pc.u_mvp * vec4(pos, 0.0, 1.0); + v_em = em; + v_color = q.color; + v_blob_loc = q.meta.x; + v_flags = q.meta.y; + v_clip_packed = q.meta.zw; +}} +"; + } + + private static string BuildFragmentShaderSource() + { + string sharedFrag = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Shared); + string drawFrag = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Draw); + const string oldAtlasDecl = "uniform highp isampler2D hb_gpu_atlas;"; + const string oldWidthDecl = "uniform int hb_gpu_atlas_width;"; + if (!sharedFrag.Contains(oldAtlasDecl, StringComparison.Ordinal) || + !sharedFrag.Contains(oldWidthDecl, StringComparison.Ordinal)) + { + throw new InvalidOperationException("Unexpected hb-gpu-fragment.glsl HB_GPU_ATLAS_2D uniform layout."); + } + sharedFrag = sharedFrag + .Replace(oldAtlasDecl, "layout(set = 0, binding = 0) uniform highp isampler2D hb_gpu_atlas;", StringComparison.Ordinal) + .Replace(oldWidthDecl, $"const int hb_gpu_atlas_width = {AtlasTexWidth};", StringComparison.Ordinal); + + return $@"#version 450 +#define HB_GPU_ATLAS_2D +{sharedFrag} +{drawFrag} + +layout(push_constant, std430) uniform Push {{ + mat4 u_mvp; + vec2 u_viewport; + vec2 u_logicalSize; +}} pc; + +layout(location = 0) in vec2 v_em; +layout(location = 1) in vec4 v_color; +layout(location = 2) flat in uint v_blob_loc; +layout(location = 3) flat in uint v_flags; +layout(location = 4) flat in uvec2 v_clip_packed; + +layout(location = 0) out vec4 frag_color; + +void main() {{ + vec2 dx = dFdx(v_em); + vec2 dy = dFdy(v_em); + vec2 em_px = vec2(length(vec2(dx.x, dy.x)), length(vec2(dx.y, dy.y))); + vec2 pixelsPerEm = 1.0 / max(em_px, vec2(1e-6)); + float cov; + + if ((v_flags & 2u) != 0u) {{ + vec2 edgeDist = (500.0 - abs(v_em)) * pixelsPerEm; + cov = clamp(min(edgeDist.x, edgeDist.y) + 0.5, 0.0, 1.0); + }} else {{ + cov = _hb_gpu_slug(v_em, pixelsPerEm, v_blob_loc); + if ((v_flags & 1u) != 0u) {{ + float ppem = hb_gpu_ppem(v_em, v_blob_loc); + if (cov > 0.0 && cov < 1.0) {{ + float brightness = dot(v_color.rgb, vec3(1.0 / 3.0)); + cov = hb_gpu_stem_darken(cov, brightness, ppem); + }} + }} + }} + + if (v_clip_packed.y != 0xFFFFFFFFu) {{ + vec2 logicalPos = gl_FragCoord.xy * (pc.u_logicalSize / pc.u_viewport); + vec2 cMin = vec2(float(v_clip_packed.x & 0xFFFFu), float(v_clip_packed.x >> 16u)); + vec2 cMax = vec2(float(v_clip_packed.y & 0xFFFFu), float(v_clip_packed.y >> 16u)); + if (logicalPos.x < cMin.x || logicalPos.y < cMin.y || logicalPos.x > cMax.x || logicalPos.y > cMax.y) {{ + cov = 0.0; + }} + }} + + float a = clamp(v_color.a * cov, 0.0, 1.0); + frag_color = vec4(v_color.rgb * a, a); +}} +"; + } + } +} diff --git a/client/Hud.cs b/client/Hud.cs new file mode 100644 index 0000000..41acd41 --- /dev/null +++ b/client/Hud.cs @@ -0,0 +1,2879 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using Godot; +using RustToDust.Core; +using RustToDust.HbGpu; + +namespace RustToDust.Client; + +public enum HitMarkerKind +{ + None = 0, + Armor = 1, + Core = 2, + Kill = 3 +} + +/// +/// Rust to Dust industrial HUD rendered in a single Vulkan draw call via : +/// - Top-Left: Chassis badge (DORSAL/CORONAL), Core HP bar, Speed/Alt/Alive/Kills, Safe Circle, Detection, Wave, Net, Prompt. +/// - Top-Right: Tactical Radar (Safe Circle, RadarSignature-scaled Spectator Wall, lock lines, contenders, salvage). +/// - Bottom-Left: Live clickable Aetheria Hardpoint & Heat Schematic + Cargo Salvage Rack (Tab expands Garage details). +/// - Bottom-Right: Imperial Broadcast Chyron (Weksa commentary). +/// - Center & 3D World: Crosshair + heat arc + incoming/outgoing hit feedback + squad chevrons + target boxes + offscreen arrows. +/// +public partial class Hud : CanvasLayer +{ + private static readonly Color BgDark = new(0.075f, 0.086f, 0.075f, 0.88f); + private static readonly Color BgInner = Color.FromHtml("#1b1f1b"); + private static readonly Color BgRowHover = new(0.16f, 0.20f, 0.16f, 0.92f); + private static readonly Color BorderCol = Color.FromHtml("#3e4638"); + private static readonly Color OliveCol = Color.FromHtml("#9bb06a"); + private static readonly Color OrangeCol = Color.FromHtml("#e08a4a"); + private static readonly Color TextLight = Color.FromHtml("#e4dfd2"); + private static readonly Color TextMuted = Color.FromHtml("#989487"); + private static readonly Color CyanCol = Color.FromHtml("#44d9e8"); + private static readonly Color AlliedCol = Color.FromHtml("#52e3a8"); + private static readonly Color GoldCol = Color.FromHtml("#e6b838"); + private static readonly Color RedCol = Color.FromHtml("#d93829"); + private static readonly Color PatronColor = Color.FromHtml("#4ba8a5"); + private static readonly Color ShadowCol = new(0.04f, 0.05f, 0.04f, 0.88f); + + private const float HitArcDuration = 0.65f; + private const float BorderPad = 36f; + private const float PanelAvoidPad = 18f; + private const float OffscreenHostileMaxDistance = 220f; + private const int MaxOffscreenHostileArrows = 6; + private const int MaxCargoHitRects = 16; + + private struct IncomingHitArc + { + public float SourceX; + public float SourceZ; + public WeaponVisualClass WeaponClass; + public float Age; + } + + private readonly struct OffscreenMarker + { + public readonly System.Numerics.Vector3 CamLocal; + public readonly float Distance; + public readonly Color Color; + public readonly bool IsLockedOnLocal; + + public OffscreenMarker(System.Numerics.Vector3 camLocal, float distance, Color color, bool isLockedOnLocal) + { + CamLocal = camLocal; + Distance = distance; + Color = color; + IsLockedOnLocal = isLockedOnLocal; + } + } + + private readonly Func _getSession; + private readonly Action _onEquipCargo; + private readonly Func _getCameraYaw; + private readonly Func? _projectWorld; + + private ColorRect _vignetteRect = null!; + private ShaderMaterial _vignetteMat = null!; + private ColorRect _bottomLeftBg = null!; + private InventoryGridControl _schematic = null!; + private HbGpuCanvas _hbCanvas = null!; + + // Interactive [F9] multiplayer input panel (kept on Godot Controls until Thing 2 Cut 14c) + private PanelContainer _netPanel = null!; + private Label _netModeBadge = null!; + private Label _netPanelStatus = null!; + private LineEdit _callsignEdit = null!; + private LineEdit _endpointEdit = null!; + private string? _uiNetError; + + // Layout rects (logical pixels) + private Rect2 _topLeftRect; + private Rect2 _topRightRect; + private Rect2 _bottomLeftRect; + private Rect2 _schematicRect; + private Rect2 _chyronRect; + private Rect2 _outcomeRect; + private bool _outcomeVisible; + private Vector2 _lastViewportSize = new(1280f, 720f); + + // Cargo click hitboxes (zero Button allocations) + private readonly Rect2[] _cargoRowRects = new Rect2[MaxCargoHitRects]; + private readonly Rect2[] _cargoFitRects = new Rect2[MaxCargoHitRects]; + private int _cargoHitCount; + private ChassisGrid? _lastCargoGrid; + private int _selectedCargoIndex = -1; + private bool _garageExpanded; + private Vector2I? _lastHoveredCell; + + // Vignette & combat feedback + private float _damagePulse; + private float _lowCoreRatio; + private float _overheatPulse; + private float _vignetteTime; + private readonly IncomingHitArc[] _incomingArcs = new IncomingHitArc[8]; + private int _incomingArcCount; + private HitMarkerKind _hitMarkerKind; + private float _hitMarkerRemaining; + private float _hitMarkerDuration; + private MatchState? _lastCrosshairState; + + // Zero-GC scratch & change-detected text caches + private readonly char[] _scratch = new char[512]; + private readonly List _offscreenHostiles = new(16); + private static readonly Comparison OffscreenSortComparison = static (a, b) => + { + int lockCmp = b.IsLockedOnLocal.CompareTo(a.IsLockedOnLocal); + return lockCmp != 0 ? lockCmp : a.Distance.CompareTo(b.Distance); + }; + + private readonly List _promptLines = new(3); + private string _cachedPromptText = string.Empty; + private int _lastPromptKey = int.MinValue; + private bool _lastPromptPod; + private int _lastPodAglRounded = int.MinValue; + private int _lastPodHorizRounded = int.MinValue; + private int _lastPodVertRounded = int.MinValue; + private bool _lastPodBurn; + + private readonly List _hoverLines = new(3); + private string _cachedHoverText = "HOVER CELL FOR TELEMETRY"; + private Color _cachedHoverColor = TextMuted; + + private readonly List _garageLines = new(24); + private string _cachedGarageDetails = string.Empty; + private int _lastGarageHash = int.MinValue; + + private BroadcastFeed? _lastBroadcastFeed; + private long _lastChyronVersion = -1; + private readonly string[] _chyronDisplayLines = new string[3]; + private readonly bool[] _chyronIsLatest = new bool[3]; + private readonly List _chyronWrapScratch = new(8); + private int _chyronLineCount; + + private readonly List _hintLines = new(2); + private int _lastHintMode = -1; + + private IClientArenaSession? _latestSession; + private string? _cachedChassisName; + private string _cachedChassisUpper = "CHASSIS"; + private bool _inputBlocked; + private bool _dirtyEmit; + private bool _emittedThisFrame; + + public event Action? JoinRequested; + public event Action? HostRequested; + public event Action? SoloRequested; + public event Action? NetworkPanelToggled; + + public Hud( + Func getSession, + Action onEquipCargo, + Func? getCameraYaw = null, + Func? projectWorld = null) + { + _getSession = getSession; + _onEquipCargo = onEquipCargo; + _getCameraYaw = getCameraYaw ?? (() => 0f); + _projectWorld = projectWorld; + Layer = 10; + } + + public HbGpuCanvas HbCanvas => _hbCanvas; + public bool GarageExpanded => _garageExpanded; + public bool NetworkPanelOpen => _netPanel.Visible; + public bool IsUiTextInputFocused => _netPanel.Visible && (_callsignEdit.HasFocus() || _endpointEdit.HasFocus()); + public InventoryGridControl Schematic => _schematic; + internal int ActiveHitArcCount => _incomingArcCount; + internal bool HasActiveHitMarker => _hitMarkerRemaining > 0f && _hitMarkerKind != HitMarkerKind.None; + internal HitMarkerKind ActiveHitMarkerKind => HasActiveHitMarker ? _hitMarkerKind : HitMarkerKind.None; + internal bool IsVignetteVisible => _vignetteRect is not null && _vignetteRect.Visible; + internal Rect2 BottomLeftPanelRect => _bottomLeftRect; + internal Rect2 ChyronPanelRect => _chyronRect; + internal string HoverLabelText => _cachedHoverText; + internal string PromptLabelText => _cachedPromptText; + internal string GarageDetailsText => _cachedGarageDetails; + + internal void PushTestHitArc(float sourceX, float sourceZ, WeaponVisualClass weaponClass) + { + if (_incomingArcCount >= _incomingArcs.Length) + { + for (int i = 1; i < _incomingArcs.Length; i++) + { + _incomingArcs[i - 1] = _incomingArcs[i]; + } + _incomingArcCount = _incomingArcs.Length - 1; + } + _incomingArcs[_incomingArcCount++] = new IncomingHitArc + { + SourceX = sourceX, + SourceZ = sourceZ, + WeaponClass = weaponClass, + Age = 0f + }; + _dirtyEmit = true; + } + + internal void ResetFeedback() + { + _damagePulse = 0f; + _lowCoreRatio = 0f; + _overheatPulse = 0f; + _vignetteTime = 0f; + _incomingArcCount = 0; + _hitMarkerKind = HitMarkerKind.None; + _hitMarkerRemaining = 0f; + _hitMarkerDuration = 0f; + if (_vignetteRect is not null) + { + _vignetteRect.Visible = false; + } + _dirtyEmit = true; + } + + internal void SimulateCellHover(Vector2I? cell, HardpointSpec? hp) => OnSchematicHoverChanged(cell, hp); + + public override void _Ready() + { + Shader vigShader = GD.Load("res://hud_vignette.gdshader") + ?? throw new InvalidOperationException("Failed to load res://hud_vignette.gdshader"); + _vignetteMat = new ShaderMaterial { Shader = vigShader }; + _vignetteRect = new ColorRect + { + Name = "HudVignette", + Material = _vignetteMat, + MouseFilter = Control.MouseFilterEnum.Ignore, + Visible = false + }; + _vignetteRect.SetAnchorsPreset(Control.LayoutPreset.FullRect); + AddChild(_vignetteRect); + + // Dark backdrop under _schematic so inactive holes (e.g. Raptor) show panel BgDark instead of 3D world + _bottomLeftBg = new ColorRect + { + Name = "BottomLeftBackdrop", + Color = BgDark, + MouseFilter = Control.MouseFilterEnum.Ignore + }; + AddChild(_bottomLeftBg); + + _schematic = new InventoryGridControl + { + Name = "SchematicGrid", + ExternalHbGpuOwner = true, + CustomMinimumSize = new Vector2(180f, 188f) + }; + _schematic.HardpointClicked += OnHardpointClicked; + _schematic.HoverChanged += OnSchematicHoverChanged; + AddChild(_schematic); + + // Single-draw-call HarfBuzz hb-gpu overlay sits strictly ABOVE _schematic's bilinear thermal backdrop + _hbCanvas = new HbGpuCanvas + { + Name = "HbGpuCanvas", + MouseFilter = Control.MouseFilterEnum.Ignore + }; + _hbCanvas.SetAnchorsAndOffsetsPreset(Control.LayoutPreset.FullRect); + AddChild(_hbCanvas); + + BuildNetworkPanel(); + + _lastViewportSize = GetViewportSizeSafe(); + RecomputeLayoutRects(_lastViewportSize, _latestSession); + } + + public void ToggleNetworkPanel() => SetNetworkPanelOpen(!_netPanel.Visible); + + public void SetNetworkPanelOpen(bool open) + { + if (_netPanel.Visible == open) return; + _netPanel.Visible = open; + if (!open) + { + _callsignEdit.ReleaseFocus(); + _endpointEdit.ReleaseFocus(); + } + NetworkPanelToggled?.Invoke(open); + } + + public void SetNetworkDefaults(string endpoint, string callsign) + { + if (!string.IsNullOrWhiteSpace(endpoint)) + { + _endpointEdit.Text = endpoint.Trim(); + } + if (!string.IsNullOrWhiteSpace(callsign)) + { + _callsignEdit.Text = callsign.Trim(); + } + } + + public void SetNetworkError(string? err) + { + _uiNetError = string.IsNullOrWhiteSpace(err) ? null : err; + } + + public void ToggleGarage() + { + _garageExpanded = !_garageExpanded; + _lastGarageHash = int.MinValue; + _schematic.CustomMinimumSize = _garageExpanded ? new Vector2(198f, 208f) : new Vector2(180f, 188f); + RecomputeLayoutRects(GetViewportSizeSafe(), _latestSession); + _dirtyEmit = true; + } + + public void SetInputBlocked(bool blocked) + { + _inputBlocked = blocked; + } + + public void SetMatchHudActive(bool active) + { + Visible = active; + if (!active) + { + _inputBlocked = false; + if (_netPanel.Visible) + { + _netPanel.Visible = false; + _callsignEdit.ReleaseFocus(); + _endpointEdit.ReleaseFocus(); + } + if (_garageExpanded) + { + ToggleGarage(); + } + ResetFeedback(); + } + } + + public override void _Input(InputEvent @event) + { + if (!Visible || _inputBlocked || _netPanel.Visible) + { + return; + } + + if (@event is InputEventMouseButton mb && mb.Pressed && mb.ButtonIndex == MouseButton.Left) + { + if (_lastCargoGrid is not null && + _bottomLeftRect.HasPoint(mb.Position) && + !_schematic.GetGlobalRect().HasPoint(mb.Position)) + { + for (int i = 0; i < _cargoHitCount; i++) + { + if (_cargoFitRects[i].HasPoint(mb.Position)) + { + AutoFitCargo(_lastCargoGrid, i); + GetViewport().SetInputAsHandled(); + _dirtyEmit = true; + return; + } + if (_cargoRowRects[i].HasPoint(mb.Position)) + { + _selectedCargoIndex = (_selectedCargoIndex == i) ? -1 : i; + if (_lastHoveredCell is null) + { + UpdateCargoSelectionTooltip(_lastCargoGrid); + } + GetViewport().SetInputAsHandled(); + _dirtyEmit = true; + return; + } + } + } + } + } + + public override void _Process(double delta) + { + if (!Visible) + { + _emittedThisFrame = false; + return; + } + + float dt = (float)delta; + bool timerAdvanced = AdvanceTimers(dt); + + if (_vignetteRect is not null) + { + if (_damagePulse > 0f && dt > 0f) + { + _damagePulse = MathF.Max(0f, _damagePulse - dt * 2.4f); + if (_damagePulse < 0.005f) _damagePulse = 0f; + } + bool active = _damagePulse >= 0.01f || _lowCoreRatio >= 0.01f || _overheatPulse >= 0.01f; + _vignetteRect.Visible = active; + if (active) + { + _vignetteTime += MathF.Max(0f, dt); + _vignetteMat.SetShaderParameter("damage_pulse", _damagePulse); + _vignetteMat.SetShaderParameter("low_core_ratio", _lowCoreRatio); + _vignetteMat.SetShaderParameter("overheat_pulse", _overheatPulse); + _vignetteMat.SetShaderParameter("time_sec", _vignetteTime); + } + } + else if (dt > 0f) + { + _vignetteTime += dt; + } + + if ((_dirtyEmit || timerAdvanced) && !_emittedThisFrame && _latestSession is not null) + { + EmitHudFrame(_latestSession); + } + + _emittedThisFrame = false; + _dirtyEmit = false; + } + + private bool AdvanceTimers(float dt) + { + bool dirty = false; + if (_incomingArcCount > 0 && dt > 0f) + { + int write = 0; + for (int i = 0; i < _incomingArcCount; i++) + { + _incomingArcs[i].Age += dt; + if (_incomingArcs[i].Age < HitArcDuration) + { + _incomingArcs[write++] = _incomingArcs[i]; + } + } + _incomingArcCount = write; + dirty = true; + } + + if (_hitMarkerRemaining > 0f && dt > 0f) + { + _hitMarkerRemaining = MathF.Max(0f, _hitMarkerRemaining - dt); + if (_hitMarkerRemaining <= 0.001f) + { + _hitMarkerRemaining = 0f; + _hitMarkerKind = HitMarkerKind.None; + } + dirty = true; + } + + return dirty; + } + + public void ConsumeEvents( + IReadOnlyList events, + int localContenderId, + float localCoreHpRatio, + float localMaxThermalRatio) + { + for (int i = 0; i < events.Count; i++) + { + switch (events[i]) + { + case MatchResetEvent: + ResetFeedback(); + break; + + case HitImpactEvent hit: + if (hit.TargetKind == (byte)HitTargetKind.Contender && hit.TargetId == localContenderId) + { + var wc = (WeaponVisualClass)hit.WeaponClass; + PushTestHitArc(hit.SourceX, hit.SourceZ, wc); + float pulse = wc is WeaponVisualClass.Explosive or WeaponVisualClass.RocketSalvo or WeaponVisualClass.GaussRail + ? 0.95f + : 0.62f; + _damagePulse = MathF.Max(_damagePulse, pulse); + } + bool targetIsVehicle = hit.TargetKind == (byte)HitTargetKind.Contender + || hit.TargetKind == (byte)HitTargetKind.Spectator; + if (targetIsVehicle && hit.IsContenderShooter && hit.ShooterId == localContenderId) + { + TriggerHitMarker(hit.CoreDamage > 0.001f, hit.Killed); + } + break; + } + } + + _lowCoreRatio = localCoreHpRatio < 0.35f + ? Math.Clamp((0.35f - localCoreHpRatio) / 0.35f, 0f, 1f) + : 0f; + _overheatPulse = localMaxThermalRatio >= 0.85f + ? Math.Clamp((localMaxThermalRatio - 0.85f) / 0.25f, 0.35f, 1.0f) + : 0f; + + if (_vignetteRect is not null) + { + bool active = _damagePulse >= 0.01f || _lowCoreRatio >= 0.01f || _overheatPulse >= 0.01f; + _vignetteRect.Visible = active; + if (active) + { + _vignetteMat.SetShaderParameter("damage_pulse", _damagePulse); + _vignetteMat.SetShaderParameter("low_core_ratio", _lowCoreRatio); + _vignetteMat.SetShaderParameter("overheat_pulse", _overheatPulse); + _vignetteMat.SetShaderParameter("time_sec", _vignetteTime); + } + } + } + + private void TriggerHitMarker(bool coreHit, bool killed) + { + HitMarkerKind nextKind = killed + ? HitMarkerKind.Kill + : (coreHit ? HitMarkerKind.Core : HitMarkerKind.Armor); + if (_hitMarkerRemaining > 0f && (int)nextKind < (int)_hitMarkerKind) + { + nextKind = _hitMarkerKind; + } + _hitMarkerKind = nextKind; + _hitMarkerDuration = nextKind switch + { + HitMarkerKind.Kill => 0.38f, + HitMarkerKind.Core => 0.26f, + _ => 0.18f + }; + _hitMarkerRemaining = _hitMarkerDuration; + _dirtyEmit = true; + } + + public bool IsPointerOverInteractiveHud(Vector2 screenPos) + { + return (Visible && _topLeftRect.HasPoint(screenPos)) + || (Visible && _topRightRect.HasPoint(screenPos)) + || (Visible && _bottomLeftRect.HasPoint(screenPos)) + || (Visible && _chyronRect.HasPoint(screenPos)) + || (Visible && _outcomeVisible && _outcomeRect.HasPoint(screenPos)) + || (_netPanel.Visible && _netPanel.GetGlobalRect().HasPoint(screenPos)); + } + + public bool HasPanelOverlapOrClip(Vector2 viewportSize) + { + RecomputeLayoutRects(viewportSize, _latestSession); + Span rects = stackalloc Rect2[5]; + int count = 0; + rects[count++] = _topLeftRect; + rects[count++] = _topRightRect; + rects[count++] = _bottomLeftRect; + rects[count++] = _chyronRect; + if (_netPanel.Visible) + { + rects[count++] = _netPanel.GetGlobalRect(); + } + + var bounds = new Rect2(Vector2.Zero, viewportSize + new Vector2(1f, 1f)); + for (int i = 0; i < count; i++) + { + if (!bounds.Encloses(rects[i])) + { + return true; + } + for (int j = i + 1; j < count; j++) + { + if (rects[i].Intersects(rects[j])) + { + return true; + } + } + } + return false; + } + + public void Sync(IClientArenaSession session) + { + _latestSession = session; + var state = session.ViewState; + if (!ReferenceEquals(_lastCrosshairState, state)) + { + _lastCrosshairState = state; + _incomingArcCount = 0; + _hitMarkerKind = HitMarkerKind.None; + _hitMarkerRemaining = 0f; + _hitMarkerDuration = 0f; + } + + var player = session.LocalContender; + var net = session.ConnectionStatus; + + OrbitalPod? localPod = FindLocalContenderPod(session, player); + + if (_netPanel.Visible) + { + SyncNetworkPanel(net); + } + + UpdatePromptCache(state, player, localPod); + UpdateHintCache(player); + + _schematic.SetGrid(player.Grid, _selectedCargoIndex); + _lastCargoGrid = player.Grid; + + if (_lastHoveredCell is null) + { + UpdateCargoSelectionTooltip(player.Grid); + } + + if (_garageExpanded) + { + UpdateGarageDetailsCache(player.Grid); + } + + SyncBroadcastChyron(state.Broadcast); + + RecomputeLayoutRects(GetViewportSizeSafe(), session); + EmitHudFrame(session); + _emittedThisFrame = true; + _dirtyEmit = false; + } + + private Vector2 GetViewportSizeSafe() + { + Viewport? vp = GetViewport(); + if (vp is not null) + { + Vector2 vis = vp.GetVisibleRect().Size; + if (vis.X >= 64f && vis.Y >= 64f) + { + _lastViewportSize = vis; + return vis; + } + } + return _lastViewportSize; + } + + private static OrbitalPod? FindLocalContenderPod(IClientArenaSession session, ContenderState player) + { + if (!player.IsInDropPod) return null; + var pods = session.ActivePods; + for (int i = 0; i < pods.Count; i++) + { + if (pods[i].PodKind == OrbitalPodKind.Contender && pods[i].ContenderId == player.Id) + { + return pods[i]; + } + } + return null; + } + + private void RecomputeLayoutRects(Vector2 vpSize, IClientArenaSession? session) + { + float vw = MathF.Max(320f, vpSize.X); + float vh = MathF.Max(240f, vpSize.Y); + + // Top-Left panel + float tlW = 396f; + float tlH = 138f + Math.Max(1, _hintLines.Count) * 14f; + if (session is not null && session.ConnectionStatus.Mode != NetworkMode.Solo) + { + tlH += 17f; + } + if (_promptLines.Count > 0) + { + tlH += 4f + _promptLines.Count * 16f; + } + _topLeftRect = new Rect2(14f, 14f, tlW, tlH); + + // Top-Right Radar panel + float trW = 234f; + float trH = 264f; + _topRightRect = new Rect2(vw - 14f - trW, 14f, trW, trH); + + // Bottom-Left Schematic + Cargo + optional Garage panel + float gridW = _garageExpanded ? 198f : 180f; + float gridH = _garageExpanded ? 208f : 188f; + const float cargoW = 156f; + float garageW = _garageExpanded ? 186f : 0f; + float blW = 10f + gridW + 8f + cargoW + (_garageExpanded ? 8f + garageW : 0f) + 10f; + + float hoverH = MathF.Max(28f, _hoverLines.Count * 14f); + float leftColH = 18f + gridH + 4f + hoverH; + + int cargoCount = session?.LocalContender.Grid.Cargo.Count ?? 0; + float cargoColH = 18f + (cargoCount > 0 ? cargoCount * 21f : 34f); + float garageColH = _garageExpanded ? MathF.Max(140f, _garageLines.Count * 13.5f + 8f) : 0f; + float blH = 8f + MathF.Max(leftColH, MathF.Max(cargoColH, garageColH)) + 8f; + + _bottomLeftRect = new Rect2(14f, vh - 14f - blH, blW, blH); + _schematicRect = new Rect2(_bottomLeftRect.Position.X + 10f, _bottomLeftRect.Position.Y + 8f + 18f, gridW, gridH); + + if (_bottomLeftBg is not null) + { + if (_bottomLeftBg.Position != _bottomLeftRect.Position) _bottomLeftBg.Position = _bottomLeftRect.Position; + if (_bottomLeftBg.Size != _bottomLeftRect.Size) _bottomLeftBg.Size = _bottomLeftRect.Size; + } + if (_schematic is not null) + { + if (_schematic.Position != _schematicRect.Position) _schematic.Position = _schematicRect.Position; + if (_schematic.Size != _schematicRect.Size) _schematic.Size = _schematicRect.Size; + } + + // Bottom-Right Chyron panel + const float chW = 570f; + const float chH = 92f; + _chyronRect = new Rect2(vw - 14f - chW, vh - 14f - chH, chW, chH); + + // Outcome banner + _outcomeRect = new Rect2(vw * 0.5f - 210f, vh * 0.28f - 40f, 420f, 80f); + _outcomeVisible = false; + if (session is not null) + { + var outcome = session.LocalOutcome; + _outcomeVisible = outcome == ClientMatchOutcome.Victory + || outcome == ClientMatchOutcome.Defeat + || session.LocalContender.WaitingForRespawn; + } + } + + private void EmitHudFrame(IClientArenaSession session) + { + if (_hbCanvas is null || !Visible) + { + return; + } + + Vector2 vpSize = GetViewportSizeSafe(); + var state = session.ViewState; + var player = session.LocalContender; + var net = session.ConnectionStatus; + OrbitalPod? localPod = FindLocalContenderPod(session, player); + + _hbCanvas.BeginFrame(); + + // 1. 3D Projected World Markers (behind panels, above scene) + EmitWorldMarkers(session, state, player, vpSize); + + // 2. Center Crosshair, Thermal Heat Arc, Incoming Hit Arcs, Hit-Marker X, Pod Altimeter + EmitCrosshairAndCombatFeedback(state, player, localPod, vpSize * 0.5f); + + // 3. Top-Left Telemetry Panel + EmitTopLeftPanel(session, state, player, net, localPod); + + // 4. Top-Right Radar Panel + EmitTopRightRadarPanel(session, state); + + // 5. Bottom-Left Schematic Panel Frame + Hardpoint Overlay + Hover + Cargo Rack + Garage + EmitBottomLeftPanel(player.Grid); + + // 6. Bottom-Right Broadcast Chyron + EmitChyronPanel(); + + // 7. Outcome / Awaiting Wave Banner + if (_outcomeVisible) + { + EmitOutcomeBanner(session, state, player, net); + } + + // 8. Optional [F9] Network panel chrome + cyan brackets (drawn behind transparent _netPanel controls) + if (_netPanel.Visible) + { + _hbCanvas.DrawPanelFrame(_netPanel.GetGlobalRect(), BgDark, CyanCol, CyanCol, cornerLen: 14f, borderPx: 1.5f, drawBg: true); + } + + _hbCanvas.EndFrameAndSubmit(); + } + + // ------------------------------------------------------------------------- + // 1. Top-Left Panel (0 GC allocs) + // ------------------------------------------------------------------------- + private void EmitTopLeftPanel( + IClientArenaSession session, + MatchState state, + ContenderState player, + NetworkStatusSnapshot net, + OrbitalPod? localPod) + { + _hbCanvas.DrawPanelFrame(_topLeftRect, BgDark, BorderCol, OliveCol, cornerLen: 12f, borderPx: 1.5f); + + float x = _topLeftRect.Position.X + 10f; + float rightX = _topLeftRect.End.X - 10f; + float y = _topLeftRect.Position.Y + 8f; + + int aliveCount = 0; + for (int i = 0; i < state.Contenders.Count; i++) + { + if (state.Contenders[i].Alive) aliveCount++; + } + + // Header + Dorsal/Coronal/Pod badge + if (player.IsInDropPod) + { + bool burning = localPod?.Phase == OrbitalPodPhase.RetroBurn; + _hbCanvas.DrawText("ORBITAL DROP POD", x, y + 14f, 16f, TextLight, wght: 700f); + ReadOnlySpan badge = burning ? "RETRO BURN" : "FREEFALL"; + Color bCol = burning ? OrangeCol : CyanCol; + float bw = _hbCanvas.MeasureTextWidth(badge, 12.5f, wght: 600f); + _hbCanvas.DrawText(badge, rightX - bw, y + 13f, 12.5f, bCol, wght: 600f); + } + else + { + string rawName = player.Grid.Spec.Name; + if (!ReferenceEquals(_cachedChassisName, rawName)) + { + _cachedChassisName = rawName; + _cachedChassisUpper = rawName.ToUpperInvariant(); + } + _hbCanvas.DrawText(_cachedChassisUpper, x, y + 14f, 16f, TextLight, wght: 700f); + bool isCoronal = player.Grid.Spec.Plane == GridPlane.Coronal; + ReadOnlySpan badge = isCoronal ? "CORONAL" : "DORSAL"; + Color bCol = isCoronal ? CyanCol : OliveCol; + float bw = _hbCanvas.MeasureTextWidth(badge, 12.5f, wght: 600f); + _hbCanvas.DrawText(badge, rightX - bw, y + 13f, 12.5f, bCol, wght: 600f); + } + y += 22f; + + // Core HP vector bar + label + float maxCore = MathF.Max(1f, player.Grid.MaxCoreHp); + float coreHp = MathF.Max(0f, player.Grid.CoreHp); + float hpFrac = Math.Clamp(coreHp / maxCore, 0f, 1f); + + SpanWriter sw = new(_scratch); + sw.Append("CORE "); + sw.AppendFloat(coreHp, "F0"); + sw.Append(" / "); + sw.AppendFloat(maxCore, "F0"); + ReadOnlySpan hpSpan = sw.Span; + float hpLabelW = _hbCanvas.MeasureTextWidth(hpSpan, 12.5f, wght: 550f); + float barW = MathF.Max(80f, rightX - x - hpLabelW - 10f); + + _hbCanvas.DrawRectFilled(x, y, barW, 15f, BgInner); + _hbCanvas.DrawRectOutline(x, y, barW, 15f, 1.0f, BorderCol); + if (hpFrac > 0.001f) + { + Color fillCol = hpFrac < 0.35f ? RedCol : OliveCol; + _hbCanvas.DrawRectFilled(x + 1f, y + 1f, MathF.Max(1f, (barW - 2f) * hpFrac), 13f, fillCol); + } + _hbCanvas.DrawText(hpSpan, x + barW + 8f, y + 12f, 12.5f, TextLight, wght: 550f); + y += 21f; + + // Stats line + sw = new SpanWriter(_scratch); + if (player.IsInDropPod) + { + float agl = localPod is not null + ? MathF.Max(0f, localPod.LastAgl) + : MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z)); + float velDown = localPod is not null ? MathF.Max(0f, -localPod.VelY) : MathF.Max(0f, -player.VelY); + float horizSpeed = localPod is not null + ? MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ) + : player.Speed; + sw.Append("ALT "); sw.AppendFloat(agl, "F0"); sw.Append("m | HORIZ "); + sw.AppendFloat(horizSpeed, "F0"); sw.Append(" m/s | VERT "); + sw.AppendFloat(velDown, "F0"); sw.Append(" m/s | ALIVE "); + sw.AppendInt(aliveCount); sw.Append(" / "); sw.AppendInt(state.Contenders.Count); + } + else if (player.Grid.Spec.IsVtol) + { + float agl = MathF.Max(0f, player.Y - player.Grid.Spec.HalfHeight - state.Terrain.SampleHeight(player.X, player.Z)); + sw.Append("SPD "); sw.AppendFloat(player.Speed, "F1"); sw.Append(" m/s | ALT "); + sw.AppendFloat(agl, "F1"); sw.Append("m | ALIVE "); + sw.AppendInt(aliveCount); sw.Append(" / "); sw.AppendInt(state.Contenders.Count); + sw.Append(" | KILLS "); sw.AppendInt(player.Kills); + } + else + { + sw.Append("SPD "); sw.AppendFloat(player.Speed, "F1"); sw.Append(" m/s | ALIVE "); + sw.AppendInt(aliveCount); sw.Append(" / "); sw.AppendInt(state.Contenders.Count); + sw.Append(" | KILLS "); sw.AppendInt(player.Kills); + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 12f, TextMuted, wght: 400f); + y += 18f; + + // Safe ring status + float distCenter = MathF.Sqrt(player.X * player.X + player.Z * player.Z); + float outside = distCenter - state.Spectators.SafeRadius; + int cleared = state.Spectators.CountClearedFor(player.Id); + int provoked = state.Spectators.CountProvokedFor(player.Id); + + sw = new SpanWriter(_scratch); + Color safeCol; + if (outside <= 0f) + { + sw.Append("RING SAFE ("); sw.AppendFloat(-outside, "F0"); sw.Append("m margin)"); + if (provoked > 0) + { + sw.Append(" • "); sw.AppendInt(provoked); sw.Append(" PROVOKED!"); + } + safeCol = provoked > 0 ? OrangeCol : OliveCol; + } + else + { + sw.Append("OUTSIDE +"); sw.AppendFloat(outside, "F0"); sw.Append("m — "); + sw.AppendInt(cleared); sw.Append(" CLEARED"); + if (provoked > 0) + { + sw.Append(" / "); sw.AppendInt(provoked); sw.Append(" PROVOKED!"); + } + else + { + sw.Append("!"); + } + safeCol = RedCol; + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 12.5f, safeCol, wght: 500f); + y += 18f; + + // Detection status + int detectedBy = session.LocalDetectedByCount; + sw = new SpanWriter(_scratch); + Color detCol; + if (detectedBy > 0) + { + sw.Append("DETECTED BY "); sw.AppendInt(detectedBy); + detCol = RedCol; + } + else + { + sw.Append("CONCEALED (TERRAIN)"); + detCol = OliveCol; + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 12.5f, detCol, wght: 500f); + y += 18f; + + // Drop wave / respawn status + var wave = session.DropWaveState; + sw = new SpanWriter(_scratch); + Color waveCol; + if (wave.RespawnCutoffReached) + { + sw.Append("FINAL RING — RESPAWNS CLOSED"); + waveCol = RedCol; + } + else if (wave.NextWaveAtSec is float nextWaveAt) + { + float eta = MathF.Max(0f, nextWaveAt - state.Time); + sw.Append("PATRON WAVE "); sw.AppendInt(wave.NextWaveIndex); + sw.Append(" IN "); sw.AppendFloat(eta, "F0"); + sw.Append("s • RESP "); sw.AppendInt(player.RespawnsRemaining); + waveCol = eta <= 10f ? GoldCol : CyanCol; + } + else + { + sw.Append("WAVE "); sw.AppendInt(wave.CurrentWaveIndex); + sw.Append(" ACTIVE • RESP "); sw.AppendInt(player.RespawnsRemaining); + waveCol = OliveCol; + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 11.8f, waveCol, wght: 450f); + y += 17f; + + // Network status (only non-Solo) + if (net.Mode != NetworkMode.Solo) + { + sw = new SpanWriter(_scratch); + Color netCol; + if (net.Mode == NetworkMode.ListenHost) + { + sw.Append(net.StateLabel); sw.Append(" • HUMANS "); + sw.AppendInt(net.ConnectedHumans); sw.Append("/"); sw.AppendInt(net.MaxHumans); + sw.Append(" • [F9] NET"); + netCol = CyanCol; + } + else if (net.Connected) + { + sw.Append("PING "); sw.AppendInt(net.PingMs); sw.Append(" ms • HUMANS "); + sw.AppendInt(net.ConnectedHumans); sw.Append("/"); sw.AppendInt(net.MaxHumans); + sw.Append(" • [F9] NET"); + netCol = net.PingMs > 120 ? OrangeCol : CyanCol; + } + else + { + sw.Append(net.StateLabel); sw.Append(" • [F9] NET"); + netCol = net.LastError is not null ? RedCol : OrangeCol; + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 11.8f, netCol, wght: 450f); + y += 17f; + } + + // Interaction or orbital prompt + if (_promptLines.Count > 0) + { + y += 4f; + for (int i = 0; i < _promptLines.Count; i++) + { + _hbCanvas.DrawText(_promptLines[i], x, y + 11f, 12f, CyanCol, wght: 550f); + y += 16f; + } + } + + // Controls hint (wrapped & clipped cleanly inside panel width) + HbGpuCommandWriter.PackClipRect( + _topLeftRect.Position.X + 8f, + _topLeftRect.Position.Y + 6f, + _topLeftRect.Size.X - 16f, + _topLeftRect.Size.Y - 12f, + out uint tlClipMin, + out uint tlClipMax); + + if (_hintLines.Count == 0) + { + UpdateHintCache(player); + } + float hintY = _topLeftRect.End.Y - 8f - Math.Max(0, _hintLines.Count - 1) * 13.5f; + for (int i = 0; i < _hintLines.Count; i++) + { + _hbCanvas.DrawText( + _hintLines[i], + x, + hintY, + 10.0f, + TextMuted, + wght: 350f, + clipMinPacked: tlClipMin, + clipMaxPacked: tlClipMax); + hintY += 13.5f; + } + } + + // ------------------------------------------------------------------------- + // 2. Top-Right Radar Panel (0 GC allocs) + // ------------------------------------------------------------------------- + private void EmitTopRightRadarPanel(IClientArenaSession session, MatchState state) + { + _hbCanvas.DrawPanelFrame(_topRightRect, BgDark, BorderCol, OrangeCol, cornerLen: 12f, borderPx: 1.5f); + + float panelCenterX = _topRightRect.Position.X + _topRightRect.Size.X * 0.5f; + ReadOnlySpan title = state.MapKind == ArenaMapKind.Sion + ? "SION 3KM • RADAR" + : "DESERT RING • RADAR"; + float titleW = _hbCanvas.MeasureTextWidth(title, 12f, wght: 650f); + _hbCanvas.DrawText(title, panelCenterX - titleW * 0.5f, _topRightRect.Position.Y + 20f, 12f, OrangeCol, wght: 650f); + + Vector2 center = new(panelCenterX, _topRightRect.Position.Y + 26f + 107f); + const float radius = 214f * 0.47f; + float maxBlipRadius = MathF.Max(4f, radius - 3f); + float arenaHalf = MathF.Max(1f, state.Terrain.MapHalfExtent); + float scale = radius / arenaHalf; + float cameraYaw = _getCameraYaw(); + int localId = session.LocalContenderId; + + _hbCanvas.DrawCircleFilled(center.X, center.Y, radius, BgInner); + _hbCanvas.DrawCircleRing(center.X, center.Y, radius, 1.5f, BorderCol); + _hbCanvas.DrawLineSegment(center.X, center.Y - radius, center.X, center.Y - radius + 6f, 2.0f, CyanCol); + + // Safe Circle + float safePx = MathF.Min(state.Spectators.SafeRadius * scale, maxBlipRadius); + _hbCanvas.DrawCircleRing(center.X, center.Y, safePx, 1.6f, OrangeCol); + + // Ground drops + for (int i = 0; i < state.GroundDrops.Count; i++) + { + var d = state.GroundDrops[i]; + if (d.PickedUp) continue; + var p = ClampToRadarDisc(center, MathF.Max(4f, radius - 4f), WorldToRadar(center, scale, d.X, d.Z, cameraYaw)); + if (d.Chassis is not null) + { + _hbCanvas.DrawRectFilled(p.X - 2.5f, p.Y - 2.5f, 5f, 5f, CyanCol); + } + else if (d.Module is { IsImperial: true }) + { + _hbCanvas.DrawCircleFilled(p.X, p.Y, 3.0f, GoldCol); + } + } + + // Active descending Orbital Pods + var pods = session.ActivePods; + for (int i = 0; i < pods.Count; i++) + { + var pod = pods[i]; + if (pod.Phase == OrbitalPodPhase.Popped) continue; + var pp = ClampToRadarDisc(center, MathF.Max(4f, radius - 5f), WorldToRadar(center, scale, pod.X, pod.Z, cameraYaw)); + if (pod.PodKind == OrbitalPodKind.Contender) + { + bool isLocalPod = pod.ContenderId == localId; + bool isAllyPod = !isLocalPod && state.AreAllies(localId, pod.ContenderId); + if (isAllyPod) + { + _hbCanvas.DrawDiamond(pp.X, pp.Y, 4.6f, AlliedCol); + } + else + { + Color pCol = isLocalPod ? OliveCol : OrangeCol; + float sz = isLocalPod ? 10.5f : 7.0f; + _hbCanvas.DrawChevron(pp.X, pp.Y, sz, -MathF.PI * 0.5f, pCol); + } + } + else + { + bool isImp = pod.WaveIndex > 0 || pod.Module?.IsImperial == true; + _hbCanvas.DrawDiamond(pp.X, pp.Y, 3.2f, isImp ? GoldCol : CyanCol); + } + } + + // Spectator Wall (LOS / Tourist horizon rule / 5s ghost memory) + var contenderContacts = session.LocalContenderContacts; + var spectatorContacts = session.LocalSpectatorContacts; + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive) continue; + + spectatorContacts.TryGetValue(s.Id, out var mem); + if (!MatchState.IsContactOnRadar(mem)) continue; + + bool live = mem!.VisibleToPlayer; + bool hasLivePos = session.IsSpectatorVisible(s.Id) && (live || mem.FaintHorizonPing); + if (!hasLivePos && !mem.HasEverBeenSeen) continue; + + float drawX = hasLivePos ? s.X : mem.LastSeenX; + float drawZ = hasLivePos ? s.Z : mem.LastSeenZ; + float blipR = 1.6f + s.RadarSignature * 3.1f; + float specClampR = MathF.Max(4f, radius - blipR - 1f); + var p = ClampToRadarDisc(center, specClampR, WorldToRadar(center, scale, drawX, drawZ, cameraYaw)); + + Color col = s.Tier switch + { + SpectatorTier.Tourist => GoldCol, + SpectatorTier.Patron => PatronColor, + _ => RedCol + }; + + if (live && s.Stance != SpectatorStance.Neutral && s.HasTargetLos && s.TargetContenderId.HasValue) + { + int tid = s.TargetContenderId.Value; + if (tid >= 0 && tid < state.Contenders.Count && state.Contenders[tid].Alive) + { + var tgt = state.Contenders[tid]; + bool targetVisible = tgt.Id == localId || + (session.IsContenderVisible(tgt.Id) && contenderContacts.TryGetValue(tgt.Id, out var tgtMem) && tgtMem.VisibleToPlayer); + if (targetVisible) + { + float tgtClampR = MathF.Max(4f, radius - (tgt.Id == localId ? 7.5f : 4.3f)); + var tp = ClampToRadarDisc(center, tgtClampR, WorldToRadar(center, scale, tgt.X, tgt.Z, cameraYaw)); + _hbCanvas.DrawLineSegment(p.X, p.Y, tp.X, tp.Y, 1.3f, new Color(RedCol.R, RedCol.G, RedCol.B, 0.65f)); + } + } + col = RedCol; + } + + if (!live) + { + float alpha = mem.FaintHorizonPing + ? 0.42f + : Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f); + Color ghostCol = mem.FaintHorizonPing ? GoldCol : col; + _hbCanvas.DrawCircleFilled(p.X, p.Y, blipR, new Color(ghostCol.R, ghostCol.G, ghostCol.B, alpha)); + } + else + { + _hbCanvas.DrawCircleFilled(p.X, p.Y, blipR, col); + } + } + + // Contenders (player live chevron; allies diamond; rivals LOS + 5s ghost memory) + float sinY = MathF.Sin(cameraYaw); + float cosY = MathF.Cos(cameraYaw); + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (!c.IsGroundedActive) continue; + + if (c.Id == localId) + { + float playerClampR = MathF.Max(4f, radius - 6.5f - 1f); + var (lPos, _, _) = session.GetInterpolatedContenderPose(localId, 1f); + var p = ClampToRadarDisc(center, playerClampR, WorldToRadar(center, scale, lPos.X, lPos.Z, cameraYaw)); + var dir = new Vector2( + -MathF.Sin(c.Yaw) * cosY + MathF.Cos(c.Yaw) * sinY, + -(MathF.Sin(c.Yaw) * sinY + MathF.Cos(c.Yaw) * cosY)); + float ang = MathF.Atan2(dir.Y, dir.X); + _hbCanvas.DrawChevron(p.X, p.Y, 12.5f, ang, OliveCol); + continue; + } + + if (state.AreAllies(localId, c.Id)) + { + float allyClampR = MathF.Max(4f, radius - 4.6f - 1f); + var (aPos, _, _) = session.GetInterpolatedContenderPose(c.Id, 1f); + var p = ClampToRadarDisc(center, allyClampR, WorldToRadar(center, scale, aPos.X, aPos.Z, cameraYaw)); + _hbCanvas.DrawDiamond(p.X, p.Y, 4.6f, AlliedCol); + continue; + } + + contenderContacts.TryGetValue(c.Id, out var mem); + if (!MatchState.IsContactOnRadar(mem)) continue; + + if (mem!.VisibleToPlayer) + { + float rivalClampR = MathF.Max(4f, radius - 3.3f - 1f); + float rx = session.IsContenderVisible(c.Id) ? c.X : mem.LastSeenX; + float rz = session.IsContenderVisible(c.Id) ? c.Z : mem.LastSeenZ; + var p = ClampToRadarDisc(center, rivalClampR, WorldToRadar(center, scale, rx, rz, cameraYaw)); + _hbCanvas.DrawCircleFilled(p.X, p.Y, 3.3f, OrangeCol); + } + else + { + float ghostClampR = MathF.Max(4f, radius - 2.8f - 1f); + var p = ClampToRadarDisc(center, ghostClampR, WorldToRadar(center, scale, mem.LastSeenX, mem.LastSeenZ, cameraYaw)); + float alpha = Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f); + _hbCanvas.DrawCircleFilled(p.X, p.Y, 2.8f, new Color(OrangeCol.R, OrangeCol.G, OrangeCol.B, alpha)); + } + } + + ReadOnlySpan attrib = state.MapKind == ArenaMapKind.Sion + ? "Data: swisstopo | [M] Switch Map" + : "[M] Switch to Sion 3 km"; + float attribW = _hbCanvas.MeasureTextWidth(attrib, 10f, wght: 350f); + _hbCanvas.DrawText(attrib, panelCenterX - attribW * 0.5f, _topRightRect.End.Y - 9f, 10f, TextMuted, wght: 350f); + } + + private static Vector2 WorldToRadar(Vector2 center, float scale, float wx, float wz, float camYaw) + { + float sinY = MathF.Sin(camYaw); + float cosY = MathF.Cos(camYaw); + float rx = -wx * cosY + wz * sinY; + float fy = wx * sinY + wz * cosY; + return center + new Vector2(rx, -fy) * scale; + } + + private static Vector2 ClampToRadarDisc(Vector2 center, float maxRadius, Vector2 pt) + { + Vector2 delta = pt - center; + float dist = delta.Length(); + if (dist > maxRadius && dist > 1e-4f) + { + return center + delta * (maxRadius / dist); + } + return pt; + } + + // ------------------------------------------------------------------------- + // 3. Crosshair, Heat Arc, Incoming Hit Arcs, Hit-Marker X, Pod Altimeter + // ------------------------------------------------------------------------- + private void EmitCrosshairAndCombatFeedback( + MatchState state, + ContenderState player, + OrbitalPod? localPod, + Vector2 center) + { + const float gap = 6f; + const float tick = 10f; + bool allDisabled = player.Alive && + player.InArcWeaponCount == 0 && player.OutOfArcWeaponCount == 0 && player.DisabledWeaponCount > 0; + bool outOfArc = player.Alive && player.AllWeaponsOutOfArc; + Color retCol = (outOfArc || allDisabled) + ? new Color(RedCol.R, RedCol.G, RedCol.B, 0.95f) + : new Color(TextLight.R, TextLight.G, TextLight.B, 0.88f); + + _hbCanvas.DrawCircleFilled(center.X, center.Y, 1.8f, retCol); + _hbCanvas.DrawLineSegment(center.X - gap - tick, center.Y, center.X - gap, center.Y, 1.6f, retCol); + _hbCanvas.DrawLineSegment(center.X + gap, center.Y, center.X + gap + tick, center.Y, 1.6f, retCol); + _hbCanvas.DrawLineSegment(center.X, center.Y - gap - tick, center.X, center.Y - gap, 1.6f, retCol); + _hbCanvas.DrawLineSegment(center.X, center.Y + gap, center.X, center.Y + gap + tick, 1.6f, retCol); + + // Outgoing hit-marker X-flash + if (_hitMarkerRemaining > 0f && _hitMarkerDuration > 0.001f && _hitMarkerKind != HitMarkerKind.None) + { + float frac = Math.Clamp(_hitMarkerRemaining / _hitMarkerDuration, 0f, 1f); + float pop = 1.0f + (1.0f - frac) * 0.25f; + Color xCol = _hitMarkerKind switch + { + HitMarkerKind.Kill => new Color(RedCol.R, RedCol.G, RedCol.B, frac * 0.98f), + HitMarkerKind.Core => new Color(1.0f, 0.28f, 0.16f, frac * 0.95f), + _ => new Color(1.0f, 0.95f, 0.78f, frac * 0.92f) + }; + float xWidth = _hitMarkerKind == HitMarkerKind.Armor ? 2.0f : 2.8f; + float rIn = 6.5f * pop; + float rOut = (_hitMarkerKind == HitMarkerKind.Armor ? 13.5f : 15.5f) * pop; + const float diag = 0.70710678f; + for (int q = 0; q < 4; q++) + { + float sx = (q & 1) == 0 ? 1f : -1f; + float sy = (q & 2) == 0 ? 1f : -1f; + Vector2 dir = new(sx * diag, sy * diag); + _hbCanvas.DrawLineSegment( + center.X + dir.X * rIn, center.Y + dir.Y * rIn, + center.X + dir.X * rOut, center.Y + dir.Y * rOut, + xWidth, xCol); + if (_hitMarkerKind == HitMarkerKind.Kill) + { + _hbCanvas.DrawLineSegment( + center.X + dir.X * (rOut + 4f), center.Y + dir.Y * (rOut + 4f), + center.X + dir.X * (rOut + 10.5f), center.Y + dir.Y * (rOut + 10.5f), + 2.2f, new Color(GoldCol.R, GoldCol.G, GoldCol.B, frac * 0.95f)); + } + } + } + + if (allDisabled) + { + ReadOnlySpan msg = "WEAPONS STRIPPED"; + float mw = _hbCanvas.MeasureTextWidth(msg, 11.5f, wght: 600f); + _hbCanvas.DrawText(msg, center.X - mw * 0.5f, center.Y + 38f, 11.5f, RedCol, wght: 600f); + } + else if (outOfArc) + { + ReadOnlySpan msg = "OUT OF ARC"; + float mw = _hbCanvas.MeasureTextWidth(msg, 11.5f, wght: 600f); + _hbCanvas.DrawText(msg, center.X - mw * 0.5f, center.Y + 38f, 11.5f, RedCol, wght: 600f); + } + + if (!player.Alive) + { + return; + } + + if (player.IsInDropPod) + { + float agl = localPod is not null ? MathF.Max(0f, localPod.LastAgl) : 0f; + float vel = localPod is not null ? MathF.Max(0f, -localPod.VelY) : 0f; + float horizSpeed = localPod is not null + ? MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ) + : player.Speed; + bool burning = localPod?.Phase == OrbitalPodPhase.RetroBurn; + Color bracketCol = burning ? OrangeCol : CyanCol; + + float startAlt = OrbitalPodPreset.GetStartAltAgl(OrbitalPodKind.Contender, state.MapKind); + float altFrac = Math.Clamp(agl / MathF.Max(1f, startAlt), 0f, 1f); + const float barX = 72f; + const float barH = 76f; + float topY = center.Y - barH * 0.5f; + Color trackCol = new(BorderCol.R, BorderCol.G, BorderCol.B, 0.55f); + _hbCanvas.DrawLineSegment(center.X - barX, topY, center.X - barX, topY + barH, 2.0f, trackCol); + _hbCanvas.DrawLineSegment(center.X + barX, topY, center.X + barX, topY + barH, 2.0f, trackCol); + + float fillH = barH * altFrac; + if (fillH > 0.5f) + { + _hbCanvas.DrawLineSegment(center.X - barX, topY + barH - fillH, center.X - barX, topY + barH, 3.0f, bracketCol); + _hbCanvas.DrawLineSegment(center.X + barX, topY + barH - fillH, center.X + barX, topY + barH, 3.0f, bracketCol); + } + + SpanWriter sw = new(_scratch); + sw.Append("ALT "); sw.AppendFloat(agl, "F0"); sw.Append("m | HORIZ "); + sw.AppendFloat(horizSpeed, "F0"); sw.Append(" m/s | VERT "); + sw.AppendFloat(vel, "F0"); sw.Append(" m/s"); + float tw = _hbCanvas.MeasureTextWidth(sw.Span, 11.5f, wght: 500f); + _hbCanvas.DrawText(sw.Span, center.X - tw * 0.5f, center.Y + 56f, 11.5f, bracketCol, wght: 500f); + + if (burning) + { + ReadOnlySpan burnTxt = "RETRO BURN ACTIVE"; + float bw = _hbCanvas.MeasureTextWidth(burnTxt, 11.5f, wght: 650f); + _hbCanvas.DrawText(burnTxt, center.X - bw * 0.5f, center.Y - 50f, 11.5f, OrangeCol, wght: 650f); + } + return; + } + + // Thermal heat-arc indicator around crosshair + float heatRatio = 0f; + bool overPlateau = false; + var mounted = player.Grid.Mounted; + for (int i = 0; i < mounted.Count; i++) + { + var m = mounted[i]; + if (m.Spec.Kind == HardpointKind.Weapon) + { + float r = Math.Clamp( + (m.CurrentTemp - ChassisGrid.AmbientTemp) / MathF.Max(1f, m.Spec.MaxTemp - ChassisGrid.AmbientTemp), + 0f, 1f); + if (r > heatRatio) heatRatio = r; + if (m.CurrentTemp > m.Spec.OptimalTemp + m.Spec.PlateauWidth * 0.5f) + { + overPlateau = true; + } + } + } + + const float arcRadius = 21f; + const float startAngle = -MathF.PI * 0.75f; + const float maxSweep = MathF.PI * 1.5f; + _hbCanvas.DrawArcStrokeStatic( + center.X, center.Y, arcRadius, 2.0f, + startAngle, startAngle + maxSweep, + rotationRadScreen: 0f, + new VectorBlobKey(VectorShapeKind.ThermalHeatArc, 0, 0), + new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.40f)); + + if (heatRatio > 0.01f) + { + const int heatSteps = 135; // 2-degree increments across 270 deg + int step = Math.Clamp((int)MathF.Round(heatRatio * heatSteps), 1, heatSteps); + float sweep = maxSweep * (step / (float)heatSteps); + Color heatCol = overPlateau ? RedCol : (heatRatio > 0.65f ? OrangeCol : OliveCol); + _hbCanvas.DrawArcStrokeStatic( + center.X, center.Y, arcRadius, 2.5f, + startAngle, startAngle + sweep, + rotationRadScreen: 0f, + new VectorBlobKey(VectorShapeKind.ThermalHeatArc, (ushort)step, 1), + heatCol); + } + + // Directional incoming-hit indicator arcs (single cached static arc rotated per angle -> 0 dynamic atlas uploads) + if (_incomingArcCount > 0) + { + float cameraYaw = _getCameraYaw(); + float sinY = MathF.Sin(cameraYaw); + float cosY = MathF.Cos(cameraYaw); + for (int i = 0; i < _incomingArcCount; i++) + { + var arc = _incomingArcs[i]; + float alpha = Math.Clamp(1f - arc.Age / HitArcDuration, 0f, 1f); + if (alpha <= 0.01f) continue; + + float dx = arc.SourceX - player.X; + float dz = arc.SourceZ - player.Z; + float rx = -dx * cosY + dz * sinY; + float fy = dx * sinY + dz * cosY; + float angle = (rx * rx + fy * fy) > 1e-4f ? MathF.Atan2(-fy, rx) : 0f; + + Color arcCol = arc.WeaponClass switch + { + WeaponVisualClass.Explosive => new Color(1.0f, 0.36f, 0.12f, alpha * 0.96f), + WeaponVisualClass.RocketSalvo => new Color(1.0f, 0.56f, 0.14f, alpha * 0.96f), + WeaponVisualClass.ThermalBeam => new Color(0.30f, 0.90f, 1.0f, alpha * 0.96f), + WeaponVisualClass.GaussRail => new Color(0.24f, 0.78f, 1.0f, alpha * 0.98f), + WeaponVisualClass.PlasmaPpc => new Color(0.18f, 0.92f, 0.96f, alpha * 0.96f), + WeaponVisualClass.SwarmSmart => new Color(0.56f, 0.96f, 0.28f, alpha * 0.96f), + _ => new Color(0.96f, 0.72f, 0.22f, alpha * 0.94f) + }; + + const float hitR = 39f; + const float halfSpan = 0.34f; + _hbCanvas.DrawArcStrokeStatic( + center.X, center.Y, hitR, 4.2f, + -halfSpan, halfSpan, + rotationRadScreen: angle, + new VectorBlobKey(VectorShapeKind.IncomingHitArc, 0, 0), + arcCol); + if (arc.WeaponClass is WeaponVisualClass.ThermalBeam or WeaponVisualClass.GaussRail or WeaponVisualClass.PlasmaPpc) + { + _hbCanvas.DrawArcStrokeStatic( + center.X, center.Y, hitR - 3.5f, 2.0f, + -halfSpan * 0.75f, halfSpan * 0.75f, + rotationRadScreen: angle, + new VectorBlobKey(VectorShapeKind.IncomingHitArc, 1, 0), + new Color(GoldCol.R, GoldCol.G, GoldCol.B, alpha * 0.90f)); + } + + float cosA = MathF.Cos(angle); + float sinA = MathF.Sin(angle); + _hbCanvas.DrawDirectionalArrow(center.X + cosA * (hitR + 4.5f), center.Y + sinA * (hitR + 4.5f), 11f, angle, arcCol); + } + + var latest = _incomingArcs[_incomingArcCount - 1]; + float tagAlpha = Math.Clamp(1f - latest.Age / HitArcDuration, 0f, 1f); + (string tagText, Color tagCol) = latest.WeaponClass switch + { + WeaponVisualClass.Autocannon => ("20MM IMPACT", new Color(0.98f, 0.70f, 0.20f, tagAlpha)), + WeaponVisualClass.Explosive => ("BLAST IMPACT", new Color(1.0f, 0.38f, 0.14f, tagAlpha)), + WeaponVisualClass.RocketSalvo => ("ROCKET HIT", new Color(1.0f, 0.58f, 0.18f, tagAlpha)), + WeaponVisualClass.ThermalBeam => ("THERMAL HIT", new Color(0.36f, 0.92f, 1.0f, tagAlpha)), + WeaponVisualClass.GaussRail => ("GAUSS RAIL", new Color(0.28f, 0.84f, 1.0f, tagAlpha)), + WeaponVisualClass.PlasmaPpc => ("PLASMA BURN", new Color(0.24f, 0.94f, 0.98f, tagAlpha)), + WeaponVisualClass.SwarmSmart => ("SWARM HIT", new Color(0.58f, 0.96f, 0.30f, tagAlpha)), + _ => ("KINETIC HIT", new Color(0.96f, 0.78f, 0.28f, tagAlpha)) + }; + float tagW = _hbCanvas.MeasureTextWidth(tagText, 10.5f, wght: 600f); + _hbCanvas.DrawText(tagText, center.X - tagW * 0.5f, center.Y + 56f, 10.5f, tagCol, wght: 600f); + } + } + + // ------------------------------------------------------------------------- + // 4. Bottom-Left Panel: Schematic + Hover + Cargo + Garage + // ------------------------------------------------------------------------- + private void EmitBottomLeftPanel(ChassisGrid grid) + { + // Draw frame & borders ONLY (backdrop is _bottomLeftBg behind _schematic so inactive holes stay BgDark) + _hbCanvas.DrawPanelFrame(_bottomLeftRect, BgDark, BorderCol, OrangeCol, cornerLen: 12f, borderPx: 1.5f, drawBg: false); + + float leftX = _bottomLeftRect.Position.X + 10f; + float topY = _bottomLeftRect.Position.Y + 8f; + float gridW = _schematicRect.Size.X; + + _hbCanvas.DrawText("HARDPOINTS & HEAT", leftX, topY + 12f, 12f, OrangeCol, wght: 650f); + + // Hardpoint L-brackets, hull outlines, stripped X-marks, compatibility pulses, Krypton labels + _schematic.EmitHbGpuOverlay(_hbCanvas, _schematicRect.Position, _vignetteTime); + + // Hover telemetry beneath schematic + float hoverY = _schematicRect.End.Y + 4f; + for (int i = 0; i < _hoverLines.Count; i++) + { + _hbCanvas.DrawText(_hoverLines[i], leftX, hoverY + 11f, 10f, _cachedHoverColor, wght: 400f); + hoverY += 13.5f; + } + + // Middle column: Salvage Cargo Rack (0 dynamic Button nodes) + float cargoX = _schematicRect.End.X + 8f; + const float cargoW = 156f; + SpanWriter sw = new(_scratch); + sw.Append("SALVAGE CARGO ("); + sw.AppendInt(grid.Cargo.Count); + sw.Append("/"); + sw.AppendInt(grid.Spec.CargoCapacity); + sw.Append(")"); + _hbCanvas.DrawText(sw.Span, cargoX, topY + 11f, 11f, OliveCol, wght: 600f); + + float rowY = topY + 18f; + _cargoHitCount = 0; + if (grid.Cargo.Count == 0) + { + _hbCanvas.DrawText("No modules in rack.", cargoX, rowY + 11f, 10.5f, TextMuted, wght: 350f); + _hbCanvas.DrawText("Press [E] near crates.", cargoX, rowY + 24f, 10.5f, TextMuted, wght: 350f); + } + else + { + Viewport? vp = GetViewport(); + Vector2 mousePos = (vp is not null && Input.MouseMode == Input.MouseModeEnum.Visible) + ? vp.GetMousePosition() + : new Vector2(-9999f, -9999f); + + int count = Math.Min(grid.Cargo.Count, MaxCargoHitRects); + for (int i = 0; i < count; i++) + { + var mod = grid.Cargo[i]; + const float rowH = 19f; + const float fitW = 32f; + Rect2 rowRect = new(cargoX, rowY, cargoW - fitW - 3f, rowH); + Rect2 fitRect = new(cargoX + cargoW - fitW, rowY, fitW, rowH); + _cargoRowRects[i] = rowRect; + _cargoFitRects[i] = fitRect; + _cargoHitCount = i + 1; + + bool rowHovered = rowRect.HasPoint(mousePos); + bool fitHovered = fitRect.HasPoint(mousePos); + bool selected = _selectedCargoIndex == i; + + Color rowBg = selected ? new Color(0.24f, 0.18f, 0.10f, 0.92f) : (rowHovered ? BgRowHover : BgInner); + Color rowBorder = selected ? OrangeCol : (mod.IsImperial ? GoldCol : BorderCol); + _hbCanvas.DrawRectFilled(rowRect.Position.X, rowRect.Position.Y, rowRect.Size.X, rowRect.Size.Y, rowBg); + _hbCanvas.DrawRectOutline(rowRect.Position.X, rowRect.Position.Y, rowRect.Size.X, rowRect.Size.Y, 1.0f, rowBorder); + + Color txtCol = selected ? OrangeCol : (mod.IsImperial ? GoldCol : TextLight); + float nameX = rowRect.Position.X + 5f; + float maxTextW = rowRect.Size.X - 10f; + if (mod.IsImperial) + { + float starW = _hbCanvas.DrawText("* ", nameX, rowRect.Position.Y + 13f, 10f, GoldCol, wght: 700f); + nameX += starW; + maxTextW = MathF.Max(8f, maxTextW - starW); + } + ReadOnlySpan displayName = TruncateWithEllipsis(mod.Name, maxTextW, 10f, 450f, _scratch); + _hbCanvas.DrawText(displayName, nameX, rowRect.Position.Y + 13f, 10f, txtCol, wght: 450f); + + Color fitBg = fitHovered ? new Color(0.22f, 0.28f, 0.20f, 0.96f) : BgInner; + _hbCanvas.DrawRectFilled(fitRect.Position.X, fitRect.Position.Y, fitRect.Size.X, fitRect.Size.Y, fitBg); + _hbCanvas.DrawRectOutline(fitRect.Position.X, fitRect.Position.Y, fitRect.Size.X, fitRect.Size.Y, 1.0f, fitHovered ? OliveCol : BorderCol); + float fw = _hbCanvas.MeasureTextWidth("FIT", 9.5f, wght: 650f); + _hbCanvas.DrawText("FIT", fitRect.Position.X + (fitW - fw) * 0.5f, fitRect.Position.Y + 13f, 9.5f, fitHovered ? Colors.White : TextLight, wght: 650f); + + rowY += 21f; + } + } + + // Optional Garage Details column when Tab is expanded + if (_garageExpanded) + { + float garageX = cargoX + cargoW + 8f; + float gy = topY + 11f; + for (int i = 0; i < _garageLines.Count; i++) + { + _hbCanvas.DrawText(_garageLines[i], garageX, gy, 10f, i <= 1 ? OliveCol : TextMuted, wght: i <= 1 ? 550f : 380f); + gy += 13.5f; + } + } + } + + // ------------------------------------------------------------------------- + // 5. Broadcast Chyron & Outcome Banner + // ------------------------------------------------------------------------- + private void EmitChyronPanel() + { + _hbCanvas.DrawPanelFrame(_chyronRect, BgDark, BorderCol, GoldCol, cornerLen: 12f, borderPx: 1.5f); + + float x = _chyronRect.Position.X + 10f; + float y = _chyronRect.Position.Y + 8f; + _hbCanvas.DrawText("IMPERIAL BROADCAST FEED", x, y + 11f, 11f, GoldCol, wght: 650f); + y += 17f; + + HbGpuCommandWriter.PackClipRect( + _chyronRect.Position.X + 8f, _chyronRect.Position.Y + 6f, + _chyronRect.Size.X - 16f, _chyronRect.Size.Y - 12f, + out uint cMin, out uint cMax); + + for (int i = 0; i < _chyronLineCount; i++) + { + bool latest = _chyronIsLatest[i]; + _hbCanvas.DrawText( + _chyronDisplayLines[i], + x, y + 12f, + latest ? 11.5f : 10.8f, + latest ? TextLight : TextMuted, + wght: latest ? 500f : 380f, + clipMinPacked: cMin, + clipMaxPacked: cMax); + y += 19f; + } + } + + private void EmitOutcomeBanner( + IClientArenaSession session, + MatchState state, + ContenderState player, + NetworkStatusSnapshot net) + { + var outcome = session.LocalOutcome; + Color accent; + ReadOnlySpan title; + ReadOnlySpan sub; + + if (outcome == ClientMatchOutcome.Victory) + { + accent = OliveCol; + title = "VICTORY — LAST RIG STANDING"; + sub = net.Mode == NetworkMode.RemoteClient ? "Next round starting soon..." : "[R] New Drop"; + } + else if (outcome == ClientMatchOutcome.Defeat) + { + accent = RedCol; + title = !player.Alive ? "CHASSIS DESTROYED" : "MATCH COMPLETED — DEFEAT"; + sub = net.Mode == NetworkMode.RemoteClient + ? (state.Phase == MatchPhase.Completed ? "Waiting for server next round..." : "Spectating live match...") + : "[R] Redeploy"; + } + else + { + accent = CyanCol; + var wave = session.DropWaveState; + float eta = wave.NextWaveAtSec is float nxt ? MathF.Max(0f, nxt - state.Time) : 0f; + SpanWriter sw = new(_scratch); + sw.Append("AWAITING PATRON WAVE "); + sw.AppendInt(wave.NextWaveIndex); + _hbCanvas.DrawPanelFrame(_outcomeRect, BgDark, BorderCol, accent, cornerLen: 16f, borderPx: 2.0f); + float cx = _outcomeRect.Position.X + _outcomeRect.Size.X * 0.5f; + float w1 = _hbCanvas.MeasureTextWidth(sw.Span, 20f, wght: 700f); + _hbCanvas.DrawText(sw.Span, cx - w1 * 0.5f, _outcomeRect.Position.Y + 36f, 20f, accent, wght: 700f); + + sw = new SpanWriter(_scratch); + sw.Append("RESPAWN IN "); + sw.AppendFloat(eta, "F1"); + sw.Append("s (RESP: "); + sw.AppendInt(player.RespawnsRemaining); + sw.Append(" LEFT)"); + float w2 = _hbCanvas.MeasureTextWidth(sw.Span, 14f, wght: 500f); + _hbCanvas.DrawText(sw.Span, cx - w2 * 0.5f, _outcomeRect.Position.Y + 60f, 14f, accent, wght: 500f); + return; + } + + _hbCanvas.DrawPanelFrame(_outcomeRect, BgDark, BorderCol, accent, cornerLen: 16f, borderPx: 2.0f); + float centerX = _outcomeRect.Position.X + _outcomeRect.Size.X * 0.5f; + float tw1 = _hbCanvas.MeasureTextWidth(title, 20f, wght: 700f); + float tw2 = _hbCanvas.MeasureTextWidth(sub, 14f, wght: 500f); + _hbCanvas.DrawText(title, centerX - tw1 * 0.5f, _outcomeRect.Position.Y + 36f, 20f, accent, wght: 700f); + _hbCanvas.DrawText(sub, centerX - tw2 * 0.5f, _outcomeRect.Position.Y + 60f, 14f, accent, wght: 500f); + } + + // ------------------------------------------------------------------------- + // 6. 3D World Markers: Squad Chevrons + Target Boxes + Offscreen Arrows + // Preserves ALL Soul-verified invariants from 8310246 (0 GC allocs on hot path) + // ------------------------------------------------------------------------- + private void EmitWorldMarkers( + IClientArenaSession session, + MatchState state, + ContenderState localPlayer, + Vector2 viewSize) + { + if (_projectWorld is null || viewSize.X < 64f || viewSize.Y < 64f) + { + return; + } + + int localId = session.LocalContenderId; + if (localId < 0 || localId >= state.Contenders.Count || !localPlayer.Alive) + { + return; + } + + var (localPos, _, _) = session.GetInterpolatedContenderPose(localId, 1f); + Vector2 center = viewSize * 0.5f; + float halfW = MathF.Max(16f, center.X - BorderPad); + float halfH = MathF.Max(16f, center.Y - BorderPad); + + // 1. Allied squad chevrons (only when SquadSize > 1: Solo vs Trio mutual exclusion) + if (state.SquadSize > 1) + { + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (c.Id == localId || !c.Alive || !state.AreAllies(localId, c.Id)) continue; + + var (allyPos, _, _) = session.GetInterpolatedContenderPose(c.Id, 1f); + float dist = (allyPos - localPos).Length(); + float headOffset = c.IsInDropPod ? 3.4f : (c.Grid.Spec.HalfHeight + 1.9f); + var worldHead = new System.Numerics.Vector3(allyPos.X, allyPos.Y + headOffset, allyPos.Z); + var (valid, inFront, sp, camLocal) = _projectWorld(worldHead); + if (!valid) continue; + + bool inFrame = inFront && + sp.X >= BorderPad && sp.X <= viewSize.X - BorderPad && + sp.Y >= BorderPad && sp.Y <= viewSize.Y - BorderPad; + + SpanWriter sw = new(_scratch); + sw.Append(c.Name); + sw.Append(" "); + sw.AppendFloat(dist, "F0"); + sw.Append("m"); + ReadOnlySpan label = sw.Span; + + if (inFrame) + { + // Pointing down chevron above ally head (+PI/2 in screen coords) + _hbCanvas.DrawChevron(sp.X, sp.Y, 12f, MathF.PI * 0.5f, AlliedCol); + float lw = _hbCanvas.MeasureTextWidth(label, 10.5f, wght: 550f); + float lx = Math.Clamp(sp.X - lw * 0.5f, 6f, MathF.Max(6f, viewSize.X - lw - 6f)); + float ly = sp.Y - 10f; + var aboveBox = new Rect2(lx - 1f, ly - 11f, lw + 2f, 13f); + if (IntersectsStaticHudPanel(aboveBox) || aboveBox.Position.Y < 2f) + { + ly = sp.Y + 19f; + } + var finalBox = new Rect2(lx - 1f, ly - 11f, lw + 2f, 13f); + if (!IntersectsStaticHudPanel(finalBox)) + { + _hbCanvas.DrawText(label, lx, ly, 10.5f, AlliedCol, wght: 550f); + } + } + else + { + Vector2 dir = ComputeOffscreenDirection(camLocal); + Vector2 edge = ComputeSafeEdgePos(center, halfW, halfH, dir); + float angle = MathF.Atan2(dir.Y, dir.X); + _hbCanvas.DrawDirectionalArrow(edge.X, edge.Y, 13f, angle, new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.88f)); + Vector2 textPos = ComputeInwardLabelPos(edge, dir, viewSize, label); + _hbCanvas.DrawText(label, textPos.X, textPos.Y, 10.5f, new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.90f), wght: 550f); + } + } + } + + // 2. Visible enemy contenders (strictly obeying fog-of-war / LOS) + var contenderContacts = session.LocalContenderContacts; + var spectatorContacts = session.LocalSpectatorContacts; + _offscreenHostiles.Clear(); + + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (c.Id == localId || !c.Alive || state.AreAllies(localId, c.Id)) continue; + if (!session.IsContenderVisible(c.Id)) continue; + if (!contenderContacts.TryGetValue(c.Id, out var mem) || !mem.VisibleToPlayer) continue; + + var (pos, rot, _) = session.GetInterpolatedContenderPose(c.Id, 1f); + float dist = (pos - localPos).Length(); + bool targetingLocal = c.AiTargetContenderId == localId; + Color col = targetingLocal ? RedCol : OrangeCol; + float hpRatio = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 1f; + + float halfBoundW = c.IsInDropPod ? 1.4f : c.Grid.Spec.HalfWidth; + float halfBoundH = c.IsInDropPod ? 1.8f : c.Grid.Spec.HalfHeight; + float halfBoundL = c.IsInDropPod ? 1.4f : c.Grid.Spec.HalfLength; + + ProcessHostileTarget( + pos, rot, halfBoundW, halfBoundH, halfBoundL, + dist, hpRatio, col, targetingLocal, viewSize); + } + + // 3. Visible hostile/provoked spectators (neutral tourists do NOT get hostile target boxes) + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive || s.Stance == SpectatorStance.Neutral) continue; + if (!session.IsSpectatorVisible(s.Id)) continue; + if (!spectatorContacts.TryGetValue(s.Id, out var mem) || !mem.VisibleToPlayer) continue; + + var (pos, rot, _) = session.GetInterpolatedSpectatorPose(s.Id, 1f); + float dist = (pos - localPos).Length(); + bool lockedOnLocal = s.TargetContenderId == localId; + float hpRatio = s.Grid.MaxCoreHp > 0f ? s.Grid.CoreHp / s.Grid.MaxCoreHp : 1f; + + ProcessHostileTarget( + pos, rot, s.Grid.Spec.HalfWidth, s.Grid.Spec.HalfHeight, s.Grid.Spec.HalfLength, + dist, hpRatio, RedCol, lockedOnLocal, viewSize); + } + + // 4. Off-screen hostile arrows (locked-on threats first, then nearest visible hostiles) + if (_offscreenHostiles.Count > 0) + { + _offscreenHostiles.Sort(OffscreenSortComparison); + int count = Math.Min(_offscreenHostiles.Count, MaxOffscreenHostileArrows); + for (int i = 0; i < count; i++) + { + EmitOffscreenArrow(_offscreenHostiles[i], viewSize, center, halfW, halfH); + } + } + } + + private void ProcessHostileTarget( + System.Numerics.Vector3 worldCenter, + System.Numerics.Quaternion rot, + float halfBoundW, + float halfBoundH, + float halfBoundL, + float dist, + float hpRatio, + Color col, + bool isLockedOnLocal, + Vector2 viewSize) + { + var (cValid, cInFront, cSp, cCamLocal) = _projectWorld!(worldCenter); + if (!cValid) return; + + bool inFrame = cInFront && + cSp.X >= BorderPad && cSp.X <= viewSize.X - BorderPad && + cSp.Y >= BorderPad && cSp.Y <= viewSize.Y - BorderPad; + + if (!inFrame) + { + if (isLockedOnLocal || dist <= OffscreenHostileMaxDistance) + { + _offscreenHostiles.Add(new OffscreenMarker(cCamLocal, dist, col, isLockedOnLocal)); + } + return; + } + + float minX = float.PositiveInfinity, minY = float.PositiveInfinity; + float maxX = float.NegativeInfinity, maxY = float.NegativeInfinity; + bool allCornersInFront = true; + + for (int sx = -1; sx <= 1; sx += 2) + { + for (int sy = -1; sy <= 1; sy += 2) + { + for (int sz = -1; sz <= 1; sz += 2) + { + var localCorner = new System.Numerics.Vector3(sx * halfBoundW, sy * halfBoundH, sz * halfBoundL); + var worldCorner = worldCenter + System.Numerics.Vector3.Transform(localCorner, rot); + var (valid, inFront, sp, _) = _projectWorld(worldCorner); + if (!valid || !inFront) + { + allCornersInFront = false; + break; + } + if (sp.X < minX) minX = sp.X; + if (sp.X > maxX) maxX = sp.X; + if (sp.Y < minY) minY = sp.Y; + if (sp.Y > maxY) maxY = sp.Y; + } + if (!allCornersInFront) break; + } + if (!allCornersInFront) break; + } + + if (!allCornersInFront) + { + var (topValid, topFront, topSp, _) = _projectWorld(worldCenter + new System.Numerics.Vector3(0f, halfBoundH, 0f)); + var (botValid, botFront, botSp, _) = _projectWorld(worldCenter - new System.Numerics.Vector3(0f, halfBoundH, 0f)); + float rawH = (topValid && topFront && botValid && botFront) + ? MathF.Abs(botSp.Y - topSp.Y) + 8f + : 44f; + float horizRadius = MathF.Max(halfBoundW, halfBoundL); + float rawW = rawH * (horizRadius / MathF.Max(0.4f, halfBoundH)); + minX = cSp.X - rawW * 0.5f; + maxX = cSp.X + rawW * 0.5f; + minY = cSp.Y - rawH * 0.5f; + maxY = cSp.Y + rawH * 0.5f; + } + else + { + minX -= 3f; + maxX += 3f; + minY -= 3f; + maxY += 3f; + } + + float boxW = Math.Clamp(maxX - minX, 22f, 220f); + float boxH = Math.Clamp(maxY - minY, 22f, 220f); + Vector2 boxCenter = new((minX + maxX) * 0.5f, (minY + maxY) * 0.5f); + var rect = new Rect2(boxCenter.X - boxW * 0.5f, boxCenter.Y - boxH * 0.5f, boxW, boxH); + + EmitTargetBox(rect, col, dist, hpRatio, isLockedOnLocal, viewSize); + } + + private void EmitTargetBox(Rect2 rect, Color col, float dist, float hpRatio, bool isLockedOnLocal, Vector2 viewSize) + { + float x0 = rect.Position.X; + float y0 = rect.Position.Y; + float x1 = x0 + rect.Size.X; + float y1 = y0 + rect.Size.Y; + float arm = Math.Clamp(MathF.Min(rect.Size.X, rect.Size.Y) * 0.22f, 5f, 26f); + + Color shadowCol = new(0.04f, 0.05f, 0.04f, 0.78f); + Color strokeCol = new(col.R, col.G, col.B, 0.95f); + + // Dark shadow pass then crisp target brackets across all 4 quadrants + _hbCanvas.DrawTargetBracketCorner(x0 - 0.8f, y0 - 0.8f, arm + 1.5f, 3.6f, 0, shadowCol); + _hbCanvas.DrawTargetBracketCorner(x1 + 0.8f, y0 - 0.8f, arm + 1.5f, 3.6f, 1, shadowCol); + _hbCanvas.DrawTargetBracketCorner(x1 + 0.8f, y1 + 0.8f, arm + 1.5f, 3.6f, 2, shadowCol); + _hbCanvas.DrawTargetBracketCorner(x0 - 0.8f, y1 + 0.8f, arm + 1.5f, 3.6f, 3, shadowCol); + + _hbCanvas.DrawTargetBracketCorner(x0, y0, arm, 2.0f, 0, strokeCol); + _hbCanvas.DrawTargetBracketCorner(x1, y0, arm, 2.0f, 1, strokeCol); + _hbCanvas.DrawTargetBracketCorner(x1, y1, arm, 2.0f, 2, strokeCol); + _hbCanvas.DrawTargetBracketCorner(x0, y1, arm, 2.0f, 3, strokeCol); + + // Format distance + LOCK tag + SpanWriter sw = new(_scratch); + sw.AppendFloat(dist, "F0"); + sw.Append("m"); + if (isLockedOnLocal) + { + sw.Append(" LOCK"); + } + ReadOnlySpan label = sw.Span; + float textW = _hbCanvas.MeasureTextWidth(label, 10.5f, wght: 600f); + + float barW = Math.Clamp(rect.Size.X, 22f, 64f); + float centerX = (x0 + x1) * 0.5f; + float barX = Math.Clamp(centerX - barW * 0.5f, 6f, MathF.Max(6f, viewSize.X - barW - 6f)); + float tx = Math.Clamp(centerX - textW * 0.5f, 6f, MathF.Max(6f, viewSize.X - textW - 6f)); + + // Prefer above-box; flip below-box if obstructed by static HUD panels (e.g. TopLeft/TopRight) or top edge + float aboveBarY = y0 - 7f; + float aboveTextY = aboveBarY - 3f; + Rect2 aboveBounds = MakeTagBounds(barX, aboveBarY, barW, tx, aboveTextY, textW, above: true); + + float belowBarY = y1 + 5f; + float belowTextY = belowBarY + 14f; + Rect2 belowBounds = MakeTagBounds(barX, belowBarY, barW, tx, belowTextY, textW, above: false); + + float chosenBarY; + float chosenTextY; + if (!IntersectsStaticHudPanel(aboveBounds) && aboveBounds.Position.Y >= 2f) + { + chosenBarY = aboveBarY; + chosenTextY = aboveTextY; + } + else if (!IntersectsStaticHudPanel(belowBounds) && belowBounds.End.Y <= viewSize.Y - 2f) + { + chosenBarY = belowBarY; + chosenTextY = belowTextY; + } + else + { + // Both top and bottom overlap static HUD panels: nudge horizontally out of top corner panels if possible, else omit unobstructed tag + float nudgedTx = tx; + float nudgedBarX = barX; + if (aboveBounds.Intersects(_topLeftRect)) + { + float shift = _topLeftRect.End.X + 8f - MathF.Min(tx, barX); + if (shift > 0f && MathF.Max(tx + textW, barX + barW) + shift < _topRightRect.Position.X - 8f) + { + nudgedTx += shift; + nudgedBarX += shift; + } + } + else if (aboveBounds.Intersects(_topRightRect)) + { + float shift = MathF.Max(tx + textW, barX + barW) - (_topRightRect.Position.X - 8f); + if (shift > 0f && MathF.Min(tx, barX) - shift > _topLeftRect.End.X + 8f) + { + nudgedTx -= shift; + nudgedBarX -= shift; + } + } + + Rect2 nudgedBounds = MakeTagBounds(nudgedBarX, aboveBarY, barW, nudgedTx, aboveTextY, textW, above: true); + if (!IntersectsStaticHudPanel(nudgedBounds) && nudgedBounds.Position.Y >= 2f) + { + barX = nudgedBarX; + tx = nudgedTx; + chosenBarY = aboveBarY; + chosenTextY = aboveTextY; + } + else + { + return; + } + } + + _hbCanvas.DrawRectFilled(barX - 1f, chosenBarY - 1f, barW + 2f, 4f, shadowCol); + _hbCanvas.DrawRectFilled(barX, chosenBarY, barW * Math.Clamp(hpRatio, 0f, 1f), 2f, strokeCol); + + _hbCanvas.DrawText(label, tx + 1f, chosenTextY + 1f, 10.5f, ShadowCol, wght: 600f); + _hbCanvas.DrawText(label, tx, chosenTextY, 10.5f, strokeCol, wght: 600f); + } + + private static Rect2 MakeTagBounds(float barX, float barY, float barW, float tx, float ty, float textW, bool above) + { + float left = MathF.Min(barX - 1f, tx - 1f); + float right = MathF.Max(barX + barW + 1f, tx + textW + 1f); + if (above) + { + float top = ty - 11f; + float bottom = barY + 3f; + return new Rect2(left, top, right - left, bottom - top); + } + else + { + float top = barY - 1f; + float bottom = ty + 3f; + return new Rect2(left, top, right - left, bottom - top); + } + } + + private bool IntersectsStaticHudPanel(Rect2 rect) + { + return rect.Intersects(_topLeftRect) + || rect.Intersects(_topRightRect) + || rect.Intersects(_bottomLeftRect) + || rect.Intersects(_chyronRect); + } + + private void EmitOffscreenArrow(OffscreenMarker m, Vector2 viewSize, Vector2 center, float halfW, float halfH) + { + Vector2 dir = ComputeOffscreenDirection(m.CamLocal); + Vector2 edge = ComputeSafeEdgePos(center, halfW, halfH, dir); + float angle = MathF.Atan2(dir.Y, dir.X); + + _hbCanvas.DrawDirectionalArrow(edge.X, edge.Y, 18f, angle, new Color(0.04f, 0.05f, 0.04f, 0.74f)); + Color arrowCol = new(m.Color.R, m.Color.G, m.Color.B, 0.94f); + _hbCanvas.DrawDirectionalArrow(edge.X, edge.Y, 14.5f, angle, arrowCol); + + SpanWriter sw = new(_scratch); + sw.AppendFloat(m.Distance, "F0"); + sw.Append("m"); + if (m.IsLockedOnLocal) + { + sw.Append(" !"); + } + ReadOnlySpan label = sw.Span; + Vector2 textPos = ComputeInwardLabelPos(edge, dir, viewSize, label); + _hbCanvas.DrawText(label, textPos.X + 1f, textPos.Y + 1f, 10.5f, ShadowCol, wght: 600f); + _hbCanvas.DrawText(label, textPos.X, textPos.Y, 10.5f, arrowCol, wght: 600f); + } + + private static Vector2 ComputeOffscreenDirection(System.Numerics.Vector3 camLocal) + { + if (!float.IsFinite(camLocal.X) || !float.IsFinite(camLocal.Y) || !float.IsFinite(camLocal.Z)) + { + return Vector2.Down; + } + + Vector2 dir; + if (camLocal.Z >= 0f) + { + dir = new Vector2(camLocal.X, -camLocal.Y); + } + else + { + float horiz = MathF.Sqrt(camLocal.X * camLocal.X + camLocal.Z * camLocal.Z); + float t = Math.Clamp(-camLocal.Z / MathF.Max(1e-4f, horiz * 0.35f), 0f, 1f); + Vector2 sideDir = new(camLocal.X, -camLocal.Y); + Vector2 behindArcDir = new(camLocal.X, MathF.Max(-camLocal.Z, 0.35f * horiz)); + dir = sideDir.Lerp(behindArcDir, t); + if (MathF.Abs(camLocal.X) < 0.35f * horiz) + { + float minDown = 0.25f * dir.Length(); + if (dir.Y < minDown) + { + dir.Y = MathF.Max(minDown, 0.25f); + } + } + } + + float lenSq = dir.LengthSquared(); + if (!float.IsFinite(lenSq) || lenSq < 1e-6f) + { + return camLocal.Z < 0f ? Vector2.Down : Vector2.Up; + } + return dir / MathF.Sqrt(lenSq); + } + + private Vector2 ComputeSafeEdgePos(Vector2 center, float halfW, float halfH, Vector2 dir) + { + float tx = MathF.Abs(dir.X) > 1e-4f ? halfW / MathF.Abs(dir.X) : float.PositiveInfinity; + float ty = MathF.Abs(dir.Y) > 1e-4f ? halfH / MathF.Abs(dir.Y) : float.PositiveInfinity; + float tBest = MathF.Min(tx, ty); + + Span avoid = stackalloc Rect2[4] + { + _topLeftRect, + _topRightRect, + _bottomLeftRect, + _chyronRect + }; + for (int i = 0; i < avoid.Length; i++) + { + Rect2 r = avoid[i].Grow(PanelAvoidPad); + if (r.HasPoint(center)) continue; + if (TryRayEnterRect(center, dir, r, out float tEnter) && tEnter > 24f && tEnter < tBest) + { + tBest = tEnter; + } + } + + tBest = MathF.Max(24f, tBest); + return center + dir * tBest; + } + + private static bool TryRayEnterRect(Vector2 origin, Vector2 dir, Rect2 r, out float tEnter) + { + float tMin = 0f; + float tMax = float.PositiveInfinity; + + if (MathF.Abs(dir.X) < 1e-5f) + { + if (origin.X < r.Position.X || origin.X > r.End.X) + { + tEnter = 0f; + return false; + } + } + else + { + float invX = 1f / dir.X; + float t1 = (r.Position.X - origin.X) * invX; + float t2 = (r.End.X - origin.X) * invX; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + if (tMin > tMax) + { + tEnter = 0f; + return false; + } + } + + if (MathF.Abs(dir.Y) < 1e-5f) + { + if (origin.Y < r.Position.Y || origin.Y > r.End.Y) + { + tEnter = 0f; + return false; + } + } + else + { + float invY = 1f / dir.Y; + float t1 = (r.Position.Y - origin.Y) * invY; + float t2 = (r.End.Y - origin.Y) * invY; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + if (tMin > tMax) + { + tEnter = 0f; + return false; + } + } + + tEnter = tMin; + return true; + } + + private Vector2 ComputeInwardLabelPos(Vector2 edge, Vector2 dir, Vector2 viewSize, ReadOnlySpan label) + { + float w = _hbCanvas.MeasureTextWidth(label, 10.5f, wght: 600f); + const float h = 11f; + Vector2 inward = edge - dir * 14f; + float textX; + float textY; + + if (MathF.Abs(dir.X) >= MathF.Abs(dir.Y)) + { + textX = dir.X > 0f ? (inward.X - w - 4f) : (inward.X + 6f); + textY = inward.Y + h * 0.3f; + } + else + { + textX = inward.X - w * 0.5f; + textY = dir.Y > 0f ? (inward.Y - 4f) : (inward.Y + h + 4f); + } + + return new Vector2( + Math.Clamp(textX, 10f, MathF.Max(10f, viewSize.X - w - 10f)), + Math.Clamp(textY, 16f, MathF.Max(16f, viewSize.Y - 10f))); + } + + // ------------------------------------------------------------------------- + // Cached Text Helpers (Rebuild ONLY on state delta -> 0 B/frame steady state) + // ------------------------------------------------------------------------- + private void UpdatePromptCache(MatchState state, ContenderState player, OrbitalPod? localPod) + { + if (player.IsInDropPod) + { + int aglR = localPod is not null + ? Mathf.RoundToInt(MathF.Max(0f, localPod.LastAgl)) + : Mathf.RoundToInt(MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z))); + int velR = localPod is not null + ? Mathf.RoundToInt(MathF.Max(0f, -localPod.VelY)) + : Mathf.RoundToInt(MathF.Max(0f, -player.VelY)); + int horR = localPod is not null + ? Mathf.RoundToInt(MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ)) + : Mathf.RoundToInt(player.Speed); + bool burn = localPod?.Phase == OrbitalPodPhase.RetroBurn; + + if (_lastPromptPod && aglR == _lastPodAglRounded && horR == _lastPodHorizRounded && velR == _lastPodVertRounded && burn == _lastPodBurn) + { + return; + } + _lastPromptPod = true; + _lastPodAglRounded = aglR; + _lastPodHorizRounded = horR; + _lastPodVertRounded = velR; + _lastPodBurn = burn; + + _cachedPromptText = $"ORBITAL INSERTION — ALT {aglR}m | HORIZ {horR} m/s | VERT {velR} m/s | [WASD] STEER" + + (burn ? " [RETRO BURN]" : ""); + WrapTextInto(_cachedPromptText, 344f, 12f, 550f, _promptLines); + return; + } + + _lastPromptPod = false; + GroundDrop? nearest = state.FindNearestInteractableDrop(player.Id); + int promptKey = nearest is null + ? -1 + : HashCode.Combine( + nearest.Id, + nearest.Module?.Id ?? string.Empty, + nearest.Chassis?.Id ?? string.Empty, + nearest.Module is { } m ? (player.Grid.FindFirstEmptyCompatibleHardpoint(m)?.Id ?? string.Empty) : string.Empty); + + if (promptKey == _lastPromptKey) + { + return; + } + _lastPromptKey = promptKey; + + _cachedPromptText = BuildInteractionPrompt(player, nearest); + if (string.IsNullOrEmpty(_cachedPromptText)) + { + _promptLines.Clear(); + } + else + { + WrapTextInto(_cachedPromptText, 344f, 12f, 550f, _promptLines); + } + } + + private static string BuildInteractionPrompt(ContenderState player, GroundDrop? nearest) + { + if (nearest is null) return string.Empty; + if (nearest.Module is { } mod) + { + var freeHp = player.Grid.FindFirstEmptyCompatibleHardpoint(mod); + if (mod.Procedural is { } proc) + { + string action = freeHp is not null + ? $"[E] Bolt [{proc.ManufacturerLabel}] {mod.Name} -> {freeHp.Id}" + : $"[E] Loot [{proc.ManufacturerLabel}] {mod.Name}"; + return $"{action}\n{proc.SummaryLine1} | {proc.SummaryLine2}"; + } + return freeHp is not null + ? $"[E] Bolt {(mod.IsImperial ? "IMPERIAL " : "")}{mod.Name} -> {freeHp.Id}" + : $"[E] Loot {(mod.IsImperial ? "IMPERIAL " : "")}{mod.Name}"; + } + if (nearest.Chassis is { } ch) + { + return $"[E] Swap to {ch.Name} ({ch.Plane})"; + } + return string.Empty; + } + + private void UpdateHintCache(ContenderState player) + { + int mode = player.IsInDropPod ? 0 : (player.Grid.Spec.IsVtol ? 1 : 2); + if (mode == _lastHintMode && _hintLines.Count > 0) + { + return; + } + _lastHintMode = mode; + + string hint = mode switch + { + 0 => "WASD Steer Pod | Mouse Look | Retro-Burn Auto | Wheel Zoom", + 1 => "WASD Fly | Space/C Alt | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net", + _ => "WASD Drive | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net | Wheel Zoom" + }; + WrapTextInto(hint, 376f, 10.0f, 350f, _hintLines); + } + + private ReadOnlySpan TruncateWithEllipsis(string text, float maxWidthPx, float fontSizePx, float wght, char[] scratch) + { + if (string.IsNullOrEmpty(text) || _hbCanvas is null || _hbCanvas.MeasureTextWidth(text, fontSizePx, wght: wght) <= maxWidthPx) + { + return text; + } + + const string ellipsis = "..."; + int maxCopy = Math.Min(text.Length, scratch.Length - ellipsis.Length); + int bestLen = 0; + for (int len = 1; len <= maxCopy; len++) + { + scratch[len - 1] = text[len - 1]; + scratch[len] = '.'; + scratch[len + 1] = '.'; + scratch[len + 2] = '.'; + if (_hbCanvas.MeasureTextWidth(scratch.AsSpan(0, len + 3), fontSizePx, wght: wght) > maxWidthPx) + { + break; + } + bestLen = len; + } + for (int i = 0; i < bestLen; i++) + { + scratch[i] = text[i]; + } + scratch[bestLen] = '.'; + scratch[bestLen + 1] = '.'; + scratch[bestLen + 2] = '.'; + return scratch.AsSpan(0, bestLen + 3); + } + + private void SyncBroadcastChyron(BroadcastFeed broadcast) + { + var lines = broadcast.Lines; + if (ReferenceEquals(_lastBroadcastFeed, broadcast) && broadcast.Version == _lastChyronVersion) + { + return; + } + + _lastBroadcastFeed = broadcast; + _lastChyronVersion = broadcast.Version; + + // Evict by whole message from newest backwards so partial tail fragments of evicted messages never appear + int capacity = _chyronDisplayLines.Length; + int remaining = capacity; + int writeBack = capacity; + for (int m = lines.Count - 1; m >= 0 && remaining > 0; m--) + { + var line = lines[m]; + bool isLatestMsg = m == lines.Count - 1; + string formatted = $"[{line.Timestamp:00.0}s] {line.Text}"; + WrapTextInto(formatted, 548f, isLatestMsg ? 11.5f : 10.8f, isLatestMsg ? 500f : 380f, _chyronWrapScratch); + + int msgLineCount = _chyronWrapScratch.Count; + if (msgLineCount == 0) + { + continue; + } + + if (isLatestMsg && msgLineCount > remaining) + { + int skip = msgLineCount - remaining; + for (int w = msgLineCount - 1; w >= skip; w--) + { + writeBack--; + _chyronDisplayLines[writeBack] = _chyronWrapScratch[w]; + _chyronIsLatest[writeBack] = true; + } + remaining = 0; + break; + } + + if (msgLineCount > remaining) + { + // Whole-message eviction: stop before emitting a partial tail of an older message + break; + } + + for (int w = msgLineCount - 1; w >= 0; w--) + { + writeBack--; + _chyronDisplayLines[writeBack] = _chyronWrapScratch[w]; + _chyronIsLatest[writeBack] = isLatestMsg; + } + remaining -= msgLineCount; + } + + int total = capacity - writeBack; + if (writeBack > 0 && total > 0) + { + for (int i = 0; i < total; i++) + { + _chyronDisplayLines[i] = _chyronDisplayLines[writeBack + i]; + _chyronIsLatest[i] = _chyronIsLatest[writeBack + i]; + } + } + _chyronLineCount = total; + } + + private void OnHardpointClicked(string hardpointId) + { + var session = _getSession(); + if (session is null) return; + var cargo = session.LocalContender.Grid.Cargo; + if (_selectedCargoIndex >= 0 && _selectedCargoIndex < cargo.Count) + { + _onEquipCargo(_selectedCargoIndex, hardpointId); + _selectedCargoIndex = -1; + _lastGarageHash = int.MinValue; + _dirtyEmit = true; + } + } + + private void AutoFitCargo(ChassisGrid grid, int cargoIndex) + { + if (cargoIndex < 0 || cargoIndex >= grid.Cargo.Count) return; + var mod = grid.Cargo[cargoIndex]; + for (int i = 0; i < grid.Spec.Hardpoints.Length; i++) + { + var hp = grid.Spec.Hardpoints[i]; + if (ChassisGrid.CanFit(hp, mod)) + { + _onEquipCargo(cargoIndex, hp.Id); + _selectedCargoIndex = -1; + _lastGarageHash = int.MinValue; + _dirtyEmit = true; + return; + } + } + } + + private void OnSchematicHoverChanged(Vector2I? cell, HardpointSpec? hp) + { + _lastHoveredCell = cell; + var grid = _schematic.Grid; + if (cell is null || grid is null) + { + if (!UpdateCargoSelectionTooltip(grid)) + { + SetHoverText("HOVER CELL FOR TELEMETRY", TextMuted); + } + return; + } + + var c = cell.Value; + float arm = grid.Armor[c.X, c.Y]; + float maxArm = grid.MaxArmor[c.X, c.Y]; + float temp = grid.Temperature[c.X, c.Y]; + if (hp is not null) + { + var mounted = grid.GetMountedOn(hp.Id); + bool strippedHp = !grid.IsHardpointOperational(hp); + string hpStatus = strippedHp ? " [STRIPPED]" : ""; + if (mounted is not null && mounted.Spec.Procedural is { } proc) + { + SetHoverText( + $"[{proc.ManufacturerLabel}] {proc.SummaryLine1}{hpStatus}\n{proc.SummaryLine2}", + (arm <= 0.01f || strippedHp) ? RedCol : ResolveManufacturerHudColor(proc.Manufacturer)); + } + else + { + string txt = mounted is not null + ? $"{hp.Kind.ToString().ToUpperInvariant()}: {mounted.Spec.Name} {mounted.CurrentTemp:F0}°C ({mounted.CurrentPerformance * 100f:F0}%){hpStatus}" + : $"{hp.Kind.ToString().ToUpperInvariant()} SLOT [{hp.Width}x{hp.Height}] EMPTY{hpStatus}"; + SetHoverText(txt, (arm <= 0.01f || strippedHp) ? RedCol : TextLight); + } + } + else + { + string txt = arm <= 0.01f + ? $"CELL ({c.X},{c.Y}) STRIPPED! {temp:F0}°C" + : $"HULL ({c.X},{c.Y}) ARM {arm:F0}/{maxArm:F0} {temp:F0}°C"; + SetHoverText(txt, arm <= 0.01f ? RedCol : TextMuted); + } + } + + private bool UpdateCargoSelectionTooltip(ChassisGrid? grid) + { + if (grid is null || _selectedCargoIndex < 0 || _selectedCargoIndex >= grid.Cargo.Count) + { + return false; + } + var mod = grid.Cargo[_selectedCargoIndex]; + if (mod.Procedural is { } proc) + { + SetHoverText($"[{proc.ManufacturerLabel}] {proc.SummaryLine1}\n{proc.SummaryLine2}", ResolveManufacturerHudColor(proc.Manufacturer)); + } + else + { + SetHoverText($"CARGO: {mod.Name} [{mod.Width}x{mod.Height}]", mod.IsImperial ? GoldCol : TextLight); + } + return true; + } + + private void SetHoverText(string text, Color color) + { + if (string.Equals(_cachedHoverText, text, StringComparison.Ordinal) && _cachedHoverColor == color) + { + return; + } + _cachedHoverText = text; + _cachedHoverColor = color; + float maxW = _garageExpanded ? 198f : 180f; + WrapTextInto(text, maxW, 10f, 400f, _hoverLines); + _dirtyEmit = true; + } + + private void UpdateGarageDetailsCache(ChassisGrid grid) + { + var hc = new HashCode(); + hc.Add(grid.Spec.Id); + hc.Add(grid.Mounted.Count); + hc.Add(_selectedCargoIndex); + if (_selectedCargoIndex >= 0 && _selectedCargoIndex < grid.Cargo.Count) + { + hc.Add(grid.Cargo[_selectedCargoIndex].Id); + } + for (int i = 0; i < grid.Mounted.Count; i++) + { + var m = grid.Mounted[i]; + hc.Add(m.HardpointId); + hc.Add(m.Spec.Id); + hc.Add(Mathf.RoundToInt(m.CurrentTemp)); + hc.Add(grid.IsHardpointOperational(m.HardpointId)); + } + int sig = hc.ToHashCode(); + if (sig == _lastGarageHash) + { + return; + } + _lastGarageHash = sig; + + _garageLines.Clear(); + var rawLines = new List(16) + { + $"COND {grid.Spec.HullConductivity:F1} | THRUST {grid.ComputeDriveThrust():F0} N", + "MOUNTED:" + }; + _garageLines.Add(rawLines[0]); + _garageLines.Add(rawLines[1]); + for (int i = 0; i < grid.Mounted.Count; i++) + { + var m = grid.Mounted[i]; + string stateTag = grid.IsHardpointOperational(m.HardpointId) ? "" : " [STRIPPED]"; + if (m.Spec.Procedural is { } proc) + { + string l0 = $"• [{proc.ManufacturerLabel}] {m.Spec.Name} {m.CurrentTemp:F0}°C{stateTag}"; + rawLines.Add(l0); + rawLines.Add($" {proc.SummaryLine1}"); + rawLines.Add($" {proc.SummaryLine2}"); + WrapTextInto(l0, 184f, 10f, 400f, _garageLines, clearDest: false); + WrapTextInto($" {proc.SummaryLine1}", 184f, 10f, 400f, _garageLines, clearDest: false); + WrapTextInto($" {proc.SummaryLine2}", 184f, 10f, 400f, _garageLines, clearDest: false); + } + else + { + string l0 = $"• {m.HardpointId}: {m.Spec.Name} {m.CurrentTemp:F0}°C ({m.CurrentPerformance * 100f:F0}%){stateTag}"; + rawLines.Add(l0); + WrapTextInto(l0, 184f, 10f, 400f, _garageLines, clearDest: false); + } + } + if (_selectedCargoIndex >= 0 && _selectedCargoIndex < grid.Cargo.Count && + grid.Cargo[_selectedCargoIndex].Procedural is { } cargoProc) + { + string l0 = $"SEL [{cargoProc.ManufacturerLabel}]:"; + rawLines.Add(l0); + rawLines.Add($" {cargoProc.SummaryLine1}"); + rawLines.Add($" {cargoProc.SummaryLine2}"); + _garageLines.Add(l0); + WrapTextInto($" {cargoProc.SummaryLine1}", 184f, 10f, 400f, _garageLines, clearDest: false); + WrapTextInto($" {cargoProc.SummaryLine2}", 184f, 10f, 400f, _garageLines, clearDest: false); + } + _cachedGarageDetails = string.Join("\n", rawLines); + } + + private void WrapTextInto(string text, float maxWidthPx, float fontSizePx, float wght, List dest, bool clearDest = true) + { + if (clearDest) + { + dest.Clear(); + } + if (string.IsNullOrEmpty(text)) + { + return; + } + + int lineStart = 0; + for (int idx = 0; idx <= text.Length; idx++) + { + if (idx == text.Length || text[idx] == '\n') + { + WrapParagraph(text.AsSpan(lineStart, idx - lineStart), maxWidthPx, fontSizePx, wght, dest); + lineStart = idx + 1; + } + } + } + + private void WrapParagraph(ReadOnlySpan para, float maxWidthPx, float fontSizePx, float wght, List dest) + { + if (para.IsEmpty) + { + dest.Add(string.Empty); + return; + } + + if (_hbCanvas is null || _hbCanvas.MeasureTextWidth(para, fontSizePx, wght: wght) <= maxWidthPx) + { + dest.Add(new string(para)); + return; + } + + int pos = 0; + while (pos < para.Length) + { + int bestEnd = pos + 1; + int lastSpace = -1; + for (int end = pos + 1; end <= para.Length; end++) + { + if (end < para.Length && para[end] == ' ') + { + lastSpace = end; + } + float w = _hbCanvas.MeasureTextWidth(para.Slice(pos, end - pos), fontSizePx, wght: wght); + if (w > maxWidthPx) + { + break; + } + bestEnd = end; + } + + int cut = (bestEnd < para.Length && lastSpace > pos) ? lastSpace : bestEnd; + dest.Add(new string(para.Slice(pos, cut - pos))); + pos = cut; + while (pos < para.Length && para[pos] == ' ') + { + pos++; + } + } + } + + private static Color ResolveManufacturerHudColor(ManufacturerId mfg) => mfg switch + { + ManufacturerId.ScrapFrontier => Color.FromHtml("#ffaa33"), + ManufacturerId.KorrathiIronworks => Color.FromHtml("#f2c422"), + ManufacturerId.AuralianOptics => Color.FromHtml("#38e8ff"), + ManufacturerId.VexNineCollective => Color.FromHtml("#7cf230"), + ManufacturerId.ThalassanForge => Color.FromHtml("#2cb8ff"), + _ => GoldCol + }; + + // ------------------------------------------------------------------------- + // [F9] Interactive Multiplayer Link Panel (Godot Controls kept until Cut 14c) + // ------------------------------------------------------------------------- + private void BuildNetworkPanel() + { + var panelStyle = new StyleBoxFlat + { + BgColor = new Color(0f, 0f, 0f, 0f), + BorderColor = new Color(0f, 0f, 0f, 0f), + ContentMarginLeft = 10, + ContentMarginRight = 10, + ContentMarginTop = 8, + ContentMarginBottom = 8 + }; + panelStyle.SetBorderWidthAll(0); + + _netPanel = new PanelContainer + { + Name = "NetworkLinkPanel", + Visible = false + }; + _netPanel.AddThemeStyleboxOverride("panel", panelStyle); + _netPanel.AnchorLeft = 0.5f; + _netPanel.AnchorRight = 0.5f; + _netPanel.AnchorTop = 0.32f; + _netPanel.AnchorBottom = 0.32f; + _netPanel.OffsetLeft = -188f; + _netPanel.OffsetRight = 188f; + _netPanel.OffsetTop = 0f; + _netPanel.OffsetBottom = 0f; + AddChild(_netPanel); + + var vbox = new VBoxContainer(); + vbox.AddThemeConstantOverride("separation", 6); + _netPanel.AddChild(vbox); + + var headRow = new HBoxContainer(); + headRow.AddThemeConstantOverride("separation", 8); + vbox.AddChild(headRow); + + var title = new Label + { + Text = "MULTIPLAYER LINK [F9]", + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + title.AddThemeColorOverride("font_color", CyanCol); + title.AddThemeFontSizeOverride("font_size", 13); + headRow.AddChild(title); + + _netModeBadge = new Label { Text = "SOLO" }; + _netModeBadge.AddThemeColorOverride("font_color", OliveCol); + _netModeBadge.AddThemeFontSizeOverride("font_size", 12); + headRow.AddChild(_netModeBadge); + + _netPanelStatus = new Label + { + Text = "LOCAL SOLO SESSION", + AutowrapMode = TextServer.AutowrapMode.Word + }; + _netPanelStatus.AddThemeColorOverride("font_color", TextMuted); + _netPanelStatus.AddThemeFontSizeOverride("font_size", 11); + vbox.AddChild(_netPanelStatus); + + var nameRow = new HBoxContainer(); + nameRow.AddThemeConstantOverride("separation", 6); + vbox.AddChild(nameRow); + + var nameLbl = new Label { Text = "CALLSIGN", CustomMinimumSize = new Vector2(74f, 0f) }; + nameLbl.AddThemeColorOverride("font_color", TextMuted); + nameLbl.AddThemeFontSizeOverride("font_size", 11); + nameRow.AddChild(nameLbl); + + _callsignEdit = new LineEdit + { + Text = "Pilot", + MaxLength = 24, + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, + PlaceholderText = "Callsign" + }; + _callsignEdit.AddThemeFontSizeOverride("font_size", 12); + nameRow.AddChild(_callsignEdit); + + var epRow = new HBoxContainer(); + epRow.AddThemeConstantOverride("separation", 6); + vbox.AddChild(epRow); + + var epLbl = new Label { Text = "HOST:PORT", CustomMinimumSize = new Vector2(74f, 0f) }; + epLbl.AddThemeColorOverride("font_color", TextMuted); + epLbl.AddThemeFontSizeOverride("font_size", 11); + epRow.AddChild(epLbl); + + _endpointEdit = new LineEdit + { + Text = "127.0.0.1:3076", + MaxLength = 96, + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, + PlaceholderText = "127.0.0.1:3076" + }; + _endpointEdit.AddThemeFontSizeOverride("font_size", 12); + epRow.AddChild(_endpointEdit); + + var btnRow = new HBoxContainer(); + btnRow.AddThemeConstantOverride("separation", 6); + vbox.AddChild(btnRow); + + var hostBtn = new Button { Text = "Host", SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, FocusMode = Control.FocusModeEnum.None }; + hostBtn.AddThemeFontSizeOverride("font_size", 12); + hostBtn.Pressed += () => + { + _uiNetError = null; + int port = ParsePort(_endpointEdit.Text, 3076); + HostRequested?.Invoke(port, _callsignEdit.Text); + }; + btnRow.AddChild(hostBtn); + + var joinBtn = new Button { Text = "Join", SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, FocusMode = Control.FocusModeEnum.None }; + joinBtn.AddThemeFontSizeOverride("font_size", 12); + joinBtn.Pressed += () => + { + _uiNetError = null; + JoinRequested?.Invoke(_endpointEdit.Text, _callsignEdit.Text); + }; + btnRow.AddChild(joinBtn); + + var soloBtn = new Button { Text = "Solo", SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, FocusMode = Control.FocusModeEnum.None }; + soloBtn.AddThemeFontSizeOverride("font_size", 12); + soloBtn.Pressed += () => + { + _uiNetError = null; + SoloRequested?.Invoke(); + }; + btnRow.AddChild(soloBtn); + + var closeBtn = new Button { Text = "Close", FocusMode = Control.FocusModeEnum.None }; + closeBtn.AddThemeFontSizeOverride("font_size", 12); + closeBtn.Pressed += () => SetNetworkPanelOpen(false); + btnRow.AddChild(closeBtn); + } + + private void SyncNetworkPanel(NetworkStatusSnapshot net) + { + _netModeBadge.Text = net.Mode switch + { + NetworkMode.ListenHost => "HOST", + NetworkMode.RemoteClient => "CLIENT", + _ => "SOLO" + }; + _netModeBadge.Modulate = net.Mode == NetworkMode.Solo ? OliveCol : CyanCol; + + string? err = _uiNetError ?? net.LastError; + if (!string.IsNullOrWhiteSpace(err)) + { + _netPanelStatus.Text = $"ERROR: {err}"; + _netPanelStatus.AddThemeColorOverride("font_color", RedCol); + return; + } + + if (net.Mode == NetworkMode.Solo) + { + _netPanelStatus.Text = "OFFLINE SOLO — ZERO NETWORK LATENCY"; + _netPanelStatus.AddThemeColorOverride("font_color", TextMuted); + } + else if (net.Mode == NetworkMode.ListenHost) + { + _netPanelStatus.Text = $"{net.StateLabel} • {net.ConnectedHumans}/{net.MaxHumans} HUMANS"; + _netPanelStatus.AddThemeColorOverride("font_color", CyanCol); + } + else if (net.Connected) + { + _netPanelStatus.Text = $"CONNECTED • PING {net.PingMs} ms • {net.ConnectedHumans}/{net.MaxHumans} HUMANS"; + _netPanelStatus.AddThemeColorOverride("font_color", OliveCol); + } + else + { + _netPanelStatus.Text = $"STATE: {net.StateLabel}..."; + _netPanelStatus.AddThemeColorOverride("font_color", OrangeCol); + } + } + + private static int ParsePort(string text, int fallback) + { + string trimmed = (text ?? string.Empty).Trim(); + int colon = trimmed.LastIndexOf(':'); + if (colon >= 0 && colon + 1 < trimmed.Length && + int.TryParse(trimmed[(colon + 1)..], NumberStyles.Integer, CultureInfo.InvariantCulture, out int p) && + p is > 0 and <= 65535) + { + return p; + } + if (int.TryParse(trimmed, NumberStyles.Integer, CultureInfo.InvariantCulture, out int direct) && + direct is > 0 and <= 65535) + { + return direct; + } + return fallback; + } + + private ref struct SpanWriter + { + private readonly char[] _buf; + private int _pos; + + public SpanWriter(char[] buf) + { + _buf = buf; + _pos = 0; + } + + public readonly ReadOnlySpan Span => _buf.AsSpan(0, _pos); + + public void Append(ReadOnlySpan s) + { + int copy = Math.Min(s.Length, _buf.Length - _pos); + if (copy > 0) + { + s[..copy].CopyTo(_buf.AsSpan(_pos)); + _pos += copy; + } + } + + public void AppendInt(int val) + { + if (val.TryFormat(_buf.AsSpan(_pos), out int written, default, CultureInfo.InvariantCulture)) + { + _pos += written; + } + } + + public void AppendFloat(float val, ReadOnlySpan fmt) + { + if (val.TryFormat(_buf.AsSpan(_pos), out int written, fmt, CultureInfo.InvariantCulture)) + { + _pos += written; + } + } + } +} diff --git a/client/ImperialChrome.cs b/client/ImperialChrome.cs new file mode 100644 index 0000000..39896a0 --- /dev/null +++ b/client/ImperialChrome.cs @@ -0,0 +1,213 @@ +using Godot; + +namespace RustToDust.Client; + +/// +/// Shared Industrial Imperial palette and beveled panel_chrome.gdshader panel/control +/// helpers for pre-match UI layers (, , +/// ). Kept separate from so Hud.GetChromeMaterials() +/// preserves its exact 6-panel contract. +/// +public static class ImperialChrome +{ + public static readonly Color BgDark = Color.FromHtml("#131613"); + public static readonly Color BgInner = Color.FromHtml("#1b1f1b"); + public static readonly Color BgHover = Color.FromHtml("#242b23"); + public static readonly Color BgPressed = Color.FromHtml("#2e372c"); + public static readonly Color BorderCol = Color.FromHtml("#3e4638"); + public static readonly Color OliveCol = Color.FromHtml("#9bb06a"); + public static readonly Color OrangeCol = Color.FromHtml("#e08a4a"); + public static readonly Color TextLight = Color.FromHtml("#e4dfd2"); + public static readonly Color TextMuted = Color.FromHtml("#989487"); + public static readonly Color CyanCol = Color.FromHtml("#44d9e8"); + public static readonly Color GoldCol = Color.FromHtml("#e6b838"); + public static readonly Color RedCol = Color.FromHtml("#d93829"); + public static readonly Color ScrimCol = new(0.03f, 0.04f, 0.03f, 0.56f); + + private static Shader? _sharedChromeShader; + private static ImageTexture? _sharedWhiteTex; + + internal static Shader? ChromeShader => _sharedChromeShader ??= GD.Load("res://panel_chrome.gdshader"); + + internal static ImageTexture WhiteTexture + { + get + { + if (_sharedWhiteTex is null) + { + var img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + img.SetPixel(0, 0, Colors.White); + _sharedWhiteTex = ImageTexture.CreateFromImage(img); + } + return _sharedWhiteTex; + } + } + + public static ImperialChromePanel CreatePanel( + Color accentColor, + float cornerLen = 14f, + float borderPx = 1.5f, + float bgAlpha = 0.90f, + int padH = 14, + int padV = 12) + { + return new ImperialChromePanel(accentColor, cornerLen, borderPx, bgAlpha, padH, padV); + } + + public static Label CreateLabel(string text, int fontSize, Color color, HorizontalAlignment align = HorizontalAlignment.Left) + { + var lbl = new Label + { + Text = text, + HorizontalAlignment = align + }; + lbl.AddThemeFontSizeOverride("font_size", fontSize); + lbl.AddThemeColorOverride("font_color", color); + return lbl; + } + + public static Button CreateButton(string text, Color accentColor, int fontSize = 13, float minHeight = 32f) + { + var btn = new Button + { + Text = text, + FocusMode = Control.FocusModeEnum.None, + CustomMinimumSize = new Vector2(0f, minHeight) + }; + StyleButton(btn, accentColor, fontSize); + return btn; + } + + public static void StyleButton(Button btn, Color accentColor, int fontSize = 13) + { + btn.AddThemeFontSizeOverride("font_size", fontSize); + btn.AddThemeColorOverride("font_color", TextLight); + btn.AddThemeColorOverride("font_hover_color", Colors.White); + btn.AddThemeColorOverride("font_pressed_color", accentColor); + btn.AddThemeColorOverride("font_disabled_color", new Color(TextMuted.R, TextMuted.G, TextMuted.B, 0.45f)); + + var normal = MakeBox(BgInner, new Color(accentColor.R, accentColor.G, accentColor.B, 0.55f), 1); + var hover = MakeBox(BgHover, accentColor, 1); + var pressed = MakeBox(BgPressed, accentColor, 2); + var disabled = MakeBox(new Color(BgDark.R, BgDark.G, BgDark.B, 0.65f), new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.4f), 1); + + btn.AddThemeStyleboxOverride("normal", normal); + btn.AddThemeStyleboxOverride("hover", hover); + btn.AddThemeStyleboxOverride("pressed", pressed); + btn.AddThemeStyleboxOverride("disabled", disabled); + btn.AddThemeStyleboxOverride("focus", hover); + } + + public static void StyleLineEdit(LineEdit edit, Color accentColor, int fontSize = 13) + { + edit.AddThemeFontSizeOverride("font_size", fontSize); + edit.AddThemeColorOverride("font_color", TextLight); + edit.AddThemeColorOverride("font_placeholder_color", new Color(TextMuted.R, TextMuted.G, TextMuted.B, 0.65f)); + edit.AddThemeColorOverride("font_uneditable_color", TextMuted); + edit.AddThemeColorOverride("caret_color", accentColor); + + var normal = MakeBox(BgInner, BorderCol, 1, padH: 8, padV: 4); + var focus = MakeBox(BgHover, accentColor, 1, padH: 8, padV: 4); + var readOnly = MakeBox(new Color(BgDark.R, BgDark.G, BgDark.B, 0.72f), new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.45f), 1, padH: 8, padV: 4); + + edit.AddThemeStyleboxOverride("normal", normal); + edit.AddThemeStyleboxOverride("focus", focus); + edit.AddThemeStyleboxOverride("read_only", readOnly); + } + + public static void StyleOptionButton(OptionButton opt, Color accentColor, int fontSize = 13) + { + StyleButton(opt, accentColor, fontSize); + } + + public static void StyleCheckBox(CheckBox chk, Color accentColor, int fontSize = 12) + { + chk.FocusMode = Control.FocusModeEnum.None; + chk.AddThemeFontSizeOverride("font_size", fontSize); + chk.AddThemeColorOverride("font_color", TextLight); + chk.AddThemeColorOverride("font_hover_color", Colors.White); + chk.AddThemeColorOverride("font_pressed_color", accentColor); + chk.AddThemeColorOverride("font_disabled_color", TextMuted); + } + + public static HSeparator MakeRule(Color? color = null) + { + var sep = new HSeparator(); + var line = new StyleBoxLine + { + Color = color ?? new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.75f), + Thickness = 1 + }; + sep.AddThemeStyleboxOverride("separator", line); + return sep; + } + + private static StyleBoxFlat MakeBox(Color bg, Color border, int borderW, int padH = 10, int padV = 6) + { + var box = new StyleBoxFlat + { + BgColor = bg, + BorderColor = border, + ContentMarginLeft = padH, + ContentMarginRight = padH, + ContentMarginTop = padV, + ContentMarginBottom = padV + }; + box.SetBorderWidthAll(borderW); + return box; + } +} + +public sealed partial class ImperialChromePanel : PanelContainer +{ + private readonly ShaderMaterial _material; + + public ImperialChromePanel( + Color accentColor, + float cornerLen = 14f, + float borderPx = 1.5f, + float bgAlpha = 0.90f, + int padH = 14, + int padV = 12) + { + _material = new ShaderMaterial { Shader = ImperialChrome.ChromeShader }; + _material.SetShaderParameter("bg_color", new Color(ImperialChrome.BgDark.R, ImperialChrome.BgDark.G, ImperialChrome.BgDark.B, bgAlpha)); + _material.SetShaderParameter("border_color", ImperialChrome.BorderCol); + _material.SetShaderParameter("accent_color", accentColor); + _material.SetShaderParameter("corner_len", cornerLen); + _material.SetShaderParameter("border_px", borderPx); + Material = _material; + + var empty = new StyleBoxEmpty + { + ContentMarginLeft = padH, + ContentMarginRight = padH, + ContentMarginTop = padV, + ContentMarginBottom = padV + }; + AddThemeStyleboxOverride("panel", empty); + } + + public ShaderMaterial ChromeMaterial => _material; + + public void SetAccentColor(Color accentColor) + { + _material.SetShaderParameter("accent_color", accentColor); + } + + public override void _Notification(int what) + { + if (what == NotificationResized) + { + _material.SetShaderParameter("rect_size", Size); + QueueRedraw(); + } + } + + public override void _Draw() + { + if (Size.X < 2f || Size.Y < 2f) return; + _material.SetShaderParameter("rect_size", Size); + DrawTextureRect(ImperialChrome.WhiteTexture, new Rect2(Vector2.Zero, Size), false, Colors.White); + } +} diff --git a/client/InventoryGridControl.cs b/client/InventoryGridControl.cs new file mode 100644 index 0000000..1c5fafd --- /dev/null +++ b/client/InventoryGridControl.cs @@ -0,0 +1,934 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; +using RustToDust.HbGpu; + +namespace RustToDust.Client; + +/// +/// Godot Control owning inventory_grid.gdshader: +/// packs a into a 3W x H RGBA8 nearest-filter data texture +/// and a W x H RGBA8 bilinear temperature texture, tracks hover and hit-pulse decay, +/// and provides accurate mouse-to-cell hit-testing for HUD and Garage schematics. +/// +public partial class InventoryGridControl : Control +{ + private static readonly Color ColBgIntact = Color.FromHtml("#263022"); + private static readonly Color ColBgArmorFull = Color.FromHtml("#4b6136"); + private static readonly Color ColBgDamaged = Color.FromHtml("#8a3c22"); + private static readonly Color ColBgStripped = Color.FromHtml("#2b1210"); + + private static readonly Color ColBorderHull = Color.FromHtml("#7a856e"); + private static readonly Color ColBorderRadiatorCell = Color.FromHtml("#44d9e8"); + private static readonly Color ColBorderWeapon = Color.FromHtml("#e08a4a"); + private static readonly Color ColBorderEngine = Color.FromHtml("#e6b838"); + private static readonly Color ColBorderRadiator = Color.FromHtml("#44d9e8"); + private static readonly Color ColBorderArmor = Color.FromHtml("#9bb06a"); + private static readonly Color ColBorderUtility = Color.FromHtml("#4ba8a5"); + private static readonly Color ColGold = Color.FromHtml("#e6b838"); + private static readonly Color ColTextLight = Color.FromHtml("#e4dfd2"); + + // 8-neighbor offsets in Aetheria mask order: N, E, S, W, NE, SE, SW, NW (screen Y-down) + private static readonly (int Dx, int Dy)[] Offsets8 = + { + (0, -1), (1, 0), (0, 1), (-1, 0), + (1, -1), (1, 1), (-1, 1), (-1, -1) + }; + + private static Shader? _sharedShader; + + private readonly TextureRect _gridSurface; + private readonly ShaderMaterial _material; + private HbGpuCanvas? _standaloneCanvas; + + private readonly Dictionary _lastEmittedTags = new(StringComparer.Ordinal); + private readonly char[] _tagScratch = new char[32]; + private int _overlayEmitCount; + private float _standaloneTime; + private bool _standaloneDirty = true; + + private Image? _dataImage; + private ImageTexture? _dataTex; + private Image? _tempImage; + private ImageTexture? _tempTex; + + private int _gridWidth; + private int _gridHeight; + private ChassisGrid? _grid; + private ChassisSpec? _spec; + private int _selectedCargoIndex = -1; + private int _lastHitSequence = -1; + + private HardpointSpec?[,] _hardpointLookup = new HardpointSpec?[0, 0]; + private float[,] _prevArmor = new float[0, 0]; + private float[,] _prevTemp = new float[0, 0]; + private float[,] _hitPulse = new float[0, 0]; + + private int _lastSelectedCargoIndex = int.MinValue; + private string? _lastSelectedCargoId; + private int _lastMountedSig = int.MinValue; + private Vector2I? _hoveredCell; + private bool _dataDirty; + private bool _tempDirty; + + public InventoryGridControl() + { + MouseFilter = MouseFilterEnum.Stop; + + _sharedShader ??= GD.Load("res://inventory_grid.gdshader"); + _material = new ShaderMaterial { Shader = _sharedShader }; + + _gridSurface = new TextureRect + { + Name = "GridShaderSurface", + MouseFilter = MouseFilterEnum.Ignore, + ExpandMode = TextureRect.ExpandModeEnum.IgnoreSize, + StretchMode = TextureRect.StretchModeEnum.Scale, + Material = _material + }; + _gridSurface.SetAnchorsPreset(LayoutPreset.FullRect); + AddChild(_gridSurface); + + MouseExited += OnMouseExited; + } + + public bool ExternalHbGpuOwner { get; set; } + public ShaderMaterial ShaderMaterial => _material; + public Control ShaderSurface => _gridSurface; + public ChassisGrid? Grid => _grid; + public Vector2I? HoveredCell => _hoveredCell; + public HardpointSpec? HoveredHardpoint => + _hoveredCell is { } c && _grid is not null && c.X >= 0 && c.Y >= 0 && c.X < _gridWidth && c.Y < _gridHeight + ? _hardpointLookup[c.X, c.Y] + : null; + + internal int OverlayEmitCount => _overlayEmitCount; + internal HbGpuCanvas? StandaloneCanvas => _standaloneCanvas; + internal string? GetLastEmittedLabel(string hardpointId) => + _lastEmittedTags.TryGetValue(hardpointId, out string? tag) ? tag : null; + + public override void _Ready() + { + if (!ExternalHbGpuOwner && _standaloneCanvas is null) + { + _standaloneCanvas = new HbGpuCanvas + { + Name = "StandaloneHbGpuCanvas", + MouseFilter = MouseFilterEnum.Ignore + }; + _standaloneCanvas.SetAnchorsPreset(LayoutPreset.FullRect); + AddChild(_standaloneCanvas); + } + } + + public event Action? CellClicked; + public event Action? HardpointClicked; + public event Action? HoverChanged; + + public override void _Notification(int what) + { + if (what == NotificationResized) + { + SyncRectUniform(); + _standaloneDirty = true; + } + } + + public override void _Process(double delta) + { + float dt = (float)delta; + _standaloneTime += MathF.Max(0f, dt); + + bool anyPulse = false; + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + if (_hitPulse[x, y] > 0f) + { + _hitPulse[x, y] = MathF.Max(0f, _hitPulse[x, y] - dt * 2.8f); + anyPulse = true; + } + } + } + + if (anyPulse && _grid is not null) + { + PackDataTexture(_grid); + FlushTextures(); + _standaloneDirty = true; + } + + if (!ExternalHbGpuOwner && _standaloneCanvas is not null && _grid is not null) + { + bool hasCompatiblePulse = _selectedCargoIndex >= 0 && _selectedCargoIndex < _grid.Cargo.Count; + if (_standaloneDirty || hasCompatiblePulse) + { + _standaloneDirty = false; + _standaloneCanvas.BeginFrame(); + EmitHbGpuOverlay(_standaloneCanvas, Vector2.Zero, _standaloneTime); + _standaloneCanvas.EndFrameAndSubmit(); + } + } + } + + public override void _GuiInput(InputEvent @event) + { + if (@event is InputEventMouseMotion mm) + { + UpdateHover(mm.Position); + return; + } + + if (@event is InputEventMouseButton mb && mb.Pressed && mb.ButtonIndex == MouseButton.Left) + { + UpdateHover(mb.Position); + if (TryGetCellAt(mb.Position, out var cell) && _grid is not null && _grid.Spec.IsActive(cell.X, cell.Y)) + { + CellClicked?.Invoke(cell.X, cell.Y); + var hp = _hardpointLookup[cell.X, cell.Y]; + if (hp is not null) + { + HardpointClicked?.Invoke(hp.Id); + } + AcceptEvent(); + } + } + } + + public void SetGrid(ChassisGrid grid, int selectedCargoIndex = -1) + { + if (grid is null) throw new ArgumentNullException(nameof(grid)); + + bool gridIdentityChanged = !ReferenceEquals(_grid, grid) + || !ReferenceEquals(_spec, grid.Spec) + || _gridWidth != grid.Spec.Width + || _gridHeight != grid.Spec.Height; + + _grid = grid; + _spec = grid.Spec; + _selectedCargoIndex = selectedCargoIndex; + string? selectedCargoId = selectedCargoIndex >= 0 && selectedCargoIndex < grid.Cargo.Count + ? grid.Cargo[selectedCargoIndex].Id + : null; + + if (gridIdentityChanged) + { + EnsureBackingBuffers(grid); + _lastSelectedCargoIndex = selectedCargoIndex; + _lastSelectedCargoId = selectedCargoId; + _lastMountedSig = ComputeMountedSignature(grid); + SnapshotTemperatures(grid); + PackDataTexture(grid); + PackTempTexture(grid); + FlushTextures(); + SyncRectUniform(); + _standaloneDirty = true; + return; + } + + bool dataChanged = DetectHits(grid); + int mountedSig = ComputeMountedSignature(grid); + if (_lastSelectedCargoIndex != selectedCargoIndex || + !string.Equals(_lastSelectedCargoId, selectedCargoId, StringComparison.Ordinal) || + _lastMountedSig != mountedSig) + { + _lastSelectedCargoIndex = selectedCargoIndex; + _lastSelectedCargoId = selectedCargoId; + _lastMountedSig = mountedSig; + dataChanged = true; + } + + bool tempChanged = HasTemperatureChanged(grid); + + if (dataChanged) + { + PackDataTexture(grid); + } + if (tempChanged) + { + SnapshotTemperatures(grid); + PackTempTexture(grid); + } + if (dataChanged || tempChanged) + { + _standaloneDirty = true; + FlushTextures(); + } + } + + public void TriggerHitPulse(int x, int y, float intensity = 1f) + { + if (_grid is null || x < 0 || y < 0 || x >= _gridWidth || y >= _gridHeight) return; + if (!_grid.Spec.IsActive(x, y)) return; + _hitPulse[x, y] = Math.Clamp(intensity, 0f, 1f); + PackDataTexture(_grid); + FlushTextures(); + _standaloneDirty = true; + } + + public bool TryGetCellAt(Vector2 localPos, out Vector2I cell) + { + cell = default; + if (_grid is null || _gridWidth <= 0 || _gridHeight <= 0) return false; + ComputeCellLayout(out float cellSize, out Vector2 origin); + if (cellSize <= 0.5f) return false; + + Vector2 rel = (localPos - origin) / cellSize; + int cx = Mathf.FloorToInt(rel.X); + int cy = Mathf.FloorToInt(rel.Y); + if (cx < 0 || cy < 0 || cx >= _gridWidth || cy >= _gridHeight) return false; + cell = new Vector2I(cx, cy); + return true; + } + + public HardpointSpec? GetHardpointAt(int x, int y) + { + if (x < 0 || y < 0 || x >= _gridWidth || y >= _gridHeight) return null; + return _hardpointLookup[x, y]; + } + + public void ComputeCellLayout(out float cellSize, out Vector2 origin) + { + int w = Math.Max(1, _gridWidth); + int h = Math.Max(1, _gridHeight); + Vector2 size = Size; + if (size.X < 2f || size.Y < 2f) + { + size = CustomMinimumSize; + } + cellSize = MathF.Min(size.X / w, size.Y / h); + origin = (size - new Vector2(w * cellSize, h * cellSize)) * 0.5f; + } + + private void OnMouseExited() + { + if (_hoveredCell.HasValue) + { + _hoveredCell = null; + HoverChanged?.Invoke(null, null); + if (_grid is not null) + { + PackDataTexture(_grid); + FlushTextures(); + _standaloneDirty = true; + } + } + } + + private void UpdateHover(Vector2 localPos) + { + Vector2I? next = null; + if (TryGetCellAt(localPos, out var c) && _grid is not null && _grid.Spec.IsActive(c.X, c.Y)) + { + next = c; + } + + if (_hoveredCell == next) return; + _hoveredCell = next; + HoverChanged?.Invoke(next, HoveredHardpoint); + if (_grid is not null) + { + PackDataTexture(_grid); + FlushTextures(); + _standaloneDirty = true; + } + } + + private void EnsureBackingBuffers(ChassisGrid grid) + { + int w = grid.Spec.Width; + int h = grid.Spec.Height; + bool dimsChanged = w != _gridWidth || h != _gridHeight || _dataTex is null || _tempTex is null; + + _gridWidth = w; + _gridHeight = h; + _hardpointLookup = new HardpointSpec?[w, h]; + for (int i = 0; i < grid.Spec.Hardpoints.Length; i++) + { + var hp = grid.Spec.Hardpoints[i]; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int hx = hp.X + dx; + int hy = hp.Y + dy; + if (hx >= 0 && hy >= 0 && hx < w && hy < h && grid.Spec.IsActive(hx, hy)) + { + _hardpointLookup[hx, hy] = hp; + } + } + } + } + + _prevArmor = new float[w, h]; + _prevTemp = new float[w, h]; + _hitPulse = new float[w, h]; + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + _prevArmor[x, y] = grid.Armor[x, y]; + _prevTemp[x, y] = grid.Temperature[x, y]; + } + } + _lastHitSequence = grid.HitSequence; + bool hadHover = _hoveredCell.HasValue; + _hoveredCell = null; + + if (dimsChanged) + { + _dataImage = Image.CreateEmpty(Math.Max(1, w * 3), Math.Max(1, h), false, Image.Format.Rgba8); + _dataTex = ImageTexture.CreateFromImage(_dataImage); + _tempImage = Image.CreateEmpty(Math.Max(1, w), Math.Max(1, h), false, Image.Format.Rgba8); + _tempTex = ImageTexture.CreateFromImage(_tempImage); + + _gridSurface.Texture = _dataTex; + _material.SetShaderParameter("data_tex", _dataTex); + _material.SetShaderParameter("temp_tex", _tempTex); + } + + _material.SetShaderParameter("grid_size", new Vector2(w, h)); + + if (hadHover) + { + HoverChanged?.Invoke(null, null); + } + } + + private bool DetectHits(ChassisGrid grid) + { + bool changed = false; + if (grid.HitSequence != _lastHitSequence) + { + _lastHitSequence = grid.HitSequence; + if (grid.LastHitX >= 0 && grid.LastHitY >= 0 && grid.LastHitX < _gridWidth && grid.LastHitY < _gridHeight) + { + _hitPulse[grid.LastHitX, grid.LastHitY] = 1f; + } + changed = true; + } + + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + float arm = grid.Armor[x, y]; + if (arm < _prevArmor[x, y] - 0.05f) + { + _hitPulse[x, y] = 1f; + _prevArmor[x, y] = arm; + changed = true; + } + else if (MathF.Abs(arm - _prevArmor[x, y]) > 0.01f) + { + _prevArmor[x, y] = arm; + changed = true; + } + } + } + return changed; + } + + private static int ComputeMountedSignature(ChassisGrid grid) + { + var hc = new HashCode(); + hc.Add(grid.Mounted.Count); + for (int i = 0; i < grid.Mounted.Count; i++) + { + var m = grid.Mounted[i]; + hc.Add(m.HardpointId); + hc.Add(m.Spec.Id); + hc.Add(m.CurrentPerformance > 0.05f); + } + return hc.ToHashCode(); + } + + private bool HasTemperatureChanged(ChassisGrid grid) + { + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + if (MathF.Abs(grid.Temperature[x, y] - _prevTemp[x, y]) >= 0.25f) + { + return true; + } + } + } + return false; + } + + private void SnapshotTemperatures(ChassisGrid grid) + { + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + _prevTemp[x, y] = grid.Temperature[x, y]; + } + } + } + + private void PackDataTexture(ChassisGrid grid) + { + if (_dataImage is null) return; + var spec = grid.Spec; + + ModuleSpec? selectedCargo = _selectedCargoIndex >= 0 && _selectedCargoIndex < grid.Cargo.Count + ? grid.Cargo[_selectedCargoIndex] + : null; + + HardpointSpec? hoveredHp = HoveredHardpoint; + + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + if (!spec.IsActive(x, y)) + { + var zero = new Color(0f, 0f, 0f, 0f); + _dataImage.SetPixel(x * 3 + 0, y, zero); + _dataImage.SetPixel(x * 3 + 1, y, zero); + _dataImage.SetPixel(x * 3 + 2, y, zero); + continue; + } + + var hp = _hardpointLookup[x, y]; + var mounted = hp is not null ? grid.GetMountedOn(hp.Id) : null; + float maxArm = MathF.Max(1f, grid.MaxArmor[x, y]); + float arm = grid.Armor[x, y]; + float armRatio = Math.Clamp(arm / maxArm, 0f, 1f); + bool stripped = arm <= 0.01f; + bool isBorder = grid.BorderCells[x, y]; + bool isCompatible = hp is not null && selectedCargo is not null && ChassisGrid.CanFit(hp, selectedCargo); + bool isHovered = (_hoveredCell is { } hc && hc.X == x && hc.Y == y) + || (hoveredHp is not null && ReferenceEquals(hp, hoveredHp)); + + // 3x+0: Cell / item fill & armor tint + Color fill; + if (stripped) + { + fill = ColBgStripped; + } + else + { + Color armorCol = armRatio > 0.5f + ? ColBgIntact.Lerp(ColBgArmorFull, (armRatio - 0.5f) * 2f) + : ColBgDamaged.Lerp(ColBgIntact, armRatio * 2f); + + if (mounted is not null) + { + Color modTint = mounted.Spec.IsImperial ? ColGold : KindColor(hp!.Kind); + fill = armorCol.Lerp(modTint, 0.28f); + } + else + { + fill = armorCol; + } + } + fill.A = stripped ? 0.92f : 0.86f; + + // 3x+1: Border / L-bracket / pipe accent color + Color accent; + if (hp is not null) + { + if (isCompatible) + { + accent = ColGold; + } + else if (mounted is { Spec.IsImperial: true }) + { + accent = ColGold; + } + else + { + accent = KindColor(hp.Kind); + if (mounted is null) + { + accent = accent.Lerp(ColBorderHull, 0.45f); + } + } + accent.A = 0.96f; + } + else if (isBorder) + { + accent = ColBorderHull.Lerp(ColBorderRadiatorCell, 0.28f); + accent.A = 0.72f; + } + else + { + accent = ColBorderHull; + accent.A = 0.62f; + } + + // 3x+2.R: 8-bit neighbor mismatch mask (Aetheria rule) + byte mask = 0; + for (int i = 0; i < Offsets8.Length; i++) + { + int nx = x + Offsets8[i].Dx; + int ny = y + Offsets8[i].Dy; + bool match; + if (!spec.IsActive(nx, ny)) + { + match = false; + } + else if (hp is not null) + { + match = ReferenceEquals(_hardpointLookup[nx, ny], hp); + } + else + { + match = _hardpointLookup[nx, ny] is null; + } + + if (!match) + { + mask |= (byte)(1 << i); + } + } + + // 3x+2.G: flags byte + int flags = 1; // bit 0: present + if (mounted is not null) flags |= 2; // bit 1: mounted module / item + if (isHovered) flags |= 4; // bit 2: hovered + if (stripped) flags |= 8; // bit 3: stripped / Armor == 0 + if (isCompatible) flags |= 16; // bit 4: compatible cargo drop target + if (isBorder) flags |= 32; // bit 5: border radiator cell + + float pulse = Math.Clamp(_hitPulse[x, y], 0f, 1f); + var meta = new Color(mask / 255f, flags / 255f, 0f, pulse); + + _dataImage.SetPixel(x * 3 + 0, y, fill); + _dataImage.SetPixel(x * 3 + 1, y, accent); + _dataImage.SetPixel(x * 3 + 2, y, meta); + } + } + + _dataDirty = true; + } + + private void PackTempTexture(ChassisGrid grid) + { + if (_tempImage is null) return; + var spec = grid.Spec; + + // First pass: active cells + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + if (!spec.IsActive(x, y)) continue; + + float t = grid.Temperature[x, y]; + float normTemp = Math.Clamp((t - ChassisGrid.AmbientTemp) / 180f, 0f, 1f); + + float stress = normTemp * 0.25f; + var hp = _hardpointLookup[x, y]; + var mounted = hp is not null ? grid.GetMountedOn(hp.Id) : null; + if (mounted is not null) + { + float highPlateau = mounted.Spec.OptimalTemp + mounted.Spec.PlateauWidth * 0.5f; + if (t > highPlateau) + { + float overSpan = MathF.Max(1f, mounted.Spec.MaxTemp - highPlateau); + stress = 0.5f + 0.5f * Math.Clamp((t - highPlateau) / overSpan, 0f, 1f); + } + else + { + stress = 0.5f * Math.Clamp(mounted.CurrentPerformance, 0f, 1f); + } + } + + _tempImage.SetPixel(x, y, new Color(normTemp, stress, 1f, 1f)); + } + } + + // Second pass: extrapolate boundary temperature into inactive neighbor cells + // so bilinear filter_linear sampling stays smooth without cold zero bleed at hull edges. + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + if (spec.IsActive(x, y)) continue; + + float sumR = 0f; + float sumG = 0f; + int count = 0; + for (int i = 0; i < Offsets8.Length; i++) + { + int nx = x + Offsets8[i].Dx; + int ny = y + Offsets8[i].Dy; + if (spec.IsActive(nx, ny)) + { + var c = _tempImage.GetPixel(nx, ny); + sumR += c.R; + sumG += c.G; + count++; + } + } + + if (count > 0) + { + _tempImage.SetPixel(x, y, new Color(sumR / count, sumG / count, 0f, 1f)); + } + else + { + _tempImage.SetPixel(x, y, new Color(0f, 0f, 0f, 1f)); + } + } + } + + _tempDirty = true; + } + + private void FlushTextures() + { + if (_dataDirty && _dataTex is not null && _dataImage is not null) + { + _dataTex.Update(_dataImage); + _dataDirty = false; + } + if (_tempDirty && _tempTex is not null && _tempImage is not null) + { + _tempTex.Update(_tempImage); + _tempDirty = false; + } + } + + private void SyncRectUniform() + { + Vector2 size = Size; + if (size.X < 2f || size.Y < 2f) + { + size = CustomMinimumSize; + } + _material.SetShaderParameter("rect_size", size); + } + + private static Color KindColor(HardpointKind kind) => kind switch + { + HardpointKind.Weapon => ColBorderWeapon, + HardpointKind.Engine => ColBorderEngine, + HardpointKind.Radiator => ColBorderRadiator, + HardpointKind.Armor => ColBorderArmor, + HardpointKind.Utility => ColBorderUtility, + _ => ColTextLight + }; + + /// + /// Emits crisp analytic vector cell borders, hardpoint L-brackets, compatibility pulses, + /// stripped X-marks, and Monaspace Krypton hardpoint labels into . + /// Zero GC allocations on steady-state calls. + /// + public void EmitHbGpuOverlay(HbGpuCanvas canvas, Vector2 originOffset, float timeSec) + { + _overlayEmitCount++; + var grid = _grid; + if (grid is null) + { + return; + } + + ComputeCellLayout(out float cellSize, out Vector2 origin); + if (cellSize < 8f) + { + return; + } + + Vector2 basePos = originOffset + origin; + var spec = grid.Spec; + ModuleSpec? selectedCargo = _selectedCargoIndex >= 0 && _selectedCargoIndex < grid.Cargo.Count + ? grid.Cargo[_selectedCargoIndex] + : null; + HardpointSpec? hoveredHp = HoveredHardpoint; + Color flashCol = new(1.0f, 0.76f, 0.38f, 1.0f); + Color redAccent = new(0.92f, 0.26f, 0.18f, 1.0f); + + // 1. Hull cell outlines, internal subdivisions, and stripped-cell X marks + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + if (!spec.IsActive(x, y)) + { + continue; + } + + float cx = basePos.X + x * cellSize; + float cy = basePos.Y + y * cellSize; + bool stripped = grid.Armor[x, y] <= 0.01f; + var hp = _hardpointLookup[x, y]; + + if (hp is null) + { + Color edgeCol = grid.BorderCells[x, y] + ? ColBorderHull.Lerp(ColBorderRadiatorCell, 0.30f) + : ColBorderHull; + float pulse = Math.Clamp(_hitPulse[x, y], 0f, 1f); + bool isCellHovered = _hoveredCell is { } hc && hc.X == x && hc.Y == y; + if (stripped) edgeCol = edgeCol.Lerp(redAccent, 0.65f); + if (isCellHovered) edgeCol = edgeCol.Lerp(Colors.White, 0.35f); + if (pulse > 0.01f) edgeCol = edgeCol.Lerp(flashCol, pulse * 0.90f); + + float inset = 1.5f; + float x0 = cx + inset; + float y0 = cy + inset; + float x1 = cx + cellSize - inset; + float y1 = cy + cellSize - inset; + + // Outer hull perimeter edges get crisp medium lines; internal matched hull edges get faint hairlines + bool nMatch = spec.IsActive(x, y - 1) && _hardpointLookup[x, y - 1] is null; + bool sMatch = spec.IsActive(x, y + 1) && _hardpointLookup[x, y + 1] is null; + bool wMatch = spec.IsActive(x - 1, y) && _hardpointLookup[x - 1, y] is null; + bool eMatch = spec.IsActive(x + 1, y) && _hardpointLookup[x + 1, y] is null; + + Color outerCol = new(edgeCol.R, edgeCol.G, edgeCol.B, isCellHovered ? 0.85f : 0.42f); + Color innerCol = new(edgeCol.R, edgeCol.G, edgeCol.B, 0.14f); + + if (!nMatch) canvas.DrawLineSegment(x0, y0, x1, y0, 1.2f, outerCol); + if (!sMatch) canvas.DrawLineSegment(x0, y1, x1, y1, 1.2f, outerCol); + else canvas.DrawLineSegment(cx + 2f, cy + cellSize, cx + cellSize - 2f, cy + cellSize, 0.9f, innerCol); + if (!wMatch) canvas.DrawLineSegment(x0, y0, x0, y1, 1.2f, outerCol); + if (!eMatch) canvas.DrawLineSegment(x1, y0, x1, y1, 1.2f, outerCol); + else canvas.DrawLineSegment(cx + cellSize, cy + 2f, cx + cellSize, cy + cellSize - 2f, 0.9f, innerCol); + } + + if (stripped) + { + float pad = MathF.Max(4.5f, cellSize * 0.18f); + Color xCol = new(0.95f, 0.28f, 0.20f, 0.78f); + canvas.DrawLineSegment(cx + pad, cy + pad, cx + cellSize - pad, cy + cellSize - pad, 1.5f, xCol); + canvas.DrawLineSegment(cx + cellSize - pad, cy + pad, cx + pad, cy + cellSize - pad, 1.5f, xCol); + } + } + } + + // 2. Contiguous hardpoint borders, L-brackets, and Krypton tags + float fontSize = cellSize >= 38f ? 10.5f : 9.2f; + float compatPulse = 0.72f + 0.28f * MathF.Sin(timeSec * 6.5f); + + for (int i = 0; i < spec.Hardpoints.Length; i++) + { + var hp = spec.Hardpoints[i]; + var mounted = grid.GetMountedOn(hp.Id); + float hx = basePos.X + hp.X * cellSize; + float hy = basePos.Y + hp.Y * cellSize; + float hw = hp.Width * cellSize; + float hh = hp.Height * cellSize; + + bool strippedHp = !grid.IsHardpointOperational(hp); + bool isCompatible = selectedCargo is not null && ChassisGrid.CanFit(hp, selectedCargo); + bool isHovered = hoveredHp is not null && ReferenceEquals(hp, hoveredHp); + + float maxPulse = 0f; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int cx = hp.X + dx; + int cy = hp.Y + dy; + if (cx >= 0 && cy >= 0 && cx < _gridWidth && cy < _gridHeight) + { + maxPulse = MathF.Max(maxPulse, _hitPulse[cx, cy]); + } + } + } + + Color accent; + if (isCompatible) + { + accent = ColGold; + } + else if (mounted is { Spec.IsImperial: true }) + { + accent = ColGold; + } + else + { + accent = KindColor(hp.Kind); + if (mounted is null) + { + accent = accent.Lerp(ColBorderHull, 0.45f); + } + } + + if (strippedHp) accent = accent.Lerp(redAccent, 0.70f); + if (isCompatible) accent = accent.Lerp(new Color(0.96f, 0.82f, 0.30f, 1f), compatPulse); + if (isHovered) accent = accent.Lerp(Colors.White, 0.35f); + if (maxPulse > 0.01f) accent = accent.Lerp(flashCol, maxPulse * 0.90f); + + const float inset = 1.8f; + float rx = hx + inset; + float ry = hy + inset; + float rw = MathF.Max(2f, hw - inset * 2f); + float rh = MathF.Max(2f, hh - inset * 2f); + + float ruleAlpha = isCompatible ? 0.68f : (isHovered ? 0.60f : 0.34f); + canvas.DrawRectOutline(rx, ry, rw, rh, isCompatible ? 1.5f : 1.0f, new Color(accent.R, accent.G, accent.B, ruleAlpha)); + + float arm = Math.Clamp(MathF.Min(rw, rh) * 0.28f, 4.5f, 12f); + float bracketThick = (isCompatible || isHovered) ? 2.4f : 1.8f; + Color bracketCol = new(accent.R, accent.G, accent.B, 0.96f); + canvas.DrawTargetBracketCorner(rx, ry, arm, bracketThick, 0, bracketCol); + canvas.DrawTargetBracketCorner(rx + rw, ry, arm, bracketThick, 1, bracketCol); + canvas.DrawTargetBracketCorner(rx + rw, ry + rh, arm, bracketThick, 2, bracketCol); + canvas.DrawTargetBracketCorner(rx, ry + rh, arm, bracketThick, 3, bracketCol); + + if (cellSize >= 14f) + { + ReadOnlySpan tagSpan = FormatHardpointTag(hp, mounted, _tagScratch); + if (!_lastEmittedTags.TryGetValue(hp.Id, out string? existingTag) || !tagSpan.SequenceEqual(existingTag)) + { + _lastEmittedTags[hp.Id] = new string(tagSpan); + } + + Color col = mounted is { Spec.IsImperial: true } ? ColGold : ColTextLight; + col.A = 0.95f; + HbGpuCommandWriter.PackClipRect(hx + 2f, hy + 2f, hw - 4f, hh - 4f, out uint clipMin, out uint clipMax); + + float tx = hx + 5f; + float ty = hy + fontSize + 4.5f; + canvas.DrawText(tagSpan, tx + 1f, ty + 1f, fontSize, new Color(0.04f, 0.05f, 0.04f, 0.90f), + wght: 550f, stemDarken: true, clipMinPacked: clipMin, clipMaxPacked: clipMax); + canvas.DrawText(tagSpan, tx, ty, fontSize, col, + wght: 550f, stemDarken: true, clipMinPacked: clipMin, clipMaxPacked: clipMax); + } + } + } + + private static ReadOnlySpan FormatHardpointTag(HardpointSpec hp, MountedModule? mounted, char[] buf) + { + if (mounted is null) + { + return hp.Kind switch + { + HardpointKind.Weapon => "WPN", + HardpointKind.Engine => "ENG", + HardpointKind.Radiator => "RAD", + HardpointKind.Armor => "ARM", + HardpointKind.Utility => "UTL", + _ => "MOD" + }; + } + + buf[0] = mounted.Spec.Kind switch + { + HardpointKind.Weapon => 'W', + HardpointKind.Engine => 'E', + HardpointKind.Radiator => 'R', + HardpointKind.Armor => 'A', + HardpointKind.Utility => 'U', + _ => 'M' + }; + buf[1] = ':'; + int pos = 2; + if (mounted.CurrentTemp.TryFormat(buf.AsSpan(pos), out int written, "F0", System.Globalization.CultureInfo.InvariantCulture)) + { + pos += written; + } + buf[pos++] = '°'; + return buf.AsSpan(0, pos); + } +} diff --git a/client/LobbyScreen.cs b/client/LobbyScreen.cs new file mode 100644 index 0000000..e74bfc1 --- /dev/null +++ b/client/LobbyScreen.cs @@ -0,0 +1,562 @@ +using System; +using System.Globalization; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Authoritative pre-match orbital lobby overlay (). +/// Displays the 12 contender slots, ready states, host-only map/seed controls, +/// live 5-second orbital insertion countdown banner, and launch/leave actions. +/// +public sealed partial class LobbyScreen : CanvasLayer +{ + private sealed class SlotRowView + { + public required PanelContainer Frame; + public required Label IndexLabel; + public required Label SquadBadge; + public required Label NameLabel; + public required Label RoleBadge; + public required Label ReadyBadge; + } + + private static readonly Color[] SquadColors = + { + Color.FromHtml("#52e3a8"), + ImperialChrome.CyanCol, + ImperialChrome.GoldCol, + ImperialChrome.OrangeCol, + ImperialChrome.OliveCol, + Color.FromHtml("#d67cff") + }; + + private readonly SlotRowView[] _slotViews = new SlotRowView[MatchState.ContenderCount]; + + private Control _root = null!; + private ImperialChromePanel _panel = null!; + private Label _modeBadge = null!; + private PanelContainer _countdownBanner = null!; + private Label _countdownLabel = null!; + private Label _rosterSummaryLabel = null!; + + private OptionButton _mapOption = null!; + private LineEdit _seedEdit = null!; + private OptionButton _squadOption = null!; + private Button _applyConfigBtn = null!; + private Button _randomSeedBtn = null!; + private Label _authorityNoteLabel = null!; + private Label _netStatusLabel = null!; + + private Button _switchSquadBtn = null!; + private Button _readyBtn = null!; + private Button _launchBtn = null!; + private Button _leaveBtn = null!; + + private IClientArenaSession? _activeSession; + private int? _lastSyncedSeed; + private byte? _lastSyncedMap; + private byte? _lastSyncedSquadSize; + + public LobbyScreen() + { + Layer = 20; + } + + public event Action? LeaveRequested; + + public bool IsTextInputFocused => Visible && _seedEdit is not null && _seedEdit.HasFocus(); + + public override void _Ready() + { + BuildUi(); + SetLobbyVisible(false); + } + + public void SetLobbyVisible(bool visible) + { + Visible = visible; + if (_root is not null) + { + _root.Visible = visible; + } + if (!visible) + { + _activeSession = null; + _lastSyncedSeed = null; + _lastSyncedMap = null; + _lastSyncedSquadSize = null; + _seedEdit?.ReleaseFocus(); + } + } + + public void Sync(IClientArenaSession session) + { + _activeSession = session; + var net = session.ConnectionStatus; + var lobby = session.LobbyState; + + _modeBadge.Text = net.Mode switch + { + NetworkMode.ListenHost => net.StateLabel, + NetworkMode.RemoteClient => net.Connected + ? $"CONNECTED • PING {net.PingMs} ms" + : (net.LastError is not null ? $"DISCONNECTED: {net.LastError}" : "CONNECTING TO LOBBY..."), + _ => "SOLO" + }; + _modeBadge.AddThemeColorOverride("font_color", + net.LastError is not null ? ImperialChrome.RedCol : (net.Connected ? ImperialChrome.CyanCol : ImperialChrome.OrangeCol)); + + if (lobby is null) + { + _countdownLabel.Text = net.LastError is not null + ? $"CONNECTION LOST — {net.LastError}" + : "ESTABLISHING RUDP UPLINK TO SERVER LOBBY..."; + _countdownLabel.AddThemeColorOverride("font_color", net.LastError is not null ? ImperialChrome.RedCol : ImperialChrome.OrangeCol); + _rosterSummaryLabel.Text = "Awaiting authoritative lobby roster..."; + _readyBtn.Disabled = true; + _switchSquadBtn.Disabled = true; + _launchBtn.Visible = false; + _mapOption.Disabled = true; + _seedEdit.Editable = false; + _squadOption.Disabled = true; + _applyConfigBtn.Disabled = true; + _randomSeedBtn.Disabled = true; + _authorityNoteLabel.Text = "Waiting for server snapshot..."; + _netStatusLabel.Text = net.StateLabel; + return; + } + + int localId = session.LocalContenderId; + bool isHost = lobby.HostSlotId.HasValue && lobby.HostSlotId.Value == localId; + bool localReady = false; + byte localSquadId = 0; + int humanCount = 0; + int readyCount = 0; + int aiCount = 0; + byte squadSize = (byte)Math.Clamp((int)lobby.SquadSize, 1, 4); + + for (int i = 0; i < _slotViews.Length; i++) + { + var view = _slotViews[i]; + if (i < lobby.Slots.Count) + { + var slot = lobby.Slots[i]; + bool isLocalSlot = slot.SlotId == localId; + bool isHostSlot = lobby.HostSlotId.HasValue && slot.SlotId == lobby.HostSlotId.Value; + if (isLocalSlot) localSquadId = slot.SquadId; + + view.IndexLabel.Text = $"SLOT {slot.SlotId + 1:00}"; + if (squadSize > 1) + { + view.SquadBadge.Text = $"[SQ {slot.SquadId + 1}]"; + view.SquadBadge.AddThemeColorOverride("font_color", SquadColors[slot.SquadId % SquadColors.Length]); + } + else + { + view.SquadBadge.Text = "[FFA]"; + view.SquadBadge.AddThemeColorOverride("font_color", ImperialChrome.TextMuted); + } + if (slot.IsHuman) + { + humanCount++; + if (slot.IsReady) readyCount++; + if (isLocalSlot) localReady = slot.IsReady; + + view.NameLabel.Text = string.IsNullOrWhiteSpace(slot.Callsign) ? $"Pilot {slot.SlotId + 1}" : slot.Callsign; + view.NameLabel.AddThemeColorOverride("font_color", isLocalSlot ? ImperialChrome.TextLight : Colors.White); + + view.RoleBadge.Text = isHostSlot + ? (isLocalSlot ? "[HOST / YOU]" : "[HOST]") + : (isLocalSlot ? "[YOU]" : "[PILOT]"); + view.RoleBadge.AddThemeColorOverride("font_color", isHostSlot ? ImperialChrome.GoldCol : ImperialChrome.CyanCol); + + view.ReadyBadge.Text = slot.IsReady ? "[READY]" : "[WAIT]"; + view.ReadyBadge.AddThemeColorOverride("font_color", slot.IsReady ? ImperialChrome.OliveCol : ImperialChrome.OrangeCol); + + ApplyRowFrame(view.Frame, isLocalSlot ? ImperialChrome.CyanCol : ImperialChrome.BorderCol, highlighted: isLocalSlot); + } + else + { + aiCount++; + view.NameLabel.Text = "AI BACKFILL"; + view.NameLabel.AddThemeColorOverride("font_color", ImperialChrome.TextMuted); + view.RoleBadge.Text = "[BOT]"; + view.RoleBadge.AddThemeColorOverride("font_color", ImperialChrome.TextMuted); + view.ReadyBadge.Text = "[ARMED]"; + view.ReadyBadge.AddThemeColorOverride("font_color", ImperialChrome.TextMuted); + ApplyRowFrame(view.Frame, new Color(ImperialChrome.BorderCol.R, ImperialChrome.BorderCol.G, ImperialChrome.BorderCol.B, 0.45f), highlighted: false); + } + } + } + + _rosterSummaryLabel.Text = $"HUMANS: {humanCount}/{MatchState.ContenderCount} • READY: {readyCount}/{Math.Max(1, humanCount)} • AI BACKFILL: {aiCount}"; + + // Countdown banner + if (lobby.CountdownSeconds is float cd) + { + int ceilSec = Math.Max(1, (int)MathF.Ceiling(cd)); + _countdownLabel.Text = $"ORBITAL INSERTION IN {ceilSec}..."; + _countdownLabel.AddThemeColorOverride("font_color", ceilSec <= 2 ? ImperialChrome.OrangeCol : ImperialChrome.GoldCol); + _panel.SetAccentColor(ImperialChrome.GoldCol); + } + else + { + string readyHint = humanCount < lobby.MinHumansToAutoStart + ? $"NEED {lobby.MinHumansToAutoStart} HUMANS FOR AUTO-LAUNCH" + : "ALL PILOTS READY UP TO BEGIN DROP"; + _countdownLabel.Text = isHost + ? $"PRE-MATCH STANDBY • {readyHint} (OR LAUNCH DROP)" + : $"PRE-MATCH STANDBY • {readyHint}"; + _countdownLabel.AddThemeColorOverride("font_color", ImperialChrome.CyanCol); + _panel.SetAccentColor(ImperialChrome.CyanCol); + } + + // Sync Map, Seed & SquadSize without clobbering active typing by host + if (_lastSyncedMap != lobby.SelectedMap) + { + _lastSyncedMap = lobby.SelectedMap; + _mapOption.Select((ArenaMapKind)lobby.SelectedMap == ArenaMapKind.Desert ? 1 : 0); + } + if (_lastSyncedSeed != lobby.SelectedSeed && (!_seedEdit.HasFocus() || !isHost)) + { + _lastSyncedSeed = lobby.SelectedSeed; + _seedEdit.Text = lobby.SelectedSeed.ToString(CultureInfo.InvariantCulture); + } + if (_lastSyncedSquadSize != squadSize) + { + _lastSyncedSquadSize = squadSize; + _squadOption.Select(squadSize - 1); + } + + // Strict host authority gating + _mapOption.Disabled = !isHost; + _seedEdit.Editable = isHost; + _squadOption.Disabled = !isHost; + _applyConfigBtn.Disabled = !isHost; + _randomSeedBtn.Disabled = !isHost; + _authorityNoteLabel.Text = isHost + ? "HOST AUTHORITY: You control drop zone, seed, squad mode, and forced launch." + : "READ-ONLY: Only the match host can edit map, seed, squad mode, or force launch."; + _authorityNoteLabel.AddThemeColorOverride("font_color", isHost ? ImperialChrome.GoldCol : ImperialChrome.TextMuted); + + _switchSquadBtn.Disabled = squadSize <= 1; + _switchSquadBtn.Text = squadSize > 1 + ? $"SWITCH SQUAD [SQ {localSquadId + 1}]" + : "SWITCH SQUAD (FFA)"; + + _readyBtn.Disabled = false; + _readyBtn.Text = localReady ? "READY [ON] — CLICK TO UNREADY" : "READY UP"; + ImperialChrome.StyleButton(_readyBtn, localReady ? ImperialChrome.OliveCol : ImperialChrome.CyanCol, 14); + + _launchBtn.Visible = isHost; + _launchBtn.Disabled = !isHost; + _launchBtn.Text = lobby.ForceLaunched ? "LAUNCHING NOW..." : "LAUNCH DROP"; + + _netStatusLabel.Text = $"{net.StateLabel} • MAP: {((ArenaMapKind)lobby.SelectedMap == ArenaMapKind.Sion ? "SION 3KM" : "DESERT RING")} • SEED {lobby.SelectedSeed}"; + } + + private void BuildUi() + { + _root = new Control + { + Name = "LobbyScreenRoot", + MouseFilter = Control.MouseFilterEnum.Stop + }; + _root.SetAnchorsPreset(Control.LayoutPreset.FullRect); + AddChild(_root); + + var scrim = new ColorRect + { + Color = new Color(0.03f, 0.04f, 0.03f, 0.36f), + MouseFilter = Control.MouseFilterEnum.Stop + }; + scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect); + _root.AddChild(scrim); + + _panel = ImperialChrome.CreatePanel(ImperialChrome.CyanCol, cornerLen: 18f, borderPx: 2f, bgAlpha: 0.92f, padH: 18, padV: 16); + _panel.Name = "LobbyScreenPanel"; + _panel.AnchorLeft = 0.5f; + _panel.AnchorRight = 0.5f; + _panel.AnchorTop = 0.5f; + _panel.AnchorBottom = 0.5f; + _panel.OffsetLeft = -515f; + _panel.OffsetRight = 515f; + _panel.OffsetTop = -330f; + _panel.OffsetBottom = 330f; + _root.AddChild(_panel); + + var vbox = new VBoxContainer(); + vbox.AddThemeConstantOverride("separation", 10); + _panel.AddChild(vbox); + + // Header row + var headerRow = new HBoxContainer(); + headerRow.AddThemeConstantOverride("separation", 12); + vbox.AddChild(headerRow); + + var titleLbl = ImperialChrome.CreateLabel("PRE-MATCH ORBITAL LOBBY", 20, ImperialChrome.TextLight); + titleLbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; + headerRow.AddChild(titleLbl); + + _modeBadge = ImperialChrome.CreateLabel("HOST :3076", 12, ImperialChrome.CyanCol, HorizontalAlignment.Right); + headerRow.AddChild(_modeBadge); + + // Countdown Banner + _countdownBanner = new PanelContainer(); + var cdStyle = new StyleBoxFlat + { + BgColor = ImperialChrome.BgInner, + BorderColor = ImperialChrome.GoldCol, + ContentMarginLeft = 12, + ContentMarginRight = 12, + ContentMarginTop = 8, + ContentMarginBottom = 8 + }; + cdStyle.SetBorderWidthAll(1); + _countdownBanner.AddThemeStyleboxOverride("panel", cdStyle); + vbox.AddChild(_countdownBanner); + + _countdownLabel = ImperialChrome.CreateLabel("PRE-MATCH STANDBY", 15, ImperialChrome.CyanCol, HorizontalAlignment.Center); + _countdownBanner.AddChild(_countdownLabel); + + // Body: Two columns (Left Roster | Right Config & Actions) + var bodyRow = new HBoxContainer + { + SizeFlagsVertical = Control.SizeFlags.ExpandFill + }; + bodyRow.AddThemeConstantOverride("separation", 16); + vbox.AddChild(bodyRow); + + // Left Column: Roster (Slot 01..12) + var leftCol = new VBoxContainer + { + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, + SizeFlagsStretchRatio = 1.35f + }; + leftCol.AddThemeConstantOverride("separation", 4); + bodyRow.AddChild(leftCol); + + leftCol.AddChild(ImperialChrome.CreateLabel("CONTENDER ROSTER (SLOTS 01 – 12)", 12, ImperialChrome.OrangeCol)); + + for (int i = 0; i < _slotViews.Length; i++) + { + var frame = new PanelContainer(); + ApplyRowFrame(frame, ImperialChrome.BorderCol, highlighted: false); + + var row = new HBoxContainer(); + row.AddThemeConstantOverride("separation", 8); + frame.AddChild(row); + + var idxLbl = ImperialChrome.CreateLabel($"SLOT {i + 1:00}", 11, ImperialChrome.TextMuted); + idxLbl.CustomMinimumSize = new Vector2(60f, 0f); + row.AddChild(idxLbl); + + var sqLbl = ImperialChrome.CreateLabel("[SQ 1]", 11, SquadColors[0]); + sqLbl.CustomMinimumSize = new Vector2(54f, 0f); + row.AddChild(sqLbl); + + var nameLbl = ImperialChrome.CreateLabel("AI BACKFILL", 12, ImperialChrome.TextMuted); + nameLbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; + nameLbl.ClipText = true; + row.AddChild(nameLbl); + + var roleLbl = ImperialChrome.CreateLabel("[BOT]", 11, ImperialChrome.TextMuted); + roleLbl.CustomMinimumSize = new Vector2(92f, 0f); + roleLbl.HorizontalAlignment = HorizontalAlignment.Right; + row.AddChild(roleLbl); + + var readyLbl = ImperialChrome.CreateLabel("[ARMED]", 11, ImperialChrome.TextMuted); + readyLbl.CustomMinimumSize = new Vector2(72f, 0f); + readyLbl.HorizontalAlignment = HorizontalAlignment.Right; + row.AddChild(readyLbl); + + leftCol.AddChild(frame); + _slotViews[i] = new SlotRowView + { + Frame = frame, + IndexLabel = idxLbl, + SquadBadge = sqLbl, + NameLabel = nameLbl, + RoleBadge = roleLbl, + ReadyBadge = readyLbl + }; + } + + _rosterSummaryLabel = ImperialChrome.CreateLabel("HUMANS: 1/12 • READY: 0/1 • AI BACKFILL: 11", 11, ImperialChrome.OliveCol); + leftCol.AddChild(_rosterSummaryLabel); + + // Right Column: Drop Zone Config & Launch Actions + var rightCol = new VBoxContainer + { + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, + SizeFlagsStretchRatio = 1.0f + }; + rightCol.AddThemeConstantOverride("separation", 10); + bodyRow.AddChild(rightCol); + + rightCol.AddChild(ImperialChrome.CreateLabel("DROP ZONE CONFIGURATION", 12, ImperialChrome.GoldCol)); + rightCol.AddChild(ImperialChrome.MakeRule()); + + var mapRow = new HBoxContainer(); + mapRow.AddThemeConstantOverride("separation", 8); + rightCol.AddChild(mapRow); + var mapLbl = ImperialChrome.CreateLabel("MAP", 12, ImperialChrome.TextMuted); + mapLbl.CustomMinimumSize = new Vector2(68f, 0f); + mapRow.AddChild(mapLbl); + _mapOption = new OptionButton { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; + _mapOption.AddItem("SION (3KM ALPINE)", 0); + _mapOption.AddItem("DESERT RING", 1); + ImperialChrome.StyleOptionButton(_mapOption, ImperialChrome.OliveCol, 13); + _mapOption.ItemSelected += _ => ApplyConfigFromUi(); + mapRow.AddChild(_mapOption); + + var seedRow = new HBoxContainer(); + seedRow.AddThemeConstantOverride("separation", 8); + rightCol.AddChild(seedRow); + var seedLbl = ImperialChrome.CreateLabel("SEED", 12, ImperialChrome.TextMuted); + seedLbl.CustomMinimumSize = new Vector2(68f, 0f); + seedRow.AddChild(seedLbl); + _seedEdit = new LineEdit + { + Text = "42", + MaxLength = 12, + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + ImperialChrome.StyleLineEdit(_seedEdit, ImperialChrome.GoldCol, 13); + _seedEdit.TextSubmitted += _ => ApplyConfigFromUi(); + seedRow.AddChild(_seedEdit); + + _randomSeedBtn = ImperialChrome.CreateButton("RND", ImperialChrome.BorderCol, 12, 30f); + _randomSeedBtn.CustomMinimumSize = new Vector2(54f, 30f); + _randomSeedBtn.Pressed += () => + { + int nextSeed = Random.Shared.Next(1, 999999); + _seedEdit.Text = nextSeed.ToString(CultureInfo.InvariantCulture); + ApplyConfigFromUi(); + }; + seedRow.AddChild(_randomSeedBtn); + + var squadRow = new HBoxContainer(); + squadRow.AddThemeConstantOverride("separation", 8); + rightCol.AddChild(squadRow); + var squadLbl = ImperialChrome.CreateLabel("SQUAD", 12, ImperialChrome.TextMuted); + squadLbl.CustomMinimumSize = new Vector2(68f, 0f); + squadRow.AddChild(squadLbl); + _squadOption = new OptionButton { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; + _squadOption.AddItem("FFA (1)", 0); + _squadOption.AddItem("DUO (2)", 1); + _squadOption.AddItem("TRIO (3)", 2); + _squadOption.AddItem("QUAD (4)", 3); + _squadOption.Select(2); + ImperialChrome.StyleOptionButton(_squadOption, ImperialChrome.CyanCol, 13); + _squadOption.ItemSelected += _ => ApplyConfigFromUi(); + squadRow.AddChild(_squadOption); + + _applyConfigBtn = ImperialChrome.CreateButton("APPLY MAP, SEED & SQUAD", ImperialChrome.GoldCol, 12, 32f); + _applyConfigBtn.Pressed += ApplyConfigFromUi; + rightCol.AddChild(_applyConfigBtn); + + _authorityNoteLabel = ImperialChrome.CreateLabel("HOST AUTHORITY", 11, ImperialChrome.TextMuted); + _authorityNoteLabel.AutowrapMode = TextServer.AutowrapMode.Word; + rightCol.AddChild(_authorityNoteLabel); + + rightCol.AddChild(ImperialChrome.MakeRule()); + + var spacer = new Control { SizeFlagsVertical = Control.SizeFlags.ExpandFill }; + rightCol.AddChild(spacer); + + _switchSquadBtn = ImperialChrome.CreateButton("SWITCH SQUAD [SQ 1]", SquadColors[0], 13, 36f); + _switchSquadBtn.Pressed += OnSwitchSquadPressed; + rightCol.AddChild(_switchSquadBtn); + + _readyBtn = ImperialChrome.CreateButton("READY UP", ImperialChrome.CyanCol, 14, 42f); + _readyBtn.Pressed += OnReadyPressed; + rightCol.AddChild(_readyBtn); + + _launchBtn = ImperialChrome.CreateButton("LAUNCH DROP", ImperialChrome.OliveCol, 14, 42f); + _launchBtn.Pressed += OnLaunchPressed; + rightCol.AddChild(_launchBtn); + + _leaveBtn = ImperialChrome.CreateButton("LEAVE TO MENU", ImperialChrome.RedCol, 13, 36f); + _leaveBtn.Pressed += () => LeaveRequested?.Invoke(); + rightCol.AddChild(_leaveBtn); + + _netStatusLabel = ImperialChrome.CreateLabel(string.Empty, 11, ImperialChrome.TextMuted); + _netStatusLabel.AutowrapMode = TextServer.AutowrapMode.Word; + vbox.AddChild(_netStatusLabel); + } + + private void OnReadyPressed() + { + if (_activeSession is null || _activeSession.LobbyState is not { } lobby) return; + int localId = _activeSession.LocalContenderId; + bool currentReady = false; + for (int i = 0; i < lobby.Slots.Count; i++) + { + if (lobby.Slots[i].SlotId == localId) + { + currentReady = lobby.Slots[i].IsReady; + break; + } + } + _activeSession.SetLobbyReady(!currentReady); + } + + private void OnSwitchSquadPressed() + { + if (_activeSession is null || _activeSession.LobbyState is not { } lobby) return; + byte squadSize = (byte)Math.Clamp((int)lobby.SquadSize, 1, 4); + if (squadSize <= 1) return; + + int maxSquads = Math.Max(1, (MatchState.ContenderCount + squadSize - 1) / squadSize); + int localId = _activeSession.LocalContenderId; + byte curSq = 0; + for (int i = 0; i < lobby.Slots.Count; i++) + { + if (lobby.Slots[i].SlotId == localId) + { + curSq = lobby.Slots[i].SquadId; + break; + } + } + byte nextSq = (byte)((curSq + 1) % maxSquads); + _activeSession.RequestLobbySquad(nextSq); + } + + private void OnLaunchPressed() + { + _activeSession?.RequestLobbyStart(); + } + + private void ApplyConfigFromUi() + { + if (_activeSession is null || _activeSession.LobbyState is not { } lobby) return; + if (!lobby.HostSlotId.HasValue || lobby.HostSlotId.Value != _activeSession.LocalContenderId) return; + + var mapKind = _mapOption.Selected == 1 ? ArenaMapKind.Desert : ArenaMapKind.Sion; + int seed = int.TryParse(_seedEdit.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed) + ? parsed + : lobby.SelectedSeed; + byte squadSize = (byte)Math.Clamp(_squadOption.Selected + 1, 1, 4); + + _seedEdit.ReleaseFocus(); + _activeSession.RequestLobbyConfig(seed, mapKind, squadSize); + } + + private static void ApplyRowFrame(PanelContainer frame, Color borderColor, bool highlighted) + { + var style = new StyleBoxFlat + { + BgColor = highlighted ? ImperialChrome.BgHover : ImperialChrome.BgInner, + BorderColor = borderColor, + ContentMarginLeft = 8, + ContentMarginRight = 8, + ContentMarginTop = 4, + ContentMarginBottom = 4 + }; + style.SetBorderWidthAll(1); + frame.AddThemeStyleboxOverride("panel", style); + } +} diff --git a/client/Main.cs b/client/Main.cs new file mode 100644 index 0000000..50be061 --- /dev/null +++ b/client/Main.cs @@ -0,0 +1,2333 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Net; +using System.Net.Sockets; +using Godot; +using RustToDust.Core; +using RustToDust.Net; +using RustToDust.Ymir; + +namespace RustToDust.Client; + +public enum ClientScreenMode +{ + MainMenu, + ServerBrowser, + Lobby, + InMatch, + PauseOverlay, + Settings +} + +/// +/// Root Godot node for Rust to Dust. +/// Godot physics is Dummy; drives Solo (), +/// Listen-Host (), or Remote () play. +/// +public partial class Main : Node3D +{ + private const ulong ContenderStableIdBase = 1000UL; + private const int DefaultNetPort = 3076; + + private TerrainRenderer _terrain = null!; + private SionMapRenderer _sionMap = null!; + private ArenaRenderer _arena = null!; + private ArenaAudioSystem _audio = null!; + private Camera3D _camera = null!; + private Hud _hud = null!; + private AtmosphereSystem _atmosphere = null!; + private MainMenu _mainMenu = null!; + private SettingsOverlay _settingsOverlay = null!; + private ServerBrowser _serverBrowser = null!; + private LobbyScreen _lobbyScreen = null!; + private GraphicsSettings _graphicsSettings = new(); + private IClientArenaSession? _session; + private MatchState? _boundViewState; + private bool _wasNetConnected; + private ClientScreenMode _screenMode = ClientScreenMode.MainMenu; + private ClientScreenMode _settingsReturnMode = ClientScreenMode.MainMenu; + private bool _hasWindowOverride; + private DirectoryReporter? _directoryReporter; + private string _directoryUrl = ServerBrowser.DefaultDirectoryUrl; + private string _publicHostOverride = "auto"; + private string _serverName = "Rust to Dust"; + private DirectoryHeartbeatSnapshot _cachedDirectorySnapshot; + private readonly object _dirSnapGate = new(); + private int _lastDirHumans = -1; + private MatchPhase _lastDirPhase = (MatchPhase)(-1); + private ArenaMapKind _lastDirMap = (ArenaMapKind)(-1); + private int _lastDirSeed; + private SionMapData? _menuSionData; + private TerrainField? _menuSionTerrain; + private int _menuPreviewTargetFrames; + private int _menuPreviewFrames; + private string? _menuPreviewOut; + private readonly WalkerFootstepTracker _footsteps = new(); + private readonly CameraJuiceState _camJuice = new(); + private readonly List _frameEvents = new(128); + private readonly List _frameFootsteps = new(32); + private ArenaMapKind _mapKind = ArenaMapKind.Sion; + private byte _squadSize = 3; + private string _callsign = "Pilot"; + private string _lastEndpoint = $"127.0.0.1:{DefaultNetPort}"; + + private PlayerInput? _scriptedInput; + private float _cameraYaw; + private float _cameraPitch = Mathf.DegToRad(5f); + private float _cameraZoom = 1.0f; + private float _smoothedShoulderY; + private string? _lastCamChassisId; + private float _orbitalPodCamBlend; + private ContenderLifecycle _prevLocalLifecycle = ContenderLifecycle.Active; + private MeshInstance3D _dropReticleMesh = null!; + private Vector3 _baseCamPos; + private Vector3 _baseLookDir = Vector3.Forward; + private bool _hasBaseCamPose; + private float _elapsedSeconds; + private bool _interactQueued; + private int _seed = 42; + + // Temporary Step 1/Step 3 perf probe (enabled only when RTD_PERF_FRAMES is set) + private int _perfTargetFrames; + private int _perfFrameCount; + private int _perfWaitConnectFrames; + private int _perfPhysicsTicks; + private long _perfLastFrameTick; + private int _perfLastDirtyRebakes; + private readonly List _perfFrameMs = new(); + private readonly List _perfPhysicsStepMs = new(); + private readonly List _perfTerrainSyncMs = new(); + private readonly List _perfArenaSyncMs = new(); + private readonly List _perfHudMs = new(); + private readonly List _perfDirtyRebakeDelta = new(); + private readonly List _perfDrawCalls = new(); + private readonly List _perfPrimitives = new(); + private readonly List _perfObjects = new(); + private readonly List _perfNodeCount = new(); + private readonly List _perfTimeProcess = new(); + private readonly List _perfTimePhysicsProcess = new(); + private readonly List _perfViewportGpuMs = new(); + private double _perfPendingStepMs; + private double _perfPendingTerrainMs; + private double _perfPendingArenaMs; + private double _perfCamMsSum; + + public IClientArenaSession Session => _session ?? throw new InvalidOperationException($"No active IClientArenaSession ({Failure ?? "uninitialized"})"); + public bool HasActiveSession => _session is not null; + public ClientScreenMode ScreenMode => _screenMode; + public TerrainRenderer Terrain => _terrain; + public SionMapRenderer SionMap => _sionMap; + public ArenaRenderer Arena => _arena; + public ArenaAudioSystem Audio => _audio; + public WalkerFootstepTracker Footsteps => _footsteps; + public CameraJuiceState CameraJuice => _camJuice; + public Camera3D Camera => _camera; + public Hud Hud => _hud; + public AtmosphereSystem Atmosphere => _atmosphere; + public MainMenu MainMenuOverlay => _mainMenu; + public SettingsOverlay SettingsOverlay => _settingsOverlay; + public GraphicsSettings GraphicsSettings => _graphicsSettings; + public ServerBrowser ServerBrowserOverlay => _serverBrowser; + public LobbyScreen LobbyOverlay => _lobbyScreen; + public ArenaMapKind MapKind => _mapKind; + public ArenaMapKind? InitialMapKindOverride { get; set; } + public bool InitialSkipDropOverride { get; set; } + public bool InitialSkipMenuOverride { get; set; } + public string? Failure { get; private set; } + public int Seed => _seed; + public float CameraYaw => _cameraYaw; + internal Vector3 BaseCameraPosition => _baseCamPos; + internal Vector3 BaseCameraLookDir => _baseLookDir; + internal (float AimX, float AimY, float AimZ) ProbeCenterScreenAim() => ComputeCenterScreenAim(); + + public override void _Ready() + { + ClientAssets.EnsureAssetsRootRegistered(); + GetViewport().UseTaa = true; + _graphicsSettings = GraphicsSettings.Load(ResolveGraphicsSettingsPath()); + ApplyGraphicsEnvOverrides(_graphicsSettings); + _graphicsSettings.Changed += OnGraphicsSettingsChanged; + + _atmosphere = new AtmosphereSystem { Name = "AtmosphereSystem" }; + AddChild(_atmosphere); + _atmosphere.EnsureInitialized(); + _atmosphere.ApplyGraphicsSettings(_graphicsSettings); + + _terrain = new TerrainRenderer { Name = "Terrain" }; + AddChild(_terrain); + + _sionMap = new SionMapRenderer { Name = "SionMap" }; + AddChild(_sionMap); + + _arena = new ArenaRenderer { Name = "Arena" }; + AddChild(_arena); + _arena.AssetCache.PreloadAll(); + _atmosphere.BindEmitterPool(_arena.Volumetrics); + + _audio = new ArenaAudioSystem { Name = "ArenaAudio" }; + AddChild(_audio); + + _camera = new Camera3D + { + Name = "ShoulderCamera", + Current = true, + Fov = 58f, + Far = 4800f + }; + AddChild(_camera); + + _hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw, ProjectWorldToHud) { Name = "Hud" }; + _hud.JoinRequested += OnJoinRequested; + _hud.HostRequested += OnHostRequested; + _hud.SoloRequested += OnSoloRequested; + _hud.NetworkPanelToggled += _ => SyncMouseMode(); + AddChild(_hud); + + _mainMenu = new MainMenu { Name = "MainMenu" }; + _mainMenu.PlaySoloRequested += OnMainMenuPlaySolo; + _mainMenu.ServerBrowserRequested += OnMainMenuServerBrowser; + _mainMenu.HostLobbyRequested += OnMainMenuHostLobby; + _mainMenu.CallsignChanged += cs => + { + _callsign = cs; + _hud.SetNetworkDefaults(_lastEndpoint, _callsign); + }; + _mainMenu.QuitRequested += () => GetTree().Quit(0); + _mainMenu.ResumeRequested += () => + { + if (_screenMode == ClientScreenMode.PauseOverlay) + { + SetScreenMode(ClientScreenMode.InMatch); + } + }; + _mainMenu.ReturnToMainMenuRequested += ReturnToMainMenu; + _mainMenu.SettingsRequested += OpenSettingsFromCurrentScreen; + AddChild(_mainMenu); + + _settingsOverlay = new SettingsOverlay { Name = "SettingsOverlay" }; + _settingsOverlay.SetGraphicsValues( + _graphicsSettings.VfxResolution, + _graphicsSettings.VolumetricSamples, + _graphicsSettings.SdfgiQuality, + _graphicsSettings.BorderlessFullscreen); + _settingsOverlay.GraphicsChanged += (res, samples, sdfgi, fullscreen) => + _graphicsSettings.Apply(res, samples, sdfgi, fullscreen, persist: !IsAutomatedRun); + _settingsOverlay.ResetDefaultsRequested += () => + _graphicsSettings.ResetToDefaults(persist: !IsAutomatedRun); + _settingsOverlay.BackRequested += CloseSettings; + AddChild(_settingsOverlay); + + _serverBrowser = new ServerBrowser { Name = "ServerBrowser" }; + _serverBrowser.JoinRequested += OnBrowserJoinRequested; + _serverBrowser.HostRequested += () => + { + SetScreenMode(ClientScreenMode.MainMenu); + _mainMenu.SetHostPanelOpen(true); + }; + _serverBrowser.BackRequested += () => SetScreenMode(ClientScreenMode.MainMenu); + AddChild(_serverBrowser); + + _lobbyScreen = new LobbyScreen { Name = "LobbyScreen" }; + _lobbyScreen.LeaveRequested += ReturnToMainMenu; + AddChild(_lobbyScreen); + + var reticleMat = new StandardMaterial3D + { + ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha, + AlbedoColor = new Color(0.27f, 0.85f, 0.91f, 0.82f), + NoDepthTest = false, + CullMode = BaseMaterial3D.CullModeEnum.Disabled + }; + _dropReticleMesh = new MeshInstance3D + { + Name = "DropLandingReticle", + Mesh = new TorusMesh { InnerRadius = 2.5f, OuterRadius = 3.05f, Rings = 28, RingSegments = 8 }, + MaterialOverride = reticleMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + Visible = false + }; + AddChild(_dropReticleMesh); + + string? cliConnect = GetCliArg("--connect"); + string? cliHost = GetCliArg("--host", allowBareFlag: true); + string? cliName = GetCliArg("--name"); + string? cliMap = GetCliArg("--map"); + string? cliSeed = GetCliArg("--seed"); + string? cliSquadSize = GetCliArg("--squad-size"); + if (int.TryParse(cliSquadSize ?? System.Environment.GetEnvironmentVariable("RTD_SQUAD_SIZE"), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsedSquad)) + { + _squadSize = (byte)Math.Clamp(parsedSquad, 1, 4); + } + bool cliSolo = GetCliArg("--solo", allowBareFlag: true) is not null + || System.Environment.GetEnvironmentVariable("RTD_SOLO") == "1"; + bool cliLobby = GetCliArg("--lobby", allowBareFlag: true) is not null + || System.Environment.GetEnvironmentVariable("RTD_LOBBY") == "1"; + string? cliDirUrl = GetCliArg("--directory-url"); + string? envDirUrl = System.Environment.GetEnvironmentVariable("RTD_DIRECTORY_URL"); + _directoryUrl = cliDirUrl ?? envDirUrl ?? ServerBrowser.DefaultDirectoryUrl; + string? cliPublicHost = GetCliArg("--public-host"); + string? envPublicHost = System.Environment.GetEnvironmentVariable("RTD_PUBLIC_HOST"); + if ((cliPublicHost ?? envPublicHost) is { Length: > 0 } ph) + { + _publicHostOverride = ph.Trim(); + } + string? cliServerName = GetCliArg("--server-name"); + string? envServerName = System.Environment.GetEnvironmentVariable("RTD_SERVER_NAME"); + if ((cliServerName ?? envServerName) is { Length: > 0 } sn) + { + _serverName = sn.Trim(); + } + + if (!string.IsNullOrWhiteSpace(cliName)) + { + _callsign = cliName.Trim(); + } + else if (System.Environment.GetEnvironmentVariable("RTD_NAME") is { Length: > 0 } envName) + { + _callsign = envName.Trim(); + } + + if (int.TryParse(cliSeed ?? System.Environment.GetEnvironmentVariable("RTD_SEED"), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsedSeed)) + { + _seed = parsedSeed; + } + + if (InitialMapKindOverride.HasValue) + { + _mapKind = InitialMapKindOverride.Value; + } + else + { + string? mapVal = cliMap ?? System.Environment.GetEnvironmentVariable("RTD_MAP"); + _mapKind = string.Equals(mapVal, "desert", StringComparison.OrdinalIgnoreCase) + ? ArenaMapKind.Desert + : ArenaMapKind.Sion; + } + + string? connectTarget = !string.IsNullOrWhiteSpace(cliConnect) + ? cliConnect + : System.Environment.GetEnvironmentVariable("RTD_CONNECT"); + + string? hostTarget = cliHost is not null + ? cliHost + : (System.Environment.GetEnvironmentVariable("RTD_HOST_PORT") ?? System.Environment.GetEnvironmentVariable("RTD_HOST")); + + if (!string.IsNullOrWhiteSpace(connectTarget)) + { + _lastEndpoint = connectTarget.Trim(); + } + else if (!string.IsNullOrWhiteSpace(hostTarget)) + { + _lastEndpoint = hostTarget.Contains(':', StringComparison.Ordinal) + ? hostTarget.Trim() + : $"127.0.0.1:{hostTarget.Trim()}"; + } + _hud.SetNetworkDefaults(_lastEndpoint, _callsign); + _mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort, _squadSize); + _serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint); + + if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"), out int perfFrames) && perfFrames > 0) + { + _perfTargetFrames = perfFrames; + ArenaSession.PerfEnabled = true; + RenderingServer.ViewportSetMeasureRenderTime(GetViewport().GetViewportRid(), true); + if (_atmosphere.VolumetricEffect is not null) + { + _atmosphere.VolumetricEffect.ProfilingEnabled = true; + } + if (_hud?.HbCanvas is not null) + { + _hud.HbCanvas.ProfilingEnabled = true; + } + } + else if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_AUTO_EXIT_FRAMES"), out int autoExitFrames) && autoExitFrames > 0) + { + _perfTargetFrames = autoExitFrames; + } + + if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_MENU_EXIT_FRAMES"), out int menuExitFrames) && menuExitFrames > 0) + { + _menuPreviewTargetFrames = menuExitFrames; + } + _menuPreviewOut = System.Environment.GetEnvironmentVariable("RTD_MENU_PREVIEW_OUT"); + + _hasWindowOverride = GetCliArg("--windowed", allowBareFlag: true) is not null + || GetCliArg("--resolution", allowBareFlag: true) is not null + || GetCliArg("-w", allowBareFlag: true) is not null; + if (!IsAutomatedRun && !_hasWindowOverride) + { + ApplyWindowMode(_graphicsSettings.BorderlessFullscreen); + } + else + { + if (IsAutomatedRun && DisplayServer.GetName() != "headless") + { + DisplayServer.WindowSetFlag(DisplayServer.WindowFlags.NoFocus, true); + } + if (_hasWindowOverride && DisplayServer.GetName() != "headless") + { + var winMode = DisplayServer.WindowGetMode(); + bool actualFullscreen = winMode == DisplayServer.WindowMode.Fullscreen + || winMode == DisplayServer.WindowMode.ExclusiveFullscreen; + _graphicsSettings.SetBorderlessFullscreen(actualFullscreen, persist: false); + } + } + + bool perfCombat = _perfTargetFrames > 0 && System.Environment.GetEnvironmentVariable("RTD_PERF_COMBAT") == "1"; + bool skipInitialDrop = InitialSkipDropOverride || perfCombat; + bool autoBypassMenu = InitialMapKindOverride.HasValue + || InitialSkipDropOverride + || InitialSkipMenuOverride + || _perfTargetFrames > 0 + || !string.IsNullOrWhiteSpace(connectTarget) + || hostTarget is not null + || cliSolo; + + if (!string.IsNullOrWhiteSpace(connectTarget)) + { + StartRemoteSession(connectTarget, _callsign, fromBrowser: false); + } + else if (hostTarget is not null) + { + StartListenHostSession( + hostTarget, + _callsign, + _mapKind, + _serverName, + startInLobby: cliLobby, + listOnPublicDirectory: false, + fallbackToLocalOnFailure: true); + } + else if (autoBypassMenu) + { + Reset(_seed, _mapKind, skipInitialDrop); + } + else + { + EnterMainMenuBackdrop(); + } + + if (perfCombat && _session is not null) + { + SetupPerfCombatScenario(_session); + } + _perfLastFrameTick = Stopwatch.GetTimestamp(); + _perfLastDirtyRebakes = _terrain.DirtyRebakes; + TerrainRenderer.PerfBakeTileMs = 0; + TerrainRenderer.PerfBakeTileCalls = 0; + VehicleVisualInstance.PerfDamageHeatMs = 0; + VehicleVisualInstance.PerfMaterialDupCount = 0; + } + + private void SetupPerfCombatScenario(IClientArenaSession session) + { + if (session is LocalArenaSession local) + { + var inner = local.Inner; + var p = inner.State.Contenders[0]; + float fwdX = MathF.Sin(p.Yaw); + float fwdZ = MathF.Cos(p.Yaw); + float rightX = -fwdZ; + float rightZ = fwdX; + + for (int i = 1; i <= 8 && i < inner.State.Contenders.Count; i++) + { + float dist = 65f + (i % 4) * 11f; + float lat = (i - 4.5f) * 11f; + float tx = p.X + fwdX * dist + rightX * lat; + float tz = p.Z + fwdZ * dist + rightZ * lat; + inner.SetContenderPose(inner.State.Contenders[i].Id, tx, tz, p.Yaw + MathF.PI); + } + + for (int i = 0; i < 6 && i < inner.State.Spectators.Spectators.Count; i++) + { + var s = inner.State.Spectators.Spectators[i]; + float dist = 78f + (i % 3) * 12f; + float lat = (i - 2.5f) * 16f; + float sx = p.X + fwdX * dist + rightX * lat; + float sz = p.Z + fwdZ * dist + rightZ * lat; + inner.SetSpectatorPose(s.Id, sx, sz, p.Yaw + MathF.PI); + inner.State.Spectators.OnSpectatorDamaged(s, p.Id); + } + + var aimTarget = inner.State.Contenders[1]; + _scriptedInput = new PlayerInput( + Throttle: 0.4f, + Steer: 0f, + AimWorldX: aimTarget.X, + AimWorldZ: aimTarget.Z, + Fire: true, + InteractPickup: false, + Brake: false); + + _arena.Sync(session, _elapsedSeconds, 0f, 1f); + UpdateCamera(1f, 1f); + _hud.Sync(session); + return; + } + + var localC = session.LocalContender; + _scriptedInput = new PlayerInput( + Throttle: 0.4f, + Steer: 0.12f, + AimWorldX: localC.X + MathF.Sin(localC.Yaw) * 60f, + AimWorldZ: localC.Z + MathF.Cos(localC.Yaw) * 60f, + Fire: true, + InteractPickup: false, + Brake: false); + } + + public override void _ExitTree() + { + DisposeSessionAndDirectory(); + } + + public void Reset(int seed, ArenaMapKind? mapKind = null, bool skipInitialDrop = false, byte? squadSize = null) + { + _seed = seed; + if (mapKind.HasValue) + { + _mapKind = mapKind.Value; + } + if (squadSize.HasValue) + { + _squadSize = (byte)Math.Clamp((int)squadSize.Value, 1, 4); + } + + DisposeSessionAndDirectory(); + Failure = null; + _hud.SetNetworkError(null); + + try + { + _session = new LocalArenaSession(seed, _mapKind, _callsign, skipInitialDrop, squadSize: _squadSize); + SetScreenMode(ClientScreenMode.InMatch); + BindSessionPresentation(resetCamera: true); + } + catch (Exception ex) + { + Failure = ex.Message; + GD.PushError("LocalArenaSession startup failed: " + ex); + } + } + + private void EnterMainMenuBackdrop() + { + DisposeSessionAndDirectory(); + Failure = null; + _hud.SetNetworkError(null); + EnsureMenuSionBackdrop(); + _mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort, _squadSize); + _mainMenu.SetHostPanelOpen(false); + SetScreenMode(ClientScreenMode.MainMenu); + } + + private void ReturnToMainMenu() + { + _mainMenu.SetStatus(null); + EnterMainMenuBackdrop(); + } + + private void DisposeSessionAndDirectory() + { + _directoryReporter?.Dispose(); + _directoryReporter = null; + _lastDirHumans = -1; + _lastDirPhase = (MatchPhase)(-1); + _lastDirMap = (ArenaMapKind)(-1); + _lastDirSeed = 0; + + if (_session is RemoteArenaSession remote) + { + remote.DisconnectGracefully("Leave"); + } + _session?.Dispose(); + _session = null; + _boundViewState = null; + _wasNetConnected = false; + } + + private void EnsureMenuSionBackdrop() + { + _menuSionData ??= SionMapLoader.Load(); + _menuSionTerrain ??= TerrainField.LoadSharedHeightmap( + _menuSionData.Metadata.SizeMeters, + _menuSionData.Metadata.GridRes, + _menuSionData.Metadata.TileGrid, + _menuSionData.BaseDem, + _menuSionData.BaseDemMinY, + _menuSionData.BaseDemScale, + _menuSionData.Metadata.MinY, + _menuSionData.Metadata.MaxY, + 42UL); + + _terrain.Visible = true; + _sionMap.Visible = true; + _arena.Visible = false; + _dropReticleMesh.Visible = false; + _camera.Far = 4200f; + _atmosphere.ApplyMap(ArenaMapKind.Sion); + _sionMap.EnsureBuilt(_menuSionData); + UpdateLobbyOrMenuOrbitCamera(ArenaMapKind.Sion, _menuSionTerrain); + _terrain.UpdateTileLod(_camera.GlobalPosition); + _terrain.Sync(_menuSionTerrain, _menuSionData); + _sionMap.UpdateLod(_camera.GlobalPosition); + } + + private void UpdateLobbyOrMenuOrbitCamera(ArenaMapKind mapKind, TerrainField terrain) + { + float orbitRadius = mapKind == ArenaMapKind.Sion ? 460f : 210f; + float speed = mapKind == ArenaMapKind.Sion ? 0.055f : 0.08f; + float angle = _elapsedSeconds * speed + 0.65f; + float ox = MathF.Cos(angle) * orbitRadius; + float oz = MathF.Sin(angle) * orbitRadius; + float groundY = terrain.SampleHeight(ox, oz); + float targetY = terrain.SampleHeight(0f, 0f) + (mapKind == ArenaMapKind.Sion ? 42f : 14f); + float camY = mapKind == ArenaMapKind.Sion + ? MathF.Max(groundY + 115f, targetY + 135f) + : MathF.Max(groundY + 55f, 85f); + + _camera.Fov = 58f; + _camera.GlobalPosition = new Vector3(ox, camY, oz); + _camera.LookAt(new Vector3(0f, targetY, 0f), Vector3.Up); + } + + private void SetScreenMode(ClientScreenMode mode) + { + _screenMode = mode; + switch (mode) + { + case ClientScreenMode.MainMenu: + _hud.SetInputBlocked(true); + _hud.SetMatchHudActive(false); + _settingsOverlay.SetSettingsVisible(false); + _serverBrowser.SetBrowserVisible(false); + _lobbyScreen.SetLobbyVisible(false); + _mainMenu.SetOverlayKind(MainMenu.OverlayKind.MainMenu); + _arena.Visible = false; + _dropReticleMesh.Visible = false; + break; + + case ClientScreenMode.ServerBrowser: + _hud.SetInputBlocked(true); + _hud.SetMatchHudActive(false); + _settingsOverlay.SetSettingsVisible(false); + _mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden); + _lobbyScreen.SetLobbyVisible(false); + _serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint); + _serverBrowser.SetBrowserVisible(true, autoRefresh: true); + _arena.Visible = false; + _dropReticleMesh.Visible = false; + break; + + case ClientScreenMode.Lobby: + _hud.SetInputBlocked(true); + _hud.SetMatchHudActive(false); + _settingsOverlay.SetSettingsVisible(false); + _mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden); + _serverBrowser.SetBrowserVisible(false); + _lobbyScreen.SetLobbyVisible(true); + _arena.Visible = false; + _dropReticleMesh.Visible = false; + break; + + case ClientScreenMode.InMatch: + _settingsOverlay.SetSettingsVisible(false); + _mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden); + _serverBrowser.SetBrowserVisible(false); + _lobbyScreen.SetLobbyVisible(false); + _arena.Visible = true; + _hud.SetMatchHudActive(true); + _hud.SetInputBlocked(false); + break; + + case ClientScreenMode.PauseOverlay: + _settingsOverlay.SetSettingsVisible(false); + _serverBrowser.SetBrowserVisible(false); + _lobbyScreen.SetLobbyVisible(false); + _arena.Visible = true; + _hud.SetMatchHudActive(true); + _hud.SetInputBlocked(true); + _mainMenu.SetPauseContext(BuildPauseContextLine()); + _mainMenu.SetOverlayKind(MainMenu.OverlayKind.PauseOverlay); + break; + + case ClientScreenMode.Settings: + _mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden); + _serverBrowser.SetBrowserVisible(false); + _lobbyScreen.SetLobbyVisible(false); + bool showMatchBehind = _settingsReturnMode == ClientScreenMode.PauseOverlay; + _arena.Visible = showMatchBehind; + _hud.SetMatchHudActive(showMatchBehind); + if (!showMatchBehind) + { + _dropReticleMesh.Visible = false; + } + _settingsOverlay.SetGraphicsValues( + _graphicsSettings.VfxResolution, + _graphicsSettings.VolumetricSamples, + _graphicsSettings.SdfgiQuality, + _graphicsSettings.BorderlessFullscreen); + _settingsOverlay.SetSettingsVisible(true); + break; + } + SyncMouseMode(); + } + + private string BuildPauseContextLine() + { + string mapLabel = _mapKind == ArenaMapKind.Sion ? "SION 3KM" : "DESERT RING"; + if (_session is null) return mapLabel; + var net = _session.ConnectionStatus; + return net.Mode switch + { + NetworkMode.ListenHost => $"{mapLabel} • {net.StateLabel}", + NetworkMode.RemoteClient => $"{mapLabel} • {net.StateLabel}", + _ => $"SOLO • {mapLabel} • SEED {_seed}" + }; + } + + private void StartListenHostSession( + string hostArg, + string callsign, + ArenaMapKind mapKind, + string serverName, + bool startInLobby, + bool listOnPublicDirectory, + bool fallbackToLocalOnFailure, + byte? squadSize = null) + { + string nextCallsign = string.IsNullOrWhiteSpace(callsign) ? "Host" : callsign.Trim(); + string cleanServerName = string.IsNullOrWhiteSpace(serverName) ? "Rust to Dust" : serverName.Trim(); + byte activeSquadSize = (byte)Math.Clamp((int)(squadSize ?? _squadSize), 1, 4); + _squadSize = activeSquadSize; + Failure = null; + _hud.SetNetworkError(null); + _mainMenu.SetHostError(null); + + try + { + IPAddress defaultBind = listOnPublicDirectory || !fallbackToLocalOnFailure ? IPAddress.Any : IPAddress.Loopback; + ParseBindAndPort(hostArg, defaultBind, DefaultNetPort, out IPAddress bindIp, out int port); + var hostSession = new ListenHostArenaSession( + bindIp, + port, + _seed, + mapKind, + startInLobby: startInLobby, + serverName: cleanServerName, + minHumansToStart: 1, + squadSize: activeSquadSize); + hostSession.Host.Session.SetHumanSlot(0, true, nextCallsign); + + DisposeSessionAndDirectory(); + _session = hostSession; + _callsign = nextCallsign; + _mapKind = mapKind; + _serverName = cleanServerName; + _lastEndpoint = $"{(bindIp.Equals(IPAddress.Any) ? IPAddress.Loopback : bindIp)}:{hostSession.Host.BoundPort}"; + _hud.SetNetworkDefaults(_lastEndpoint, _callsign); + + if (listOnPublicDirectory) + { + string normDir = DirectoryBrowserClient.NormalizeBaseUrl(_directoryUrl); + if (!string.IsNullOrEmpty(normDir)) + { + UpdateCachedDirectorySnapshot(hostSession); + _directoryReporter = new DirectoryReporter(normDir, ReadCachedDirectorySnapshot); + } + } + + SetScreenMode(startInLobby ? ClientScreenMode.Lobby : ClientScreenMode.InMatch); + BindSessionPresentation(resetCamera: true); + } + catch (Exception ex) + { + Failure = ex.Message; + if (fallbackToLocalOnFailure && _session is null) + { + _session = new LocalArenaSession(_seed, _mapKind, _callsign, squadSize: _squadSize); + SetScreenMode(ClientScreenMode.InMatch); + BindSessionPresentation(resetCamera: false); + } + _hud.SetNetworkError(ex.Message); + _mainMenu.SetHostError(ex.Message); + GD.PushError("ListenHostArenaSession startup failed: " + ex); + } + } + + private void StartRemoteSession(string endpointText, string callsign, bool fromBrowser) + { + string nextCallsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim(); + Failure = null; + _hud.SetNetworkError(null); + _serverBrowser.SetError(null); + + try + { + IPEndPoint ep = ResolveEndPoint(endpointText, DefaultNetPort); + var remote = new RemoteArenaSession(ep, nextCallsign); + remote.PumpNetwork(); + + DisposeSessionAndDirectory(); + _session = remote; + _callsign = nextCallsign; + _lastEndpoint = endpointText.Trim(); + _hud.SetNetworkDefaults(_lastEndpoint, _callsign); + SetScreenMode(fromBrowser ? ClientScreenMode.Lobby : ClientScreenMode.InMatch); + BindSessionPresentation(resetCamera: true); + } + catch (Exception ex) + { + Failure = ex.Message; + if (!fromBrowser && _session is null && _screenMode == ClientScreenMode.InMatch) + { + _session = new LocalArenaSession(_seed, _mapKind, _callsign, squadSize: _squadSize); + SetScreenMode(ClientScreenMode.InMatch); + BindSessionPresentation(resetCamera: false); + } + _hud.SetNetworkError(ex.Message); + _serverBrowser.SetError(ex.Message); + GD.PushError("RemoteArenaSession startup failed: " + ex); + } + } + + private DirectoryHeartbeatSnapshot ReadCachedDirectorySnapshot() + { + lock (_dirSnapGate) + { + return _cachedDirectorySnapshot; + } + } + + private void UpdateCachedDirectorySnapshot(ListenHostArenaSession hostSession) + { + var state = hostSession.ViewState; + int humans = hostSession.Host.ConnectedHumanCount; + string phaseStr = state.Phase switch + { + MatchPhase.Lobby => "Lobby", + MatchPhase.Completed => "Completed", + _ => "Active" + }; + string mapStr = state.MapKind == ArenaMapKind.Sion ? "sion" : "desert"; + int wave = hostSession.DropWaveState.CurrentWaveIndex; + + bool changed = humans != _lastDirHumans + || state.Phase != _lastDirPhase + || state.MapKind != _lastDirMap + || state.Seed != _lastDirSeed; + + lock (_dirSnapGate) + { + _cachedDirectorySnapshot = new DirectoryHeartbeatSnapshot( + Name: _serverName, + PublicHost: _publicHostOverride, + UdpPort: hostSession.Host.BoundPort, + Map: mapStr, + Seed: state.Seed, + Humans: humans, + MaxHumans: MatchState.ContenderCount, + Phase: phaseStr, + Wave: wave); + } + + if (changed) + { + _lastDirHumans = humans; + _lastDirPhase = state.Phase; + _lastDirMap = state.MapKind; + _lastDirSeed = state.Seed; + _directoryReporter?.NotifyChanged(); + } + } + + private void OnMainMenuPlaySolo(ArenaMapKind mapKind, string callsign, byte squadSize) + { + _callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim(); + _squadSize = (byte)Math.Clamp((int)squadSize, 1, 4); + _hud.SetNetworkDefaults(_lastEndpoint, _callsign); + Reset(_seed, mapKind, skipInitialDrop: false, squadSize: _squadSize); + } + + private void OnMainMenuServerBrowser(string callsign) + { + _callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim(); + _hud.SetNetworkDefaults(_lastEndpoint, _callsign); + SetScreenMode(ClientScreenMode.ServerBrowser); + } + + private void OnMainMenuHostLobby(int port, string serverName, ArenaMapKind mapKind, bool listOnPublicDirectory, string callsign, byte squadSize) + { + string? envBind = System.Environment.GetEnvironmentVariable("RTD_BIND"); + string hostArg = !string.IsNullOrWhiteSpace(envBind) ? $"{envBind.Trim()}:{port}" : port.ToString(CultureInfo.InvariantCulture); + _squadSize = (byte)Math.Clamp((int)squadSize, 1, 4); + StartListenHostSession( + hostArg, + callsign, + mapKind, + serverName, + startInLobby: true, + listOnPublicDirectory: listOnPublicDirectory, + fallbackToLocalOnFailure: false, + squadSize: _squadSize); + } + + private void OnBrowserJoinRequested(string endpointText, string callsign) + { + StartRemoteSession(endpointText, callsign, fromBrowser: true); + } + + private void OnSoloRequested() + { + Reset(_seed, _mapKind); + } + + private void OnHostRequested(int port, string callsign) + { + string? envBind = System.Environment.GetEnvironmentVariable("RTD_BIND"); + string hostArg = !string.IsNullOrWhiteSpace(envBind) ? $"{envBind.Trim()}:{port}" : port.ToString(CultureInfo.InvariantCulture); + StartListenHostSession( + hostArg, + callsign, + _mapKind, + _serverName, + startInLobby: false, + listOnPublicDirectory: false, + fallbackToLocalOnFailure: true); + } + + private void OnJoinRequested(string endpointText, string callsign) + { + StartRemoteSession(endpointText, callsign, fromBrowser: false); + } + + private void BindSessionPresentation(bool resetCamera) + { + if (_session is null) return; + var state = _session.ViewState; + _boundViewState = state; + _mapKind = state.MapKind; + _seed = state.Seed; + _wasNetConnected = _session.ConnectionStatus.Connected; + + if (resetCamera) + { + var p = _session.LocalContender; + _cameraYaw = p.Yaw; + _prevLocalLifecycle = p.Lifecycle; + if (p.IsInDropPod) + { + _cameraPitch = Mathf.DegToRad(34f); + _orbitalPodCamBlend = 1.0f; + } + else + { + _cameraPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(5f) : Mathf.DegToRad(12f); + _orbitalPodCamBlend = 0f; + } + _cameraZoom = 1.0f; + _lastCamChassisId = null; + _hasBaseCamPose = false; + _camJuice.Reset(); + _footsteps.Clear(); + _frameEvents.Clear(); + _frameFootsteps.Clear(); + _audio.ResetForSession(_session); + _hud.ResetFeedback(); + } + else + { + _audio.ResetForSession(_session); + } + + _camera.Far = _mapKind == ArenaMapKind.Sion ? 4800f : 2600f; + _atmosphere.ApplyMap(_mapKind); + + bool inLobby = _screenMode == ClientScreenMode.Lobby || state.Phase == MatchPhase.Lobby; + + _terrain.Visible = true; + _terrain.InvalidateAll(); + _terrain.UpdateTileLod(_camera.GlobalPosition); + _terrain.Sync(state.Terrain, state.SionMap); + + if (_mapKind == ArenaMapKind.Sion && state.SionMap is not null) + { + _sionMap.Visible = true; + _sionMap.EnsureBuilt(state.SionMap); + if (!inLobby) + { + _arena.Sync(_session, _elapsedSeconds, 0f, 1f); + UpdateCamera(1f, 1f); + } + else + { + UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain); + } + _terrain.UpdateTileLod(_camera.GlobalPosition); + _sionMap.UpdateLod(_camera.GlobalPosition); + } + else + { + _sionMap.Visible = false; + if (!inLobby) + { + _arena.Sync(_session, _elapsedSeconds, 0f, 1f); + UpdateCamera(1f, 1f); + } + else + { + UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain); + } + _terrain.UpdateTileLod(_camera.GlobalPosition); + } + + if (!inLobby) + { + var localStart = _session.LocalContender; + Vector3 startVec = new(localStart.X, localStart.Y, localStart.Z); + Vector3 startFwd = new(MathF.Sin(localStart.Yaw), 0f, MathF.Cos(localStart.Yaw)); + _arena.Particles.PrewarmFlashLights(startVec, startFwd); + _arena.GpuSparks.Prewarm(startVec); + _arena.PomDecals.PrewarmShader(startVec); + _hud.Sync(_session); + } + else + { + _lobbyScreen.Sync(_session); + } + SyncMouseMode(); + } + + private bool IsAutomatedRun => + DisplayServer.GetName() == "headless" + || InitialMapKindOverride.HasValue + || InitialSkipDropOverride + || InitialSkipMenuOverride + || _perfTargetFrames > 0 + || _menuPreviewTargetFrames > 0 + || string.Equals(GetCliArg("--audio-driver"), "Dummy", StringComparison.OrdinalIgnoreCase) + || GetCliArg("--script", allowBareFlag: true) is not null + || !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_NO_CAPTURE")) + || !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES")) + || !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_AUTO_EXIT_FRAMES")) + || !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_MENU_EXIT_FRAMES")); + + public override void _Notification(int what) + { + if (what == NotificationApplicationFocusOut || what == NotificationWMWindowFocusOut) + { + Input.MouseMode = Input.MouseModeEnum.Visible; + } + else if (what == NotificationApplicationFocusIn || what == NotificationWMWindowFocusIn) + { + if (IsInsideTree()) + { + SyncMouseMode(); + } + } + } + + private void OpenSettingsFromCurrentScreen() + { + if (_screenMode == ClientScreenMode.PauseOverlay || _screenMode == ClientScreenMode.MainMenu) + { + _settingsReturnMode = _screenMode; + } + SetScreenMode(ClientScreenMode.Settings); + } + + private void CloseSettings() + { + if (_screenMode == ClientScreenMode.Settings) + { + SetScreenMode(_settingsReturnMode); + } + } + + private void OnGraphicsSettingsChanged(GraphicsSettings settings) + { + _atmosphere.ApplyGraphicsSettings(settings); + _settingsOverlay?.SetGraphicsValues( + settings.VfxResolution, + settings.VolumetricSamples, + settings.SdfgiQuality, + settings.BorderlessFullscreen); + if (!IsAutomatedRun && DisplayServer.GetName() != "headless") + { + ApplyWindowMode(settings.BorderlessFullscreen); + } + } + + private static string? ResolveGraphicsSettingsPath() + { + try + { + return ProjectSettings.GlobalizePath("user://" + GraphicsSettings.DefaultFileName); + } + catch + { + return null; + } + } + + private static void ApplyGraphicsEnvOverrides(GraphicsSettings settings) + { + string? resEnv = System.Environment.GetEnvironmentVariable("RTD_VFX_RES"); + if (!string.IsNullOrWhiteSpace(resEnv)) + { + VfxResolutionScale? parsed = resEnv.Trim().ToLowerInvariant() switch + { + "half" or "0.5" or "0.5x" => VfxResolutionScale.Half, + "threequarter" or "three_quarter" or "high" or "0.75" or "0.75x" => VfxResolutionScale.ThreeQuarter, + "full" or "1.0" or "1.0x" or "native" => VfxResolutionScale.Full, + _ => null + }; + if (parsed.HasValue) + { + settings.SetVfxResolution(parsed.Value, persist: false); + } + } + + string? samplesEnv = System.Environment.GetEnvironmentVariable("RTD_VFX_SAMPLES"); + if (!string.IsNullOrWhiteSpace(samplesEnv)) + { + VolumetricSamples? parsed = samplesEnv.Trim().ToLowerInvariant() switch + { + "low" or "8" => VolumetricSamples.Low, + "medium" or "10" => VolumetricSamples.Medium, + "high" or "16" => VolumetricSamples.High, + "ultra" or "24" => VolumetricSamples.Ultra, + _ => null + }; + if (parsed.HasValue) + { + settings.SetVolumetricSamples(parsed.Value, persist: false); + } + } + + string? sdfgiEnv = System.Environment.GetEnvironmentVariable("RTD_SDFGI_QUALITY"); + if (!string.IsNullOrWhiteSpace(sdfgiEnv)) + { + SdfgiQuality? parsed = sdfgiEnv.Trim().ToLowerInvariant() switch + { + "off" => SdfgiQuality.Off, + "balanced" => SdfgiQuality.Balanced, + "high" => SdfgiQuality.High, + _ => null + }; + if (parsed.HasValue) + { + settings.SetSdfgiQuality(parsed.Value, persist: false); + } + } + } + + private static void ApplyWindowMode(bool borderlessFullscreen) + { + if (DisplayServer.GetName() == "headless") + { + return; + } + var current = DisplayServer.WindowGetMode(); + bool isFullscreen = current == DisplayServer.WindowMode.Fullscreen || current == DisplayServer.WindowMode.ExclusiveFullscreen; + if (isFullscreen != borderlessFullscreen) + { + DisplayServer.WindowSetMode(borderlessFullscreen ? DisplayServer.WindowMode.Fullscreen : DisplayServer.WindowMode.Windowed); + } + } + + private void ToggleBorderlessFullscreen() + { + if (IsAutomatedRun || DisplayServer.GetName() == "headless") + { + return; + } + var mode = DisplayServer.WindowGetMode(); + bool nextFullscreen = !(mode == DisplayServer.WindowMode.Fullscreen || mode == DisplayServer.WindowMode.ExclusiveFullscreen); + DisplayServer.WindowSetMode(nextFullscreen ? DisplayServer.WindowMode.Fullscreen : DisplayServer.WindowMode.Windowed); + _graphicsSettings.SetBorderlessFullscreen(nextFullscreen, persist: !IsAutomatedRun); + } + + private void SyncMouseMode() + { + if (IsAutomatedRun) + { + Input.MouseMode = Input.MouseModeEnum.Visible; + return; + } + if (!IsInsideTree() || GetWindow() is not { } win || !win.HasFocus()) + { + Input.MouseMode = Input.MouseModeEnum.Visible; + return; + } + if (_screenMode != ClientScreenMode.InMatch) + { + Input.MouseMode = Input.MouseModeEnum.Visible; + return; + } + bool uiOpen = _hud.GarageExpanded || _hud.NetworkPanelOpen; + Input.MouseMode = uiOpen ? Input.MouseModeEnum.Visible : Input.MouseModeEnum.Captured; + } + + private static string? GetCliArg(string flag, bool allowBareFlag = false) + { + static string? SearchArgs(string[] args, string flagName, bool bare, int startIndex = 0) + { + string prefix = flagName + "="; + for (int i = startIndex; i < args.Length; i++) + { + string a = args[i]; + if (a.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + return a[prefix.Length..]; + } + if (a.Equals(flagName, StringComparison.OrdinalIgnoreCase)) + { + if (i + 1 < args.Length && !args[i + 1].StartsWith("-", StringComparison.Ordinal)) + { + return args[i + 1]; + } + if (bare) + { + return string.Empty; + } + } + } + return null; + } + + return SearchArgs(OS.GetCmdlineUserArgs(), flag, allowBareFlag) + ?? SearchArgs(OS.GetCmdlineArgs(), flag, allowBareFlag) + ?? SearchArgs(System.Environment.GetCommandLineArgs(), flag, allowBareFlag, startIndex: 1); + } + + private static void ParseBindAndPort(string? raw, IPAddress defaultIp, int defaultPort, out IPAddress bindIp, out int port) + { + bindIp = defaultIp; + port = defaultPort; + string trimmed = (raw ?? string.Empty).Trim(); + if (string.IsNullOrEmpty(trimmed)) + { + return; + } + + int colon = trimmed.LastIndexOf(':'); + if (colon >= 0) + { + string ipPart = trimmed[..colon].Trim(); + string portPart = trimmed[(colon + 1)..].Trim(); + if (!string.IsNullOrEmpty(ipPart) && IPAddress.TryParse(ipPart, out var parsedIp)) + { + bindIp = parsedIp; + } + if (int.TryParse(portPart, NumberStyles.Integer, CultureInfo.InvariantCulture, out int p) && p is > 0 and <= 65535) + { + port = p; + } + return; + } + + if (int.TryParse(trimmed, NumberStyles.Integer, CultureInfo.InvariantCulture, out int onlyPort) && onlyPort is > 0 and <= 65535) + { + port = onlyPort; + } + else if (IPAddress.TryParse(trimmed, out var onlyIp)) + { + bindIp = onlyIp; + } + } + + private static IPEndPoint ResolveEndPoint(string endpointText, int defaultPort) + { + string trimmed = (endpointText ?? string.Empty).Trim(); + if (string.IsNullOrEmpty(trimmed)) + { + throw new ArgumentException("Server endpoint cannot be empty."); + } + + string host = trimmed; + int port = defaultPort; + int colon = trimmed.LastIndexOf(':'); + if (colon > 0 && trimmed[..colon].IndexOf(':') < 0) + { + host = trimmed[..colon].Trim(); + string portStr = trimmed[(colon + 1)..].Trim(); + if (!int.TryParse(portStr, NumberStyles.Integer, CultureInfo.InvariantCulture, out port) || port is <= 0 or > 65535) + { + throw new FormatException($"Invalid port in endpoint '{endpointText}'."); + } + } + + if (IPAddress.TryParse(host, out var ip)) + { + return new IPEndPoint(ip, port); + } + + var addrs = Dns.GetHostAddresses(host); + for (int i = 0; i < addrs.Length; i++) + { + if (addrs[i].AddressFamily == AddressFamily.InterNetwork) + { + return new IPEndPoint(addrs[i], port); + } + } + if (addrs.Length > 0) + { + return new IPEndPoint(addrs[0], port); + } + throw new SocketException((int)SocketError.HostNotFound); + } + + public void SetScriptedInput(PlayerInput? input) => _scriptedInput = input; + + public override void _Input(InputEvent @event) + { + if (@event is InputEventKey key && key.Pressed && !key.Echo) + { + bool isAltEnter = (key.Keycode == Key.Enter || key.Keycode == Key.KpEnter) + && key.AltPressed && !key.CtrlPressed && !key.ShiftPressed; + bool isF11 = key.Keycode == Key.F11 && !key.AltPressed && !key.CtrlPressed && !key.ShiftPressed; + if (isAltEnter || isF11) + { + ToggleBorderlessFullscreen(); + GetViewport().SetInputAsHandled(); + } + } + } + + public override void _UnhandledInput(InputEvent @event) + { + if (@event is InputEventKey key && key.Pressed && !key.Echo) + { + if (_screenMode == ClientScreenMode.MainMenu) + { + if (key.Keycode == Key.Escape && _mainMenu.IsHostPanelOpen) + { + _mainMenu.SetHostPanelOpen(false); + } + return; + } + if (_screenMode == ClientScreenMode.ServerBrowser) + { + if (key.Keycode == Key.Escape) + { + SetScreenMode(ClientScreenMode.MainMenu); + } + return; + } + if (_screenMode == ClientScreenMode.Lobby) + { + return; + } + if (_screenMode == ClientScreenMode.PauseOverlay) + { + if (key.Keycode == Key.Escape) + { + SetScreenMode(ClientScreenMode.InMatch); + } + return; + } + if (_screenMode == ClientScreenMode.Settings) + { + if (key.Keycode == Key.Escape) + { + CloseSettings(); + } + return; + } + + if (key.Keycode == Key.F9) + { + _hud.ToggleNetworkPanel(); + SyncMouseMode(); + return; + } + + if (key.Keycode == Key.Escape) + { + if (_hud.NetworkPanelOpen) + { + _hud.SetNetworkPanelOpen(false); + SyncMouseMode(); + } + else if (_hud.GarageExpanded) + { + _hud.ToggleGarage(); + SyncMouseMode(); + } + else + { + SetScreenMode(ClientScreenMode.PauseOverlay); + } + return; + } + + if (_hud.IsUiTextInputFocused) + { + return; + } + + switch (key.Keycode) + { + case Key.E: + _interactQueued = true; + break; + case Key.Tab: + _hud.ToggleGarage(); + SyncMouseMode(); + break; + case Key.R: + _session?.RequestNewMatch(_seed + 1, _mapKind); + break; + case Key.M: + _session?.RequestNewMatch(_seed, _mapKind == ArenaMapKind.Sion ? ArenaMapKind.Desert : ArenaMapKind.Sion); + break; + } + return; + } + + if (_screenMode != ClientScreenMode.InMatch) + { + return; + } + + if (@event is InputEventMouseMotion mm && Input.MouseMode == Input.MouseModeEnum.Captured) + { + _cameraYaw -= mm.Relative.X * 0.0028f; + _cameraPitch = Math.Clamp( + _cameraPitch + mm.Relative.Y * 0.0024f, + Mathf.DegToRad(-78f), + Mathf.DegToRad(62f)); + return; + } + + if (@event is InputEventMouseButton mb && mb.Pressed) + { + if (mb.ButtonIndex == MouseButton.WheelUp) + { + _cameraZoom = Math.Clamp(_cameraZoom - 0.08f, 0.75f, 1.6f); + } + else if (mb.ButtonIndex == MouseButton.WheelDown) + { + _cameraZoom = Math.Clamp(_cameraZoom + 0.08f, 0.75f, 1.6f); + } + else if (mb.ButtonIndex == MouseButton.Left && + Input.MouseMode == Input.MouseModeEnum.Visible && + !_hud.GarageExpanded && + !_hud.NetworkPanelOpen && + !_hud.IsPointerOverInteractiveHud(mb.Position)) + { + SyncMouseMode(); + } + } + } + + public override void _PhysicsProcess(double delta) + { + if (_session is null) + { + return; + } + + _elapsedSeconds += (float)delta; + PlayerInput input; + if (_screenMode == ClientScreenMode.InMatch) + { + input = _scriptedInput ?? GatherPlayerInput(); + } + else + { + input = new PlayerInput(0f, 0f, 0f, 0f, false, false, false); + } + _interactQueued = false; + + if (_perfTargetFrames > 0) + { + long t0 = Stopwatch.GetTimestamp(); + _session.SubmitLocalInput(in input, isPhysicsTick: true); + long t1 = Stopwatch.GetTimestamp(); + double toMs = 1000.0 / Stopwatch.Frequency; + _perfPendingStepMs += (t1 - t0) * toMs; + _perfPhysicsTicks++; + } + else + { + _session.SubmitLocalInput(in input, isPhysicsTick: true); + } + } + + public override void _Process(double delta) + { + if (_session is null) + { + _elapsedSeconds += (float)delta; + EnsureMenuSionBackdrop(); + if (_menuPreviewTargetFrames > 0) + { + _menuPreviewFrames++; + if (_menuPreviewFrames >= _menuPreviewTargetFrames) + { + SaveMenuPreviewAndQuit(); + } + } + return; + } + + float alpha = Math.Clamp((float)Engine.GetPhysicsInterpolationFraction(), 0f, 1f); + _session.BeginRenderFrame(delta, alpha); + + if (_session is ListenHostArenaSession liveHost && _directoryReporter is not null) + { + UpdateCachedDirectorySnapshot(liveHost); + } + + bool nowConnected = _session.ConnectionStatus.Connected; + bool sessionReadyForPhaseRouting = _session is not RemoteArenaSession || nowConnected; + if (sessionReadyForPhaseRouting) + { + if (_session.ViewState.Phase == MatchPhase.Lobby && _screenMode != ClientScreenMode.Lobby) + { + SetScreenMode(ClientScreenMode.Lobby); + BindSessionPresentation(resetCamera: true); + } + else if (_session.ViewState.Phase != MatchPhase.Lobby && _screenMode == ClientScreenMode.Lobby) + { + SetScreenMode(ClientScreenMode.InMatch); + BindSessionPresentation(resetCamera: true); + } + } + + if (!ReferenceEquals(_boundViewState, _session.ViewState) || (!_wasNetConnected && nowConnected)) + { + BindSessionPresentation(resetCamera: true); + if (_perfTargetFrames > 0 && !_wasNetConnected && nowConnected) + { + _perfFrameCount = 0; + _perfPhysicsTicks = 0; + _perfFrameMs.Clear(); + _perfPhysicsStepMs.Clear(); + _perfTerrainSyncMs.Clear(); + _perfArenaSyncMs.Clear(); + _perfHudMs.Clear(); + _perfDirtyRebakeDelta.Clear(); + _perfDrawCalls.Clear(); + _perfPrimitives.Clear(); + _perfObjects.Clear(); + _perfNodeCount.Clear(); + _perfTimeProcess.Clear(); + _perfTimePhysicsProcess.Clear(); + _perfCamMsSum = 0; + _perfLastFrameTick = Stopwatch.GetTimestamp(); + } + } + _wasNetConnected = nowConnected; + + if (_screenMode == ClientScreenMode.Lobby) + { + _frameEvents.Clear(); + _session.DrainSimEvents(_frameEvents); + UpdateLobbyOrMenuOrbitCamera(_mapKind, _session.ViewState.Terrain); + _terrain.UpdateTileLod(_camera.GlobalPosition); + _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap); + if (_mapKind == ArenaMapKind.Sion) + { + _sionMap.UpdateLod(_camera.GlobalPosition); + } + _lobbyScreen.Sync(_session); + return; + } + + if (_perfTargetFrames > 0) + { + if (_session.ConnectionStatus.Mode == NetworkMode.RemoteClient && !nowConnected && _perfWaitConnectFrames < 300) + { + _perfWaitConnectFrames++; + _perfLastFrameTick = Stopwatch.GetTimestamp(); + return; + } + double toMs = 1000.0 / Stopwatch.Frequency; + long tt0 = Stopwatch.GetTimestamp(); + _terrain.UpdateTileLod(_camera.GlobalPosition); + _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap); + long tt1 = Stopwatch.GetTimestamp(); + _arena.Sync(_session, _elapsedSeconds, (float)delta, alpha); + DrainAndFanSimEvents((float)delta, alpha); + long ta1 = Stopwatch.GetTimestamp(); + _perfPendingTerrainMs = (tt1 - tt0) * toMs; + _perfPendingArenaMs = (ta1 - tt1) * toMs; + + long tc0 = Stopwatch.GetTimestamp(); + UpdateCamera((float)delta, alpha); + _audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha); + _terrain.UpdateTileLod(_camera.GlobalPosition); + if (_mapKind == ArenaMapKind.Sion) + { + _sionMap.UpdateLod(_camera.GlobalPosition); + } + long th0 = Stopwatch.GetTimestamp(); + var localP = _session.LocalContender; + float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f; + _hud.ConsumeEvents(_frameEvents, _session.LocalContenderId, coreRatio, localP.MaxThermalRatio); + _hud.Sync(_session); + long th1 = Stopwatch.GetTimestamp(); + _perfCamMsSum += (th0 - tc0) * toMs; + double hudMs = (th1 - th0) * toMs; + + long now = Stopwatch.GetTimestamp(); + double frameMs = (now - _perfLastFrameTick) * 1000.0 / Stopwatch.Frequency; + _perfLastFrameTick = now; + + _perfFrameMs.Add(frameMs); + _perfPhysicsStepMs.Add(_perfPendingStepMs); + _perfTerrainSyncMs.Add(_perfPendingTerrainMs); + _perfArenaSyncMs.Add(_perfPendingArenaMs); + _perfHudMs.Add(hudMs); + _perfPendingStepMs = 0; + _perfPendingTerrainMs = 0; + _perfPendingArenaMs = 0; + + int rebakesNow = _terrain.DirtyRebakes; + _perfDirtyRebakeDelta.Add(rebakesNow - _perfLastDirtyRebakes); + _perfLastDirtyRebakes = rebakesNow; + + _perfDrawCalls.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalDrawCallsInFrame)); + _perfPrimitives.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalPrimitivesInFrame)); + _perfObjects.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalObjectsInFrame)); + _perfNodeCount.Add(Performance.GetMonitor(Performance.Monitor.ObjectNodeCount)); + _perfTimeProcess.Add(Performance.GetMonitor(Performance.Monitor.TimeProcess) * 1000.0); + _perfTimePhysicsProcess.Add(Performance.GetMonitor(Performance.Monitor.TimePhysicsProcess) * 1000.0); + if (ArenaSession.PerfEnabled) + { + _perfViewportGpuMs.Add(RenderingServer.ViewportGetMeasuredRenderTimeGpu(GetViewport().GetViewportRid())); + } + + _perfFrameCount++; + if (_perfFrameCount >= _perfTargetFrames) + { + PrintPerfSummaryAndQuit(); + } + } + else + { + _terrain.UpdateTileLod(_camera.GlobalPosition); + _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap); + _arena.Sync(_session, _elapsedSeconds, (float)delta, alpha); + DrainAndFanSimEvents((float)delta, alpha); + UpdateCamera((float)delta, alpha); + _audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha); + _terrain.UpdateTileLod(_camera.GlobalPosition); + if (_mapKind == ArenaMapKind.Sion) + { + _sionMap.UpdateLod(_camera.GlobalPosition); + } + var localP = _session.LocalContender; + float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f; + _hud.ConsumeEvents(_frameEvents, _session.LocalContenderId, coreRatio, localP.MaxThermalRatio); + _hud.Sync(_session); + } + } + + private void SaveMenuPreviewAndQuit() + { + if (!string.IsNullOrWhiteSpace(_menuPreviewOut) && DisplayServer.GetName() != "headless") + { + var img = GetViewport().GetTexture()?.GetImage(); + if (img is not null) + { + var err = img.SavePng(_menuPreviewOut); + GD.Print($"MENU PREVIEW SAVED: {_menuPreviewOut} ({img.GetWidth()}x{img.GetHeight()}, err={err})"); + } + } + GetTree().Quit(0); + } + + private void DrainAndFanSimEvents(float dt, float alpha) + { + if (_session is null) + { + return; + } + _frameEvents.Clear(); + _session.DrainSimEvents(_frameEvents); + + _frameFootsteps.Clear(); + _footsteps.StepSession(_session, dt, alpha, _frameFootsteps, ResolveLiveWalkerFootWorld); + + _arena.ConsumeEvents(_session, _frameEvents, _frameFootsteps, dt, SampleCurrentMapGroundTint); + + var local = _session.LocalContender; + if (local.Lifecycle == ContenderLifecycle.Deploying && _prevLocalLifecycle != ContenderLifecycle.Deploying) + { + _cameraPitch = Mathf.DegToRad(34f); + _orbitalPodCamBlend = 1.0f; + } + _prevLocalLifecycle = local.Lifecycle; + + var localPos = new System.Numerics.Vector3(local.X, local.Y, local.Z); + _camJuice.ConsumeEvents(_frameEvents, _session.LocalContenderId, localPos, _session); + _camJuice.ConsumeFootsteps(_frameFootsteps, _session.LocalContenderId); + OrbitalPodPhase localPodPhase = OrbitalPodPhase.Freefall; + float camHorizSpeed = local.Speed; + if (local.IsInDropPod) + { + var pods = _session.ActivePods; + for (int i = 0; i < pods.Count; i++) + { + if (pods[i].PodKind == OrbitalPodKind.Contender && + pods[i].ContenderId == _session.LocalContenderId) + { + localPodPhase = pods[i].Phase; + camHorizSpeed = MathF.Sqrt(pods[i].VelX * pods[i].VelX + pods[i].VelZ * pods[i].VelZ); + if (pods[i].Phase == OrbitalPodPhase.RetroBurn) + { + _camJuice.ApplyOrbitalBurnRumble(1.0f); + } + break; + } + } + } + _camJuice.Update(dt, camHorizSpeed, local.Grid.Spec.IsVtol, local.IsInDropPod, localPodPhase); + } + + private static readonly Color DesertDustTint = new(0.76f, 0.59f, 0.40f, 1.0f); + + internal Color SampleCurrentMapGroundTint(float worldX, float worldZ) => + _mapKind == ArenaMapKind.Sion + ? _terrain.SampleGroundTint(worldX, worldZ) + : DesertDustTint; + + private System.Numerics.Vector3? ResolveLiveWalkerFootWorld(bool isContender, int id, int legIndex) + { + VehicleVisualInstance? vis = isContender + ? _arena.GetContenderVisual(id) + : _arena.GetSpectatorVisual(id); + if (vis is null || vis.IsStaticLod || vis.RigState?.WalkerRig is not { } rig) + { + return null; + } + if ((uint)legIndex >= (uint)rig.Legs.Length) + { + return null; + } + Node3D footNode = rig.Legs[legIndex].Foot.Node; + if (!GodotObject.IsInstanceValid(footNode) || !footNode.IsInsideTree()) + { + return null; + } + Vector3 p = footNode.GlobalPosition; + return new System.Numerics.Vector3(p.X, p.Y, p.Z); + } + + private void PrintPerfSummaryAndQuit() + { + static double Avg(List v) + { + if (v.Count == 0) return 0; + double s = 0; + foreach (double x in v) s += x; + return s / v.Count; + } + static double P95(List v) + { + if (v.Count == 0) return 0; + var sorted = new List(v); + sorted.Sort(); + int idx = Math.Clamp((int)Math.Ceiling(sorted.Count * 0.95) - 1, 0, sorted.Count - 1); + return sorted[idx]; + } + double totalMs = 0; + foreach (double x in _perfFrameMs) totalMs += x; + double fps = totalMs > 0 ? (_perfFrameMs.Count * 1000.0 / totalMs) : 0; + double rebakeAvg = 0; + int rebakeTotal = 0; + foreach (int r in _perfDirtyRebakeDelta) rebakeTotal += r; + rebakeAvg = _perfDirtyRebakeDelta.Count > 0 ? (double)rebakeTotal / _perfDirtyRebakeDelta.Count : 0; + + double steadyMs = 0; + int steadyCount = Math.Max(0, _perfFrameMs.Count - 10); + for (int i = 10; i < _perfFrameMs.Count; i++) steadyMs += _perfFrameMs[i]; + double steadyAvgMs = steadyCount > 0 ? steadyMs / steadyCount : 0; + double steadyFps = steadyAvgMs > 0 ? 1000.0 / steadyAvgMs : 0; + + GD.Print("=== PERF BENCHMARK SUMMARY ==="); + GD.Print($"Frames={_perfFrameMs.Count} PhysicsTicks={_perfPhysicsTicks} AvgFPS={fps:F2} SteadyFPS(10..{_perfFrameMs.Count - 1})={steadyFps:F2} EngineFPS={Engine.GetFramesPerSecond():F1}"); + GD.Print($"frameMs: avg={Avg(_perfFrameMs):F2} steadyAvg={steadyAvgMs:F2} p95={P95(_perfFrameMs):F2}"); + GD.Print($"physicsStepMs/frame: avg={Avg(_perfPhysicsStepMs):F2} p95={P95(_perfPhysicsStepMs):F2}"); + GD.Print($"terrainSyncMs/frame: avg={Avg(_perfTerrainSyncMs):F2} p95={P95(_perfTerrainSyncMs):F2} dirtyRebakesTotal={rebakeTotal} dirtyRebakesAvg={rebakeAvg:F2}"); + GD.Print($"arenaSyncMs/frame: avg={Avg(_perfArenaSyncMs):F2} p95={P95(_perfArenaSyncMs):F2}"); + GD.Print($"hudMs/frame: avg={Avg(_perfHudMs):F2} p95={P95(_perfHudMs):F2}"); + GD.Print($"RenderTotalDrawCallsInFrame: avg={Avg(_perfDrawCalls):F0} max={P95(_perfDrawCalls):F0}"); + GD.Print($"RenderTotalPrimitivesInFrame: avg={Avg(_perfPrimitives):F0}"); + GD.Print($"RenderTotalObjectsInFrame: avg={Avg(_perfObjects):F0}"); + GD.Print($"ObjectNodeCount: avg={Avg(_perfNodeCount):F0}"); + GD.Print($"TimeProcessMs: avg={Avg(_perfTimeProcess):F2}"); + GD.Print($"TimePhysicsProcessMs: avg={Avg(_perfTimePhysicsProcess):F2}"); + GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count:F2}"); + int ticks = Math.Max(1, _perfPhysicsTicks); + GD.Print($"StepBreakdownMs/tick: ring={ArenaSession.PerfRingMs / ticks:F2} ai={ArenaSession.PerfAiMs / ticks:F2} drive={ArenaSession.PerfDriveMs / ticks:F2} world={ArenaSession.PerfWorldMs / ticks:F2} sync={ArenaSession.PerfBodySyncMs / ticks:F2} detect={ArenaSession.PerfDetectMs / ticks:F2} weapons={ArenaSession.PerfWeaponsMs / ticks:F2}"); + GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} gpuSparksEmitted={_arena.GpuSparks.TotalEmittedCount} volEmitters={_arena.Volumetrics.ActiveEmitterCount} volImpulses={_arena.Volumetrics.ActiveImpulseCount} flashLightsPeak={_arena.Particles.PeakFlashLightCount} tracers={_session?.ViewState.Tracers.Count ?? 0}"); + if (_atmosphere.VolumetricEffect is { } volFx) + { + Rid vpRid = GetViewport().GetViewportRid(); + double vpGpuMs = RenderingServer.ViewportGetMeasuredRenderTimeGpu(vpRid); + double vpCpuMs = RenderingServer.ViewportGetMeasuredRenderTimeCpu(vpRid); + GD.Print($"Cut10bGpuMs: total={volFx.LastTotalGpuMs:F3} flow={volFx.LastFlowGpuMs:F3} cull={volFx.LastCullGpuMs:F3} march={volFx.LastMarchGpuMs:F3} comp={volFx.LastCompGpuMs:F3} marchSize={volFx.LastMarchSize.X}x{volFx.LastMarchSize.Y} maxSteps={volFx.CurrentMaxSteps} maxIter={volFx.CurrentMaxIter} vfxRes={_graphicsSettings.VfxResolution} volSamples={_graphicsSettings.VolumetricSamples} sdfgi={_graphicsSettings.SdfgiQuality} viewportGpuMs={vpGpuMs:F2} viewportCpuMs={vpCpuMs:F2}"); + if (_perfViewportGpuMs.Count > 10) + { + var steadyGpu = new List(_perfViewportGpuMs.Count - 10); + for (int i = 10; i < _perfViewportGpuMs.Count; i++) steadyGpu.Add(_perfViewportGpuMs[i]); + steadyGpu.Sort(); + double gpuP50 = steadyGpu[(int)Math.Clamp(Math.Floor(steadyGpu.Count * 0.50), 0, steadyGpu.Count - 1)]; + double gpuP95 = steadyGpu[(int)Math.Clamp(Math.Ceiling(steadyGpu.Count * 0.95) - 1, 0, steadyGpu.Count - 1)]; + double gpuMax = steadyGpu[^1]; + GD.Print($"viewportGpuMsTimeline(10..{_perfViewportGpuMs.Count - 1}): avg={Avg(steadyGpu):F2} p50={gpuP50:F2} p95={gpuP95:F2} max={gpuMax:F2}"); + } + } + if (_hud?.HbCanvas is { } hb) + { + GD.Print($"HbGpuHud: drawCalls={hb.LastDrawCallCount} quads={hb.LastQuadCount} gpuMs={hb.LastHbGpuMs:F4}"); + } + if (_session is not null) + { + var net = _session.ConnectionStatus; + uint snapSeq = _session is RemoteArenaSession remote ? remote.LastSnapshotSeq : 0u; + GD.Print($"NetStatus: mode={net.Mode} connected={net.Connected} localSlot={_session.LocalContenderId} pingMs={net.PingMs} humans={net.ConnectedHumans}/{net.MaxHumans} snapshotSeq={snapSeq} label='{net.StateLabel}'"); + } + if (_mapKind == ArenaMapKind.Sion) + { + GD.Print($"SionMap: terrainTiles={_terrain.BakedTileCount} gpuScarSlots={_terrain.ActiveGpuScarSlots} bldgTiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}"); + } + foreach (var kv in _arena.AssetCache.Vehicles) + { + int tris = 0; + var bm = kv.Value.BakedStaticMesh; + for (int s = 0; s < bm.GetSurfaceCount(); s++) + { + var arr = bm.SurfaceGetArrays(s); + if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array) + tris += arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length / 3; + } + int farTris = 0; + var fm = kv.Value.BakedLodFarMesh; + for (int s = 0; s < fm.GetSurfaceCount(); s++) + { + var arr = fm.SurfaceGetArrays(s); + if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array) + farTris += arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length / 3; + } + int nodes = CountSubtreeNodes(kv.Value.SceneTemplate); + GD.Print($" Vehicle '{kv.Key}': nodes={nodes} bakedTris={tris} farTris={farTris} surfs={bm.GetSurfaceCount()} farSurfs={fm.GetSurfaceCount()} detachChunks={kv.Value.DetachableParts.Count}"); + } + if (_arena.AssetCache.Vehicles.TryGetValue("paladin", out var palTpl)) + { + var names = new List(); + CollectNodeNames(palTpl.SceneTemplate, names, 40); + GD.Print($" Paladin sample nodes: {string.Join(", ", names)}"); + } + GD.Print("=== END PERF BENCHMARK ==="); + string? previewOut = System.Environment.GetEnvironmentVariable("RTD_PREVIEW_OUT"); + if (string.IsNullOrWhiteSpace(previewOut)) + { + previewOut = System.Environment.GetEnvironmentVariable("RTD_CAPTURE_PREVIEW"); + } + if (!string.IsNullOrWhiteSpace(previewOut) && DisplayServer.GetName() != "headless") + { + var img = GetViewport().GetTexture()?.GetImage(); + if (img is not null) + { + var err = img.SavePng(previewOut); + GD.Print($"PERF PREVIEW SAVED: {previewOut} ({img.GetWidth()}x{img.GetHeight()}, err={err})"); + } + } + GetTree().Quit(0); + } + + private static void CollectNodeNames(Node cur, List outNames, int limit) + { + if (outNames.Count >= limit) return; + outNames.Add($"{cur.Name}({cur.GetType().Name})"); + for (int i = 0; i < cur.GetChildCount(); i++) CollectNodeNames(cur.GetChild(i), outNames, limit); + } + + private static int CountSubtreeNodes(Node cur) + { + int n = 1; + for (int i = 0; i < cur.GetChildCount(); i++) n += CountSubtreeNodes(cur.GetChild(i)); + return n; + } + + private PlayerInput GatherPlayerInput() + { + var local = Session.LocalContender; + bool inPod = local.IsInDropPod; + var (aimX, aimY, aimZ) = inPod + ? (local.X + MathF.Sin(_cameraYaw) * 120f, local.Y - 40f, local.Z + MathF.Cos(_cameraYaw) * 120f) + : ComputeCenterScreenAim(); + + if (_hud.IsUiTextInputFocused || local.WaitingForRespawn) + { + return new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: aimX, + AimWorldZ: aimZ, + Fire: false, + InteractPickup: false, + Brake: false, + AimWorldY: aimY, + VerticalThrottle: 0f); + } + + float throttle = 0f; + if (Input.IsKeyPressed(Key.W) || Input.IsKeyPressed(Key.Up)) throttle += 1f; + if (Input.IsKeyPressed(Key.S) || Input.IsKeyPressed(Key.Down)) throttle -= 1f; + + float steer = 0f; + if (Input.IsKeyPressed(Key.D) || Input.IsKeyPressed(Key.Right)) steer += 1f; + if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) steer -= 1f; + + bool isVtol = !inPod && local.Grid.Spec.IsVtol; + float verticalThrottle = 0f; + if (!inPod) + { + if (Input.IsKeyPressed(Key.Space)) verticalThrottle += 1f; + if (Input.IsKeyPressed(Key.C) || Input.IsKeyPressed(Key.Ctrl)) verticalThrottle -= 1f; + } + + bool brake = !inPod && (isVtol ? Input.IsKeyPressed(Key.Shift) : Input.IsKeyPressed(Key.Space)); + bool pointerOnHud = Input.MouseMode != Input.MouseModeEnum.Captured && + (_hud.NetworkPanelOpen || _hud.IsPointerOverInteractiveHud(GetViewport().GetMousePosition())); + bool fire = !inPod && !pointerOnHud && Input.IsMouseButtonPressed(MouseButton.Left); + + return new PlayerInput( + Throttle: throttle, + Steer: steer, + AimWorldX: aimX, + AimWorldZ: aimZ, + Fire: fire, + InteractPickup: !inPod && _interactQueued, + Brake: brake, + AimWorldY: aimY, + VerticalThrottle: verticalThrottle); + } + + private (float AimX, float AimY, float AimZ) ComputeCenterScreenAim() + { + var player = Session.LocalContender; + var spec = player.Grid.Spec; + Vector2 screenSize = GetViewport().GetVisibleRect().Size; + if (screenSize.X < 2f || screenSize.Y < 2f) + { + return ( + player.X + MathF.Sin(_cameraYaw) * 40f, + player.Y, + player.Z + MathF.Cos(_cameraYaw) * 40f); + } + + Vector2 center = screenSize * 0.5f; + Vector3 rayOrigin = _hasBaseCamPose + ? _baseCamPos + _baseLookDir * _camera.Near + : _camera.ProjectRayOrigin(center); + Vector3 rayDir = _hasBaseCamPose + ? _baseLookDir + : _camera.ProjectRayNormal(center); + + const float maxAimDist = 450f; + ulong playerStableId = ContenderStableIdBase + (ulong)player.Id; + var (pPos, _, _) = Session.GetInterpolatedContenderPose(player.Id, 1f); + Vector3 playerCenter = new Vector3(pPos.X, pPos.Y, pPos.Z); + float camToCenterProj = (playerCenter - rayOrigin).Dot(rayDir); + float minForwardDot = -MathF.Max(spec.HalfWidth, spec.HalfLength) * 0.35f; + + bool IsValidForwardHit(Vector3 pt, float distFromCam) => + (pt - playerCenter).Dot(rayDir) >= minForwardDot && + distFromCam >= camToCenterProj - 0.5f; + + Vector3 castOrigin = rayOrigin; + float remainingDist = maxAimDist; + float boxDist = maxAimDist; + Vector3 boxHitPt = Vector3.Zero; + bool hasBoxHit = false; + + // Cast against session world, skipping the player's own chassis and any surface behind the vehicle's forward plane. + for (int attempt = 0; attempt < 4 && remainingDist > 1f; attempt++) + { + var hit = Session.CastWorldRayClosest( + new System.Numerics.Vector3(castOrigin.X, castOrigin.Y, castOrigin.Z), + new System.Numerics.Vector3(rayDir.X * remainingDist, rayDir.Y * remainingDist, rayDir.Z * remainingDist)); + if (!hit.Hit) + { + break; + } + + var pt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z); + float distFromCam = rayOrigin.DistanceTo(pt); + if (hit.StableId == playerStableId || !IsValidForwardHit(pt, distFromCam)) + { + float skip = distFromCam + 0.4f; + castOrigin = rayOrigin + rayDir * skip; + remainingDist = MathF.Max(1f, maxAimDist - skip); + continue; + } + + boxHitPt = pt; + boxDist = distFromCam; + hasBoxHit = true; + break; + } + + float terrainStartDist = 0f; + bool hasTerrainHit = false; + float tx = 0f, ty = 0f, tz = 0f, terrainDist = maxAimDist; + for (int attempt = 0; attempt < 2 && terrainStartDist < boxDist; attempt++) + { + Vector3 tOrigin = rayOrigin + rayDir * terrainStartDist; + float tMaxDist = boxDist - terrainStartDist; + if (!Session.ViewState.Terrain.Raycast( + tOrigin.X, tOrigin.Y, tOrigin.Z, + rayDir.X, rayDir.Y, rayDir.Z, + maxDistance: tMaxDist, + out float hx, out float hy, out float hz, out float localDist)) + { + break; + } + + float totalDist = terrainStartDist + localDist; + var hitPt = new Vector3(hx, hy, hz); + if (!IsValidForwardHit(hitPt, totalDist)) + { + terrainStartDist = MathF.Max(totalDist + 0.5f, camToCenterProj - 0.4f); + continue; + } + + tx = hx; + ty = hy; + tz = hz; + terrainDist = totalDist; + hasTerrainHit = true; + break; + } + + if (hasTerrainHit && terrainDist <= boxDist) + { + return (tx, ty, tz); + } + + if (hasBoxHit) + { + return (boxHitPt.X, boxHitPt.Y, boxHitPt.Z); + } + + Vector3 farPt = rayOrigin + rayDir * 320f; + return (farPt.X, farPt.Y, farPt.Z); + } + + private void UpdateCamera(float dt, float alpha) + { + var p = Session.LocalContender; + var spec = p.Grid.Spec; + var (posInterp, _, _) = Session.GetInterpolatedContenderPose(p.Id, alpha); + + Vector3 camRight = new(-MathF.Cos(_cameraYaw), 0f, MathF.Sin(_cameraYaw)); + Vector3 camFwdHoriz = new(MathF.Sin(_cameraYaw), 0f, MathF.Cos(_cameraYaw)); + + Vector3 camPos; + Vector3 lookDir; + + if (p.WaitingForRespawn) + { + _dropReticleMesh.Visible = false; + float orbitRadius = MathF.Min(Session.ViewState.Spectators.SafeRadius * 0.45f, 165f); + float orbitAngle = _elapsedSeconds * 0.14f + _cameraYaw; + float ox = MathF.Cos(orbitAngle) * orbitRadius; + float oz = MathF.Sin(orbitAngle) * orbitRadius; + float oy = Session.ViewState.Terrain.SampleHeight(ox, oz) + 75f; + camPos = new Vector3(ox, MathF.Max(oy, 110f), oz); + float centerY = Session.ViewState.Terrain.SampleHeight(0f, 0f) + 12f; + lookDir = (new Vector3(0f, centerY, 0f) - camPos).Normalized(); + } + else if (p.IsInDropPod) + { + // Live landing ring reticle directly under the descending pod + float surfY = Session.ViewState.Terrain.SampleHeight(posInterp.X, posInterp.Z); + var (nx, ny, nz) = Session.ViewState.Terrain.SampleNormal(posInterp.X, posInterp.Z); + if (_mapKind == ArenaMapKind.Sion && Session.ViewState.SionMap is { } sm && + sm.TryGetBuildingAt(posInterp.X, posInterp.Z, 1.6f, out var bldg)) + { + if (bldg.RoofY > surfY && posInterp.Y >= bldg.RoofY - 1.0f) + { + surfY = bldg.RoofY; + nx = 0f; ny = 1f; nz = 0f; + } + } + Vector3 surfNorm = new Vector3(nx, ny, nz).Normalized(); + if (surfNorm.LengthSquared() < 1e-4f) surfNorm = Vector3.Up; + Vector3 upRef = MathF.Abs(surfNorm.Y) > 0.92f ? Vector3.Forward : Vector3.Up; + Vector3 rRight = upRef.Cross(surfNorm).Normalized(); + Vector3 rFwd = surfNorm.Cross(rRight).Normalized(); + float pulse = 1.0f + 0.08f * MathF.Sin(_elapsedSeconds * 7.5f); + _dropReticleMesh.Visible = true; + _dropReticleMesh.GlobalTransform = new Transform3D( + new Basis(rRight, surfNorm, rFwd) * Basis.FromScale(new Vector3(pulse, 1f, pulse)), + new Vector3(posInterp.X, surfY + 0.35f, posInterp.Z)); + + _orbitalPodCamBlend = 1.0f; + float backDist = 28.0f * _cameraZoom; + Vector3 pivot = new(posInterp.X, posInterp.Y + 4.0f, posInterp.Z); + lookDir = (camFwdHoriz * MathF.Cos(_cameraPitch) - Vector3.Up * MathF.Sin(_cameraPitch)).Normalized(); + + float effectiveRight = 1.6f; + if (CastStaticCameraRay(pivot, camRight, effectiveRight, out float rightHitDist)) + { + effectiveRight = MathF.Min(effectiveRight, SafeCameraPullbackDist(rightHitDist)); + } + Vector3 shoulderPos = pivot + camRight * effectiveRight; + + float effectiveBack = backDist; + if (CastStaticCameraRay(shoulderPos, -lookDir, backDist, out float backHitDist)) + { + effectiveBack = MathF.Min(effectiveBack, SafeCameraPullbackDist(backHitDist)); + } + camPos = shoulderPos - lookDir * effectiveBack; + float minTerrainY = Session.ViewState.Terrain.SampleHeight(camPos.X, camPos.Z) + 2.2f; + if (camPos.Y < minTerrainY) camPos.Y = minTerrainY; + _smoothedShoulderY = pivot.Y; + } + else + { + _dropReticleMesh.Visible = false; + if (_orbitalPodCamBlend > 0.001f && dt > 0f && dt < 0.5f) + { + float targetPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(8f) : Mathf.DegToRad(12f); + _cameraPitch = Mathf.Lerp(_cameraPitch, targetPitch, 1f - MathF.Exp(-dt * 4.0f)); + _orbitalPodCamBlend *= MathF.Exp(-dt * 4.5f); + if (_orbitalPodCamBlend < 0.005f) _orbitalPodCamBlend = 0f; + } + + float rightOffset = MathF.Max(1.6f, spec.HalfWidth * 1.15f + 0.8f); + float heightOffset = spec.HalfHeight * 1.45f + 1.4f; + float boundingR = MathF.Max(spec.HalfWidth, MathF.Max(spec.HalfHeight * 0.72f, spec.HalfLength * 0.90f)); + float backDist = Math.Clamp(boundingR * 2.15f + 4.2f, 7.2f, 19.5f) * _cameraZoom; + if (_orbitalPodCamBlend > 0f) + { + backDist = Mathf.Lerp(backDist, 22.0f * _cameraZoom, _orbitalPodCamBlend); + heightOffset = Mathf.Lerp(heightOffset, heightOffset + 2.2f, _orbitalPodCamBlend); + } + float targetShoulderY = (posInterp.Y - spec.HalfHeight) + heightOffset; + + if (_lastCamChassisId != spec.Id || dt >= 1f) + { + _smoothedShoulderY = targetShoulderY; + _lastCamChassisId = spec.Id; + } + else + { + float yBlend = 1f - MathF.Exp(-dt * 24f); + _smoothedShoulderY = Mathf.Lerp(_smoothedShoulderY, targetShoulderY, yBlend); + } + + var pivot = new Vector3(posInterp.X, _smoothedShoulderY, posInterp.Z); + lookDir = (camFwdHoriz * MathF.Cos(_cameraPitch) - Vector3.Up * MathF.Sin(_cameraPitch)).Normalized(); + + // Segment 1: sweep terrain + static Box3D (StableId < ContenderStableIdBase) from pivot along camRight * rightOffset + float effectiveRight = rightOffset; + if (CastStaticCameraRay(pivot, camRight, rightOffset, out float rightHitDist)) + { + effectiveRight = MathF.Min(effectiveRight, SafeCameraPullbackDist(rightHitDist)); + } + Vector3 shoulderPos = pivot + camRight * effectiveRight; + + // Segment 2: sweep terrain + static Box3D from shoulderPos along -lookDir * backDist + float effectiveBack = backDist; + if (CastStaticCameraRay(shoulderPos, -lookDir, backDist, out float backHitDist)) + { + effectiveBack = MathF.Min(effectiveBack, SafeCameraPullbackDist(backHitDist)); + } + + camPos = shoulderPos - lookDir * effectiveBack; + + float minTerrainY = Session.ViewState.Terrain.SampleHeight(camPos.X, camPos.Z) + 1.2f; + if (camPos.Y < minTerrainY) + { + camPos.Y = minTerrainY; + } + + // Segment 3: verify direct pivot -> camPos LOS against static terrain/buildings so stepped wings cannot occlude player + Vector3 pivotToCam = camPos - pivot; + float pivotToCamDist = pivotToCam.Length(); + if (pivotToCamDist > 0.05f) + { + Vector3 pivotToCamDir = pivotToCam / pivotToCamDist; + if (CastStaticCameraRay(pivot, pivotToCamDir, pivotToCamDist, out float wingHitDist)) + { + camPos = pivot + pivotToCamDir * SafeCameraPullbackDist(wingHitDist); + } + } + } + + _baseCamPos = camPos; + _baseLookDir = lookDir; + _hasBaseCamPose = true; + + float targetFov = CameraJuiceState.BaseFovDeg + _camJuice.FovOffsetDeg; + if (MathF.Abs(_camera.Fov - targetFov) > 0.005f) + { + _camera.Fov = targetFov; + } + + if (_camJuice.IsIdle) + { + _camera.GlobalPosition = camPos; + _camera.LookAt(camPos + lookDir * 60f, Vector3.Up); + return; + } + + _camJuice.ComputeOffsets( + out System.Numerics.Vector3 jOff, + out float pitchOffRad, + out float yawOffRad, + out float rollOffRad); + + Vector3 juicedCamPos = camPos + + camRight * jOff.X + + Vector3.Up * jOff.Y + - lookDir * jOff.Z; + + Vector3 juiceDelta = juicedCamPos - camPos; + float juiceDist = juiceDelta.Length(); + if (juiceDist > 0.02f) + { + Vector3 juiceDir = juiceDelta / juiceDist; + if (CastStaticCameraRay(camPos, juiceDir, juiceDist, out float juiceHitDist)) + { + juicedCamPos = camPos + juiceDir * SafeCameraPullbackDist(juiceHitDist); + } + } + + float minJuicedY = Session.ViewState.Terrain.SampleHeight(juicedCamPos.X, juicedCamPos.Z) + 1.15f; + if (juicedCamPos.Y < minJuicedY) + { + juicedCamPos.Y = minJuicedY; + } + + Vector3 juicedLookDir = lookDir; + if (MathF.Abs(yawOffRad) > 1e-6f) + { + juicedLookDir = juicedLookDir.Rotated(Vector3.Up, yawOffRad); + } + if (MathF.Abs(pitchOffRad) > 1e-6f) + { + Vector3 pitchAxis = Vector3.Up.Cross(juicedLookDir); + if (pitchAxis.LengthSquared() > 1e-6f) + { + juicedLookDir = juicedLookDir.Rotated(pitchAxis.Normalized(), pitchOffRad); + } + } + juicedLookDir = juicedLookDir.Normalized(); + + Vector3 camUp = MathF.Abs(rollOffRad) > 1e-6f + ? Vector3.Up.Rotated(juicedLookDir, rollOffRad) + : Vector3.Up; + + _camera.GlobalPosition = juicedCamPos; + _camera.LookAt(juicedCamPos + juicedLookDir * 60f, camUp); + } + + private static float SafeCameraPullbackDist(float rawDist) => + MathF.Max(0.0f, rawDist - MathF.Min(0.35f, MathF.Max(0.08f, rawDist * 0.25f))); + + private bool CastStaticCameraRay(Vector3 origin, Vector3 dir, float maxDist, out float hitDist) + { + hitDist = maxDist; + if (maxDist <= 0.01f) + { + return false; + } + + bool hasHit = false; + if (Session.ViewState.Terrain.Raycast( + origin.X, origin.Y, origin.Z, + dir.X, dir.Y, dir.Z, + maxDist, + out _, out _, out _, out float terrainDist)) + { + hitDist = MathF.Min(hitDist, terrainDist); + hasHit = true; + } + + Vector3 castOrigin = origin; + float skipped = 0f; + float remaining = hitDist; + for (int attempt = 0; attempt < 16 && remaining > 0.05f; attempt++) + { + var hit = Session.CastWorldRayClosest( + new System.Numerics.Vector3(castOrigin.X, castOrigin.Y, castOrigin.Z), + new System.Numerics.Vector3(dir.X * remaining, dir.Y * remaining, dir.Z * remaining)); + if (!hit.Hit) + { + break; + } + + var pt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z); + float distFromOrigin = origin.DistanceTo(pt); + if (ArenaSession.IsStaticWorldStableId(hit.StableId)) + { + if (distFromOrigin < hitDist) + { + hitDist = distFromOrigin; + hasHit = true; + } + break; + } + + float nextSkip = MathF.Max(distFromOrigin + 0.15f, skipped + 0.5f); + if (nextSkip >= hitDist) + { + break; + } + skipped = nextSkip; + castOrigin = origin + dir * skipped; + remaining = hitDist - skipped; + } + + return hasHit; + } + + private void OnEquipCargo(int cargoIndex, string hardpointId) + { + _session?.RequestEquipCargo(cargoIndex, hardpointId); + } + + private (bool Valid, bool InFront, Vector2 ScreenPos, System.Numerics.Vector3 CamLocal) ProjectWorldToHud(System.Numerics.Vector3 worldPos) + { + if (_camera is null || !GodotObject.IsInstanceValid(_camera) || !_camera.IsInsideTree()) + { + return (false, false, Vector2.Zero, System.Numerics.Vector3.Zero); + } + var wp = new Vector3(worldPos.X, worldPos.Y, worldPos.Z); + Transform3D camXform = _camera.GlobalTransform; + Vector3 rel = wp - camXform.Origin; + Basis b = camXform.Basis; + // Godot Camera3D local axes: +X = right, +Y = up, -Z = forward + float localRight = rel.Dot(b.X); + float localUp = rel.Dot(b.Y); + float localForward = -rel.Dot(b.Z); + var camLocal = new System.Numerics.Vector3(localRight, localUp, localForward); + + if (localForward <= 0.1f) + { + return (true, false, Vector2.Zero, camLocal); + } + + Vector2 sp = _camera.UnprojectPosition(wp); + if (!float.IsFinite(sp.X) || !float.IsFinite(sp.Y)) + { + return (true, false, Vector2.Zero, camLocal); + } + return (true, true, sp, camLocal); + } +} diff --git a/client/Main.tscn b/client/Main.tscn new file mode 100644 index 0000000..4285746 --- /dev/null +++ b/client/Main.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://Main.cs" id="1"] + +[node name="Main" type="Node3D"] +script = ExtResource("1") diff --git a/client/MainMenu.cs b/client/MainMenu.cs new file mode 100644 index 0000000..2e1ec20 --- /dev/null +++ b/client/MainMenu.cs @@ -0,0 +1,487 @@ +using System; +using System.Globalization; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Industrial Imperial main menu overlay over the live Sion 3D orbit backdrop, +/// plus the in-match [ESC] pause overlay. +/// +public sealed partial class MainMenu : CanvasLayer +{ + public enum OverlayKind + { + Hidden, + MainMenu, + PauseOverlay + } + + private Control _mainRoot = null!; + private ImperialChromePanel _menuPanel = null!; + private ImperialChromePanel _hostPanel = null!; + private LineEdit _callsignEdit = null!; + private OptionButton _soloSquadOption = null!; + private Label _statusLabel = null!; + + private LineEdit _serverNameEdit = null!; + private LineEdit _portEdit = null!; + private OptionButton _hostMapOption = null!; + private OptionButton _hostSquadOption = null!; + private CheckBox _listPublicCheck = null!; + private Label _directoryHintLabel = null!; + private Label _hostErrorLabel = null!; + + private Control _pauseRoot = null!; + private Label _pauseContextLabel = null!; + + private OverlayKind _overlayKind = OverlayKind.Hidden; + private string _directoryUrl = string.Empty; + + public MainMenu() + { + Layer = 20; + } + + public event Action? PlaySoloRequested; + public event Action? ServerBrowserRequested; + public event Action? HostLobbyRequested; + public event Action? CallsignChanged; + public event Action? QuitRequested; + public event Action? ResumeRequested; + public event Action? ReturnToMainMenuRequested; + public event Action? SettingsRequested; + + public bool IsHostPanelOpen => _hostPanel is not null && _hostPanel.Visible; + public bool IsTextInputFocused => + Visible && _overlayKind == OverlayKind.MainMenu && + (_callsignEdit.HasFocus() || _serverNameEdit.HasFocus() || _portEdit.HasFocus()); + public string Callsign => SanitizeCallsign(_callsignEdit?.Text); + + public override void _Ready() + { + BuildMainRoot(); + BuildPauseRoot(); + SetOverlayKind(OverlayKind.Hidden); + } + + public void SetOverlayKind(OverlayKind kind) + { + _overlayKind = kind; + Visible = kind != OverlayKind.Hidden; + if (_mainRoot is not null) + { + _mainRoot.Visible = kind == OverlayKind.MainMenu; + } + if (_pauseRoot is not null) + { + _pauseRoot.Visible = kind == OverlayKind.PauseOverlay; + } + if (kind != OverlayKind.MainMenu) + { + ReleaseTextFocus(); + } + } + + public void SetHostPanelOpen(bool open) + { + if (_hostPanel is null) return; + _hostPanel.Visible = open; + if (open) + { + _hostErrorLabel.Text = string.Empty; + _hostErrorLabel.Visible = false; + } + else + { + _serverNameEdit.ReleaseFocus(); + _portEdit.ReleaseFocus(); + } + } + + public void SetDefaults(string callsign, string directoryUrl, ArenaMapKind defaultMap = ArenaMapKind.Sion, int defaultPort = 3076, byte defaultSquadSize = 3) + { + _directoryUrl = directoryUrl ?? string.Empty; + if (_callsignEdit is not null) + { + _callsignEdit.Text = SanitizeCallsign(callsign); + } + int sqIdx = Math.Clamp((int)defaultSquadSize, 1, 4) - 1; + _soloSquadOption?.Select(sqIdx); + _hostSquadOption?.Select(sqIdx); + if (_portEdit is not null) + { + _portEdit.Text = defaultPort.ToString(CultureInfo.InvariantCulture); + } + if (_hostMapOption is not null) + { + _hostMapOption.Select(defaultMap == ArenaMapKind.Desert ? 1 : 0); + } + if (_directoryHintLabel is not null) + { + _directoryHintLabel.Text = string.IsNullOrWhiteSpace(_directoryUrl) + ? "Public directory disabled (empty URL)" + : $"Directory: {_directoryUrl}"; + } + } + + public byte SelectedSoloSquadSize => _soloSquadOption is not null + ? (byte)Math.Clamp(_soloSquadOption.Selected + 1, 1, 4) + : (byte)3; + + public byte SelectedHostSquadSize => _hostSquadOption is not null + ? (byte)Math.Clamp(_hostSquadOption.Selected + 1, 1, 4) + : (byte)3; + + public void SetStatus(string? message, bool isError = false) + { + if (_statusLabel is null) return; + if (string.IsNullOrWhiteSpace(message)) + { + _statusLabel.Visible = false; + _statusLabel.Text = string.Empty; + return; + } + _statusLabel.Text = message.Trim(); + _statusLabel.AddThemeColorOverride("font_color", isError ? ImperialChrome.RedCol : ImperialChrome.CyanCol); + _statusLabel.Visible = true; + } + + public void SetHostError(string? message) + { + if (_hostErrorLabel is null) return; + if (string.IsNullOrWhiteSpace(message)) + { + _hostErrorLabel.Visible = false; + _hostErrorLabel.Text = string.Empty; + return; + } + _hostErrorLabel.Text = message.Trim(); + _hostErrorLabel.Visible = true; + } + + public void SetPauseContext(string contextLine) + { + if (_pauseContextLabel is not null) + { + _pauseContextLabel.Text = contextLine; + } + } + + private void ReleaseTextFocus() + { + _callsignEdit?.ReleaseFocus(); + _serverNameEdit?.ReleaseFocus(); + _portEdit?.ReleaseFocus(); + } + + private void BuildMainRoot() + { + _mainRoot = new Control + { + Name = "MainMenuRoot", + MouseFilter = Control.MouseFilterEnum.Ignore + }; + _mainRoot.SetAnchorsPreset(Control.LayoutPreset.FullRect); + AddChild(_mainRoot); + + _menuPanel = ImperialChrome.CreatePanel(ImperialChrome.OrangeCol, cornerLen: 18f, borderPx: 2f, bgAlpha: 0.91f, padH: 20, padV: 18); + _menuPanel.Name = "MainMenuPanel"; + _menuPanel.AnchorLeft = 0f; + _menuPanel.AnchorTop = 0f; + _menuPanel.OffsetLeft = 48f; + _menuPanel.OffsetTop = 52f; + _menuPanel.OffsetRight = 458f; + _mainRoot.AddChild(_menuPanel); + + var vbox = new VBoxContainer(); + vbox.AddThemeConstantOverride("separation", 10); + _menuPanel.AddChild(vbox); + + vbox.AddChild(ImperialChrome.CreateLabel("IMPERIAL ORBITAL INSERTION • SECTOR 01", 11, ImperialChrome.GoldCol)); + + var title = ImperialChrome.CreateLabel("RUST TO DUST", 32, ImperialChrome.TextLight); + vbox.AddChild(title); + + vbox.AddChild(ImperialChrome.CreateLabel("SION 3KM ALPINE ARENA • BROKKR COMBAT CHASSIS", 11, ImperialChrome.TextMuted)); + vbox.AddChild(ImperialChrome.MakeRule()); + + // Callsign row + var callRow = new HBoxContainer(); + callRow.AddThemeConstantOverride("separation", 10); + vbox.AddChild(callRow); + + var callLbl = ImperialChrome.CreateLabel("CALLSIGN", 12, ImperialChrome.TextMuted); + callLbl.CustomMinimumSize = new Vector2(82f, 0f); + callRow.AddChild(callLbl); + + _callsignEdit = new LineEdit + { + Text = "Pilot", + MaxLength = 24, + PlaceholderText = "Pilot", + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + ImperialChrome.StyleLineEdit(_callsignEdit, ImperialChrome.CyanCol, 13); + _callsignEdit.TextChanged += txt => CallsignChanged?.Invoke(SanitizeCallsign(txt)); + callRow.AddChild(_callsignEdit); + + var squadRow = new HBoxContainer(); + squadRow.AddThemeConstantOverride("separation", 10); + vbox.AddChild(squadRow); + + var squadLbl = ImperialChrome.CreateLabel("SQUAD MODE", 12, ImperialChrome.TextMuted); + squadLbl.CustomMinimumSize = new Vector2(82f, 0f); + squadRow.AddChild(squadLbl); + + _soloSquadOption = CreateSquadOptionButton(); + _soloSquadOption.ItemSelected += idx => _hostSquadOption?.Select((int)idx); + squadRow.AddChild(_soloSquadOption); + + vbox.AddChild(ImperialChrome.MakeRule()); + + var playSionBtn = ImperialChrome.CreateButton("PLAY SOLO — SION", ImperialChrome.OliveCol, 14, 38f); + playSionBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Sion, Callsign, SelectedSoloSquadSize); + vbox.AddChild(playSionBtn); + + var playDesertBtn = ImperialChrome.CreateButton("PLAY SOLO — DESERT", ImperialChrome.OrangeCol, 14, 38f); + playDesertBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Desert, Callsign, SelectedSoloSquadSize); + vbox.AddChild(playDesertBtn); + + var browserBtn = ImperialChrome.CreateButton("SERVER BROWSER", ImperialChrome.CyanCol, 14, 38f); + browserBtn.Pressed += () => ServerBrowserRequested?.Invoke(Callsign); + vbox.AddChild(browserBtn); + + var hostBtn = ImperialChrome.CreateButton("HOST MATCH", ImperialChrome.GoldCol, 14, 38f); + hostBtn.Pressed += () => SetHostPanelOpen(!IsHostPanelOpen); + vbox.AddChild(hostBtn); + + var settingsBtn = ImperialChrome.CreateButton("SETTINGS", ImperialChrome.CyanCol, 14, 38f); + settingsBtn.Pressed += () => + { + SetHostPanelOpen(false); + SettingsRequested?.Invoke(); + }; + vbox.AddChild(settingsBtn); + + vbox.AddChild(ImperialChrome.MakeRule()); + + var quitBtn = ImperialChrome.CreateButton("QUIT", ImperialChrome.RedCol, 13, 34f); + quitBtn.Pressed += () => QuitRequested?.Invoke(); + vbox.AddChild(quitBtn); + + _statusLabel = ImperialChrome.CreateLabel(string.Empty, 11, ImperialChrome.CyanCol); + _statusLabel.AutowrapMode = TextServer.AutowrapMode.Word; + _statusLabel.Visible = false; + vbox.AddChild(_statusLabel); + + vbox.AddChild(ImperialChrome.CreateLabel("Data: swisstopo 3km Sion | CultNet UDP 3076", 10, ImperialChrome.TextMuted)); + + BuildHostPanel(); + } + + private void BuildHostPanel() + { + _hostPanel = ImperialChrome.CreatePanel(ImperialChrome.GoldCol, cornerLen: 16f, borderPx: 1.5f, bgAlpha: 0.93f, padH: 18, padV: 16); + _hostPanel.Name = "HostConfigPanel"; + _hostPanel.AnchorLeft = 0f; + _hostPanel.AnchorTop = 0f; + _hostPanel.OffsetLeft = 480f; + _hostPanel.OffsetTop = 132f; + _hostPanel.OffsetRight = 900f; + _hostPanel.Visible = false; + _mainRoot.AddChild(_hostPanel); + + var vbox = new VBoxContainer(); + vbox.AddThemeConstantOverride("separation", 10); + _hostPanel.AddChild(vbox); + + vbox.AddChild(ImperialChrome.CreateLabel("HOST PRE-MATCH LOBBY", 14, ImperialChrome.GoldCol)); + vbox.AddChild(ImperialChrome.MakeRule()); + + var nameRow = new HBoxContainer(); + nameRow.AddThemeConstantOverride("separation", 8); + vbox.AddChild(nameRow); + var srvLbl = ImperialChrome.CreateLabel("SERVER NAME", 11, ImperialChrome.TextMuted); + srvLbl.CustomMinimumSize = new Vector2(106f, 0f); + nameRow.AddChild(srvLbl); + _serverNameEdit = new LineEdit + { + Text = "Rust to Dust", + MaxLength = 48, + PlaceholderText = "Server Name", + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + ImperialChrome.StyleLineEdit(_serverNameEdit, ImperialChrome.GoldCol, 13); + nameRow.AddChild(_serverNameEdit); + + var portRow = new HBoxContainer(); + portRow.AddThemeConstantOverride("separation", 8); + vbox.AddChild(portRow); + var portLbl = ImperialChrome.CreateLabel("UDP PORT", 11, ImperialChrome.TextMuted); + portLbl.CustomMinimumSize = new Vector2(106f, 0f); + portRow.AddChild(portLbl); + _portEdit = new LineEdit + { + Text = "3076", + MaxLength = 5, + PlaceholderText = "3076", + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + ImperialChrome.StyleLineEdit(_portEdit, ImperialChrome.GoldCol, 13); + portRow.AddChild(_portEdit); + + var mapRow = new HBoxContainer(); + mapRow.AddThemeConstantOverride("separation", 8); + vbox.AddChild(mapRow); + var mapLbl = ImperialChrome.CreateLabel("DROP ZONE", 11, ImperialChrome.TextMuted); + mapLbl.CustomMinimumSize = new Vector2(106f, 0f); + mapRow.AddChild(mapLbl); + _hostMapOption = new OptionButton + { + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + _hostMapOption.AddItem("SION (3KM ALPINE)", 0); + _hostMapOption.AddItem("DESERT RING", 1); + _hostMapOption.Select(0); + ImperialChrome.StyleOptionButton(_hostMapOption, ImperialChrome.OliveCol, 13); + mapRow.AddChild(_hostMapOption); + + var hostSqRow = new HBoxContainer(); + hostSqRow.AddThemeConstantOverride("separation", 8); + vbox.AddChild(hostSqRow); + var hostSqLbl = ImperialChrome.CreateLabel("SQUAD MODE", 11, ImperialChrome.TextMuted); + hostSqLbl.CustomMinimumSize = new Vector2(106f, 0f); + hostSqRow.AddChild(hostSqLbl); + _hostSquadOption = CreateSquadOptionButton(); + hostSqRow.AddChild(_hostSquadOption); + + _listPublicCheck = new CheckBox + { + Text = "List on Public Directory", + ButtonPressed = false + }; + ImperialChrome.StyleCheckBox(_listPublicCheck, ImperialChrome.CyanCol, 12); + vbox.AddChild(_listPublicCheck); + + _directoryHintLabel = ImperialChrome.CreateLabel("Directory: https://eureka.gamecult.org/rtd-directory", 10, ImperialChrome.TextMuted); + _directoryHintLabel.AutowrapMode = TextServer.AutowrapMode.Word; + vbox.AddChild(_directoryHintLabel); + + _hostErrorLabel = ImperialChrome.CreateLabel(string.Empty, 11, ImperialChrome.RedCol); + _hostErrorLabel.AutowrapMode = TextServer.AutowrapMode.Word; + _hostErrorLabel.Visible = false; + vbox.AddChild(_hostErrorLabel); + + var btnRow = new HBoxContainer(); + btnRow.AddThemeConstantOverride("separation", 8); + vbox.AddChild(btnRow); + + var launchBtn = ImperialChrome.CreateButton("LAUNCH LOBBY", ImperialChrome.OliveCol, 13, 34f); + launchBtn.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; + launchBtn.Pressed += OnHostLaunchPressed; + btnRow.AddChild(launchBtn); + + var cancelBtn = ImperialChrome.CreateButton("CANCEL", ImperialChrome.BorderCol, 13, 34f); + cancelBtn.Pressed += () => SetHostPanelOpen(false); + btnRow.AddChild(cancelBtn); + } + + private void OnHostLaunchPressed() + { + if (!int.TryParse(_portEdit.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int port) || + port is < 1 or > 65535) + { + SetHostError("UDP port must be between 1 and 65535."); + return; + } + + string serverName = string.IsNullOrWhiteSpace(_serverNameEdit.Text) + ? "Rust to Dust" + : _serverNameEdit.Text.Trim(); + var mapKind = _hostMapOption.Selected == 1 ? ArenaMapKind.Desert : ArenaMapKind.Sion; + bool listPublic = _listPublicCheck.ButtonPressed; + + SetHostError(null); + HostLobbyRequested?.Invoke(port, serverName, mapKind, listPublic, Callsign, SelectedHostSquadSize); + } + + private static OptionButton CreateSquadOptionButton() + { + var opt = new OptionButton + { + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + opt.AddItem("FFA (1)", 0); + opt.AddItem("DUO (2)", 1); + opt.AddItem("TRIO (3)", 2); + opt.AddItem("QUAD (4)", 3); + opt.Select(2); + ImperialChrome.StyleOptionButton(opt, ImperialChrome.CyanCol, 13); + return opt; + } + + private void BuildPauseRoot() + { + _pauseRoot = new Control + { + Name = "PauseOverlayRoot", + MouseFilter = Control.MouseFilterEnum.Stop + }; + _pauseRoot.SetAnchorsPreset(Control.LayoutPreset.FullRect); + AddChild(_pauseRoot); + + var scrim = new ColorRect + { + Color = ImperialChrome.ScrimCol, + MouseFilter = Control.MouseFilterEnum.Stop + }; + scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect); + _pauseRoot.AddChild(scrim); + + var panel = ImperialChrome.CreatePanel(ImperialChrome.OrangeCol, cornerLen: 16f, borderPx: 2f, bgAlpha: 0.94f, padH: 20, padV: 18); + panel.Name = "PauseOverlayPanel"; + panel.AnchorLeft = 0.5f; + panel.AnchorRight = 0.5f; + panel.AnchorTop = 0.5f; + panel.AnchorBottom = 0.5f; + panel.OffsetLeft = -190f; + panel.OffsetRight = 190f; + panel.OffsetTop = -156f; + panel.OffsetBottom = 156f; + _pauseRoot.AddChild(panel); + + var vbox = new VBoxContainer(); + vbox.AddThemeConstantOverride("separation", 10); + panel.AddChild(vbox); + + vbox.AddChild(ImperialChrome.CreateLabel("TACTICAL PAUSE • [ESC]", 16, ImperialChrome.OrangeCol, HorizontalAlignment.Center)); + + _pauseContextLabel = ImperialChrome.CreateLabel("COMBAT ACTIVE", 11, ImperialChrome.TextMuted, HorizontalAlignment.Center); + vbox.AddChild(_pauseContextLabel); + vbox.AddChild(ImperialChrome.MakeRule()); + + var resumeBtn = ImperialChrome.CreateButton("RESUME", ImperialChrome.OliveCol, 14, 36f); + resumeBtn.Pressed += () => ResumeRequested?.Invoke(); + vbox.AddChild(resumeBtn); + + var settingsBtn = ImperialChrome.CreateButton("SETTINGS", ImperialChrome.CyanCol, 14, 36f); + settingsBtn.Pressed += () => SettingsRequested?.Invoke(); + vbox.AddChild(settingsBtn); + + var menuBtn = ImperialChrome.CreateButton("RETURN TO MAIN MENU", ImperialChrome.OrangeCol, 14, 36f); + menuBtn.Pressed += () => ReturnToMainMenuRequested?.Invoke(); + vbox.AddChild(menuBtn); + + var quitBtn = ImperialChrome.CreateButton("QUIT", ImperialChrome.RedCol, 13, 34f); + quitBtn.Pressed += () => QuitRequested?.Invoke(); + vbox.AddChild(quitBtn); + } + + private static string SanitizeCallsign(string? raw) + { + string trimmed = (raw ?? string.Empty).Trim(); + return string.IsNullOrEmpty(trimmed) ? "Pilot" : trimmed; + } +} diff --git a/client/MultiMeshPartPool.cs b/client/MultiMeshPartPool.cs new file mode 100644 index 0000000..5ed7689 --- /dev/null +++ b/client/MultiMeshPartPool.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Generic; +using Godot; + +namespace RustToDust.Client; + +/// +/// Unified MultiMeshInstance3D part pool sharing mech_paint.gdshader in vertex-material mode. +/// Collapses all live vehicle limbs, armor chunks, mounted gear, salvage drops, and tumbling debris +/// sharing the same single-surface into one +/// draw call with per-instance INSTANCE_CUSTOM = (scorch, heat_glow, role_tint_index, alpha). +/// +public partial class MultiMeshPartPool : Node3D +{ + private readonly record struct PendingInstance( + Transform3D Xform, + Color Custom, + bool WantsShadow, + Vector3 WorldCenter, + float ScaledRadius); + + private sealed class PoolBucket + { + public required ArrayMesh Mesh; + public required Vector3 LocalCenter; + public required float LocalRadius; + public required MultiMesh MultiMesh; + public required MultiMeshInstance3D Node; + public readonly List Pending = new(16); + } + + private readonly Dictionary _buckets = new(); + private readonly List _bucketList = new(); + private readonly Plane[] _frustumPlanes = new Plane[6]; + private ShaderMaterial _sharedMat = null!; + private bool _hasFrustum; + private Vector3 _camPos; + + public int BucketCount => _bucketList.Count; + public int ActiveBucketCount { get; private set; } + public int TotalSubmittedInstances { get; private set; } + + public override void _Ready() + { + Shader shader = GD.Load("res://mech_paint.gdshader") + ?? throw new InvalidOperationException("Failed to load res://mech_paint.gdshader for MultiMeshPartPool."); + _sharedMat = new ShaderMaterial { Shader = shader }; + _sharedMat.SetShaderParameter("use_vertex_material", true); + _sharedMat.SetShaderParameter("heat_emission_energy", 2.6f); + } + + public void EnsureInitialized() + { + if (_sharedMat is null) + { + _Ready(); + } + } + + public void BeginFrame(Camera3D? cam) + { + EnsureInitialized(); + TotalSubmittedInstances = 0; + + for (int i = 0; i < _bucketList.Count; i++) + { + _bucketList[i].Pending.Clear(); + } + + if (cam is not null && cam.IsInsideTree()) + { + _camPos = cam.GlobalPosition; + var planes = cam.GetFrustum(); + if (planes.Count >= 6) + { + for (int i = 0; i < 6; i++) + { + _frustumPlanes[i] = planes[i]; + } + _hasFrustum = true; + return; + } + } + _hasFrustum = false; + } + + public void Submit( + ArrayMesh mesh, + in Transform3D worldXform, + in Color customData, + bool wantsShadow) + { + if (mesh is null || mesh.GetSurfaceCount() == 0) + { + return; + } + + PoolBucket bucket = GetOrCreateBucket(mesh); + + Basis b = worldXform.Basis; + float maxScaleSq = MathF.Max( + b.Column0.LengthSquared(), + MathF.Max(b.Column1.LengthSquared(), b.Column2.LengthSquared())); + float scale = MathF.Sqrt(MathF.Max(0.0001f, maxScaleSq)); + float scaledRadius = bucket.LocalRadius * scale; + Vector3 worldCenter = worldXform * bucket.LocalCenter; + + if (_hasFrustum && !IsSphereInFrustum(worldCenter, scaledRadius)) + { + return; + } + + bool castShadow = wantsShadow && bucket.LocalRadius >= 0.45f; + if (castShadow && _hasFrustum) + { + float maxShadowDist = 120f + scaledRadius; + if (worldCenter.DistanceSquaredTo(_camPos) > maxShadowDist * maxShadowDist) + { + castShadow = false; + } + } + + bucket.Pending.Add(new PendingInstance(worldXform, customData, castShadow, worldCenter, scaledRadius)); + TotalSubmittedInstances++; + } + + public void EndFrame() + { + int active = 0; + for (int i = 0; i < _bucketList.Count; i++) + { + PoolBucket bucket = _bucketList[i]; + int count = bucket.Pending.Count; + if (count == 0) + { + bucket.MultiMesh.VisibleInstanceCount = 0; + bucket.Node.Visible = false; + continue; + } + + active++; + if (bucket.MultiMesh.InstanceCount < count) + { + bucket.MultiMesh.InstanceCount = Math.Max(16, count * 2); + } + + Vector3 aabbMin = new(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + Vector3 aabbMax = new(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity); + bool anyShadow = false; + + for (int k = 0; k < count; k++) + { + PendingInstance inst = bucket.Pending[k]; + bucket.MultiMesh.SetInstanceTransform(k, inst.Xform); + bucket.MultiMesh.SetInstanceCustomData(k, inst.Custom); + if (inst.WantsShadow) + { + anyShadow = true; + } + + Vector3 r = new(inst.ScaledRadius, inst.ScaledRadius, inst.ScaledRadius); + Vector3 lo = inst.WorldCenter - r; + Vector3 hi = inst.WorldCenter + r; + aabbMin = new Vector3(MathF.Min(aabbMin.X, lo.X), MathF.Min(aabbMin.Y, lo.Y), MathF.Min(aabbMin.Z, lo.Z)); + aabbMax = new Vector3(MathF.Max(aabbMax.X, hi.X), MathF.Max(aabbMax.Y, hi.Y), MathF.Max(aabbMax.Z, hi.Z)); + } + + bucket.MultiMesh.VisibleInstanceCount = count; + bucket.Node.CustomAabb = new Aabb(aabbMin, aabbMax - aabbMin); + bucket.Node.CastShadow = anyShadow + ? GeometryInstance3D.ShadowCastingSetting.On + : GeometryInstance3D.ShadowCastingSetting.Off; + bucket.Node.Visible = true; + } + ActiveBucketCount = active; + } + + public void ClearAll() + { + for (int i = 0; i < _bucketList.Count; i++) + { + PoolBucket bucket = _bucketList[i]; + bucket.Pending.Clear(); + bucket.MultiMesh.VisibleInstanceCount = 0; + bucket.Node.Visible = false; + } + ActiveBucketCount = 0; + TotalSubmittedInstances = 0; + } + + private PoolBucket GetOrCreateBucket(ArrayMesh mesh) + { + ulong id = mesh.GetInstanceId(); + if (_buckets.TryGetValue(id, out PoolBucket? existing)) + { + return existing; + } + + Aabb aabb = mesh.GetAabb(); + Vector3 localCenter = aabb.GetCenter(); + float localRadius = MathF.Max(0.2f, aabb.Size.Length() * 0.5f); + + var mm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = mesh, + InstanceCount = 16, + VisibleInstanceCount = 0 + }; + var mmi = new MultiMeshInstance3D + { + Name = $"MMPool_{_bucketList.Count}", + Multimesh = mm, + MaterialOverride = _sharedMat, + Visible = false, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off + }; + AddChild(mmi); + + var created = new PoolBucket + { + Mesh = mesh, + LocalCenter = localCenter, + LocalRadius = localRadius, + MultiMesh = mm, + Node = mmi + }; + _buckets[id] = created; + _bucketList.Add(created); + return created; + } + + private bool IsSphereInFrustum(Vector3 center, float radius) + { + float margin = radius + 1.5f; + for (int i = 0; i < 6; i++) + { + if (_frustumPlanes[i].DistanceTo(center) > margin) + { + return false; + } + } + return true; + } +} diff --git a/client/NativeLibraries.cs b/client/NativeLibraries.cs new file mode 100644 index 0000000..a2973a2 --- /dev/null +++ b/client/NativeLibraries.cs @@ -0,0 +1,89 @@ +using System; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Godot; +using RustToDust.HbGpu; +using Ymir.Box3D; + +namespace RustToDust.Client; + +/// +/// Resolves native libraries (ymir_box3d, rtd_hbgpu) for Godot's AssemblyLoadContext. +/// +internal static class NativeLibraries +{ + private const string YmirLibrary = "ymir_box3d"; + private const string HbGpuLibrary = "rtd_hbgpu"; + +#pragma warning disable CA2255 // application code: the resolver must exist before the first DllImport + [ModuleInitializer] + internal static void Register() + { + NativeLibrary.SetDllImportResolver(typeof(Box3DSoaWorld).Assembly, Resolve); + NativeLibrary.SetDllImportResolver(typeof(HbGpuNative).Assembly, Resolve); + } + + private static IntPtr Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath) + { + string? stem = name switch + { + YmirLibrary => YmirLibrary, + HbGpuLibrary => HbGpuLibrary, + _ => null + }; + if (stem is null) + { + return IntPtr.Zero; + } + + string fileName = FileName(stem); + + if (OS.HasFeature("template")) + { + string exePath = OS.GetExecutablePath(); + string exeDir = exePath.GetBaseDir(); + string exeStem = Path.GetFileNameWithoutExtension(exePath); + string platArch = $"{Platform()}_{Arch()}"; + + string[] candidates = + { + Path.Combine(exeDir, fileName), + Path.Combine(exeDir, $"data_{exeStem}_{platArch}", fileName), + Path.Combine(exeDir, $"data_RustToDust_{platArch}", fileName), + Path.Combine(exeDir, $"data_RustToDust.Client_{platArch}", fileName), + Path.Combine(AppContext.BaseDirectory, fileName), + }; + + foreach (string candidate in candidates) + { + if (File.Exists(candidate) && NativeLibrary.TryLoad(candidate, out var exportHandle)) + { + return exportHandle; + } + } + return IntPtr.Zero; + } + + string debugPath = Path.Combine(ProjectSettings.GlobalizePath("res://.godot/mono/temp/bin/Debug"), fileName); + if (File.Exists(debugPath) && NativeLibrary.TryLoad(debugPath, out var debugHandle)) + { + return debugHandle; + } + + string releasePath = Path.Combine(ProjectSettings.GlobalizePath("res://.godot/mono/temp/bin/Release"), fileName); + return File.Exists(releasePath) && NativeLibrary.TryLoad(releasePath, out var releaseHandle) + ? releaseHandle + : IntPtr.Zero; + } + + private static string FileName(string stem) => + OperatingSystem.IsWindows() ? $"{stem}.dll" : OperatingSystem.IsMacOS() ? $"lib{stem}.dylib" : $"lib{stem}.so"; + + private static string Platform() => + OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linuxbsd"; + + private static string Arch() => + RuntimeInformation.ProcessArchitecture == System.Runtime.InteropServices.Architecture.Arm64 ? "arm64" : "x86_64"; +} diff --git a/client/ParticlePool.cs b/client/ParticlePool.cs new file mode 100644 index 0000000..ca2bce3 --- /dev/null +++ b/client/ParticlePool.cs @@ -0,0 +1,734 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Owns ONLY the strictly capped [2] dynamic combat flash pool +/// plus idempotent deduplication and dispatch into +/// (smoke/fire/shockwaves) and +/// ( sparks/embers/dust/muzzle bursts). +/// Zero CPU particle buffers or billboard MultiMeshes. +/// +public partial class ParticlePool : Node3D +{ + public const int MaxFlashLights = 2; + + private struct FlashLightSlot + { + public OmniLight3D Light; + public bool Active; + public int Priority; + public float Age; + public float Duration; + public float StartEnergy; + public float Range; + public Color Color; + } + + private readonly FlashLightSlot[] _flashLights = new FlashLightSlot[MaxFlashLights]; + + // Bounded rolling dedupe buffers (zero polling cursor on MatchState) + private readonly int[] _recentShotIds = new int[64]; + private int _recentShotCursor; + private readonly long[] _recentHitIds = new long[64]; + private int _recentHitCursor; + + private VolumetricEmitterPool? _volumetrics; + private GpuSparksSystem? _gpuSparks; + private int _warmupFramesRemaining; + private bool _initialized; + + public int FlashLightPoolSize => MaxFlashLights; + + public int ActiveFlashLightCount + { + get + { + int count = 0; + for (int i = 0; i < _flashLights.Length; i++) + { + if (_flashLights[i].Active) count++; + } + return count; + } + } + + public int PeakFlashLightCount { get; private set; } + + public void BindTargets(VolumetricEmitterPool volumetrics, GpuSparksSystem gpuSparks) + { + _volumetrics = volumetrics; + _gpuSparks = gpuSparks; + } + + public override void _Ready() + { + EnsureInitialized(); + } + + public void EnsureInitialized() + { + if (_initialized) + { + return; + } + _initialized = true; + + for (int i = 0; i < MaxFlashLights; i++) + { + var light = new OmniLight3D + { + Name = $"CombatFlashLight_{i}", + ShadowEnabled = false, + OmniAttenuation = 1.6f, + OmniRange = 14f, + LightEnergy = 0f, + LightVolumetricFogEnergy = 0f, + Visible = false + }; + AddChild(light); + _flashLights[i] = new FlashLightSlot { Light = light }; + } + } + + /// + /// Pre-warms the pooled nodes on startup for 2 rendered frames + /// with near-zero energy so Forward+ compiles lit shader variants before combat begins. + /// + public void PrewarmFlashLights(Vector3 nearPos, Vector3 forwardHoriz) + { + EnsureInitialized(); + _warmupFramesRemaining = 2; + Vector3 fwd = forwardHoriz.LengthSquared() > 1e-4f ? forwardHoriz.Normalized() : Vector3.Forward; + for (int i = 0; i < _flashLights.Length; i++) + { + ref FlashLightSlot slot = ref _flashLights[i]; + slot.Active = false; + slot.Priority = 0; + slot.Age = 0f; + slot.Duration = 0f; + slot.StartEnergy = 0f; + slot.Range = 22f; + slot.Light.Position = i == 0 ? nearPos + new Vector3(0f, 2f, 0f) : nearPos + fwd * 72f + new Vector3(0f, 3f, 0f); + slot.Light.LightColor = Colors.White; + slot.Light.OmniRange = 22f; + slot.Light.OmniAttenuation = 1.6f; + slot.Light.LightEnergy = 0.001f; + slot.Light.Visible = true; + } + } + + public void ClearAll() + { + EnsureInitialized(); + Array.Clear(_recentShotIds, 0, _recentShotIds.Length); + Array.Clear(_recentHitIds, 0, _recentHitIds.Length); + _recentShotCursor = 0; + _recentHitCursor = 0; + _warmupFramesRemaining = 0; + PeakFlashLightCount = 0; + + for (int i = 0; i < _flashLights.Length; i++) + { + _flashLights[i].Active = false; + _flashLights[i].Age = 0f; + _flashLights[i].Duration = 0f; + _flashLights[i].Light.Visible = false; + _flashLights[i].Light.LightEnergy = 0f; + } + } + + public void ConsumeEvents( + IClientArenaSession session, + IReadOnlyList events, + Vector3 camPos, + bool hasCam, + Func sampleGroundTint) + { + EnsureInitialized(); + var state = session.ViewState; + + for (int i = 0; i < events.Count; i++) + { + switch (events[i]) + { + case MatchResetEvent: + ClearAll(); + break; + + case ShotFiredEvent shot: + HandleShotFired(shot, camPos, hasCam, sampleGroundTint); + break; + + case HitImpactEvent hit: + HandleHitImpact(hit, camPos, hasCam, sampleGroundTint); + break; + + case ContenderEliminatedEvent elim: + if ((elim.VictimId == session.LocalContenderId || session.IsContenderVisible(elim.VictimId)) && + elim.VictimId >= 0 && elim.VictimId < state.Contenders.Count) + { + var v = state.Contenders[elim.VictimId]; + EmitChassisExplosion(new Vector3(v.X, v.Y + 0.6f, v.Z), v.Grid.Spec.MassKg, camPos, hasCam, sampleGroundTint); + } + break; + + case SpectatorDestroyedEvent sdet: + { + if (!session.IsSpectatorVisible(sdet.SpectatorId)) + { + break; + } + var specs = state.Spectators.Spectators; + for (int s = 0; s < specs.Count; s++) + { + if (specs[s].Id == sdet.SpectatorId) + { + var sp = specs[s]; + EmitChassisExplosion(new Vector3(sp.X, sp.Y + 0.5f, sp.Z), sp.Grid.Spec.MassKg, camPos, hasCam, sampleGroundTint); + break; + } + } + break; + } + + case DropPodEvent dpe: + if ((DropPodEventKind)dpe.Kind == DropPodEventKind.PodTouchdownBlowPetals) + { + bool isLocal = dpe.ContenderId == session.LocalContenderId; + bool isContender = dpe.PodKind == (byte)OrbitalPodKind.Contender; + Vector3 pos = new(dpe.X, dpe.Y, dpe.Z); + Vector3 nrm = new(dpe.NormalX, dpe.NormalY, dpe.NormalZ); + if (nrm.LengthSquared() < 1e-4f) nrm = Vector3.Up; + nrm = nrm.Normalized(); + EmitPodTouchdownBurst(pos, nrm, sampleGroundTint(pos.X, pos.Z), isContender, isLocal, camPos, hasCam); + } + else if ((DropPodEventKind)dpe.Kind == DropPodEventKind.PodRetroBurnStart) + { + bool isLocal = dpe.ContenderId == session.LocalContenderId; + Vector3 pos = new(dpe.X, dpe.Y, dpe.Z); + if (isLocal || !hasCam || pos.DistanceSquaredTo(camPos) <= 220f * 220f) + { + SpawnFlashLight(pos - new Vector3(0f, 0.8f, 0f), new Color(1.0f, 0.62f, 0.22f), 4.5f, 15f, 0.14f, priority: isLocal ? 9 : 4); + } + } + break; + } + } + } + + public void EmitFootstepDust(in FootstepPulse pulse, Color groundTint, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + Vector3 footPos = new(pulse.WorldPos.X, pulse.WorldPos.Y + 0.14f, pulse.WorldPos.Z); + if (hasCam && footPos.DistanceSquaredTo(camPos) > 115f * 115f) + { + return; + } + + float massScale = Math.Clamp(pulse.MassKg / 2600f, 0.72f, 1.55f); + float loadScale = Math.Clamp(pulse.LoadG, 0.5f, 1.8f); + int count = pulse.MassKg >= 3600f ? 42 : 26; + _gpuSparks?.EmitDustMotes(footPos, Vector3.Up, count, groundTint with { A = 0.76f }, 3.4f * massScale * MathF.Sqrt(loadScale), 0.048f * massScale); + _volumetrics?.EmitFootstepOrTirePuff(footPos, groundTint, massScale); + } + + public void EmitTireDust(Vector3 worldPos, Vector3 vehicleVel, Color groundTint, float intensity, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && worldPos.DistanceSquaredTo(camPos) > 95f * 95f) + { + return; + } + + float scale = Math.Clamp(intensity, 0.5f, 1.5f); + _gpuSparks?.EmitDustMotes(worldPos, Vector3.Up, 18, groundTint with { A = 0.70f }, 2.6f * scale, 0.045f * scale); + _volumetrics?.EmitFootstepOrTirePuff(worldPos, groundTint, scale * 0.9f); + } + + public void EmitThermalVent(Vector3 worldPos, float thermalRatio, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && worldPos.DistanceSquaredTo(camPos) > 105f * 105f) + { + return; + } + + _volumetrics?.EmitThermalVentPlume(worldPos, thermalRatio); + if (thermalRatio >= 0.94f) + { + _gpuSparks?.EmitSparkBurst(worldPos, Vector3.Up, 20, new Color(4.6f, 2.4f, 0.55f, 0.96f), 6.5f, 0.026f); + } + } + + public void EmitDamageSmokeAndFire(Vector3 worldPos, float coreHpRatio, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && worldPos.DistanceSquaredTo(camPos) > 125f * 125f) + { + return; + } + + _volumetrics?.EmitDamageSmokePlume(worldPos, coreHpRatio); + if (coreHpRatio < 0.24f) + { + _gpuSparks?.EmitEmberBurst(worldPos, 16, new Color(4.2f, 1.8f, 0.35f, 0.94f), 2.4f, 0.030f); + } + } + + public void EmitOrdnanceBurst(Vector3 pos, Color accentCol, int sparkCount, float radiusScale, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && pos.DistanceSquaredTo(camPos) > 220f * 220f) + { + return; + } + + Color moltenHdr = new(4.8f, 2.6f, 0.65f, 0.98f); + Color subtleTint = new( + Mathf.Lerp(moltenHdr.R, accentCol.R * 3.8f, 0.25f), + Mathf.Lerp(moltenHdr.G, accentCol.G * 3.8f, 0.25f), + Mathf.Lerp(moltenHdr.B, accentCol.B * 3.8f, 0.25f), + 0.98f); + _gpuSparks?.EmitSparkBurst(pos, Vector3.Up, Math.Clamp(sparkCount * 16, 48, 160), subtleTint, 15f * radiusScale, 0.028f); + _gpuSparks?.EmitEmberBurst(pos, Math.Clamp(sparkCount * 7, 22, 80), moltenHdr * 0.85f, 5.0f * radiusScale, 0.032f); + } + + public void EmitThermalPoolEmber(Vector3 pos, float radius, Color accentCol, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && pos.DistanceSquaredTo(camPos) > 150f * 150f) + { + return; + } + + _gpuSparks?.EmitThermalPoolEmber(pos, radius, accentCol); + } + + public void EmitPodReentryStreak(Vector3 podPos, Vector3 podVel, float heatGlow, bool isContender, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && podPos.DistanceSquaredTo(camPos) > 650f * 650f) + { + return; + } + + _volumetrics?.EmitPodReentryPlume(podPos, podVel, heatGlow, isContender); + _gpuSparks?.EmitEmberBurst(podPos, isContender ? 20 : 12, new Color(4.4f, 2.2f, 0.55f, 0.95f), 2.8f, 0.030f); + } + + public void EmitPodRetroBurn( + Vector3 podBasePos, + float agl, + Color groundTint, + bool isContender, + bool isLocal, + Vector3 camPos, + bool hasCam) + { + EnsureInitialized(); + float distSq = hasCam ? podBasePos.DistanceSquaredTo(camPos) : 0f; + if (hasCam && distSq > 480f * 480f) + { + return; + } + + _volumetrics?.EmitPodRetroPlume(podBasePos, agl, groundTint, isContender); + _gpuSparks?.EmitPodRetroSparksAndDust(podBasePos, agl, groundTint, isContender); + + if (isLocal || !hasCam || distSq <= 95f * 95f) + { + SpawnFlashLight(podBasePos - new Vector3(0f, 0.6f, 0f), new Color(1.0f, 0.60f, 0.18f), 3.8f, 14f, 0.09f, priority: isLocal ? 8 : 3); + } + } + + public void EmitPodTouchdownBurst( + Vector3 pos, + Vector3 normal, + Color groundTint, + bool isContender, + bool isLocal, + Vector3 camPos, + bool hasCam) + { + EnsureInitialized(); + float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f; + if (!isLocal && hasCam && distSq > 360f * 360f) + { + return; + } + + _volumetrics?.EmitPodTouchdownPlume(pos, normal, groundTint, isContender); + _gpuSparks?.EmitPodTouchdownSparksAndDust(pos, normal, groundTint, isContender); + + if (isLocal || !hasCam || distSq <= 140f * 140f) + { + SpawnFlashLight(pos + normal * 1.2f, new Color(1.0f, 0.58f, 0.16f), 5.8f, 18f, 0.18f, priority: isLocal ? 10 : 6); + } + } + + public void TriggerFlashLightForTest(Vector3 pos, Color color, float energy, float range, float duration, int priority) + { + EnsureInitialized(); + SpawnFlashLight(pos, color, energy, range, duration, priority); + } + + public void AdvanceAndCommit(float dt) + { + EnsureInitialized(); + float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; + + int activeLights = 0; + for (int i = 0; i < _flashLights.Length; i++) + { + ref FlashLightSlot slot = ref _flashLights[i]; + if (!slot.Active) + { + continue; + } + + if (stepDt > 0f) + { + slot.Age += stepDt; + if (slot.Age >= slot.Duration) + { + slot.Active = false; + slot.Light.Visible = false; + slot.Light.LightEnergy = 0f; + continue; + } + } + + float t = Math.Clamp(slot.Age / MathF.Max(0.01f, slot.Duration), 0f, 1f); + float decay = MathF.Pow(1f - t, 1.8f); + slot.Light.LightColor = slot.Color; + slot.Light.OmniRange = slot.Range; + slot.Light.LightEnergy = slot.StartEnergy * decay; + slot.Light.Visible = slot.Light.LightEnergy > 0.01f; + if (slot.Light.Visible) + { + activeLights++; + } + } + if (_warmupFramesRemaining > 0) + { + _warmupFramesRemaining--; + if (_warmupFramesRemaining == 0) + { + for (int i = 0; i < _flashLights.Length; i++) + { + if (!_flashLights[i].Active) + { + _flashLights[i].Light.Visible = false; + _flashLights[i].Light.LightEnergy = 0f; + } + } + } + } + if (activeLights > PeakFlashLightCount) + { + PeakFlashLightCount = activeLights; + } + } + + private void HandleShotFired( + ShotFiredEvent shot, + Vector3 camPos, + bool hasCam, + Func sampleGroundTint) + { + if (shot.TracerId != 0) + { + for (int k = 0; k < _recentShotIds.Length; k++) + { + if (_recentShotIds[k] == shot.TracerId) + { + return; + } + } + _recentShotIds[_recentShotCursor] = shot.TracerId; + _recentShotCursor = (_recentShotCursor + 1) % _recentShotIds.Length; + } + + Vector3 start = new(shot.StartX, shot.StartY, shot.StartZ); + Vector3 end = new(shot.EndX, shot.EndY, shot.EndZ); + if (hasCam && start.DistanceSquaredTo(camPos) > 140f * 140f) + { + return; + } + + var wClass = (WeaponVisualClass)shot.WeaponClass; + bool isRecoilless = string.Equals(shot.WeaponId, "recoilless", StringComparison.Ordinal); + bool isLance = string.Equals(shot.WeaponId, "gilded_lance", StringComparison.Ordinal); + bool isPd = string.Equals(shot.WeaponId, "pd_flak", StringComparison.Ordinal); + Vector3 aimDir = (end - start).LengthSquared() > 1e-4f ? (end - start).Normalized() : Vector3.Forward; + + switch (wClass) + { + case WeaponVisualClass.KineticLight: + _gpuSparks?.EmitMuzzleStarburst(start, new Color(4.2f, 2.8f, 1.0f, 0.96f), isPd ? 0.42f : 0.30f, 0.07f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 18, new Color(4.5f, 2.8f, 0.8f, 0.96f), 11f, 0.024f); + break; + + case WeaponVisualClass.Autocannon: + _gpuSparks?.EmitMuzzleStarburst(start, new Color(4.6f, 2.6f, 0.75f, 0.98f), 0.56f, 0.08f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 32, new Color(4.8f, 2.6f, 0.65f, 0.96f), 13f, 0.026f); + _volumetrics?.EmitMuzzleBreechPuff(start, end, sampleGroundTint(start.X, start.Z), wClass, isRecoilless: false); + if (!hasCam || start.DistanceSquaredTo(camPos) <= 45f * 45f) + { + SpawnFlashLight(start, new Color(1.0f, 0.68f, 0.24f), 2.8f, 10.5f, 0.10f, priority: 3); + } + break; + + case WeaponVisualClass.Explosive: + _gpuSparks?.EmitMuzzleStarburst(start, new Color(5.0f, 2.6f, 0.70f, 0.98f), isRecoilless ? 0.78f : 0.48f, 0.09f); + _gpuSparks?.EmitSparkBurst(start, aimDir, isRecoilless ? 64 : 32, new Color(5.0f, 2.5f, 0.60f, 0.98f), 15f, 0.028f); + _volumetrics?.EmitMuzzleBreechPuff(start, end, sampleGroundTint(start.X, start.Z), wClass, isRecoilless); + if (!hasCam || start.DistanceSquaredTo(camPos) <= 65f * 65f) + { + SpawnFlashLight(start, new Color(1.0f, 0.58f, 0.18f), isRecoilless ? 4.2f : 2.6f, isRecoilless ? 14f : 10f, 0.13f, priority: 5); + } + break; + + case WeaponVisualClass.ThermalBeam: + { + Color beamCol = isLance ? new Color(4.8f, 3.2f, 0.95f, 0.96f) : new Color(2.8f, 3.4f, 3.8f, 0.96f); + _gpuSparks?.EmitMuzzleStarburst(start, beamCol, isLance ? 0.68f : 0.48f, 0.09f); + if (!hasCam || start.DistanceSquaredTo(camPos) <= 45f * 45f) + { + Color lCol = isLance ? new Color(1.0f, 0.78f, 0.28f) : new Color(0.32f, 0.90f, 1.0f); + SpawnFlashLight(start, lCol, isLance ? 3.5f : 2.6f, 11f, 0.12f, priority: 4); + } + break; + } + + case WeaponVisualClass.GaussRail: + { + Color gaussHdr = new(3.6f, 2.8f, 1.8f, 0.98f); + _gpuSparks?.EmitMuzzleStarburst(start, new Color(1.4f, 3.5f, 4.8f, 0.98f), 0.72f, 0.09f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 56, gaussHdr, 19f, 0.026f); + if (!hasCam || start.DistanceSquaredTo(camPos) <= 65f * 65f) + { + SpawnFlashLight(start, new Color(0.22f, 0.78f, 1.0f), 4.2f, 14f, 0.11f, priority: 5); + } + break; + } + + case WeaponVisualClass.PlasmaPpc: + { + Color plasmaHdr = new(3.4f, 2.8f, 1.6f, 0.96f); + _gpuSparks?.EmitMuzzleStarburst(start, new Color(1.0f, 3.4f, 4.2f, 0.96f), 0.65f, 0.09f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 38, plasmaHdr, 12f, 0.028f); + if (!hasCam || start.DistanceSquaredTo(camPos) <= 55f * 55f) + { + SpawnFlashLight(start, new Color(0.16f, 0.88f, 0.95f), 3.4f, 12f, 0.12f, priority: 4); + } + break; + } + + case WeaponVisualClass.RocketSalvo: + _gpuSparks?.EmitMuzzleStarburst(start, new Color(4.8f, 2.6f, 0.75f, 0.96f), 0.62f, 0.095f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 42, new Color(4.8f, 2.4f, 0.60f, 0.96f), 13f, 0.028f); + _volumetrics?.EmitMuzzleBreechPuff(start, end, sampleGroundTint(start.X, start.Z), wClass, isRecoilless: false); + break; + + case WeaponVisualClass.SwarmSmart: + _gpuSparks?.EmitMuzzleStarburst(start, new Color(2.8f, 3.8f, 1.2f, 0.96f), 0.48f, 0.085f); + break; + } + } + + private void HandleHitImpact( + HitImpactEvent hit, + Vector3 camPos, + bool hasCam, + Func sampleGroundTint) + { + if (hit.EventId != 0) + { + for (int k = 0; k < _recentHitIds.Length; k++) + { + if (_recentHitIds[k] == hit.EventId) + { + return; + } + } + _recentHitIds[_recentHitCursor] = hit.EventId; + _recentHitCursor = (_recentHitCursor + 1) % _recentHitIds.Length; + } + + Vector3 pos = new(hit.HitX, hit.HitY, hit.HitZ); + if (hasCam && pos.DistanceSquaredTo(camPos) > 180f * 180f) + { + return; + } + + Vector3 normal = new(hit.NormalX, hit.NormalY, hit.NormalZ); + if (normal.LengthSquared() < 1e-4f) normal = Vector3.Up; + normal = normal.Normalized(); + + var wClass = (WeaponVisualClass)hit.WeaponClass; + bool isTerrain = hit.TargetKind == (byte)HitTargetKind.Terrain; + Color groundTint = isTerrain ? sampleGroundTint(pos.X, pos.Z) : new Color(0.46f, 0.42f, 0.38f, 1f); + + if (hit.IsAirburst || (wClass == WeaponVisualClass.KineticLight && string.Equals(hit.WeaponId, "pd_flak", StringComparison.Ordinal))) + { + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: true); + _gpuSparks?.EmitSparkBurst(pos, normal, 76, new Color(5.0f, 2.7f, 0.70f, 0.98f), 14f, 0.026f); + _gpuSparks?.EmitEmberBurst(pos, 28, new Color(4.0f, 1.8f, 0.35f, 0.95f), 4.5f, 0.030f); + return; + } + + switch (wClass) + { + case WeaponVisualClass.KineticLight: + if (isTerrain) + { + _gpuSparks?.EmitDustMotes(pos, normal, 36, groundTint with { A = 0.76f }, 4.5f, 0.045f); + } + else + { + _gpuSparks?.EmitSparkBurst(pos, normal, 62, new Color(4.8f, 3.0f, 0.95f, 0.96f), 11f, 0.024f); + } + break; + + case WeaponVisualClass.Autocannon: + _gpuSparks?.EmitSparkBurst(pos, normal, 76, new Color(4.8f, 2.6f, 0.70f, 0.98f), 13.5f, 0.026f); + _gpuSparks?.EmitDustMotes(pos, normal, 42, groundTint with { A = 0.78f }, 5.5f, 0.048f); + _volumetrics?.EmitFootstepOrTirePuff(pos, groundTint, 1.0f); + break; + + case WeaponVisualClass.Explosive: + { + bool isRecoilless = string.Equals(hit.WeaponId, "recoilless", StringComparison.Ordinal); + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, isRecoilless ? 140 : 88, new Color(5.2f, 2.6f, 0.65f, 0.98f), 17f, 0.028f); + _gpuSparks?.EmitEmberBurst(pos, isRecoilless ? 54 : 32, new Color(4.2f, 1.7f, 0.35f, 0.95f), 5.5f, 0.032f); + _gpuSparks?.EmitDustMotes(pos, normal, isRecoilless ? 68 : 44, groundTint with { A = 0.80f }, 7.5f, 0.052f); + if (!hasCam || pos.DistanceSquaredTo(camPos) <= 75f * 75f) + { + SpawnFlashLight(pos + normal * 0.45f, new Color(1.0f, 0.55f, 0.16f), isRecoilless ? 4.8f : 3.2f, isRecoilless ? 14.5f : 11f, 0.14f, priority: 7); + } + break; + } + + case WeaponVisualClass.ThermalBeam: + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, 68, new Color(4.6f, 2.8f, 1.4f, 0.98f), 13f, 0.026f); + break; + + case WeaponVisualClass.GaussRail: + _gpuSparks?.EmitSparkBurst(pos, normal, 96, new Color(4.2f, 3.0f, 1.8f, 0.98f), 20f, 0.026f); + _gpuSparks?.EmitDustMotes(pos, normal, 48, groundTint with { A = 0.78f }, 6.5f, 0.048f); + _volumetrics?.EmitFootstepOrTirePuff(pos, groundTint, 1.2f); + if (!hasCam || pos.DistanceSquaredTo(camPos) <= 65f * 65f) + { + SpawnFlashLight(pos + normal * 0.35f, new Color(0.28f, 0.82f, 1.0f), 4.0f, 13f, 0.12f, priority: 6); + } + break; + + case WeaponVisualClass.PlasmaPpc: + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, 84, new Color(4.0f, 2.8f, 1.6f, 0.98f), 15f, 0.028f); + _gpuSparks?.EmitEmberBurst(pos, 40, new Color(3.6f, 2.0f, 0.85f, 0.92f), 4.5f, 0.032f); + break; + + case WeaponVisualClass.RocketSalvo: + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, 112, new Color(5.0f, 2.7f, 0.65f, 0.98f), 16f, 0.028f); + _gpuSparks?.EmitEmberBurst(pos, 38, new Color(4.0f, 1.7f, 0.35f, 0.95f), 5.0f, 0.032f); + _gpuSparks?.EmitDustMotes(pos, normal, 56, groundTint with { A = 0.80f }, 7.0f, 0.052f); + if (!hasCam || pos.DistanceSquaredTo(camPos) <= 75f * 75f) + { + SpawnFlashLight(pos + normal * 0.45f, new Color(1.0f, 0.56f, 0.16f), 4.5f, 14f, 0.14f, priority: 7); + } + break; + + case WeaponVisualClass.SwarmSmart: + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, 68, new Color(4.2f, 2.8f, 0.85f, 0.98f), 13f, 0.026f); + break; + } + } + + private void EmitChassisExplosion( + Vector3 pos, + float massKg, + Vector3 camPos, + bool hasCam, + Func sampleGroundTint) + { + if (hasCam && pos.DistanceSquaredTo(camPos) > 280f * 280f) + { + return; + } + + Color gTint = sampleGroundTint(pos.X, pos.Z); + _volumetrics?.EmitChassisExplosion(pos, massKg, gTint); + _gpuSparks?.EmitSparkBurst(pos, Vector3.Up, 260, new Color(5.6f, 2.9f, 0.70f, 0.98f), 22f, 0.028f); + _gpuSparks?.EmitEmberBurst(pos, 140, new Color(4.4f, 1.8f, 0.35f, 0.95f), 7.5f, 0.034f); + _gpuSparks?.EmitDustMotes(pos, Vector3.Up, 64, gTint with { A = 0.82f }, 9.0f, 0.056f); + + if (!hasCam || pos.DistanceSquaredTo(camPos) <= 95f * 95f) + { + SpawnFlashLight(pos + new Vector3(0f, 1.2f, 0f), new Color(1.0f, 0.56f, 0.14f), 6.2f, 16f, 0.18f, priority: 10); + } + } + + private void SpawnFlashLight(Vector3 pos, Color color, float energy, float range, float duration, int priority) + { + int targetIdx = -1; + for (int i = 0; i < _flashLights.Length; i++) + { + if (!_flashLights[i].Active) + { + targetIdx = i; + break; + } + } + + if (targetIdx < 0) + { + int lowestPri = int.MaxValue; + float oldestAge = -1f; + for (int i = 0; i < _flashLights.Length; i++) + { + if (_flashLights[i].Priority < lowestPri || + (_flashLights[i].Priority == lowestPri && _flashLights[i].Age > oldestAge)) + { + lowestPri = _flashLights[i].Priority; + oldestAge = _flashLights[i].Age; + targetIdx = i; + } + } + if (targetIdx < 0 || lowestPri > priority) + { + return; + } + } + + float clampedRange = Math.Clamp(range, 6.5f, 22f); + ref FlashLightSlot slot = ref _flashLights[targetIdx]; + slot.Active = true; + slot.Priority = priority; + slot.Age = 0f; + slot.Duration = MathF.Max(0.04f, duration); + slot.StartEnergy = energy; + slot.Range = clampedRange; + slot.Color = color; + slot.Light.Position = pos; + slot.Light.LightColor = color; + slot.Light.OmniRange = clampedRange; + slot.Light.LightEnergy = energy; + slot.Light.Visible = true; + + int active = ActiveFlashLightCount; + if (active > PeakFlashLightCount) + { + PeakFlashLightCount = active; + } + } +} diff --git a/client/PomDecalPool.cs b/client/PomDecalPool.cs new file mode 100644 index 0000000..edeeeb7 --- /dev/null +++ b/client/PomDecalPool.cs @@ -0,0 +1,486 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Live 4x4 Parallax Occlusion Mapping (POM) combat decal pool rendered in 1 draw call +/// using decal_pom.gdshader and assets/decals/decal_atlas_*.png. +/// Supports terrain impacts, static cover impacts, and vehicle-cell-attached scars +/// that cool smoothly over 3.5s, ride with moving limbs/turrets, and fade when armor detaches. +/// +public partial class PomDecalPool : Node3D +{ + public const int MaxDecals = 256; + private const float HeatCoolDuration = 3.5f; + private const float DetachFadeDuration = 0.35f; + private const float EndFadeDuration = 2.0f; + + private struct DecalSlot + { + public bool Active; + public float Age; + public float Lifetime; + public float TileIndex; + public float InitialHeat; + public float BaseOpacity; + public float DepthScale; + public Transform3D WorldXform; + + public bool IsAttached; + public VehicleVisualInstance? Visual; + public Node3D? Pivot; + public Transform3D LocalToPivot; + public ChassisGrid? Grid; + public int CellX; + public int CellY; + public float DetachedFadeRemaining; + } + + private readonly DecalSlot[] _slots = new DecalSlot[MaxDecals]; + private int _writeCursor; + private MatchState? _boundState; + + private MultiMesh _multiMesh = null!; + private MultiMeshInstance3D _instanceNode = null!; + private ShaderMaterial _material = null!; + private ImageTexture _albedoTex = null!; + private ImageTexture _normalTex = null!; + private ImageTexture _ormhTex = null!; + + public int ActiveCount { get; private set; } + + public override void _Ready() + { + Shader shader = GD.Load("res://decal_pom.gdshader") + ?? throw new InvalidOperationException("Failed to load res://decal_pom.gdshader"); + + string assetsDir = ClientAssets.LocateAssetsDirectory(); + string decalsDir = Path.Combine(assetsDir, "decals"); + + _albedoTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_albedo.png")); + _normalTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_normal.png")); + _ormhTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_ormh.png")); + + _material = new ShaderMaterial { Shader = shader }; + _material.SetShaderParameter("albedo_tex", _albedoTex); + _material.SetShaderParameter("normal_tex", _normalTex); + _material.SetShaderParameter("ormh_tex", _ormhTex); + _material.SetShaderParameter("use_instance_custom", true); + _material.SetShaderParameter("default_depth_scale", 0.06f); + _material.SetShaderParameter("normal_offset", 0.012f); + _material.SetShaderParameter("heat_emission_energy", 2.8f); + + _multiMesh = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = new QuadMesh { Size = Vector2.One }, + InstanceCount = MaxDecals, + VisibleInstanceCount = 0 + }; + + _instanceNode = new MultiMeshInstance3D + { + Name = "PomDecalsBatch", + Multimesh = _multiMesh, + MaterialOverride = _material, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + Visible = false + }; + AddChild(_instanceNode); + } + + public void EnsureInitialized() + { + if (_multiMesh is null) + { + _Ready(); + } + } + + public void ClearAll() + { + Array.Clear(_slots, 0, _slots.Length); + _writeCursor = 0; + ActiveCount = 0; + if (_multiMesh is not null) + { + _multiMesh.VisibleInstanceCount = 0; + _instanceNode.Visible = false; + } + } + + public void ConsumeEvents( + IClientArenaSession session, + IReadOnlyList events, + float dt, + Func getVisual) + { + EnsureInitialized(); + var state = session.ViewState; + if (!ReferenceEquals(_boundState, state)) + { + _boundState = state; + ClearAll(); + } + + for (int i = 0; i < events.Count; i++) + { + switch (events[i]) + { + case MatchResetEvent: + ClearAll(); + break; + case HitImpactEvent hit: + StampHit(in hit, state, getVisual); + break; + case DropPodEvent dpe: + if ((DropPodEventKind)dpe.Kind == DropPodEventKind.PodTouchdownBlowPetals) + { + bool isContender = dpe.PodKind == (byte)OrbitalPodKind.Contender; + Vector3 pos = new(dpe.X, dpe.Y, dpe.Z); + Vector3 nrm = new(dpe.NormalX, dpe.NormalY, dpe.NormalZ); + if (nrm.LengthSquared() < 1e-4f) nrm = Vector3.Up; + nrm = nrm.Normalized(); + Transform3D xf = BuildSurfaceTransform(pos + nrm * 0.05f, nrm, isContender ? 6.2f : 3.8f, dpe.PodId * 1.13f); + AllocateSlot(new DecalSlot + { + Active = true, + Age = 0f, + Lifetime = isContender ? 34f : 24f, + TileIndex = 15f, + InitialHeat = 1.0f, + BaseOpacity = 0.98f, + DepthScale = 0.095f, + WorldXform = xf, + DetachedFadeRemaining = -1f + }); + } + break; + } + } + + UpdateAndCommit(dt); + } + + public void PrewarmShader(Vector3 nearPos) + { + EnsureInitialized(); + if (ActiveCount > 0) + { + return; + } + AllocateSlot(new DecalSlot + { + Active = true, + Age = 0f, + Lifetime = 0.04f, + TileIndex = 12f, + InitialHeat = 0f, + BaseOpacity = 0.03f, + DepthScale = 0.02f, + WorldXform = BuildSurfaceTransform(nearPos, Vector3.Up, 0.05f, 0f), + DetachedFadeRemaining = -1f + }); + UpdateAndCommit(0f); + } + + public void StampTestDecal( + Vector3 worldPos, + Vector3 worldNormal, + float size, + int tileIndex, + float heat = 0.95f, + float depth = 0.085f) + { + EnsureInitialized(); + Transform3D xf = BuildSurfaceTransform(worldPos, worldNormal, size, (float)_writeCursor * 1.17f); + AllocateSlot(new DecalSlot + { + Active = true, + Age = 0f, + Lifetime = 26f, + TileIndex = tileIndex, + InitialHeat = heat, + BaseOpacity = 1f, + DepthScale = depth, + WorldXform = xf, + DetachedFadeRemaining = -1f + }); + UpdateAndCommit(0f); + } + + private void StampHit( + in HitImpactEvent ev, + MatchState state, + Func getVisual) + { + var targetKind = (HitTargetKind)ev.TargetKind; + var weaponClass = (WeaponVisualClass)ev.WeaponClass; + if (ev.IsAirburst && targetKind == HitTargetKind.StaticCover && ev.TargetId < 0) + { + return; + } + + bool isVehicle = targetKind == HitTargetKind.Contender || targetKind == HitTargetKind.Spectator; + int tile; + float size; + float heat; + float depth; + float lifetime; + + switch (weaponClass) + { + case WeaponVisualClass.ThermalBeam: + tile = string.Equals(ev.WeaponId, "gilded_lance", StringComparison.Ordinal) || !isVehicle + ? 14 // molten plasma crater + : 14; + size = isVehicle + ? (string.Equals(ev.WeaponId, "gilded_lance", StringComparison.Ordinal) ? 0.78f : 0.56f) + : (string.Equals(ev.WeaponId, "gilded_lance", StringComparison.Ordinal) ? 2.10f : 1.35f); + heat = 1.0f; + depth = 0.095f; + lifetime = 26f; + break; + + case WeaponVisualClass.Explosive: + bool isRecoilless = string.Equals(ev.WeaponId, "recoilless", StringComparison.Ordinal); + tile = isVehicle ? 13 : 15; // shrapnel gouge on armor, blast scorch on ground + size = isVehicle ? (isRecoilless ? 0.88f : 0.66f) : (isRecoilless ? 3.20f : 1.75f); + heat = isRecoilless ? 0.98f : 0.82f; + depth = isRecoilless ? 0.095f : 0.075f; + lifetime = 28f; + break; + + case WeaponVisualClass.Autocannon: + tile = (ev.EventId % 3 == 0) ? 13 : 12; // AP hole or shrapnel gouge + size = isVehicle ? 0.54f : 0.92f; + heat = 0.90f; + depth = 0.088f; + lifetime = 24f; + break; + + default: // KineticLight (mg_762, pd_flak) + tile = string.Equals(ev.WeaponId, "pd_flak", StringComparison.Ordinal) ? 13 : 12; + size = isVehicle ? 0.36f : 0.58f; + heat = 0.78f; + depth = 0.078f; + lifetime = 20f; + break; + } + + Vector3 hitPos = new(ev.HitX, ev.HitY, ev.HitZ); + Vector3 normal = new(ev.NormalX, ev.NormalY, ev.NormalZ); + if (normal.LengthSquared() < 1e-4f) normal = Vector3.Up; + normal = normal.Normalized(); + + if (isVehicle) + { + bool isContender = targetKind == HitTargetKind.Contender; + VehicleVisualInstance? vis = getVisual(isContender, ev.TargetId); + if (vis is null || !vis.Root.IsInsideTree() || !vis.Root.Visible) + { + return; + } + + ChassisGrid? grid = null; + if (isContender) + { + if (ev.TargetId >= 0 && ev.TargetId < state.Contenders.Count) + grid = state.Contenders[ev.TargetId].Grid; + } + else + { + var specs = state.Spectators.Spectators; + for (int si = 0; si < specs.Count; si++) + { + if (specs[si].Id == ev.TargetId) + { + grid = specs[si].Grid; + break; + } + } + } + if (grid is null || grid.IsDestroyed) + { + return; + } + + Vector3 rayDir = (vis.Root.GlobalPosition - hitPos); + if (rayDir.LengthSquared() < 1e-4f) rayDir = -normal; + rayDir = rayDir.Normalized(); + Vector3 rayOrigin = hitPos - rayDir * 0.75f; + + if (vis.TryRayHitAttachedPart(rayOrigin, rayDir, out Node3D? hitPivot, out Transform3D localToPivot, size) && + hitPivot is not null) + { + AllocateSlot(new DecalSlot + { + Active = true, + Age = 0f, + Lifetime = lifetime, + TileIndex = tile, + InitialHeat = heat, + BaseOpacity = 1f, + DepthScale = depth, + IsAttached = true, + Visual = vis, + Pivot = hitPivot, + LocalToPivot = localToPivot, + Grid = grid, + CellX = ev.CellX, + CellY = ev.CellY, + DetachedFadeRemaining = -1f + }); + return; + } + + // Fallback: attach to Root if sculpted geometry ray glanced past edge + Transform3D worldXf = BuildSurfaceTransform(hitPos, normal, size, ev.EventId * 0.73f); + AllocateSlot(new DecalSlot + { + Active = true, + Age = 0f, + Lifetime = lifetime, + TileIndex = tile, + InitialHeat = heat, + BaseOpacity = 1f, + DepthScale = depth, + IsAttached = true, + Visual = vis, + Pivot = vis.Root, + LocalToPivot = vis.Root.GlobalTransform.AffineInverse() * worldXf, + Grid = grid, + CellX = ev.CellX, + CellY = ev.CellY, + DetachedFadeRemaining = -1f + }); + return; + } + + // Terrain or StaticCover decal + Transform3D groundXf = BuildSurfaceTransform(hitPos + normal * 0.045f, normal, size, ev.EventId * 1.13f); + AllocateSlot(new DecalSlot + { + Active = true, + Age = 0f, + Lifetime = lifetime, + TileIndex = tile, + InitialHeat = heat, + BaseOpacity = 0.96f, + DepthScale = depth, + WorldXform = groundXf, + DetachedFadeRemaining = -1f + }); + } + + private void UpdateAndCommit(float dt) + { + float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; + int visibleIdx = 0; + + for (int i = 0; i < MaxDecals; i++) + { + ref DecalSlot s = ref _slots[i]; + if (!s.Active) + { + continue; + } + + s.Age += stepDt; + if (s.Age >= s.Lifetime) + { + s.Active = false; + continue; + } + + Transform3D xf = s.WorldXform; + float opacity = s.BaseOpacity; + + if (s.IsAttached) + { + if (s.Visual is null || s.Pivot is null || !GodotObject.IsInstanceValid(s.Pivot) || + !s.Pivot.IsInsideTree() || !s.Visual.Root.Visible) + { + s.Active = false; + continue; + } + + if (s.DetachedFadeRemaining < 0f && s.Grid is not null) + { + bool cellStripped = s.Grid.IsDestroyed || + (s.CellX >= 0 && s.CellX < s.Grid.Spec.Width && + s.CellY >= 0 && s.CellY < s.Grid.Spec.Height && + s.Grid.Armor[s.CellX, s.CellY] <= 0.01f); + if (cellStripped) + { + s.DetachedFadeRemaining = DetachFadeDuration; + } + } + + if (s.DetachedFadeRemaining >= 0f) + { + s.DetachedFadeRemaining -= stepDt; + if (s.DetachedFadeRemaining <= 0f) + { + s.Active = false; + continue; + } + opacity *= Math.Clamp(s.DetachedFadeRemaining / DetachFadeDuration, 0f, 1f); + } + + xf = s.Pivot.GlobalTransform * s.LocalToPivot; + } + + float remaining = s.Lifetime - s.Age; + if (remaining < EndFadeDuration) + { + opacity *= Math.Clamp(remaining / EndFadeDuration, 0f, 1f); + } + + float heatGlow = s.InitialHeat * MathF.Max(0f, 1f - s.Age / HeatCoolDuration); + _multiMesh.SetInstanceTransform(visibleIdx, xf); + _multiMesh.SetInstanceCustomData(visibleIdx, new Color(s.TileIndex, heatGlow, opacity, s.DepthScale)); + visibleIdx++; + } + + ActiveCount = visibleIdx; + _multiMesh.VisibleInstanceCount = visibleIdx; + _instanceNode.Visible = visibleIdx > 0; + } + + private void AllocateSlot(in DecalSlot slot) + { + _slots[_writeCursor] = slot; + _writeCursor = (_writeCursor + 1) % MaxDecals; + } + + private static Transform3D BuildSurfaceTransform(Vector3 worldPos, Vector3 worldNormal, float size, float spinRad) + { + Vector3 n = worldNormal.LengthSquared() > 1e-6f ? worldNormal.Normalized() : Vector3.Up; + Vector3 upRef = MathF.Abs(n.Y) > 0.92f ? Vector3.Forward : Vector3.Up; + Vector3 right = upRef.Cross(n).Normalized(); + Vector3 up = n.Cross(right).Normalized(); + Basis spin = new(n, spinRad); + right = spin * right; + up = spin * up; + return new Transform3D(new Basis(right * size, up * size, n), worldPos); + } + + private static ImageTexture LoadTextureWithMips(string path) + { + var img = Image.LoadFromFile(path); + if (img is null) + { + throw new FileNotFoundException($"Could not load POM decal texture '{path}'.", path); + } + img.GenerateMipmaps(); + return ImageTexture.CreateFromImage(img); + } +} diff --git a/client/ProceduralAudioBank.cs b/client/ProceduralAudioBank.cs new file mode 100644 index 0000000..22aaa0c --- /dev/null +++ b/client/ProceduralAudioBank.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Godot; +using RustToDust.Core; +using RustToDust.Core.Audio; + +namespace RustToDust.Client; + +/// +/// Owns all immutable assets built once at client startup: +/// 25 curated Haven Kendrick WAVs from assets/audio/haven/ plus all deterministic +/// procedural clips (with separable ). +/// Zero .import sidecar dependency. +/// +public sealed class ProceduralAudioBank +{ + public static readonly string[] ExpectedHavenClips = + { + "mg_shot_01", "mg_shot_02", "mg_tail", + "ac_light_01", "ac_light_02", "ac_med_01", "ac_rotary", + "flak_blast_01", "flak_blast_02", "cannon_heavy_01", "cannon_heavy_02", + "pd_bark_01", "pd_bark_02", "pd_laser", + "rocket_salvo_01", "rocket_salvo_02", + "plasma_ppc_01", "plasma_ppc_02", "lance_beam_01", "laser_heavy_01", "gauss_rail_01", + "mech_reload_bolt", "mech_quick_bolt", "mech_eject", "mech_turret_servo" + }; + + private readonly Dictionary _streams = new(StringComparer.OrdinalIgnoreCase); + + public ProceduralAudioBank(bool wetMixMode = true, string? havenDirOverride = null) + { + WetMixMode = wetMixMode; + LoadHavenClips(havenDirOverride ?? LocateHavenAudioDirectory()); + BuildProceduralClips(wetMixMode); + } + + public bool WetMixMode { get; private set; } + public int HavenClipCount { get; private set; } + public int ProceduralClipCount { get; private set; } + public int TotalClipCount => _streams.Count; + + public bool TryGetStream(string key, out AudioStreamWav stream) => + _streams.TryGetValue(key, out stream!); + + public AudioStreamWav GetStream(string key) => + _streams.TryGetValue(key, out var stream) + ? stream + : throw new KeyNotFoundException($"Missing audio clip '{key}' in ProceduralAudioBank."); + + public void RebuildProcedural(bool wetMixMode) + { + WetMixMode = wetMixMode; + BuildProceduralClips(wetMixMode); + } + + public static string LocateHavenAudioDirectory() + { + string assetsDir = ClientAssets.LocateAssetsDirectory(); + string havenDir = Path.Combine(assetsDir, "audio", "haven"); + if (!Directory.Exists(havenDir)) + { + throw new DirectoryNotFoundException($"Curated Haven audio directory not found: {havenDir}"); + } + return havenDir; + } + + private void LoadHavenClips(string havenDir) + { + int loaded = 0; + for (int i = 0; i < ExpectedHavenClips.Length; i++) + { + string key = ExpectedHavenClips[i]; + string path = Path.Combine(havenDir, key + ".wav"); + if (!File.Exists(path)) + { + throw new FileNotFoundException($"Missing curated Haven WAV '{path}'.", path); + } + + WavPcmInfo wav = WavFileReader.ReadMonoOrStereo16(path); + var stream = new AudioStreamWav + { + Format = AudioStreamWav.FormatEnum.Format16Bits, + MixRate = wav.SampleRate, + Stereo = wav.Channels == 2, + LoopMode = AudioStreamWav.LoopModeEnum.Disabled, + Data = wav.PcmBytes + }; + _streams[key] = stream; + loaded++; + } + HavenClipCount = loaded; + } + + private void BuildProceduralClips(bool wetMixMode) + { + Dictionary clips = PcmSynth.SynthesizeAll(wetMixMode); + int count = 0; + foreach (var kv in clips) + { + PcmClipData clip = kv.Value; + var stream = new AudioStreamWav + { + Format = AudioStreamWav.FormatEnum.Format16Bits, + MixRate = clip.SampleRate, + Stereo = false, + LoopMode = clip.IsLoop ? AudioStreamWav.LoopModeEnum.Forward : AudioStreamWav.LoopModeEnum.Disabled, + LoopBegin = 0, + LoopEnd = clip.IsLoop ? clip.Samples.Length : 0, + Data = clip.Pcm16Bytes + }; + _streams[clip.Key] = stream; + count++; + } + ProceduralClipCount = count; + } +} diff --git a/client/RustToDust.Client.csproj b/client/RustToDust.Client.csproj new file mode 100644 index 0000000..6ed04f3 --- /dev/null +++ b/client/RustToDust.Client.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + true + enable + RustToDust.Client + RustToDust.Client + Release + + + + + + + + diff --git a/client/ServerBrowser.cs b/client/ServerBrowser.cs new file mode 100644 index 0000000..eda6536 --- /dev/null +++ b/client/ServerBrowser.cs @@ -0,0 +1,738 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Godot; +using RustToDust.Net; + +namespace RustToDust.Client; + +/// +/// Public Yggdrasil directory server browser with live non-blocking UDP RTDP +/// ping probes, optional 127.0.0.1:3076 localhost probe, and direct IP:Port join. +/// +public sealed partial class ServerBrowser : CanvasLayer +{ + public const string DefaultDirectoryUrl = "https://eureka.gamecult.org/rtd-directory"; + + private sealed class ServerRowModel + { + public required string Key; + public required string Host; + public required int Port; + public required string Name; + public required string Map; + public required int Humans; + public required int MaxHumans; + public required string Phase; + public required bool IsLocalProbe; + public int? PingMs; + public bool TimedOut; + public bool Probing = true; + public bool Disposed; + + public Button? RowButton; + public Label? NameLabel; + public Label? MapLabel; + public Label? PlayersLabel; + public Label? PhaseLabel; + public Label? PingLabel; + public Label? AddressLabel; + } + + private readonly ConcurrentQueue _mainThreadQueue = new(); + private readonly List _rows = new(); + + private Control _root = null!; + private Label _dirStatusLabel = null!; + private Label _dirUrlLabel = null!; + private VBoxContainer _rowsContainer = null!; + private CheckBox _probeLocalhostCheck = null!; + private LineEdit _directEndpointEdit = null!; + private Button _refreshBtn = null!; + private Button _joinBtn = null!; + private Label _footerErrorLabel = null!; + + private CancellationTokenSource? _refreshCts; + private int _refreshSeq; + private string _directoryUrl = DefaultDirectoryUrl; + private string _callsign = "Pilot"; + private string? _selectedKey; + + public ServerBrowser() + { + Layer = 20; + } + + public event Action? JoinRequested; + public event Action? HostRequested; + public event Action? BackRequested; + + public bool IsTextInputFocused => Visible && _directEndpointEdit is not null && _directEndpointEdit.HasFocus(); + public int RowCount => _rows.Count; + + public override void _Ready() + { + BuildUi(); + SetBrowserVisible(false); + } + + public override void _ExitTree() + { + CancelPendingRefresh(); + } + + public override void _Process(double delta) + { + while (_mainThreadQueue.TryDequeue(out var action)) + { + action(); + } + } + + public void Configure(string directoryUrl, string callsign, string? defaultDirectEndpoint = null) + { + _directoryUrl = directoryUrl ?? string.Empty; + _callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim(); + if (_dirUrlLabel is not null) + { + _dirUrlLabel.Text = string.IsNullOrWhiteSpace(_directoryUrl) + ? "DIRECTORY: DISABLED" + : $"DIRECTORY: {_directoryUrl}"; + } + if (_directEndpointEdit is not null && !string.IsNullOrWhiteSpace(defaultDirectEndpoint)) + { + _directEndpointEdit.Text = defaultDirectEndpoint.Trim(); + } + } + + public void SetBrowserVisible(bool visible, bool autoRefresh = true) + { + Visible = visible; + if (_root is not null) + { + _root.Visible = visible; + } + if (visible) + { + SetError(null); + if (autoRefresh) + { + Refresh(); + } + } + else + { + CancelPendingRefresh(); + _directEndpointEdit?.ReleaseFocus(); + } + } + + public void SetError(string? message) + { + if (_footerErrorLabel is null) return; + if (string.IsNullOrWhiteSpace(message)) + { + _footerErrorLabel.Visible = false; + _footerErrorLabel.Text = string.Empty; + return; + } + _footerErrorLabel.Text = message.Trim(); + _footerErrorLabel.Visible = true; + } + + public void Refresh() + { + CancelPendingRefresh(); + int seq = ++_refreshSeq; + _refreshCts = new CancellationTokenSource(); + CancellationToken ct = _refreshCts.Token; + + ClearRows(); + _selectedKey = null; + UpdateJoinButtonState(); + SetError(null); + + bool probeLocal = _probeLocalhostCheck is null || _probeLocalhostCheck.ButtonPressed; + if (probeLocal) + { + var localRow = new ServerRowModel + { + Key = "local:127.0.0.1:3076", + Host = "127.0.0.1", + Port = 3076, + Name = "LOCALHOST (127.0.0.1:3076)", + Map = "-", + Humans = 0, + MaxHumans = 12, + Phase = "PROBING", + IsLocalProbe = true, + Probing = true + }; + AddRowWidget(localRow); + _ = ProbeRowAsync(localRow, seq, ct); + } + + string dirUrl = DirectoryBrowserClient.NormalizeBaseUrl(_directoryUrl); + if (string.IsNullOrEmpty(dirUrl)) + { + SetDirectoryStatus("Directory URL not configured — local/direct connect ready.", isWarning: true); + return; + } + + SetDirectoryStatus("Querying public Yggdrasil directory...", isWarning: false); + + _ = Task.Run(async () => + { + try + { + var servers = await DirectoryBrowserClient.FetchServersAsync(dirUrl, ct).ConfigureAwait(false); + _mainThreadQueue.Enqueue(() => + { + if (!IsInsideTree() || seq != _refreshSeq) return; + OnDirectoryFetched(servers, seq, ct); + }); + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + _mainThreadQueue.Enqueue(() => + { + if (!IsInsideTree() || seq != _refreshSeq) return; + SetDirectoryStatus($"Directory offline ({ShortError(ex.Message)}) — direct IP:Port connect available.", isWarning: true); + }); + } + }, ct); + } + + private void OnDirectoryFetched(IReadOnlyList servers, int seq, CancellationToken ct) + { + if (servers.Count == 0) + { + SetDirectoryStatus("Directory online — 0 public servers listed.", isWarning: false); + return; + } + + SetDirectoryStatus($"Directory online — {servers.Count} {(servers.Count == 1 ? "server" : "servers")} listed. Pinging...", isWarning: false); + + for (int i = 0; i < servers.Count; i++) + { + var s = servers[i]; + if (string.IsNullOrWhiteSpace(s.PublicHost) || s.UdpPort is < 1 or > 65535) + { + continue; + } + + // Avoid duplicating localhost row if directory explicitly lists 127.0.0.1:3076 + bool isLoopbackDefault = string.Equals(s.PublicHost, "127.0.0.1", StringComparison.Ordinal) && s.UdpPort == 3076; + if (isLoopbackDefault) + { + RemoveLocalProbeRowIfPresent(); + } + + var row = new ServerRowModel + { + Key = $"dir:{s.ServerId:N}:{s.PublicHost}:{s.UdpPort}", + Host = s.PublicHost, + Port = s.UdpPort, + Name = string.IsNullOrWhiteSpace(s.Name) ? $"{s.PublicHost}:{s.UdpPort}" : s.Name.Trim(), + Map = FormatMap(s.Map), + Humans = s.Humans, + MaxHumans = s.MaxHumans > 0 ? s.MaxHumans : 12, + Phase = FormatPhase(s.Phase), + IsLocalProbe = false, + Probing = true + }; + AddRowWidget(row); + _ = ProbeRowAsync(row, seq, ct); + } + } + + private async Task ProbeRowAsync(ServerRowModel row, int seq, CancellationToken ct) + { + try + { + var result = await ServerPingProbe.ProbeAsync(row.Host, row.Port, TimeSpan.FromMilliseconds(1400), ct).ConfigureAwait(false); + _mainThreadQueue.Enqueue(() => + { + if (!IsInsideTree() || seq != _refreshSeq || row.Disposed || !_rows.Contains(row) || row.RowButton is null || !IsInstanceValid(row.RowButton)) return; + row.Probing = false; + if (result.Success && result.Summary is { } summary) + { + row.PingMs = result.RttMs; + row.TimedOut = false; + if (!string.IsNullOrWhiteSpace(summary.ServerName)) + { + row.Name = row.IsLocalProbe + ? $"[LOCAL] {summary.ServerName.Trim()}" + : summary.ServerName.Trim(); + } + row.Map = summary.MapKind == RustToDust.Core.ArenaMapKind.Sion ? "SION" : "DESERT"; + row.Humans = summary.Humans; + row.MaxHumans = summary.MaxHumans > 0 ? summary.MaxHumans : 12; + row.Phase = summary.Phase switch + { + RustToDust.Core.MatchPhase.Lobby => "LOBBY", + RustToDust.Core.MatchPhase.Completed => "COMPLETE", + _ => "IN-MATCH" + }; + } + else + { + row.PingMs = null; + row.TimedOut = true; + if (row.IsLocalProbe) + { + row.Phase = "OFFLINE"; + } + } + SyncRowVisual(row); + }); + } + catch (OperationCanceledException) + { + } + catch + { + _mainThreadQueue.Enqueue(() => + { + if (!IsInsideTree() || seq != _refreshSeq || row.Disposed || !_rows.Contains(row) || row.RowButton is null || !IsInstanceValid(row.RowButton)) return; + row.Probing = false; + row.PingMs = null; + row.TimedOut = true; + SyncRowVisual(row); + }); + } + } + + private void CancelPendingRefresh() + { + _refreshSeq++; + if (_refreshCts is not null) + { + try { _refreshCts.Cancel(); } catch { } + _refreshCts.Dispose(); + _refreshCts = null; + } + while (_mainThreadQueue.TryDequeue(out _)) { } + } + + private void BuildUi() + { + _root = new Control + { + Name = "ServerBrowserRoot", + MouseFilter = Control.MouseFilterEnum.Stop + }; + _root.SetAnchorsPreset(Control.LayoutPreset.FullRect); + AddChild(_root); + + var scrim = new ColorRect + { + Color = new Color(0.03f, 0.04f, 0.03f, 0.42f), + MouseFilter = Control.MouseFilterEnum.Stop + }; + scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect); + _root.AddChild(scrim); + + var panel = ImperialChrome.CreatePanel(ImperialChrome.CyanCol, cornerLen: 18f, borderPx: 2f, bgAlpha: 0.93f, padH: 18, padV: 16); + panel.Name = "ServerBrowserPanel"; + panel.AnchorLeft = 0.5f; + panel.AnchorRight = 0.5f; + panel.AnchorTop = 0.5f; + panel.AnchorBottom = 0.5f; + panel.OffsetLeft = -530f; + panel.OffsetRight = 530f; + panel.OffsetTop = -290f; + panel.OffsetBottom = 290f; + _root.AddChild(panel); + + var vbox = new VBoxContainer(); + vbox.AddThemeConstantOverride("separation", 10); + panel.AddChild(vbox); + + // Header bar + var headerRow = new HBoxContainer(); + headerRow.AddThemeConstantOverride("separation", 10); + vbox.AddChild(headerRow); + + var titleCol = new VBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; + titleCol.AddThemeConstantOverride("separation", 2); + headerRow.AddChild(titleCol); + titleCol.AddChild(ImperialChrome.CreateLabel("PUBLIC YGGDRASIL SERVER BROWSER", 20, ImperialChrome.CyanCol)); + _dirUrlLabel = ImperialChrome.CreateLabel($"DIRECTORY: {_directoryUrl}", 11, ImperialChrome.TextMuted); + titleCol.AddChild(_dirUrlLabel); + + _refreshBtn = ImperialChrome.CreateButton("REFRESH", ImperialChrome.CyanCol, 13, 34f); + _refreshBtn.CustomMinimumSize = new Vector2(108f, 34f); + _refreshBtn.Pressed += Refresh; + headerRow.AddChild(_refreshBtn); + + var hostBtn = ImperialChrome.CreateButton("HOST", ImperialChrome.GoldCol, 13, 34f); + hostBtn.CustomMinimumSize = new Vector2(92f, 34f); + hostBtn.Pressed += () => HostRequested?.Invoke(); + headerRow.AddChild(hostBtn); + + var backBtn = ImperialChrome.CreateButton("BACK", ImperialChrome.OrangeCol, 13, 34f); + backBtn.CustomMinimumSize = new Vector2(92f, 34f); + backBtn.Pressed += () => BackRequested?.Invoke(); + headerRow.AddChild(backBtn); + + // Status + Localhost toggle row + var subRow = new HBoxContainer(); + subRow.AddThemeConstantOverride("separation", 12); + vbox.AddChild(subRow); + + _dirStatusLabel = ImperialChrome.CreateLabel("Ready.", 12, ImperialChrome.TextMuted); + _dirStatusLabel.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; + _dirStatusLabel.ClipText = true; + subRow.AddChild(_dirStatusLabel); + + _probeLocalhostCheck = new CheckBox + { + Text = "Probe Localhost (127.0.0.1:3076)", + ButtonPressed = true + }; + ImperialChrome.StyleCheckBox(_probeLocalhostCheck, ImperialChrome.OliveCol, 12); + _probeLocalhostCheck.Toggled += _ => Refresh(); + subRow.AddChild(_probeLocalhostCheck); + + vbox.AddChild(ImperialChrome.MakeRule()); + + // Column headers + var colHeader = new HBoxContainer(); + colHeader.AddThemeConstantOverride("separation", 8); + vbox.AddChild(colHeader); + AddHeaderCell(colHeader, "SERVER NAME", expand: true, width: 0f); + AddHeaderCell(colHeader, "MAP", expand: false, width: 96f); + AddHeaderCell(colHeader, "PLAYERS", expand: false, width: 90f); + AddHeaderCell(colHeader, "PHASE", expand: false, width: 112f); + AddHeaderCell(colHeader, "PING", expand: false, width: 100f); + AddHeaderCell(colHeader, "ENDPOINT", expand: false, width: 175f); + + // Scrollable rows + var listFrame = new PanelContainer + { + SizeFlagsVertical = Control.SizeFlags.ExpandFill + }; + var frameStyle = new StyleBoxFlat + { + BgColor = new Color(ImperialChrome.BgDark.R, ImperialChrome.BgDark.G, ImperialChrome.BgDark.B, 0.72f), + BorderColor = ImperialChrome.BorderCol, + ContentMarginLeft = 6, + ContentMarginRight = 6, + ContentMarginTop = 6, + ContentMarginBottom = 6 + }; + frameStyle.SetBorderWidthAll(1); + listFrame.AddThemeStyleboxOverride("panel", frameStyle); + vbox.AddChild(listFrame); + + var scroll = new ScrollContainer + { + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, + SizeFlagsVertical = Control.SizeFlags.ExpandFill, + HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled + }; + listFrame.AddChild(scroll); + + _rowsContainer = new VBoxContainer + { + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + _rowsContainer.AddThemeConstantOverride("separation", 4); + scroll.AddChild(_rowsContainer); + + vbox.AddChild(ImperialChrome.MakeRule()); + + // Footer: direct IP:Port + Join Selected + var footerRow = new HBoxContainer(); + footerRow.AddThemeConstantOverride("separation", 10); + vbox.AddChild(footerRow); + + footerRow.AddChild(ImperialChrome.CreateLabel("DIRECT IP:PORT", 12, ImperialChrome.TextMuted)); + + _directEndpointEdit = new LineEdit + { + Text = "127.0.0.1:3076", + PlaceholderText = "127.0.0.1:3076", + MaxLength = 96, + CustomMinimumSize = new Vector2(240f, 34f) + }; + ImperialChrome.StyleLineEdit(_directEndpointEdit, ImperialChrome.CyanCol, 13); + _directEndpointEdit.TextSubmitted += _ => JoinDirect(); + footerRow.AddChild(_directEndpointEdit); + + var directBtn = ImperialChrome.CreateButton("DIRECT CONNECT", ImperialChrome.OrangeCol, 13, 34f); + directBtn.CustomMinimumSize = new Vector2(150f, 34f); + directBtn.Pressed += JoinDirect; + footerRow.AddChild(directBtn); + + var spacer = new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; + footerRow.AddChild(spacer); + + _joinBtn = ImperialChrome.CreateButton("JOIN SELECTED", ImperialChrome.OliveCol, 14, 34f); + _joinBtn.CustomMinimumSize = new Vector2(170f, 34f); + _joinBtn.Disabled = true; + _joinBtn.Pressed += JoinSelected; + footerRow.AddChild(_joinBtn); + + _footerErrorLabel = ImperialChrome.CreateLabel(string.Empty, 12, ImperialChrome.RedCol); + _footerErrorLabel.AutowrapMode = TextServer.AutowrapMode.Word; + _footerErrorLabel.Visible = false; + vbox.AddChild(_footerErrorLabel); + } + + private static void AddHeaderCell(HBoxContainer parent, string text, bool expand, float width) + { + var lbl = ImperialChrome.CreateLabel(text, 11, ImperialChrome.TextMuted); + if (expand) + { + lbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; + } + else + { + lbl.CustomMinimumSize = new Vector2(width, 0f); + } + parent.AddChild(lbl); + } + + private void ClearRows() + { + for (int i = 0; i < _rows.Count; i++) + { + _rows[i].Disposed = true; + } + _rows.Clear(); + if (_rowsContainer is null) return; + for (int i = _rowsContainer.GetChildCount() - 1; i >= 0; i--) + { + var c = _rowsContainer.GetChild(i); + _rowsContainer.RemoveChild(c); + c.QueueFree(); + } + } + + private void RemoveLocalProbeRowIfPresent() + { + for (int i = _rows.Count - 1; i >= 0; i--) + { + if (!_rows[i].IsLocalProbe) continue; + var row = _rows[i]; + row.Disposed = true; + var btn = row.RowButton; + _rows.RemoveAt(i); + if (btn is not null && IsInstanceValid(btn)) + { + _rowsContainer.RemoveChild(btn); + btn.QueueFree(); + } + } + } + + private void AddRowWidget(ServerRowModel row) + { + _rows.Add(row); + + var btn = new Button + { + FocusMode = Control.FocusModeEnum.None, + CustomMinimumSize = new Vector2(0f, 34f), + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + row.RowButton = btn; + + var hbox = new HBoxContainer + { + MouseFilter = Control.MouseFilterEnum.Ignore + }; + hbox.SetAnchorsPreset(Control.LayoutPreset.FullRect); + hbox.OffsetLeft = 10f; + hbox.OffsetRight = -10f; + hbox.AddThemeConstantOverride("separation", 8); + btn.AddChild(hbox); + + row.NameLabel = MakeRowCell(row.Name, 13, ImperialChrome.TextLight, expand: true, width: 0f); + row.MapLabel = MakeRowCell(row.Map, 12, ImperialChrome.OliveCol, expand: false, width: 96f); + row.PlayersLabel = MakeRowCell($"{row.Humans}/{row.MaxHumans}", 12, ImperialChrome.TextLight, expand: false, width: 90f); + row.PhaseLabel = MakeRowCell(row.Phase, 12, ImperialChrome.CyanCol, expand: false, width: 112f); + row.PingLabel = MakeRowCell("...", 12, ImperialChrome.TextMuted, expand: false, width: 100f); + row.AddressLabel = MakeRowCell($"{row.Host}:{row.Port}", 11, ImperialChrome.TextMuted, expand: false, width: 175f); + + hbox.AddChild(row.NameLabel); + hbox.AddChild(row.MapLabel); + hbox.AddChild(row.PlayersLabel); + hbox.AddChild(row.PhaseLabel); + hbox.AddChild(row.PingLabel); + hbox.AddChild(row.AddressLabel); + + btn.Pressed += () => SelectRow(row); + btn.GuiInput += ev => + { + if (ev is InputEventMouseButton mb && mb.Pressed && mb.DoubleClick && mb.ButtonIndex == MouseButton.Left) + { + SelectRow(row); + JoinSelected(); + } + }; + + _rowsContainer.AddChild(btn); + SyncRowVisual(row); + } + + private static Label MakeRowCell(string text, int fontSize, Color color, bool expand, float width) + { + var lbl = new Label + { + Text = text, + VerticalAlignment = VerticalAlignment.Center, + ClipText = true, + MouseFilter = Control.MouseFilterEnum.Ignore + }; + lbl.AddThemeFontSizeOverride("font_size", fontSize); + lbl.AddThemeColorOverride("font_color", color); + if (expand) + { + lbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; + } + else + { + lbl.CustomMinimumSize = new Vector2(width, 0f); + } + return lbl; + } + + private void SelectRow(ServerRowModel row) + { + _selectedKey = row.Key; + if (_directEndpointEdit is not null && !_directEndpointEdit.HasFocus()) + { + _directEndpointEdit.Text = $"{row.Host}:{row.Port}"; + } + for (int i = 0; i < _rows.Count; i++) + { + SyncRowVisual(_rows[i]); + } + UpdateJoinButtonState(); + } + + private void SyncRowVisual(ServerRowModel row) + { + if (row.Disposed || !_rows.Contains(row) || row.RowButton is null || !IsInstanceValid(row.RowButton)) return; + bool selected = string.Equals(_selectedKey, row.Key, StringComparison.Ordinal); + + Color accent = selected + ? ImperialChrome.OliveCol + : (row.TimedOut ? ImperialChrome.BorderCol : ImperialChrome.CyanCol); + var normal = new StyleBoxFlat + { + BgColor = selected ? ImperialChrome.BgPressed : ImperialChrome.BgInner, + BorderColor = selected ? ImperialChrome.OliveCol : new Color(ImperialChrome.BorderCol.R, ImperialChrome.BorderCol.G, ImperialChrome.BorderCol.B, 0.7f) + }; + normal.SetBorderWidthAll(selected ? 2 : 1); + var hover = new StyleBoxFlat + { + BgColor = ImperialChrome.BgHover, + BorderColor = accent + }; + hover.SetBorderWidthAll(1); + + row.RowButton.AddThemeStyleboxOverride("normal", normal); + row.RowButton.AddThemeStyleboxOverride("hover", hover); + row.RowButton.AddThemeStyleboxOverride("pressed", hover); + row.RowButton.AddThemeStyleboxOverride("focus", hover); + + row.NameLabel!.Text = row.Name; + row.NameLabel.AddThemeColorOverride("font_color", row.TimedOut && row.IsLocalProbe ? ImperialChrome.TextMuted : ImperialChrome.TextLight); + row.MapLabel!.Text = row.Map; + row.PlayersLabel!.Text = $"{row.Humans}/{row.MaxHumans}"; + row.PhaseLabel!.Text = row.Phase; + + Color phaseCol = row.Phase switch + { + "LOBBY" => ImperialChrome.OliveCol, + "IN-MATCH" => ImperialChrome.GoldCol, + "OFFLINE" => ImperialChrome.TextMuted, + _ => ImperialChrome.CyanCol + }; + row.PhaseLabel.AddThemeColorOverride("font_color", phaseCol); + + if (row.Probing) + { + row.PingLabel!.Text = "..."; + row.PingLabel.AddThemeColorOverride("font_color", ImperialChrome.TextMuted); + } + else if (row.PingMs is int ms) + { + row.PingLabel!.Text = $"{ms} ms"; + Color pingCol = ms < 70 ? ImperialChrome.OliveCol : (ms < 150 ? ImperialChrome.GoldCol : ImperialChrome.OrangeCol); + row.PingLabel.AddThemeColorOverride("font_color", pingCol); + } + else + { + row.PingLabel!.Text = "TIMEOUT"; + row.PingLabel.AddThemeColorOverride("font_color", ImperialChrome.RedCol); + } + + row.AddressLabel!.Text = $"{row.Host}:{row.Port}"; + } + + private void UpdateJoinButtonState() + { + if (_joinBtn is null) return; + _joinBtn.Disabled = string.IsNullOrEmpty(_selectedKey); + } + + private void JoinSelected() + { + for (int i = 0; i < _rows.Count; i++) + { + if (string.Equals(_rows[i].Key, _selectedKey, StringComparison.Ordinal)) + { + string ep = $"{_rows[i].Host}:{_rows[i].Port}"; + JoinRequested?.Invoke(ep, _callsign); + return; + } + } + } + + private void JoinDirect() + { + string ep = (_directEndpointEdit?.Text ?? string.Empty).Trim(); + if (string.IsNullOrEmpty(ep)) + { + SetError("Enter host:port to connect directly."); + return; + } + SetError(null); + JoinRequested?.Invoke(ep, _callsign); + } + + private void SetDirectoryStatus(string message, bool isWarning) + { + if (_dirStatusLabel is null) return; + _dirStatusLabel.Text = message; + _dirStatusLabel.AddThemeColorOverride("font_color", isWarning ? ImperialChrome.OrangeCol : ImperialChrome.OliveCol); + } + + private static string FormatMap(string? map) => + string.Equals(map, "sion", StringComparison.OrdinalIgnoreCase) ? "SION" : "DESERT"; + + private static string FormatPhase(string? phase) + { + if (string.Equals(phase, "Lobby", StringComparison.OrdinalIgnoreCase)) return "LOBBY"; + if (string.Equals(phase, "Completed", StringComparison.OrdinalIgnoreCase)) return "COMPLETE"; + return "IN-MATCH"; + } + + private static string ShortError(string msg) + { + if (string.IsNullOrWhiteSpace(msg)) return "unreachable"; + string oneLine = msg.Replace('\r', ' ').Replace('\n', ' ').Trim(); + return oneLine.Length > 64 ? oneLine[..64] + "..." : oneLine; + } +} diff --git a/client/SettingsOverlay.cs b/client/SettingsOverlay.cs new file mode 100644 index 0000000..e6ce30f --- /dev/null +++ b/client/SettingsOverlay.cs @@ -0,0 +1,407 @@ +using System; +using Godot; + +namespace RustToDust.Client; + +/// +/// Industrial Imperial Settings overlay with left-rail submenu navigation +/// (GRAPHICS active; Audio/Controls placeholders for future passes). +/// Decoupled from persistence: receives values via +/// and emits change/reset/back events. +/// +public sealed partial class SettingsOverlay : CanvasLayer +{ + public enum SettingsCategory + { + Graphics = 0 + } + + private Control _root = null!; + private ImperialChromePanel _panel = null!; + private Button _graphicsTabBtn = null!; + private Control _graphicsPane = null!; + + private readonly Button[] _vfxResButtons = new Button[3]; + private readonly Button[] _volSampleButtons = new Button[4]; + private readonly Button[] _sdfgiButtons = new Button[3]; + private readonly Button[] _displayModeButtons = new Button[2]; + + private VfxResolutionScale _vfxRes = VfxResolutionScale.Half; + private VolumetricSamples _volSamples = VolumetricSamples.Medium; + private SdfgiQuality _sdfgi = SdfgiQuality.Balanced; + private bool _borderlessFullscreen = true; + private bool _built; + + public SettingsOverlay() + { + Layer = 22; + } + + public event Action? GraphicsChanged; + public event Action? ResetDefaultsRequested; + public event Action? BackRequested; + + public bool IsOpen => Visible; + + public override void _Ready() + { + BuildUi(); + SetSettingsVisible(false); + } + + public void SetSettingsVisible(bool visible) + { + Visible = visible; + if (_root is not null) + { + _root.Visible = visible; + } + } + + public void SetGraphicsValues( + VfxResolutionScale vfxRes, + VolumetricSamples volSamples, + SdfgiQuality sdfgi, + bool borderlessFullscreen) + { + _vfxRes = vfxRes; + _volSamples = volSamples; + _sdfgi = sdfgi; + _borderlessFullscreen = borderlessFullscreen; + if (_built) + { + RefreshSelectionVisuals(); + } + } + + private void BuildUi() + { + _root = new Control + { + Name = "SettingsOverlayRoot", + MouseFilter = Control.MouseFilterEnum.Stop + }; + _root.SetAnchorsPreset(Control.LayoutPreset.FullRect); + AddChild(_root); + + var scrim = new ColorRect + { + Color = ImperialChrome.ScrimCol, + MouseFilter = Control.MouseFilterEnum.Stop + }; + scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect); + _root.AddChild(scrim); + + _panel = ImperialChrome.CreatePanel( + ImperialChrome.OrangeCol, + cornerLen: 18f, + borderPx: 2f, + bgAlpha: 0.94f, + padH: 22, + padV: 20); + _panel.Name = "SettingsPanel"; + _panel.AnchorLeft = 0.5f; + _panel.AnchorRight = 0.5f; + _panel.AnchorTop = 0.5f; + _panel.AnchorBottom = 0.5f; + _panel.OffsetLeft = -440f; + _panel.OffsetRight = 440f; + _panel.OffsetTop = -255f; + _panel.OffsetBottom = 255f; + _root.AddChild(_panel); + + var outerVbox = new VBoxContainer(); + outerVbox.AddThemeConstantOverride("separation", 12); + _panel.AddChild(outerVbox); + + // Header + var headerRow = new HBoxContainer(); + headerRow.AddThemeConstantOverride("separation", 12); + outerVbox.AddChild(headerRow); + + var titleCol = new VBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; + titleCol.AddThemeConstantOverride("separation", 2); + headerRow.AddChild(titleCol); + titleCol.AddChild(ImperialChrome.CreateLabel("SYSTEM CONFIGURATION • SUBMENU", 11, ImperialChrome.GoldCol)); + titleCol.AddChild(ImperialChrome.CreateLabel("SETTINGS", 24, ImperialChrome.TextLight)); + + var liveBadge = ImperialChrome.CreateLabel("LIVE APPLY • NO RESTART", 11, ImperialChrome.CyanCol, HorizontalAlignment.Right); + liveBadge.VerticalAlignment = VerticalAlignment.Bottom; + headerRow.AddChild(liveBadge); + + outerVbox.AddChild(ImperialChrome.MakeRule()); + + // Main Split: Submenu Rail + Content Pane + var split = new HBoxContainer + { + SizeFlagsVertical = Control.SizeFlags.ExpandFill + }; + split.AddThemeConstantOverride("separation", 18); + outerVbox.AddChild(split); + + var navCol = new VBoxContainer + { + CustomMinimumSize = new Vector2(168f, 0f) + }; + navCol.AddThemeConstantOverride("separation", 8); + split.AddChild(navCol); + + navCol.AddChild(ImperialChrome.CreateLabel("CATEGORIES", 10, ImperialChrome.TextMuted)); + + _graphicsTabBtn = ImperialChrome.CreateButton("GRAPHICS", ImperialChrome.CyanCol, 13, 38f); + StyleSegmentedButton(_graphicsTabBtn, selected: true, ImperialChrome.CyanCol); + _graphicsTabBtn.Pressed += () => SelectCategory(SettingsCategory.Graphics); + navCol.AddChild(_graphicsTabBtn); + + var audioTabBtn = ImperialChrome.CreateButton("AUDIO [SOON]", ImperialChrome.BorderCol, 12, 34f); + audioTabBtn.Disabled = true; + audioTabBtn.TooltipText = "Audio controls arrive in a future pass"; + navCol.AddChild(audioTabBtn); + + var controlsTabBtn = ImperialChrome.CreateButton("CONTROLS [SOON]", ImperialChrome.BorderCol, 12, 34f); + controlsTabBtn.Disabled = true; + controlsTabBtn.TooltipText = "Input bindings arrive in a future pass"; + navCol.AddChild(controlsTabBtn); + + var vSep = new VSeparator(); + vSep.AddThemeStyleboxOverride("separator", new StyleBoxLine + { + Color = new Color(ImperialChrome.BorderCol.R, ImperialChrome.BorderCol.G, ImperialChrome.BorderCol.B, 0.75f), + Thickness = 1, + Vertical = true + }); + split.AddChild(vSep); + + _graphicsPane = new VBoxContainer + { + Name = "GraphicsSettingsPane", + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, + SizeFlagsVertical = Control.SizeFlags.ExpandFill + }; + ((VBoxContainer)_graphicsPane).AddThemeConstantOverride("separation", 12); + split.AddChild(_graphicsPane); + + _graphicsPane.AddChild(ImperialChrome.CreateLabel("GRAPHICS • VOLUMETRICS, GI & DISPLAY", 14, ImperialChrome.CyanCol)); + + // 1. VFX / Fog Resolution + AddSettingRow( + _graphicsPane, + "VFX / FOG RESOLUTION", + "Compute resolution for raymarched smoke, fireballs & plumes (Full = 1:1 native)", + new[] + { + ("Half (0.5x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.Half))), + ("High (0.75x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.ThreeQuarter))), + ("Full (1.0x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.Full))) + }, + _vfxResButtons); + + // 2. Volumetric Sample Count + AddSettingRow( + _graphicsPane, + "VOLUMETRIC SAMPLE COUNT", + "Raymarch step budget per pixel (higher = smoother volume density & gradients)", + new[] + { + ("Low (8)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Low))), + ("Medium (10)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Medium))), + ("High (16)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.High))), + ("Ultra (24)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Ultra))) + }, + _volSampleButtons); + + // 3. Global Illumination (SDFGI) + AddSettingRow( + _graphicsPane, + "GLOBAL ILLUMINATION (SDFGI)", + "Signed-distance multi-bounce sky & terrain indirect lighting", + new[] + { + ("Off", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.Off))), + ("Balanced", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.Balanced))), + ("High", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.High))) + }, + _sdfgiButtons); + + // 4. Display Mode + AddSettingRow( + _graphicsPane, + "DISPLAY MODE", + "Window presentation mode (also toggleable anytime via Alt+Enter or F11)", + new[] + { + ("Borderless Fullscreen", (Action)(() => OnGraphicsOptionSelected(borderlessFullscreen: true))), + ("Windowed", (Action)(() => OnGraphicsOptionSelected(borderlessFullscreen: false))) + }, + _displayModeButtons); + + outerVbox.AddChild(ImperialChrome.MakeRule()); + + // Footer + var footerRow = new HBoxContainer(); + footerRow.AddThemeConstantOverride("separation", 10); + outerVbox.AddChild(footerRow); + + var resetBtn = ImperialChrome.CreateButton("RESET DEFAULTS", ImperialChrome.GoldCol, 13, 36f); + resetBtn.CustomMinimumSize = new Vector2(180f, 36f); + resetBtn.Pressed += () => ResetDefaultsRequested?.Invoke(); + footerRow.AddChild(resetBtn); + + footerRow.AddChild(new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }); + + var backBtn = ImperialChrome.CreateButton("BACK [ESC]", ImperialChrome.OrangeCol, 13, 36f); + backBtn.CustomMinimumSize = new Vector2(160f, 36f); + backBtn.Pressed += () => BackRequested?.Invoke(); + footerRow.AddChild(backBtn); + + _built = true; + RefreshSelectionVisuals(); + } + + private static void AddSettingRow( + Control parent, + string labelText, + string hintText, + (string Text, Action OnSelect)[] options, + Button[] targetButtons) + { + var block = new VBoxContainer(); + block.AddThemeConstantOverride("separation", 4); + parent.AddChild(block); + + var row = new HBoxContainer(); + row.AddThemeConstantOverride("separation", 12); + block.AddChild(row); + + var lbl = ImperialChrome.CreateLabel(labelText, 12, ImperialChrome.TextLight); + lbl.CustomMinimumSize = new Vector2(228f, 0f); + lbl.VerticalAlignment = VerticalAlignment.Center; + row.AddChild(lbl); + + var btnGroup = new HBoxContainer + { + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + btnGroup.AddThemeConstantOverride("separation", 6); + row.AddChild(btnGroup); + + for (int i = 0; i < options.Length; i++) + { + var (text, onSelect) = options[i]; + var btn = ImperialChrome.CreateButton(text, ImperialChrome.CyanCol, 12, 32f); + btn.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; + btn.Pressed += onSelect; + btnGroup.AddChild(btn); + targetButtons[i] = btn; + } + + var hint = ImperialChrome.CreateLabel(hintText, 10, ImperialChrome.TextMuted); + block.AddChild(hint); + } + + private void SelectCategory(SettingsCategory category) + { + if (category == SettingsCategory.Graphics && _graphicsPane is not null) + { + _graphicsPane.Visible = true; + } + } + + private void OnGraphicsOptionSelected( + VfxResolutionScale? vfxRes = null, + VolumetricSamples? volSamples = null, + SdfgiQuality? sdfgi = null, + bool? borderlessFullscreen = null) + { + VfxResolutionScale nextRes = vfxRes ?? _vfxRes; + VolumetricSamples nextSamples = volSamples ?? _volSamples; + SdfgiQuality nextSdfgi = sdfgi ?? _sdfgi; + bool nextFullscreen = borderlessFullscreen ?? _borderlessFullscreen; + + if (nextRes == _vfxRes + && nextSamples == _volSamples + && nextSdfgi == _sdfgi + && nextFullscreen == _borderlessFullscreen) + { + return; + } + + _vfxRes = nextRes; + _volSamples = nextSamples; + _sdfgi = nextSdfgi; + _borderlessFullscreen = nextFullscreen; + RefreshSelectionVisuals(); + GraphicsChanged?.Invoke(_vfxRes, _volSamples, _sdfgi, _borderlessFullscreen); + } + + private void RefreshSelectionVisuals() + { + for (int i = 0; i < _vfxResButtons.Length; i++) + { + StyleSegmentedButton(_vfxResButtons[i], i == (int)_vfxRes, ImperialChrome.CyanCol); + } + for (int i = 0; i < _volSampleButtons.Length; i++) + { + StyleSegmentedButton(_volSampleButtons[i], i == (int)_volSamples, ImperialChrome.CyanCol); + } + for (int i = 0; i < _sdfgiButtons.Length; i++) + { + StyleSegmentedButton(_sdfgiButtons[i], i == (int)_sdfgi, ImperialChrome.OliveCol); + } + StyleSegmentedButton(_displayModeButtons[0], _borderlessFullscreen, ImperialChrome.OrangeCol); + StyleSegmentedButton(_displayModeButtons[1], !_borderlessFullscreen, ImperialChrome.OrangeCol); + } + + private static void StyleSegmentedButton(Button btn, bool selected, Color accentColor) + { + if (selected) + { + btn.AddThemeFontSizeOverride("font_size", 12); + btn.AddThemeColorOverride("font_color", Colors.White); + btn.AddThemeColorOverride("font_hover_color", Colors.White); + btn.AddThemeColorOverride("font_pressed_color", accentColor); + + var activeBox = MakeSegmentBox( + new Color(accentColor.R * 0.24f + ImperialChrome.BgPressed.R * 0.76f, + accentColor.G * 0.24f + ImperialChrome.BgPressed.G * 0.76f, + accentColor.B * 0.24f + ImperialChrome.BgPressed.B * 0.76f, + 1f), + accentColor, + borderW: 2); + btn.AddThemeStyleboxOverride("normal", activeBox); + btn.AddThemeStyleboxOverride("hover", activeBox); + btn.AddThemeStyleboxOverride("pressed", activeBox); + btn.AddThemeStyleboxOverride("focus", activeBox); + } + else + { + btn.AddThemeFontSizeOverride("font_size", 12); + btn.AddThemeColorOverride("font_color", ImperialChrome.TextMuted); + btn.AddThemeColorOverride("font_hover_color", ImperialChrome.TextLight); + btn.AddThemeColorOverride("font_pressed_color", accentColor); + + var normal = MakeSegmentBox(ImperialChrome.BgInner, ImperialChrome.BorderCol, borderW: 1); + var hover = MakeSegmentBox(ImperialChrome.BgHover, new Color(accentColor.R, accentColor.G, accentColor.B, 0.75f), borderW: 1); + var pressed = MakeSegmentBox(ImperialChrome.BgPressed, accentColor, borderW: 2); + btn.AddThemeStyleboxOverride("normal", normal); + btn.AddThemeStyleboxOverride("hover", hover); + btn.AddThemeStyleboxOverride("pressed", pressed); + btn.AddThemeStyleboxOverride("focus", hover); + } + } + + private static StyleBoxFlat MakeSegmentBox(Color bg, Color border, int borderW) + { + var box = new StyleBoxFlat + { + BgColor = bg, + BorderColor = border, + ContentMarginLeft = 8, + ContentMarginRight = 8, + ContentMarginTop = 5, + ContentMarginBottom = 5 + }; + box.SetBorderWidthAll(borderW); + return box; + } +} diff --git a/client/SionMapRenderer.cs b/client/SionMapRenderer.cs new file mode 100644 index 0000000..834ffc2 --- /dev/null +++ b/client/SionMapRenderer.cs @@ -0,0 +1,322 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Renders Sion, Switzerland legacy building tiles (swapping cleanly between LOD1 <= 520m, LOD2 520..2200m, +/// and culled > 2200m). Terrain rendering is unified in . +/// (This class is scheduled for deletion in Cut 13c when WorldCityRenderer lands.) +/// +public partial class SionMapRenderer : Node3D +{ + public const float Lod1DistanceM = 400f; + public const float CullDistanceM = 1750f; + public const float ShadowDistanceM = 280f; + + private sealed class BuildingTileEntry + { + public int Tx; + public int Tz; + public float CenterX; + public float CenterZ; + public required ArrayMesh Lod1Mesh; + public required ArrayMesh Lod2Mesh; + public required MeshInstance3D Instance; + } + + private readonly List _buildingTiles = new(36); + private readonly Dictionary _sharedBuildingMaterials = new(StringComparer.Ordinal); + private string? _builtForDir; + + public bool IsBuilt { get; private set; } + public int BuildingTileCount => _buildingTiles.Count; + public int ActiveLod1TileCount { get; private set; } + public int ActiveLod2TileCount { get; private set; } + public int CulledTileCount { get; private set; } + + public void EnsureBuilt(SionMapData sion) + { + if (IsBuilt && string.Equals(_builtForDir, sion.DirectoryPath, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + ClearBuilt(); + _builtForDir = sion.DirectoryPath; + BuildBuildingTiles(sion); + IsBuilt = true; + } + + public void UpdateLod(Vector3 camPos) + { + if (!IsBuilt) + { + return; + } + + const float lod1Sq = Lod1DistanceM * Lod1DistanceM; + const float cullSq = CullDistanceM * CullDistanceM; + const float shadowSq = ShadowDistanceM * ShadowDistanceM; + + int lod1Count = 0; + int lod2Count = 0; + int culledCount = 0; + + for (int i = 0; i < _buildingTiles.Count; i++) + { + var t = _buildingTiles[i]; + float dx = t.CenterX - camPos.X; + float dz = t.CenterZ - camPos.Z; + float d2 = dx * dx + dz * dz; + + if (d2 > cullSq) + { + if (t.Instance.Visible) + { + t.Instance.Visible = false; + } + culledCount++; + continue; + } + + if (!t.Instance.Visible) + { + t.Instance.Visible = true; + } + + ArrayMesh desired = d2 <= lod1Sq ? t.Lod1Mesh : t.Lod2Mesh; + if (!ReferenceEquals(t.Instance.Mesh, desired)) + { + t.Instance.Mesh = desired; + } + if (d2 <= lod1Sq) lod1Count++; + else lod2Count++; + + var desiredShadow = d2 <= shadowSq + ? GeometryInstance3D.ShadowCastingSetting.On + : GeometryInstance3D.ShadowCastingSetting.Off; + if (t.Instance.CastShadow != desiredShadow) + { + t.Instance.CastShadow = desiredShadow; + } + } + + ActiveLod1TileCount = lod1Count; + ActiveLod2TileCount = lod2Count; + CulledTileCount = culledCount; + } + + private void BuildBuildingTiles(SionMapData sion) + { + var tiles = sion.Metadata.Tiles; + for (int i = 0; i < tiles.Count; i++) + { + var tm = tiles[i]; + string lod1Path = Path.Combine(sion.DirectoryPath, tm.Lod1RelativePath.Replace('/', Path.DirectorySeparatorChar)); + string lod2Path = Path.Combine(sion.DirectoryPath, tm.Lod2RelativePath.Replace('/', Path.DirectorySeparatorChar)); + + ArrayMesh lod1Mesh = LoadMergedTileGlb(lod1Path); + ArrayMesh lod2Mesh = LoadMergedTileGlb(lod2Path); + + var mi = new MeshInstance3D + { + Name = $"SionBuildings_{tm.Tx}_{tm.Tz}", + Mesh = lod2Mesh, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + AddChild(mi); + + _buildingTiles.Add(new BuildingTileEntry + { + Tx = tm.Tx, + Tz = tm.Tz, + CenterX = tm.Center.X, + CenterZ = tm.Center.Z, + Lod1Mesh = lod1Mesh, + Lod2Mesh = lod2Mesh, + Instance = mi + }); + } + } + + private ArrayMesh LoadMergedTileGlb(string glbPath) + { + if (!File.Exists(glbPath)) + { + throw new FileNotFoundException($"Missing Sion building GLB: {glbPath}", glbPath); + } + + var doc = new GltfDocument(); + var state = new GltfState(); + Error err = doc.AppendFromFile(glbPath, state); + if (err != Error.Ok) + { + throw new InvalidOperationException($"GltfDocument failed to load '{glbPath}': {err}"); + } + + Node? root = doc.GenerateScene(state); + if (root is null) + { + throw new InvalidOperationException($"GltfDocument generated null scene for '{glbPath}'."); + } + + try + { + var byMat = new Dictionary Pos, List Norm, List Idx)>(StringComparer.Ordinal); + CollectMeshesRecursive(root, Transform3D.Identity, byMat); + + var outMesh = new ArrayMesh(); + foreach (var kv in byMat) + { + var entry = kv.Value; + if (entry.Pos.Count == 0 || entry.Idx.Count == 0) + { + continue; + } + + var arrays = new Godot.Collections.Array(); + arrays.Resize((int)Mesh.ArrayType.Max); + arrays[(int)Mesh.ArrayType.Vertex] = entry.Pos.ToArray(); + arrays[(int)Mesh.ArrayType.Normal] = entry.Norm.ToArray(); + arrays[(int)Mesh.ArrayType.Index] = entry.Idx.ToArray(); + + int surfIdx = outMesh.GetSurfaceCount(); + outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays); + outMesh.SurfaceSetMaterial(surfIdx, entry.Mat); + } + + return outMesh; + } + finally + { + root.Free(); + } + } + + private void CollectMeshesRecursive( + Node node, + Transform3D parentXf, + Dictionary Pos, List Norm, List Idx)> byMat) + { + Transform3D xf = node is Node3D n3 ? parentXf * n3.Transform : parentXf; + if (node is MeshInstance3D mi && mi.Mesh is not null) + { + Basis normalBasis = xf.Basis.Inverse().Transposed(); + int surfCount = mi.Mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arr = mi.Mesh.SurfaceGetArrays(s); + if (arr.Count <= (int)Mesh.ArrayType.Vertex) + { + continue; + } + + Vector3[] posArr = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + if (posArr.Length == 0) + { + continue; + } + + Vector3[]? normArr = arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array + ? arr[(int)Mesh.ArrayType.Normal].AsVector3Array() + : null; + int[]? idxArr = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array + ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() + : null; + + Material? srcMat = mi.Mesh.SurfaceGetMaterial(s); + (string matKey, StandardMaterial3D sharedMat) = GetOrShareBuildingMaterial(srcMat); + + if (!byMat.TryGetValue(matKey, out var bucket)) + { + bucket = (sharedMat, new List(posArr.Length), new List(posArr.Length), new List(idxArr?.Length ?? posArr.Length)); + byMat[matKey] = bucket; + } + + int baseVert = bucket.Pos.Count; + for (int v = 0; v < posArr.Length; v++) + { + bucket.Pos.Add(xf * posArr[v]); + Vector3 n = normArr is not null && v < normArr.Length + ? (normalBasis * normArr[v]).Normalized() + : Vector3.Up; + bucket.Norm.Add(n); + } + + if (idxArr is not null && idxArr.Length > 0) + { + for (int k = 0; k < idxArr.Length; k++) + { + bucket.Idx.Add(baseVert + idxArr[k]); + } + } + else + { + for (int k = 0; k < posArr.Length; k++) + { + bucket.Idx.Add(baseVert + k); + } + } + } + } + + for (int i = 0; i < node.GetChildCount(); i++) + { + CollectMeshesRecursive(node.GetChild(i), xf, byMat); + } + } + + private (string Key, StandardMaterial3D Mat) GetOrShareBuildingMaterial(Material? srcMat) + { + if (srcMat is StandardMaterial3D std) + { + Color c = std.AlbedoColor; + string key = $"{std.ResourceName}|{c.R:F3},{c.G:F3},{c.B:F3},{c.A:F3}|{std.Roughness:F2}|{std.Metallic:F2}"; + if (!_sharedBuildingMaterials.TryGetValue(key, out var cached)) + { + cached = new StandardMaterial3D + { + AlbedoColor = c, + Roughness = std.Roughness, + Metallic = std.Metallic, + CullMode = BaseMaterial3D.CullModeEnum.Back + }; + _sharedBuildingMaterials[key] = cached; + } + return (key, cached); + } + + const string defaultKey = "__default_building"; + if (!_sharedBuildingMaterials.TryGetValue(defaultKey, out var defMat)) + { + defMat = new StandardMaterial3D + { + AlbedoColor = new Color(0.55f, 0.52f, 0.48f), + Roughness = 0.88f, + Metallic = 0.04f + }; + _sharedBuildingMaterials[defaultKey] = defMat; + } + return (defaultKey, defMat); + } + + private void ClearBuilt() + { + for (int i = 0; i < _buildingTiles.Count; i++) + { + _buildingTiles[i].Instance.QueueFree(); + } + _buildingTiles.Clear(); + + _sharedBuildingMaterials.Clear(); + _builtForDir = null; + IsBuilt = false; + ActiveLod1TileCount = 0; + ActiveLod2TileCount = 0; + CulledTileCount = 0; + } +} diff --git a/client/TerrainRenderer.cs b/client/TerrainRenderer.cs new file mode 100644 index 0000000..6b01092 --- /dev/null +++ b/client/TerrainRenderer.cs @@ -0,0 +1,1272 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Unified Layer-0 + live GPU brush compute terrain renderer for both Desert (8x8) and Sion (16x16). +/// Replaces permanent SubViewports and CanvasItem brush shaders with one compute shader +/// (terrain_tile_bake.glsl) writing sparse 388x388 delta slots +/// in an LRU pool (max 96 active scarred tiles; untouched tiles bind a 1x1 neutral fallback), +/// rendered via 3 exact-ratio shared PlaneMeshes (192/48/12) with zero T-junction edge morphing. +/// +public partial class TerrainRenderer : Node3D +{ + public const int DeltaTexSize = 388; + public const float InnerTexelSpan = 384.0f; + public const float GutterStartIndex = 2.0f; + public const float GutterCenterOffset = 2.5f; + public const int MaxGpuScarTiles = 96; + public const int MaxDirtyRebakesPerSync = 4; + private const int BrushStrideBytes = 48; + private const int PushConstantBytes = 48; + private const int MaxSsboBrushes = 8192; + private const int GroundTintGridSize = 128; + + private static readonly Color DesertAlbedoClear = new(0.69f, 0.50f, 0.31f, 1.0f); + private static readonly Color NeutralAlpineDustTint = new(0.56f, 0.53f, 0.46f, 1.0f); + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct GpuBrush + { + public Vector4 PosRot; + public Vector4 RadDelta; + public Vector4 MatColor; + } + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct TileBakePush + { + public Vector4 TileOriginAndSpan; + public Vector4 BaseColorAndGutter; + public uint BrushStart; + public uint BrushCount; + public uint TexSize; + public uint IsSion; + } + + private sealed class TileNode + { + public int Tx; + public int Tz; + public float OriginX; + public float OriginZ; + public MeshInstance3D SurfaceMesh = null!; + public ShaderMaterial SurfaceMat = null!; + public int BakedStructuralVersion = -1; + public int BakedVisualVersion = -1; + public int LruSlotIndex = -1; + public float TileQuads = 192f; + public float SentTileQuads = -1f; + public Vector4 SentNeighborQuads = new(-1f, -1f, -1f, -1f); + } + + private sealed class LruSlot + { + public int SlotIndex; + public Rid DeltaHeightRid; + public Rid DeltaAlbedoRid; + public Rid UniformSetRid; + public Texture2Drd DeltaHeightTex = null!; + public Texture2Drd DeltaAlbedoTex = null!; + public int AssignedTileIndex = -1; + public ulong LastUsedSeq; + public bool IsRdAllocated; + } + + private sealed class PendingBakeJob + { + public int SlotIndex; + public float TileOriginX; + public float TileOriginZ; + public float TileSize; + public bool IsSion; + public GpuBrush[] Brushes = Array.Empty(); + } + + private TileNode[,]? _tiles; + private int _gridCount; + private float _tileSize = TerrainField.TileSize; + private float _mapSize = TerrainField.ArenaSize; + + private readonly LruSlot[] _lruPool = new LruSlot[MaxGpuScarTiles]; + private ulong _lruClock; + + private PlaneMesh _nearPlaneMesh = null!; + private PlaneMesh _midPlaneMesh = null!; + private PlaneMesh _farPlaneMesh = null!; + private Shader _surfaceShader = null!; + + private ImageTexture _neutralDeltaHeightTex = null!; + private ImageTexture _neutralDeltaAlbedoTex = null!; + private ImageTexture _zeroDem1x1Tex = null!; + private ImageTexture _whiteSurface1x1Tex = null!; + private ImageTexture _zeroMask1x1Tex = null!; + + private Texture2Drd? _sionDemTexRd; + private Rid _sionDemRid; + private byte[]? _pendingSionDemUpload; + private int _pendingSionDemRes; + private ImageTexture? _sionSurfaceTex; + private ImageTexture? _sionMaskTex; + private Color[]? _groundTintGrid; + private float _groundTintSizeM; + private string? _loadedSionDir; + private float _sionDemMinY; + private float _sionDemScaleSpan; + + private TerrainField? _lastTerrain; + private SionMapData? _lastSionMap; + private Vector3 _lastCamPos; + private int _rebakeCursor; + private readonly List<(int Idx, float DistSq)> _scarCandidateScratch = new(256); + private readonly List<(int Slot, float DistSq)> _lodResidentScratch = new(MaxGpuScarTiles); + + // Render-thread compute state + private readonly object _jobLock = new(); + private readonly List _pendingJobs = new(); + private readonly byte[] _ssboStagingBytes = new byte[MaxSsboBrushes * BrushStrideBytes]; + private readonly byte[] _pushBytes = new byte[PushConstantBytes]; + private volatile bool _hasQueuedRdFlush; + private bool _rdInitialized; + private bool _rdFailed; + private Rid _bakeShaderRid; + private Rid _bakePipeRid; + private Rid _brushSsboRid; + + // Synchronous test readback state (main thread calls ForceSync + readback via CallOnRenderThread) + private Rid _readbackTargetRid; + private byte[]? _readbackResult; + + public int BakedTileCount { get; private set; } + public int DirtyRebakes { get; private set; } + public int ActiveGpuScarSlots + { + get + { + int count = 0; + for (int i = 0; i < _lruPool.Length; i++) + { + if (_lruPool[i] is not null && _lruPool[i].AssignedTileIndex >= 0) + { + count++; + } + } + return count; + } + } + public static double PerfBakeTileMs; + public static int PerfBakeTileCalls; + + public override void _Ready() + { + var neutralHImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah); + neutralHImg.SetPixel(0, 0, new Color(0f, 0.88f, 0f, 0f)); + _neutralDeltaHeightTex = ImageTexture.CreateFromImage(neutralHImg); + + var neutralAImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + neutralAImg.SetPixel(0, 0, new Color(DesertAlbedoClear.R, DesertAlbedoClear.G, DesertAlbedoClear.B, 1.0f)); + _neutralDeltaAlbedoTex = ImageTexture.CreateFromImage(neutralAImg); + + var zeroDemImg = Image.CreateEmpty(1, 1, false, Image.Format.Rh); + zeroDemImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 1f)); + _zeroDem1x1Tex = ImageTexture.CreateFromImage(zeroDemImg); + + var surf1x1Img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + surf1x1Img.SetPixel(0, 0, Colors.White); + _whiteSurface1x1Tex = ImageTexture.CreateFromImage(surf1x1Img); + + var mask1x1Img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + mask1x1Img.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f)); + _zeroMask1x1Tex = ImageTexture.CreateFromImage(mask1x1Img); + + _surfaceShader = GD.Load("res://terrain_surface.gdshader") + ?? throw new InvalidOperationException("Failed to load res://terrain_surface.gdshader"); + + for (int i = 0; i < MaxGpuScarTiles; i++) + { + _lruPool[i] = new LruSlot + { + SlotIndex = i, + DeltaHeightTex = new Texture2Drd(), + DeltaAlbedoTex = new Texture2Drd() + }; + } + } + + public override void _ExitTree() + { + base._ExitTree(); + if (RenderingServer.GetRenderingDevice() is not null) + { + RenderingServer.CallOnRenderThread(Callable.From(DisposeRdResourcesOnRenderThread)); + RenderingServer.ForceSync(); + } + } + + public void InvalidateAll() + { + if (_tiles is not null) + { + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) + { + var t = _tiles[tx, tz]; + if (t is null) continue; + t.BakedStructuralVersion = -1; + t.BakedVisualVersion = -1; + ReleaseTileSlot(t); + } + } + } + for (int i = 0; i < _lruPool.Length; i++) + { + if (_lruPool[i] is not null) + { + _lruPool[i].AssignedTileIndex = -1; + _lruPool[i].LastUsedSeq = 0; + } + } + BakedTileCount = 0; + DirtyRebakes = 0; + _rebakeCursor = 0; + _lastTerrain = null; + } + + public void Sync(TerrainField terrain, SionMapData? sionMap = null) + { + bool mapChanged = !ReferenceEquals(_lastTerrain, terrain) || !ReferenceEquals(_lastSionMap, sionMap); + if (mapChanged) + { + InvalidateAll(); + EnsureGridAllocated(terrain, sionMap); + _lastTerrain = terrain; + _lastSionMap = sionMap; + } + + if (_tiles is null) + { + return; + } + + int grid = terrain.TileGridCount; + int totalTiles = grid * grid; + bool isSion = sionMap is not null; + float halfTile = _tileSize * 0.5f; + + Span wantSlot = stackalloc bool[totalTiles]; + if (!isSion) + { + wantSlot.Fill(true); + } + else + { + _scarCandidateScratch.Clear(); + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + if (terrain.GetTileBrushIndices(tx, tz).Count > 0) + { + var tile = _tiles[tx, tz]; + float dx = (tile.OriginX + halfTile) - _lastCamPos.X; + float dz = (tile.OriginZ + halfTile) - _lastCamPos.Z; + _scarCandidateScratch.Add((tz * grid + tx, dx * dx + dz * dz)); + } + } + } + + if (_scarCandidateScratch.Count <= MaxGpuScarTiles) + { + for (int i = 0; i < _scarCandidateScratch.Count; i++) + { + wantSlot[_scarCandidateScratch[i].Idx] = true; + } + } + else + { + _scarCandidateScratch.Sort((a, b) => a.DistSq.CompareTo(b.DistSq)); + for (int i = 0; i < MaxGpuScarTiles; i++) + { + wantSlot[_scarCandidateScratch[i].Idx] = true; + } + } + } + + // 0. Release LRU slots on tiles outside the active top-96 scarred set (graceful Layer-0 DEM fallback) + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + int idx = tz * grid + tx; + if (!wantSlot[idx]) + { + var tile = _tiles[tx, tz]; + if (tile.LruSlotIndex >= 0) + { + ReleaseTileSlot(tile); + tile.SurfaceMat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex); + tile.SurfaceMat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex); + } + } + } + } + + // 1. Structural dirty tiles, uninitialized tiles, and newly promoted top-96 tiles bake immediately (never throttled) + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + int idx = tz * grid + tx; + var tile = _tiles[tx, tz]; + int structVer = terrain.StructuralTileVersions[tx, tz]; + int visVer = terrain.VisualTileVersions[tx, tz]; + bool isUninit = tile.BakedVisualVersion < 0; + + if (!wantSlot[idx]) + { + if (isUninit) + { + BakedTileCount++; + } + tile.BakedStructuralVersion = structVer; + tile.BakedVisualVersion = visVer; + continue; + } + + bool isStructDirty = tile.BakedStructuralVersion != structVer; + bool needsSlotReacquire = tile.LruSlotIndex < 0; + + if (isUninit || isStructDirty || needsSlotReacquire) + { + EnqueueTileBake(tx, tz, tile, terrain, isSion); + if (isUninit) + { + BakedTileCount++; + } + else + { + DirtyRebakes++; + } + tile.BakedStructuralVersion = structVer; + tile.BakedVisualVersion = visVer; + } + } + } + + // 2. Remaining passive visual dirty tiles (Tracks / Scorch) inside top-96 throttled to <= MaxDirtyRebakesPerSync (4) + int rebakedThisSync = 0; + int startCursor = _rebakeCursor; + for (int step = 0; step < totalTiles; step++) + { + int idx = (startCursor + step) % totalTiles; + if (!wantSlot[idx]) + { + continue; + } + int tx = idx % grid; + int tz = idx / grid; + var tile = _tiles[tx, tz]; + int visVer = terrain.VisualTileVersions[tx, tz]; + if (tile.BakedVisualVersion != visVer) + { + if (rebakedThisSync < MaxDirtyRebakesPerSync) + { + EnqueueTileBake(tx, tz, tile, terrain, isSion); + DirtyRebakes++; + tile.BakedStructuralVersion = terrain.StructuralTileVersions[tx, tz]; + tile.BakedVisualVersion = visVer; + rebakedThisSync++; + _rebakeCursor = (idx + 1) % totalTiles; + } + else + { + break; + } + } + } + + DispatchPendingJobsIfNeeded(); + } + + public int CountPendingDirtyVisualTiles(TerrainField terrain) + { + if (_tiles is null || !ReferenceEquals(_lastTerrain, terrain)) + { + return 0; + } + int count = 0; + int grid = terrain.TileGridCount; + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + if (_tiles[tx, tz].BakedVisualVersion != terrain.VisualTileVersions[tx, tz]) + { + count++; + } + } + } + return count; + } + + public void UpdateTileLod(Vector3 camPos) + { + _lastCamPos = camPos; + if (_tiles is null) + { + return; + } + + const float nearRadiusSq = 220f * 220f; + const float midRadiusSq = 780f * 780f; + const float shadowRadiusSq = 360f * 360f; + float halfTile = _tileSize * 0.5f; + _lodResidentScratch.Clear(); + + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) + { + var tile = _tiles[tx, tz]; + float cx = tile.OriginX + halfTile; + float cz = tile.OriginZ + halfTile; + float dx = cx - camPos.X; + float dz = cz - camPos.Z; + float d2 = dx * dx + dz * dz; + + if (tile.LruSlotIndex >= 0) + { + _lodResidentScratch.Add((tile.LruSlotIndex, d2)); + } + + PlaneMesh desiredMesh; + float quads; + if (d2 <= nearRadiusSq) + { + desiredMesh = _nearPlaneMesh; + quads = 192f; + } + else if (d2 <= midRadiusSq) + { + desiredMesh = _midPlaneMesh; + quads = 48f; + } + else + { + desiredMesh = _farPlaneMesh; + quads = 12f; + } + + tile.TileQuads = quads; + if (!ReferenceEquals(tile.SurfaceMesh.Mesh, desiredMesh)) + { + tile.SurfaceMesh.Mesh = desiredMesh; + } + var desiredShadow = d2 <= shadowRadiusSq + ? GeometryInstance3D.ShadowCastingSetting.On + : GeometryInstance3D.ShadowCastingSetting.Off; + if (tile.SurfaceMesh.CastShadow != desiredShadow) + { + tile.SurfaceMesh.CastShadow = desiredShadow; + } + } + } + + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) + { + var tile = _tiles[tx, tz]; + float qSelf = tile.TileQuads; + float qLeft = tx > 0 ? _tiles[tx - 1, tz].TileQuads : qSelf; + float qRight = tx < _gridCount - 1 ? _tiles[tx + 1, tz].TileQuads : qSelf; + float qTop = tz > 0 ? _tiles[tx, tz - 1].TileQuads : qSelf; + float qBottom = tz < _gridCount - 1 ? _tiles[tx, tz + 1].TileQuads : qSelf; + var nq = new Vector4(qLeft, qRight, qTop, qBottom); + + if (tile.SentTileQuads != qSelf) + { + tile.SurfaceMat.SetShaderParameter("tile_quads", qSelf); + tile.SentTileQuads = qSelf; + } + if (tile.SentNeighborQuads != nq) + { + tile.SurfaceMat.SetShaderParameter("neighbor_quads", nq); + tile.SentNeighborQuads = nq; + } + } + } + + if (_lodResidentScratch.Count > 0) + { + _lodResidentScratch.Sort((a, b) => b.DistSq.CompareTo(a.DistSq)); + for (int i = 0; i < _lodResidentScratch.Count; i++) + { + _lruPool[_lodResidentScratch[i].Slot].LastUsedSeq = ++_lruClock; + } + } + } + + public Color SampleGroundTint(float worldX, float worldZ) + { + Color[]? grid = _groundTintGrid; + float sizeM = _groundTintSizeM; + if (grid is null || sizeM <= 1f || !float.IsFinite(worldX) || !float.IsFinite(worldZ)) + { + return NeutralAlpineDustTint; + } + + float half = sizeM * 0.5f; + float u = (worldX + half) / sizeM; + float v = (worldZ + half) / sizeM; + if (u < 0f || u > 1f || v < 0f || v > 1f) + { + return NeutralAlpineDustTint; + } + + float fx = u * (GroundTintGridSize - 1); + float fy = v * (GroundTintGridSize - 1); + int x0 = Math.Clamp((int)MathF.Floor(fx), 0, GroundTintGridSize - 1); + int y0 = Math.Clamp((int)MathF.Floor(fy), 0, GroundTintGridSize - 1); + int x1 = Math.Min(x0 + 1, GroundTintGridSize - 1); + int y1 = Math.Min(y0 + 1, GroundTintGridSize - 1); + float tx = fx - x0; + float ty = fy - y0; + + Color c00 = grid[y0 * GroundTintGridSize + x0]; + Color c10 = grid[y0 * GroundTintGridSize + x1]; + Color c01 = grid[y1 * GroundTintGridSize + x0]; + Color c11 = grid[y1 * GroundTintGridSize + x1]; + return c00.Lerp(c10, tx).Lerp(c01.Lerp(c11, tx), ty); + } + + public bool TryGetHeightImageFormat(out Image.Format format) + { + format = Image.Format.Max; + if (RenderingServer.GetRenderingDevice() is null || _rdFailed) + { + return false; + } + format = Image.Format.Rgbah; + return true; + } + + public bool TrySampleBakedHeight(float wx, float wz, out float bakedHeight) + { + bakedHeight = 0f; + if (_lastTerrain is not { } terrain || _tiles is null) + { + return false; + } + if (RenderingServer.GetRenderingDevice() is null || _rdFailed) + { + return false; + } + + if (_hasQueuedRdFlush) + { + RenderingServer.ForceSync(); + } + + float half = terrain.MapHalfExtent; + float cx = Math.Clamp(wx, -half, half); + float cz = Math.Clamp(wz, -half, half); + terrain.MapWorldToTile(cx, cz, out int tx, out int tz); + + var tile = _tiles[tx, tz]; + float baseH = terrain.SampleBaseHeight(cx, cz); + + if (tile.LruSlotIndex < 0) + { + bakedHeight = Math.Clamp(baseH, terrain.MapMinHeight, terrain.MapMaxHeight); + return true; + } + + var slot = _lruPool[tile.LruSlotIndex]; + if (!slot.IsRdAllocated || !slot.DeltaHeightRid.IsValid) + { + return false; + } + + _readbackTargetRid = slot.DeltaHeightRid; + _readbackResult = null; + RenderingServer.CallOnRenderThread(Callable.From(ReadbackTextureOnRenderThread)); + RenderingServer.ForceSync(); + + byte[]? raw = _readbackResult; + if (raw is null || raw.Length < DeltaTexSize * DeltaTexSize * 8) + { + return false; + } + + float pixelsPerMeter = InnerTexelSpan / _tileSize; + float px = GutterCenterOffset + (cx - tile.OriginX) * pixelsPerMeter; + float py = GutterCenterOffset + (cz - tile.OriginZ) * pixelsPerMeter; + float fx = Math.Clamp(px - 0.5f, 0f, DeltaTexSize - 1.0001f); + float fy = Math.Clamp(py - 0.5f, 0f, DeltaTexSize - 1.0001f); + + int x0 = (int)MathF.Floor(fx); + int y0 = (int)MathF.Floor(fy); + int x1 = Math.Min(x0 + 1, DeltaTexSize - 1); + int y1 = Math.Min(y0 + 1, DeltaTexSize - 1); + float txFrac = fx - x0; + float tyFrac = fy - y0; + + float ReadHalfR(int x, int y) + { + int byteOff = (y * DeltaTexSize + x) * 8; + return (float)BitConverter.ToHalf(raw, byteOff); + } + + float h00 = ReadHalfR(x0, y0); + float h10 = ReadHalfR(x1, y0); + float h01 = ReadHalfR(x0, y1); + float h11 = ReadHalfR(x1, y1); + + float deltaH = (h00 * (1f - txFrac) + h10 * txFrac) * (1f - tyFrac) + + (h01 * (1f - txFrac) + h11 * txFrac) * tyFrac; + + bakedHeight = Math.Clamp(baseH + deltaH, terrain.MapMinHeight, terrain.MapMaxHeight); + return true; + } + + private void EnsureGridAllocated(TerrainField terrain, SionMapData? sionMap) + { + bool needsRebuild = _tiles is null || + _gridCount != terrain.TileGridCount || + MathF.Abs(_tileSize - terrain.MapTileSize) > 0.01f; + + if (sionMap is not null) + { + EnsureSionLayer0Resources(sionMap); + } + + if (needsRebuild) + { + if (_tiles is not null) + { + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) + { + var old = _tiles[tx, tz]; + if (old?.SurfaceMesh is not null && IsInstanceValid(old.SurfaceMesh)) + { + old.SurfaceMesh.QueueFree(); + } + } + } + } + + _gridCount = terrain.TileGridCount; + _tileSize = terrain.MapTileSize; + _mapSize = terrain.MapSize; + + _nearPlaneMesh = new PlaneMesh + { + Size = new Vector2(_tileSize, _tileSize), + SubdivideWidth = 191, + SubdivideDepth = 191 + }; + _midPlaneMesh = new PlaneMesh + { + Size = new Vector2(_tileSize, _tileSize), + SubdivideWidth = 47, + SubdivideDepth = 47 + }; + _farPlaneMesh = new PlaneMesh + { + Size = new Vector2(_tileSize, _tileSize), + SubdivideWidth = 11, + SubdivideDepth = 11 + }; + + _tiles = new TileNode[_gridCount, _gridCount]; + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) + { + float originX = -terrain.MapHalfExtent + tx * _tileSize; + float originZ = -terrain.MapHalfExtent + tz * _tileSize; + var mat = new ShaderMaterial { Shader = _surfaceShader }; + var mi = new MeshInstance3D + { + Name = $"Tile_{tx}_{tz}_Mesh", + Mesh = _nearPlaneMesh, + MaterialOverride = mat, + Position = new Vector3(originX + _tileSize * 0.5f, 0f, originZ + _tileSize * 0.5f) + }; + AddChild(mi); + + _tiles[tx, tz] = new TileNode + { + Tx = tx, + Tz = tz, + OriginX = originX, + OriginZ = originZ, + SurfaceMesh = mi, + SurfaceMat = mat + }; + } + } + } + + bool isSion = sionMap is not null; + float minY = terrain.MapMinHeight; + float maxY = terrain.MapMaxHeight; + float span = MathF.Max(1f, maxY - minY); + + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) + { + var tile = _tiles![tx, tz]; + var mat = tile.SurfaceMat; + mat.SetShaderParameter("base_dem_tex", isSion && _sionDemTexRd is not null ? _sionDemTexRd : _zeroDem1x1Tex); + mat.SetShaderParameter("base_surface_tex", isSion && _sionSurfaceTex is not null ? _sionSurfaceTex : _whiteSurface1x1Tex); + mat.SetShaderParameter("base_mask_tex", isSion && _sionMaskTex is not null ? _sionMaskTex : _zeroMask1x1Tex); + mat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex); + mat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex); + mat.SetShaderParameter("dem_min_y", isSion ? _sionDemMinY : 0f); + mat.SetShaderParameter("dem_scale_span", isSion ? _sionDemScaleSpan : 0f); + mat.SetShaderParameter("dem_grid_res", isSion ? (float)sionMap!.Metadata.GridRes : 1f); + mat.SetShaderParameter("height_min", minY); + mat.SetShaderParameter("height_max", maxY); + mat.SetShaderParameter("map_size", _mapSize); + mat.SetShaderParameter("tile_origin_x", tile.OriginX); + mat.SetShaderParameter("tile_origin_z", tile.OriginZ); + mat.SetShaderParameter("tile_size", _tileSize); + mat.SetShaderParameter("inner_span", InnerTexelSpan); + mat.SetShaderParameter("tex_size", (float)DeltaTexSize); + mat.SetShaderParameter("gutter_center", GutterCenterOffset); + mat.SetShaderParameter("is_sion", isSion ? 1f : 0f); + + tile.SurfaceMesh.CustomAabb = new Aabb( + new Vector3(-_tileSize * 0.5f, minY - 2f, -_tileSize * 0.5f), + new Vector3(_tileSize, span + 4f, _tileSize)); + } + } + } + + private void EnsureSionLayer0Resources(SionMapData sionMap) + { + if (string.Equals(_loadedSionDir, sionMap.DirectoryPath, StringComparison.OrdinalIgnoreCase)) + { + return; + } + _loadedSionDir = sionMap.DirectoryPath; + _sionDemMinY = sionMap.BaseDemMinY; + _sionDemScaleSpan = 65535.0f * sionMap.BaseDemScale; + + string surfPath = Path.Combine(sionMap.DirectoryPath, sionMap.Metadata.SurfaceTexture); + if (!File.Exists(surfPath)) + { + throw new FileNotFoundException($"Missing Sion terrain surface texture: {surfPath}", surfPath); + } + var surfImg = Image.LoadFromFile(surfPath) + ?? throw new InvalidOperationException($"Failed to decode Sion terrain surface texture: {surfPath}"); + + var tintImg = (Image)surfImg.Duplicate(); + tintImg.Resize(GroundTintGridSize, GroundTintGridSize, Image.Interpolation.Bilinear); + var grid = new Color[GroundTintGridSize * GroundTintGridSize]; + for (int y = 0; y < GroundTintGridSize; y++) + { + for (int x = 0; x < GroundTintGridSize; x++) + { + Color c = tintImg.GetPixel(x, y); + grid[y * GroundTintGridSize + x] = new Color( + Math.Clamp(c.R + 0.11f, 0.20f, 0.90f), + Math.Clamp(c.G + 0.11f, 0.20f, 0.88f), + Math.Clamp(c.B + 0.10f, 0.18f, 0.84f), + 1.0f); + } + } + _groundTintGrid = grid; + _groundTintSizeM = sionMap.Metadata.SizeMeters; + + surfImg.GenerateMipmaps(); + _sionSurfaceTex = ImageTexture.CreateFromImage(surfImg); + + string maskName = string.IsNullOrWhiteSpace(sionMap.Metadata.SurfaceMaskTexture) + ? "terrain_surface_mask.png" + : sionMap.Metadata.SurfaceMaskTexture; + string maskPath = Path.Combine(sionMap.DirectoryPath, maskName); + if (File.Exists(maskPath)) + { + var maskImg = Image.LoadFromFile(maskPath); + if (maskImg is not null && !maskImg.IsEmpty()) + { + maskImg.GenerateMipmaps(); + _sionMaskTex = ImageTexture.CreateFromImage(maskImg); + } + } + + if (RenderingServer.GetRenderingDevice() is not null) + { + _sionDemTexRd ??= new Texture2Drd(); + byte[] demBytes = new byte[sionMap.BaseDem.Length * 2]; + Buffer.BlockCopy(sionMap.BaseDem, 0, demBytes, 0, demBytes.Length); + _pendingSionDemUpload = demBytes; + _pendingSionDemRes = sionMap.Metadata.GridRes; + RenderingServer.CallOnRenderThread(Callable.From(UploadSionDemOnRenderThread)); + } + } + + private void EnqueueTileBake(int tx, int tz, TileNode tile, TerrainField terrain, bool isSion) + { + long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; + + IReadOnlyList indices = terrain.GetTileBrushIndices(tx, tz); + if (indices.Count == 0 && isSion) + { + // Untouched Sion tile: release LRU slot and bind shared 1x1 neutral delta texture + ReleaseTileSlot(tile); + tile.SurfaceMat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex); + tile.SurfaceMat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex); + return; + } + + int tileIdx = tz * _gridCount + tx; + LruSlot slot = AcquireLruSlot(tileIdx, tile); + tile.SurfaceMat.SetShaderParameter("delta_height_tex", slot.DeltaHeightTex); + tile.SurfaceMat.SetShaderParameter("delta_albedo_tex", slot.DeltaAlbedoTex); + + if (RenderingServer.GetRenderingDevice() is not null && !_rdFailed) + { + var brushes = terrain.Brushes; + var gpuList = new List(indices.Count); + for (int i = 0; i < indices.Count; i++) + { + var b = brushes[indices[i]]; + if (b.RadiusX <= 0.05f || b.RadiusZ <= 0.05f) + { + continue; + } + float invRx = 1f / MathF.Max(0.1f, b.RadiusX); + float invRz = 1f / MathF.Max(0.1f, b.RadiusZ); + float maxR = MathF.Max(0.1f, MathF.Max(b.RadiusX, b.RadiusZ)); + gpuList.Add(new GpuBrush + { + PosRot = new Vector4(b.X, b.Z, MathF.Cos(b.RotationRad), MathF.Sin(b.RotationRad)), + RadDelta = new Vector4(invRx, invRz, b.HeightDelta, maxR * maxR), + MatColor = new Vector4(b.AlbedoR, b.AlbedoG, b.AlbedoB, (float)(int)b.Kind) + }); + } + + lock (_jobLock) + { + _pendingJobs.Add(new PendingBakeJob + { + SlotIndex = slot.SlotIndex, + TileOriginX = tile.OriginX, + TileOriginZ = tile.OriginZ, + TileSize = _tileSize, + IsSion = isSion, + Brushes = gpuList.ToArray() + }); + } + } + + if (t0 != 0) + { + PerfBakeTileMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; + PerfBakeTileCalls++; + } + } + + private LruSlot AcquireLruSlot(int tileIdx, TileNode tile) + { + _lruClock++; + if (tile.LruSlotIndex >= 0) + { + var cur = _lruPool[tile.LruSlotIndex]; + if (cur.AssignedTileIndex == tileIdx) + { + cur.LastUsedSeq = _lruClock; + return cur; + } + } + + int bestIdx = -1; + ulong bestAge = ulong.MaxValue; + for (int i = 0; i < MaxGpuScarTiles; i++) + { + if (_lruPool[i].AssignedTileIndex < 0) + { + bestIdx = i; + break; + } + if (_lruPool[i].LastUsedSeq < bestAge) + { + bestAge = _lruPool[i].LastUsedSeq; + bestIdx = i; + } + } + + var chosen = _lruPool[bestIdx]; + if (chosen.AssignedTileIndex >= 0 && _tiles is not null) + { + int prevTileIdx = chosen.AssignedTileIndex; + int prevTx = prevTileIdx % _gridCount; + int prevTz = prevTileIdx / _gridCount; + if ((uint)prevTx < (uint)_gridCount && (uint)prevTz < (uint)_gridCount) + { + var evicted = _tiles[prevTx, prevTz]; + if (evicted.LruSlotIndex == bestIdx) + { + evicted.LruSlotIndex = -1; + evicted.BakedVisualVersion = -1; + evicted.BakedStructuralVersion = -1; + evicted.SurfaceMat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex); + evicted.SurfaceMat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex); + } + } + } + + chosen.AssignedTileIndex = tileIdx; + chosen.LastUsedSeq = _lruClock; + tile.LruSlotIndex = bestIdx; + return chosen; + } + + private void ReleaseTileSlot(TileNode tile) + { + if (tile.LruSlotIndex >= 0) + { + var slot = _lruPool[tile.LruSlotIndex]; + if (slot.AssignedTileIndex == tile.Tz * _gridCount + tile.Tx) + { + slot.AssignedTileIndex = -1; + } + tile.LruSlotIndex = -1; + } + } + + private void DispatchPendingJobsIfNeeded() + { + if (RenderingServer.GetRenderingDevice() is null || _rdFailed) + { + lock (_jobLock) + { + _pendingJobs.Clear(); + } + return; + } + + bool any; + lock (_jobLock) + { + any = _pendingJobs.Count > 0; + } + if (any) + { + _hasQueuedRdFlush = true; + RenderingServer.CallOnRenderThread(Callable.From(FlushPendingGpuBakesOnRenderThread)); + } + } + + private void UploadSionDemOnRenderThread() + { + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + byte[]? demBytes = _pendingSionDemUpload; + int res = _pendingSionDemRes; + _pendingSionDemUpload = null; + if (rd is null || demBytes is null || res <= 1) + { + return; + } + + if (_sionDemRid.IsValid) + { + if (_sionDemTexRd is not null) + { + _sionDemTexRd.TextureRdRid = new Rid(); + } + rd.FreeRid(_sionDemRid); + _sionDemRid = new Rid(); + } + + var fmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R16Unorm, + Width = (uint)res, + Height = (uint)res, + Depth = 1, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.CanUpdateBit + }; + var dataArr = new Godot.Collections.Array { demBytes }; + _sionDemRid = rd.TextureCreate(fmt, new RDTextureView(), dataArr); + if (_sionDemTexRd is not null && _sionDemRid.IsValid) + { + _sionDemTexRd.TextureRdRid = _sionDemRid; + } + } + + private bool EnsureComputePipelineOnRenderThread(RenderingDevice rd) + { + if (_rdInitialized) + { + return true; + } + if (_rdFailed) + { + return false; + } + + string source = Godot.FileAccess.GetFileAsString("res://terrain_tile_bake.glsl"); + if (string.IsNullOrWhiteSpace(source)) + { + GD.PrintErr("TerrainRenderer: missing compute shader res://terrain_tile_bake.glsl"); + _rdFailed = true; + return false; + } + + using var rdSrc = new RDShaderSource + { + Language = RenderingDevice.ShaderLanguage.Glsl, + SourceCompute = source + }; + using RDShaderSpirV spirv = rd.ShaderCompileSpirVFromSource(rdSrc, allowCache: true); + if (!string.IsNullOrEmpty(spirv.CompileErrorCompute)) + { + GD.PrintErr($"TerrainRenderer: SPIR-V compile error in terrain_tile_bake.glsl: {spirv.CompileErrorCompute}"); + _rdFailed = true; + return false; + } + + _bakeShaderRid = rd.ShaderCreateFromSpirV(spirv, "terrain_tile_bake"); + _bakePipeRid = rd.ComputePipelineCreate(_bakeShaderRid); + if (!_bakeShaderRid.IsValid || !_bakePipeRid.IsValid) + { + GD.PrintErr("TerrainRenderer: failed to create compute pipeline"); + _rdFailed = true; + return false; + } + + _brushSsboRid = rd.StorageBufferCreate(MaxSsboBrushes * BrushStrideBytes, new byte[MaxSsboBrushes * BrushStrideBytes]); + _rdInitialized = true; + return true; + } + + private void EnsureSlotRdAllocatedOnRenderThread(RenderingDevice rd, LruSlot slot) + { + if (slot.IsRdAllocated) + { + return; + } + + var hFmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat, + Width = DeltaTexSize, + Height = DeltaTexSize, + Depth = 1, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | + RenderingDevice.TextureUsageBits.StorageBit | + RenderingDevice.TextureUsageBits.CanCopyFromBit + }; + slot.DeltaHeightRid = rd.TextureCreate(hFmt, new RDTextureView()); + + var aFmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R8G8B8A8Unorm, + Width = DeltaTexSize, + Height = DeltaTexSize, + Depth = 1, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit + }; + slot.DeltaAlbedoRid = rd.TextureCreate(aFmt, new RDTextureView()); + + var uniforms = new Godot.Collections.Array + { + new RDUniform + { + UniformType = RenderingDevice.UniformType.Image, + Binding = 0, + _Ids = new Godot.Collections.Array { slot.DeltaHeightRid } + }, + new RDUniform + { + UniformType = RenderingDevice.UniformType.Image, + Binding = 1, + _Ids = new Godot.Collections.Array { slot.DeltaAlbedoRid } + }, + new RDUniform + { + UniformType = RenderingDevice.UniformType.StorageBuffer, + Binding = 2, + _Ids = new Godot.Collections.Array { _brushSsboRid } + } + }; + slot.UniformSetRid = rd.UniformSetCreate(uniforms, _bakeShaderRid, 0); + slot.DeltaHeightTex.TextureRdRid = slot.DeltaHeightRid; + slot.DeltaAlbedoTex.TextureRdRid = slot.DeltaAlbedoRid; + slot.IsRdAllocated = true; + } + + private void FlushPendingGpuBakesOnRenderThread() + { + PendingBakeJob[] jobs; + lock (_jobLock) + { + if (_pendingJobs.Count == 0) + { + _hasQueuedRdFlush = false; + return; + } + jobs = _pendingJobs.ToArray(); + _pendingJobs.Clear(); + } + + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null || !EnsureComputePipelineOnRenderThread(rd)) + { + _hasQueuedRdFlush = false; + return; + } + + long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; + + int totalBrushes = 0; + var brushStarts = new uint[jobs.Length]; + for (int j = 0; j < jobs.Length; j++) + { + int count = jobs[j].Brushes.Length; + if (totalBrushes + count > MaxSsboBrushes) + { + count = Math.Max(0, MaxSsboBrushes - totalBrushes); + } + brushStarts[j] = (uint)totalBrushes; + for (int b = 0; b < count; b++) + { + int byteOff = (totalBrushes + b) * BrushStrideBytes; + MemoryMarshal.Write(_ssboStagingBytes.AsSpan(byteOff, BrushStrideBytes), in jobs[j].Brushes[b]); + } + totalBrushes += count; + } + + if (totalBrushes > 0) + { + rd.BufferUpdate(_brushSsboRid, 0, (uint)(totalBrushes * BrushStrideBytes), _ssboStagingBytes); + } + + for (int j = 0; j < jobs.Length; j++) + { + EnsureSlotRdAllocatedOnRenderThread(rd, _lruPool[jobs[j].SlotIndex]); + } + + uint groups = (uint)((DeltaTexSize + 7) / 8); + long cl = rd.ComputeListBegin(); + rd.ComputeListBindComputePipeline(cl, _bakePipeRid); + for (int j = 0; j < jobs.Length; j++) + { + var job = jobs[j]; + var slot = _lruPool[job.SlotIndex]; + uint bCount = (uint)Math.Min(job.Brushes.Length, MaxSsboBrushes - (int)brushStarts[j]); + var push = new TileBakePush + { + TileOriginAndSpan = new Vector4(job.TileOriginX, job.TileOriginZ, job.TileSize, InnerTexelSpan), + BaseColorAndGutter = job.IsSion + ? new Vector4(0f, 0f, 0f, GutterStartIndex) + : new Vector4(DesertAlbedoClear.R, DesertAlbedoClear.G, DesertAlbedoClear.B, GutterStartIndex), + BrushStart = brushStarts[j], + BrushCount = bCount, + TexSize = DeltaTexSize, + IsSion = job.IsSion ? 1u : 0u + }; + MemoryMarshal.Write(_pushBytes, in push); + rd.ComputeListBindUniformSet(cl, slot.UniformSetRid, 0); + rd.ComputeListSetPushConstant(cl, _pushBytes, PushConstantBytes); + rd.ComputeListDispatch(cl, groups, groups, 1); + } + rd.ComputeListEnd(); + _hasQueuedRdFlush = false; + + if (t0 != 0) + { + PerfBakeTileMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; + } + } + + private void ReadbackTextureOnRenderThread() + { + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null || !_readbackTargetRid.IsValid) + { + _readbackResult = null; + return; + } + _readbackResult = rd.TextureGetData(_readbackTargetRid, 0); + } + + private void DisposeRdResourcesOnRenderThread() + { + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null) + { + return; + } + + for (int i = 0; i < _lruPool.Length; i++) + { + var slot = _lruPool[i]; + if (slot is null || !slot.IsRdAllocated) + { + continue; + } + slot.DeltaHeightTex.TextureRdRid = new Rid(); + slot.DeltaAlbedoTex.TextureRdRid = new Rid(); + if (slot.UniformSetRid.IsValid) rd.FreeRid(slot.UniformSetRid); + if (slot.DeltaHeightRid.IsValid) rd.FreeRid(slot.DeltaHeightRid); + if (slot.DeltaAlbedoRid.IsValid) rd.FreeRid(slot.DeltaAlbedoRid); + slot.UniformSetRid = new Rid(); + slot.DeltaHeightRid = new Rid(); + slot.DeltaAlbedoRid = new Rid(); + slot.IsRdAllocated = false; + } + + if (_sionDemTexRd is not null) + { + _sionDemTexRd.TextureRdRid = new Rid(); + } + if (_sionDemRid.IsValid) + { + rd.FreeRid(_sionDemRid); + _sionDemRid = new Rid(); + } + if (_brushSsboRid.IsValid) + { + rd.FreeRid(_brushSsboRid); + _brushSsboRid = new Rid(); + } + if (_bakePipeRid.IsValid) + { + rd.FreeRid(_bakePipeRid); + _bakePipeRid = new Rid(); + } + if (_bakeShaderRid.IsValid) + { + rd.FreeRid(_bakeShaderRid); + _bakeShaderRid = new Rid(); + } + _rdInitialized = false; + } +} diff --git a/client/UiFonts.cs b/client/UiFonts.cs new file mode 100644 index 0000000..c3aba41 --- /dev/null +++ b/client/UiFonts.cs @@ -0,0 +1,35 @@ +using Godot; + +namespace RustToDust.Client; + +/// +/// Central font accessor for custom Control._Draw() canvas calls. +/// Standard controls inherit gui/theme/custom_font from project.godot. +/// +internal static class UiFonts +{ + private const string RegularPath = "res://fonts/MonaspaceKrypton-Regular.otf"; + private const string SemiBoldPath = "res://fonts/MonaspaceKrypton-SemiBold.otf"; + private const string BoldPath = "res://fonts/MonaspaceKrypton-Bold.otf"; + + private static Font? _regular; + private static Font? _semiBold; + private static Font? _bold; + + public static Font Regular => _regular ??= LoadOrFallback(RegularPath, ThemeDB.FallbackFont); + public static Font SemiBold => _semiBold ??= LoadOrFallback(SemiBoldPath, Regular); + public static Font Bold => _bold ??= LoadOrFallback(BoldPath, SemiBold); + + private static Font LoadOrFallback(string path, Font fallback) + { + if (ResourceLoader.Exists(path)) + { + var loaded = GD.Load(path); + if (loaded is not null) + { + return loaded; + } + } + return fallback; + } +} diff --git a/client/VehicleAssetCache.cs b/client/VehicleAssetCache.cs new file mode 100644 index 0000000..8473599 --- /dev/null +++ b/client/VehicleAssetCache.cs @@ -0,0 +1,2414 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Runtime GLB asset loader & template cache for all 15 Brokkr vehicles (resolved via +/// + ) +/// and all 6 modular gear GLBs in assets/gear/. +/// Parses the glTF JSON chunk to map rtd.id, rtd.kind, rtd.size, and rtd.joint +/// deterministically to exact s inside the Godot scene tree generated by +/// + . +/// +public sealed class VehicleAssetCache : IDisposable +{ + public sealed record GlbAnchorInfo( + string Id, + string Kind, + Vector3 Size, + NodePath RelativePath, + Transform3D ModelSpaceTransform); + + public sealed record GlbJointInfo( + string JointId, + string NodeName, + Vector3 Axis, + float MinVal, + float MaxVal, + NodePath RelativePath); + + public sealed record GlbPartNodeInfo( + string NodeName, + int CellX, + int CellY, + string Kind, + NodePath RelativePath, + bool HasProtectedDescendant); + + public sealed record RigidPartTemplate( + NodePath PivotPath, + ArrayMesh Mesh, + int CellX, + int CellY, + string Kind); + + public sealed class VehicleTemplate + { + public required VehiclePackage Package { get; init; } + public required string GlbPath { get; init; } + public required Node3D SceneTemplate { get; init; } + public required ArrayMesh BakedStaticMesh { get; init; } + public required ArrayMesh BakedLodFarMesh { get; init; } + public required ArrayMesh SingleSurfaceStaticMesh { get; init; } + public required ArrayMesh SingleSurfaceLodFarMesh { get; init; } + public required Vector3[] FarRayTris { get; init; } + public required Aabb FarRayAabb { get; init; } + public required float MinY { get; init; } + public required float MaxY { get; init; } + public required IReadOnlyDictionary Anchors { get; init; } + public required IReadOnlyDictionary Joints { get; init; } + public required IReadOnlyDictionary NodesByOriginalName { get; init; } + public required IReadOnlyList DetachableParts { get; init; } + public required IReadOnlyList StaticRigidParts { get; init; } + public required IReadOnlyList DetachableRigidParts { get; init; } + public required IReadOnlyList MobilityNodePaths { get; init; } + } + + public sealed class GearTemplate + { + public required string Id { get; init; } + public required string GlbPath { get; init; } + public required Node3D SceneTemplate { get; init; } + public required ArrayMesh BakedDropMesh { get; init; } + public required ArrayMesh SingleSurfaceMesh { get; init; } + public required Vector3 Size { get; init; } + public required float MinY { get; init; } + public required Vector3 LocalModelForward { get; init; } + public required IReadOnlyDictionary PartCentroidsLocal { get; init; } + } + + public sealed class DropPodTemplate + { + public required string GlbPath { get; init; } + public required Node3D SceneTemplate { get; init; } + public required ArrayMesh CoreMesh { get; init; } + public required ArrayMesh PetalMesh { get; init; } + public required Transform3D[] PetalLocalTransforms { get; init; } + public required Vector3 Size { get; init; } + public required float MinY { get; init; } + public required float MaxY { get; init; } + } + + public sealed class WeaponPartTemplate + { + public required string Id { get; init; } + public required string Slot { get; init; } + public required string GlbPath { get; init; } + public required Node3D SceneTemplate { get; init; } + public required ArrayMesh SingleSurfaceMesh { get; init; } + public required Vector3 Size { get; init; } + public required float MinY { get; init; } + public required IReadOnlyDictionary SocketsLocal { get; init; } + } + + public static readonly string[] ExpectedGearIds = + { + "mg_762", "autocannon", "recoilless", "copper_rad", "gilded_lance", "gold_radiator" + }; + + public static readonly string[] ExpectedWeaponPartIds = + { + "rx_salvage_frame", "rx_korrathi_cradle", "rx_auralian_prism", "rx_vex_pod_rack", + "brl_autocannon", "brl_sabot_rail", "brl_prism_lance", "brl_missile_tube", + "fd_belt_drum", "fd_rotary_loader", "fd_capacitor_bank", "fd_swarm_magazine", + "mz_slotted_brake", "mz_mirv_warhead", "mz_loiter_aero_fin", "mz_plasma_diffuser" + }; + + private readonly Dictionary _vehicles = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _gear = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _weaponParts = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _gearVariantMeshes = new(StringComparer.OrdinalIgnoreCase); + private DropPodTemplate? _dropPod; + private readonly string _vehiclesDir; + private readonly string _gearDir; + private readonly string _weaponPartsDir; + private bool _disposed; + + public VehicleAssetCache() + { + ClientAssets.EnsureAssetsRootRegistered(); + _vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory(); + string assetsDir = ClientAssets.LocateAssetsDirectory(); + _gearDir = Path.Combine(assetsDir, "gear"); + if (!Directory.Exists(_gearDir)) + { + throw new DirectoryNotFoundException($"Could not locate gear directory '{_gearDir}'."); + } + _weaponPartsDir = Path.Combine(_gearDir, "parts"); + } + + public IReadOnlyDictionary Vehicles => _vehicles; + public IReadOnlyDictionary Gear => _gear; + public IReadOnlyDictionary WeaponParts => _weaponParts; + + public void PreloadAll() + { + foreach (var pkg in Catalog.PackagesById.Values) + { + GetOrLoadVehicle(pkg.Id); + } + foreach (string gearId in ExpectedGearIds) + { + GetOrLoadGear(gearId); + } + foreach (string partId in ExpectedWeaponPartIds) + { + GetOrLoadWeaponPart(partId); + } + GetOrLoadDropPod(); + } + + public WeaponPartTemplate GetOrLoadWeaponPart(string partId) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_weaponParts.TryGetValue(partId, out var cached)) + { + return cached; + } + + string glbPath = Path.Combine(_weaponPartsDir, $"{partId}.glb"); + if (!File.Exists(glbPath)) + { + throw new FileNotFoundException($"Missing modular weapon part GLB '{partId}': {glbPath}", glbPath); + } + + var template = LoadWeaponPartTemplate(partId, glbPath); + _weaponParts[partId] = template; + return template; + } + + public DropPodTemplate GetOrLoadDropPod() + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_dropPod is not null) + { + return _dropPod; + } + + string glbPath = Path.Combine(_vehiclesDir, "drop_pod", "drop_pod.glb"); + if (!File.Exists(glbPath)) + { + throw new FileNotFoundException($"Missing drop pod GLB: {glbPath}", glbPath); + } + + _dropPod = LoadDropPodTemplate(glbPath); + return _dropPod; + } + + public VehicleTemplate GetOrLoadVehicle(string vehicleId) + { + ObjectDisposedException.ThrowIf(_disposed, this); + string resolvedId = ResolveModelId(vehicleId); + if (_vehicles.TryGetValue(resolvedId, out var cached)) + { + return cached; + } + + var pkg = Catalog.TryGetPackage(resolvedId) + ?? throw new KeyNotFoundException($"Unknown vehicle '{vehicleId}' in Catalog.PackagesById."); + + string glbPath = Path.Combine(_vehiclesDir, pkg.Id, pkg.ModelAsset); + if (!File.Exists(glbPath)) + { + throw new FileNotFoundException($"Missing vehicle GLB for '{pkg.Id}': {glbPath}", glbPath); + } + + var template = LoadVehicleTemplate(pkg, glbPath); + _vehicles[pkg.Id] = template; + return template; + } + + public static string ResolveModelId(string chassisId) => + string.Equals(chassisId, "exemplar_frame", StringComparison.OrdinalIgnoreCase) + ? "raptor" + : chassisId; + + public GearTemplate GetOrLoadGear(string gearId) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_gear.TryGetValue(gearId, out var cached)) + { + return cached; + } + + string glbPath = Path.Combine(_gearDir, $"{gearId}.glb"); + if (!File.Exists(glbPath)) + { + throw new FileNotFoundException($"Missing gear GLB '{gearId}': {glbPath}", glbPath); + } + + var template = LoadGearTemplate(gearId, glbPath); + _gear[gearId] = template; + return template; + } + + public ArrayMesh GetOrBuildGearVariantMesh( + string moduleId, + string gearGlbId, + Color? paintTint, + Color? accentTint) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_gearVariantMeshes.TryGetValue(moduleId, out ArrayMesh? cached)) + { + return cached; + } + + GearTemplate tpl = GetOrLoadGear(gearGlbId); + ArrayMesh mesh = !paintTint.HasValue && !accentTint.HasValue + ? tpl.SingleSurfaceMesh + : CollapseToSingleSurfaceMechPaintMesh(tpl.BakedDropMesh, paintTint, accentTint); + _gearVariantMeshes[moduleId] = mesh; + return mesh; + } + + private static VehicleTemplate LoadVehicleTemplate(VehiclePackage pkg, string glbPath) + { + byte[] jsonBytes = ReadGlbJsonChunk(glbPath); + using var gltfJson = JsonDocument.Parse(jsonBytes); + JsonElement jsonRoot = gltfJson.RootElement; + + var doc = new GltfDocument(); + var state = new GltfState(); + Error err = doc.AppendFromFile(glbPath, state, flags: 0, basePath: Path.GetDirectoryName(glbPath) ?? string.Empty); + if (err != Error.Ok) + { + throw new InvalidOperationException($"GltfDocument.AppendFromFile failed for '{glbPath}': {err}"); + } + + Node? generated = doc.GenerateScene(state); + if (generated is not Node3D sceneRoot) + { + generated?.QueueFree(); + throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for '{glbPath}'."); + } + ClearOwnerRecursive(sceneRoot); + + var gltfNodes = state.GetNodes(); + var jsonNodes = jsonRoot.GetProperty("nodes"); + int nodeCount = Math.Min(gltfNodes.Count, jsonNodes.GetArrayLength()); + + var pathByGltfIndex = new NodePath[nodeCount]; + var nodeByGltfIndex = new Node3D?[nodeCount]; + var origNameByIndex = new string[nodeCount]; + var nodesByOriginalName = new Dictionary(StringComparer.Ordinal); + var anchors = new Dictionary(StringComparer.Ordinal); + var joints = new Dictionary(StringComparer.Ordinal); + var protectedIndices = new HashSet(); + var parentByIndex = new Dictionary(); + + for (int i = 0; i < nodeCount; i++) + { + JsonElement jn = jsonNodes[i]; + if (jn.TryGetProperty("children", out var childrenEl) && childrenEl.ValueKind == JsonValueKind.Array) + { + foreach (var ch in childrenEl.EnumerateArray()) + { + parentByIndex[ch.GetInt32()] = i; + } + } + } + + // Resolve every glTF node deterministically to its exact Godot Node3D via GltfNode.GetSceneNodePath(state) + for (int i = 0; i < nodeCount; i++) + { + GltfNode gn = gltfNodes[i]; + JsonElement jn = jsonNodes[i]; + string origName = !string.IsNullOrEmpty(gn.OriginalName) + ? gn.OriginalName + : (jn.TryGetProperty("name", out var nm) ? nm.GetString() ?? $"node_{i}" : $"node_{i}"); + origNameByIndex[i] = origName; + + Node? resolved = ResolveSceneNode(sceneRoot, gn.GetSceneNodePath(state), origName); + if (resolved is Node3D n3d) + { + NodePath relPath = BuildRelativeNodePath(sceneRoot, n3d); + pathByGltfIndex[i] = relPath; + nodeByGltfIndex[i] = n3d; + nodesByOriginalName.TryAdd(origName, relPath); + } + else + { + pathByGltfIndex[i] = new NodePath(); + } + } + + // Compute model-space transforms once from sceneRoot + var modelTransforms = new Dictionary(); + CollectModelTransforms(sceneRoot, Transform3D.Identity, modelTransforms); + + // Extract rtd.* extras from glTF JSON chunk & mark protected structural/joint/hardpoint nodes + for (int i = 0; i < nodeCount; i++) + { + JsonElement jn = jsonNodes[i]; + Node3D? node = nodeByGltfIndex[i]; + if (node is null) + { + continue; + } + + NodePath relPath = pathByGltfIndex[i]; + if (!jn.TryGetProperty("extras", out JsonElement extras) || extras.ValueKind != JsonValueKind.Object) + { + continue; + } + + if (extras.TryGetProperty("rtd.id", out var rtdIdEl) && rtdIdEl.ValueKind == JsonValueKind.String) + { + string hpId = rtdIdEl.GetString()!; + string hpKind = extras.TryGetProperty("rtd.kind", out var kEl) && kEl.ValueKind == JsonValueKind.String + ? kEl.GetString()! + : "weapon"; + Vector3 hpSize = ReadVec3(extras, "rtd.size", new Vector3(0.5f, 0.5f, 0.1f)); + Transform3D modelXform = modelTransforms.TryGetValue(node, out var xf) ? xf : Transform3D.Identity; + anchors[hpId] = new GlbAnchorInfo(hpId, hpKind, hpSize, relPath, modelXform); + MarkAncestorsProtected(i, parentByIndex, protectedIndices); + } + + if (extras.TryGetProperty("rtd.joint", out var rtdJointEl) && rtdJointEl.ValueKind == JsonValueKind.String) + { + string jId = rtdJointEl.GetString()!; + Vector3 axis = ReadVec3(extras, "rtd.axis", Vector3.Up); + if (axis.LengthSquared() < 1e-6f) axis = Vector3.Up; + axis = axis.Normalized(); + float minVal = extras.TryGetProperty("rtd.min", out var mnEl) ? mnEl.GetSingle() : -180f; + float maxVal = extras.TryGetProperty("rtd.max", out var mxEl) ? mxEl.GetSingle() : 180f; + joints[jId] = new GlbJointInfo(jId, origNameByIndex[i], axis, minVal, maxVal, relPath); + MarkAncestorsProtected(i, parentByIndex, protectedIndices); + } + } + + // Also mark structural mechanism/skeleton/mobility nodes and their ancestors protected + var mobilityPaths = new List(); + var mechNames = new HashSet(StringComparer.Ordinal); + if (pkg.Mechanisms is not null) + { + foreach (var d in pkg.Mechanisms.Dofs) mechNames.Add(d.Name); + foreach (var r in pkg.Mechanisms.Rams) + { + mechNames.Add(r.Name); + mechNames.Add(r.BarrelBone); + mechNames.Add(r.RodBone); + } + foreach (var sc in pkg.Mechanisms.Scissors) + { + mechNames.Add(sc.Name); + mechNames.Add(sc.UpperBone); + mechNames.Add(sc.LowerBone); + } + } + + for (int i = 0; i < nodeCount; i++) + { + string nm = origNameByIndex[i]; + if (mechNames.Contains(nm) || IsStructuralNodeName(nm)) + { + MarkAncestorsProtected(i, parentByIndex, protectedIndices); + } + } + + foreach (var pc in pkg.PartCells) + { + if (string.Equals(pc.Kind, "mobility", StringComparison.OrdinalIgnoreCase)) + { + if (nodesByOriginalName.TryGetValue(pc.NodeName, out var mobPath)) + { + mobilityPaths.Add(mobPath); + } + for (int i = 0; i < nodeCount; i++) + { + if (string.Equals(origNameByIndex[i], pc.NodeName, StringComparison.Ordinal)) + { + MarkAncestorsProtected(i, parentByIndex, protectedIndices); + } + } + } + } + + // Compute protected-descendant flag for each glTF node index + var hasProtectedDesc = new bool[nodeCount]; + for (int i = 0; i < nodeCount; i++) + { + if (protectedIndices.Contains(i)) + { + int cur = i; + while (parentByIndex.TryGetValue(cur, out int p)) + { + hasProtectedDesc[p] = true; + cur = p; + } + } + } + + // Index detachable exterior armor/shroud (and safe leaf cladding) parts mapped to cells + var indexByName = new Dictionary(StringComparer.Ordinal); + for (int i = 0; i < nodeCount; i++) + { + indexByName.TryAdd(origNameByIndex[i], i); + } + + var detachableParts = new List(); + foreach (var pc in pkg.PartCells) + { + if (!indexByName.TryGetValue(pc.NodeName, out int idx)) + { + continue; + } + Node3D? node = nodeByGltfIndex[idx]; + if (node is not MeshInstance3D) + { + continue; + } + if (protectedIndices.Contains(idx) || hasProtectedDesc[idx]) + { + continue; + } + if (!IsDetachablePartKind(pc.Kind, pc.NodeName, node.GetChildCount())) + { + continue; + } + detachableParts.Add(new GlbPartNodeInfo( + pc.NodeName, + pc.CellX, + pc.CellY, + pc.Kind, + pathByGltfIndex[idx], + hasProtectedDesc[idx])); + } + + // Verify all VehiclePackage hardpoint AnchorIds & Joints resolved + foreach (var hp in pkg.Hardpoints) + { + if (!anchors.ContainsKey(hp.AnchorId)) + { + sceneRoot.QueueFree(); + throw new InvalidOperationException($"{pkg.Id}: failed to resolve hardpoint AnchorId '{hp.AnchorId}' in '{glbPath}'."); + } + } + foreach (var j in pkg.Joints) + { + if (!joints.ContainsKey(j.Id)) + { + sceneRoot.QueueFree(); + throw new InvalidOperationException($"{pkg.Id}: failed to resolve joint '{j.Id}' in '{glbPath}'."); + } + } + + ComputeSceneMeshBoundsY(sceneRoot, out float minY, out float maxY); + + // Build full set of protected structural/rig/joint/anchor/mobility Godot nodes + var protectedNodes = new HashSet { sceneRoot }; + for (int i = 0; i < nodeCount; i++) + { + if ((protectedIndices.Contains(i) || hasProtectedDesc[i]) && nodeByGltfIndex[i] is { } pn) + { + MarkNodeAndAncestorsProtected(pn, sceneRoot, protectedNodes); + } + } + foreach (var a in anchors.Values) + { + if (sceneRoot.GetNodeOrNull(a.RelativePath) is { } an) + { + MarkNodeAndAncestorsProtected(an, sceneRoot, protectedNodes); + } + } + foreach (var j in joints.Values) + { + if (sceneRoot.GetNodeOrNull(j.RelativePath) is { } jn) + { + MarkNodeAndAncestorsProtected(jn, sceneRoot, protectedNodes); + } + } + foreach (var mp in mobilityPaths) + { + if (sceneRoot.GetNodeOrNull(mp) is { } mn) + { + MarkNodeAndAncestorsProtected(mn, sceneRoot, protectedNodes); + } + } + + // Map original detachable MeshInstance3Ds so we can merge them per (rigidParent, CellX, CellY) + var detachableByNode = new Dictionary(); + foreach (var dp in detachableParts) + { + if (sceneRoot.GetNodeOrNull(dp.RelativePath) is MeshInstance3D mi && !protectedNodes.Contains(mi)) + { + detachableByNode.TryAdd(mi, (dp.CellX, dp.CellY, dp.Kind)); + } + } + + // A & B: Merge detachable armor per (rigidParent, CellX, CellY) and static meshes per rigidParent + var mergedDetachableInfos = MergeVehicleSubMeshes(sceneRoot, protectedNodes, detachableByNode); + + // Prune stale nodesByOriginalName entries that were collapsed into merged meshes + var survivingNames = new Dictionary(StringComparer.Ordinal); + foreach (var (origName, relPath) in nodesByOriginalName) + { + Node? resolved = relPath.ToString() == "." ? sceneRoot : sceneRoot.GetNodeOrNull(relPath); + if (resolved is not null) + { + survivingNames[origName] = relPath; + } + } + + // C: Build single-node BakedStaticMesh + decimated BakedLodFarMesh (>130m) per template + ArrayMesh bakedStaticMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false); + ArrayMesh bakedCoarseStatic = BuildBakedStaticMesh(sceneRoot, coarseMaterials: true); + ArrayMesh bakedLodFarMesh = DecimateMeshGrid(bakedCoarseStatic, cellSize: 0.45f, targetMinY: minY); + + ArrayMesh singleSurfaceStatic = CollapseToSingleSurfaceMechPaintMesh(bakedStaticMesh); + ArrayMesh singleSurfaceLodFar = CollapseToSingleSurfaceMechPaintMesh(bakedLodFarMesh); + Vector3[] farRayTris = ExtractFlatTriangles(singleSurfaceLodFar); + Aabb farRayAabb = singleSurfaceLodFar.GetAabb().Grow(0.20f); + + // D: Extract single-surface MechPaint rigid parts (static limbs + detachable armor chunks) + // and strip all MeshInstance3D nodes from SceneTemplate so live rigs have zero MeshInstance3D children! + ExtractRigidPartsAndStripMeshes( + sceneRoot, + protectedNodes, + mergedDetachableInfos, + out var staticRigidParts, + out var detachableRigidParts); + + return new VehicleTemplate + { + Package = pkg, + GlbPath = glbPath, + SceneTemplate = sceneRoot, + BakedStaticMesh = bakedStaticMesh, + BakedLodFarMesh = bakedLodFarMesh, + SingleSurfaceStaticMesh = singleSurfaceStatic, + SingleSurfaceLodFarMesh = singleSurfaceLodFar, + FarRayTris = farRayTris, + FarRayAabb = farRayAabb, + MinY = minY, + MaxY = maxY, + Anchors = anchors, + Joints = joints, + NodesByOriginalName = survivingNames, + DetachableParts = mergedDetachableInfos, + StaticRigidParts = staticRigidParts, + DetachableRigidParts = detachableRigidParts, + MobilityNodePaths = mobilityPaths + }; + } + + private static readonly HashSet PreservedGearPartNames = new(StringComparer.OrdinalIgnoreCase) + { + "barrel_inner", "receiver", "muzzle_brake_L", "gun_housing", + "sight_tube", "breech_band", "condenser_ring_2", "ivory_cowl" + }; + + private static GearTemplate LoadGearTemplate(string gearId, string glbPath) + { + var doc = new GltfDocument(); + var state = new GltfState(); + Error err = doc.AppendFromFile(glbPath, state, flags: 0, basePath: Path.GetDirectoryName(glbPath) ?? string.Empty); + if (err != Error.Ok) + { + throw new InvalidOperationException($"GltfDocument.AppendFromFile failed for gear '{glbPath}': {err}"); + } + + Node? generated = doc.GenerateScene(state); + if (generated is not Node3D sceneRoot) + { + generated?.QueueFree(); + throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for gear '{glbPath}'."); + } + ClearOwnerRecursive(sceneRoot); + + ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax); + var partCentroids = CollectGearPartCentroids(sceneRoot); + MergeGearSubMeshes(sceneRoot, gearId); + ArrayMesh bakedDropMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false); + ArrayMesh singleSurfaceMesh = CollapseToSingleSurfaceMechPaintMesh(bakedDropMesh); + Vector3 localFwd = new Vector3(0f, 0f, 1f); + + return new GearTemplate + { + Id = gearId, + GlbPath = glbPath, + SceneTemplate = sceneRoot, + BakedDropMesh = bakedDropMesh, + SingleSurfaceMesh = singleSurfaceMesh, + Size = bMax - bMin, + MinY = bMin.Y, + LocalModelForward = localFwd, + PartCentroidsLocal = partCentroids + }; + } + + private static WeaponPartTemplate LoadWeaponPartTemplate(string partId, string glbPath) + { + var doc = new GltfDocument(); + var state = new GltfState(); + Error err = doc.AppendFromFile(glbPath, state, flags: 0, basePath: Path.GetDirectoryName(glbPath) ?? string.Empty); + if (err != Error.Ok) + { + throw new InvalidOperationException($"GltfDocument.AppendFromFile failed for weapon part '{glbPath}': {err}"); + } + + Node? generated = doc.GenerateScene(state); + if (generated is not Node3D sceneRoot) + { + generated?.QueueFree(); + throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for weapon part '{glbPath}'."); + } + ClearOwnerRecursive(sceneRoot); + + var modelTransforms = new Dictionary(); + CollectModelTransforms(sceneRoot, Transform3D.Identity, modelTransforms); + + string partSlot = "unknown"; + var sockets = new Dictionary(StringComparer.OrdinalIgnoreCase); + + byte[] jsonBytes = ReadGlbJsonChunk(glbPath); + using (var jsonDoc = JsonDocument.Parse(jsonBytes)) + { + if (jsonDoc.RootElement.TryGetProperty("nodes", out JsonElement jsonNodes) && + jsonNodes.ValueKind == JsonValueKind.Array) + { + var gltfNodes = state.Nodes; + int nodeCount = Math.Min(gltfNodes.Count, jsonNodes.GetArrayLength()); + for (int i = 0; i < nodeCount; i++) + { + JsonElement jn = jsonNodes[i]; + if (!jn.TryGetProperty("extras", out JsonElement extras) || extras.ValueKind != JsonValueKind.Object) + { + continue; + } + + GltfNode gn = gltfNodes[i]; + string origName = !string.IsNullOrEmpty(gn.OriginalName) + ? gn.OriginalName + : (jn.TryGetProperty("name", out var nm) ? nm.GetString() ?? $"node_{i}" : $"node_{i}"); + Node? resolved = ResolveSceneNode(sceneRoot, gn.GetSceneNodePath(state), origName); + if (resolved is not Node3D n3d) + { + continue; + } + + if (extras.TryGetProperty("rtd.part_slot", out var slotEl) && slotEl.ValueKind == JsonValueKind.String) + { + partSlot = slotEl.GetString() ?? partSlot; + } + if (extras.TryGetProperty("rtd.socket", out var sockEl) && sockEl.ValueKind == JsonValueKind.String) + { + string? sockName = sockEl.GetString(); + if (!string.IsNullOrWhiteSpace(sockName) && modelTransforms.TryGetValue(n3d, out Transform3D sockXf)) + { + sockets[sockName] = sockXf; + } + } + } + } + } + + ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax); + ArrayMesh bakedMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false); + ArrayMesh singleSurfaceMesh = CollapseToSingleSurfaceMechPaintMesh(bakedMesh); + + return new WeaponPartTemplate + { + Id = partId, + Slot = partSlot, + GlbPath = glbPath, + SceneTemplate = sceneRoot, + SingleSurfaceMesh = singleSurfaceMesh, + Size = bMax - bMin, + MinY = bMin.Y, + SocketsLocal = sockets + }; + } + + private static DropPodTemplate LoadDropPodTemplate(string glbPath) + { + var doc = new GltfDocument(); + var state = new GltfState(); + Error err = doc.AppendFromFile(glbPath, state, flags: 0, basePath: Path.GetDirectoryName(glbPath) ?? string.Empty); + if (err != Error.Ok) + { + throw new InvalidOperationException($"GltfDocument.AppendFromFile failed for drop_pod '{glbPath}': {err}"); + } + + Node? generated = doc.GenerateScene(state); + if (generated is not Node3D sceneRoot) + { + generated?.QueueFree(); + throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for drop_pod '{glbPath}'."); + } + ClearOwnerRecursive(sceneRoot); + + ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax); + float yGroundShift = MathF.Abs(bMin.Y) > 1e-4f ? -bMin.Y : 0f; + Transform3D groundShift = new Transform3D(Basis.Identity, new Vector3(0f, yGroundShift, 0f)); + + var allMeshes = new List(); + CollectAllMeshInstances(sceneRoot, allMeshes); + + var coreSources = new List<(Mesh Mesh, Transform3D RelXf)>(allMeshes.Count); + var petalMeshes = new MeshInstance3D?[4]; + var petalTransforms = new Transform3D[4]; + + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (!CanMergeMeshInstance(mi) || mi.Mesh is null) + { + continue; + } + + string nodeName = mi.Name.ToString(); + int petalIdx = -1; + if (nodeName.StartsWith("Petal_", StringComparison.OrdinalIgnoreCase) && + int.TryParse(nodeName.AsSpan(6), out int parsedIdx) && + parsedIdx is >= 0 and < 4) + { + petalIdx = parsedIdx; + } + + if (petalIdx >= 0) + { + petalMeshes[petalIdx] = mi; + petalTransforms[petalIdx] = groundShift * ComputeRelativeTransform(sceneRoot, mi); + } + else + { + coreSources.Add((mi.Mesh, groundShift * ComputeRelativeTransform(sceneRoot, mi))); + } + } + + for (int p = 0; p < 4; p++) + { + if (petalMeshes[p]?.Mesh is null) + { + sceneRoot.QueueFree(); + throw new InvalidOperationException($"drop_pod GLB '{glbPath}' missing Petal_{p} mesh."); + } + } + + ArrayMesh coreMesh = CollapseToSingleSurfaceMechPaintMesh(coreSources) + ?? throw new InvalidOperationException($"drop_pod GLB '{glbPath}' produced empty CoreMesh."); + + var petalSources = new List<(Mesh Mesh, Transform3D RelXf)>(1) + { + (petalMeshes[0]!.Mesh!, Transform3D.Identity) + }; + ArrayMesh petalMesh = CollapseToSingleSurfaceMechPaintMesh(petalSources) + ?? throw new InvalidOperationException($"drop_pod GLB '{glbPath}' produced empty PetalMesh."); + + return new DropPodTemplate + { + GlbPath = glbPath, + SceneTemplate = sceneRoot, + CoreMesh = coreMesh, + PetalMesh = petalMesh, + PetalLocalTransforms = petalTransforms, + Size = bMax - bMin, + MinY = 0f, + MaxY = bMax.Y - bMin.Y + }; + } + + private static readonly HashSet ExactStructuralNodeNames = new(StringComparer.OrdinalIgnoreCase) + { + "chassis", "hull", "pelvis", "core", "trunk", "waist", "waistlug", "torso.pose", "aim.turret", "hull.pose", + "legl.hipslew", "legr.hipslew", "legl.hip", "legr.hip", "legl.hipyaw", "legr.hipyaw", + "legl.cross", "legr.cross", + "legl.shin", "legr.shin", "legl.foot", "legr.foot", "footl", "footr", + "legl.upper", "legr.upper", "legl.lower", "legr.lower", "legl.ankle", "legr.ankle", + "legl.thigh", "legr.thigh", "legl.cannon", "legr.cannon", + "legl.oleo", "legr.oleo", "legl.oleofork", "legr.oleofork", + "legl.torqueup", "legr.torqueup", "legl.torquelow", "legr.torquelow", + "legl.lug", "legr.lug", "legl.ramluga0", "legl.ramluga1", "legr.ramluga0", "legr.ramluga1", + "legl.recessram0", "legl.recessram1", "legr.recessram0", "legr.recessram1", + "legfl.coxa", "legfr.coxa", "legbl.coxa", "legbr.coxa", + "legfl.s1", "legfr.s1", "legbl.s1", "legbr.s1", + "legfl.s2", "legfr.s2", "legbl.s2", "legbr.s2", + "footfl", "footfr", "footbl", "footbr", + "bone.hip_splay.fl", "bone.hip_splay.fr", "bone.hip_splay.rl", "bone.hip_splay.rr", + "thigh.fl", "thigh.fr", "thigh.rl", "thigh.rr", + "shin.fl", "shin.fr", "shin.rl", "shin.rr", + "ankle.fl", "ankle.fr", "ankle.rl", "ankle.rr", + "foot.fl", "foot.fr", "foot.rl", "foot.rr" + }; + + private static bool IsStructuralNodeName(string name) => + ExactStructuralNodeNames.Contains(name); + + private static void ClearOwnerRecursive(Node cur) + { + cur.Owner = null; + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + ClearOwnerRecursive(cur.GetChild(i)); + } + } + + private static bool IsDetachablePartKind(string kind, string nodeName, int childCount) + { + if (string.Equals(kind, "armor", StringComparison.OrdinalIgnoreCase) || + string.Equals(kind, "shroud", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + if (!string.Equals(kind, "hull", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + string low = nodeName.ToLowerInvariant(); + // Safe exterior cladding panels (e.g., buggy hood/side panels, skirt/tasset/cod plates, mech dress panels) + if (low.Contains("hood") || low.Contains("side.") || low.Contains("roof") || + low.Contains("tasset") || low.Contains("cod") || low.Contains("cuisse") || + low.Contains(".panels") || low.Contains(".dress.") || low.Contains("brow") || + low.Contains("pauldron") || low.Contains("wing") && !low.Contains("stub_wing")) + { + return true; + } + return childCount == 0 && (low.Contains("canopy") || low.Contains("hatch") || low.Contains("visor")); + } + + private static void MarkNodeAndAncestorsProtected(Node node, Node root, HashSet protectedNodes) + { + Node? cur = node; + while (cur is not null) + { + protectedNodes.Add(cur); + if (ReferenceEquals(cur, root)) + { + break; + } + cur = cur.GetParent(); + } + } + + private static Node3D FindNearestProtectedParent(Node node, Node3D sceneRoot, HashSet protectedNodes) + { + Node? cur = node.GetParent(); + while (cur is not null) + { + if (cur is Node3D n3d && protectedNodes.Contains(cur)) + { + return n3d; + } + if (ReferenceEquals(cur, sceneRoot)) + { + break; + } + cur = cur.GetParent(); + } + return sceneRoot; + } + + private static Transform3D ComputeRelativeTransform(Node3D ancestor, Node descendant) + { + Transform3D xf = Transform3D.Identity; + Node? cur = descendant; + while (cur is not null && !ReferenceEquals(cur, ancestor)) + { + if (cur is Node3D n3d) + { + xf = n3d.Transform * xf; + } + cur = cur.GetParent(); + } + return xf; + } + + private static bool CanMergeMeshInstance(MeshInstance3D mi) + { + if (mi.Mesh is null || mi.Mesh.GetSurfaceCount() == 0) + { + return false; + } + if (mi.Mesh is ArrayMesh am) + { + int surfCount = am.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + if (am.SurfaceGetPrimitiveType(s) != Mesh.PrimitiveType.Triangles) + { + return false; + } + } + } + return true; + } + + private static void CollectAllMeshInstances(Node cur, List outList) + { + if (cur is MeshInstance3D mi) + { + outList.Add(mi); + } + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + CollectAllMeshInstances(cur.GetChild(i), outList); + } + } + + private static void ReparentChildrenAndRemove(MeshInstance3D mi) + { + Node? parent = mi.GetParent(); + if (parent is not null) + { + for (int i = mi.GetChildCount() - 1; i >= 0; i--) + { + Node ch = mi.GetChild(i); + mi.RemoveChild(ch); + if (ch is Node3D ch3d) + { + ch3d.Transform = mi.Transform * ch3d.Transform; + } + parent.AddChild(ch); + } + parent.RemoveChild(mi); + } + mi.QueueFree(); + } + + private static List MergeVehicleSubMeshes( + Node3D sceneRoot, + HashSet protectedNodes, + Dictionary detachableByNode) + { + var allMeshes = new List(); + CollectAllMeshInstances(sceneRoot, allMeshes); + + var detachableGroups = new Dictionary<(Node3D RigidParent, int CellX, int CellY), (string Kind, List<(MeshInstance3D Mi, Transform3D RelXf)> Items)>(); + var staticGroups = new Dictionary>(); + var detachResultNodes = new List<(MeshInstance3D Node, int CellX, int CellY, string Kind)>(); + + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (!CanMergeMeshInstance(mi)) + { + continue; + } + + if (detachableByNode.TryGetValue(mi, out var detInfo)) + { + Node3D rigidParent = FindNearestProtectedParent(mi, sceneRoot, protectedNodes); + Transform3D relXf = ComputeRelativeTransform(rigidParent, mi); + var key = (rigidParent, detInfo.CellX, detInfo.CellY); + if (!detachableGroups.TryGetValue(key, out var group)) + { + group = (detInfo.Kind, new List<(MeshInstance3D, Transform3D)>()); + detachableGroups[key] = group; + } + group.Items.Add((mi, relXf)); + } + else if (!protectedNodes.Contains(mi)) + { + Node3D rigidParent = FindNearestProtectedParent(mi, sceneRoot, protectedNodes); + Transform3D relXf = ComputeRelativeTransform(rigidParent, mi); + if (!staticGroups.TryGetValue(rigidParent, out var list)) + { + list = new List<(MeshInstance3D, Transform3D)>(); + staticGroups[rigidParent] = list; + } + list.Add((mi, relXf)); + } + } + + // B. Merge detachable armor parts per (rigidParent, CellX, CellY) + int detSeq = 0; + foreach (var ((rigidParent, cellX, cellY), (kind, items)) in detachableGroups) + { + if (items.Count == 1 && ReferenceEquals(items[0].Mi.GetParent(), rigidParent)) + { + // Already a single child directly under rigidParent — keep as-is + detachResultNodes.Add((items[0].Mi, cellX, cellY, kind)); + continue; + } + + ArrayMesh? merged = BuildMergedArrayMesh(items); + if (merged is null) + { + continue; + } + + var chunkNode = new MeshInstance3D + { + Name = $"ArmorCell_{cellX}_{cellY}_{detSeq++}", + Mesh = merged + }; + rigidParent.AddChild(chunkNode); + detachResultNodes.Add((chunkNode, cellX, cellY, kind)); + + for (int i = 0; i < items.Count; i++) + { + ReparentChildrenAndRemove(items[i].Mi); + } + } + + // A. Merge static non-detachable sub-meshes per rigid articulated parent, and collapse PaintTag==0 surfaces on protected structural meshes + var mergedProtectedMeshes = new HashSet(); + foreach (var (rigidParent, items) in staticGroups) + { + if (rigidParent is MeshInstance3D parentMi && CanMergeMeshInstance(parentMi)) + { + var combined = new List<(MeshInstance3D, Transform3D)>(items.Count + 1) + { + (parentMi, Transform3D.Identity) + }; + combined.AddRange(items); + ArrayMesh? merged = BuildMergedArrayMesh(combined); + if (merged is not null) + { + parentMi.MaterialOverride = null; + parentMi.Mesh = merged; + mergedProtectedMeshes.Add(parentMi); + for (int i = 0; i < items.Count; i++) + { + ReparentChildrenAndRemove(items[i].Mi); + } + } + } + else if (items.Count > 1 || (items.Count == 1 && !ReferenceEquals(items[0].Mi.GetParent(), rigidParent))) + { + ArrayMesh? merged = BuildMergedArrayMesh(items); + if (merged is not null) + { + var staticNode = new MeshInstance3D + { + Name = $"{rigidParent.Name}_StaticMerged", + Mesh = merged + }; + rigidParent.AddChild(staticNode); + for (int i = 0; i < items.Count; i++) + { + ReparentChildrenAndRemove(items[i].Mi); + } + } + } + } + + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (GodotObject.IsInstanceValid(mi) && + protectedNodes.Contains(mi) && + !mergedProtectedMeshes.Contains(mi) && + CanMergeMeshInstance(mi) && + mi.Mesh is not null && + mi.Mesh.GetSurfaceCount() > 1) + { + var single = new List<(MeshInstance3D, Transform3D)>(1) { (mi, Transform3D.Identity) }; + ArrayMesh? collapsed = BuildMergedArrayMesh(single); + if (collapsed is not null && collapsed.GetSurfaceCount() < mi.Mesh.GetSurfaceCount()) + { + mi.MaterialOverride = null; + mi.Mesh = collapsed; + } + } + } + + // Prune empty non-protected grouping nodes left behind + PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, protectedNodes); + + var result = new List(detachResultNodes.Count); + for (int i = 0; i < detachResultNodes.Count; i++) + { + var (node, cellX, cellY, kind) = detachResultNodes[i]; + if (!GodotObject.IsInstanceValid(node) || !sceneRoot.IsAncestorOf(node)) + { + continue; + } + result.Add(new GlbPartNodeInfo( + node.Name, + cellX, + cellY, + kind, + BuildRelativeNodePath(sceneRoot, node), + HasProtectedDescendant: false)); + } + return result; + } + + private static void MergeGearSubMeshes(Node3D sceneRoot, string gearId) + { + var keptNodes = new HashSet { sceneRoot }; + var allMeshes = new List(); + CollectAllMeshInstances(sceneRoot, allMeshes); + + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (PreservedGearPartNames.Contains(mi.Name)) + { + MarkNodeAndAncestorsProtected(mi, sceneRoot, keptNodes); + } + } + + var mergeList = new List<(MeshInstance3D Mi, Transform3D RelXf)>(); + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (!keptNodes.Contains(mi) && CanMergeMeshInstance(mi)) + { + mergeList.Add((mi, ComputeRelativeTransform(sceneRoot, mi))); + } + } + + if (mergeList.Count <= 1) + { + return; + } + + ArrayMesh? merged = BuildMergedArrayMesh(mergeList); + if (merged is null) + { + return; + } + + var mergedNode = new MeshInstance3D + { + Name = $"{gearId}_StaticMerged", + Mesh = merged + }; + sceneRoot.AddChild(mergedNode); + for (int i = 0; i < mergeList.Count; i++) + { + ReparentChildrenAndRemove(mergeList[i].Mi); + } + PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, keptNodes); + } + + private static ArrayMesh BuildBakedStaticMesh(Node3D sceneRoot, bool coarseMaterials = false) + { + var allMeshes = new List(); + CollectAllMeshInstances(sceneRoot, allMeshes); + + var items = new List<(MeshInstance3D Mi, Transform3D RelXf)>(allMeshes.Count); + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (CanMergeMeshInstance(mi)) + { + items.Add((mi, ComputeRelativeTransform(sceneRoot, mi))); + } + } + + return BuildMergedArrayMesh(items, coarseMaterials) ?? new ArrayMesh(); + } + + private static Dictionary CollectGearPartCentroids(Node3D sceneRoot) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + var allMeshes = new List(); + CollectAllMeshInstances(sceneRoot, allMeshes); + + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (!PreservedGearPartNames.Contains(mi.Name) || mi.Mesh is null) + { + continue; + } + Transform3D toRoot = ComputeRelativeTransform(sceneRoot, mi); + Vector3 sum = Vector3.Zero; + int count = 0; + int surfCount = mi.Mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arr = mi.Mesh.SurfaceGetArrays(s); + if (arr.Count > (int)Mesh.ArrayType.Vertex && + arr[(int)Mesh.ArrayType.Vertex].VariantType == Variant.Type.PackedVector3Array) + { + Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + for (int v = 0; v < verts.Length; v++) + { + sum += toRoot * verts[v]; + count++; + } + } + } + if (count > 0) + { + result[mi.Name] = sum / count; + } + } + return result; + } + + private static void ExtractRigidPartsAndStripMeshes( + Node3D sceneRoot, + HashSet protectedNodes, + List detachableInfos, + out List staticPartsOut, + out List detachablePartsOut) + { + staticPartsOut = new List(); + detachablePartsOut = new List(); + + var detachableSet = new Dictionary(); + for (int i = 0; i < detachableInfos.Count; i++) + { + var dp = detachableInfos[i]; + if (sceneRoot.GetNodeOrNull(dp.RelativePath) is MeshInstance3D dmi) + { + detachableSet[dmi] = dp; + } + } + + // 1. Extract detachable per-cell armor chunks in their rigidParent's local space + foreach (var (mi, dp) in detachableSet) + { + if (!CanMergeMeshInstance(mi) || mi.Mesh is null) + { + continue; + } + Node3D rigidParent = protectedNodes.Contains(mi) + ? mi + : FindNearestProtectedParent(mi, sceneRoot, protectedNodes); + Transform3D relXf = ReferenceEquals(mi, rigidParent) + ? Transform3D.Identity + : ComputeRelativeTransform(rigidParent, mi); + var single = new List<(Mesh Mesh, Transform3D RelXf)>(1) { (mi.Mesh, relXf) }; + ArrayMesh? collapsed = CollapseToSingleSurfaceMechPaintMesh(single); + if (collapsed is not null) + { + detachablePartsOut.Add(new RigidPartTemplate( + BuildRelativeNodePath(sceneRoot, rigidParent), + collapsed, + dp.CellX, + dp.CellY, + dp.Kind)); + } + } + + // 2. Group remaining non-detachable rigid meshes by rigidParent and collapse each to 1 surface + var allMeshes = new List(); + CollectAllMeshInstances(sceneRoot, allMeshes); + var staticByPivot = new Dictionary>(); + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (detachableSet.ContainsKey(mi) || !CanMergeMeshInstance(mi) || mi.Mesh is null) + { + continue; + } + Node3D rigidParent = protectedNodes.Contains(mi) + ? mi + : FindNearestProtectedParent(mi, sceneRoot, protectedNodes); + Transform3D relXf = ReferenceEquals(mi, rigidParent) + ? Transform3D.Identity + : ComputeRelativeTransform(rigidParent, mi); + if (!staticByPivot.TryGetValue(rigidParent, out var list)) + { + list = new List<(Mesh, Transform3D)>(); + staticByPivot[rigidParent] = list; + } + list.Add((mi.Mesh, relXf)); + } + + foreach (var (rigidParent, items) in staticByPivot) + { + ArrayMesh? collapsed = CollapseToSingleSurfaceMechPaintMesh(items); + if (collapsed is not null) + { + staticPartsOut.Add(new RigidPartTemplate( + BuildRelativeNodePath(sceneRoot, rigidParent), + collapsed, + -1, + -1, + "static")); + } + } + + // 3. Strip all MeshInstance3D nodes from sceneRoot: + // - Protected MeshInstance3Ds become plain Node3D pivots preserving Name, Transform, and children. + // - Non-protected MeshInstance3Ds are removed cleanly. + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (!GodotObject.IsInstanceValid(mi) || ReferenceEquals(mi, sceneRoot)) + { + continue; + } + if (protectedNodes.Contains(mi)) + { + ReplaceMeshInstanceWithPivot(mi); + } + else + { + ReparentChildrenAndRemove(mi); + } + } + } + + private static void ReplaceMeshInstanceWithPivot(MeshInstance3D mi) + { + Node? parent = mi.GetParent(); + if (parent is null) + { + return; + } + int idx = mi.GetIndex(); + var pivot = new Node3D + { + Name = mi.Name, + Transform = mi.Transform + }; + parent.RemoveChild(mi); + parent.AddChild(pivot); + parent.MoveChild(pivot, idx); + while (mi.GetChildCount() > 0) + { + Node ch = mi.GetChild(0); + mi.RemoveChild(ch); + pivot.AddChild(ch); + } + mi.QueueFree(); + } + + private static Vector3[] ExtractFlatTriangles(ArrayMesh mesh) + { + var tris = new List(); + int surfCount = mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arr = mesh.SurfaceGetArrays(s); + if (arr.Count <= (int)Mesh.ArrayType.Vertex || + arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + int[]? indices = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array + ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() + : null; + int triCount = (indices is not null ? indices.Length : verts.Length) / 3; + for (int t = 0; t < triCount; t++) + { + int i0 = indices is not null ? indices[t * 3] : t * 3; + int i1 = indices is not null ? indices[t * 3 + 1] : t * 3 + 1; + int i2 = indices is not null ? indices[t * 3 + 2] : t * 3 + 2; + tris.Add(verts[i0]); + tris.Add(verts[i1]); + tris.Add(verts[i2]); + } + } + return tris.ToArray(); + } + + public static ArrayMesh CollapseToSingleSurfaceMechPaintMesh( + ArrayMesh src, + Color? gearPaintTint = null, + Color? gearAccentTint = null) + { + var list = new List<(Mesh Mesh, Transform3D RelXf)>(1) { (src, Transform3D.Identity) }; + return CollapseToSingleSurfaceMechPaintMesh(list, gearPaintTint, gearAccentTint) ?? new ArrayMesh(); + } + + private static ArrayMesh? CollapseToSingleSurfaceMechPaintMesh( + List<(Mesh Mesh, Transform3D RelXf)> sources, + Color? gearPaintTint = null, + Color? gearAccentTint = null) + { + int totalVerts = 0; + int totalIndices = 0; + var chunks = new List<(Godot.Collections.Array Arrays, Transform3D RelXf, Vector3 LinearCol, int Band, float Rough, int VertCount, int IdxCount)>(); + + for (int i = 0; i < sources.Count; i++) + { + var (mesh, relXf) = sources[i]; + int surfCount = mesh.GetSurfaceCount(); + var am = mesh as ArrayMesh; + for (int s = 0; s < surfCount; s++) + { + if (am is not null && am.SurfaceGetPrimitiveType(s) != Mesh.PrimitiveType.Triangles) + { + continue; + } + var arr = mesh.SurfaceGetArrays(s); + if (arr.Count <= (int)Mesh.ArrayType.Vertex || + arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + if (verts.Length == 0) + { + continue; + } + + int idxCount = verts.Length; + if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array) + { + idxCount = arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length; + } + if (idxCount < 3) + { + continue; + } + + ClassifyMaterialForMechPaint(mesh.SurfaceGetMaterial(s), gearPaintTint, gearAccentTint, out Vector3 linCol, out int band, out float rough); + chunks.Add((arr, relXf, linCol, band, rough, verts.Length, idxCount)); + totalVerts += verts.Length; + totalIndices += idxCount; + } + } + + if (totalVerts == 0 || totalIndices == 0) + { + return null; + } + + var outVerts = new Vector3[totalVerts]; + var outNorms = new Vector3[totalVerts]; + var outColors = new Color[totalVerts]; + var outUvs = new Vector2[totalVerts]; + var outUv2s = new Vector2[totalVerts]; + var outIndices = new int[totalIndices]; + + int vOff = 0; + int iOff = 0; + for (int c = 0; c < chunks.Count; c++) + { + var (arr, relXf, linCol, band, rough, vCount, idxCount) = chunks[c]; + Vector3[] srcV = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + bool flipWinding = relXf.Basis.Determinant() < 0f; + Basis normBasis = relXf.Basis.Inverse().Transposed(); + + for (int v = 0; v < vCount; v++) + { + outVerts[vOff + v] = relXf * srcV[v]; + } + + if (arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array) + { + Vector3[] srcN = arr[(int)Mesh.ArrayType.Normal].AsVector3Array(); + for (int v = 0; v < vCount; v++) + { + Vector3 n = normBasis * srcN[v]; + outNorms[vOff + v] = n.LengthSquared() > 1e-10f ? n.Normalized() : Vector3.Up; + } + } + else + { + for (int v = 0; v < vCount; v++) outNorms[vOff + v] = Vector3.Up; + } + + if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray) + { + Array.Copy(arr[(int)Mesh.ArrayType.Color].AsColorArray(), 0, outColors, vOff, vCount); + } + else + { + // Gear or unbaked submesh: neutral cavity AO, crisp edge highlight, steady rest height above mud line + var defaultCol = new Color(0.86f, 0.36f, 0.50f, 0.65f); + for (int v = 0; v < vCount; v++) outColors[vOff + v] = defaultCol; + } + + var uv0 = new Vector2(linCol.X, linCol.Y); + var uv1 = new Vector2(linCol.Z, band * 2.0f + rough); + for (int v = 0; v < vCount; v++) + { + outUvs[vOff + v] = uv0; + outUv2s[vOff + v] = uv1; + } + + bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array; + int[]? srcIdx = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null; + if (!flipWinding) + { + if (srcIdx is not null) + { + for (int k = 0; k < idxCount; k++) outIndices[iOff + k] = srcIdx[k] + vOff; + } + else + { + for (int k = 0; k < idxCount; k++) outIndices[iOff + k] = k + vOff; + } + } + else + { + for (int k = 0; k + 2 < idxCount; k += 3) + { + int a = srcIdx is not null ? srcIdx[k] : k; + int bIdx = srcIdx is not null ? srcIdx[k + 1] : k + 1; + int cIdx = srcIdx is not null ? srcIdx[k + 2] : k + 2; + outIndices[iOff + k] = a + vOff; + outIndices[iOff + k + 1] = cIdx + vOff; + outIndices[iOff + k + 2] = bIdx + vOff; + } + } + + vOff += vCount; + iOff += idxCount; + } + + var surfArrays = new Godot.Collections.Array(); + surfArrays.Resize((int)Mesh.ArrayType.Max); + surfArrays[(int)Mesh.ArrayType.Vertex] = outVerts; + surfArrays[(int)Mesh.ArrayType.Normal] = outNorms; + surfArrays[(int)Mesh.ArrayType.Color] = outColors; + surfArrays[(int)Mesh.ArrayType.TexUV] = outUvs; + surfArrays[(int)Mesh.ArrayType.TexUV2] = outUv2s; + surfArrays[(int)Mesh.ArrayType.Index] = outIndices; + + var outMesh = new ArrayMesh(); + outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, surfArrays); + return outMesh; + } + + private static void ClassifyMaterialForMechPaint( + Material? mat, + Color? gearPaintTint, + Color? gearAccentTint, + out Vector3 linearColor, + out int band, + out float roughness) + { + if (mat is not StandardMaterial3D sm) + { + linearColor = new Vector3(0.08f, 0.09f, 0.06f); + band = 3; + roughness = 0.58f; + return; + } + + string mName = (sm.ResourceName ?? string.Empty).ToLowerInvariant(); + roughness = Math.Clamp(sm.Roughness, 0.08f, 0.90f); + + if (mName.Contains("mfg_primary")) + { + Color b = sm.AlbedoColor.SrgbToLinear(); + linearColor = new Vector3(b.R, b.G, b.B); + band = 3; + roughness = 0.50f; + return; + } + + if (mName.Contains("mfg_accent")) + { + Color b = sm.AlbedoColor.SrgbToLinear(); + linearColor = new Vector3(b.R, b.G, b.B); + band = 4; + roughness = 0.38f; + return; + } + + if (mName.Contains("mfg_glow")) + { + Color eCol = (sm.EmissionEnabled ? sm.Emission : sm.AlbedoColor).SrgbToLinear(); + linearColor = new Vector3(eCol.R, eCol.G, eCol.B); + band = 5; + roughness = 0.22f; + return; + } + + if (mName.Contains("lamp") || mName.Contains("glow") || mName.Contains("cyan") || + mName.Contains("amber") || mName.Contains("optic_red")) + { + Color eCol = (sm.EmissionEnabled ? sm.Emission : sm.AlbedoColor).SrgbToLinear(); + linearColor = new Vector3(eCol.R, eCol.G, eCol.B); + band = 5; + roughness = 0.22f; + return; + } + + if (mName.Contains("olive") || mName.Contains("khaki") || mName.Contains("armour") || mName.Contains("armor")) + { + if (gearPaintTint.HasValue) + { + Color c = gearPaintTint.Value.SrgbToLinear(); + linearColor = new Vector3(c.R, c.G, c.B); + band = 6; + roughness = 0.56f; + return; + } + Color b = sm.AlbedoColor.SrgbToLinear(); + linearColor = new Vector3(b.R, b.G, b.B); + band = 3; + roughness = 0.58f; + return; + } + + if (mName.Contains("ivory") && gearPaintTint.HasValue) + { + Color c = gearPaintTint.Value.SrgbToLinear(); + linearColor = new Vector3(c.R, c.G, c.B); + band = 6; + roughness = 0.42f; + return; + } + + if (mName.Contains("signal") || mName.Contains("orange") || mName.Contains("hazard")) + { + if (gearAccentTint.HasValue) + { + Color c = gearAccentTint.Value.SrgbToLinear(); + linearColor = new Vector3(c.R, c.G, c.B); + band = 7; + roughness = 0.42f; + return; + } + Color b = sm.AlbedoColor.SrgbToLinear(); + linearColor = new Vector3(b.R, b.G, b.B); + band = 4; + roughness = 0.44f; + return; + } + + if (gearAccentTint.HasValue && (mName.Contains("copper") || mName.Contains("gold"))) + { + Color c = gearAccentTint.Value.SrgbToLinear(); + linearColor = new Vector3(c.R, c.G, c.B); + band = 7; + roughness = 0.36f; + return; + } + + if (mName.Contains("glass") || mName.Contains("visor") || mName.Contains("canopy") || mName.Contains("lens")) + { + Color b = sm.AlbedoColor.SrgbToLinear(); + linearColor = new Vector3(b.R, b.G, b.B); + band = 8; + roughness = Math.Clamp(sm.Roughness, 0.08f, 0.16f); + return; + } + + Color lin = sm.AlbedoColor.SrgbToLinear(); + linearColor = new Vector3(lin.R, lin.G, lin.B); + band = sm.Metallic >= 0.70f ? 2 : (sm.Metallic >= 0.35f ? 1 : 0); + } + + private static void PruneEmptyNonProtectedNodes(Node cur, Node sceneRoot, HashSet protectedNodes) + { + for (int i = cur.GetChildCount() - 1; i >= 0; i--) + { + Node ch = cur.GetChild(i); + PruneEmptyNonProtectedNodes(ch, sceneRoot, protectedNodes); + if (!ReferenceEquals(ch, sceneRoot) && + !protectedNodes.Contains(ch) && + ch is not MeshInstance3D && + ch.GetChildCount() == 0) + { + cur.RemoveChild(ch); + ch.QueueFree(); + } + } + } + + private readonly record struct StandardMatKey( + int PaintTag, + int R, + int G, + int B, + int A, + int Metallic, + int Roughness, + bool EmissionEnabled, + int EmR, + int EmG, + int EmB, + int EmEnergy, + int Transparency, + int CullMode); + + private static bool TryGetMaterialValueKey( + Material mat, + bool coarse, + out StandardMatKey key) + { + if (mat is StandardMaterial3D sm && + sm.AlbedoTexture is null && + sm.NormalTexture is null && + sm.RoughnessTexture is null && + sm.MetallicTexture is null && + sm.EmissionTexture is null) + { + string mName = (sm.ResourceName ?? string.Empty).ToLowerInvariant(); + int paintTag = (mName.Contains("olive") || mName.Contains("khaki")) ? 1 + : (mName.Contains("signal") || mName.Contains("orange")) ? 2 + : 0; + float colorScale = coarse ? 2f : 32f; + float pbrScale = coarse ? 0f : 4f; + key = new StandardMatKey( + paintTag, + (int)MathF.Round(sm.AlbedoColor.R * colorScale), + (int)MathF.Round(sm.AlbedoColor.G * colorScale), + (int)MathF.Round(sm.AlbedoColor.B * colorScale), + (int)MathF.Round(sm.AlbedoColor.A * 10f), + (int)MathF.Round(sm.Metallic * pbrScale), + (int)MathF.Round(sm.Roughness * pbrScale), + sm.EmissionEnabled, + (int)MathF.Round(sm.Emission.R * colorScale), + (int)MathF.Round(sm.Emission.G * colorScale), + (int)MathF.Round(sm.Emission.B * colorScale), + (int)MathF.Round(sm.EmissionEnergyMultiplier * pbrScale), + (int)sm.Transparency, + (int)sm.CullMode); + return true; + } + key = default; + return false; + } + + private sealed class MaterialSurfaceBucket + { + public required Material? Material; + public readonly List<(Mesh Mesh, int SurfaceIdx, Transform3D RelXf)> Sources = new(); + } + + private static ArrayMesh? BuildMergedArrayMesh( + List<(MeshInstance3D Mi, Transform3D RelXf)> items, + bool coarseMaterials = false) + { + if (items.Count == 0) + { + return null; + } + + var buckets = new List(); + var bucketByMatId = new Dictionary(); + var bucketByMatVal = new Dictionary(); + MaterialSurfaceBucket? nullMatBucket = null; + + for (int i = 0; i < items.Count; i++) + { + var (mi, relXf) = items[i]; + if (mi.Mesh is not { } mesh) + { + continue; + } + int surfCount = mesh.GetSurfaceCount(); + var am = mesh as ArrayMesh; + for (int s = 0; s < surfCount; s++) + { + if (am is not null && am.SurfaceGetPrimitiveType(s) != Mesh.PrimitiveType.Triangles) + { + continue; + } + Material? mat = mi.MaterialOverride ?? mi.GetActiveMaterial(s); + MaterialSurfaceBucket bucket; + if (mat is null) + { + nullMatBucket ??= new MaterialSurfaceBucket { Material = null }; + if (!buckets.Contains(nullMatBucket)) + { + buckets.Add(nullMatBucket); + } + bucket = nullMatBucket; + } + else if (TryGetMaterialValueKey(mat, coarseMaterials, out var matKey)) + { + if (!bucketByMatVal.TryGetValue(matKey, out bucket!)) + { + bucket = new MaterialSurfaceBucket { Material = mat }; + bucketByMatVal[matKey] = bucket; + buckets.Add(bucket); + } + } + else + { + ulong id = mat.GetInstanceId(); + if (!bucketByMatId.TryGetValue(id, out bucket!)) + { + bucket = new MaterialSurfaceBucket { Material = mat }; + bucketByMatId[id] = bucket; + buckets.Add(bucket); + } + } + bucket.Sources.Add((mesh, s, relXf)); + } + } + + if (buckets.Count == 0) + { + return null; + } + + var outMesh = new ArrayMesh(); + for (int b = 0; b < buckets.Count; b++) + { + var bucket = buckets[b]; + bool anyNormal = false; + bool anyTangent = false; + bool anyUv = false; + bool anyUv2 = false; + bool anyColor = false; + int totalVerts = 0; + int totalIndices = 0; + + var cachedArrays = new List<(Godot.Collections.Array Arrays, Transform3D RelXf, int VertCount, int IndexCount)>(bucket.Sources.Count); + for (int s = 0; s < bucket.Sources.Count; s++) + { + var (mesh, surfIdx, relXf) = bucket.Sources[s]; + var arr = mesh.SurfaceGetArrays(surfIdx); + if (arr.Count <= (int)Mesh.ArrayType.Vertex || + arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + if (verts.Length == 0) + { + continue; + } + + if (arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array) anyNormal = true; + if (arr.Count > (int)Mesh.ArrayType.Tangent && arr[(int)Mesh.ArrayType.Tangent].VariantType == Variant.Type.PackedFloat32Array) anyTangent = true; + if (arr.Count > (int)Mesh.ArrayType.TexUV && arr[(int)Mesh.ArrayType.TexUV].VariantType == Variant.Type.PackedVector2Array) anyUv = true; + if (arr.Count > (int)Mesh.ArrayType.TexUV2 && arr[(int)Mesh.ArrayType.TexUV2].VariantType == Variant.Type.PackedVector2Array) anyUv2 = true; + if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray) anyColor = true; + + int idxCount = verts.Length; + if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array) + { + idxCount = arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length; + } + + totalVerts += verts.Length; + totalIndices += idxCount; + cachedArrays.Add((arr, relXf, verts.Length, idxCount)); + } + + if (totalVerts == 0 || totalIndices == 0) + { + continue; + } + + var outVerts = new Vector3[totalVerts]; + Vector3[]? outNormals = anyNormal ? new Vector3[totalVerts] : null; + float[]? outTangents = anyTangent ? new float[totalVerts * 4] : null; + Vector2[]? outUvs = anyUv ? new Vector2[totalVerts] : null; + Vector2[]? outUv2s = anyUv2 ? new Vector2[totalVerts] : null; + Color[]? outColors = anyColor ? new Color[totalVerts] : null; + var outIndices = new int[totalIndices]; + + int vOffset = 0; + int iOffset = 0; + for (int c = 0; c < cachedArrays.Count; c++) + { + var (arr, relXf, vCount, idxCount) = cachedArrays[c]; + Vector3[] srcVerts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + bool flipWinding = relXf.Basis.Determinant() < 0f; + Basis normBasis = relXf.Basis.Inverse().Transposed(); + + for (int v = 0; v < vCount; v++) + { + outVerts[vOffset + v] = relXf * srcVerts[v]; + } + + if (outNormals is not null) + { + if (arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array) + { + Vector3[] srcN = arr[(int)Mesh.ArrayType.Normal].AsVector3Array(); + for (int v = 0; v < vCount; v++) + { + Vector3 n = normBasis * srcN[v]; + outNormals[vOffset + v] = n.LengthSquared() > 1e-10f ? n.Normalized() : Vector3.Up; + } + } + else + { + for (int v = 0; v < vCount; v++) outNormals[vOffset + v] = Vector3.Up; + } + } + + if (outTangents is not null) + { + if (arr.Count > (int)Mesh.ArrayType.Tangent && arr[(int)Mesh.ArrayType.Tangent].VariantType == Variant.Type.PackedFloat32Array) + { + float[] srcT = arr[(int)Mesh.ArrayType.Tangent].AsFloat32Array(); + for (int v = 0; v < vCount; v++) + { + int sBase = v * 4; + int dBase = (vOffset + v) * 4; + Vector3 t = relXf.Basis * new Vector3(srcT[sBase], srcT[sBase + 1], srcT[sBase + 2]); + t = t.LengthSquared() > 1e-10f ? t.Normalized() : Vector3.Right; + outTangents[dBase] = t.X; + outTangents[dBase + 1] = t.Y; + outTangents[dBase + 2] = t.Z; + outTangents[dBase + 3] = flipWinding ? -srcT[sBase + 3] : srcT[sBase + 3]; + } + } + else + { + for (int v = 0; v < vCount; v++) + { + int dBase = (vOffset + v) * 4; + outTangents[dBase] = 1f; + outTangents[dBase + 3] = 1f; + } + } + } + + if (outUvs is not null) + { + if (arr.Count > (int)Mesh.ArrayType.TexUV && arr[(int)Mesh.ArrayType.TexUV].VariantType == Variant.Type.PackedVector2Array) + { + Array.Copy(arr[(int)Mesh.ArrayType.TexUV].AsVector2Array(), 0, outUvs, vOffset, vCount); + } + } + + if (outUv2s is not null) + { + if (arr.Count > (int)Mesh.ArrayType.TexUV2 && arr[(int)Mesh.ArrayType.TexUV2].VariantType == Variant.Type.PackedVector2Array) + { + Array.Copy(arr[(int)Mesh.ArrayType.TexUV2].AsVector2Array(), 0, outUv2s, vOffset, vCount); + } + } + + if (outColors is not null) + { + if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray) + { + Color[] srcC = arr[(int)Mesh.ArrayType.Color].AsColorArray(); + Array.Copy(srcC, 0, outColors, vOffset, vCount); + } + else + { + for (int v = 0; v < vCount; v++) outColors[vOffset + v] = Colors.White; + } + } + + bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array; + int[]? srcIdx = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null; + if (!flipWinding) + { + if (srcIdx is not null) + { + for (int k = 0; k < idxCount; k++) outIndices[iOffset + k] = srcIdx[k] + vOffset; + } + else + { + for (int k = 0; k < idxCount; k++) outIndices[iOffset + k] = k + vOffset; + } + } + else + { + for (int k = 0; k + 2 < idxCount; k += 3) + { + int a = srcIdx is not null ? srcIdx[k] : k; + int bIdx = srcIdx is not null ? srcIdx[k + 1] : k + 1; + int cIdx = srcIdx is not null ? srcIdx[k + 2] : k + 2; + outIndices[iOffset + k] = a + vOffset; + outIndices[iOffset + k + 1] = cIdx + vOffset; + outIndices[iOffset + k + 2] = bIdx + vOffset; + } + } + + vOffset += vCount; + iOffset += idxCount; + } + + var surfArrays = new Godot.Collections.Array(); + surfArrays.Resize((int)Mesh.ArrayType.Max); + surfArrays[(int)Mesh.ArrayType.Vertex] = outVerts; + if (outNormals is not null) surfArrays[(int)Mesh.ArrayType.Normal] = outNormals; + if (outTangents is not null) surfArrays[(int)Mesh.ArrayType.Tangent] = outTangents; + if (outUvs is not null) surfArrays[(int)Mesh.ArrayType.TexUV] = outUvs; + if (outUv2s is not null) surfArrays[(int)Mesh.ArrayType.TexUV2] = outUv2s; + if (outColors is not null) surfArrays[(int)Mesh.ArrayType.Color] = outColors; + surfArrays[(int)Mesh.ArrayType.Index] = outIndices; + + int newSurf = outMesh.GetSurfaceCount(); + outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, surfArrays); + if (bucket.Material is not null) + { + outMesh.SurfaceSetMaterial(newSurf, bucket.Material); + } + } + + return outMesh.GetSurfaceCount() > 0 ? outMesh : null; + } + + private static ArrayMesh DecimateMeshGrid(ArrayMesh src, float cellSize, float targetMinY) + { + var outMesh = new ArrayMesh(); + float invCell = 1f / MathF.Max(0.02f, cellSize); + int surfCount = src.GetSurfaceCount(); + + for (int s = 0; s < surfCount; s++) + { + var arr = src.SurfaceGetArrays(s); + if (arr.Count <= (int)Mesh.ArrayType.Vertex || + arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + + Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + if (verts.Length == 0) + { + continue; + } + + bool hasNorm = arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array; + Vector3[]? norms = hasNorm ? arr[(int)Mesh.ArrayType.Normal].AsVector3Array() : null; + + bool hasColor = arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray; + Color[]? colors = hasColor ? arr[(int)Mesh.ArrayType.Color].AsColorArray() : null; + + bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array; + int[]? indices = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null; + int triVertCount = indices is not null ? indices.Length : verts.Length; + + var cellToNewIdx = new Dictionary<(int, int, int), int>(verts.Length / 2 + 16); + var vertToCellIdx = new int[verts.Length]; + var accumPos = new List(verts.Length / 2 + 16); + var accumNorm = norms is not null ? new List(verts.Length / 2 + 16) : null; + var accumColor = colors is not null ? new List(verts.Length / 2 + 16) : null; + var counts = new List(verts.Length / 2 + 16); + var cellMinY = new List(verts.Length / 2 + 16); + + for (int v = 0; v < verts.Length; v++) + { + Vector3 p = verts[v]; + var key = ( + (int)MathF.Floor(p.X * invCell), + (int)MathF.Floor(p.Y * invCell), + (int)MathF.Floor(p.Z * invCell)); + + if (!cellToNewIdx.TryGetValue(key, out int ci)) + { + ci = accumPos.Count; + cellToNewIdx[key] = ci; + accumPos.Add(p); + if (accumNorm is not null) accumNorm.Add(norms![v]); + if (accumColor is not null) accumColor.Add(colors![v]); + counts.Add(1); + cellMinY.Add(p.Y); + } + else + { + accumPos[ci] += p; + if (accumNorm is not null) accumNorm[ci] += norms![v]; + if (accumColor is not null) accumColor[ci] += colors![v]; + counts[ci]++; + if (p.Y < cellMinY[ci]) cellMinY[ci] = p.Y; + } + vertToCellIdx[v] = ci; + } + + var outIndices = new List(triVertCount / 2 + 12); + for (int k = 0; k + 2 < triVertCount; k += 3) + { + int i0 = indices is not null ? indices[k] : k; + int i1 = indices is not null ? indices[k + 1] : k + 1; + int i2 = indices is not null ? indices[k + 2] : k + 2; + int c0 = vertToCellIdx[i0]; + int c1 = vertToCellIdx[i1]; + int c2 = vertToCellIdx[i2]; + if (c0 != c1 && c1 != c2 && c0 != c2) + { + outIndices.Add(c0); + outIndices.Add(c1); + outIndices.Add(c2); + } + } + + if (outIndices.Count == 0) + { + // Keep original tiny surface intact if grid collapsed all triangles + int fallbackSurf = outMesh.GetSurfaceCount(); + outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arr); + Material? fMat = src.SurfaceGetMaterial(s); + if (fMat is not null) outMesh.SurfaceSetMaterial(fallbackSurf, fMat); + continue; + } + + var outVerts = new Vector3[accumPos.Count]; + Vector3[]? outNorms = accumNorm is not null ? new Vector3[accumPos.Count] : null; + Color[]? outColors = accumColor is not null ? new Color[accumPos.Count] : null; + for (int i = 0; i < accumPos.Count; i++) + { + Vector3 avg = accumPos[i] / counts[i]; + // Preserve exact ground-contacting vertex minY so far LOD ChassisDrops never float or sink + float y = cellMinY[i] <= targetMinY + 0.08f ? cellMinY[i] : avg.Y; + if (y < targetMinY) y = targetMinY; + outVerts[i] = new Vector3(avg.X, y, avg.Z); + if (outNorms is not null) + { + Vector3 n = accumNorm![i]; + outNorms[i] = n.LengthSquared() > 1e-8f ? n.Normalized() : Vector3.Up; + } + if (outColors is not null) + { + outColors[i] = accumColor![i] / counts[i]; + } + } + + var newArr = new Godot.Collections.Array(); + newArr.Resize((int)Mesh.ArrayType.Max); + newArr[(int)Mesh.ArrayType.Vertex] = outVerts; + if (outNorms is not null) newArr[(int)Mesh.ArrayType.Normal] = outNorms; + if (outColors is not null) newArr[(int)Mesh.ArrayType.Color] = outColors; + newArr[(int)Mesh.ArrayType.Index] = outIndices.ToArray(); + + int newSurf = outMesh.GetSurfaceCount(); + outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, newArr); + Material? mat = src.SurfaceGetMaterial(s); + if (mat is not null) + { + outMesh.SurfaceSetMaterial(newSurf, mat); + } + } + + return outMesh.GetSurfaceCount() > 0 ? outMesh : src; + } + + private static void MarkAncestorsProtected(int idx, Dictionary parentByIndex, HashSet protectedSet) + { + int cur = idx; + while (true) + { + if (!protectedSet.Add(cur)) + { + // Still continue up in case a parent wasn't marked yet, or break if parent already marked + } + if (!parentByIndex.TryGetValue(cur, out int parent)) + { + break; + } + cur = parent; + } + } + + private static Node? ResolveSceneNode(Node3D sceneRoot, NodePath scenePath, string originalName) + { + if (!scenePath.IsEmpty) + { + Node? direct = sceneRoot.GetNodeOrNull(scenePath); + if (direct is not null) + { + return direct; + } + + string raw = scenePath.ToString(); + if (raw == "." || raw == sceneRoot.Name) + { + return sceneRoot; + } + + int slash = raw.IndexOf('/'); + if (slash >= 0) + { + string sub = raw[(slash + 1)..]; + Node? trimmed = sceneRoot.GetNodeOrNull(sub); + if (trimmed is not null) + { + return trimmed; + } + } + } + + // Fallback: sanitized name match + string sanitized = originalName.Replace('.', '_').Replace(':', '_').Replace('@', '_').Replace('/', '_'); + return FindNodeRecursive(sceneRoot, originalName, sanitized); + } + + private static Node? FindNodeRecursive(Node cur, string exactName, string sanitized) + { + string nm = cur.Name; + if (string.Equals(nm, exactName, StringComparison.Ordinal) || + string.Equals(nm, sanitized, StringComparison.Ordinal)) + { + return cur; + } + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + Node? found = FindNodeRecursive(cur.GetChild(i), exactName, sanitized); + if (found is not null) + { + return found; + } + } + return null; + } + + private static NodePath BuildRelativeNodePath(Node root, Node target) + { + if (ReferenceEquals(root, target)) + { + return new NodePath("."); + } + + var segments = new List(); + Node? cur = target; + while (cur is not null && !ReferenceEquals(cur, root)) + { + segments.Add(cur.Name); + cur = cur.GetParent(); + } + if (!ReferenceEquals(cur, root)) + { + return new NodePath("."); + } + segments.Reverse(); + return new NodePath(string.Join("/", segments)); + } + + private static void CollectModelTransforms(Node cur, Transform3D parentTransform, Dictionary map) + { + Transform3D world = cur is Node3D n3d ? parentTransform * n3d.Transform : parentTransform; + map[cur] = world; + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + CollectModelTransforms(cur.GetChild(i), world, map); + } + } + + private static void ComputeSceneMeshBoundsY(Node3D root, out float minY, out float maxY) + { + ComputeSceneMeshBounds(root, out Vector3 mn, out Vector3 mx); + minY = mn.Y; + maxY = mx.Y; + } + + private static void ComputeSceneMeshBounds(Node3D root, out Vector3 boundsMin, out Vector3 boundsMax) + { + Vector3 mn = new(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + Vector3 mx = new(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity); + AccumulateBounds(root, Transform3D.Identity, ref mn, ref mx); + + if (!float.IsFinite(mn.X)) + { + mn = Vector3.Zero; + mx = Vector3.One; + } + boundsMin = mn; + boundsMax = mx; + } + + private static void AccumulateBounds(Node cur, Transform3D parentXf, ref Vector3 mn, ref Vector3 mx) + { + Transform3D xf = cur is Node3D n3d ? parentXf * n3d.Transform : parentXf; + if (cur is MeshInstance3D mi && mi.Mesh is not null) + { + bool usedVertices = false; + int surfCount = mi.Mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arrays = mi.Mesh.SurfaceGetArrays(s); + if (arrays.Count > (int)Mesh.ArrayType.Vertex) + { + Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + if (verts.Length > 0) + { + usedVertices = true; + for (int v = 0; v < verts.Length; v++) + { + Vector3 w = xf * verts[v]; + mn = new Vector3(MathF.Min(mn.X, w.X), MathF.Min(mn.Y, w.Y), MathF.Min(mn.Z, w.Z)); + mx = new Vector3(MathF.Max(mx.X, w.X), MathF.Max(mx.Y, w.Y), MathF.Max(mx.Z, w.Z)); + } + } + } + } + + if (!usedVertices) + { + Aabb aabb = mi.Mesh.GetAabb(); + Vector3 p = aabb.Position; + Vector3 sz = aabb.Size; + for (int ix = 0; ix < 2; ix++) + { + for (int iy = 0; iy < 2; iy++) + { + for (int iz = 0; iz < 2; iz++) + { + Vector3 corner = new(p.X + ix * sz.X, p.Y + iy * sz.Y, p.Z + iz * sz.Z); + Vector3 w = xf * corner; + mn = new Vector3(MathF.Min(mn.X, w.X), MathF.Min(mn.Y, w.Y), MathF.Min(mn.Z, w.Z)); + mx = new Vector3(MathF.Max(mx.X, w.X), MathF.Max(mx.Y, w.Y), MathF.Max(mx.Z, w.Z)); + } + } + } + } + } + + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + AccumulateBounds(cur.GetChild(i), xf, ref mn, ref mx); + } + } + + private static byte[] ReadGlbJsonChunk(string glbPath) + { + byte[] data = File.ReadAllBytes(glbPath); + if (data.Length < 20) + { + throw new InvalidDataException($"{glbPath}: GLB smaller than 20-byte header."); + } + + uint magic = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(0, 4)); + uint version = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(4, 4)); + if (magic != 0x46546C67 || version != 2) + { + throw new InvalidDataException($"{glbPath}: invalid GLB header magic=0x{magic:X8} version={version}."); + } + + uint jsonLen = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(12, 4)); + uint jsonType = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(16, 4)); + if (jsonType != 0x4E4F534A) + { + throw new InvalidDataException($"{glbPath}: first GLB chunk is not JSON (0x{jsonType:X8})."); + } + + return data.AsSpan(20, (int)jsonLen).ToArray(); + } + + private static Vector3 ReadVec3(JsonElement obj, string propName, Vector3 fallback) + { + if (!obj.TryGetProperty(propName, out JsonElement arr) || arr.ValueKind != JsonValueKind.Array || arr.GetArrayLength() < 3) + { + return fallback; + } + return new Vector3(arr[0].GetSingle(), arr[1].GetSingle(), arr[2].GetSingle()); + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + foreach (var v in _vehicles.Values) + { + if (GodotObject.IsInstanceValid(v.SceneTemplate)) + { + v.SceneTemplate.QueueFree(); + } + } + foreach (var g in _gear.Values) + { + if (GodotObject.IsInstanceValid(g.SceneTemplate)) + { + g.SceneTemplate.QueueFree(); + } + } + foreach (var wp in _weaponParts.Values) + { + if (GodotObject.IsInstanceValid(wp.SceneTemplate)) + { + wp.SceneTemplate.QueueFree(); + } + } + _vehicles.Clear(); + _gear.Clear(); + _weaponParts.Clear(); + if (_dropPod is not null && GodotObject.IsInstanceValid(_dropPod.SceneTemplate)) + { + _dropPod.SceneTemplate.QueueFree(); + } + _dropPod = null; + } +} diff --git a/client/VehicleRigAnimator.cs b/client/VehicleRigAnimator.cs new file mode 100644 index 0000000..c0359ec --- /dev/null +++ b/client/VehicleRigAnimator.cs @@ -0,0 +1,1090 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; +using RustToDust.Ymir; + +namespace RustToDust.Client; + +public readonly record struct VehicleRigDriveInput( + Vector3 Velocity, + float Yaw, + float AimYawWorld, + float AimPitchDeg, + float SteerCmd, + float ThrottleCmd, + float VerticalThrottleCmd, + float EngineThermalPerf, + float DeltaTime, + bool IsGrounded = true); + +/// +/// Drives real-time secondary mechanism animations on +/// from live physics state with strict NaN/Inf guards: +/// - Wheeled: wheel spin (v / r), front-axle steering, subtle chassis suspension roll/pitch. +/// - Turrets/Torsos/Arms: yaw tracking (joint.turret_yaw, joint.torso_yaw) & arm pitch. +/// - VTOL: rotor spin scaled by EngineThermalPerf + lift demand, nacelle tilt with acceleration. +/// - Walkers/Mechs: pure FK posing from Hybrid B with per-segment +/// rest-basis alignment (Q_offset), Manticore tail aiming, and Breaker's real GRF-driven +/// oleo strut + 2-link scissor torque links + telescoping recess rams. +/// +public static class VehicleRigAnimator +{ + public sealed class StrutState + { + public float Compression; + public float Velocity; + } + + public sealed class ScissorBinding + { + public required Node3D UpperNode; + public required Node3D LowerNode; + public required Node3D ShinNode; + public required Node3D OleoNode; + public required Node3D OleoForkNode; + public required Transform3D RestLocalUp; + public required Transform3D RestLocalLow; + public required Vector3 AInShin; + public required Vector3 BInOleoFork; + public required Vector3 OutInShin; + public required float Arm; + public required Vector3 DirUp0InShin; + public required Vector3 DirLow0InOleoFork; + } + + public sealed class RamBinding + { + public required Node3D RamNode; + public required Node3D LugNode; + public required Node3D OleoNode; + public required Node3D OleoForkNode; + public required Node3D FootNode; + public required Transform3D RestLocalRam; + public required Vector3 APosInLug; + public required Vector3 BPosInFoot; + public required Vector3 WantDir0InLug; + } + + public sealed class BreakerMechRig + { + public bool Initialized; + public readonly Dictionary Struts = new(StringComparer.Ordinal); + public readonly Dictionary OleoNodes = new(StringComparer.Ordinal); + public readonly List Scissors = new(); + public readonly List Rams = new(); + } + + public sealed class SegmentBinding + { + public required Node3D Node; + public required Transform3D RestLocal; + public required Node3D[] IntermediateBefore; + public required Basis QOffset; + } + + public sealed class WalkerLegBinding + { + public SegmentBinding? Coxa; + public required SegmentBinding Thigh; + public required SegmentBinding Shin; + public SegmentBinding? Cannon; + public required SegmentBinding Foot; + } + + public sealed class WalkerVisualRig + { + public required WalkerGeometrySpec Geom; + public required WalkerLegBinding[] Legs; + } + + public sealed class RigState + { + public float WheelSpinRad; + public float SteerRad; + public float TurretYawRad; + public float ArmPitchRad; + public float RotorSpinRad; + public float NacelleTiltRad; + public float PrevForwardSpeed; + public float ChassisPitchRad; + public float ChassisRollRad; + public float ElapsedSeconds; + public BreakerMechRig? BreakerRig; + public WalkerVisualRig? WalkerRig; + } + + public static void Update( + VehicleVisualInstance visual, + ContenderState c, + Vector3 velocity, + Basis worldBasis, + float dt, + bool snap = false) + { + var input = BuildContenderInput(c, velocity, dt); + Update(visual, in input, worldBasis, snap); + } + + public static void Update( + VehicleVisualInstance visual, + ContenderState c, + Vector3 velocity, + Basis worldBasis, + float dt, + in WalkerVisualSnapshot walkerSnap, + bool snap = false) + { + var input = BuildContenderInput(c, velocity, dt); + Update(visual, in input, worldBasis, in walkerSnap, snap); + } + + private static VehicleRigDriveInput BuildContenderInput(ContenderState c, Vector3 velocity, float dt) + { + float aimYawWorld = c.Yaw; + float dx = c.AimX - c.X; + float dz = c.AimZ - c.Z; + if (float.IsFinite(dx) && float.IsFinite(dz) && (dx * dx + dz * dz) > 0.01f) + { + aimYawWorld = MathF.Atan2(dx, dz); + } + + float aimPitchDeg = 0f; + if (float.IsFinite(c.AimY)) + { + float aimOriginY = MatchRules.GetObserverEyeY(c.Y, c.Grid.Spec.HalfHeight); + float horiz = MathF.Sqrt(dx * dx + dz * dz); + if (horiz > 0.1f) + { + aimPitchDeg = Mathf.RadToDeg(MathF.Atan2(c.AimY - aimOriginY, horiz)); + } + } + + return new VehicleRigDriveInput( + Velocity: velocity, + Yaw: c.Yaw, + AimYawWorld: aimYawWorld, + AimPitchDeg: aimPitchDeg, + SteerCmd: c.SteerCmd, + ThrottleCmd: c.ThrottleCmd, + VerticalThrottleCmd: c.VerticalThrottleCmd, + EngineThermalPerf: c.Grid.ComputeEngineThermalPerformance(), + DeltaTime: dt, + IsGrounded: !c.Grid.Spec.IsVtol); + } + + public static void Update( + VehicleVisualInstance visual, + in VehicleRigDriveInput input, + Basis worldBasis, + bool snap = false) + { + UpdateCore(visual, in input, worldBasis, hasWalkerSnap: false, in DefaultSnapshot, snap); + } + + public static void Update( + VehicleVisualInstance visual, + in VehicleRigDriveInput input, + Basis worldBasis, + in WalkerVisualSnapshot walkerSnap, + bool snap = false) + { + UpdateCore(visual, in input, worldBasis, hasWalkerSnap: true, in walkerSnap, snap); + } + + private static readonly WalkerVisualSnapshot DefaultSnapshot = default; + + private static void UpdateCore( + VehicleVisualInstance visual, + in VehicleRigDriveInput input, + Basis worldBasis, + bool hasWalkerSnap, + in WalkerVisualSnapshot walkerSnap, + bool snap) + { + float dt = Sanitize(input.DeltaTime, 0f, 0f, 0.1f); + if (!snap && dt <= 0f) + { + return; + } + Vector3 vel = SanitizeVec(input.Velocity); + float yaw = Sanitize(input.Yaw, 0f, -MathF.Tau * 4f, MathF.Tau * 4f); + float aimYawWorld = Sanitize(input.AimYawWorld, yaw, -MathF.Tau * 4f, MathF.Tau * 4f); + float aimPitchDeg = Sanitize(input.AimPitchDeg, 0f, -85f, 85f); + float steerCmd = Sanitize(input.SteerCmd, 0f, -1f, 1f); + float throttleCmd = Sanitize(input.ThrottleCmd, 0f, -1f, 1f); + float vertCmd = Sanitize(input.VerticalThrottleCmd, 0f, -1f, 1f); + float enginePerf = Sanitize(input.EngineThermalPerf, 1f, 0f, 1f); + + RigState st = visual.RigState; + st.ElapsedSeconds += dt; + + Vector3 fwd = worldBasis.Z; + fwd.Y = 0f; + fwd = fwd.LengthSquared() > 1e-5f ? fwd.Normalized() : new Vector3(MathF.Sin(yaw), 0f, MathF.Cos(yaw)); + Vector3 right = new(-fwd.Z, 0f, fwd.X); + + float forwardSpeed = vel.Dot(fwd); + float lateralSpeed = vel.Dot(right); + + float relYaw = MatchRules.NormalizeAngle(aimYawWorld - yaw); + float aimPitchRad = Mathf.DegToRad(aimPitchDeg); + + float blendFast = dt > 0f ? 1f - MathF.Exp(-dt * 10f) : 1f; + float blendMed = dt > 0f ? 1f - MathF.Exp(-dt * 7f) : 1f; + + // 1. Turrets & torsos + UpdateTurretAndTorso(visual, st, relYaw, aimPitchRad, blendFast); + + // 2. Mobility-specific drives + var mobility = visual.Package.Mobility; + switch (mobility) + { + case MobilityKind.Wheeled: + UpdateWheeled(visual, st, forwardSpeed, lateralSpeed, steerCmd, dt, blendFast); + break; + + case MobilityKind.Vtol: + UpdateVtol(visual, st, forwardSpeed, throttleCmd, vertCmd, enginePerf, dt, blendMed); + break; + + case MobilityKind.Walker: + if (hasWalkerSnap) + { + UpdateWalkerFromSnapshot(visual, st, in walkerSnap, relYaw, aimPitchRad, dt, blendMed); + } + else if (string.Equals(visual.ModelId, "manticore", StringComparison.OrdinalIgnoreCase)) + { + AnimateManticoreTail(visual, st, relYaw, aimPitchRad, blendMed); + } + break; + + case MobilityKind.Tracked: + UpdateTrackedSuspension(visual, st, forwardSpeed, lateralSpeed, dt, blendMed); + break; + } + + st.PrevForwardSpeed = forwardSpeed; + } + + private static void UpdateTurretAndTorso( + VehicleVisualInstance visual, + RigState st, + float relYaw, + float aimPitchRad, + float blend) + { + if (visual.Joints.TryGetValue("joint.turret_yaw", out var turretJoint) || + visual.Joints.TryGetValue("joint.torso_yaw", out turretJoint)) + { + bool fullSpin = turretJoint.MinRad <= -MathF.PI * 0.99f && turretJoint.MaxRad >= MathF.PI * 0.99f; + float targetYaw = fullSpin + ? relYaw + : Math.Clamp(relYaw, turretJoint.MinRad, turretJoint.MaxRad); + + if (fullSpin) + { + float diff = MatchRules.NormalizeAngle(targetYaw - st.TurretYawRad); + st.TurretYawRad = MatchRules.NormalizeAngle(st.TurretYawRad + diff * blend); + } + else + { + st.TurretYawRad += (targetYaw - st.TurretYawRad) * blend; + } + + SetJointAngle(turretJoint, st.TurretYawRad); + } + + st.ArmPitchRad += (aimPitchRad - st.ArmPitchRad) * blend; + // Positive elevation (+aimPitchRad) rotates negatively around vehicle +X (raises +Z barrels toward +Y) + if (visual.Joints.TryGetValue("joint.arm_l_pitch", out var armL)) + { + float clampedL = Math.Clamp(-st.ArmPitchRad, armL.MinRad, armL.MaxRad); + SetJointAngle(armL, clampedL); + } + if (visual.Joints.TryGetValue("joint.arm_r_pitch", out var armR)) + { + float clampedR = Math.Clamp(-st.ArmPitchRad, armR.MinRad, armR.MaxRad); + SetJointAngle(armR, clampedR); + } + } + + private static void UpdateWheeled( + VehicleVisualInstance visual, + RigState st, + float forwardSpeed, + float lateralSpeed, + float steerCmd, + float dt, + float blend) + { + float radiusSum = 0f; + int radiusCount = 0; + foreach (var (jid, j) in visual.Joints) + { + if (jid.StartsWith("joint.wheel_", StringComparison.Ordinal)) + { + float y = j.RestLocal.Origin.Y; + if (y <= 0.05f && j.Node.GetParent() is Node3D p3) + { + y = p3.Transform.Origin.Y; + } + if (y > 0.1f) + { + radiusSum += y; + radiusCount++; + } + } + } + float wheelRadius = radiusCount > 0 ? radiusSum / radiusCount : 0.45f; + + st.WheelSpinRad = MathF.IEEERemainder(st.WheelSpinRad + (forwardSpeed / MathF.Max(0.25f, wheelRadius)) * dt, MathF.Tau); + + float targetSteer = -steerCmd * Mathf.DegToRad(28f); + st.SteerRad += (targetSteer - st.SteerRad) * blend; + + foreach (var (jid, j) in visual.Joints) + { + if (jid.StartsWith("joint.wheel_", StringComparison.Ordinal)) + { + SetJointAngle(j, st.WheelSpinRad); + } + else if (jid.StartsWith("joint.steer_", StringComparison.Ordinal)) + { + float clampedSteer = Math.Clamp(st.SteerRad, j.MinRad, j.MaxRad); + SetJointAngle(j, clampedSteer); + } + } + + float accel = dt > 1e-4f ? (forwardSpeed - st.PrevForwardSpeed) / dt : 0f; + float targetPitch = Math.Clamp(-accel * 0.0022f, -0.05f, 0.05f); + float targetRoll = Math.Clamp(lateralSpeed * 0.0045f + steerCmd * MathF.Min(1f, MathF.Abs(forwardSpeed) / 14f) * 0.035f, -0.06f, 0.06f); + st.ChassisPitchRad += (targetPitch - st.ChassisPitchRad) * blend; + st.ChassisRollRad += (targetRoll - st.ChassisRollRad) * blend; + + if (visual.GetNamedNode("Chassis") is { } chassis && visual.TryGetRestLocal("Chassis", out var restChassis)) + { + Basis tilt = new Basis(Vector3.Right, st.ChassisPitchRad) * new Basis(Vector3.Back, st.ChassisRollRad); + chassis.Transform = new Transform3D(tilt * restChassis.Basis, restChassis.Origin); + } + } + + private static void UpdateTrackedSuspension( + VehicleVisualInstance visual, + RigState st, + float forwardSpeed, + float lateralSpeed, + float dt, + float blend) + { + float accel = dt > 1e-4f ? (forwardSpeed - st.PrevForwardSpeed) / dt : 0f; + float targetPitch = Math.Clamp(-accel * 0.0018f, -0.045f, 0.045f); + float targetRoll = Math.Clamp(lateralSpeed * 0.003f, -0.045f, 0.045f); + st.ChassisPitchRad += (targetPitch - st.ChassisPitchRad) * blend; + st.ChassisRollRad += (targetRoll - st.ChassisRollRad) * blend; + + if (visual.GetNamedNode("Chassis") is { } chassis && visual.TryGetRestLocal("Chassis", out var restChassis)) + { + Basis tilt = new Basis(Vector3.Right, st.ChassisPitchRad) * new Basis(Vector3.Back, st.ChassisRollRad); + chassis.Transform = new Transform3D(tilt * restChassis.Basis, restChassis.Origin); + } + } + + private static void UpdateVtol( + VehicleVisualInstance visual, + RigState st, + float forwardSpeed, + float throttleCmd, + float vertCmd, + float enginePerf, + float dt, + float blend) + { + float rotorSpeed = (5.5f + 18.0f * enginePerf) * + (1f + 0.35f * MathF.Max(0f, vertCmd) + 0.16f * MathF.Abs(throttleCmd)); + st.RotorSpinRad = MathF.IEEERemainder(st.RotorSpinRad + rotorSpeed * dt, MathF.Tau); + + float targetTilt = throttleCmd * 0.42f + (forwardSpeed / 42f) * 0.28f; + st.NacelleTiltRad += (targetTilt - st.NacelleTiltRad) * blend; + + foreach (var (jid, j) in visual.Joints) + { + if (jid.StartsWith("joint.rotor_", StringComparison.Ordinal)) + { + float dir = (jid.Contains("_r", StringComparison.Ordinal) && !jid.Contains("_rl", StringComparison.Ordinal)) || + jid.EndsWith("_rl", StringComparison.Ordinal) + ? -1f + : 1f; + SetJointAngle(j, st.RotorSpinRad * dir); + } + else if (jid.StartsWith("joint.nacelle_", StringComparison.Ordinal)) + { + float clampedTilt = Math.Clamp(st.NacelleTiltRad, j.MinRad, j.MaxRad); + SetJointAngle(j, clampedTilt); + } + } + } + + private static void UpdateWalkerFromSnapshot( + VehicleVisualInstance visual, + RigState st, + in WalkerVisualSnapshot snap, + float relYaw, + float aimPitchRad, + float dt, + float blend) + { + var rig = st.WalkerRig ??= InitWalkerRig(visual); + if (rig is null) + { + return; + } + + var geom = rig.Geom; + var bodyRotSys = snap.ComRot.LengthSquared() < 1e-6f + ? System.Numerics.Quaternion.Identity + : System.Numerics.Quaternion.Normalize(snap.ComRot); + var bodyRotInv = System.Numerics.Quaternion.Conjugate(bodyRotSys); + + int count = Math.Min(rig.Legs.Length, snap.LegCount); + for (int i = 0; i < count; i++) + { + var legRig = rig.Legs[i]; + var legSpec = geom.Legs[i]; + var ang = snap.LegAngles[i]; + if (!float.IsFinite(ang.HipPitch) || !float.IsFinite(ang.HipRoll) || + !float.IsFinite(ang.KneeFlex) || !float.IsFinite(ang.HockFlex) || + !float.IsFinite(ang.AnklePitch)) + { + continue; + } + + Vector3 footNormModel = ToGodot(System.Numerics.Vector3.Transform(snap.FootNormal[i], bodyRotInv)); + footNormModel = footNormModel.LengthSquared() > 1e-6f ? footNormModel.Normalized() : Vector3.Up; + + Vector3 r0 = ToGodot(legSpec.LegRight0); + Vector3 f0 = ToGodot(legSpec.LegFwd0); + + Basis curModelBasis = Basis.Identity; + + if (snap.IsArachnidUp) + { + float coxaYaw = ang.HipRoll; + Vector3 legOut = (f0 * MathF.Cos(coxaYaw) + r0 * MathF.Sin(coxaYaw)).Normalized(); + Vector3 legRight = (r0 * MathF.Cos(coxaYaw) - f0 * MathF.Sin(coxaYaw)).Normalized(); + + if (legRig.Coxa is { } coxaSeg) + { + Basis coxaBasis = BasisFromDownAndRight(-legOut, Vector3.Up.Cross(legOut)) * coxaSeg.QOffset; + curModelBasis = ApplySegmentModelBasis(coxaSeg, curModelBasis, coxaBasis); + } + + Vector3 s1Dir = (legOut * MathF.Cos(ang.HipPitch) + Vector3.Up * MathF.Sin(ang.HipPitch)).Normalized(); + float s2Elev = ang.HipPitch - ang.KneeFlex; + Vector3 s2Dir = (legOut * MathF.Cos(s2Elev) + Vector3.Up * MathF.Sin(s2Elev)).Normalized(); + + Basis thighBasis = BasisFromDownAndRight(s1Dir, legRight) * legRig.Thigh.QOffset; + curModelBasis = ApplySegmentModelBasis(legRig.Thigh, curModelBasis, thighBasis); + + Basis shinBasis = BasisFromDownAndRight(s2Dir, legRight) * legRig.Shin.QOffset; + curModelBasis = ApplySegmentModelBasis(legRig.Shin, curModelBasis, shinBasis); + + float lat = Math.Clamp(footNormModel.Dot(legRight), -0.85f, 0.85f); + float planarMag = MathF.Sqrt(MathF.Max(0.01f, 1f - lat * lat)); + Vector3 footUp = (legRight * lat + (Vector3.Up * MathF.Cos(ang.AnklePitch) + legOut * MathF.Sin(ang.AnklePitch)) * planarMag).Normalized(); + Basis footBasis = BasisFromDownAndRight(-footUp, legRight) * legRig.Foot.QOffset; + ApplySegmentModelBasis(legRig.Foot, curModelBasis, footBasis); + } + else + { + float hipRoll = ang.HipRoll; + Vector3 legRight = (r0 * MathF.Cos(hipRoll) + Vector3.Up * MathF.Sin(hipRoll)).Normalized(); + Vector3 downTilted = (-Vector3.Up * MathF.Cos(hipRoll) + r0 * MathF.Sin(hipRoll)).Normalized(); + + Vector3 thighDir = (downTilted * MathF.Cos(ang.HipPitch) + f0 * MathF.Sin(ang.HipPitch)).Normalized(); + float shinAngle = ang.HipPitch - ang.KneeFlex; + Vector3 shinDir = (downTilted * MathF.Cos(shinAngle) + f0 * MathF.Sin(shinAngle)).Normalized(); + + Basis thighBasis = BasisFromDownAndRight(thighDir, legRight) * legRig.Thigh.QOffset; + curModelBasis = ApplySegmentModelBasis(legRig.Thigh, curModelBasis, thighBasis); + + Basis shinBasis = BasisFromDownAndRight(shinDir, legRight) * legRig.Shin.QOffset; + curModelBasis = ApplySegmentModelBasis(legRig.Shin, curModelBasis, shinBasis); + + if (snap.IsDigitigrade && legRig.Cannon is { } cannonSeg) + { + float cannonAngle = shinAngle + ang.HockFlex; + Vector3 cannonDir = (downTilted * MathF.Cos(cannonAngle) + f0 * MathF.Sin(cannonAngle)).Normalized(); + Basis cannonBasis = BasisFromDownAndRight(cannonDir, legRight) * cannonSeg.QOffset; + curModelBasis = ApplySegmentModelBasis(cannonSeg, curModelBasis, cannonBasis); + } + + float lat = Math.Clamp(footNormModel.Dot(legRight), -0.85f, 0.85f); + float planarMag = MathF.Sqrt(MathF.Max(0.01f, 1f - lat * lat)); + Vector3 footUp = (legRight * lat + (Vector3.Up * MathF.Cos(ang.AnklePitch) + f0 * MathF.Sin(ang.AnklePitch)) * planarMag).Normalized(); + Basis footBasis = BasisFromDownAndRight(-footUp, legRight) * legRig.Foot.QOffset; + ApplySegmentModelBasis(legRig.Foot, curModelBasis, footBasis); + } + } + + string id = visual.ModelId; + if (string.Equals(id, "manticore", StringComparison.OrdinalIgnoreCase)) + { + AnimateManticoreTail(visual, st, relYaw, aimPitchRad, blend); + } + else if (string.Equals(id, "breaker", StringComparison.OrdinalIgnoreCase)) + { + StepBreakerLinkages(visual, snap.LoadG[0], snap.LoadG[1], dt); + } + } + + private static Basis ApplySegmentModelBasis(SegmentBinding seg, Basis curBasisInModel, Basis targetBasisInModel) + { + for (int i = 0; i < seg.IntermediateBefore.Length; i++) + { + curBasisInModel *= seg.IntermediateBefore[i].Transform.Basis.Orthonormalized(); + } + Basis localBasis = curBasisInModel.Inverse() * targetBasisInModel; + seg.Node.Transform = new Transform3D(localBasis, seg.RestLocal.Origin); + return targetBasisInModel; + } + + private static WalkerVisualRig? InitWalkerRig(VehicleVisualInstance visual) + { + var geom = WalkerGeometrySpec.GetForChassis(visual.ModelId); + string id = visual.ModelId.ToLowerInvariant(); + var legs = new WalkerLegBinding[geom.LegCount]; + + for (int i = 0; i < geom.LegCount; i++) + { + string? coxaName = null; + string thighName, shinName, footName; + string? cannonName = null; + + switch (id) + { + case "breaker": + { + string s = i == 0 ? "L" : "R"; + thighName = $"Leg{s}.Hip"; + shinName = $"Leg{s}.Shin"; + footName = $"Leg{s}.Foot"; + break; + } + case "paladin": + { + string s = i == 0 ? "L" : "R"; + thighName = $"Leg{s}.Upper"; + shinName = $"Leg{s}.Lower"; + footName = $"Leg{s}.Ankle"; + break; + } + case "raptor": + case "exemplar_frame": + { + string s = i == 0 ? "L" : "R"; + thighName = $"Leg{s}.Thigh"; + shinName = $"Leg{s}.Shin"; + cannonName = $"Leg{s}.Cannon"; + footName = $"Foot{s}"; + break; + } + case "spectre": + { + string s = i == 0 ? "L" : "R"; + thighName = $"Leg{s}.Thigh"; + shinName = $"Leg{s}.Shin"; + cannonName = $"Leg{s}.Cannon"; + footName = $"Leg{s}.Ankle"; + break; + } + case "kestrel": + { + string s = i == 0 ? "L" : "R"; + thighName = $"Leg{s}.Thigh"; + shinName = $"Leg{s}.Shin"; + footName = $"Leg{s}.Foot"; + break; + } + case "manticore": + { + string q = i switch { 0 => "FL", 1 => "FR", 2 => "BL", _ => "BR" }; + coxaName = $"Leg{q}.Coxa"; + thighName = $"Leg{q}.S1"; + shinName = $"Leg{q}.S2"; + footName = $"Foot{q}"; + break; + } + case "bastion": + { + string q = i switch { 0 => "fl", 1 => "fr", 2 => "rl", _ => "rr" }; + thighName = $"Thigh.{q}"; + shinName = $"Shin.{q}"; + footName = $"Ankle.{q}"; + break; + } + default: + return null; + } + + if (visual.GetNamedNode(thighName) is not { } thighNode || + visual.GetNamedNode(shinName) is not { } shinNode || + visual.GetNamedNode(footName) is not { } footNode || + !visual.TryGetRestLocal(thighName, out var restThigh) || + !visual.TryGetRestLocal(shinName, out var restShin) || + !visual.TryGetRestLocal(footName, out var restFoot) || + !visual.TryGetRestModel(thighName, out var modelThigh) || + !visual.TryGetRestModel(shinName, out var modelShin) || + !visual.TryGetRestModel(footName, out var modelFoot)) + { + return null; + } + + Node3D? cannonNode = null; + Transform3D restCannon = Transform3D.Identity; + Transform3D modelCannon = Transform3D.Identity; + if (cannonName is not null) + { + if (visual.GetNamedNode(cannonName) is not { } cn || + !visual.TryGetRestLocal(cannonName, out restCannon) || + !visual.TryGetRestModel(cannonName, out modelCannon)) + { + return null; + } + cannonNode = cn; + } + + Node3D? coxaNode = null; + Transform3D restCoxa = Transform3D.Identity; + Transform3D modelCoxa = Transform3D.Identity; + if (coxaName is not null && + visual.GetNamedNode(coxaName) is { } cxn && + visual.TryGetRestLocal(coxaName, out restCoxa) && + visual.TryGetRestModel(coxaName, out modelCoxa)) + { + coxaNode = cxn; + } + + Vector3 dirRestThigh = (modelShin.Origin - modelThigh.Origin).Normalized(); + Vector3 shinEndOrigin = cannonNode is not null ? modelCannon.Origin : modelFoot.Origin; + Vector3 dirRestShin = (shinEndOrigin - modelShin.Origin).Normalized(); + Vector3 dirRestCannon = cannonNode is not null + ? (modelFoot.Origin - modelCannon.Origin).Normalized() + : Vector3.Down; + + Vector3 legRightRest = geom.IsArachnidUp + ? dirRestThigh.Cross(Vector3.Up).Normalized() + : ToGodot(geom.Legs[i].LegRight0); + + SegmentBinding? coxaBinding = null; + if (coxaNode is not null) + { + Vector3 rad0 = new(modelFoot.Origin.X - modelThigh.Origin.X, 0f, modelFoot.Origin.Z - modelThigh.Origin.Z); + rad0 = rad0.LengthSquared() > 1e-6f ? rad0.Normalized() : ToGodot(geom.Legs[i].LegFwd0); + Basis fCoxaRest = BasisFromDownAndRight(-rad0, Vector3.Up.Cross(rad0)); + coxaBinding = new SegmentBinding + { + Node = coxaNode, + RestLocal = restCoxa, + IntermediateBefore = BuildIntermediateChain(visual.ModelRoot, coxaNode), + QOffset = fCoxaRest.Inverse() * modelCoxa.Basis.Orthonormalized() + }; + } + + var thighBinding = new SegmentBinding + { + Node = thighNode, + RestLocal = restThigh, + IntermediateBefore = BuildIntermediateChain(coxaNode ?? visual.ModelRoot, thighNode), + QOffset = BasisFromDownAndRight(dirRestThigh, legRightRest).Inverse() * modelThigh.Basis.Orthonormalized() + }; + + var shinBinding = new SegmentBinding + { + Node = shinNode, + RestLocal = restShin, + IntermediateBefore = BuildIntermediateChain(thighNode, shinNode), + QOffset = BasisFromDownAndRight(dirRestShin, legRightRest).Inverse() * modelShin.Basis.Orthonormalized() + }; + + SegmentBinding? cannonBinding = null; + if (cannonNode is not null) + { + cannonBinding = new SegmentBinding + { + Node = cannonNode, + RestLocal = restCannon, + IntermediateBefore = BuildIntermediateChain(shinNode, cannonNode), + QOffset = BasisFromDownAndRight(dirRestCannon, legRightRest).Inverse() * modelCannon.Basis.Orthonormalized() + }; + } + + var footBinding = new SegmentBinding + { + Node = footNode, + RestLocal = restFoot, + IntermediateBefore = BuildIntermediateChain(cannonNode ?? shinNode, footNode), + QOffset = BasisFromDownAndRight(Vector3.Down, legRightRest).Inverse() * modelFoot.Basis.Orthonormalized() + }; + + legs[i] = new WalkerLegBinding + { + Coxa = coxaBinding, + Thigh = thighBinding, + Shin = shinBinding, + Cannon = cannonBinding, + Foot = footBinding + }; + } + + return new WalkerVisualRig + { + Geom = geom, + Legs = legs + }; + } + + private static Node3D[] BuildIntermediateChain(Node3D ancestorExclusive, Node3D childExclusive) + { + var list = new List(4); + for (Node? cur = childExclusive.GetParent(); cur is Node3D n3d && !ReferenceEquals(cur, ancestorExclusive); cur = cur.GetParent()) + { + list.Add(n3d); + } + list.Reverse(); + return list.ToArray(); + } + + private static Basis BasisFromDownAndRight(Vector3 downDir, Vector3 rightX) + { + Vector3 upY = -downDir.Normalized(); + Vector3 x = rightX - upY * rightX.Dot(upY); + x = x.LengthSquared() > 1e-6f ? x.Normalized() : Vector3.Right; + Vector3 z = x.Cross(upY).Normalized(); + x = upY.Cross(z).Normalized(); + return new Basis(x, upY, z); + } + + private static Vector3 ToGodot(System.Numerics.Vector3 v) => new(v.X, v.Y, v.Z); + + private static void AnimateManticoreTail( + VehicleVisualInstance visual, + RigState st, + float relYaw, + float aimPitchRad, + float blend) + { + if (visual.Joints.TryGetValue("joint.tail_yaw", out var tailYaw)) + { + float targetTailYaw = Math.Clamp(relYaw, tailYaw.MinRad, tailYaw.MaxRad); + st.TurretYawRad += (targetTailYaw - st.TurretYawRad) * blend; + SetJointAngle(tailYaw, st.TurretYawRad); + } + + float idleSway = MathF.Sin(st.ElapsedSeconds * 2.1f) * 0.05f; + float pitchDrive = aimPitchRad * 0.5f + idleSway; + + if (visual.Joints.TryGetValue("joint.tail_s1", out var s1)) + { + SetJointAngle(s1, Math.Clamp(pitchDrive * 0.45f, s1.MinRad, s1.MaxRad)); + } + if (visual.Joints.TryGetValue("joint.tail_s2", out var s2)) + { + SetJointAngle(s2, Math.Clamp(-pitchDrive * 0.65f, s2.MinRad, s2.MaxRad)); + } + if (visual.Joints.TryGetValue("joint.tail_s3", out var s3)) + { + SetJointAngle(s3, Math.Clamp(-pitchDrive * 0.55f, s3.MinRad, s3.MaxRad)); + } + if (visual.Joints.TryGetValue("joint.tail_elev", out var elev)) + { + SetJointAngle(elev, Math.Clamp(-aimPitchRad * 0.85f, elev.MinRad, elev.MaxRad)); + } + } + + /// + /// Steps Breaker's real oleo gas-spring struts, 2-link scissor torque knees, and telescoping recess rams + /// from real Newtonian GRF per-leg load factors (grfN / (0.5f * weightN)). + /// + public static void StepBreakerLinkages( + VehicleVisualInstance visual, + float leftLoadG, + float rightLoadG, + float dt) + { + VehicleMechanismsRecord? mech = visual.Package.Mechanisms; + if (mech is null || mech.Struts.Count == 0) + { + return; + } + + RigState st = visual.RigState; + BreakerMechRig rig = st.BreakerRig ??= InitBreakerRig(visual, mech); + if (!rig.Initialized) + { + return; + } + + float strideLoadL = Math.Clamp(leftLoadG, 0f, 3.5f); + float strideLoadR = Math.Clamp(rightLoadG, 0f, 3.5f); + + // 1. Oleo gas-spring + asymmetric orifice damping (Brokkr mechrig.Model.strut_step) + if (dt > 0f) + { + float stepDt = Math.Clamp(dt, 0.001f, 0.05f); + for (int i = 0; i < mech.Struts.Count; i++) + { + var sr = mech.Struts[i]; + if (!rig.Struts.TryGetValue(sr.Name, out var ss)) + { + continue; + } + + float load = string.Equals(sr.Side, "R", StringComparison.OrdinalIgnoreCase) ? strideLoadR : strideLoadL; + float w = MathF.Tau * MathF.Max(0.1f, sr.Hertz); + float column = 1.15f * MathF.Max(0.02f, sr.Travel); + float h = stepDt / 16f; + + for (int sub = 0; sub < 16; sub++) + { + float ratio = Math.Clamp(1f - ss.Compression / column, 0.08f, 2f); + float spring = w * w * column * (MathF.Pow(ratio, -1.3f) - 1f) / 1.3f; + float c = 2f * sr.DampingRatio * w * (ss.Velocity < 0f ? 1.3f : 1f); + ss.Velocity += h * (9.81f * load - spring - c * ss.Velocity); + ss.Compression += h * ss.Velocity; + if (ss.Compression < 0f || ss.Compression > sr.Travel) + { + ss.Compression = Math.Clamp(ss.Compression, 0f, sr.Travel); + ss.Velocity = 0f; + } + } + + if (rig.OleoNodes.TryGetValue(sr.Dof, out var oleo)) + { + // LegL/R.Oleo local +Y points down toward the foot; compression slides up (-Y) + oleo.Node.Transform = new Transform3D( + oleo.RestLocal.Basis, + oleo.RestLocal.Origin + new Vector3(0f, -ss.Compression, 0f)); + } + } + } + + // 2. Scissor 2-link torque knees (LegL/R.TorqueUp, LegL/R.TorqueLow) + for (int i = 0; i < rig.Scissors.Count; i++) + { + var sb = rig.Scissors[i]; + Transform3D forkInShin = sb.OleoNode.Transform * sb.OleoForkNode.Transform; + Vector3 bInShin = forkInShin * sb.BInOleoFork; + Vector3 apexInShin = SolveScissorApex(sb.AInShin, bInShin, sb.OutInShin, sb.Arm); + + Vector3 dirUp = apexInShin - sb.AInShin; + if (dirUp.LengthSquared() > 1e-8f) + { + Quaternion qUp = ShortestArcQuat(sb.DirUp0InShin, dirUp.Normalized()); + Basis rotUp = new Basis(qUp); + sb.UpperNode.Transform = new Transform3D(rotUp, sb.AInShin - rotUp * sb.AInShin) * sb.RestLocalUp; + } + + Vector3 apexInFork = forkInShin.Inverse() * apexInShin; + Vector3 dirLow = apexInFork - sb.BInOleoFork; + if (dirLow.LengthSquared() > 1e-8f) + { + Quaternion qLow = ShortestArcQuat(sb.DirLow0InOleoFork, dirLow.Normalized()); + Basis rotLow = new Basis(qLow); + sb.LowerNode.Transform = new Transform3D(rotLow, sb.BInOleoFork - rotLow * sb.BInOleoFork) * sb.RestLocalLow; + } + } + + // 3. Telescoping recess hydraulic rams (LegL/R.RecessRam0/1) + for (int i = 0; i < rig.Rams.Count; i++) + { + var rb = rig.Rams[i]; + Transform3D forkInShin = rb.OleoNode.Transform * rb.OleoForkNode.Transform; + Transform3D footInLug = rb.LugNode.Transform.Inverse() * forkInShin * rb.FootNode.Transform; + Vector3 bInLug = footInLug * rb.BPosInFoot; + Vector3 span = bInLug - rb.APosInLug; + if (span.LengthSquared() > 1e-8f) + { + Quaternion qRam = ShortestArcQuat(rb.WantDir0InLug, span.Normalized()); + rb.RamNode.Transform = new Transform3D(new Basis(qRam) * rb.RestLocalRam.Basis, rb.RestLocalRam.Origin); + } + } + } + + private static BreakerMechRig InitBreakerRig(VehicleVisualInstance visual, VehicleMechanismsRecord mech) + { + var rig = new BreakerMechRig(); + + foreach (var sr in mech.Struts) + { + float w = MathF.Tau * MathF.Max(0.1f, sr.Hertz); + float col = 1.15f * MathF.Max(0.02f, sr.Travel); + float xRest = col * (1f - MathF.Pow(1f + 1.3f * 9.81f * 1.0f / (w * w * col), -1f / 1.3f)); + rig.Struts[sr.Name] = new StrutState + { + Compression = Math.Clamp(xRest, 0f, sr.Travel), + Velocity = 0f + }; + + if (visual.GetNamedNode(sr.Dof) is { } oNode && visual.TryGetRestLocal(sr.Dof, out var oRest)) + { + rig.OleoNodes[sr.Dof] = (oNode, oRest); + } + } + + foreach (var sc in mech.Scissors) + { + string side = sc.Name.StartsWith("LegR", StringComparison.Ordinal) ? "R" : "L"; + string upName = $"Leg{side}.TorqueUp"; + string lowName = $"Leg{side}.TorqueLow"; + string shinName = $"Leg{side}.Shin"; + string oleoName = $"Leg{side}.Oleo"; + string forkName = $"Leg{side}.OleoFork"; + + if (visual.GetNamedNode(upName) is not { } upNode || + visual.GetNamedNode(lowName) is not { } lowNode || + visual.GetNamedNode(shinName) is not { } shinNode || + visual.GetNamedNode(oleoName) is not { } oleoNode || + visual.GetNamedNode(forkName) is not { } forkNode || + !visual.TryGetRestLocal(upName, out var restUp) || + !visual.TryGetRestLocal(lowName, out var restLow) || + !visual.TryGetRestModel(shinName, out var shinRestModel) || + !visual.TryGetRestModel(forkName, out var forkRestModel) || + sc.APos is null || sc.BPos is null || sc.OutDir is null) + { + continue; + } + + Vector3 aModel = new(sc.APos[0], sc.APos[1], sc.APos[2]); + Vector3 bModel = new(sc.BPos[0], sc.BPos[1], sc.BPos[2]); + Vector3 outModel = new(sc.OutDir[0], sc.OutDir[1], sc.OutDir[2]); + + Transform3D shinInv = shinRestModel.Inverse(); + Transform3D forkInv = forkRestModel.Inverse(); + + Vector3 aInShin = shinInv * aModel; + Vector3 bRestInShin = shinInv * bModel; + Vector3 bInFork = forkInv * bModel; + Vector3 outInShin = (shinInv.Basis * outModel).Normalized(); + + Vector3 apex0InShin = SolveScissorApex(aInShin, bRestInShin, outInShin, sc.Arm); + Vector3 apex0InFork = (forkRestModel.Inverse() * shinRestModel) * apex0InShin; + + Vector3 dirUp0 = (apex0InShin - aInShin).Normalized(); + Vector3 dirLow0 = (apex0InFork - bInFork).Normalized(); + + rig.Scissors.Add(new ScissorBinding + { + UpperNode = upNode, + LowerNode = lowNode, + ShinNode = shinNode, + OleoNode = oleoNode, + OleoForkNode = forkNode, + RestLocalUp = restUp, + RestLocalLow = restLow, + AInShin = aInShin, + BInOleoFork = bInFork, + OutInShin = outInShin, + Arm = sc.Arm, + DirUp0InShin = dirUp0, + DirLow0InOleoFork = dirLow0 + }); + } + + foreach (var r in mech.Rams) + { + string side = r.Name.StartsWith("LegR", StringComparison.Ordinal) ? "R" : "L"; + char idxChar = r.Name[^1]; + string lugName = $"Leg{side}.RamLugA{idxChar}"; + string oleoName = $"Leg{side}.Oleo"; + string forkName = $"Leg{side}.OleoFork"; + string footName = $"Leg{side}.Foot"; + + if (visual.GetNamedNode(r.Name) is not { } ramNode || + visual.GetNamedNode(lugName) is not { } lugNode || + visual.GetNamedNode(oleoName) is not { } oleoNode || + visual.GetNamedNode(forkName) is not { } forkNode || + visual.GetNamedNode(footName) is not { } footNode || + !visual.TryGetRestLocal(r.Name, out var restRam) || + !visual.TryGetRestModel(lugName, out var lugRestModel) || + !visual.TryGetRestModel(footName, out var footRestModel) || + r.BPos is null) + { + continue; + } + + Vector3 bModel = new(r.BPos[0], r.BPos[1], r.BPos[2]); + Vector3 aInLug = restRam.Origin; + Vector3 bInLug0 = lugRestModel.Inverse() * bModel; + Vector3 bInFoot = footRestModel.Inverse() * bModel; + Vector3 want0 = (bInLug0 - aInLug).Normalized(); + + rig.Rams.Add(new RamBinding + { + RamNode = ramNode, + LugNode = lugNode, + OleoNode = oleoNode, + OleoForkNode = forkNode, + FootNode = footNode, + RestLocalRam = restRam, + APosInLug = aInLug, + BPosInFoot = bInFoot, + WantDir0InLug = want0 + }); + } + + rig.Initialized = rig.Struts.Count > 0; + return rig; + } + + private static Vector3 SolveScissorApex(Vector3 a, Vector3 b, Vector3 outDir, float arm) + { + Vector3 u = b - a; + float d = u.Length(); + if (d < 1e-5f) + { + return (a + b) * 0.5f + outDir * arm; + } + u /= d; + Vector3 oFlat = outDir - u * outDir.Dot(u); + oFlat = oFlat.LengthSquared() > 1e-6f ? oFlat.Normalized() : Vector3.Back; + float h = MathF.Sqrt(MathF.Max(arm * arm - (d * 0.5f) * (d * 0.5f), 0f)); + return (a + b) * 0.5f + oFlat * h; + } + + private static void SetJointAngle(VehicleVisualInstance.BoundJoint j, float angleRad) + { + if (!GodotObject.IsInstanceValid(j.Node) || !float.IsFinite(angleRad)) + { + return; + } + Basis delta = new Basis(j.AxisInParent, angleRad); + j.Node.Transform = new Transform3D(delta * j.RestLocal.Basis, j.RestLocal.Origin); + } + + private static Quaternion ShortestArcQuat(Vector3 from, Vector3 to) + { + float dot = Math.Clamp(from.Dot(to), -1f, 1f); + if (dot > 0.99999f) + { + return Quaternion.Identity; + } + if (dot < -0.99999f) + { + Vector3 ortho = MathF.Abs(from.X) < 0.8f ? Vector3.Right : Vector3.Up; + Vector3 axis = from.Cross(ortho).Normalized(); + return new Quaternion(axis, MathF.PI); + } + Vector3 cross = from.Cross(to); + return new Quaternion(cross.X, cross.Y, cross.Z, 1f + dot).Normalized(); + } + + private static float Sanitize(float v, float fallback, float min, float max) => + float.IsFinite(v) ? Math.Clamp(v, min, max) : fallback; + + private static Vector3 SanitizeVec(Vector3 v) => + new( + float.IsFinite(v.X) ? v.X : 0f, + float.IsFinite(v.Y) ? v.Y : 0f, + float.IsFinite(v.Z) ? v.Z : 0f); +} diff --git a/client/VehicleVisualInstance.cs b/client/VehicleVisualInstance.cs new file mode 100644 index 0000000..e9ab85f --- /dev/null +++ b/client/VehicleVisualInstance.cs @@ -0,0 +1,1167 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +public enum VehicleVisualRole +{ + Player, + Rival, + SpectatorTourist, + SpectatorPatron, + SpectatorExemplar, + SalvageDrop +} + +/// +/// Lightweight Node3D rig hierarchy for a Brokkr vehicle/mech GLB, submitting all +/// rigid limbs, detachable armor chunks, and mounted gear into +/// (zero rendering MeshInstance3D children on rigs, zero per-hit material clones). +/// +public sealed class VehicleVisualInstance +{ + public sealed class BoundJoint + { + public required string JointId; + public required Node3D Node; + public required Transform3D RestLocal; + public required Vector3 AxisInParent; + public required float MinRad; + public required float MaxRad; + } + + public sealed class StaticPartBinding + { + public required Node3D Pivot; + public required ArrayMesh Mesh; + } + + public readonly record struct ModularWeaponPartBinding( + ArrayMesh Mesh, + Transform3D LocalToGearPivot, + string Slot); + + private sealed class BoundHardpoint + { + public required HardpointSpec Spec; + public required VehicleAssetCache.GlbAnchorInfo AnchorInfo; + public required Node3D AnchorNode; + public string? MountedModuleId; + public Node3D? GearNode; + public ArrayMesh? GearMesh; + public VehicleAssetCache.GearTemplate? GearTemplate; + public ModularWeaponPartBinding[]? ModularParts; + public float ManufacturerRoleIndex; + public Vector3 ModularMuzzleTipLocal; + public Vector3 ModularReceiverCenterLocal; + public float HeatGlow; + } + + private sealed class CellPartBinding + { + public required Node3D Pivot; + public required ArrayMesh Mesh; + public bool Detached; + public float Scorch; + public float HeatGlow; + } + + private readonly record struct GearVisualRecipe( + string GearGlbId, + Vector3 VariantScale, + Color? PaintTint, + Color? AccentTint); + + private static readonly Color TouristGold = Color.FromHtml("#e6b838"); + private static readonly Color TouristIvory = Color.FromHtml("#f2ead8"); + + private readonly VehicleAssetCache _cache; + private readonly VehicleAssetCache.VehicleTemplate _template; + private readonly Dictionary _hardpoints = new(StringComparer.Ordinal); + private readonly List _hardpointList = new(); + private readonly List<(int X, int Y)> _activeCells = new(); + private readonly Dictionary _joints = new(StringComparer.Ordinal); + private readonly Dictionary _namedNodes = new(StringComparer.Ordinal); + private readonly Dictionary _restLocalByName = new(StringComparer.Ordinal); + private readonly Dictionary _restModelByName = new(StringComparer.Ordinal); + private readonly Dictionary _restModelByNode = new(); + private readonly List _staticParts = new(); + private readonly List[,] _cellParts; + private readonly List _allCellParts = new(); + private readonly bool[,] _strippedCells; + private readonly HashSet _shearedHardpoints = new(StringComparer.Ordinal); + private readonly VehicleRigAnimator.RigState _rigState = new(); + + private readonly VehicleVisualRole _role; + private readonly float _roleIndex; + private readonly string _chassisId; + private bool _isStaticLod; + private bool _castShadows = true; + private bool _hasAnyStrippedCell; + private float _hullScorch; + private float _hullHeatGlow; + + public static double PerfDamageHeatMs; + public static int PerfMaterialDupCount; + + private VehicleVisualInstance( + VehicleAssetCache cache, + VehicleAssetCache.VehicleTemplate template, + Node3D root, + Node3D modelRoot, + string chassisId, + VehicleVisualRole role) + { + _cache = cache; + _template = template; + Root = root; + ModelRoot = modelRoot; + _chassisId = chassisId; + _role = role; + _roleIndex = role switch + { + VehicleVisualRole.Rival => 1f, + VehicleVisualRole.SpectatorTourist => 2f, + VehicleVisualRole.SpectatorPatron => 3f, + VehicleVisualRole.SpectatorExemplar => 4f, + VehicleVisualRole.SalvageDrop => 5f, + _ => 0f + }; + + int w = template.Package.GridWidth; + int h = template.Package.GridHeight; + _cellParts = new List[w, h]; + _strippedCells = new bool[w, h]; + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + _cellParts[x, y] = new List(); + } + } + } + + public Node3D Root { get; } + public Node3D ModelRoot { get; } + public VehicleAssetCache.VehicleTemplate Template => _template; + public VehiclePackage Package => _template.Package; + public string ChassisId => _chassisId; + public string ModelId => _template.Package.Id; + public VehicleRigAnimator.RigState RigState => _rigState; + public IReadOnlyDictionary Joints => _joints; + public IReadOnlyList StaticParts => _staticParts; + public int BoundHardpointCount => _hardpoints.Count; + public bool IsStaticLod => _isStaticLod; + public bool HasAnyStrippedCell => _hasAnyStrippedCell; + public float RoleIndex => _roleIndex; + + public void SetLodState(bool useStaticLod, bool castShadows) + { + if (_role == VehicleVisualRole.SalvageDrop) + { + _isStaticLod = useStaticLod; + _castShadows = castShadows; + return; + } + + if (_hasAnyStrippedCell) + { + useStaticLod = false; + } + if (_isStaticLod != useStaticLod) + { + _isStaticLod = useStaticLod; + ModelRoot.Visible = !useStaticLod; + ModelRoot.PhysicsInterpolationMode = useStaticLod + ? Node.PhysicsInterpolationModeEnum.Off + : Node.PhysicsInterpolationModeEnum.Inherit; + ModelRoot.ProcessMode = useStaticLod + ? Node.ProcessModeEnum.Disabled + : Node.ProcessModeEnum.Inherit; + } + _castShadows = castShadows; + } + + public static VehicleVisualInstance Create( + VehicleAssetCache cache, + string chassisId, + VehicleVisualRole role, + float visualScale = 1.0f, + float? targetHalfHeight = null) + { + var template = cache.GetOrLoadVehicle(chassisId); + var pkg = template.Package; + float halfHeight = targetHalfHeight ?? (pkg.HalfHeight * visualScale); + float effectiveScale = targetHalfHeight.HasValue && pkg.HalfHeight > 1e-4f + ? visualScale * (targetHalfHeight.Value / pkg.HalfHeight) + : visualScale; + + var root = new Node3D { Name = $"Actor_{chassisId}" }; + Vector3 modelScale = new(effectiveScale, effectiveScale, effectiveScale); + // Align glTF grounded minY=0 to physics chassis bottom (-halfHeight) + Vector3 modelPos = new(0f, -halfHeight - template.MinY * effectiveScale, 0f); + + if (role == VehicleVisualRole.SalvageDrop) + { + var dropPivot = new Node3D + { + Name = $"Model_{pkg.Id}", + Scale = modelScale, + Position = modelPos + }; + root.AddChild(dropPivot); + return new VehicleVisualInstance(cache, template, root, dropPivot, chassisId, role); + } + + if (template.SceneTemplate.Duplicate() is not Node3D modelRoot) + { + throw new InvalidOperationException($"Failed to duplicate GLB scene template for '{pkg.Id}'."); + } + modelRoot.Name = $"Model_{pkg.Id}"; + modelRoot.Scale = modelScale; + modelRoot.Position = modelPos; + root.AddChild(modelRoot); + + var instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId, role); + instance.BindAll(); + return instance; + } + + private void BindAll() + { + var pkg = _template.Package; + + // Collect cumulative pure glTF model-space transforms (minY=0, unscaled) starting at ModelRoot = Identity + var modelXforms = new Dictionary + { + [ModelRoot] = Transform3D.Identity + }; + int modelChildCount = ModelRoot.GetChildCount(); + for (int i = 0; i < modelChildCount; i++) + { + CollectNodeTransforms(ModelRoot.GetChild(i), Transform3D.Identity, modelXforms); + } + + // Bind named nodes for procedural/mechanism rigs + foreach (var (origName, relPath) in _template.NodesByOriginalName) + { + Node3D? node = ResolveRelative(ModelRoot, relPath); + if (node is not null) + { + _namedNodes[origName] = node; + _restLocalByName[origName] = node.Transform; + if (modelXforms.TryGetValue(node, out var mxf)) + { + _restModelByName[origName] = mxf; + _restModelByNode[node] = mxf; + } + } + } + + // Bind all joints from rtd.joint metadata + foreach (var (jointId, jInfo) in _template.Joints) + { + Node3D? jNode = ResolveRelative(ModelRoot, jInfo.RelativePath); + if (jNode is null) + { + throw new InvalidOperationException($"{pkg.Id}: duplicated scene missing joint node '{jInfo.NodeName}' ({jointId})."); + } + + Basis parentModelBasis = Basis.Identity; + Node? parent = jNode.GetParent(); + if (parent is not null && modelXforms.TryGetValue(parent, out var pxf)) + { + parentModelBasis = pxf.Basis.Orthonormalized(); + } + + Vector3 axisInParent = parentModelBasis.Inverse() * jInfo.Axis; + axisInParent = axisInParent.LengthSquared() > 1e-6f ? axisInParent.Normalized() : Vector3.Up; + + _joints[jointId] = new BoundJoint + { + JointId = jointId, + Node = jNode, + RestLocal = jNode.Transform, + AxisInParent = axisInParent, + MinRad = Mathf.DegToRad(jInfo.MinVal), + MaxRad = Mathf.DegToRad(jInfo.MaxVal) + }; + } + + // Bind every ChassisSpec hardpoint to its exact exterior anchor Node3D + ChassisSpec spec = pkg.ToChassisSpec(); + var pkgHpById = new Dictionary(StringComparer.Ordinal); + foreach (var rec in pkg.Hardpoints) + { + pkgHpById[rec.Id] = rec; + } + + for (int i = 0; i < spec.Hardpoints.Length; i++) + { + HardpointSpec hp = spec.Hardpoints[i]; + if (!pkgHpById.TryGetValue(hp.Id, out var rec) || + !_template.Anchors.TryGetValue(rec.AnchorId, out var anchorInfo)) + { + throw new InvalidOperationException($"{pkg.Id}: missing AnchorId for hardpoint '{hp.Id}'."); + } + + Node3D? anchorNode = ResolveRelative(ModelRoot, anchorInfo.RelativePath); + if (anchorNode is null) + { + throw new InvalidOperationException($"{pkg.Id}: duplicated scene missing anchor node '{rec.AnchorId}'."); + } + + var bh = new BoundHardpoint + { + Spec = hp, + AnchorInfo = anchorInfo, + AnchorNode = anchorNode + }; + _hardpoints[hp.Id] = bh; + _hardpointList.Add(bh); + } + + // Bind rigid static parts & detachable per-cell armor parts to their live Node3D pivots + foreach (var sp in _template.StaticRigidParts) + { + if (ResolveRelative(ModelRoot, sp.PivotPath) is { } pivot) + { + _staticParts.Add(new StaticPartBinding { Pivot = pivot, Mesh = sp.Mesh }); + } + } + + int w = pkg.GridWidth; + int h = pkg.GridHeight; + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (spec.IsActive(x, y)) + { + _activeCells.Add((x, y)); + } + } + } + foreach (var dp in _template.DetachableRigidParts) + { + if (dp.CellX < 0 || dp.CellX >= w || dp.CellY < 0 || dp.CellY >= h) + { + continue; + } + if (ResolveRelative(ModelRoot, dp.PivotPath) is { } pivot) + { + var binding = new CellPartBinding { Pivot = pivot, Mesh = dp.Mesh }; + _cellParts[dp.CellX, dp.CellY].Add(binding); + _allCellParts.Add(binding); + } + } + } + + public Node3D? GetNamedNode(string name) => + _namedNodes.TryGetValue(name, out var n) && GodotObject.IsInstanceValid(n) ? n : null; + + public bool TryGetRestLocal(string name, out Transform3D xform) => + _restLocalByName.TryGetValue(name, out xform); + + public bool TryGetRestModel(string name, out Transform3D xform) => + _restModelByName.TryGetValue(name, out xform); + + public bool TryGetRestModel(Node3D node, out Transform3D xform) => + _restModelByNode.TryGetValue(node, out xform); + + public Node3D? GetHardpointAnchorNode(string hardpointId) => + _hardpoints.TryGetValue(hardpointId, out var bh) ? bh.AnchorNode : null; + + public Node3D? GetMountedGearNode(string hardpointId) => + _hardpoints.TryGetValue(hardpointId, out var bh) && GodotObject.IsInstanceValid(bh.GearNode) ? bh.GearNode : null; + + public int CountDetachablePartsForCell(int x, int y) => + x >= 0 && x < _template.Package.GridWidth && y >= 0 && y < _template.Package.GridHeight + ? _cellParts[x, y].Count + : 0; + + public bool TryGetMountedWeaponCentroidsInModel( + string hardpointId, + string frontPartName, + string rearPartName, + out Vector3 frontInModel, + out Vector3 rearInModel) + { + frontInModel = Vector3.Zero; + rearInModel = Vector3.Zero; + if (!_hardpoints.TryGetValue(hardpointId, out var bh) || + bh.GearNode is null || + !GodotObject.IsInstanceValid(bh.GearNode)) + { + return false; + } + + Transform3D gearToModel = ComputeRelativeTransform(bh.GearNode, ModelRoot); + if (bh.ModularParts is not null) + { + frontInModel = gearToModel * bh.ModularMuzzleTipLocal; + rearInModel = gearToModel * bh.ModularReceiverCenterLocal; + return true; + } + + if (bh.GearTemplate is null) + { + return false; + } + if (!bh.GearTemplate.PartCentroidsLocal.TryGetValue(frontPartName, out Vector3 fLocal) || + !bh.GearTemplate.PartCentroidsLocal.TryGetValue(rearPartName, out Vector3 rLocal)) + { + return false; + } + + frontInModel = gearToModel * fLocal; + rearInModel = gearToModel * rLocal; + return true; + } + + public static void BuildModularWeaponAssembly( + VehicleAssetCache cache, + ModularWeaponAssembly assembly, + out ModularWeaponPartBinding[] parts, + out Vector3 muzzleTipLocal, + out Vector3 receiverCenterLocal, + out float minY) + { + var rxTpl = cache.GetOrLoadWeaponPart(assembly.ReceiverPartName); + var brlTpl = cache.GetOrLoadWeaponPart(assembly.BarrelPartName); + var fdTpl = cache.GetOrLoadWeaponPart(assembly.FeedPartName); + var mzTpl = cache.GetOrLoadWeaponPart(assembly.MuzzlePartName); + + Transform3D rxXf = Transform3D.Identity; + Transform3D brlXf = rxTpl.SocketsLocal.TryGetValue("barrel", out var bx) + ? bx + : new Transform3D(Basis.Identity, new Vector3(0f, 0.20f, 0.24f)); + Transform3D fdXf = rxTpl.SocketsLocal.TryGetValue("feed", out var fx) + ? fx + : new Transform3D(Basis.Identity, new Vector3(0.14f, 0.20f, 0f)); + Transform3D brlMuzzle = brlTpl.SocketsLocal.TryGetValue("muzzle", out var mx) + ? mx + : new Transform3D(Basis.Identity, new Vector3(0f, 0f, 0.55f)); + Transform3D mzXf = brlXf * brlMuzzle; + Transform3D mzTip = mzTpl.SocketsLocal.TryGetValue("muzzle_tip", out var tx) + ? tx + : new Transform3D(Basis.Identity, new Vector3(0f, 0f, 0.22f)); + + muzzleTipLocal = (mzXf * mzTip).Origin; + receiverCenterLocal = new Vector3(0f, rxTpl.Size.Y * 0.5f, 0f); + minY = rxTpl.MinY; + + parts = new[] + { + new ModularWeaponPartBinding(rxTpl.SingleSurfaceMesh, rxXf, "receiver"), + new ModularWeaponPartBinding(brlTpl.SingleSurfaceMesh, brlXf, "barrel"), + new ModularWeaponPartBinding(fdTpl.SingleSurfaceMesh, fdXf, "feed"), + new ModularWeaponPartBinding(mzTpl.SingleSurfaceMesh, mzXf, "muzzle") + }; + } + + public static void ResolveDropGearVisual( + VehicleAssetCache cache, + ModuleSpec mod, + out ArrayMesh mesh, + out Vector3 scale, + out float yOffset) + { + GearVisualRecipe recipe = ResolveGearRecipe(mod); + var template = cache.GetOrLoadGear(recipe.GearGlbId); + mesh = cache.GetOrBuildGearVariantMesh(mod.Id, recipe.GearGlbId, recipe.PaintTint, recipe.AccentTint); + scale = recipe.VariantScale; + yOffset = -template.MinY * recipe.VariantScale.Y; + } + + /// + /// Synchronizes exterior gear transform anchors on all hardpoints with . + /// + public void SyncMountedGear(ChassisGrid grid) + { + foreach (var bh in _hardpoints.Values) + { + if (_shearedHardpoints.Contains(bh.Spec.Id) || !grid.IsHardpointOperational(bh.Spec)) + { + continue; + } + + MountedModule? mounted = grid.GetMountedOn(bh.Spec.Id); + string? desiredId = mounted?.Spec.Id; + + if (string.Equals(bh.MountedModuleId, desiredId, StringComparison.Ordinal)) + { + continue; + } + + if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode)) + { + bh.GearNode.GetParent()?.RemoveChild(bh.GearNode); + bh.GearNode.QueueFree(); + } + bh.GearNode = null; + bh.GearMesh = null; + bh.GearTemplate = null; + bh.ModularParts = null; + bh.ManufacturerRoleIndex = 0f; + bh.HeatGlow = 0f; + bh.MountedModuleId = desiredId; + + if (mounted is null) + { + continue; + } + + if (mounted.Spec.Procedural is { } proc) + { + BuildModularWeaponAssembly( + _cache, + proc.Assembly, + out var modParts, + out Vector3 muzzleTipLocal, + out Vector3 receiverCenterLocal, + out float minY); + Transform3D mountXf = ComputeHardpointMountTransform( + bh.Spec, + bh.AnchorInfo, + Vector3.One * proc.Assembly.VisualScale, + localModelForwardZ: 1f, + minY); + var gearNode = new Node3D + { + Name = $"Mounted_{mounted.Spec.Id}_{bh.Spec.Id}", + Transform = mountXf + }; + bh.AnchorNode.AddChild(gearNode); + bh.GearNode = gearNode; + bh.ModularParts = modParts; + bh.ManufacturerRoleIndex = 10f + (float)proc.Manufacturer; + bh.ModularMuzzleTipLocal = muzzleTipLocal; + bh.ModularReceiverCenterLocal = receiverCenterLocal; + } + else + { + Node3D gearNode = CreateGearPivotForHardpoint( + mounted.Spec, + bh.Spec, + bh.AnchorInfo, + out ArrayMesh gearMesh, + out VehicleAssetCache.GearTemplate gearTemplate); + bh.AnchorNode.AddChild(gearNode); + bh.GearNode = gearNode; + bh.GearMesh = gearMesh; + bh.GearTemplate = gearTemplate; + } + } + } + + /// + /// Detaches exterior armor/shroud plates when Armor[x, y] <= 0.01f, + /// shears mounted gear off non-operational hardpoints into , + /// and updates per-part scorch/heat channels for . + /// + public void SyncDamageAndHeat(ChassisGrid grid, DebrisSystem debris, Vector3 vehicleVelocity) + { + long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; + Vector3 blastOrigin = Root.IsInsideTree() ? Root.GlobalPosition : Root.Position; + + float scorchSum = 0f; + float maxHeat = 0f; + int cellCount = _activeCells.Count; + + // 1. Part-by-cell detachment & cell scorch/heat channels + for (int c = 0; c < cellCount; c++) + { + var (x, y) = _activeCells[c]; + float armor = grid.Armor[x, y]; + float maxArmor = MathF.Max(1f, grid.MaxArmor[x, y]); + float temp = grid.Temperature[x, y]; + float dmgFrac = 1f - Math.Clamp(armor / maxArmor, 0f, 1f); + float cellScorch = Math.Clamp((dmgFrac - 0.18f) / 0.82f, 0f, 1f); + float cellHeat = Math.Clamp((temp - 65f) / 110f, 0f, 1f); + scorchSum += cellScorch; + if (cellHeat > maxHeat) maxHeat = cellHeat; + + var parts = _cellParts[x, y]; + if (!_strippedCells[x, y] && armor <= 0.01f) + { + _strippedCells[x, y] = true; + _hasAnyStrippedCell = true; + for (int i = 0; i < parts.Count; i++) + { + var pb = parts[i]; + if (!pb.Detached && GodotObject.IsInstanceValid(pb.Pivot)) + { + pb.Detached = true; + Transform3D worldXf = pb.Pivot.IsInsideTree() + ? pb.Pivot.GlobalTransform + : ComputeWorldTransformFallback(pb.Pivot); + debris.SpawnDetachedPart(pb.Mesh, worldXf, blastOrigin, vehicleVelocity, _roleIndex, impulseScale: 1.0f, applyScorch: true); + } + } + continue; + } + + for (int i = 0; i < parts.Count; i++) + { + var pb = parts[i]; + if (!pb.Detached) + { + pb.Scorch = cellScorch; + pb.HeatGlow = cellHeat; + } + } + } + + _hullScorch = cellCount > 0 ? Math.Clamp((scorchSum / cellCount) * 0.85f, 0f, 0.85f) : 0f; + _hullHeatGlow = maxHeat * 0.72f; + + // 2. Hardpoint shear & mounted gear heat glow + for (int i = 0; i < _hardpointList.Count; i++) + { + var bh = _hardpointList[i]; + if (!_shearedHardpoints.Contains(bh.Spec.Id) && !grid.IsHardpointOperational(bh.Spec)) + { + _shearedHardpoints.Add(bh.Spec.Id); + _hasAnyStrippedCell = true; + if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode)) + { + Transform3D worldXf = bh.GearNode.IsInsideTree() + ? bh.GearNode.GlobalTransform + : ComputeWorldTransformFallback(bh.GearNode); + ModularWeaponPartBinding[]? modParts = bh.ModularParts; + float mfgRole = bh.ManufacturerRoleIndex; + ArrayMesh? gearMesh = bh.GearMesh; + Node3D sheared = bh.GearNode; + bh.GearNode = null; + bh.GearMesh = null; + bh.GearTemplate = null; + bh.ModularParts = null; + bh.ManufacturerRoleIndex = 0f; + bh.MountedModuleId = null; + bh.HeatGlow = 0f; + sheared.GetParent()?.RemoveChild(sheared); + sheared.QueueFree(); + + if (modParts is not null) + { + for (int p = 0; p < modParts.Length; p++) + { + debris.SpawnDetachedPart( + modParts[p].Mesh, + worldXf * modParts[p].LocalToGearPivot, + blastOrigin, + vehicleVelocity, + mfgRole, + impulseScale: 1.15f, + applyScorch: true); + } + } + else if (gearMesh is not null) + { + debris.SpawnDetachedPart(gearMesh, worldXf, blastOrigin, vehicleVelocity, _roleIndex, impulseScale: 1.15f, applyScorch: true); + } + } + continue; + } + + if (bh.GearNode is null) + { + continue; + } + + MountedModule? mounted = grid.GetMountedOn(bh.Spec.Id); + bh.HeatGlow = mounted is not null + ? Math.Clamp((mounted.CurrentTemp - 65f) / 115f, 0f, 1f) + : 0f; + } + + if (t0 != 0) + { + PerfDamageHeatMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; + } + } + + public void SubmitToPool(MultiMeshPartPool pool) + { + if (!Root.Visible) + { + return; + } + + Transform3D modelWorld = ModelRoot.IsInsideTree() ? ModelRoot.GlobalTransform : Root.Transform * ModelRoot.Transform; + + if (_role == VehicleVisualRole.SalvageDrop) + { + ArrayMesh dropMesh = _isStaticLod ? _template.SingleSurfaceLodFarMesh : _template.SingleSurfaceStaticMesh; + pool.Submit(dropMesh, in modelWorld, new Color(0f, 0f, _roleIndex, 1f), _castShadows); + return; + } + + if (_isStaticLod) + { + pool.Submit(_template.SingleSurfaceLodFarMesh, in modelWorld, new Color(_hullScorch, _hullHeatGlow, _roleIndex, 1f), _castShadows); + return; + } + + for (int i = 0; i < _staticParts.Count; i++) + { + var sp = _staticParts[i]; + if (!GodotObject.IsInstanceValid(sp.Pivot)) + { + continue; + } + Transform3D xf = ReferenceEquals(sp.Pivot, ModelRoot) + ? modelWorld + : (sp.Pivot.IsInsideTree() ? sp.Pivot.GlobalTransform : ComputeWorldTransformFallback(sp.Pivot)); + pool.Submit(sp.Mesh, in xf, new Color(_hullScorch, _hullHeatGlow, _roleIndex, 1f), _castShadows); + } + + for (int i = 0; i < _allCellParts.Count; i++) + { + var pb = _allCellParts[i]; + if (pb.Detached || !GodotObject.IsInstanceValid(pb.Pivot)) + { + continue; + } + Transform3D xf = ReferenceEquals(pb.Pivot, ModelRoot) + ? modelWorld + : (pb.Pivot.IsInsideTree() ? pb.Pivot.GlobalTransform : ComputeWorldTransformFallback(pb.Pivot)); + pool.Submit(pb.Mesh, in xf, new Color(pb.Scorch, pb.HeatGlow, _roleIndex, 1f), wantsShadow: false); + } + + for (int i = 0; i < _hardpointList.Count; i++) + { + var bh = _hardpointList[i]; + if (bh.GearNode is null || !GodotObject.IsInstanceValid(bh.GearNode)) + { + continue; + } + Transform3D xf = bh.GearNode.IsInsideTree() ? bh.GearNode.GlobalTransform : ComputeWorldTransformFallback(bh.GearNode); + if (bh.ModularParts is { } modParts) + { + Color custom = new(0f, bh.HeatGlow, bh.ManufacturerRoleIndex, 1f); + for (int p = 0; p < modParts.Length; p++) + { + Transform3D partXf = xf * modParts[p].LocalToGearPivot; + pool.Submit(modParts[p].Mesh, in partXf, in custom, wantsShadow: false); + } + } + else if (bh.GearMesh is not null) + { + pool.Submit(bh.GearMesh, in xf, new Color(0f, bh.HeatGlow, _roleIndex, 1f), wantsShadow: false); + } + } + } + + /// + /// Fast zero-allocation ray intersection against cached far-LOD triangles in space + /// so POM impact decals sit flush on sculpted armor surfaces without per-hit GPU mesh readbacks. + /// + public bool TryRayHitAttachedPart( + Vector3 rayOriginWorld, + Vector3 rayDirWorld, + out Node3D? hitPivot, + out Transform3D decalLocalToPivot, + float decalSize) + { + hitPivot = null; + decalLocalToPivot = Transform3D.Identity; + if (!Root.IsInsideTree() || !ModelRoot.IsInsideTree() || _template.FarRayTris.Length < 3) + { + return false; + } + + Transform3D modelXf = ModelRoot.GlobalTransform; + Transform3D inv = modelXf.AffineInverse(); + Vector3 locOrig = inv * rayOriginWorld; + Vector3 locDir = inv.Basis * rayDirWorld; + float dirLen = locDir.Length(); + if (dirLen < 1e-6f) + { + return false; + } + locDir /= dirLen; + + if (!RayIntersectsAabb(_template.FarRayAabb, locOrig, locDir)) + { + return false; + } + + Vector3[] tris = _template.FarRayTris; + float bestT = float.PositiveInfinity; + Vector3 bestLocalN = Vector3.Back; + + for (int t = 0; t + 2 < tris.Length; t += 3) + { + Vector3 v0 = tris[t]; + Vector3 v1 = tris[t + 1]; + Vector3 v2 = tris[t + 2]; + if (RayTriangle(locOrig, locDir, v0, v1, v2, out float hitT) && hitT < bestT) + { + Vector3 fn = (v1 - v0).Cross(v2 - v0); + if (fn.LengthSquared() > 1e-10f) + { + fn = fn.Normalized(); + if (fn.Dot(-locDir) < 0f) fn = -fn; + bestT = hitT; + bestLocalN = fn; + } + } + } + + if (!float.IsFinite(bestT)) + { + return false; + } + + Vector3 hitWorld = modelXf * (locOrig + locDir * bestT); + Vector3 normalWorld = (modelXf.Basis.Inverse().Transposed() * bestLocalN).Normalized(); + Vector3 upRef = MathF.Abs(normalWorld.Y) > 0.92f ? Vector3.Forward : Vector3.Up; + Vector3 right = upRef.Cross(normalWorld).Normalized(); + Vector3 up = normalWorld.Cross(right).Normalized(); + Transform3D worldDecalXf = new(new Basis(right * decalSize, up * decalSize, normalWorld), hitWorld); + + hitPivot = ModelRoot; + decalLocalToPivot = inv * worldDecalXf; + return true; + } + + private Node3D CreateGearPivotForHardpoint( + ModuleSpec mod, + HardpointSpec hp, + VehicleAssetCache.GlbAnchorInfo anchorInfo, + out ArrayMesh gearMesh, + out VehicleAssetCache.GearTemplate gearTemplate) + { + GearVisualRecipe recipe = ResolveGearRecipe(mod); + gearTemplate = _cache.GetOrLoadGear(recipe.GearGlbId); + gearMesh = _cache.GetOrBuildGearVariantMesh(mod.Id, recipe.GearGlbId, recipe.PaintTint, recipe.AccentTint); + Transform3D xf = ComputeHardpointMountTransform( + hp, + anchorInfo, + recipe.VariantScale, + gearTemplate.LocalModelForward.Z, + gearTemplate.MinY); + return new Node3D + { + Name = $"Mounted_{mod.Id}_{hp.Id}", + Transform = xf + }; + } + + private static Transform3D ComputeHardpointMountTransform( + HardpointSpec hp, + VehicleAssetCache.GlbAnchorInfo anchorInfo, + Vector3 variantScale, + float localModelForwardZ, + float minY) + { + Basis anchorModelBasis = anchorInfo.ModelSpaceTransform.Basis.Orthonormalized(); + Vector3 upOut = anchorModelBasis.Y.Normalized(); + if (upOut.LengthSquared() < 1e-6f) upOut = Vector3.Up; + + Vector3 vehForward = new(0f, 0f, 1f); + Vector3 desiredGearFwd; + + if (hp.Kind == HardpointKind.Weapon) + { + if (upOut.Z > 0.72f) + { + upOut = upOut.Y <= 0.1f ? new Vector3(0f, -1f, 0f) : new Vector3(0f, 1f, 0f); + desiredGearFwd = vehForward; + } + else + { + Vector3 proj = vehForward - upOut * vehForward.Dot(upOut); + desiredGearFwd = proj.LengthSquared() > 1e-4f + ? proj.Normalized() + : anchorModelBasis.Z.Normalized(); + } + } + else + { + if (MathF.Abs(upOut.Z) > 0.78f) + { + Vector3 upProj = Vector3.Up - upOut * Vector3.Up.Dot(upOut); + desiredGearFwd = upProj.LengthSquared() > 1e-4f ? upProj.Normalized() : Vector3.Up; + } + else + { + Vector3 proj = vehForward - upOut * vehForward.Dot(upOut); + desiredGearFwd = proj.LengthSquared() > 1e-4f ? proj.Normalized() : Vector3.Up; + } + } + + Vector3 rightX = upOut.Cross(desiredGearFwd); + rightX = rightX.LengthSquared() < 1e-5f ? Vector3.Right : rightX.Normalized(); + desiredGearFwd = rightX.Cross(upOut).Normalized(); + var desiredModelBasis = new Basis(rightX, upOut, desiredGearFwd); + + if (localModelForwardZ < 0f) + { + desiredModelBasis *= new Basis(Vector3.Up, MathF.PI); + } + + Basis localBasis = anchorModelBasis.Inverse() * desiredModelBasis; + + float sx = MathF.Max(0.25f, anchorInfo.Size.X); + float sy = MathF.Max(0.25f, anchorInfo.Size.Y); + Vector3 fitScale; + if (hp.Kind == HardpointKind.Weapon) + { + float baseScale = Math.Clamp(MathF.Min(sx, sy) / 0.56f, 0.72f, 1.75f); + fitScale = variantScale * baseScale; + } + else + { + float scaleX = Math.Clamp(sx / 0.48f, 0.72f, 2.15f); + float scaleZ = Math.Clamp(sy / 0.45f, 0.72f, 2.15f); + float scaleY = Math.Clamp(0.5f * (scaleX + scaleZ), 0.72f, 1.85f); + fitScale = new Vector3( + variantScale.X * scaleX, + variantScale.Y * scaleY, + variantScale.Z * scaleZ); + } + + Basis finalBasis = localBasis * Basis.FromScale(fitScale); + float ySeat = -minY * fitScale.Y; + Vector3 pos = (anchorModelBasis.Inverse() * upOut) * ySeat; + return new Transform3D(finalBasis, pos); + } + + private static GearVisualRecipe ResolveGearRecipe(ModuleSpec mod) + { + return mod.Id switch + { + "mg_762" => new("mg_762", Vector3.One, null, null), + "autocannon" => new("autocannon", Vector3.One, null, null), + "recoilless" => new("recoilless", Vector3.One, null, null), + "copper_rad" => new("copper_rad", Vector3.One, null, null), + "gilded_lance" => new("gilded_lance", Vector3.One, null, null), + "gold_radiator" => new("gold_radiator", Vector3.One, null, null), + + "flak" => new("autocannon", new Vector3(1.12f, 0.92f, 0.68f), Color.FromHtml("#5a4a3f"), Color.FromHtml("#d96c27")), + "pd_flak" => new("mg_762", new Vector3(1.22f, 1.10f, 0.85f), Color.FromHtml("#3d4440"), Color.FromHtml("#e08a4a")), + "touring_plasma" => new("gilded_lance", new Vector3(1.05f, 0.96f, 0.72f), TouristIvory, Color.FromHtml("#38c9d8")), + "aegis_pd" => new("gilded_lance", new Vector3(0.95f, 0.92f, 0.56f), TouristGold, Color.FromHtml("#38c9d8")), + "diesel_core" => new("copper_rad", new Vector3(0.92f, 1.15f, 1.05f), Color.FromHtml("#363a38"), Color.FromHtml("#b35a2b")), + "turbo_core" => new("copper_rad", new Vector3(1.12f, 1.28f, 1.38f), Color.FromHtml("#2a2f32"), Color.FromHtml("#e07024")), + "noble_core" => new("gold_radiator", new Vector3(1.10f, 1.32f, 1.38f), TouristGold, Color.FromHtml("#38c9d8")), + "welded_plate" => new("copper_rad", new Vector3(1.30f, 0.34f, 0.95f), Color.FromHtml("#4e5740"), Color.FromHtml("#6a6f66")), + "gilded_plate" => new("gold_radiator", new Vector3(1.30f, 0.34f, 0.95f), TouristIvory, TouristGold), + _ => new(mod.IsImperial ? "gilded_lance" : "mg_762", Vector3.One, null, null) + }; + } + + private static Node3D? ResolveRelative(Node3D root, NodePath relPath) + { + if (relPath.IsEmpty) + { + return null; + } + return relPath.ToString() == "." ? root : root.GetNodeOrNull(relPath); + } + + private static void CollectNodeTransforms(Node cur, Transform3D parentXf, Dictionary map) + { + Transform3D xf = cur is Node3D n3d ? parentXf * n3d.Transform : parentXf; + map[cur] = xf; + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + CollectNodeTransforms(cur.GetChild(i), xf, map); + } + } + + private Transform3D ComputeWorldTransformFallback(Node3D node) + { + Transform3D xf = Transform3D.Identity; + for (Node? cur = node; cur is Node3D n3d; cur = cur.GetParent()) + { + xf = n3d.Transform * xf; + if (ReferenceEquals(cur, Root)) + { + break; + } + } + return xf; + } + + private static Transform3D ComputeRelativeTransform(Node3D node, Node3D ancestor) + { + Transform3D xf = Transform3D.Identity; + for (Node? cur = node; cur is Node3D n3d && !ReferenceEquals(cur, ancestor); cur = cur.GetParent()) + { + xf = n3d.Transform * xf; + } + return xf; + } + + /// + /// Computes the highest rendered vertex Y in local space across active rigid parts + /// and all currently mounted gear meshes. + /// + public float ComputeMountedMaxY() + { + float maxY = float.NegativeInfinity; + if (_role == VehicleVisualRole.SalvageDrop) + { + ArrayMesh m = _isStaticLod ? _template.SingleSurfaceLodFarMesh : _template.SingleSurfaceStaticMesh; + AccumulateMeshMinMaxY(m, ModelRoot.Transform, out _, out maxY); + return float.IsFinite(maxY) ? maxY : ModelRoot.Position.Y + _template.MaxY * ModelRoot.Scale.Y; + } + + for (int i = 0; i < _staticParts.Count; i++) + { + AccumulateMeshMinMaxY(_staticParts[i].Mesh, ComputeRelativeTransform(_staticParts[i].Pivot, Root), out _, out float pyMax); + if (pyMax > maxY) maxY = pyMax; + } + for (int i = 0; i < _allCellParts.Count; i++) + { + var pb = _allCellParts[i]; + if (!pb.Detached) + { + AccumulateMeshMinMaxY(pb.Mesh, ComputeRelativeTransform(pb.Pivot, Root), out _, out float cyMax); + if (cyMax > maxY) maxY = cyMax; + } + } + for (int i = 0; i < _hardpointList.Count; i++) + { + var bh = _hardpointList[i]; + if (bh.GearNode is null || !GodotObject.IsInstanceValid(bh.GearNode)) + { + continue; + } + Transform3D gearRel = ComputeRelativeTransform(bh.GearNode, Root); + if (bh.ModularParts is { } modParts) + { + for (int p = 0; p < modParts.Length; p++) + { + AccumulateMeshMinMaxY(modParts[p].Mesh, gearRel * modParts[p].LocalToGearPivot, out _, out float pyMax); + if (pyMax > maxY) maxY = pyMax; + } + } + else if (bh.GearMesh is not null) + { + AccumulateMeshMinMaxY(bh.GearMesh, gearRel, out _, out float gyMax); + if (gyMax > maxY) maxY = gyMax; + } + } + + return float.IsFinite(maxY) ? maxY : ModelRoot.Position.Y + _template.MaxY * ModelRoot.Scale.Y; + } + + /// + /// Computes the lowest rendered vertex Y in world/parent space (or space if ). + /// + public float ComputeMinVertexY(float baseWorldY = 0f, bool relativeToModelRoot = false) + { + float minY = float.PositiveInfinity; + Transform3D rootBase = relativeToModelRoot + ? Transform3D.Identity + : new Transform3D(Basis.Identity, new Vector3(0f, baseWorldY, 0f)) * Root.Transform; + + if (_role == VehicleVisualRole.SalvageDrop) + { + ArrayMesh m = _isStaticLod ? _template.SingleSurfaceLodFarMesh : _template.SingleSurfaceStaticMesh; + Transform3D xf = relativeToModelRoot ? Transform3D.Identity : rootBase * ModelRoot.Transform; + AccumulateMeshMinMaxY(m, xf, out minY, out _); + return minY; + } + + Node3D relTarget = relativeToModelRoot ? ModelRoot : Root; + Transform3D baseXf = relativeToModelRoot ? Transform3D.Identity : rootBase; + + for (int i = 0; i < _staticParts.Count; i++) + { + Transform3D xf = baseXf * ComputeRelativeTransform(_staticParts[i].Pivot, relTarget); + AccumulateMeshMinMaxY(_staticParts[i].Mesh, xf, out float pyMin, out _); + if (pyMin < minY) minY = pyMin; + } + for (int i = 0; i < _allCellParts.Count; i++) + { + var pb = _allCellParts[i]; + if (!pb.Detached) + { + Transform3D xf = baseXf * ComputeRelativeTransform(pb.Pivot, relTarget); + AccumulateMeshMinMaxY(pb.Mesh, xf, out float cyMin, out _); + if (cyMin < minY) minY = cyMin; + } + } + return minY; + } + + private static void AccumulateMeshMinMaxY(ArrayMesh mesh, Transform3D xform, out float minY, out float maxY) + { + minY = float.PositiveInfinity; + maxY = float.NegativeInfinity; + int surfCount = mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arrays = mesh.SurfaceGetArrays(s); + if (arrays.Count <= (int)Mesh.ArrayType.Vertex || + arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + for (int v = 0; v < verts.Length; v++) + { + float wy = (xform * verts[v]).Y; + if (wy < minY) minY = wy; + if (wy > maxY) maxY = wy; + } + } + } + + private static bool RayIntersectsAabb(Aabb aabb, Vector3 orig, Vector3 dir) + { + Vector3 min = aabb.Position; + Vector3 max = aabb.End; + float tmin = float.NegativeInfinity; + float tmax = float.PositiveInfinity; + + for (int axis = 0; axis < 3; axis++) + { + float o = orig[axis]; + float d = dir[axis]; + if (MathF.Abs(d) < 1e-7f) + { + if (o < min[axis] || o > max[axis]) return false; + } + else + { + float inv = 1f / d; + float t1 = (min[axis] - o) * inv; + float t2 = (max[axis] - o) * inv; + if (t1 > t2) (t1, t2) = (t2, t1); + tmin = MathF.Max(tmin, t1); + tmax = MathF.Min(tmax, t2); + if (tmin > tmax) return false; + } + } + return tmax >= 0f; + } + + private static bool RayTriangle(Vector3 orig, Vector3 dir, Vector3 v0, Vector3 v1, Vector3 v2, out float t) + { + t = 0f; + Vector3 e1 = v1 - v0; + Vector3 e2 = v2 - v0; + Vector3 pvec = dir.Cross(e2); + float det = e1.Dot(pvec); + if (MathF.Abs(det) < 1e-7f) return false; + float invDet = 1f / det; + Vector3 tvec = orig - v0; + float u = tvec.Dot(pvec) * invDet; + if (u < 0f || u > 1f) return false; + Vector3 qvec = tvec.Cross(e1); + float v = dir.Dot(qvec) * invDet; + if (v < 0f || u + v > 1f) return false; + t = e2.Dot(qvec) * invDet; + return t > 0.01f; + } +} diff --git a/client/VolumetricCompositorEffect.cs b/client/VolumetricCompositorEffect.cs new file mode 100644 index 0000000..debe86c --- /dev/null +++ b/client/VolumetricCompositorEffect.cs @@ -0,0 +1,724 @@ +using System; +using System.Runtime.InteropServices; +using Godot; + +namespace RustToDust.Client; + +/// +/// 4-pass Forward+ Vulkan compute pipeline (PostSky) owning: +/// Pass 0: flow_field_step.glsl (camera-snapped 3m 64x24x64 RGBA16F ping-pong -> ) +/// Pass 1: volumetric_tile_cull.glsl (16x16 half-res tiles + 128-element Bitonic sort) +/// Pass 2: volumetric_raymarch.glsl (sorted monotonic sweep-line + Aetheria curl/triNoise + shock cavity + 2 shadow taps) +/// Pass 3: volumetric_composite.glsl (2x2 bilateral depth upsample pre-tonemap) +/// +public sealed partial class VolumetricCompositorEffect : CompositorEffect +{ + public const int FlowDimX = 64; + public const int FlowDimY = 24; + public const int FlowDimZ = 64; + public const float FlowVoxelSizeMeters = 3.0f; + public const int TileSizeHalfRes = 16; + public const int TileStrideBytes = 112; + public const int FrameUboBytes = 272; + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct VolumetricFrameUbo + { + public Vector4 InvProj0, InvProj1, InvProj2, InvProj3; + public Vector4 CamPosTime; + public Vector4 CamRightAspect; + public Vector4 CamUpTanHalfFov; + public Vector4 CamFwdNearFar; + public Vector4 SunDirIntensity; + public Vector4 SunColorExt; + public Vector4 AmbientColorFog; + public Vector4 ViewportInfo; + public uint HalfW, HalfH, TilesX, FrameIndex; + public Vector4 FlowOriginVoxel; + public Vector4 FlowInvExtentDt; + public int DeltaX, DeltaY, DeltaZ, ImpulseCount; + public uint MaxSteps, MaxIter, IsFullRes, QualityPad; + } + + private readonly Texture3Drd _flowTexRd; + private VolumetricEmitterPool _emitterPool; + + // Atmosphere parameters updated from game thread via volatile/lock + private readonly object _atmoLock = new(); + private Vector3 _sunDir = new Vector3(0.45f, 0.55f, 0.70f).Normalized(); + private float _sunEnergy = 1.25f; + private Color _sunColor = Colors.White; + private Color _ambientColor = new(0.28f, 0.34f, 0.42f); + private float _globalExtinctionScale = 0.28f; + private VfxResolutionScale _resolutionScale = VfxResolutionScale.Half; + private VolumetricSamples _volumetricSamples = VolumetricSamples.Medium; + + // Render-thread RD state + private RenderingDevice? _rd; + private bool _rdInitialized; + private bool _rdFailed; + + private Rid _flowShaderRid, _flowPipeRid; + private Rid _cullShaderRid, _cullPipeRid; + private Rid _marchShaderRid, _marchPipeRid; + private Rid _compShaderRid, _compPipeRid; + + private readonly Rid[] _flowTexRids = new Rid[2]; + private int _flowReadIdx; + private Vector3I _prevFlowVoxelOrigin; + private bool _hasPrevFlowOrigin; + + private Rid _nearestSamplerRid; + private Rid _linearSamplerRid; + private Rid _frameUboRid; + private Rid _emitterSsboRid; + private Rid _impulseSsboRid; + private Rid _tileSsboRid; + private int _tileSsboCapacityTiles; + + private Rid _halfVolRid; + private Vector2I _halfVolSize; + private uint _frameCounter; + + // Pre-allocated CPU staging buffers (zero per-frame allocations) + private readonly byte[] _uboBytes = new byte[FrameUboBytes]; + private readonly byte[] _emitterUploadBytes = new byte[VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes]; + private readonly byte[] _impulseUploadBytes = new byte[VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes]; + + // Lightweight RD timestamp telemetry (populated when ProfilingEnabled == true) + public bool ProfilingEnabled { get; set; } + private ulong _lastSampledTimestampFrame = ulong.MaxValue; + public double LastFlowGpuMs { get; private set; } + public double LastCullGpuMs { get; private set; } + public double LastMarchGpuMs { get; private set; } + public double LastCompGpuMs { get; private set; } + public double LastTotalGpuMs => LastFlowGpuMs + LastCullGpuMs + LastMarchGpuMs + LastCompGpuMs; + public Vector2I LastMarchSize { get; private set; } + public int CurrentMaxSteps { get; private set; } = 10; + public int CurrentMaxIter { get; private set; } = 15; + + public VolumetricCompositorEffect() : this(new Texture3Drd(), new VolumetricEmitterPool()) + { + } + + public VolumetricCompositorEffect(Texture3Drd flowTexRd, VolumetricEmitterPool emitterPool) + { + _flowTexRd = flowTexRd; + _emitterPool = emitterPool; + EffectCallbackType = EffectCallbackTypeEnum.PostSky; + AccessResolvedColor = true; + AccessResolvedDepth = true; + Enabled = true; + } + + public void SetEmitterPool(VolumetricEmitterPool pool) + { + _emitterPool = pool ?? throw new ArgumentNullException(nameof(pool)); + } + + public void ApplyGraphicsSettings(GraphicsSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + lock (_atmoLock) + { + _resolutionScale = settings.VfxResolution; + _volumetricSamples = settings.VolumetricSamples; + } + } + + public void SetAtmosphere(Vector3 sunDir, float sunEnergy, Color sunColor, Color ambientColor, float extinctionScale = 0.28f) + { + lock (_atmoLock) + { + _sunDir = sunDir.LengthSquared() > 1e-5f ? sunDir.Normalized() : Vector3.Up; + _sunEnergy = MathF.Max(0.05f, sunEnergy); + _sunColor = sunColor; + _ambientColor = ambientColor; + _globalExtinctionScale = Math.Clamp(extinctionScale, 0.05f, 2.0f); + } + } + + public override void _RenderCallback(int effectCallbackType, RenderData renderData) + { + if (effectCallbackType != (int)EffectCallbackTypeEnum.PostSky || _rdFailed) + { + return; + } + + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null) + { + return; + } + + if (!_rdInitialized && !TryInitializeRd(rd)) + { + _rdFailed = true; + return; + } + + if (renderData.GetRenderSceneBuffers() is not RenderSceneBuffersRD sceneBuffers) + { + return; + } + + RenderSceneData sceneData = renderData.GetRenderSceneData(); + if (sceneData is null) + { + return; + } + + Vector2I fullSize = sceneBuffers.GetInternalSize(); + if (fullSize.X < 2 || fullSize.Y < 2) + { + return; + } + + VfxResolutionScale resScale; + VolumetricSamples volSamples; + Vector3 sunDir; + float sunEnergy; + Color sunCol, ambCol; + float extScale; + lock (_atmoLock) + { + resScale = _resolutionScale; + volSamples = _volumetricSamples; + sunDir = _sunDir; + sunEnergy = _sunEnergy; + sunCol = _sunColor; + ambCol = _ambientColor; + extScale = _globalExtinctionScale; + } + + bool isFullRes = resScale == VfxResolutionScale.Full; + float resFactor = GraphicsSettings.GetResolutionScaleFactor(resScale); + Vector2I marchSize = isFullRes + ? fullSize + : new Vector2I( + Math.Max(1, (int)MathF.Round(fullSize.X * resFactor)), + Math.Max(1, (int)MathF.Round(fullSize.Y * resFactor))); + int tilesX = Math.Max(1, (marchSize.X + TileSizeHalfRes - 1) / TileSizeHalfRes); + int tilesY = Math.Max(1, (marchSize.Y + TileSizeHalfRes - 1) / TileSizeHalfRes); + int totalTiles = tilesX * tilesY; + (int maxSteps, int maxIter) = GraphicsSettings.GetVolumetricStepBudget(volSamples); + + LastMarchSize = marchSize; + CurrentMaxSteps = maxSteps; + CurrentMaxIter = maxIter; + + EnsureHalfResAndTileBuffers(rd, marchSize, totalTiles); + + uint viewCount = Math.Max(1u, sceneData.GetViewCount()); + const uint view = 0u; + + Transform3D camXf = sceneData.GetCamTransform(); + Projection rawProj = sceneData.GetViewProjection(view); + + // Validate reverse-Z projection convention [1..0] + Vector4 testNear = rawProj * new Vector4(0f, 0f, -0.05f, 1f); + Projection revProj = (testNear.W != 0f && (testNear.Z / testNear.W) < 0f) + ? Projection.CreateDepthCorrection(flipY: false) * rawProj + : rawProj; + Projection invProj = revProj.Inverse(); + + Vector4 nearView = invProj * new Vector4(0f, 0f, 1f, 1f); + Vector4 farView = invProj * new Vector4(0f, 0f, 0f, 1f); + float zNear = MathF.Max(0.01f, MathF.Abs(nearView.W) > 1e-6f ? -nearView.Z / nearView.W : 0.05f); + float zFar = MathF.Abs(farView.W) > 1e-6f && (-farView.Z / farView.W) > zNear + 1f + ? -farView.Z / farView.W + : 4800f; + + float tanHalfFovY = 1f / MathF.Max(1e-4f, MathF.Abs(rawProj.Y.Y)); + float aspect = MathF.Abs(rawProj.Y.Y) / MathF.Max(1e-4f, MathF.Abs(rawProj.X.X)); + + Vector3 camPos = camXf.Origin; + Vector3 camRight = camXf.Basis.X.Normalized(); + Vector3 camUp = camXf.Basis.Y.Normalized(); + Vector3 camFwd = (-camXf.Basis.Z).Normalized(); + + _emitterPool.CopyRenderSnapshot( + _emitterUploadBytes, + _impulseUploadBytes, + out int emitterCount, + out int impulseCount, + out float elapsedTime, + out float dt); + + Vector3I newVoxelOrigin = new( + (int)MathF.Floor((camPos.X - 96f) / FlowVoxelSizeMeters), + (int)MathF.Floor((camPos.Y - 24f) / FlowVoxelSizeMeters), + (int)MathF.Floor((camPos.Z - 96f) / FlowVoxelSizeMeters)); + Vector3I flowDelta = _hasPrevFlowOrigin ? (newVoxelOrigin - _prevFlowVoxelOrigin) : Vector3I.Zero; + _prevFlowVoxelOrigin = newVoxelOrigin; + _hasPrevFlowOrigin = true; + + Vector3 flowOriginWorld = new( + newVoxelOrigin.X * FlowVoxelSizeMeters, + newVoxelOrigin.Y * FlowVoxelSizeMeters, + newVoxelOrigin.Z * FlowVoxelSizeMeters); + Vector3 flowInvExtent = new( + 1f / (FlowDimX * FlowVoxelSizeMeters), + 1f / (FlowDimY * FlowVoxelSizeMeters), + 1f / (FlowDimZ * FlowVoxelSizeMeters)); + + _frameCounter++; + var ubo = new VolumetricFrameUbo + { + InvProj0 = invProj.X, + InvProj1 = invProj.Y, + InvProj2 = invProj.Z, + InvProj3 = invProj.W, + CamPosTime = new Vector4(camPos.X, camPos.Y, camPos.Z, elapsedTime), + CamRightAspect = new Vector4(camRight.X, camRight.Y, camRight.Z, aspect), + CamUpTanHalfFov = new Vector4(camUp.X, camUp.Y, camUp.Z, tanHalfFovY), + CamFwdNearFar = new Vector4(camFwd.X, camFwd.Y, camFwd.Z, 0f), + SunDirIntensity = new Vector4(sunDir.X, sunDir.Y, sunDir.Z, sunEnergy), + SunColorExt = new Vector4(sunCol.R, sunCol.G, sunCol.B, extScale), + AmbientColorFog = new Vector4(ambCol.R, ambCol.G, ambCol.B, zNear), + ViewportInfo = new Vector4(fullSize.X, fullSize.Y, zFar, emitterCount), + HalfW = (uint)marchSize.X, + HalfH = (uint)marchSize.Y, + TilesX = (uint)tilesX, + FrameIndex = _frameCounter, + FlowOriginVoxel = new Vector4(flowOriginWorld.X, flowOriginWorld.Y, flowOriginWorld.Z, FlowVoxelSizeMeters), + FlowInvExtentDt = new Vector4(flowInvExtent.X, flowInvExtent.Y, flowInvExtent.Z, dt), + DeltaX = flowDelta.X, + DeltaY = flowDelta.Y, + DeltaZ = flowDelta.Z, + ImpulseCount = impulseCount, + MaxSteps = (uint)maxSteps, + MaxIter = (uint)maxIter, + IsFullRes = isFullRes ? 1u : 0u, + QualityPad = 0u + }; + + MemoryMarshal.Write(_uboBytes, in ubo); + rd.BufferUpdate(_frameUboRid, 0, FrameUboBytes, _uboBytes); + + if (emitterCount > 0) + { + uint emBytes = (uint)(emitterCount * VolumetricEmitterPool.EmitterStrideBytes); + rd.BufferUpdate(_emitterSsboRid, 0, emBytes, _emitterUploadBytes); + } + if (impulseCount > 0) + { + uint impBytes = (uint)(impulseCount * VolumetricEmitterPool.ImpulseStrideBytes); + rd.BufferUpdate(_impulseSsboRid, 0, impBytes, _impulseUploadBytes); + } + + int writeIdx = 1 - _flowReadIdx; + Rid prevFlowRid = _flowTexRids[_flowReadIdx]; + Rid nextFlowRid = _flowTexRids[writeIdx]; + + bool captureThisFrame = ProfilingEnabled && (_frameCounter & 7u) == 0u && _frameCounter >= 24u && rd.GetCapturedTimestampsCount() < 180; + if (ProfilingEnabled) + { + SamplePreviousFrameTimestamps(rd); + } + if (captureThisFrame) + { + rd.CaptureTimestamp("Cut10b_FlowStart"); + } + + // Compute pass list (Pass 0 always; Passes 1-3 whenever active emitters exist) + long computeList = rd.ComputeListBegin(); + + // Pass 0: flow_field_step (64x24x64 / 8x4x8 = 8x6x8 groups) + Rid flowSet = GetPass0UniformSet(prevFlowRid, nextFlowRid); + rd.ComputeListBindComputePipeline(computeList, _flowPipeRid); + rd.ComputeListBindUniformSet(computeList, flowSet, 0); + rd.ComputeListDispatch(computeList, 8, 6, 8); + + if (emitterCount > 0) + { + for (uint v = 0; v < viewCount; v++) + { + Rid colorLayer = sceneBuffers.GetColorLayer(v, false); + Rid depthLayer = sceneBuffers.GetDepthLayer(v, false); + if (!colorLayer.IsValid || !depthLayer.IsValid) + { + continue; + } + + // Pass 1: volumetric_tile_cull + rd.ComputeListAddBarrier(computeList); + if (captureThisFrame && v == 0) + { + rd.ComputeListEnd(); + rd.CaptureTimestamp("Cut10b_CullStart"); + computeList = rd.ComputeListBegin(); + } + + Rid cullSet = GetPass1UniformSet(depthLayer); + rd.ComputeListBindComputePipeline(computeList, _cullPipeRid); + rd.ComputeListBindUniformSet(computeList, cullSet, 0); + rd.ComputeListDispatch(computeList, (uint)tilesX, (uint)tilesY, 1); + + // Pass 2: volumetric_raymarch (reading freshly updated nextFlowRid!) + rd.ComputeListAddBarrier(computeList); + if (captureThisFrame && v == 0) + { + rd.ComputeListEnd(); + rd.CaptureTimestamp("Cut10b_MarchStart"); + computeList = rd.ComputeListBegin(); + } + + Rid marchSet = GetPass2UniformSet(depthLayer, nextFlowRid); + rd.ComputeListBindComputePipeline(computeList, _marchPipeRid); + rd.ComputeListBindUniformSet(computeList, marchSet, 0); + rd.ComputeListDispatch(computeList, (uint)tilesX, (uint)tilesY, 1); + + // Pass 3: volumetric_composite (2x2 bilateral depth upsample -> colorLayer) + rd.ComputeListAddBarrier(computeList); + if (captureThisFrame && v == 0) + { + rd.ComputeListEnd(); + rd.CaptureTimestamp("Cut10b_CompStart"); + computeList = rd.ComputeListBegin(); + } + + Rid compSet = GetPass3UniformSet(depthLayer, colorLayer); + rd.ComputeListBindComputePipeline(computeList, _compPipeRid); + rd.ComputeListBindUniformSet(computeList, compSet, 0); + uint compGroupsX = (uint)((fullSize.X + 15) / 16); + uint compGroupsY = (uint)((fullSize.Y + 15) / 16); + rd.ComputeListDispatch(computeList, compGroupsX, compGroupsY, 1); + } + } + + rd.ComputeListEnd(); + + if (captureThisFrame) + { + rd.CaptureTimestamp("Cut10b_End"); + } + + // Advance ping-pong & update global Texture3Drd + flow origin for GPUParticles3D + _flowReadIdx = writeIdx; + _flowTexRd.TextureRdRid = nextFlowRid; + RenderingServer.GlobalShaderParameterSet("rtd_flow_origin", flowOriginWorld); + RenderingServer.GlobalShaderParameterSet("rtd_flow_inv_extent", flowInvExtent); + } + + private void SamplePreviousFrameTimestamps(RenderingDevice rd) + { + uint count = rd.GetCapturedTimestampsCount(); + if (count == 0) + { + return; + } + + ulong tsFrame = rd.GetCapturedTimestampsFrame(); + if (tsFrame == _lastSampledTimestampFrame) + { + return; + } + _lastSampledTimestampFrame = tsFrame; + + ulong tFlow = 0, tCull = 0, tMarch = 0, tComp = 0, tEnd = 0; + for (uint i = 0; i < count; i++) + { + string name = rd.GetCapturedTimestampName(i); + switch (name) + { + case "Cut10b_FlowStart": tFlow = rd.GetCapturedTimestampGpuTime(i); break; + case "Cut10b_CullStart": tCull = rd.GetCapturedTimestampGpuTime(i); break; + case "Cut10b_MarchStart": tMarch = rd.GetCapturedTimestampGpuTime(i); break; + case "Cut10b_CompStart": tComp = rd.GetCapturedTimestampGpuTime(i); break; + case "Cut10b_End": tEnd = rd.GetCapturedTimestampGpuTime(i); break; + } + } + + // Godot 4.7 Vulkan GetCapturedTimestampGpuTime empirically returns nanoseconds (confirmed vs --gpu-profile; GodotSharp.xml's "microseconds" doc is stale) + if (tFlow > 0 && tEnd >= tFlow) + { + if (tCull > tFlow && tMarch > tCull && tComp > tMarch && tEnd >= tComp) + { + LastFlowGpuMs = (tCull - tFlow) / 1_000_000.0; + LastCullGpuMs = (tMarch - tCull) / 1_000_000.0; + LastMarchGpuMs = (tComp - tMarch) / 1_000_000.0; + LastCompGpuMs = (tEnd - tComp) / 1_000_000.0; + } + else + { + LastFlowGpuMs = (tEnd - tFlow) / 1_000_000.0; + LastCullGpuMs = 0.0; + LastMarchGpuMs = 0.0; + LastCompGpuMs = 0.0; + } + } + } + + private bool TryInitializeRd(RenderingDevice rd) + { + _rd = rd; + + if (!TryCompileCompute(rd, "res://flow_field_step.glsl", "flow_field_step", out _flowShaderRid, out _flowPipeRid) || + !TryCompileCompute(rd, "res://volumetric_tile_cull.glsl", "volumetric_tile_cull", out _cullShaderRid, out _cullPipeRid) || + !TryCompileCompute(rd, "res://volumetric_raymarch.glsl", "volumetric_raymarch", out _marchShaderRid, out _marchPipeRid) || + !TryCompileCompute(rd, "res://volumetric_composite.glsl", "volumetric_composite", out _compShaderRid, out _compPipeRid)) + { + return false; + } + + var nearestState = new RDSamplerState + { + MinFilter = RenderingDevice.SamplerFilter.Nearest, + MagFilter = RenderingDevice.SamplerFilter.Nearest, + RepeatU = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatV = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatW = RenderingDevice.SamplerRepeatMode.ClampToEdge + }; + _nearestSamplerRid = rd.SamplerCreate(nearestState); + + var linearState = new RDSamplerState + { + MinFilter = RenderingDevice.SamplerFilter.Linear, + MagFilter = RenderingDevice.SamplerFilter.Linear, + RepeatU = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatV = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatW = RenderingDevice.SamplerRepeatMode.ClampToEdge + }; + _linearSamplerRid = rd.SamplerCreate(linearState); + + var flowFmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type3D, + Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat, + Width = FlowDimX, + Height = FlowDimY, + Depth = FlowDimZ, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit + }; + byte[] zero3d = new byte[FlowDimX * FlowDimY * FlowDimZ * 8]; + var initArr = new Godot.Collections.Array { zero3d }; + _flowTexRids[0] = rd.TextureCreate(flowFmt, new RDTextureView(), initArr); + _flowTexRids[1] = rd.TextureCreate(flowFmt, new RDTextureView(), initArr); + _flowReadIdx = 0; + _flowTexRd.TextureRdRid = _flowTexRids[0]; + + _frameUboRid = rd.UniformBufferCreate(FrameUboBytes, new byte[FrameUboBytes]); + _emitterSsboRid = rd.StorageBufferCreate( + (uint)(VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes), + new byte[VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes]); + _impulseSsboRid = rd.StorageBufferCreate( + (uint)(VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes), + new byte[VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes]); + + _rdInitialized = true; + return true; + } + + private static bool TryCompileCompute( + RenderingDevice rd, + string resPath, + string debugName, + out Rid shaderRid, + out Rid pipeRid) + { + shaderRid = new Rid(); + pipeRid = new Rid(); + + string source = FileAccess.GetFileAsString(resPath); + if (string.IsNullOrWhiteSpace(source)) + { + GD.PrintErr($"VolumetricCompositorEffect: missing compute shader '{resPath}'"); + return false; + } + + using var rdSrc = new RDShaderSource + { + Language = RenderingDevice.ShaderLanguage.Glsl, + SourceCompute = source + }; + using RDShaderSpirV spirv = rd.ShaderCompileSpirVFromSource(rdSrc, allowCache: true); + string err = spirv.CompileErrorCompute; + if (!string.IsNullOrEmpty(err)) + { + GD.PrintErr($"VolumetricCompositorEffect: SPIR-V compile error in '{resPath}': {err}"); + return false; + } + + shaderRid = rd.ShaderCreateFromSpirV(spirv, debugName); + if (!shaderRid.IsValid) + { + GD.PrintErr($"VolumetricCompositorEffect: ShaderCreateFromSpirV failed for '{resPath}'"); + return false; + } + pipeRid = rd.ComputePipelineCreate(shaderRid); + if (!pipeRid.IsValid) + { + GD.PrintErr($"VolumetricCompositorEffect: ComputePipelineCreate failed for '{resPath}'"); + return false; + } + return true; + } + + private void EnsureHalfResAndTileBuffers(RenderingDevice rd, Vector2I halfSize, int totalTiles) + { + if (!_halfVolRid.IsValid || _halfVolSize != halfSize) + { + if (_halfVolRid.IsValid) + { + rd.FreeRid(_halfVolRid); + } + var fmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat, + Width = (uint)halfSize.X, + Height = (uint)halfSize.Y, + Depth = 1, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit + }; + _halfVolRid = rd.TextureCreate(fmt, new RDTextureView()); + _halfVolSize = halfSize; + } + + if (!_tileSsboRid.IsValid || _tileSsboCapacityTiles < totalTiles) + { + if (_tileSsboRid.IsValid) + { + rd.FreeRid(_tileSsboRid); + } + _tileSsboCapacityTiles = Math.Max(totalTiles, 2048); + uint sizeBytes = (uint)(_tileSsboCapacityTiles * TileStrideBytes); + _tileSsboRid = rd.StorageBufferCreate(sizeBytes, new byte[sizeBytes]); + } + } + + private Rid GetPass0UniformSet(Rid prevFlowRid, Rid nextFlowRid) + { + var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 }; + u0.AddId(_frameUboRid); + var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 }; + u1.AddId(_impulseSsboRid); + var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 2 }; + u2.AddId(_linearSamplerRid); + u2.AddId(prevFlowRid); + var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 3 }; + u3.AddId(nextFlowRid); + return UniformSetCacheRD.GetCache(_flowShaderRid, 0, new Godot.Collections.Array { u0, u1, u2, u3 }); + } + + private Rid GetPass1UniformSet(Rid depthLayer) + { + var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 }; + u0.AddId(_frameUboRid); + var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 }; + u1.AddId(_emitterSsboRid); + var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 2 }; + u2.AddId(_tileSsboRid); + var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 3 }; + u3.AddId(_nearestSamplerRid); + u3.AddId(depthLayer); + return UniformSetCacheRD.GetCache(_cullShaderRid, 0, new Godot.Collections.Array { u0, u1, u2, u3 }); + } + + private Rid GetPass2UniformSet(Rid depthLayer, Rid flowTexRid) + { + var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 }; + u0.AddId(_frameUboRid); + var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 }; + u1.AddId(_emitterSsboRid); + var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 2 }; + u2.AddId(_tileSsboRid); + var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 3 }; + u3.AddId(_nearestSamplerRid); + u3.AddId(depthLayer); + var u4 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 4 }; + u4.AddId(_linearSamplerRid); + u4.AddId(flowTexRid); + var u5 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 5 }; + u5.AddId(_halfVolRid); + return UniformSetCacheRD.GetCache(_marchShaderRid, 0, new Godot.Collections.Array { u0, u1, u2, u3, u4, u5 }); + } + + private Rid GetPass3UniformSet(Rid depthLayer, Rid colorLayer) + { + var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 }; + u0.AddId(_frameUboRid); + var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 1 }; + u1.AddId(_nearestSamplerRid); + u1.AddId(depthLayer); + var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 2 }; + u2.AddId(_nearestSamplerRid); + u2.AddId(_halfVolRid); + var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 3 }; + u3.AddId(colorLayer); + var u4 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 4 }; + u4.AddId(_tileSsboRid); + return UniformSetCacheRD.GetCache(_compShaderRid, 0, new Godot.Collections.Array { u0, u1, u2, u3, u4 }); + } + + public void DisposeRdResources() + { + if (!_rdInitialized || _rd is null) + { + return; + } + _rdInitialized = false; + Enabled = false; + + if (_flowTexRd is not null) + { + _flowTexRd.TextureRdRid = new Rid(); + } + + FreeIfValid(_rd, ref _flowTexRids[0]); + FreeIfValid(_rd, ref _flowTexRids[1]); + FreeIfValid(_rd, ref _halfVolRid); + FreeIfValid(_rd, ref _frameUboRid); + FreeIfValid(_rd, ref _emitterSsboRid); + FreeIfValid(_rd, ref _impulseSsboRid); + FreeIfValid(_rd, ref _tileSsboRid); + FreeIfValid(_rd, ref _nearestSamplerRid); + FreeIfValid(_rd, ref _linearSamplerRid); + + // Free shaders (automatically cleans up dependent pipelines in Godot RD) + _flowPipeRid = new Rid(); + _cullPipeRid = new Rid(); + _marchPipeRid = new Rid(); + _compPipeRid = new Rid(); + FreeIfValid(_rd, ref _flowShaderRid); + FreeIfValid(_rd, ref _cullShaderRid); + FreeIfValid(_rd, ref _marchShaderRid); + FreeIfValid(_rd, ref _compShaderRid); + + _rd = null; + } + + public override void _Notification(int what) + { + if (what != NotificationPredelete) + { + return; + } + + // Only release if still alive and not already cleaned up in AtmosphereSystem._ExitTree + if (_flowTexRd is not null) + { + _flowTexRd.TextureRdRid = new Rid(); + } + if (_rdInitialized && RenderingServer.GetRenderingDevice() is not null) + { + DisposeRdResources(); + } + } + + private static void FreeIfValid(RenderingDevice rd, ref Rid rid) + { + if (rid.IsValid) + { + rd.FreeRid(rid); + rid = new Rid(); + } + } +} diff --git a/client/VolumetricEmitterPool.cs b/client/VolumetricEmitterPool.cs new file mode 100644 index 0000000..b6d567b --- /dev/null +++ b/client/VolumetricEmitterPool.cs @@ -0,0 +1,1027 @@ +using System; +using System.Runtime.InteropServices; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// CPU authority for all volumetric smoke, fire, retro-plume, plasma, and thermal-pool emitters +/// (<= 128) plus 3D flow-field impulses (<= 64) consumed by . +/// Packs std430-aligned snapshots under a short lock for zero-allocation GPU upload. +/// +public sealed class VolumetricEmitterPool +{ + public const int MaxEmitters = 128; + public const int MaxFlowImpulses = 64; + public const int EmitterStrideBytes = 64; + public const int ImpulseStrideBytes = 48; + + public const uint EmitterSmoke = 0u; + public const uint EmitterFireball = 1u; + public const uint EmitterRetroPlume = 2u; + public const uint EmitterPlasmaBurst = 3u; + public const uint EmitterThermalPool = 4u; + + public const uint FlowShockShell = 0u; + public const uint FlowRetroDownwash = 1u; + public const uint FlowThermalUpdraft = 2u; + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + public struct GpuVolumetricEmitter + { + public float Ax, Ay, Az, RadiusA; + public float Bx, By, Bz, Temp; + public float DensityMult, RadiusB, FlowSpeed, PackedFlags; + public float R, G, B, Softness; + } + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + public struct GpuFlowImpulse + { + public float PosX, PosY, PosZ, Radius; + public float DirX, DirY, DirZ, Strength; + public float ShellThickness, ShockPressure, TypeBitsFloat, FalloffExp; + } + + private struct EmitterSlot + { + public bool Active; + public uint Type; + public int Priority; + public byte Seed; + public Vector3 StartPos; + public Vector3 EndPos; + public Vector3 VelStart; + public Vector3 VelEnd; + public float Drag; + public float Buoyancy; + public float RadiusA0; + public float RadiusA1; + public float RadiusB0; + public float RadiusB1; + public float Density0; + public float Density1; + public float Temp0; + public float Temp1; + public float FlowSpeed; + public float Softness; + public Color Tint0; + public Color Tint1; + public float Age; + public float Lifetime; + } + + private struct ImpulseSlot + { + public bool Active; + public uint Type; + public int Priority; + public Vector3 Pos; + public Vector3 Dir; + public float Radius0; + public float Radius1; + public float Strength0; + public float Strength1; + public float ShellThickness; + public float ShockPressure0; + public float ShockPressure1; + public float FalloffExp; + public float Age; + public float Lifetime; + } + + private readonly EmitterSlot[] _emitters = new EmitterSlot[MaxEmitters]; + private readonly ImpulseSlot[] _impulses = new ImpulseSlot[MaxFlowImpulses]; + + private readonly object _sync = new(); + private readonly byte[] _emitterBytes = new byte[MaxEmitters * EmitterStrideBytes]; + private readonly byte[] _impulseBytes = new byte[MaxFlowImpulses * ImpulseStrideBytes]; + private int _packedEmitterCount; + private int _packedImpulseCount; + private float _elapsedTime; + private float _lastStepDt = 1f / 60f; + private uint _rng = 0x51F29D4Bu; + private byte _seedSeq; + + public int ActiveEmitterCount { get; private set; } + public int ActiveImpulseCount { get; private set; } + + public void ClearAll() + { + Array.Clear(_emitters, 0, _emitters.Length); + Array.Clear(_impulses, 0, _impulses.Length); + ActiveEmitterCount = 0; + ActiveImpulseCount = 0; + lock (_sync) + { + _packedEmitterCount = 0; + _packedImpulseCount = 0; + Array.Clear(_emitterBytes, 0, _emitterBytes.Length); + Array.Clear(_impulseBytes, 0, _impulseBytes.Length); + } + } + + public void Step(float dt) + { + float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; + _elapsedTime += stepDt; + + Span gpuEmitters = stackalloc GpuVolumetricEmitter[MaxEmitters]; + int emCount = 0; + for (int i = 0; i < MaxEmitters; i++) + { + ref EmitterSlot s = ref _emitters[i]; + if (!s.Active) + { + continue; + } + if (stepDt > 0f) + { + s.Age += stepDt; + if (s.Age >= s.Lifetime) + { + s.Active = false; + continue; + } + if (s.Drag > 0f) + { + float damp = MathF.Exp(-s.Drag * stepDt); + s.VelStart *= damp; + s.VelEnd *= damp; + } + s.VelStart.Y += s.Buoyancy * stepDt; + s.VelEnd.Y += s.Buoyancy * stepDt; + s.StartPos += s.VelStart * stepDt; + s.EndPos += s.VelEnd * stepDt; + } + + float t = Math.Clamp(s.Age / MathF.Max(0.01f, s.Lifetime), 0f, 1f); + float density = Mathf.Lerp(s.Density0, s.Density1, t); + // Smooth fade-out tail in last 25% of lifetime + if (t > 0.75f) + { + density *= 1f - (t - 0.75f) / 0.25f; + } + if (density <= 0.002f) + { + continue; + } + + float rA = MathF.Max(0.25f, Mathf.Lerp(s.RadiusA0, s.RadiusA1, t)); + float rB = MathF.Max(0.25f, Mathf.Lerp(s.RadiusB0, s.RadiusB1, t)); + float tempT = MathF.Pow(t, 1.45f); + float temp = MathF.Max(0f, Mathf.Lerp(s.Temp0, s.Temp1, tempT)); + Color tint = s.Tint0.Lerp(s.Tint1, t); + + uint ageByte = (uint)Math.Clamp((int)(t * 255f), 0, 255); + uint packedFlags = (s.Type & 0xFu) | (ageByte << 4) | ((uint)s.Seed << 12); + + gpuEmitters[emCount++] = new GpuVolumetricEmitter + { + Ax = s.StartPos.X, + Ay = s.StartPos.Y, + Az = s.StartPos.Z, + RadiusA = rA, + Bx = s.EndPos.X, + By = s.EndPos.Y, + Bz = s.EndPos.Z, + Temp = temp, + DensityMult = density, + RadiusB = rB, + FlowSpeed = s.FlowSpeed, + PackedFlags = BitConverter.UInt32BitsToSingle(packedFlags), + R = MathF.Max(0f, tint.R), + G = MathF.Max(0f, tint.G), + B = MathF.Max(0f, tint.B), + Softness = s.Softness + }; + } + + Span gpuImpulses = stackalloc GpuFlowImpulse[MaxFlowImpulses]; + int impCount = 0; + for (int i = 0; i < MaxFlowImpulses; i++) + { + ref ImpulseSlot s = ref _impulses[i]; + if (!s.Active) + { + continue; + } + if (stepDt > 0f) + { + s.Age += stepDt; + if (s.Age >= s.Lifetime) + { + s.Active = false; + continue; + } + } + + float t = Math.Clamp(s.Age / MathF.Max(0.01f, s.Lifetime), 0f, 1f); + float radius = MathF.Max(0.5f, Mathf.Lerp(s.Radius0, s.Radius1, t)); + float strength = Mathf.Lerp(s.Strength0, s.Strength1, t); + float pressure = MathF.Max(0f, Mathf.Lerp(s.ShockPressure0, s.ShockPressure1, t)); + + gpuImpulses[impCount++] = new GpuFlowImpulse + { + PosX = s.Pos.X, + PosY = s.Pos.Y, + PosZ = s.Pos.Z, + Radius = radius, + DirX = s.Dir.X, + DirY = s.Dir.Y, + DirZ = s.Dir.Z, + Strength = strength, + ShellThickness = s.ShellThickness, + ShockPressure = pressure, + TypeBitsFloat = BitConverter.UInt32BitsToSingle(s.Type), + FalloffExp = s.FalloffExp + }; + } + + ActiveEmitterCount = emCount; + ActiveImpulseCount = impCount; + + lock (_sync) + { + _packedEmitterCount = emCount; + _packedImpulseCount = impCount; + if (stepDt > 0f) + { + _lastStepDt = stepDt; + } + if (emCount > 0) + { + MemoryMarshal.AsBytes(gpuEmitters.Slice(0, emCount)).CopyTo(_emitterBytes); + } + if (impCount > 0) + { + MemoryMarshal.AsBytes(gpuImpulses.Slice(0, impCount)).CopyTo(_impulseBytes); + } + } + } + + public void CopyRenderSnapshot( + byte[] dstEmitters, + byte[] dstImpulses, + out int emitterCount, + out int impulseCount, + out float elapsedTime, + out float dt) + { + lock (_sync) + { + emitterCount = _packedEmitterCount; + impulseCount = _packedImpulseCount; + elapsedTime = _elapsedTime; + dt = _lastStepDt; + if (emitterCount > 0) + { + Buffer.BlockCopy(_emitterBytes, 0, dstEmitters, 0, emitterCount * EmitterStrideBytes); + } + if (impulseCount > 0) + { + Buffer.BlockCopy(_impulseBytes, 0, dstImpulses, 0, impulseCount * ImpulseStrideBytes); + } + } + } + + public void SpawnEmitter( + uint type, + Vector3 startPos, + Vector3 endPos, + Vector3 velStart, + Vector3 velEnd, + float radiusA0, + float radiusA1, + float radiusB0, + float radiusB1, + float density0, + float density1, + float temp0, + float temp1, + Color tint0, + Color tint1, + float lifetime, + float flowSpeed = 0.55f, + float softness = 0.36f, + float drag = 1.2f, + float buoyancy = 0.45f, + int priority = 5) + { + int slot = FindOrEvictEmitterSlot(priority); + if (slot < 0) + { + return; + } + _emitters[slot] = new EmitterSlot + { + Active = true, + Type = type, + Priority = priority, + Seed = _seedSeq++, + StartPos = startPos, + EndPos = endPos, + VelStart = velStart, + VelEnd = velEnd, + Drag = drag, + Buoyancy = buoyancy, + RadiusA0 = radiusA0, + RadiusA1 = radiusA1, + RadiusB0 = radiusB0, + RadiusB1 = radiusB1, + Density0 = density0, + Density1 = density1, + Temp0 = temp0, + Temp1 = temp1, + FlowSpeed = flowSpeed, + Softness = softness, + Tint0 = tint0, + Tint1 = tint1, + Age = 0f, + Lifetime = MathF.Max(0.05f, lifetime) + }; + ActiveEmitterCount = CountActiveEmitters(); + } + + public void SpawnFlowImpulse( + uint type, + Vector3 pos, + Vector3 dir, + float radius0, + float radius1, + float strength0, + float strength1, + float shellThickness, + float shockPressure0, + float shockPressure1, + float lifetime, + float falloffExp = 1.6f, + int priority = 5) + { + int slot = FindOrEvictImpulseSlot(priority); + if (slot < 0) + { + return; + } + _impulses[slot] = new ImpulseSlot + { + Active = true, + Type = type, + Priority = priority, + Pos = pos, + Dir = dir.LengthSquared() > 1e-5f ? dir.Normalized() : Vector3.Up, + Radius0 = radius0, + Radius1 = radius1, + Strength0 = strength0, + Strength1 = strength1, + ShellThickness = shellThickness, + ShockPressure0 = shockPressure0, + ShockPressure1 = shockPressure1, + FalloffExp = falloffExp, + Age = 0f, + Lifetime = MathF.Max(0.04f, lifetime) + }; + ActiveImpulseCount = CountActiveImpulses(); + } + + public void EmitChassisExplosion(Vector3 pos, float massKg, Color groundTint) + { + Color gLin = groundTint.SrgbToLinear(); + float scale = Math.Clamp(massKg / 2800f, 0.85f, 1.55f); + // Primary fireball -> rising billowing soot capsule (3.5s) + SpawnEmitter( + EmitterFireball, + startPos: pos + new Vector3(0f, 0.4f, 0f), + endPos: pos + new Vector3(NextSigned() * 0.4f, 2.2f * scale, NextSigned() * 0.4f), + velStart: new Vector3(NextSigned() * 0.6f, 1.4f, NextSigned() * 0.6f), + velEnd: new Vector3(NextSigned() * 0.9f, 3.8f * scale, NextSigned() * 0.9f), + radiusA0: 1.8f * scale, + radiusA1: 5.2f * scale, + radiusB0: 2.2f * scale, + radiusB1: 6.4f * scale, + density0: 2.35f, + density1: 0.80f, + temp0: 1.95f, + temp1: 0.10f, + tint0: new Color(0.10f, 0.08f, 0.07f), + tint1: new Color(0.05f, 0.048f, 0.048f), + lifetime: 3.4f, + flowSpeed: 0.85f, + softness: 0.42f, + drag: 0.95f, + buoyancy: 0.90f, + priority: 10); + + // Low ground dust skirt pushed outward by blast + SpawnEmitter( + EmitterSmoke, + startPos: pos - new Vector3(1.5f, 0.1f, 0f), + endPos: pos + new Vector3(1.5f, 0.2f, 0f), + velStart: Vector3.Up * 0.5f, + velEnd: Vector3.Up * 1.1f, + radiusA0: 2.4f * scale, + radiusA1: 6.8f * scale, + radiusB0: 2.4f * scale, + radiusB1: 6.8f * scale, + density0: 0.80f, + density1: 0.10f, + temp0: 0.30f, + temp1: 0f, + tint0: gLin * 0.85f, + tint1: gLin * 0.50f, + lifetime: 2.2f, + flowSpeed: 0.65f, + softness: 0.48f, + drag: 1.4f, + buoyancy: 0.25f, + priority: 9); + + // Expanding radial ShockShell (~90 m/s) + buoyant ThermalUpdraft column + SpawnFlowImpulse( + FlowShockShell, + pos, + Vector3.Up, + radius0: 1.6f * scale, + radius1: 24.0f * scale, + strength0: 90f, + strength1: 14f, + shellThickness: 3.4f, + shockPressure0: 1.4f, + shockPressure1: 0.0f, + lifetime: 0.40f, + priority: 10); + + SpawnFlowImpulse( + FlowThermalUpdraft, + pos, + Vector3.Up, + radius0: 5.5f * scale, + radius1: 8.5f * scale, + strength0: 13.5f, + strength1: 3.5f, + shellThickness: 0f, + shockPressure0: 0f, + shockPressure1: 0f, + lifetime: 3.2f, + priority: 9); + } + + public void EmitExplosiveHit(Vector3 pos, Vector3 normal, Color groundTint, WeaponVisualClass wClass, bool isRecoilless, bool isAirburst) + { + bool isPlasma = wClass == WeaponVisualClass.PlasmaPpc; + bool isSwarm = wClass == WeaponVisualClass.SwarmSmart; + bool isThermal = wClass == WeaponVisualClass.ThermalBeam; + float scale = isRecoilless || wClass == WeaponVisualClass.RocketSalvo + ? 1.35f + : (isAirburst ? 1.15f : (isThermal ? 0.58f : 0.90f)); + + uint type = (isPlasma || isSwarm || isThermal) ? EmitterPlasmaBurst : EmitterFireball; + Color gLin = groundTint.SrgbToLinear(); + Color tint0 = isPlasma + ? new Color(0.10f, 0.52f, 0.72f) + : isSwarm + ? new Color(0.24f, 0.62f, 0.14f) + : isThermal + ? new Color(0.12f, 0.22f, 0.28f) + : gLin * 0.30f + new Color(0.05f, 0.045f, 0.04f); + Color tint1 = new(0.05f, 0.048f, 0.045f); + + float temp0 = (isPlasma || isThermal) ? 1.65f : (isAirburst || isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 2.10f : 1.70f); + float life = (isRecoilless || wClass == WeaponVisualClass.RocketSalvo) ? 1.55f : (isThermal ? 0.50f : 0.95f); + + SpawnEmitter( + type, + startPos: pos + normal * 0.25f, + endPos: pos + normal * (1.2f * scale) + Vector3.Up * (0.9f * scale), + velStart: normal * 1.4f, + velEnd: normal * 2.4f + Vector3.Up * 1.8f, + radiusA0: 0.9f * scale, + radiusA1: 2.8f * scale, + radiusB0: 1.1f * scale, + radiusB1: 3.4f * scale, + density0: 1.85f, + density1: 0.26f, + temp0: temp0, + temp1: 0.0f, + tint0: tint0, + tint1: tint1, + lifetime: life, + flowSpeed: 0.75f, + softness: 0.42f, + drag: 1.4f, + buoyancy: 0.65f, + priority: isRecoilless ? 8 : 6); + + if (isRecoilless || wClass is WeaponVisualClass.RocketSalvo or WeaponVisualClass.PlasmaPpc or WeaponVisualClass.Explosive) + { + SpawnFlowImpulse( + FlowShockShell, + pos, + normal, + radius0: 0.8f, + radius1: 11.0f * scale, + strength0: 54f * scale, + strength1: 8f, + shellThickness: 2.4f, + shockPressure0: 1.05f, + shockPressure1: 0.0f, + lifetime: 0.26f, + priority: 7); + } + } + + public void EmitMuzzleBreechPuff(Vector3 start, Vector3 end, Color groundTint, WeaponVisualClass wClass, bool isRecoilless) + { + Vector3 dir = (end - start).LengthSquared() > 1e-4f ? (end - start).Normalized() : Vector3.Forward; + float scale = isRecoilless ? 1.25f : 0.85f; + Color gLin = groundTint.SrgbToLinear(); + Color smokeTint = new( + Mathf.Lerp(0.24f, gLin.R, 0.35f), + Mathf.Lerp(0.22f, gLin.G, 0.35f), + Mathf.Lerp(0.20f, gLin.B, 0.35f)); + + SpawnEmitter( + EmitterSmoke, + startPos: start + dir * 0.2f, + endPos: start + dir * (2.6f * scale), + velStart: dir * 2.8f + Vector3.Up * 0.8f, + velEnd: dir * 4.2f + Vector3.Up * 1.4f, + radiusA0: 0.48f * scale, + radiusA1: 1.55f * scale, + radiusB0: 0.75f * scale, + radiusB1: 2.15f * scale, + density0: 1.35f, + density1: 0.18f, + temp0: isRecoilless ? 0.65f : 0.35f, + temp1: 0f, + tint0: smokeTint, + tint1: smokeTint * 0.75f, + lifetime: isRecoilless ? 0.82f : 0.50f, + flowSpeed: 0.6f, + softness: 0.44f, + drag: 2.2f, + buoyancy: 0.55f, + priority: 6); + + if (isRecoilless || wClass == WeaponVisualClass.RocketSalvo) + { + // Backblast / recoil puff & impulse + SpawnFlowImpulse( + FlowShockShell, + start, + dir, + radius0: 0.6f, + radius1: 6.5f * scale, + strength0: 28f, + strength1: 4f, + shellThickness: 1.8f, + shockPressure0: 0.55f, + shockPressure1: 0f, + lifetime: 0.18f, + priority: 5); + } + } + + public void EmitOrdnanceDetonation(Vector3 pos, Color accentCol, float splashRadius) + { + float scale = Math.Clamp(splashRadius / 4.2f, 0.75f, 1.85f); + SpawnEmitter( + EmitterFireball, + startPos: pos, + endPos: pos + Vector3.Up * (1.8f * scale), + velStart: Vector3.Up * 1.4f, + velEnd: Vector3.Up * 3.2f, + radiusA0: 1.2f * scale, + radiusA1: 3.8f * scale, + radiusB0: 1.4f * scale, + radiusB1: 4.5f * scale, + density0: 2.15f, + density1: 0.42f, + temp0: 2.05f, + temp1: 0.10f, + tint0: accentCol * 0.32f + new Color(0.07f, 0.06f, 0.055f), + tint1: new Color(0.055f, 0.05f, 0.048f), + lifetime: 2.1f, + flowSpeed: 0.8f, + softness: 0.40f, + drag: 1.1f, + buoyancy: 0.85f, + priority: 9); + + SpawnFlowImpulse( + FlowShockShell, + pos, + Vector3.Up, + radius0: 1.0f, + radius1: Math.Clamp(splashRadius * 3.2f, 9f, 24f), + strength0: 76f, + strength1: 12f, + shellThickness: 2.8f, + shockPressure0: 1.25f, + shockPressure1: 0f, + lifetime: 0.34f, + priority: 9); + + SpawnFlowImpulse( + FlowThermalUpdraft, + pos, + Vector3.Up, + radius0: 3.5f * scale, + radius1: 6.0f * scale, + strength0: 9.5f, + strength1: 2.5f, + shellThickness: 0f, + shockPressure0: 0f, + shockPressure1: 0f, + lifetime: 2.2f, + priority: 7); + } + + public void EmitOrdnanceTrailCapsule(Vector3 tailPos, Vector3 pos, Vector3 vel, Color accentCol, bool isRocket) + { + if (ActiveEmitterCount >= 112) + { + return; + } + Vector3 back = vel.LengthSquared() > 1f ? -vel.Normalized() : Vector3.Up; + Vector3 segStart = pos; + Vector3 segEnd = pos.DistanceSquaredTo(tailPos) > 0.25f ? tailPos : pos + back * 2.2f; + SpawnEmitter( + isRocket ? EmitterFireball : EmitterSmoke, + startPos: segStart, + endPos: segEnd, + velStart: back * 1.4f + Vector3.Up * 0.5f, + velEnd: back * 0.8f + Vector3.Up * 1.1f, + radiusA0: isRocket ? 0.55f : 0.38f, + radiusA1: isRocket ? 1.85f : 1.15f, + radiusB0: isRocket ? 0.72f : 0.48f, + radiusB1: isRocket ? 2.25f : 1.35f, + density0: isRocket ? 0.92f : 0.58f, + density1: 0.06f, + temp0: isRocket ? 0.75f : 0.10f, + temp1: 0f, + tint0: isRocket ? new Color(0.62f, 0.56f, 0.50f) : accentCol * 0.65f, + tint1: new Color(0.32f, 0.30f, 0.28f), + lifetime: isRocket ? 0.95f : 0.55f, + flowSpeed: 0.65f, + softness: 0.46f, + drag: 1.6f, + buoyancy: 0.45f, + priority: 4); + } + + public void EmitThermalPoolPlume(Vector3 pos, float radius, Color accentCol) + { + if (ActiveEmitterCount >= 116) + { + return; + } + float r = Math.Clamp(radius * 0.55f, 1.4f, 4.5f); + SpawnEmitter( + EmitterThermalPool, + startPos: pos + new Vector3(NextSigned() * r * 0.45f, 0.2f, NextSigned() * r * 0.45f), + endPos: pos + new Vector3(NextSigned() * r * 0.35f, 2.8f, NextSigned() * r * 0.35f), + velStart: Vector3.Up * 1.1f, + velEnd: Vector3.Up * 2.2f, + radiusA0: r * 0.55f, + radiusA1: r * 0.85f, + radiusB0: r * 0.40f, + radiusB1: r * 0.95f, + density0: 0.78f, + density1: 0.10f, + temp0: 0.85f, + temp1: 0.15f, + tint0: accentCol, + tint1: accentCol * 0.55f, + lifetime: 0.75f, + flowSpeed: 0.75f, + softness: 0.45f, + drag: 1.0f, + buoyancy: 0.85f, + priority: 5); + + SpawnFlowImpulse( + FlowThermalUpdraft, + pos, + Vector3.Up, + radius0: radius, + radius1: radius * 1.15f, + strength0: 7.5f, + strength1: 7.5f, + shellThickness: 0f, + shockPressure0: 0f, + shockPressure1: 0f, + lifetime: 0.45f, + priority: 4); + } + + public void EmitPodReentryPlume(Vector3 podPos, Vector3 podVel, float heatGlow, bool isContender) + { + float scale = isContender ? 1.25f : 0.85f; + Vector3 upTrail = podVel.LengthSquared() > 1f ? -podVel.Normalized() : Vector3.Up; + SpawnEmitter( + EmitterRetroPlume, + startPos: podPos + upTrail * 0.8f, + endPos: podPos + upTrail * (4.5f * scale), + velStart: upTrail * 2.5f, + velEnd: upTrail * 4.0f, + radiusA0: 0.75f * scale, + radiusA1: 1.85f * scale, + radiusB0: 1.15f * scale, + radiusB1: 2.65f * scale, + density0: 0.90f, + density1: 0.08f, + temp0: 0.72f + heatGlow * 0.45f, + temp1: 0.04f, + tint0: new Color(0.55f, 0.42f, 0.34f), + tint1: new Color(0.28f, 0.26f, 0.25f), + lifetime: 0.42f, + flowSpeed: 0.90f, + softness: 0.42f, + drag: 1.6f, + buoyancy: 0.4f, + priority: isContender ? 7 : 4); + } + + public void EmitPodRetroPlume(Vector3 podBasePos, float agl, Color groundTint, bool isContender) + { + float scale = isContender ? 1.25f : 0.88f; + float jetLen = MathF.Min(12f * scale, MathF.Max(3.5f, agl * 0.6f)); + SpawnEmitter( + EmitterRetroPlume, + startPos: podBasePos, + endPos: podBasePos - new Vector3(0f, jetLen, 0f), + velStart: new Vector3(0f, -8f, 0f), + velEnd: new Vector3(NextSigned() * 2.5f, -4f, NextSigned() * 2.5f), + radiusA0: 0.85f * scale, + radiusA1: 1.6f * scale, + radiusB0: 1.65f * scale, + radiusB1: 3.4f * scale, + density0: 1.85f, + density1: 0.24f, + temp0: 1.55f, + temp1: 0.14f, + tint0: new Color(0.60f, 0.48f, 0.38f), + tint1: groundTint * 0.72f, + lifetime: 0.26f, + flowSpeed: 1.1f, + softness: 0.40f, + drag: 1.8f, + buoyancy: 0.2f, + priority: isContender ? 9 : 6); + + if (agl < 65f) + { + float washT = Math.Clamp(1f - agl / 65f, 0.20f, 1f); + Vector3 groundPos = podBasePos - new Vector3(0f, MathF.Max(0f, agl), 0f) + new Vector3(0f, 0.6f, 0f); + SpawnEmitter( + EmitterSmoke, + startPos: groundPos + new Vector3(-1.8f * scale, 0f, 0f), + endPos: groundPos + new Vector3(1.8f * scale, 0.4f, 0f), + velStart: new Vector3(-3.5f * washT, 1.1f, NextSigned() * 2.2f), + velEnd: new Vector3(3.5f * washT, 1.3f, NextSigned() * 2.2f), + radiusA0: 1.6f * scale, + radiusA1: 4.8f * scale * washT + 1.4f, + radiusB0: 1.6f * scale, + radiusB1: 4.8f * scale * washT + 1.4f, + density0: 0.82f * washT, + density1: 0.08f, + temp0: 0.10f, + temp1: 0f, + tint0: groundTint, + tint1: groundTint * 0.78f, + lifetime: 0.72f, + flowSpeed: 0.85f, + softness: 0.48f, + drag: 1.6f, + buoyancy: 0.35f, + priority: isContender ? 8 : 5); + + SpawnFlowImpulse( + FlowRetroDownwash, + groundPos, + Vector3.Down, + radius0: 14.0f * scale, + radius1: 18.0f * scale, + strength0: 42f * washT, + strength1: 30f * washT, + shellThickness: 0f, + shockPressure0: 0.65f * washT, + shockPressure1: 0.35f * washT, + lifetime: 0.14f, + priority: isContender ? 9 : 6); + } + } + + public void EmitPodTouchdownPlume(Vector3 pos, Vector3 normal, Color groundTint, bool isContender) + { + float scale = isContender ? 1.40f : 0.95f; + SpawnEmitter( + EmitterFireball, + startPos: pos + normal * 0.6f, + endPos: pos + normal * (2.6f * scale), + velStart: normal * 1.8f, + velEnd: normal * 3.4f, + radiusA0: 1.6f * scale, + radiusA1: 5.5f * scale, + radiusB0: 1.9f * scale, + radiusB1: 6.2f * scale, + density0: 1.85f, + density1: 0.30f, + temp0: 1.35f, + temp1: 0.0f, + tint0: groundTint * 0.82f, + tint1: groundTint * 0.55f, + lifetime: isContender ? 1.85f : 1.15f, + flowSpeed: 0.85f, + softness: 0.46f, + drag: 1.3f, + buoyancy: 0.65f, + priority: isContender ? 10 : 7); + + SpawnFlowImpulse( + FlowShockShell, + pos + normal * 0.4f, + normal, + radius0: 1.8f, + radius1: 22.0f * scale, + strength0: 68f * scale, + strength1: 12f, + shellThickness: 3.2f, + shockPressure0: 1.1f, + shockPressure1: 0f, + lifetime: 0.35f, + priority: 10); + } + + public void EmitThermalVentPlume(Vector3 pos, float thermalRatio) + { + if (ActiveEmitterCount >= 112) + { + return; + } + float heatT = Math.Clamp((thermalRatio - 0.85f) / 0.25f, 0f, 1f); + SpawnEmitter( + EmitterSmoke, + startPos: pos, + endPos: pos + new Vector3(0f, 1.4f, 0f), + velStart: new Vector3(NextSigned() * 0.6f, 2.2f, NextSigned() * 0.6f), + velEnd: new Vector3(NextSigned() * 0.8f, 3.0f, NextSigned() * 0.8f), + radiusA0: 0.45f, + radiusA1: 1.45f + heatT * 0.4f, + radiusB0: 0.55f, + radiusB1: 1.65f + heatT * 0.5f, + density0: 0.72f, + density1: 0.06f, + temp0: 0.25f + heatT * 0.45f, + temp1: 0f, + tint0: new Color(0.82f, 0.72f - heatT * 0.22f, 0.62f - heatT * 0.35f), + tint1: new Color(0.45f, 0.42f, 0.40f), + lifetime: 0.65f, + flowSpeed: 0.6f, + softness: 0.45f, + drag: 1.5f, + buoyancy: 0.75f, + priority: 4); + } + + public void EmitDamageSmokePlume(Vector3 pos, float coreHpRatio) + { + if (ActiveEmitterCount >= 112) + { + return; + } + float dmgT = Math.Clamp((0.35f - coreHpRatio) / 0.35f, 0f, 1f); + SpawnEmitter( + dmgT > 0.35f ? EmitterFireball : EmitterSmoke, + startPos: pos, + endPos: pos + new Vector3(0f, 1.8f, 0f), + velStart: new Vector3(NextSigned() * 0.5f, 2.1f, NextSigned() * 0.5f), + velEnd: new Vector3(NextSigned() * 0.8f, 3.2f, NextSigned() * 0.8f), + radiusA0: 0.62f, + radiusA1: 1.95f + dmgT * 0.65f, + radiusB0: 0.75f, + radiusB1: 2.35f + dmgT * 0.75f, + density0: 1.65f, + density1: 0.24f, + temp0: dmgT > 0.30f ? 0.85f + dmgT * 0.55f : 0.12f, + temp1: 0f, + tint0: new Color(0.11f, 0.10f, 0.095f), + tint1: new Color(0.06f, 0.06f, 0.06f), + lifetime: 0.95f, + flowSpeed: 0.7f, + softness: 0.42f, + drag: 1.1f, + buoyancy: 0.85f, + priority: 5); + } + + public void EmitFootstepOrTirePuff(Vector3 pos, Color groundTint, float scale) + { + // Strictly gated under 48 active emitters so combat explosions never drop slots and desert stays within GPU budget + if (ActiveEmitterCount >= 48) + { + return; + } + Color gLin = groundTint.SrgbToLinear(); + SpawnEmitter( + EmitterSmoke, + startPos: pos, + endPos: pos + new Vector3(NextSigned() * 0.4f, 0.45f, NextSigned() * 0.4f), + velStart: new Vector3(NextSigned() * 1.1f, 0.9f, NextSigned() * 1.1f), + velEnd: new Vector3(NextSigned() * 1.4f, 1.4f, NextSigned() * 1.4f), + radiusA0: 0.48f * scale, + radiusA1: 1.55f * scale, + radiusB0: 0.58f * scale, + radiusB1: 1.75f * scale, + density0: 0.38f, + density1: 0.04f, + temp0: 0f, + temp1: 0f, + tint0: gLin * 1.1f, + tint1: gLin * 0.75f, + lifetime: 0.44f, + flowSpeed: 0.45f, + softness: 0.50f, + drag: 2.0f, + buoyancy: 0.35f, + priority: 1); + } + + private int FindOrEvictEmitterSlot(int priority) + { + int oldestIdx = -1; + int lowestPri = int.MaxValue; + float oldestAge = -1f; + for (int i = 0; i < MaxEmitters; i++) + { + if (!_emitters[i].Active) + { + return i; + } + if (_emitters[i].Priority < lowestPri || + (_emitters[i].Priority == lowestPri && _emitters[i].Age > oldestAge)) + { + lowestPri = _emitters[i].Priority; + oldestAge = _emitters[i].Age; + oldestIdx = i; + } + } + return lowestPri <= priority ? oldestIdx : -1; + } + + private int FindOrEvictImpulseSlot(int priority) + { + int oldestIdx = -1; + int lowestPri = int.MaxValue; + float oldestAge = -1f; + for (int i = 0; i < MaxFlowImpulses; i++) + { + if (!_impulses[i].Active) + { + return i; + } + if (_impulses[i].Priority < lowestPri || + (_impulses[i].Priority == lowestPri && _impulses[i].Age > oldestAge)) + { + lowestPri = _impulses[i].Priority; + oldestAge = _impulses[i].Age; + oldestIdx = i; + } + } + return lowestPri <= priority ? oldestIdx : -1; + } + + private int CountActiveEmitters() + { + int count = 0; + for (int i = 0; i < MaxEmitters; i++) + { + if (_emitters[i].Active) count++; + } + return count; + } + + private int CountActiveImpulses() + { + int count = 0; + for (int i = 0; i < MaxFlowImpulses; i++) + { + if (_impulses[i].Active) count++; + } + return count; + } + + private float NextFloat() + { + uint x = _rng; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + _rng = x; + return (x & 0x00FFFFFFu) / 16777216f; + } + + private float NextSigned() => NextFloat() * 2f - 1f; +} diff --git a/client/WalkerFootstepTracker.cs b/client/WalkerFootstepTracker.cs new file mode 100644 index 0000000..0d84046 --- /dev/null +++ b/client/WalkerFootstepTracker.cs @@ -0,0 +1,196 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using RustToDust.Core; +using RustToDust.Ymir; + +namespace RustToDust.Client; + +public readonly record struct FootstepPulse( + bool IsContender, + int EntityId, + int LegIndex, + string ChassisId, + float MassKg, + float LoadG, + Vector3 WorldPos); + +/// +/// Tracks per-walker leg GRF hysteresis (LoadG arming < 0.10, touchdown >= 0.24, +/// 0.18 s cooldown) from interpolated s across both Solo and +/// Multiplayer (). Zero Godot dependency so xUnit and headless +/// Godot tests run the exact same edge detector. +/// +public sealed class WalkerFootstepTracker +{ + public const float ArmLoadGThreshold = 0.10f; + public const float TriggerLoadGThreshold = 0.24f; + public const float LegCooldownSec = 0.18f; + + private struct LegHysteresis + { + public bool Armed; + public float Cooldown; + } + + private sealed class WalkerTrackState + { + public string ChassisId = string.Empty; + public int LegCount; + public readonly LegHysteresis[] Legs = new LegHysteresis[4]; + } + + private readonly Dictionary<(bool IsContender, int Id), WalkerTrackState> _walkers = new(); + + public int TrackedWalkerCount => _walkers.Count; + + public void Clear() => _walkers.Clear(); + + public void StepSession( + IClientArenaSession session, + float dt, + float alpha, + List outPulses, + Func? resolveLiveFootWorld = null) + { + var state = session.ViewState; + var contenders = state.Contenders; + for (int i = 0; i < contenders.Count; i++) + { + var c = contenders[i]; + if (!c.Alive || !c.Grid.Spec.IsWalker || !session.IsContenderVisible(c.Id)) + { + _walkers.Remove((true, c.Id)); + continue; + } + if (!session.TrySampleInterpolatedWalkerPose(true, c.Id, alpha, out var snap)) + { + continue; + } + StepActor( + isContender: true, + entityId: c.Id, + chassisId: c.Grid.Spec.Id, + massKg: c.Grid.Spec.MassKg, + in snap, + state.Terrain, + dt, + outPulses, + resolveLiveFootWorld); + } + + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive || !s.Grid.Spec.IsWalker || !session.IsSpectatorVisible(s.Id)) + { + _walkers.Remove((false, s.Id)); + continue; + } + if (!session.TrySampleInterpolatedWalkerPose(false, s.Id, alpha, out var snap)) + { + continue; + } + StepActor( + isContender: false, + entityId: s.Id, + chassisId: s.Grid.Spec.Id, + massKg: s.Grid.Spec.MassKg, + in snap, + state.Terrain, + dt, + outPulses, + resolveLiveFootWorld); + } + } + + public void StepActor( + bool isContender, + int entityId, + string chassisId, + float massKg, + in WalkerVisualSnapshot snap, + TerrainField terrain, + float dt, + List outPulses, + Func? resolveLiveFootWorld = null) + { + int legCount = Math.Clamp(snap.LegCount, 0, 4); + if (legCount == 0) + { + return; + } + + var key = (isContender, entityId); + if (!_walkers.TryGetValue(key, out var track) || + !string.Equals(track.ChassisId, chassisId, StringComparison.OrdinalIgnoreCase) || + track.LegCount != legCount) + { + track = new WalkerTrackState + { + ChassisId = chassisId, + LegCount = legCount + }; + // First sighting initializes Armed = false for zero spawn / swap pop + _walkers[key] = track; + return; + } + + float stepDt = MathF.Max(0f, dt); + WalkerGeometrySpec? geom = null; + float geomScale = snap.GeomScale > 0.01f ? snap.GeomScale : 1f; + Quaternion comRot = snap.ComRot.LengthSquared() > 1e-6f + ? Quaternion.Normalize(snap.ComRot) + : Quaternion.Identity; + + for (int i = 0; i < legCount; i++) + { + ref LegHysteresis leg = ref track.Legs[i]; + if (leg.Cooldown > 0f) + { + leg.Cooldown = MathF.Max(0f, leg.Cooldown - stepDt); + } + + float loadG = snap.LoadG[i]; + if (loadG < ArmLoadGThreshold) + { + leg.Armed = true; + continue; + } + + if (leg.Armed && loadG >= TriggerLoadGThreshold && leg.Cooldown <= 0f) + { + leg.Armed = false; + leg.Cooldown = LegCooldownSec; + + Vector3? liveFoot = resolveLiveFootWorld?.Invoke(isContender, entityId, i); + Vector3 footWorld; + if (liveFoot.HasValue) + { + float fy = terrain.SampleHeight(liveFoot.Value.X, liveFoot.Value.Z); + footWorld = new Vector3(liveFoot.Value.X, fy, liveFoot.Value.Z); + } + else + { + geom ??= WalkerGeometrySpec.GetForChassis(chassisId); + Vector2 restXZ = geom.Legs[i].RestFootXZ * geomScale; + Vector3 offset = Vector3.Transform(new Vector3(restXZ.X, 0f, restXZ.Y), comRot); + float fx = snap.ComPos.X + offset.X; + float fz = snap.ComPos.Z + offset.Z; + float fy = terrain.SampleHeight(fx, fz); + footWorld = new Vector3(fx, fy, fz); + } + + outPulses.Add(new FootstepPulse( + isContender, + entityId, + i, + chassisId, + massKg, + loadG, + footWorld)); + } + } + } +} diff --git a/client/decal_pom.gdshader b/client/decal_pom.gdshader new file mode 100644 index 0000000..0239a1f --- /dev/null +++ b/client/decal_pom.gdshader @@ -0,0 +1,140 @@ +shader_type spatial; +render_mode blend_mix, depth_draw_never, cull_back; + +// Forward+ Vulkan Parallax Occlusion Mapping (POM) decal shader for MultiMeshInstance3D. +// Renders hundreds of hard-surface vents, hatches, stencils, and live combat hits in 1 draw call. +// +// INSTANCE_CUSTOM layout: +// x = tile_index (0..15 in 4x4 trim-sheet atlas) +// y = heat_glow (0..1, incandescent glow on rolled rim & core of fresh combat hits) +// z = opacity (0..1) +// w = depth_scale (default ~0.06 when 0) +// +// Atlas textures (assets/decals/): +// albedo_tex : RGBA albedo + alpha mask +// normal_tex : tangent-space normal map (+X right, +Y down, +Z out) +// ormh_tex : R=AO, G=Roughness, B=Metallic, A=Height (1.0=flush surface, 0.0=deep recess) + +uniform sampler2D albedo_tex : source_color, filter_linear_mipmap, repeat_disable; +uniform sampler2D normal_tex : hint_normal, filter_linear_mipmap, repeat_disable; +uniform sampler2D ormh_tex : filter_linear_mipmap, repeat_disable; + +uniform bool use_instance_custom = true; +uniform float fallback_tile_index : hint_range(0.0, 15.0) = 0.0; +uniform float fallback_heat_glow : hint_range(0.0, 1.0) = 0.0; +uniform float fallback_opacity : hint_range(0.0, 1.0) = 1.0; +uniform float default_depth_scale : hint_range(0.0, 0.25) = 0.06; +uniform float normal_offset : hint_range(0.0, 0.02) = 0.004; +uniform float normal_depth : hint_range(0.0, 3.0) = 1.15; +uniform float heat_emission_energy : hint_range(0.0, 10.0) = 2.6; + +varying vec4 v_custom; + +void vertex() { + VERTEX += NORMAL * normal_offset; + if (use_instance_custom) { + v_custom = INSTANCE_CUSTOM; + } else { + v_custom = vec4(fallback_tile_index, fallback_heat_glow, fallback_opacity, default_depth_scale); + } +} + +void fragment() { + const int POM_STEPS = 6; + const float CELL_SIZE = 0.25; + + float tile_idx = floor(clamp(v_custom.x + 0.5, 0.0, 15.0)); + float heat_glow = clamp(v_custom.y, 0.0, 1.0); + float opacity = clamp(v_custom.z, 0.0, 1.0); + float depth_scale = v_custom.w > 0.0001 ? v_custom.w : default_depth_scale; + + float col_idx = mod(tile_idx, 4.0); + float row_idx = floor(tile_idx * 0.25); + vec2 cell_origin = vec2(col_idx, row_idx) * CELL_SIZE; + + // Hoist screen-space derivatives above any non-uniform control flow / discard (GLSL 330 safety) + vec2 d_uv_dx = dFdx(UV * CELL_SIZE); + vec2 d_uv_dy = dFdy(UV * CELL_SIZE); + + // Soft outer edge fade on local quad UV + float edge_fade = smoothstep(0.0, 0.04, UV.x) + * smoothstep(1.0, 0.96, UV.x) + * smoothstep(0.0, 0.04, UV.y) + * smoothstep(1.0, 0.96, UV.y); + + // Tangent-space view ray (Godot fragment VIEW, TANGENT, BINORMAL, NORMAL are all in view space) + vec3 t_dir = normalize(TANGENT); + vec3 b_dir = normalize(BINORMAL); + vec3 n_dir = normalize(NORMAL); + vec3 view_ts = normalize(vec3(dot(VIEW, t_dir), dot(VIEW, b_dir), dot(VIEW, n_dir))); + + // Clamp grazing Z so oblique rays stay well-behaved without sliding out of the tile + float vz = max(view_ts.z, 0.22); + vec2 p_dir = -(view_ts.xy / vz) * depth_scale; + + // 10 linear POM steps from surface (layer_depth=0, height=1) into recess (layer_depth=1, height=0) + float step_size = 1.0 / float(POM_STEPS); + vec2 delta_uv = p_dir * step_size; + + vec2 cur_uv = UV; + float cur_layer_depth = 0.0; + float cur_tex_depth = 1.0 - textureLod(ormh_tex, cell_origin + clamp(cur_uv, 0.002, 0.998) * CELL_SIZE, 0.0).a; + + vec2 prev_uv = cur_uv; + float prev_layer_depth = cur_layer_depth; + float prev_tex_depth = cur_tex_depth; + + for (int i = 0; i < POM_STEPS; i++) { + if (cur_layer_depth >= cur_tex_depth) { + break; + } + prev_uv = cur_uv; + prev_layer_depth = cur_layer_depth; + prev_tex_depth = cur_tex_depth; + + cur_uv += delta_uv; + cur_layer_depth += step_size; + cur_tex_depth = 1.0 - textureLod(ormh_tex, cell_origin + clamp(cur_uv, 0.002, 0.998) * CELL_SIZE, 0.0).a; + } + + // 1 secant interpolation step + float after_d = cur_tex_depth - cur_layer_depth; + float before_d = prev_tex_depth - prev_layer_depth; + float denom = after_d - before_d; + float weight = abs(denom) > 1e-5 ? clamp(after_d / denom, 0.0, 1.0) : 0.0; + vec2 final_uv = mix(cur_uv, prev_uv, weight); + + // Discard cleanly outside tile bounds so adjacent atlas cells never bleed + if (final_uv.x < 0.002 || final_uv.x > 0.998 || final_uv.y < 0.002 || final_uv.y > 0.998) { + discard; + } + + vec2 atlas_uv = cell_origin + final_uv * CELL_SIZE; + vec4 alb = textureGrad(albedo_tex, atlas_uv, d_uv_dx, d_uv_dy); + vec3 nrm_sample = textureGrad(normal_tex, atlas_uv, d_uv_dx, d_uv_dy).rgb; + vec4 ormh = textureGrad(ormh_tex, atlas_uv, d_uv_dx, d_uv_dy); + + float out_alpha = alb.a * edge_fade * opacity; + if (out_alpha < 0.015) { + discard; + } + + // Emissive rim & molten crater mask for combat hits (Row 3: tiles 12..15) + float is_combat = step(11.5, tile_idx); + // Rolled metallic lip & crater wall glow hot while keeping pitch-black bore contrast + float rim_band = smoothstep(0.94, 0.50, ormh.a) * smoothstep(0.08, 0.55, ormh.b); + float bore_inner_ring = smoothstep(0.35, 0.10, ormh.a) * smoothstep(0.01, 0.16, ormh.a); + float hot_mask = clamp((rim_band * 1.15 + bore_inner_ring * 0.45) * is_combat, 0.0, 1.0); + float hot_intensity = heat_glow * hot_mask; + vec3 hot_col = mix(vec3(0.95, 0.18, 0.02), vec3(1.0, 0.58, 0.14), smoothstep(0.25, 0.90, hot_intensity)); + + ALBEDO = alb.rgb; + ALPHA = out_alpha; + NORMAL_MAP = nrm_sample; + NORMAL_MAP_DEPTH = normal_depth; + AO = ormh.r; + AO_LIGHT_AFFECT = 0.85; + ROUGHNESS = clamp(ormh.g, 0.12, 0.98); + METALLIC = clamp(ormh.b, 0.0, 1.0); + EMISSION = hot_col * (hot_intensity * heat_emission_energy); +} diff --git a/client/export_presets.cfg b/client/export_presets.cfg new file mode 100644 index 0000000..4a70a59 --- /dev/null +++ b/client/export_presets.cfg @@ -0,0 +1,48 @@ +[preset.0] + +name="Windows Desktop" +platform="Windows Desktop" +runnable=true +advanced_options=false +dedicated_server=false +custom_features="" +export_filter="all_resources" +include_filter="*.glsl" +exclude_filter="tests/*,*.uid" +export_path="" +patches=PackedStringArray() +encryption_include_filters="" +encryption_exclude_filters="" +seed=0 +encrypt_pck=false +encrypt_directory=false +script_export_mode=2 + +[preset.0.options] + +custom_template/debug="" +custom_template/release="" +debug/export_console_wrapper=1 +binary_format/embed_pck=false +texture_format/s3tc_bptc=true +texture_format/etc2_astc=false +shader_baker/enabled=false +binary_format/architecture="x86_64" +codesign/enable=false +application/modify_resources=true +application/icon="" +application/console_wrapper_icon="" +application/icon_interpolation=4 +application/file_version="" +application/product_version="" +application/company_name="GameCult" +application/product_name="Rust to Dust" +application/file_description="Rust to Dust" +application/copyright="" +application/trademarks="" +application/export_angle=0 +application/export_d3d12=0 +application/d3d12_agility_sdk_multiarch=true +ssh_remote_deploy/enabled=false +dotnet/include_scripts_content=false +dotnet/include_debug_symbols=false diff --git a/client/film_grain.gdshader b/client/film_grain.gdshader new file mode 100644 index 0000000..6f9cf5a --- /dev/null +++ b/client/film_grain.gdshader @@ -0,0 +1,27 @@ +shader_type canvas_item; +render_mode blend_mix; + +// Forward+ Vulkan post-tonemap temporal film grain (CanvasLayer Layer=5 < Hud Layer=10). +// Runs strictly after AgX tonemapping & normalized additive bloom so HUD text stays razor-sharp. + +uniform sampler2D screen_tex : hint_screen_texture, filter_nearest; +uniform float grain_strength : hint_range(0.0, 0.1) = 0.018; +uniform float post_gamma : hint_range(0.5, 2.5) = 1.32; + +float interleaved_gradient_noise(vec2 frag_xy, float frame_idx) { + vec2 p = frag_xy + vec2(frame_idx * 17.0, frame_idx * 31.0); + return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); +} + +void fragment() { + vec4 src = texture(screen_tex, SCREEN_UV); + vec3 graded = pow(max(src.rgb, vec3(0.0)), vec3(post_gamma)); + float frame_idx = mod(floor(fract(TIME * 0.001) * 60000.0), 64.0); + float n = interleaved_gradient_noise(FRAGCOORD.xy, frame_idx); + + float luma = dot(graded, vec3(0.2126, 0.7152, 0.0722)); + float midtone_weight = smoothstep(0.02, 0.18, luma) * (1.0 - 0.65 * smoothstep(0.65, 1.0, luma)); + vec3 grained = clamp(graded + vec3((n - 0.5) * 2.0 * grain_strength * midtone_weight), vec3(0.0), vec3(1.0)); + + COLOR = vec4(grained, src.a); +} diff --git a/client/flow_field_step.glsl b/client/flow_field_step.glsl new file mode 100644 index 0000000..3fbe2a0 --- /dev/null +++ b/client/flow_field_step.glsl @@ -0,0 +1,130 @@ +#version 450 + +layout(local_size_x = 8, local_size_y = 4, local_size_z = 8) in; + +struct FlowImpulse { + vec4 posRadius; + vec4 dirStrength; + vec4 shellParams; +}; + +layout(set = 0, binding = 0, std140) uniform VolumetricFrame { + mat4 invProj; + vec4 camPosTime; + vec4 camRightAspect; + vec4 camUpTanHalfFov; + vec4 camFwdNearFar; + vec4 sunDirIntensity; + vec4 sunColorExt; + vec4 ambientColorFog; + vec4 viewportInfo; + uvec4 tileGridParams; + vec4 flowOriginVoxel; + vec4 flowInvExtentDt; + ivec4 flowDeltaImpulse; + uvec4 qualityParams; +} u_frame; + +layout(set = 0, binding = 1, std430) readonly buffer FlowImpulseBuffer { + FlowImpulse impulses[]; +} u_impulses; + +layout(set = 0, binding = 2) uniform sampler3D u_prevFlow; +layout(set = 0, binding = 3, rgba16f) uniform writeonly image3D u_nextFlow; + +shared FlowImpulse sImp[64]; + +void main() { + uint tid = gl_LocalInvocationIndex; + uint impulseCount = min(uint(max(0, u_frame.flowDeltaImpulse.w)), 64u); + if (tid < impulseCount) { + sImp[tid] = u_impulses.impulses[tid]; + } + memoryBarrierShared(); + barrier(); + + ivec3 g = ivec3(gl_GlobalInvocationID.xyz); + const ivec3 gridDim = ivec3(64, 24, 64); + if (any(greaterThanEqual(g, gridDim))) { + return; + } + + float voxelSize = u_frame.flowOriginVoxel.w; + float dt = clamp(u_frame.flowInvExtentDt.w, 0.0, 0.05); + float elapsed = u_frame.camPosTime.w; + + // Gentle planetary wind that shifts subtly with time so idle smoke plumes breathe + vec3 ambientWind = vec3( + 1.25 + 0.35 * sin(elapsed * 0.23), + 0.18, + 0.55 + 0.25 * cos(elapsed * 0.19) + ); + + ivec3 prevIdx = g + u_frame.flowDeltaImpulse.xyz; + bool inPrev = all(greaterThanEqual(prevIdx, ivec3(0))) && all(lessThan(prevIdx, gridDim)); + vec3 prevVel = inPrev ? texelFetch(u_prevFlow, prevIdx, 0).rgb : ambientWind; + + vec3 srcUv = (vec3(prevIdx) + vec3(0.5) - (prevVel * dt) / voxelSize) / vec3(gridDim); + vec4 advected = (inPrev && all(greaterThanEqual(srcUv, vec3(0.0))) && all(lessThanEqual(srcUv, vec3(1.0)))) + ? textureLod(u_prevFlow, srcUv, 0.0) + : vec4(ambientWind, 0.0); + + vec3 vel = mix(ambientWind, advected.rgb, exp(-dt * 1.45)); + float shockP = advected.a * exp(-dt * 4.5); + + vec3 worldP = u_frame.flowOriginVoxel.xyz + (vec3(g) + vec3(0.5)) * voxelSize; + + for (uint i = 0u; i < impulseCount; i++) { + FlowImpulse imp = sImp[i]; + uint typeBits = floatBitsToUint(imp.shellParams.z); + float radius = max(0.5, imp.posRadius.w); + float strength = imp.dirStrength.w; + + if (typeBits == 0u) { + // ShockShell: expanding radial blast shell + vec3 delta = worldP - imp.posRadius.xyz; + float dist = length(delta); + float thick = max(1.5, imp.shellParams.x); + float dShell = (dist - radius) / thick; + if (abs(dShell) < 3.0) { + float shell = exp(-dShell * dShell); + vec3 rDir = dist > 0.05 ? delta / dist : vec3(0.0, 1.0, 0.0); + vel += rDir * (strength * shell); + shockP = max(shockP, imp.shellParams.y * shell); + } + } else if (typeBits == 1u) { + // RetroDownwash: radial ground deflection from pod retro thruster + vec3 d = worldP - imp.posRadius.xyz; + float rXZ = length(d.xz); + float rNorm = rXZ / radius; + float hNorm = abs(d.y) / max(3.0, radius * 0.55); + if (rNorm < 1.35 && hNorm < 1.35) { + float rFall = exp(-rNorm * rNorm * 1.6) * smoothstep(1.35, 0.08, rNorm); + float hFall = exp(-hNorm * hNorm * 1.4); + vec2 rXZDir = rXZ > 0.1 ? d.xz / rXZ : vec2(1.0, 0.0); + vec3 outDir = normalize(vec3(rXZDir.x, 0.28, rXZDir.y)); + float w = rFall * hFall; + vel += outDir * (strength * w); + shockP = max(shockP, imp.shellParams.y * w); + } + } else { + // ThermalUpdraft: buoyant rising column above fireballs & thermal pools + vec3 d = worldP - imp.posRadius.xyz; + float rXZ = length(d.xz); + float rNorm = rXZ / radius; + if (rNorm < 1.3 && d.y > -2.5 && d.y < radius * 2.8) { + float hFall = smoothstep(-2.5, 1.5, d.y) * smoothstep(radius * 2.8, 0.0, max(0.0, d.y)); + float colFall = exp(-rNorm * rNorm * 1.5) * hFall; + vel += vec3(0.0, strength * colFall, 0.0); + } + } + } + + float vLen = length(vel); + if (vLen > 120.0) { + vel *= 120.0 / vLen; + } + shockP = clamp(shockP, 0.0, 2.0); + + imageStore(u_nextFlow, g, vec4(vel, shockP)); +} diff --git a/client/fonts/MONASPACE_LICENSE.txt b/client/fonts/MONASPACE_LICENSE.txt new file mode 100644 index 0000000..1b82de9 --- /dev/null +++ b/client/fonts/MONASPACE_LICENSE.txt @@ -0,0 +1,93 @@ +Copyright (c) 2023, GitHub https://github.com/githubnext/monaspace +with Reserved Font Name "Monaspace", including subfamilies: "Argon", "Neon", "Xenon", "Radon", and "Krypton" + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting — in part or in whole — any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/client/fonts/MonaspaceKrypton-Bold.otf b/client/fonts/MonaspaceKrypton-Bold.otf new file mode 100644 index 0000000..4fafd5f Binary files /dev/null and b/client/fonts/MonaspaceKrypton-Bold.otf differ diff --git a/client/fonts/MonaspaceKrypton-Bold.otf.import b/client/fonts/MonaspaceKrypton-Bold.otf.import new file mode 100644 index 0000000..11f4f1e --- /dev/null +++ b/client/fonts/MonaspaceKrypton-Bold.otf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://dlsxsr034f5sv" +path="res://.godot/imported/MonaspaceKrypton-Bold.otf-a6e22263037c0e08923dee8788f7d7d1.fontdata" + +[deps] + +source_file="res://fonts/MonaspaceKrypton-Bold.otf" +dest_files=["res://.godot/imported/MonaspaceKrypton-Bold.otf-a6e22263037c0e08923dee8788f7d7d1.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/client/fonts/MonaspaceKrypton-Regular.otf b/client/fonts/MonaspaceKrypton-Regular.otf new file mode 100644 index 0000000..ce21874 Binary files /dev/null and b/client/fonts/MonaspaceKrypton-Regular.otf differ diff --git a/client/fonts/MonaspaceKrypton-Regular.otf.import b/client/fonts/MonaspaceKrypton-Regular.otf.import new file mode 100644 index 0000000..03294fe --- /dev/null +++ b/client/fonts/MonaspaceKrypton-Regular.otf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://1udxuivwq46s" +path="res://.godot/imported/MonaspaceKrypton-Regular.otf-879dc21ea909cad808c934de94044b6e.fontdata" + +[deps] + +source_file="res://fonts/MonaspaceKrypton-Regular.otf" +dest_files=["res://.godot/imported/MonaspaceKrypton-Regular.otf-879dc21ea909cad808c934de94044b6e.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/client/fonts/MonaspaceKrypton-SemiBold.otf b/client/fonts/MonaspaceKrypton-SemiBold.otf new file mode 100644 index 0000000..8c9d680 Binary files /dev/null and b/client/fonts/MonaspaceKrypton-SemiBold.otf differ diff --git a/client/fonts/MonaspaceKrypton-SemiBold.otf.import b/client/fonts/MonaspaceKrypton-SemiBold.otf.import new file mode 100644 index 0000000..e76054a --- /dev/null +++ b/client/fonts/MonaspaceKrypton-SemiBold.otf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://270t27q6bpet" +path="res://.godot/imported/MonaspaceKrypton-SemiBold.otf-c294810382571aa26a9353cf57198e74.fontdata" + +[deps] + +source_file="res://fonts/MonaspaceKrypton-SemiBold.otf" +dest_files=["res://.godot/imported/MonaspaceKrypton-SemiBold.otf-c294810382571aa26a9353cf57198e74.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/client/gpu_sparks_draw.gdshader b/client/gpu_sparks_draw.gdshader new file mode 100644 index 0000000..2441a07 --- /dev/null +++ b/client/gpu_sparks_draw.gdshader @@ -0,0 +1,151 @@ +shader_type spatial; +render_mode unshaded, cull_disabled, depth_draw_opaque; + +varying vec4 v_color; +varying vec2 v_uvCentered; +varying vec2 v_kite; +varying float v_ageNorm; +varying float v_type; +varying float v_camFade; + +void vertex() { + vec3 worldPos = MODEL_MATRIX[3].xyz; + vec3 velWorld = MODEL_MATRIX[0].xyz; + + float widthM = max(0.012, INSTANCE_CUSTOM.x); + float ageNorm = clamp(INSTANCE_CUSTOM.y / max(0.01, INSTANCE_CUSTOM.z), 0.0, 1.0); + float pType = floor(INSTANCE_CUSTOM.w + 0.001); + + v_color = COLOR; + v_ageNorm = ageNorm; + v_type = pType; + v_uvCentered = UV * 2.0 - vec2(1.0); + + // Kite-stretch trick: rotate quad coordinates 45 degrees so pointed ears align directly along velocity: + // (-1,-1) -> u=-1,v=0 (tail tip); (+1,+1) -> u=+1,v=0 (nose tip); (+1,-1)/(-1,+1) -> v=±1 (side ears) + float uKite = 0.5 * (v_uvCentered.x + v_uvCentered.y); + float vKite = 0.5 * (v_uvCentered.x - v_uvCentered.y); + v_kite = vec2(uKite, vKite); + + vec3 camRight = INV_VIEW_MATRIX[0].xyz; + vec3 camUp = INV_VIEW_MATRIX[1].xyz; + vec3 toCamVec = CAMERA_POSITION_WORLD - worldPos; + float toCamLen2 = dot(toCamVec, toCamVec); + float distToCam = sqrt(toCamLen2); + v_camFade = smoothstep(1.2, 2.8, distToCam); + if (distToCam < 1.2) { + MODELVIEW_MATRIX = VIEW_MATRIX; + VERTEX = worldPos; + } else { + vec3 toCam = toCamLen2 > 1e-6 ? toCamVec * inversesqrt(toCamLen2) : INV_VIEW_MATRIX[2].xyz; + + if (pType > 2.5) { + // Type 3: Stationary 4-point HDR muzzle starburst + float pulse = sin(ageNorm * 3.14159265); + float sz = min(widthM * (0.65 + 0.45 * pulse), distToCam * 0.032); + vec3 displacedWorld = worldPos + camRight * (v_uvCentered.x * sz) + camUp * (v_uvCentered.y * sz); + MODELVIEW_MATRIX = VIEW_MATRIX; + VERTEX = displacedWorld; + } else { + float speed = length(velWorld); + vec3 vProj = velWorld - toCam * dot(velWorld, toCam); + float vProjLen2 = dot(vProj, vProj); + vec3 axisWorld = vProjLen2 > 1e-4 ? vProj * inversesqrt(vProjLen2) : camRight; + vec3 rawPerp = cross(toCam, axisWorld); + float rawPerpLen2 = dot(rawPerp, rawPerp); + vec3 perpWorld = rawPerpLen2 > 1e-6 ? rawPerp * inversesqrt(rawPerpLen2) : camUp; + + float dist = distToCam; + float halfWidth; + float halfLen; + + if (pType > 1.5) { + // Type 2: Tiny flow-blown grit / dust mote + float minGritPx = dist * 0.0010; + halfWidth = max(clamp(widthM * (0.75 + 0.30 * ageNorm), 0.020, 0.055), minGritPx); + halfLen = halfWidth + clamp(speed * 0.006, 0.01, 0.09); + } else { + // Type 0 (VelocitySpark) & Type 1 (BuoyantEmber): crisp short punchy streaks (halfLen capped 0.04..0.16m) + float minSparkPx = dist * 0.0012; + halfWidth = max(clamp(widthM * mix(0.82, 0.38, ageNorm), 0.012, 0.030), minSparkPx); + float baseLen = clamp(halfWidth * 1.6 + speed * 0.008, 0.04, 0.16); + halfLen = max(halfWidth * 1.8, min(0.16, max(baseLen, minSparkPx * 2.6))); + } + + // Near-camera angular cap so sparks & dust motes at 1.8-2.5m never blow up into giant halftone spears + float maxAngLen = dist * 0.022; + halfLen = min(halfLen, maxAngLen); + halfWidth = min(halfWidth, maxAngLen * 0.32); + + vec3 displacedWorld = worldPos + axisWorld * (uKite * halfLen) + perpWorld * (vKite * halfWidth); + MODELVIEW_MATRIX = VIEW_MATRIX; + VERTEX = displacedWorld; + } + } +} + +void fragment() { + if (v_camFade < 0.02) { + discard; + } + float fade = (1.0 - v_ageNorm * v_ageNorm) * clamp(v_color.a, 0.0, 1.0) * v_camFade; + if (fade < 0.02) { + discard; + } + + // Temporally animated Interleaved Gradient Noise for stochastic opaque TAA coverage (depth_draw_opaque) + float frameIdx = mod(floor(TIME * 60.0), 64.0); + float dither = fract(52.9829189 * fract(dot(FRAGCOORD.xy + 5.588238 * frameIdx, vec2(0.06711056, 0.00583715)))); + + if (v_type > 2.5) { + // 4-point HDR muzzle starburst + float r = length(v_uvCentered); + if (r > 1.0) { + discard; + } + float cx = exp(-abs(v_uvCentered.y) * 9.5) * smoothstep(1.0, 0.05, abs(v_uvCentered.x)); + float cy = exp(-abs(v_uvCentered.x) * 9.5) * smoothstep(1.0, 0.05, abs(v_uvCentered.y)); + float core = smoothstep(0.55, 0.0, r); + float mask = max(core, max(cx, cy) * 0.90); + float coverage = clamp(mask * fade * 1.25, 0.0, 1.0); + if (coverage <= dither) { + discard; + } + ALBEDO = max(v_color.rgb, vec3(0.0)) * (1.0 + core * 0.95); + } else if (v_type > 1.5) { + // Flow-entrained grit / dust mote + float r = length(v_kite); + if (r > 0.92) { + discard; + } + float coverage = smoothstep(0.92, 0.14, r) * fade * 0.85; + if (coverage <= dither) { + discard; + } + ALBEDO = max(v_color.rgb, vec3(0.0)); + } else { + // Molten slag spark / ember: white-gold -> amber -> deep copper-orange cooling ramp + float rKite = length(vec2(v_kite.x, v_kite.y * 1.15)); + if (rKite > 1.0) { + discard; + } + float core = pow(clamp(1.0 - rKite, 0.0, 1.0), 1.45); + float hotCenter = smoothstep(0.50, 0.0, rKite); + float coverage = clamp(core * fade * 1.20, 0.0, 1.0); + if (coverage <= dither) { + discard; + } + + vec3 whiteGold = vec3(6.2, 4.2, 1.65); + vec3 moltenAmber = vec3(4.3, 1.85, 0.30); + vec3 copperEmber = vec3(1.85, 0.42, 0.05); + vec3 ramp = v_ageNorm < 0.38 + ? mix(whiteGold, moltenAmber, v_ageNorm / 0.38) + : mix(moltenAmber, copperEmber, clamp((v_ageNorm - 0.38) / 0.62, 0.0, 1.0)); + + // Subtle caller tint (20%) so plasma/thermal slag still reads predominantly as molten fire + vec3 tintRgb = max(v_color.rgb, vec3(0.0)); + vec3 moltenRgb = mix(ramp, tintRgb, 0.20); + ALBEDO = mix(moltenRgb, whiteGold * 1.15, hotCenter * (1.0 - 0.55 * v_ageNorm)); + } +} diff --git a/client/gpu_sparks_process.gdshader b/client/gpu_sparks_process.gdshader new file mode 100644 index 0000000..0a05bf2 --- /dev/null +++ b/client/gpu_sparks_process.gdshader @@ -0,0 +1,154 @@ +shader_type particles; +render_mode disable_velocity; + +global uniform sampler3D rtd_flow_field; +global uniform vec3 rtd_flow_origin; +global uniform vec3 rtd_flow_inv_extent; + +float tri(float x) { + return abs(fract(x) - 0.5); +} + +vec3 tri3(vec3 p) { + return vec3( + tri(p.z + tri(p.y)), + tri(p.z + tri(p.x)), + tri(p.y + tri(p.x)) + ); +} + +vec3 safeNorm(vec3 v) { + float l2 = dot(v, v); + return l2 > 1e-8 ? v * inversesqrt(l2) : vec3(0.0, 1.0, 0.0); +} + +vec3 aetheriaCurl(vec3 pos, float flowScale, float scrollSpeed, float t) { + vec3 field = pos / max(0.5, flowScale); + float s1 = t * scrollSpeed; + float s2 = t * scrollSpeed * 1.61803398875; + vec3 t1 = safeNorm(tri3(field - vec3(0.0, s1, 0.0))); + vec3 t2 = safeNorm(tri3(field * 1.61803398875 - vec3(0.0, s2, 0.0))); + return cross(t1, t2); +} + +uint hashU32(uint x) { + x ^= x >> 16u; + x *= 0x7FEB352Du; + x ^= x >> 15u; + x *= 0x846CA68Bu; + x ^= x >> 16u; + return x; +} + +float hash01(uint x) { + return float(hashU32(x) & 0x00FFFFFFu) / 16777216.0; +} + +void start() { + ACTIVE = true; + float pType = floor(CUSTOM.w + 0.001); + + if (pType > 2.5) { + // Type 3: MuzzleStarburst stays stationary at muzzle + VELOCITY = vec3(0.0); + TRANSFORM[0].xyz = vec3(1.0, 0.0, 0.0); + TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0); + TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0); + } else { + uint seed = INDEX ^ (NUMBER * 747796405u) ^ floatBitsToUint(TIME); + float r0 = hash01(seed + 1u); + float r1 = hash01(seed + 17u); + float r2 = hash01(seed + 53u); + float r3 = hash01(seed + 131u); + float r4 = hash01(seed + 257u); + float r5 = hash01(seed + 509u); + + // Wide log-normal speed dispersion (0.25x..2.8x) + 3D directional chaos to shatter radial shell fans + float gauss = (r0 + r1 - 1.0) * 1.45; + float speedMult = clamp(exp(gauss * 0.72), 0.25, 2.80); + float baseSpeed = length(VELOCITY); + vec3 dirJitter = vec3(r2 * 2.0 - 1.0, r4 * 2.0 - 1.0, r5 * 2.0 - 1.0); + VELOCITY = VELOCITY * speedMult + dirJitter * (baseSpeed * 0.30); + + // Sub-frame / burst-window birth offset (0..55ms) with immediate curl + gravity advection + float dt0 = r3 * 0.055; + vec3 curl0 = aetheriaCurl(TRANSFORM[3].xyz, 3.0, 0.90, TIME); + if (pType < 0.5) { + VELOCITY += curl0 * (18.0 * dt0); + VELOCITY.y -= 11.0 * dt0; + } else if (pType < 1.5) { + VELOCITY += curl0 * (14.0 * dt0); + VELOCITY.y += 2.6 * dt0; + } else { + VELOCITY += curl0 * (10.0 * dt0); + VELOCITY.y -= 1.2 * dt0; + } + TRANSFORM[3].xyz += VELOCITY * dt0; + CUSTOM.y = min(CUSTOM.z * 0.35, dt0 * 0.65); + + TRANSFORM[0].xyz = VELOCITY; + TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0); + TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0); + } +} + +void process() { + float age = CUSTOM.y + DELTA; + float maxLife = max(0.01, CUSTOM.z); + if (age >= maxLife) { + ACTIVE = false; + } else { + CUSTOM.y = age; + float pType = floor(CUSTOM.w + 0.001); + float drag = fract(CUSTOM.w) * 20.0; + + if (pType > 2.5) { + // Type 3: MuzzleStarburst (stationary HDR flash) + VELOCITY = vec3(0.0); + TRANSFORM[0].xyz = vec3(1.0, 0.0, 0.0); + TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0); + TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0); + } else { + vec3 worldPos = TRANSFORM[3].xyz; + vec3 flowUv = (worldPos - rtd_flow_origin) * rtd_flow_inv_extent; + vec4 flowSample = vec4(0.0); + if (all(greaterThanEqual(flowUv, vec3(0.0))) && all(lessThanEqual(flowUv, vec3(1.0)))) { + flowSample = textureLod(rtd_flow_field, flowUv, 0.0); + } + + vec3 flowVel = flowSample.rgb; + float shockP = flowSample.a; + vec3 curl = aetheriaCurl(worldPos, 3.2, 0.85, TIME); + + if (pType < 0.5) { + // Type 0: VelocitySpark (ballistic + wispy Tri3D curl streams + flow drag + shock kick) + VELOCITY += (flowVel - VELOCITY) * min(1.0, drag * DELTA); + VELOCITY += curl * (22.0 * DELTA); + VELOCITY.y -= 11.0 * DELTA; + if (shockP > 0.20) { + VELOCITY += flowVel * (shockP * 0.55 * DELTA); + } + } else if (pType < 1.5) { + // Type 1: BuoyantEmber (upward buoyancy + swirling Tri3D thermal streams) + VELOCITY += (flowVel - VELOCITY) * min(1.0, drag * DELTA); + VELOCITY += curl * (15.5 * DELTA); + VELOCITY.y += 3.0 * DELTA; + if (shockP > 0.20) { + VELOCITY += flowVel * (shockP * 0.70 * DELTA); + } + } else { + // Type 2: DustMote (heavily flow-entrained ground grit + curl wisps) + float dustDrag = max(drag, 3.2); + VELOCITY += (flowVel - VELOCITY) * min(1.0, dustDrag * DELTA); + VELOCITY += curl * (11.0 * DELTA); + VELOCITY.y -= 1.2 * DELTA; + } + + TRANSFORM[3].xyz += VELOCITY * DELTA; + // Pass world VELOCITY to gpu_sparks_draw.gdshader cleanly via MODEL_MATRIX[0] + TRANSFORM[0].xyz = VELOCITY; + TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0); + TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0); + } + } +} diff --git a/client/hud_vignette.gdshader b/client/hud_vignette.gdshader new file mode 100644 index 0000000..a22a771 --- /dev/null +++ b/client/hud_vignette.gdshader @@ -0,0 +1,32 @@ +shader_type canvas_item; +render_mode blend_mix; + +// Forward+ Vulkan fullscreen combat vignette for damage impact, low core HP, and thermal overheat. +uniform float damage_pulse : hint_range(0.0, 1.0) = 0.0; +uniform float low_core_ratio : hint_range(0.0, 1.0) = 0.0; +uniform float overheat_pulse : hint_range(0.0, 1.0) = 0.0; +uniform float time_sec = 0.0; + +void fragment() { + vec2 p = UV * 2.0 - vec2(1.0); + float ellip_r = length(vec2(p.x * 0.88, p.y)); + float edge_mask = smoothstep(0.42, 1.18, ellip_r); + float tight_edge = smoothstep(0.68, 1.24, ellip_r); + + float low_heartbeat = low_core_ratio * (0.55 + 0.45 * sin(time_sec * 5.2)); + float red_strength = clamp(damage_pulse * 0.82 + low_heartbeat * 0.48, 0.0, 0.92); + + float thermal_wave = 0.72 + 0.28 * sin(time_sec * 11.0 + UV.y * 16.0); + float heat_strength = clamp(overheat_pulse * thermal_wave * 0.72, 0.0, 0.85); + + vec3 dmg_col = vec3(0.92, 0.14, 0.09); + vec3 heat_col = vec3(0.98, 0.50, 0.10); + + float dmg_a = edge_mask * red_strength * 0.58; + float heat_a = tight_edge * heat_strength * 0.52; + + float total_a = clamp(dmg_a + heat_a, 0.0, 0.78); + vec3 rgb = (dmg_col * dmg_a + heat_col * heat_a) / max(dmg_a + heat_a, 0.0001); + + COLOR = vec4(rgb, total_a); +} diff --git a/client/inventory_grid.gdshader b/client/inventory_grid.gdshader new file mode 100644 index 0000000..c77eb2d --- /dev/null +++ b/client/inventory_grid.gdshader @@ -0,0 +1,155 @@ +shader_type canvas_item; +render_mode blend_premul_alpha; + +// Port of Aetheria's UI/Inventory Grid shader to Godot 4 Forward+ Vulkan. +// Evaluates stateless interior cell fill: corner-folded texel masks, bilinear heat glow, +// hit-pulse flash, and 45-degree fracture hatching. Crisp vector frames, L-brackets, +// stripped X-marks, and Krypton labels are rendered by HbGpuCanvas on top. +// +// data_tex (3W x H, filter_nearest): +// 3x + 0 : cell/item fill & armor tint (RGBA) +// 3x + 1 : reserved / accent tint +// 3x + 2 : R = 8-bit neighbor mismatch mask (N,E,S,W,NE,SE,SW,NW) +// G = flags (bit0=present, bit1=item, bit2=hover, bit3=damaged/stripped, bit4=compatible, bit5=border_radiator) +// B = reserved (0) +// A = hit-pulse flash intensity (0..1) +// temp_tex (W x H, filter_linear): +// R = normalized temperature [20C..200C -> 0..1] +// G = thermal plateau / overheat stress [0..0.5 optimal, 0.5..1.0 overheating] +// B = active cell mask + +uniform sampler2D data_tex : filter_nearest, repeat_disable; +uniform sampler2D temp_tex : filter_linear, repeat_disable; + +uniform vec2 grid_size = vec2(4.0, 5.0); +uniform vec2 rect_size = vec2(180.0, 225.0); + +uniform float bg_texel = 1.0; +uniform float fill_inset = 2.6; +uniform float softness = 1.0; + +const float FAR = 1000.0; + +float box_profile(float x, float lo, float hi, float soft) { + if (hi < lo) { + return 0.0; + } + float outside = max(max(lo - x, x - hi), 0.0); + return clamp(1.0 - outside / soft, 0.0, 1.0); +} + +float eval_bg_mask(vec2 p, float cell_px, float texel, uint mask, float aa_px) { + float t = min(texel, cell_px / 8.0); + bool left = p.x < cell_px * 0.5; + bool top = p.y >= cell_px * 0.5; + float max_t = max(cell_px * 0.5 / t, 4.0); + float x = clamp((left ? p.x : cell_px - p.x) / t, 0.5, max_t); + float y = clamp((top ? cell_px - p.y : p.y) / t, 0.5, max_t); + + uint v_shift = top ? 0u : 2u; + uint h_shift = left ? 3u : 1u; + uint d_shift = top ? (left ? 7u : 4u) : (left ? 6u : 5u); + bool v = ((mask >> v_shift) & 1u) != 0u; + bool h = ((mask >> h_shift) & 1u) != 0u; + bool d = ((mask >> d_shift) & 1u) != 0u; + bool concave = !v && !h && d; + + float soft = clamp(softness * aa_px / max(t, 0.25), 0.15, 2.0); + float fill_lo = fill_inset + 0.5; + float fx = h ? box_profile(x, fill_lo, FAR, soft) : 1.0; + float fy = v ? box_profile(y, fill_lo, FAR, soft) : 1.0; + float f = fx * fy; + if (concave) { + f -= box_profile(x, -FAR, fill_inset - 0.5, soft) * box_profile(y, -FAR, fill_inset - 0.5, soft); + } + return clamp(f, 0.0, 1.0); +} + +vec3 thermal_ramp(float t) { + vec3 c0 = vec3(0.11, 0.18, 0.24); // ambient cool slate + vec3 c1 = vec3(0.24, 0.48, 0.34); // warm olive + vec3 c2 = vec3(0.86, 0.64, 0.18); // optimal plateau amber-gold + vec3 c3 = vec3(0.92, 0.28, 0.14); // hot crimson-orange + vec3 c4 = vec3(1.00, 0.85, 0.58); // critical incandescent + if (t < 0.25) return mix(c0, c1, t / 0.25); + if (t < 0.55) return mix(c1, c2, (t - 0.25) / 0.30); + if (t < 0.85) return mix(c2, c3, (t - 0.55) / 0.30); + return mix(c3, c4, (t - 0.85) / 0.15); +} + +void fragment() { + vec2 safe_grid = max(grid_size, vec2(1.0)); + vec2 cell_wh = rect_size / safe_grid; + float S = min(cell_wh.x, cell_wh.y); + vec2 grid_px = safe_grid * S; + vec2 origin = (rect_size - grid_px) * 0.5; + vec2 local_px = UV * rect_size - origin; + + // Hoist derivatives and implicit-LOD texture lookup above non-uniform branches (GLSL 330 helper quads) + float aa_px = clamp(max(fwidth(UV.x) * rect_size.x, fwidth(UV.y) * rect_size.y), 0.2, 2.0); + vec4 temp_sample = texture(temp_tex, clamp(local_px / max(grid_px, vec2(1.0)), vec2(0.0), vec2(1.0))); + + vec2 cellf = floor(local_px / S); + if (cellf.x < 0.0 || cellf.y < 0.0 || cellf.x >= safe_grid.x || cellf.y >= safe_grid.y) { + COLOR = vec4(0.0); + } else { + vec2 p_godot = local_px - cellf * S; + // Flip Y inside cell to match Aetheria's y-up Layer / Pipes convention + vec2 p = vec2(p_godot.x, S - p_godot.y); + + float tex_w = safe_grid.x * 3.0; + float ty = (cellf.y + 0.5) / safe_grid.y; + vec4 cell_fill = textureLod(data_tex, vec2((cellf.x * 3.0 + 0.5) / tex_w, ty), 0.0); + vec4 meta = textureLod(data_tex, vec2((cellf.x * 3.0 + 2.5) / tex_w, ty), 0.0); + + uint mask = uint(round(meta.r * 255.0)); + uint flags = uint(round(meta.g * 255.0)); + float hit_pulse = meta.a; + + if ((flags & 1u) == 0u) { + COLOR = vec4(0.0); + } else { + bool is_hover = (flags & 4u) != 0u; + bool is_damaged = (flags & 8u) != 0u; + bool is_compatible = (flags & 16u) != 0u; + + float norm_temp = temp_sample.r; + float plateau_stress = temp_sample.g; + vec3 heat_col = thermal_ramp(norm_temp); + + float a_bg = eval_bg_mask(p, S, bg_texel, mask, aa_px) * cell_fill.a; + + // Intact vs stripped (Armor == 0) interior fill with always-active subtle bilinear heat glow on hot cells + float hot_blend = smoothstep(0.05, 0.65, norm_temp) * 0.56; + vec3 base_rgb = mix(cell_fill.rgb, heat_col, hot_blend); + if (is_damaged) { + // Diagonal fracture/exposed-core hatching at 45 deg + float hatch_coord = (p_godot.x + p_godot.y) / max(S * 0.22, 4.0); + float hatch_dist = abs(fract(hatch_coord) - 0.5); + float hatch = 1.0 - smoothstep(0.10, 0.22, hatch_dist); + base_rgb = mix(base_rgb * 0.55, vec3(0.82, 0.20, 0.14), hatch * 0.65); + } + + // Direct bilinear thermal plateau glow over hot cells + float overheat_glow = max(plateau_stress - 0.5, 0.0) * 2.0; + base_rgb += heat_col * (0.20 * norm_temp + 0.30 * overheat_glow); + base_rgb = clamp(base_rgb, vec3(0.0), vec3(1.0)); + + if (is_compatible) { + float pulse = 0.72 + 0.28 * sin(TIME * 6.5); + base_rgb = mix(base_rgb, vec3(0.96, 0.82, 0.30), 0.16 * pulse); + } + if (is_hover) { + base_rgb = mix(base_rgb, vec3(0.95, 0.94, 0.88), 0.16); + } + + // Active hit-pulse impact flash + vec3 flash_col = vec3(1.0, 0.76, 0.38); + base_rgb = clamp(mix(base_rgb, flash_col, hit_pulse * 0.85), vec3(0.0), vec3(1.0)); + + float out_a = clamp(a_bg, 0.0, 1.0); + vec3 out_rgb = clamp(base_rgb, vec3(0.0), vec3(1.0)) * out_a; + COLOR = vec4(out_rgb, out_a); + } + } +} diff --git a/client/mech_paint.gdshader b/client/mech_paint.gdshader new file mode 100644 index 0000000..510173b --- /dev/null +++ b/client/mech_paint.gdshader @@ -0,0 +1,360 @@ +shader_type spatial; +render_mode cull_back, depth_draw_opaque; + +// Real-time Forward+ Vulkan port of Brokkr's 6-layer MechPaint. +// Samples 3D procedural noise in rest-pose object space (v_local_pos, v_local_nrm) +// so weathering never swims during skeletal/joint animation or chassis motion. +// +// Expects baked vertex COLOR_0: +// R = geometric cavity AO (0 = deep crevice, 1 = open exposed face) +// G = convex dihedral edge curvature (0 = flat, 1 = sharp exposed edge) +// B = per-island connected-component hash (0..1) +// A = rest-pose height above ground (meters / 6.0, clamped 0..1) +// +// Live combat channels (via INSTANCE_CUSTOM or uniform fallback for non-MultiMesh): +// INSTANCE_CUSTOM.x / scorch (0..1) -> char/soot darkening + matte roughness +// INSTANCE_CUSTOM.y / heat_glow (0..1) -> incandescent orange-red emission without cloning materials + +uniform vec4 base_color : source_color = vec4(0.306, 0.341, 0.251, 1.0); +uniform float roughness : hint_range(0.0, 1.0) = 0.58; +uniform float metallic : hint_range(0.0, 1.0) = 0.28; +uniform float tone_variation : hint_range(0.0, 1.0) = 0.30; +uniform float mottle : hint_range(0.0, 2.0) = 1.0; +uniform float noise_scale : hint_range(0.1, 10.0) = 1.0; + +uniform float grime : hint_range(0.0, 2.0) = 0.90; +uniform vec4 grime_color : source_color = vec4(0.145, 0.133, 0.114, 1.0); + +uniform float streaks : hint_range(0.0, 2.0) = 0.95; +uniform float dust : hint_range(0.0, 2.0) = 0.55; +uniform vec4 dust_color : source_color = vec4(0.451, 0.431, 0.388, 1.0); + +uniform float wear : hint_range(0.0, 2.5) = 0.95; +uniform vec4 chip_color : source_color = vec4(0.460, 0.470, 0.465, 1.0); +uniform float chip_metallic : hint_range(0.0, 1.0) = 0.85; +uniform float chip_roughness : hint_range(0.0, 1.0) = 0.28; +uniform vec4 primer_color : source_color = vec4(0.345, 0.325, 0.286, 1.0); + +uniform float mud : hint_range(0.0, 2.0) = 1.0; +uniform float mud_top : hint_range(0.1, 5.0) = 1.45; +uniform vec4 mud_color : source_color = vec4(0.180, 0.148, 0.118, 1.0); +uniform float wet : hint_range(0.0, 2.0) = 0.60; +uniform float wet_top : hint_range(0.1, 6.0) = 2.80; + +uniform float scorch : hint_range(0.0, 1.0) = 0.0; +uniform float heat_glow : hint_range(0.0, 1.0) = 0.0; +uniform float heat_emission_energy : hint_range(0.0, 8.0) = 2.6; +uniform bool use_vertex_material = false; + +varying vec3 v_local_pos; +varying vec3 v_local_nrm; +varying vec4 v_color; +varying vec4 v_mat_data; +varying float v_scorch; +varying float v_heat; +varying float v_role; +varying float v_alpha; + +// Safe remapping helper supporting inverted bounds (lo > hi) without GLSL smoothstep UB. +float map_range(float v, float lo, float hi, float out_lo, float out_hi) { + float denom = hi - lo; + float t = abs(denom) > 1e-6 ? clamp((v - lo) / denom, 0.0, 1.0) : 0.0; + t = t * t * (3.0 - 2.0 * t); + return mix(out_lo, out_hi, t); +} + +float hash31(vec3 p) { + p = fract(p * vec3(0.1031, 0.1030, 0.0973)); + p += dot(p, p.yxz + 33.33); + return fract((p.x + p.y) * p.z); +} + +float noise3d(vec3 p) { + vec3 i = floor(p); + vec3 f = fract(p); + vec3 u = f * f * (3.0 - 2.0 * f); + + float n000 = hash31(i + vec3(0.0, 0.0, 0.0)); + float n100 = hash31(i + vec3(1.0, 0.0, 0.0)); + float n010 = hash31(i + vec3(0.0, 1.0, 0.0)); + float n110 = hash31(i + vec3(1.0, 1.0, 0.0)); + float n001 = hash31(i + vec3(0.0, 0.0, 1.0)); + float n101 = hash31(i + vec3(1.0, 0.0, 1.0)); + float n011 = hash31(i + vec3(0.0, 1.0, 1.0)); + float n111 = hash31(i + vec3(1.0, 1.0, 1.0)); + + float nx00 = mix(n000, n100, u.x); + float nx10 = mix(n010, n110, u.x); + float nx01 = mix(n001, n101, u.x); + float nx11 = mix(n011, n111, u.x); + float nxy0 = mix(nx00, nx10, u.y); + float nxy1 = mix(nx01, nx11, u.y); + return mix(nxy0, nxy1, u.z); +} + +float fbm2(vec3 p) { + // Rotate second octave to eliminate cubic lattice grid alignment + const mat3 rot = mat3( + vec3(0.80, -0.48, 0.36), + vec3(0.60, 0.64, -0.48), + vec3(0.00, 0.60, 0.80) + ); + float a = noise3d(p); + float b = noise3d((rot * p) * 2.17 + vec3(17.3, 9.1, 23.7)); + float c = noise3d((rot * p) * 4.61 + vec3(5.7, 31.4, 11.2)); + return a * 0.55 + b * 0.30 + c * 0.15; +} + +vec3 rgb_to_hsv(vec3 c) { + vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); + vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); + vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); + float d = q.x - min(q.w, q.y); + float e = 1.0e-6; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); +} + +vec3 hsv_to_rgb(vec3 c) { + vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); + return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); +} + +void vertex() { + v_local_pos = VERTEX; + v_local_nrm = NORMAL; + v_color = COLOR; + v_mat_data = vec4(UV.x, UV.y, UV2.x, UV2.y); + v_scorch = clamp(max(INSTANCE_CUSTOM.x, scorch), 0.0, 1.0); + v_heat = clamp(max(INSTANCE_CUSTOM.y, heat_glow), 0.0, 1.0); + v_role = INSTANCE_CUSTOM.z; + v_alpha = use_vertex_material ? clamp(INSTANCE_CUSTOM.w, 0.0, 1.0) : 1.0; +} + +void resolve_role_armor(int role, out vec3 col, out float met, out float rgh) { + if (role == 1) { + col = vec3(0.109, 0.074, 0.054); met = 0.26; rgh = 0.58; // Rival (#5d4d42) + } else if (role == 2) { + col = vec3(0.791, 0.479, 0.039); met = 0.72; rgh = 0.30; // SpectatorTourist (#e6b838) + } else if (role == 3) { + col = vec3(0.026, 0.195, 0.188); met = 0.32; rgh = 0.50; // SpectatorPatron (#2d7a78) + } else if (role == 4) { + col = vec3(0.011, 0.011, 0.016); met = 0.45; rgh = 0.42; // SpectatorExemplar (#1b1b22) + } else if (role == 5) { + col = vec3(0.089, 0.105, 0.107); met = 0.55; rgh = 0.48; // SalvageDrop (#545b5c) + } else if (role == 10) { + col = vec3(0.076, 0.095, 0.051); met = 0.30; rgh = 0.58; // ScrapFrontier (#4e5740) + } else if (role == 11) { + col = vec3(0.017, 0.019, 0.022); met = 0.72; rgh = 0.40; // KorrathiIronworks (#232629) + } else if (role == 12) { + col = vec3(0.888, 0.823, 0.687); met = 0.18; rgh = 0.34; // AuralianOptics (#f2ead8) + } else if (role == 13) { + col = vec3(0.023, 0.028, 0.039); met = 0.50; rgh = 0.38; // VexNineCollective (#2a2f38) + } else if (role == 14) { + col = vec3(0.013, 0.127, 0.138); met = 0.56; rgh = 0.36; // ThalassanForge (#1e6468) + } else { + col = vec3(0.076, 0.095, 0.051); met = 0.28; rgh = 0.58; // Player (#4e5740) + } +} + +void resolve_role_accent(int role, out vec3 col, out float met, out float rgh, out float emit_e) { + emit_e = 0.0; + if (role == 1) { + col = vec3(0.468, 0.068, 0.032); met = 0.20; rgh = 0.46; // Rival (#b64a32) + } else if (role == 2) { + col = vec3(0.896, 0.823, 0.687); met = 0.16; rgh = 0.38; // SpectatorTourist (#f2ead8) + } else if (role == 3) { + col = vec3(0.392, 0.147, 0.037); met = 0.65; rgh = 0.36; // SpectatorPatron (#a86c36) + } else if (role == 4) { + col = vec3(0.584, 0.023, 0.023); met = 0.25; rgh = 0.36; emit_e = 0.65; // SpectatorExemplar (#c92a2a) + } else if (role == 5) { + col = vec3(0.058, 0.694, 0.807); met = 0.22; rgh = 0.34; emit_e = 0.45; // SalvageDrop (#44d9e8) + } else if (role == 10) { + col = vec3(0.258, 0.068, 0.024); met = 0.34; rgh = 0.52; // ScrapFrontier rust (#8b4a2b) + } else if (role == 11) { + col = vec3(0.753, 0.048, 0.010); met = 0.22; rgh = 0.42; // KorrathiIronworks hazard-red (#e13e1a) + } else if (role == 12) { + col = vec3(0.791, 0.479, 0.039); met = 0.88; rgh = 0.26; // AuralianOptics gold (#e6b838) + } else if (role == 13) { + col = vec3(0.258, 0.061, 0.658); met = 0.32; rgh = 0.36; emit_e = 0.15; // VexNineCollective violet (#8b46d4) + } else if (role == 14) { + col = vec3(0.578, 0.168, 0.039); met = 0.86; rgh = 0.30; // ThalassanForge copper-brass (#c87238) + } else { + col = vec3(0.694, 0.150, 0.020); met = 0.18; rgh = 0.44; // Player (#d96c27) + } +} + +void resolve_role_glow(int role, inout vec3 col) { + if (role == 10) { + col = vec3(1.000, 0.402, 0.033); // ScrapFrontier amber (#ffaa33) + } else if (role == 11) { + col = vec3(0.888, 0.552, 0.016); // KorrathiIronworks hazard-yellow (#f2c422) + } else if (role == 12) { + col = vec3(0.039, 0.807, 1.000); // AuralianOptics cyan (#38e8ff) + } else if (role == 13) { + col = vec3(0.201, 0.888, 0.030); // VexNineCollective lime-optic (#7cf230) + } else if (role == 14) { + col = vec3(0.025, 0.479, 1.000); // ThalassanForge electric-blue (#2cb8ff) + } +} + +void fragment() { + if (v_alpha < 0.99) { + float dither = fract(sin(dot(floor(FRAGCOORD.xy), vec2(12.9898, 78.233))) * 43758.5453); + if (v_alpha < dither) { + discard; + } + } + + vec3 mat_base_col = base_color.rgb; + float mat_rough = roughness; + float mat_metal = metallic; + float mat_wear = wear; + float mat_mud = mud; + float mat_grime = grime; + float mat_static_emit = 0.0; + if (use_vertex_material) { + int band = int(floor((v_mat_data.w + 0.5) * 0.5)); + mat_rough = clamp(v_mat_data.w - float(band) * 2.0, 0.08, 0.95); + mat_base_col = clamp(v_mat_data.rgb, vec3(0.0), vec3(1.0)); + int role = int(floor(v_role + 0.5)); + if (band == 0) { + mat_metal = 0.12; + } else if (band == 1) { + mat_metal = 0.55; + } else if (band == 2) { + mat_metal = 0.85; + } else if (band == 3) { + resolve_role_armor(role, mat_base_col, mat_metal, mat_rough); + } else if (band == 4) { + resolve_role_accent(role, mat_base_col, mat_metal, mat_rough, mat_static_emit); + } else if (band == 5) { + if (role >= 10 && role <= 14) { + resolve_role_glow(role, mat_base_col); + } + mat_metal = 0.15; + mat_static_emit = 1.85; + mat_wear = 0.0; + mat_mud = 0.0; + } else if (band == 6) { + mat_metal = 0.26; + } else if (band == 8) { + mat_metal = 0.35; + mat_wear = 0.0; + mat_mud = 0.0; + mat_grime = 0.15; + } else { + mat_metal = 0.65; + } + } + + vec3 pos = v_local_pos * noise_scale; + vec3 nrm = normalize(v_local_nrm); + float up = nrm.y; + + float occ = clamp(v_color.r, 0.0, 1.0); + float edge = clamp(v_color.g, 0.0, 1.0); + float island_rand = clamp(v_color.b, 0.0, 1.0); + float height_m = clamp(v_color.a, 0.0, 1.0) * 6.0; + + // Shared rotated multi-scale 3D noise basis (5 lookups total vs 352 hashes across 6 layers) + const mat3 rot = mat3( + vec3(0.80, -0.48, 0.36), + vec3(0.60, 0.64, -0.48), + vec3(0.00, 0.60, 0.80) + ); + vec3 rpos = rot * pos; + float n_macro = noise3d(pos * 0.85); + float n_mid = noise3d(rpos * 3.8 + vec3(17.3, 9.1, 23.7)); + float n_fine = noise3d(pos * 10.5 + vec3(5.7, 31.4, 11.2)); + float n_speck = noise3d(rpos * 27.0 + vec3(11.1, 3.7, 19.4)); + float n_streak = noise3d(pos * vec3(13.0, 0.5, 13.0)); + + // Layer 1: Base paint + per-island tone variation + multi-octave mottle + float rand2 = fract(island_rand * 7.31 + 0.37); + vec3 hsv = rgb_to_hsv(mat_base_col); + hsv.x = fract(hsv.x + (rand2 - 0.5) * tone_variation * 0.14); + hsv.y = clamp(hsv.y * (1.0 + (rand2 - 0.5) * tone_variation * 0.75), 0.0, 1.0); + hsv.z = clamp(hsv.z * (1.0 + (island_rand * 2.0 - 1.0) * tone_variation * 0.65), 0.01, 2.0); + vec3 col = hsv_to_rgb(hsv); + + float blotch = n_macro * 0.70 + n_mid * 0.30; + float mid_n = n_mid * 0.68 + n_fine * 0.32; + float shade = map_range(blotch, 0.25, 0.75, -0.14, 0.14) + + map_range(n_speck, 0.25, 0.75, -0.07, 0.07) + + map_range(mid_n, 0.25, 0.75, -0.09, 0.09); + col *= clamp(1.0 + shade * mottle, 0.55, 1.35); + + // Layer 2: Cavity grime darkening + roughness boost from (1 - AO) + float cavity = clamp(map_range(occ, 0.90, 0.42, 0.0, 1.0) * map_range(mid_n, 0.30, 0.65, 0.45, 1.0) * mat_grime, 0.0, 1.0); + float film = clamp(map_range(n_macro * 0.5 + n_mid * 0.5, 0.54, 0.72, 0.0, 1.0) * 0.30 * mat_grime, 0.0, 1.0); + float grime_amt = max(cavity, film); + col = mix(col, grime_color.rgb, min(grime_amt, 0.85)); + + // Layer 3: Vertical rain/oil streaks on upright surfaces boosted by cavity + float upright = map_range(abs(up), 0.80, 0.35, 0.0, 1.0); + float under = map_range(occ, 0.96, 0.65, 0.40, 1.0); + float broken = map_range(n_macro, 0.35, 0.55, 0.15, 1.0); + float streak_mix = n_streak * 0.72 + n_fine * 0.28; + float dark_run = clamp(map_range(streak_mix, 0.52, 0.68, 0.0, 1.0) * upright * under * broken * streaks, 0.0, 1.0); + float pale_run = clamp(map_range(1.0 - streak_mix, 0.62, 0.76, 0.0, 1.0) * upright * 0.28 * streaks, 0.0, 1.0); + col = mix(col, dust_color.rgb, pale_run); + col = mix(col, grime_color.rgb, dark_run * 0.85); + + // Layer 4: Pale dust on upward-facing normals (v_local_nrm.y) + float dust_amt = clamp(map_range(up, 0.45, 0.95, 0.0, 1.0) * map_range(mid_n, 0.25, 0.70, 0.25, 1.0) * dust * 0.55, 0.0, 1.0); + col = mix(col, dust_color.rgb, dust_amt); + + // Layer 5: Metallic edge chipping + thin primer_color halo from edge_curvature * noise + float exposed = map_range(occ, 0.42, 0.88, 0.0, 1.0); + float edge_sharp = pow(edge, 1.85); + float chip_n = map_range(n_mid * 0.6 + n_fine * 0.4, 0.30, 0.72, 0.0, 0.44) + + map_range(n_speck, 0.30, 0.70, -0.06, 0.06); + float wear_level = chip_n + edge_sharp * exposed * mat_wear * 0.56; + float scuff = map_range(mid_n, 0.68, 0.72, 0.0, 1.0) * clamp(mat_wear / 1.8, 0.0, 1.0) * 0.55; + float chip_metal_mask = clamp(max(map_range(wear_level, 0.76, 0.80, 0.0, 1.0), scuff * 0.85), 0.0, 1.0); + float primer_mask = clamp(max(map_range(wear_level, 0.71, 0.75, 0.0, 1.0), scuff), 0.0, 1.0); + col = mix(col, primer_color.rgb, primer_mask * 0.75); + col = mix(col, chip_color.rgb, chip_metal_mask); + + // Layer 6: Lower-hull/foot mud & wet gloss driven by rest_height (COLOR.a) + float wet_amt = clamp(map_range(height_m, wet_top, 0.0, 0.0, 1.0) * wet * clamp(mat_mud, 0.0, 1.0), 0.0, 1.0); + col *= (1.0 - 0.50 * wet_amt); + float mud_n = n_macro * 0.35 + n_mid * 0.65; + float thick = map_range(height_m, mud_top, 0.0, 0.0, 1.0) + * map_range(mud_n, 0.35, 0.62, 0.1, 1.5) + * map_range(occ, 0.95, 0.50, 0.7, 1.6) * mat_mud; + float splash = map_range(n_fine, 0.62, 0.66, 0.0, 1.0) + * map_range(height_m, mud_top * 2.2, mud_top * 0.4, 0.0, 1.0) * mat_mud * 0.85; + float mud_amt = clamp(max(map_range(thick, 0.20, 0.50, 0.0, 1.0), splash), 0.0, 1.0); + col = mix(col, mud_color.rgb * map_range(mud_n, 0.30, 0.70, 0.70, 1.30), mud_amt); + + // PBR metallic & roughness synthesis + float out_metallic = mix(mat_metal, chip_metallic, chip_metal_mask); + out_metallic *= (1.0 - mud_amt) * (1.0 - grime_amt * 0.70); + + float out_rough = mat_rough + grime_amt * 0.22 + (1.0 - occ) * 0.12 * clamp(mat_grime, 0.0, 1.0); + out_rough = mix(out_rough, chip_roughness, chip_metal_mask); + out_rough -= wet_amt * 0.18; + out_rough += mud_amt * 0.18; + out_rough = clamp(out_rough, 0.08, 0.98); + + // Live combat channel 1: scorch (char/soot darkening + matte roughness) + float soot_pat = mix(0.65, 1.0, mid_n); + float scorch_mask = clamp(v_scorch * soot_pat, 0.0, 1.0); + col = mix(col, vec3(0.022, 0.018, 0.016), scorch_mask * 0.88); + out_metallic *= (1.0 - scorch_mask * 0.75); + out_rough = mix(out_rough, 0.94, scorch_mask); + + // Live combat channel 2: heat_glow (incandescent orange-red emission without cloning material) + float heat_mod = mix(0.25, 1.15, pow(edge, 1.4) * 0.6 + mid_n * 0.4); + float h_val = clamp(v_heat * heat_mod, 0.0, 1.0); + vec3 heat_col = mix(vec3(0.85, 0.12, 0.01), vec3(1.0, 0.52, 0.10), smoothstep(0.25, 0.95, h_val)); + + ALBEDO = col; + METALLIC = clamp(out_metallic, 0.0, 1.0); + ROUGHNESS = out_rough; + AO = mix(1.0, occ, 0.65); + AO_LIGHT_AFFECT = 0.65; + EMISSION = mat_base_col * mat_static_emit + heat_col * (pow(v_heat, 1.35) * heat_mod * heat_emission_energy); +} diff --git a/client/panel_chrome.gdshader b/client/panel_chrome.gdshader new file mode 100644 index 0000000..2aa8a0f --- /dev/null +++ b/client/panel_chrome.gdshader @@ -0,0 +1,80 @@ +shader_type canvas_item; +render_mode blend_premul_alpha; + +// Resolution-independent industrial panel chrome using the same analytical corner-folded +// Box / L-bracket + hairline border + inset fill math as inventory_grid.gdshader (1x1 cell). +// Stays razor-sharp at 720p, 1080p, 1440p, and 4K. + +uniform vec2 rect_size = vec2(320.0, 160.0); +uniform float corner_len = 12.0; +uniform float border_px = 1.5; +uniform float fill_inset = 2.0; +uniform float rule_inset = 1.5; +uniform float rule_alpha = 0.55; +uniform float bracket_alpha = 1.0; +uniform float top_bar_px = 2.0; +uniform float scanline_strength = 0.045; + +uniform vec4 bg_color : source_color = vec4(0.075, 0.086, 0.075, 0.88); +uniform vec4 border_color : source_color = vec4(0.243, 0.275, 0.220, 1.0); +uniform vec4 accent_color : source_color = vec4(0.878, 0.541, 0.290, 1.0); + +const float FAR = 10000.0; + +float box_profile(float x, float lo, float hi, float soft) { + if (hi < lo) { + return 0.0; + } + float outside = max(max(lo - x, x - hi), 0.0); + return clamp(1.0 - outside / max(soft, 0.05), 0.0, 1.0); +} + +void fragment() { + vec2 size = max(rect_size, vec2(4.0)); + vec2 p = UV * size; + float aa = clamp(max(fwidth(UV.x) * size.x, fwidth(UV.y) * size.y), 0.2, 2.0); + + // Fold into nearest corner quadrant (1x1 cell, all 4 cardinal edges active) + bool left = p.x < size.x * 0.5; + bool top = p.y < size.y * 0.5; + float x = max(left ? p.x : size.x - p.x, 0.5 * aa); + float y = max(top ? p.y : size.y - p.y, 0.5 * aa); + + // Inset background fill + float fx = box_profile(x, fill_inset, FAR, aa); + float fy = box_profile(y, fill_inset, FAR, aa); + float fill_mask = fx * fy; + + // Hairline border and corner L-brackets (logical thickness stays fixed in rect_size units) + float ri = rule_inset; + float half_w = max(border_px - 1.0, 0.0) * 0.5; + float rlo = ri - half_w; + float rhi = ri + half_w; + float rx = box_profile(x, rlo, rhi, aa); + float ry = box_profile(y, rlo, rhi, aa); + + float rule_mask = max(ry * box_profile(x, rlo, FAR, aa), rx * box_profile(y, rlo, FAR, aa)); + float clen = min(corner_len, min(size.x, size.y) * 0.35); + float bracket_mask = max(ry * box_profile(x, rlo, ri + clen, aa), rx * box_profile(y, rlo, ri + clen, aa)); + + // Subtle top-bar & micro-scanline accent inside the fill + float top_bar = box_profile(p.y, fill_inset + 0.5, fill_inset + 0.5 + top_bar_px, aa) * fx; + float scan = 1.0 - scanline_strength * (0.5 + 0.5 * sin(p.y * 2.0943951)); + + vec3 fill_rgb = mix(bg_color.rgb * scan, accent_color.rgb, top_bar * 0.24); + float fill_a = fill_mask * bg_color.a; + + float edge_rule = clamp(rule_mask - bracket_mask, 0.0, 1.0) * rule_alpha * border_color.a; + float edge_bracket = bracket_mask * bracket_alpha * accent_color.a; + + vec3 rgb = fill_rgb * fill_a; + float alpha = fill_a; + + rgb = border_color.rgb * edge_rule + rgb * (1.0 - edge_rule); + alpha = edge_rule + alpha * (1.0 - edge_rule); + + rgb = accent_color.rgb * edge_bracket + rgb * (1.0 - edge_bracket); + alpha = edge_bracket + alpha * (1.0 - edge_bracket); + + COLOR = vec4(rgb, clamp(alpha, 0.0, 1.0)); +} diff --git a/client/project.godot b/client/project.godot new file mode 100644 index 0000000..c4a58ec --- /dev/null +++ b/client/project.godot @@ -0,0 +1,44 @@ +; Engine configuration file. +; It's best edited using the editor UI and not directly, +; since the parameters that go here are not all obvious. + +config_version=5 + +[application] + +config/name="Rust to Dust" +run/main_scene="res://Main.tscn" +config/features=PackedStringArray("4.7", "C#") + +[display] + +window/size/viewport_width=1280 +window/size/viewport_height=720 +window/stretch/mode="canvas_items" + +[dotnet] + +project/assembly_name="RustToDust.Client" + +[gui] + +theme/custom_font="res://fonts/MonaspaceKrypton-Regular.otf" + +[physics] + +; Godot's physics is switched off: Ymir is the only physics world. ArenaSession ticks at 60 Hz. +3d/physics_engine="Dummy" +common/physics_ticks_per_second=60 +common/physics_interpolation=true + +[rendering] + +renderer/rendering_method="forward_plus" +renderer/rendering_method.mobile="forward_plus" +anti_aliasing/quality/use_taa=true +anti_aliasing/screen_space_roughness_limiter/enabled=true +lights_and_shadows/directional_shadow/size=4096 +lights_and_shadows/directional_shadow/soft_shadow_filter_quality=3 +environment/volumetric_fog/volume_size=64 +environment/volumetric_fog/volume_depth=96 +environment/screen_space_reflection/half_size=true diff --git a/client/sky_atmosphere.gdshader b/client/sky_atmosphere.gdshader new file mode 100644 index 0000000..c56dcf9 --- /dev/null +++ b/client/sky_atmosphere.gdshader @@ -0,0 +1,58 @@ +shader_type sky; + +// Forward+ Vulkan precomputed Bruneton/Hillaire atmospheric scattering skybox. +// Single bilinear LUT lookup per fragment + analytic limb-darkened solar disc & Mie aureole. + +uniform sampler2D skyview_lut : filter_linear, repeat_enable; +uniform vec3 sun_dir = vec3(0.41, 0.59, 0.69); +uniform vec3 sun_transmittance = vec3(0.88, 0.85, 0.78); +uniform float horizon_elev = -0.0124; +uniform float sun_disc_intensity = 8.5; +uniform float mie_aureole_strength = 0.24; +uniform float sky_exposure = 1.0; + +void sky() { + vec3 dir = normalize(EYEDIR); + vec3 sdir = normalize(sun_dir); + + vec2 dir_xz = dir.xz; + vec2 sun_xz = sdir.xz; + float dir_len = length(dir_xz); + float sun_len = length(sun_xz); + float u = 0.0; + if (dir_len > 1e-5 && sun_len > 1e-5) { + vec2 d2 = dir_xz / dir_len; + vec2 s2 = sun_xz / sun_len; + float c = clamp(dot(d2, s2), -1.0, 1.0); + float s = d2.x * s2.y - d2.y * s2.x; + float dphi = atan(s, c); + if (dphi < 0.0) { + dphi += 2.0 * PI; + } + u = dphi / (2.0 * PI); + } + + float alpha = asin(clamp(dir.y, -1.0, 1.0)); + float v; + if (alpha >= horizon_elev) { + float l = sqrt(clamp((alpha - horizon_elev) / max(0.0001, PI * 0.5 - horizon_elev), 0.0, 1.0)); + v = 0.5 + 0.5 * l; + } else { + float l = sqrt(clamp((horizon_elev - alpha) / max(0.0001, PI * 0.5 + horizon_elev), 0.0, 1.0)); + v = 0.5 - 0.5 * l; + } + v = clamp(v, 0.5 / 128.0, 127.5 / 128.0); + + vec3 sky_rad = textureLod(skyview_lut, vec2(u, v), 0.0).rgb * sky_exposure; + + if (!AT_CUBEMAP_PASS && LIGHT0_ENABLED) { + float sun_dot = dot(dir, sdir); + float disc = smoothstep(0.99985, 0.99997, sun_dot); + float limb = smoothstep(0.99985, 0.99999, sun_dot) * 0.35 + 0.65; + float aureole = pow(max(sun_dot, 0.0), 64.0) * mie_aureole_strength; + float horizon_fade = smoothstep(-0.02, 0.04, dir.y); + sky_rad += sun_transmittance * (disc * limb * sun_disc_intensity + aureole) * horizon_fade; + } + + COLOR = sky_rad; +} diff --git a/client/terrain_surface.gdshader b/client/terrain_surface.gdshader new file mode 100644 index 0000000..0818af1 --- /dev/null +++ b/client/terrain_surface.gdshader @@ -0,0 +1,147 @@ +shader_type spatial; +render_mode cull_back, depth_draw_opaque; + +uniform sampler2D base_dem_tex : filter_linear, repeat_disable; +uniform sampler2D base_surface_tex : source_color, filter_linear_mipmap, repeat_disable; +uniform sampler2D base_mask_tex : filter_linear_mipmap, repeat_disable; +uniform sampler2D delta_height_tex : filter_linear, repeat_disable; +uniform sampler2D delta_albedo_tex : source_color, filter_linear, repeat_disable; + +uniform float dem_min_y = 0.0; +uniform float dem_scale_span = 0.0; +uniform float dem_grid_res = 6145.0; +uniform float height_min = -18.0; +uniform float height_max = 52.0; +uniform float map_size = 1536.0; +uniform float tile_origin_x = 0.0; +uniform float tile_origin_z = 0.0; +uniform float tile_size = 192.0; +uniform float inner_span = 384.0; +uniform float tex_size = 388.0; +uniform float gutter_center = 2.5; +uniform float is_sion = 0.0; +uniform float tile_quads = 192.0; +uniform vec4 neighbor_quads = vec4(192.0, 192.0, 192.0, 192.0); // (-X, +X, -Z, +Z) + +varying vec3 v_world_pos; + +float hash21(vec2 p) { + p = fract(p * vec2(123.34, 456.21)); + p += dot(p, p + 45.32); + return fract(p.x * p.y); +} + +float value_noise(vec2 p) { + vec2 i = floor(p); + vec2 f = fract(p); + vec2 u = f * f * (3.0 - 2.0 * f); + float a = hash21(i); + float b = hash21(i + vec2(1.0, 0.0)); + float c = hash21(i + vec2(0.0, 1.0)); + float d = hash21(i + vec2(1.0, 1.0)); + return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); +} + +vec2 to_baked_uv(vec2 mesh_uv) { + return (mesh_uv * inner_span + gutter_center) / tex_size; +} + +float sample_total_height(vec2 mesh_uv) { + vec2 world_xz = vec2(tile_origin_x, tile_origin_z) + mesh_uv * tile_size; + float base_h = 0.0; + if (is_sion > 0.5) { + float max_idx = dem_grid_res - 1.0; + vec2 dem_uv = ((world_xz + map_size * 0.5) / map_size * max_idx + 0.5) / dem_grid_res; + base_h = dem_min_y + textureLod(base_dem_tex, dem_uv, 0.0).r * dem_scale_span; + } + float delta_h = textureLod(delta_height_tex, to_baked_uv(mesh_uv), 0.0).r; + return clamp(base_h + delta_h, height_min, height_max); +} + +float sample_edge_snapped_height(vec2 uv) { + // Zero T-junction cracks: if an adjacent tile is coarser, snap edge vertex height + // onto the exact linear segment connecting the neighbor's coarse edge vertices. + if (uv.x < 0.0005 && neighbor_quads.x < tile_quads - 0.5) { + float nq = neighbor_quads.x; + float t = uv.y * nq; + float i0 = floor(t); + float u0 = i0 / nq; + float u1 = min(1.0, (i0 + 1.0) / nq); + return mix(sample_total_height(vec2(0.0, u0)), sample_total_height(vec2(0.0, u1)), t - i0); + } + if (uv.x > 0.9995 && neighbor_quads.y < tile_quads - 0.5) { + float nq = neighbor_quads.y; + float t = uv.y * nq; + float i0 = floor(t); + float u0 = i0 / nq; + float u1 = min(1.0, (i0 + 1.0) / nq); + return mix(sample_total_height(vec2(1.0, u0)), sample_total_height(vec2(1.0, u1)), t - i0); + } + if (uv.y < 0.0005 && neighbor_quads.z < tile_quads - 0.5) { + float nq = neighbor_quads.z; + float t = uv.x * nq; + float i0 = floor(t); + float u0 = i0 / nq; + float u1 = min(1.0, (i0 + 1.0) / nq); + return mix(sample_total_height(vec2(u0, 0.0)), sample_total_height(vec2(u1, 0.0)), t - i0); + } + if (uv.y > 0.9995 && neighbor_quads.w < tile_quads - 0.5) { + float nq = neighbor_quads.w; + float t = uv.x * nq; + float i0 = floor(t); + float u0 = i0 / nq; + float u1 = min(1.0, (i0 + 1.0) / nq); + return mix(sample_total_height(vec2(u0, 1.0)), sample_total_height(vec2(u1, 1.0)), t - i0); + } + return sample_total_height(uv); +} + +void vertex() { + float h = sample_edge_snapped_height(UV); + VERTEX.y += h; + v_world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz; +} + +void fragment() { + float world_step = tile_size / inner_span; // 0.5m + float uv_step = world_step / tile_size; + + float hL = sample_total_height(UV - vec2(uv_step, 0.0)); + float hR = sample_total_height(UV + vec2(uv_step, 0.0)); + float hD = sample_total_height(UV - vec2(0.0, uv_step)); + float hU = sample_total_height(UV + vec2(0.0, uv_step)); + + vec3 world_normal = normalize(vec3(hL - hR, 2.0 * world_step, hD - hU)); + NORMAL = normalize((VIEW_MATRIX * vec4(world_normal, 0.0)).xyz); + + vec2 uv_baked = to_baked_uv(UV); + vec4 mat = texture(delta_height_tex, uv_baked); + vec3 delta_alb = texture(delta_albedo_tex, uv_baked).rgb; + float scorch = clamp(mat.b, 0.0, 1.0); + + vec3 alb; + float rough = clamp(mat.g, 0.35, 1.0); + if (is_sion > 0.5) { + vec2 world_uv = (v_world_pos.xz + map_size * 0.5) / map_size; + vec3 base_col = texture(base_surface_tex, world_uv).rgb; + vec4 cls = texture(base_mask_tex, world_uv); + alb = mix(base_col, delta_alb, clamp(mat.a, 0.0, 1.0)); + + float dist = length((INV_VIEW_MATRIX * vec4(0.0, 0.0, 0.0, 1.0)).xyz - v_world_pos); + float near_fade = clamp(1.0 - smoothstep(140.0, 480.0, dist), 0.12, 1.0); + float macro = (value_noise(v_world_pos.xz * 0.28) - 0.5) * 0.07; + float grit = (hash21(floor(v_world_pos.xz * 8.0)) - 0.5) * 0.045; + alb = clamp(alb * (1.0 + macro * 1.4 + grit * 1.6 * near_fade), 0.0, 1.0) * (1.0 - 0.32 * scorch); + + float base_rough = cls.r * 0.94 + cls.g * 0.90 + cls.b * 0.80 + cls.a * 0.26; + float cls_sum = max(0.001, cls.r + cls.g + cls.b + cls.a); + rough = mix(clamp(base_rough / cls_sum, 0.26, 0.96), rough, clamp(mat.a, 0.0, 1.0)); + } else { + float grain = (hash21(floor(UV * 768.0)) - 0.5) * 0.045; + alb = clamp(delta_alb * (1.0 + grain * 1.4), 0.0, 1.0) * (1.0 - 0.30 * scorch); + } + + ALBEDO = alb; + ROUGHNESS = rough; + METALLIC = 0.02; +} diff --git a/client/terrain_tile_bake.glsl b/client/terrain_tile_bake.glsl new file mode 100644 index 0000000..96b0c42 --- /dev/null +++ b/client/terrain_tile_bake.glsl @@ -0,0 +1,176 @@ +#version 450 + +layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in; + +struct GpuBrush { + vec4 posRot; // x, z, cosR, sinR + vec4 radDelta; // invRx, invRz, heightDelta, maxRadiusSq + vec4 matColor; // albedoR, albedoG, albedoB, float(kind) +}; + +layout(set = 0, binding = 0, rgba16f) uniform writeonly image2D u_delta_height; +layout(set = 0, binding = 1, rgba8) uniform writeonly image2D u_delta_albedo; + +layout(set = 0, binding = 2, std430) readonly buffer BrushBuffer { + GpuBrush brushes[]; +} u_brushes; + +layout(push_constant, std430) uniform TileBakeParams { + vec4 tileOriginAndSpan; // x=tileMinX, y=tileMinZ, z=tileSize(192), w=innerSpan(384) + vec4 baseColorAndGutter; // rgb=clearAlbedo, w=gutterStart(2.0) + uvec4 counts; // x=brushStart, y=brushCount, z=texSize(388), w=isSion +} u_params; + +void main() { + ivec2 gid = ivec2(gl_GlobalInvocationID.xy); + int texSize = int(u_params.counts.z); + if (gid.x >= texSize || gid.y >= texSize) { + return; + } + + float tileMinX = u_params.tileOriginAndSpan.x; + float tileMinZ = u_params.tileOriginAndSpan.y; + float tileSize = u_params.tileOriginAndSpan.z; + float innerSpan = u_params.tileOriginAndSpan.w; + float gutterStart = u_params.baseColorAndGutter.w; + + float stepM = tileSize / innerSpan; + float wx = tileMinX + (float(gid.x) - gutterStart) * stepM; + float wz = tileMinZ + (float(gid.y) - gutterStart) * stepM; + + bool isSion = u_params.counts.w != 0u; + uint brushStart = u_params.counts.x; + uint brushEnd = brushStart + u_params.counts.y; + + float totalDh = 0.0; + float totalDg = 0.0; + float totalScorch = 0.0; + vec3 albedoAcc = u_params.baseColorAndGutter.rgb; + float deltaBlendAcc = isSion ? 0.0 : 1.0; + + for (uint i = brushStart; i < brushEnd; i++) { + GpuBrush b = u_brushes.brushes[i]; + float dx = wx - b.posRot.x; + float dz = wz - b.posRot.y; + if (dx * dx + dz * dz >= b.radDelta.w) { + continue; + } + + float cosR = b.posRot.z; + float sinR = b.posRot.w; + float lx = dx * cosR + dz * sinR; + float lz = -dx * sinR + dz * cosR; + + float u = lx * b.radDelta.x; + float v = lz * b.radDelta.y; + float r2 = u * u + v * v; + if (r2 >= 1.0) { + continue; + } + + int kind = int(b.matColor.w + 0.5); + float heightDelta = b.radDelta.z; + vec3 bCol = b.matColor.rgb; + float dh = 0.0; + float dg = 0.0; + float dScorch = 0.0; + vec3 col = bCol; + float alpha = 0.0; + + if (kind == 0) { + // DuneRidge + float env = 1.0 - r2; + env *= env; + float ridge = max(0.0, 1.0 - u * u); + float asym = 1.0 + 0.32 * u; + dh = heightDelta * env * (0.35 + 0.65 * ridge) * asym; + if (heightDelta > 0.0) { + dg = 0.02 * env; + } + col = mix(bCol * 0.90, bCol * 1.12, ridge); + alpha = env * 0.72; + } else if (kind == 1) { + // Mesa + float r = sqrt(r2); + float t = clamp((1.0 - r) / 0.45, 0.0, 1.0); + float plateau = t * t * (3.0 - 2.0 * t); + dh = heightDelta * plateau; + float cliffBand = clamp(1.0 - abs(r - 0.74) * 5.0, 0.0, 1.0); + col = mix(bCol, bCol * 0.68, cliffBand); + alpha = clamp(plateau + cliffBand * 0.5, 0.0, 0.94); + } else if (kind == 2) { + // SalvagePad + float env = 1.0 - r2; + env *= env; + dh = heightDelta * env; + if (heightDelta > 0.0) { + dg = 0.03 * env; + } + float border = smoothstep(0.75, 0.92, sqrt(r2)); + col = mix(bCol, vec3(0.32, 0.28, 0.24), border * 0.45); + alpha = clamp(env * 1.15, 0.0, 0.88); + } else if (kind == 3) { + // Road + float env = 1.0 - r2; + env *= env; + dh = heightDelta * env; + float rut = smoothstep(0.15, 0.45, abs(v)) * (1.0 - smoothstep(0.60, 0.92, abs(v))); + col = mix(bCol, bCol * 0.76, rut); + alpha = env * (0.45 + 0.35 * rut); + } else if (kind == 4) { + // Crater + float r = sqrt(r2); + float depth = abs(heightDelta); + float pitT = clamp(1.0 - r / 0.62, 0.0, 1.0); + float pit = -depth * pitT * pitT * (3.0 - 2.0 * pitT); + float rimT = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0)); + float rim = 0.32 * depth * rimT * rimT; + dh = pit + rim; + dg = 0.04 * (1.0 - r); + dScorch = 0.78 * clamp(1.0 - r * 0.9, 0.0, 1.0); + vec3 ejecta = isSion ? vec3(0.34, 0.31, 0.27) : vec3(0.62, 0.38, 0.22); + col = mix(ejecta, bCol, clamp(pitT * 1.3, 0.0, 1.0)); + alpha = clamp(max(pitT * 0.94, rimT * rimT * 0.72), 0.0, 0.95); + } else if (kind == 5) { + // Track + float env = 1.0 - r2; + env *= env; + dh = heightDelta * env; + dScorch = 0.32 * env; + float treads = smoothstep(0.18, 0.45, abs(v)) * (1.0 - smoothstep(0.62, 0.92, abs(v))); + col = bCol; + alpha = env * treads * 0.62; + } else if (kind == 6) { + // Scorch + float r = sqrt(r2); + float mask = clamp(1.0 - r, 0.0, 1.0); + float mask2 = mask * mask; + dg = 0.02 * mask2; + dScorch = 0.85 * mask2; + col = bCol; + alpha = mask2 * 0.88; + } else if (kind == 7) { + // Rubble + float env = 1.0 - r2; + env *= env; + float mound = 0.72 + 0.28 * cos(u * 3.14159265 * 2.5); + dh = heightDelta * env * mound; + dg = 0.08 * env; + dScorch = 0.35 * env; + float chunk = fract(sin(dot(floor(vec2(wx, wz) * 1.5), vec2(12.9898, 78.233))) * 43758.5453); + col = mix(bCol * 0.80, bCol * 1.15, chunk); + alpha = clamp(env * 1.2, 0.0, 0.96); + } + + totalDh += dh; + totalDg += dg; + totalScorch += dScorch; + albedoAcc = mix(albedoAcc, col, alpha); + deltaBlendAcc = max(deltaBlendAcc, alpha); + } + + float roughness = clamp(0.88 + totalDg, 0.35, 1.0); + float scorch = clamp(totalScorch, 0.0, 1.0); + imageStore(u_delta_height, gid, vec4(totalDh, roughness, scorch, clamp(deltaBlendAcc, 0.0, 1.0))); + imageStore(u_delta_albedo, gid, vec4(clamp(albedoAcc, 0.0, 1.0), 1.0)); +} diff --git a/client/tests/HbGpuProbe.cs b/client/tests/HbGpuProbe.cs new file mode 100644 index 0000000..aa8187c --- /dev/null +++ b/client/tests/HbGpuProbe.cs @@ -0,0 +1,233 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Godot; +using RustToDust.HbGpu; + +namespace RustToDust.Client.Tests; + +/// +/// Cut 14a visual & headless verification probe for HbGpuCanvas (1 Vulkan draw call). +/// Run headless: Godot --headless --audio-driver Dummy --path client res://tests/HbGpuProbe.tscn +/// Run Vulkan: Godot --audio-driver Dummy --windowed --path client res://tests/HbGpuProbe.tscn -- --capture-proof=path.png +/// +public partial class HbGpuProbe : Control +{ + private HbGpuCanvas _canvas = null!; + private bool _done; + private int _frameCount; + private string? _capturePath; + + public override void _Ready() + { + foreach (string arg in OS.GetCmdlineUserArgs()) + { + if (arg.StartsWith("--capture-proof=", StringComparison.Ordinal)) + { + _capturePath = arg["--capture-proof=".Length..]; + } + } + _capturePath ??= System.Environment.GetEnvironmentVariable("RTD_HBGPU_PROOF_PNG"); + + var bg = new ColorRect + { + Color = new Color(0.05f, 0.065f, 0.085f, 1.0f), + MouseFilter = MouseFilterEnum.Ignore + }; + AddChild(bg); + bg.SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); + + _canvas = new HbGpuCanvas + { + Name = "HbGpuCanvas", + ProfilingEnabled = true + }; + AddChild(_canvas); + _canvas.SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); + + _ = RunVerificationAsync(); + } + + private async Task RunVerificationAsync() + { + try + { + // Render enough frames to warm Vulkan pipeline & collect RD GPU timestamps + int targetFrames = _canvas.IsVulkanActive ? 24 : 3; + for (int i = 0; i < targetFrames; i++) + { + SubmitShowcaseFrame(i); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + _frameCount++; + } + + if (_canvas.LastQuadCount <= 0) + { + Fail("Expected LastQuadCount > 0 after submitting HbGpu showcase frame."); + return; + } + + if (!_canvas.IsVulkanActive) + { + GD.Print($"HBGPU_PROBE PASS (headless null-RD): quads={_canvas.LastQuadCount}, frames={_frameCount}"); + Finish(0); + return; + } + + if (_canvas.LastDrawCallCount != 1) + { + Fail($"Expected LastDrawCallCount == 1 on Vulkan, got {_canvas.LastDrawCallCount}."); + return; + } + + if (!_canvas.TryReadbackRgba8(out byte[] rgba, out int w, out int h)) + { + Fail("HbGpuCanvas.TryReadbackRgba8 returned false on active Vulkan device."); + return; + } + + int nonZero = 0; + int premulViolations = 0; + for (int i = 0; i + 3 < rgba.Length; i += 4) + { + byte r = rgba[i]; + byte g = rgba[i + 1]; + byte b = rgba[i + 2]; + byte a = rgba[i + 3]; + if (a > 0) + { + nonZero++; + } + if (r > a || g > a || b > a) + { + premulViolations++; + } + } + + if (nonZero < 1500) + { + Fail($"Expected >= 1500 rendered pixels in HbGpu Texture2Drd, got {nonZero} ({w}x{h})."); + return; + } + + if (premulViolations != 0) + { + Fail($"Premultiplied alpha invariant violated on {premulViolations} pixels."); + return; + } + + if (!string.IsNullOrWhiteSpace(_capturePath)) + { + SubmitShowcaseFrame(_frameCount); + await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw); + Image? vpImg = GetViewport().GetTexture()?.GetImage(); + if (vpImg is null) + { + Fail("Viewport capture returned null Image."); + return; + } + string? dir = Path.GetDirectoryName(_capturePath); + if (!string.IsNullOrEmpty(dir)) + { + Directory.CreateDirectory(dir); + } + Error saveErr = vpImg.SavePng(_capturePath); + if (saveErr != Error.Ok) + { + Fail($"Failed to save proof PNG '{_capturePath}': {saveErr}"); + return; + } + } + + GD.Print( + $"HBGPU_PROBE PASS (Vulkan): size={w}x{h}, quads={_canvas.LastQuadCount}, " + + $"draw_calls={_canvas.LastDrawCallCount}, gpu_ms={_canvas.LastHbGpuMs:F4}, " + + $"non_zero_px={nonZero}, premul_violations={premulViolations}"); + Finish(0); + } + catch (Exception ex) + { + Fail(ex.ToString()); + } + } + + private void SubmitShowcaseFrame(int frameIndex) + { + Color amber = new(0.95f, 0.72f, 0.22f, 1.0f); + Color cyan = new(0.32f, 0.86f, 0.96f, 1.0f); + Color slate = new(0.78f, 0.84f, 0.90f, 1.0f); + Color panelBg = new(0.06f, 0.09f, 0.12f, 0.78f); + Color alert = new(0.96f, 0.28f, 0.22f, 1.0f); + Color emerald = new(0.28f, 0.90f, 0.56f, 1.0f); + + _canvas.BeginFrame(); + + // Top-left panel backdrop + crisp Krypton typography across weights/slants/sizes + _canvas.DrawRectFilled(40f, 36f, 680f, 224f, panelBg); + _canvas.DrawLineSegment(40f, 36f, 720f, 36f, 2f, amber); + _canvas.DrawLineSegment(40f, 260f, 720f, 260f, 1.5f, new Color(amber, 0.5f)); + + _canvas.DrawText("RUST TO DUST // HB-GPU VULKAN", 60f, 84f, 32f, amber, wght: 700f); + _canvas.DrawText("CHASSIS: RAPTOR-7 | ALT: 142.8m | SPD: 28.4m/s", 60f, 124f, 20f, slate, wght: 550f); + _canvas.DrawText("CALT / LIGA: -> ==> != <= >= // 0x4F2A", 60f, 158f, 18f, cyan, wght: 350f); + _canvas.DrawText("SLANT -9 DEG // STEM DARKENED ANALYTIC SLUG", 60f, 192f, 15f, emerald, wght: 400f, slnt: -9f); + _canvas.DrawText("11PX MICRO TELEMETRY: 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ", 60f, 226f, 11f, slate, wght: 250f); + + // Center crosshair reticle + dynamic cubic Bezier thermal heat arc + float cx = 640f; + float cy = 400f; + _canvas.DrawCircleFilled(cx, cy, 3.5f, amber); + _canvas.DrawLineSegment(cx - 28f, cy, cx - 10f, cy, 2.0f, cyan); + _canvas.DrawLineSegment(cx + 10f, cy, cx + 28f, cy, 2.0f, cyan); + _canvas.DrawLineSegment(cx, cy - 28f, cx, cy - 10f, 2.0f, cyan); + _canvas.DrawLineSegment(cx, cy + 10f, cx, cy + 28f, 2.0f, cyan); + + float heatSweep = -2.356f + (0.65f + 0.1f * MathF.Sin(frameIndex * 0.1f)) * 4.712f; + _canvas.DrawArcStrokeDynamic(cx, cy, 62f, 5.5f, -2.356f, heatSweep, amber); + _canvas.DrawArcStrokeDynamic(cx, cy, 82f, 4.0f, -0.34f, 0.34f, alert); + + // Target lock corner brackets (all 4 quadrants) + float bx0 = 860f, by0 = 280f, bx1 = 1040f, by1 = 460f; + _canvas.DrawTargetBracketCorner(bx0, by0, 26f, 3.5f, 0, alert); + _canvas.DrawTargetBracketCorner(bx1, by0, 26f, 3.5f, 1, alert); + _canvas.DrawTargetBracketCorner(bx1, by1, 26f, 3.5f, 2, alert); + _canvas.DrawTargetBracketCorner(bx0, by1, 26f, 3.5f, 3, alert); + _canvas.DrawText("LOCK: SPECTATOR-02 [318m]", bx0, by0 - 12f, 14f, alert, wght: 600f); + + // Offscreen directional arrows + _canvas.DrawDirectionalArrow(1160f, 560f, 28f, 0.55f, amber); + _canvas.DrawDirectionalArrow(120f, 560f, 28f, -2.45f, alert); + + // Radar circle, safe ring, LOS lock line, diamond blip & chevron + float rx = 1080f, ry = 160f, rr = 96f; + _canvas.DrawCircleFilled(rx, ry, rr, new Color(0.04f, 0.07f, 0.09f, 0.85f)); + _canvas.DrawCircleRing(rx, ry, rr, 2.5f, cyan); + _canvas.DrawCircleRing(rx, ry, rr * 0.58f, 1.5f, new Color(emerald, 0.75f)); + _canvas.DrawLineSegment(rx, ry, rx + 44f, ry - 52f, 1.5f, new Color(alert, 0.85f)); + _canvas.Writer.DrawBlob( + HbGpuVectorShapes.GetDiamondBlip(_canvas.Blobs), + rx + 44f, ry - 52f, + 0.012f, 0f, 0f, -0.012f, 0f, 0f, + alert.R, alert.G, alert.B, alert.A); + _canvas.Writer.DrawBlob( + HbGpuVectorShapes.GetChevronTriangle(_canvas.Blobs), + rx, ry, + 0.014f, 0f, 0f, -0.014f, 0f, 0f, + emerald.R, emerald.G, emerald.B, emerald.A); + + _canvas.EndFrameAndSubmit(); + } + + private void Fail(string msg) + { + GD.PrintErr("HBGPU_PROBE FAIL: " + msg); + Finish(1); + } + + private void Finish(int code) + { + if (_done) return; + _done = true; + GetTree().Quit(code); + } +} diff --git a/client/tests/HbGpuProbe.tscn b/client/tests/HbGpuProbe.tscn new file mode 100644 index 0000000..ee00a32 --- /dev/null +++ b/client/tests/HbGpuProbe.tscn @@ -0,0 +1,12 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://tests/HbGpuProbe.cs" id="1"] + +[node name="HbGpuProbe" type="Control"] +layout_mode = 3 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +script = ExtResource("1") diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs new file mode 100644 index 0000000..bde0dc5 --- /dev/null +++ b/client/tests/Smoke.cs @@ -0,0 +1,2632 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Godot; +using RustToDust.Core; +using RustToDust.Net; +using RustToDust.Ymir; + +namespace RustToDust.Client.Tests; + +/// +/// Headless & Vulkan Forward+ Godot smoke test: instantiates Main, drives 60 frames with throttle + fire + crater stamp, +/// verifies terrain tile baking and Ymir physics integration, and exits with code 0 on pass. +/// godot --headless --path client res://tests/Smoke.tscn +/// +public partial class Smoke : Node +{ + private const double WatchdogSeconds = 90.0; + + private readonly List _failures = new(); + private Main _main = null!; + private bool _done; + + public override void _Ready() => _ = RunAsync(); + + public override void _Process(double delta) + { + if (!_done && Time.GetTicksMsec() > WatchdogSeconds * 1000.0) + { + Check(false, $"Smoke watchdog timed out after {WatchdogSeconds}s"); + Finish(); + } + } + + private async Task RunAsync() + { + try + { + _main = GD.Load("res://Main.tscn").Instantiate
(); + _main.InitialMapKindOverride = ArenaMapKind.Desert; + _main.InitialSkipDropOverride = true; + AddChild(_main); + + if (_main.Failure is { } failure) + { + Check(false, "Main failed to initialize IClientArenaSession: " + failure); + } + else + { + await RunScenarioAsync(); + } + } + catch (Exception ex) + { + Check(false, ex.ToString()); + } + + Finish(); + } + + private async Task RunScenarioAsync() + { + Check(Engine.PhysicsTicksPerSecond == 60, $"Expected 60 physics ticks/sec, got {Engine.PhysicsTicksPerSecond}"); + Check((string)ProjectSettings.GetSetting("physics/3d/physics_engine") == "Dummy", "Godot 3D physics_engine is not Dummy"); + Check(!_main.GetWorld3D().Space.IsValid, "Godot should have no active 3D physics space"); + Check(_main.Terrain.BakedTileCount == 64, $"Expected 64 baked terrain tiles, got {_main.Terrain.BakedTileCount}"); + + var player = _main.Session.ViewState.Contenders[0]; + float startX = player.X; + float startZ = player.Z; + + _main.SetScriptedInput(new PlayerInput( + Throttle: 1f, + Steer: 0.25f, + AimWorldX: startX + 35f, + AimWorldZ: startZ + 10f, + Fire: true, + InteractPickup: false, + Brake: false)); + + for (int i = 0; i < 60; i++) + { + await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame); + if (_main.Failure is { } f) + { + Check(false, "Session failure during physics loop: " + f); + return; + } + } + + float dx = player.X - startX; + float dz = player.Z - startZ; + float displacement = MathF.Sqrt(dx * dx + dz * dz); + Check(displacement > 3f, $"Expected player displacement > 3m after 60 frames, got {displacement:F2}m"); + Check(!float.IsNaN(player.X) && !float.IsNaN(player.Y) && !float.IsNaN(player.Z), "Player position became NaN"); + + // Pause physics during the isolated crater check so AI contender track stamps in other tiles do not race it. + _main.SetScriptedInput(null); + _main.SetPhysicsProcess(false); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + bool isHeadless = DisplayServer.GetName() == "headless"; + int rebakesBefore = _main.Terrain.DirtyRebakes; + float cpuBefore = _main.Session.ViewState.Terrain.SampleHeight(-96f, -96f); + float gpuBefore = 0f; + if (!isHeadless) + { + if (_main.Terrain.TryGetHeightImageFormat(out var imgFormat)) + { + GD.Print($"SMOKE INFO: HeightViewport format={imgFormat}"); + } + + bool hasGpuBefore = _main.Terrain.TrySampleBakedHeight(-96f, -96f, out gpuBefore); + Check(hasGpuBefore, "Expected GPU HeightViewport readback to succeed before crater"); + if (hasGpuBefore) + { + float beforeErr = MathF.Abs(gpuBefore - cpuBefore); + GD.Print($"SMOKE INFO: Crater-site pre-stamp cpu={cpuBefore:F4}m gpu={gpuBefore:F4}m err={beforeErr:F4}m"); + Check(beforeErr <= 0.20f, + $"Expected baked GPU height ({gpuBefore:F4}m) to match CPU height ({cpuBefore:F4}m) before crater within 0.20m"); + } + + // Verify brushed terrain relief (tallest Mesa/DuneRidge center) so a flat-map bug can never pass + TerrainBrush? reliefBrush = null; + float bestHillCpu = 0f; + foreach (var b in _main.Session.ViewState.Terrain.Brushes) + { + if (b.Kind == TerrainBrushKind.Mesa || (b.Kind == TerrainBrushKind.DuneRidge && b.HeightDelta > 0f)) + { + float h = _main.Session.ViewState.Terrain.SampleHeight(b.X, b.Z); + if (h > bestHillCpu) + { + bestHillCpu = h; + reliefBrush = b; + } + } + } + + Check(reliefBrush.HasValue && bestHillCpu > 10f, "Expected brushed terrain relief > 10m in generated arena"); + if (reliefBrush.HasValue) + { + var rb = reliefBrush.Value; + bool hasGpuHill = _main.Terrain.TrySampleBakedHeight(rb.X, rb.Z, out float gpuHill); + Check(hasGpuHill, "Expected GPU HeightViewport readback to succeed on brushed relief hill/mesa"); + if (hasGpuHill) + { + float hillErr = MathF.Abs(gpuHill - bestHillCpu); + GD.Print($"SMOKE INFO: Relief {rb.Kind} at ({rb.X:F1},{rb.Z:F1}) cpu={bestHillCpu:F4}m gpu={gpuHill:F4}m err={hillErr:F4}m"); + Check(gpuHill > 10f, $"Expected GPU baked hill height > 10m, got {gpuHill:F4}m"); + Check(hillErr <= 0.20f, + $"Expected GPU hill height ({gpuHill:F4}m) to match CPU ({bestHillCpu:F4}m) within 0.20m"); + } + } + + // Verify tile seam continuity across interior tile boundaries (< 0.01m) + float maxSeamErr = 0f; + float[] boundaries = { -192f, 0f, 192f }; + float[] offsets = { -280f, -96f, 96f, 280f }; + foreach (float bCoord in boundaries) + { + foreach (float ortho in offsets) + { + if (_main.Terrain.TrySampleBakedHeight(bCoord - 0.0001f, ortho, out float hL) && + _main.Terrain.TrySampleBakedHeight(bCoord + 0.0001f, ortho, out float hR)) + { + maxSeamErr = MathF.Max(maxSeamErr, MathF.Abs(hL - hR)); + } + if (_main.Terrain.TrySampleBakedHeight(ortho, bCoord - 0.0001f, out float hD) && + _main.Terrain.TrySampleBakedHeight(ortho, bCoord + 0.0001f, out float hU)) + { + maxSeamErr = MathF.Max(maxSeamErr, MathF.Abs(hD - hU)); + } + } + } + GD.Print($"SMOKE INFO: Max tile seam error={maxSeamErr:F5}m"); + Check(maxSeamErr < 0.01f, $"Expected tile seam error < 0.01m, got {maxSeamErr:F5}m"); + } + + _main.Session.ViewState.Terrain.StampCrater(-96f, -96f, radius: 5f, depth: 1.4f); + _main.Terrain.Sync(_main.Session.ViewState.Terrain); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + float cpuAfter = _main.Session.ViewState.Terrain.SampleHeight(-96f, -96f); + Check(cpuAfter < cpuBefore - 0.8f, + $"Expected CPU terrain height to drop after crater stamp (before {cpuBefore:F2}m, after {cpuAfter:F2}m)"); + Check(_main.Terrain.DirtyRebakes == rebakesBefore + 1, + $"Expected 1 dirty tile rebake from isolated crater stamp, got {_main.Terrain.DirtyRebakes - rebakesBefore}"); + + if (!isHeadless) + { + bool hasGpuAfter = _main.Terrain.TrySampleBakedHeight(-96f, -96f, out float gpuAfter); + Check(hasGpuAfter, "Expected GPU HeightViewport readback to succeed after crater"); + if (hasGpuAfter) + { + float afterErr = MathF.Abs(gpuAfter - cpuAfter); + GD.Print($"SMOKE INFO: Crater-site post-stamp cpu={cpuAfter:F4}m gpu={gpuAfter:F4}m err={afterErr:F4}m"); + Check(afterErr <= 0.20f, + $"Expected baked GPU height ({gpuAfter:F4}m) to match CPU height ({cpuAfter:F4}m) after crater within 0.20m"); + Check(gpuAfter < gpuBefore - 0.8f, + $"Expected baked GPU height to drop after crater (before {gpuBefore:F4}m, after {gpuAfter:F4}m)"); + } + } + + // Regression check: 4-tile boundary crater at (0, 0) bakes all 4 tiles on Sync#1 (<= 0.20m error on all 4 quadrants) + // and passive Track throttling (MaxDirtyRebakesPerSync=4) preserves pending visual versions until all tiles are baked without skipping via _rebakeCursor. + { + // Flush any lingering track rebakes first so baseline is clean + for (int flush = 0; flush < 32 && _main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) > 0; flush++) + { + _main.Terrain.Sync(_main.Session.ViewState.Terrain); + } + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + (float Qx, float Qz)[] quadrants = { (-1f, -1f), (1f, -1f), (-1f, 1f), (1f, 1f) }; + float[] qGpuBefore = new float[4]; + if (!isHeadless) + { + for (int q = 0; q < 4; q++) + { + Check(_main.Terrain.TrySampleBakedHeight(quadrants[q].Qx, quadrants[q].Qz, out qGpuBefore[q]), + $"Expected GPU readback before 4-tile boundary crater at quadrant {q}"); + } + } + + int rebakes4Before = _main.Terrain.DirtyRebakes; + _main.Session.ViewState.Terrain.StampCrater(0f, 0f, radius: 6f, depth: 1.4f); + _main.Terrain.Sync(_main.Session.ViewState.Terrain); // Sync#1 + Check(_main.Terrain.DirtyRebakes == rebakes4Before + 4, + $"Expected 4-tile boundary crater at (0,0) to bake all 4 tiles on Sync#1, got {_main.Terrain.DirtyRebakes - rebakes4Before}"); + Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 0, + "Expected 0 pending dirty tiles after Sync#1 on 4-tile boundary crater"); + + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + if (!isHeadless) + { + for (int q = 0; q < 4; q++) + { + float qCpu = _main.Session.ViewState.Terrain.SampleHeight(quadrants[q].Qx, quadrants[q].Qz); + bool ok = _main.Terrain.TrySampleBakedHeight(quadrants[q].Qx, quadrants[q].Qz, out float qGpu); + Check(ok, $"Expected GPU readback on quadrant {q} after 4-tile boundary crater"); + if (ok) + { + float qErr = MathF.Abs(qGpu - qCpu); + GD.Print($"SMOKE INFO: 4-tile crater Q{q} ({quadrants[q].Qx},{quadrants[q].Qz}) cpu={qCpu:F4}m gpu={qGpu:F4}m err={qErr:F4}m"); + Check(qErr <= 0.20f, $"4-tile crater quadrant {q} GPU error {qErr:F4}m > 0.20m"); + Check(qGpu < qGpuBefore[q] - 0.35f, $"4-tile crater quadrant {q} did not depress on Sync#1 (before={qGpuBefore[q]:F4}, after={qGpu:F4})"); + } + } + } + + // Stamp 5 passive tracks in distinct tiles so _rebakeCursor advances across Sync#1 (4) and Sync#2 (1) without skipping + int rebakesTrackBefore = _main.Terrain.DirtyRebakes; + _main.Session.ViewState.Terrain.StampTrack(-480f, -480f, 0f, 2f, 3f); + _main.Session.ViewState.Terrain.StampTrack(-288f, -480f, 0f, 2f, 3f); + _main.Session.ViewState.Terrain.StampTrack(-96f, -480f, 0f, 2f, 3f); + _main.Session.ViewState.Terrain.StampTrack(96f, -480f, 0f, 2f, 3f); + _main.Session.ViewState.Terrain.StampTrack(288f, -480f, 0f, 2f, 3f); + _main.Terrain.Sync(_main.Session.ViewState.Terrain); + Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 4, + $"Expected Sync#1 to throttle 5 passive tracks to 4 rebakes, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); + Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 1, + "Expected 1 pending dirty track tile remaining after Sync#1"); + _main.Terrain.Sync(_main.Session.ViewState.Terrain); + Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 5, + $"Expected Sync#2 to bake remaining 5th passive track tile without _rebakeCursor skip, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); + Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 0, + "Expected 0 pending dirty tiles after all passive track tiles baked"); + } + + _main.SetPhysicsProcess(true); + + await VerifyHudAndShadersAsync(isHeadless); + await VerifyCut3bVehiclesAndMechanismsAsync(); + await MaybeCapturePreviewAsync(isHeadless); + await VerifyMaxLoadPaladinGarageAsync(); + await VerifySionMapAsync(); + await VerifyOrbitalDropSequenceAsync(); + await VerifyCut7bModularOrdnanceAsync(); + VerifyForwardPlusAtmosphere(); + await VerifyGpuSparksRenderAsync(isHeadless); + } + + private async Task VerifyHudAndShadersAsync(bool isHeadless) + { + var invShader = _main.Hud.Schematic.ShaderMaterial.Shader; + Check(invShader is not null && !string.IsNullOrWhiteSpace(invShader.Code), + "inventory_grid.gdshader failed to load"); + Check(_main.Hud.HbCanvas is not null, "Expected Hud.HbCanvas to be initialized"); + + // Warm up HUD HbGpuCanvas and verify steady-state Sync allocates zero managed bytes + _main.Hud.Sync(_main.Session); + _main.Hud.Sync(_main.Session); + _main.Hud.Sync(_main.Session); + Check(_main.Hud.HbCanvas!.LastQuadCount > 50, + $"Expected Hud.HbCanvas.LastQuadCount > 50 after Sync, got {_main.Hud.HbCanvas.LastQuadCount}"); + long gcBefore = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < 16; i++) + { + _main.Hud.Sync(_main.Session); + } + long gcAfter = GC.GetAllocatedBytesForCurrentThread(); + long gcDelta = gcAfter - gcBefore; + GD.Print($"SMOKE INFO: Steady-state Hud.Sync x16 managed allocs={gcDelta} B"); + Check(gcDelta == 0, $"Expected 0 B managed allocations across steady-state Hud.Sync x16, got {gcDelta} B"); + + // Pack a real Ironclad chassis with mounted modules, thermal gradient, stripped cell, and active hit-pulse + var testGrid = new ChassisGrid(Catalog.Ironclad); + Check(testGrid.TryMount(Catalog.Recoilless, "hp.weapon.main"), "Expected Recoilless to mount on hp.weapon.main"); + Check(testGrid.TryMount(Catalog.Mg762, "hp.weapon.coax"), "Expected Mg762 to mount on hp.weapon.coax"); + Check(testGrid.TryMount(Catalog.TurboCore, "hp.engine.rear"), "Expected TurboCore to mount on hp.engine.rear"); + Check(testGrid.TryMount(Catalog.CopperRad, "hp.radiator.l"), "Expected CopperRad to mount on hp.radiator.l"); + Check(testGrid.TryMount(Catalog.WeldedPlate, "hp.armor.front"), "Expected WeldedPlate to mount on hp.armor.front"); + testGrid.InjectHardpointHeat("hp.engine.rear", 1800f); + testGrid.InjectHardpointHeat("hp.weapon.main", 900f); + testGrid.StepHeat(0.25f); + testGrid.Armor[0, 0] = 0f; // stripped armor cell + + var schematic = _main.Hud.Schematic; + schematic.SetGrid(testGrid); + schematic.TriggerHitPulse(1, 1, 1f); + + // Hit-testing verification: center of cell (1, 1) must map to (1, 1) and hardpoint "hp.weapon.main" + schematic.ComputeCellLayout(out float cellSize, out Vector2 origin); + Check(cellSize > 10f, $"Expected InventoryGridControl cellSize > 10px, got {cellSize:F2}"); + Vector2 probePos = origin + new Vector2(1.5f * cellSize, 1.5f * cellSize); + bool hitCell = schematic.TryGetCellAt(probePos, out var mappedCell); + Check(hitCell && mappedCell == new Vector2I(1, 1), + $"Expected TryGetCellAt to map center of (1,1) to (1,1), got hit={hitCell} cell={mappedCell}"); + var mappedHp = schematic.GetHardpointAt(1, 1); + Check(mappedHp is { Id: "hp.weapon.main" }, + $"Expected GetHardpointAt(1,1) to return hp.weapon.main, got {mappedHp?.Id ?? "null"}"); + + // Regression check (Finding 3): same-dimension SwapChassis updates _hardpointLookup and clears hover state + schematic._GuiInput(new InputEventMouseMotion { Position = probePos }); + Check(schematic.HoveredCell == new Vector2I(1, 1) && schematic.HoveredHardpoint is { Id: "hp.weapon.main" }, + $"Expected hover on (1,1)/hp.weapon.main before SwapChassis, got cell={schematic.HoveredCell} hp={schematic.HoveredHardpoint?.Id ?? "null"}"); + + bool hoverResetEmitted = false; + void OnSwapHoverChanged(Vector2I? cell, HardpointSpec? hp) + { + if (cell is null && hp is null) + { + hoverResetEmitted = true; + } + } + schematic.HoverChanged += OnSwapHoverChanged; + var altTankSpec = Catalog.Ironclad with + { + Id = "ironclad_alt", + Hardpoints = new[] + { + new HardpointSpec("wpn_swapped", HardpointKind.Weapon, 1, 1, 2, 2, 18f) + } + }; + testGrid.SwapChassis(altTankSpec); + schematic.SetGrid(testGrid); + schematic.HoverChanged -= OnSwapHoverChanged; + + Check(schematic.GetHardpointAt(1, 1) is { Id: "wpn_swapped" }, + $"Expected GetHardpointAt(1,1) to update to wpn_swapped after same-dimension SwapChassis, got {schematic.GetHardpointAt(1, 1)?.Id ?? "null"}"); + Check(schematic.GetHardpointAt(0, 1) is null, + $"Expected old hardpoint hp.weapon.coax at (0,1) to clear after SwapChassis, got {schematic.GetHardpointAt(0, 1)?.Id ?? "null"}"); + Check(schematic.HoveredCell is null && schematic.HoveredHardpoint is null && hoverResetEmitted, + $"Expected SwapChassis to clear hover and emit HoverChanged(null, null), cell={schematic.HoveredCell} emitted={hoverResetEmitted}"); + + // Re-seed Ironclad grid for GPU tests below + testGrid = new ChassisGrid(Catalog.Ironclad); + Check(testGrid.TryMount(Catalog.Recoilless, "hp.weapon.main"), "Expected Recoilless to remount on hp.weapon.main"); + Check(testGrid.TryMount(Catalog.Mg762, "hp.weapon.coax"), "Expected Mg762 to remount on hp.weapon.coax"); + Check(testGrid.TryMount(Catalog.TurboCore, "hp.engine.rear"), "Expected TurboCore to remount on hp.engine.rear"); + Check(testGrid.TryMount(Catalog.CopperRad, "hp.radiator.l"), "Expected CopperRad to remount on hp.radiator.l"); + Check(testGrid.TryMount(Catalog.WeldedPlate, "hp.armor.front"), "Expected WeldedPlate to remount on hp.armor.front"); + testGrid.InjectHardpointHeat("hp.engine.rear", 1800f); + testGrid.InjectHardpointHeat("hp.weapon.main", 900f); + testGrid.StepHeat(0.25f); + testGrid.Armor[0, 0] = 0f; + + // Restore live player grid to HUD and verify layout has no overlaps or clipping + _main.Hud.Sync(_main.Session); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + Vector2 vpSize = GetViewport().GetVisibleRect().Size; + Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Compact HUD panels overlapped or clipped at {vpSize}"); + _main.Hud.ToggleGarage(); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Garage HUD panels overlapped or clipped at {vpSize}"); + _main.Hud.ToggleGarage(); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + _main.Hud.ToggleNetworkPanel(); + _main.Hud.Sync(_main.Session); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"F9 Network HUD panel overlapped or clipped at {vpSize}"); + _main.Hud.ToggleNetworkPanel(); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + if (isHeadless) + { + return; + } + + // GPU verification on Forward+ Vulkan: render isolated InventoryGridControl (ambient vs live bilinear heat) & panel_chrome.gdshader + var gridVp = new SubViewport + { + Size = new Vector2I(240, 240), + TransparentBg = true, + RenderTargetUpdateMode = SubViewport.UpdateMode.Always + }; + var vpGrid = new InventoryGridControl + { + Size = new Vector2(240f, 240f), + CustomMinimumSize = new Vector2(240f, 240f) + }; + gridVp.AddChild(vpGrid); + AddChild(gridVp); + + var coolGrid = new ChassisGrid(Catalog.Ironclad); + coolGrid.TryMount(Catalog.Recoilless, "hp.weapon.main"); + coolGrid.TryMount(Catalog.Mg762, "hp.weapon.coax"); + coolGrid.TryMount(Catalog.TurboCore, "hp.engine.rear"); + coolGrid.TryMount(Catalog.CopperRad, "hp.radiator.l"); + coolGrid.TryMount(Catalog.WeldedPlate, "hp.armor.front"); + coolGrid.Armor[0, 0] = 0f; + + vpGrid.SetGrid(coolGrid); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var coolImg = gridVp.GetTexture().GetImage(); + int coolOpaque = CountNonZeroAlphaPixels(coolImg, 0.08f); + GD.Print($"SMOKE INFO: InventoryGrid GPU cool opaque pixels={coolOpaque}"); + Check(coolOpaque > 4000, $"Expected > 4000 rendered pixels from InventoryGrid shader, got {coolOpaque}"); + + vpGrid.SetGrid(testGrid); + vpGrid.TriggerHitPulse(1, 1, 1f); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var hotImg = gridVp.GetTexture().GetImage(); + int hotOpaque = CountNonZeroAlphaPixels(hotImg, 0.08f); + int heatDiff = CountDifferentPixels(coolImg, hotImg, 0.05f); + GD.Print($"SMOKE INFO: InventoryGrid GPU hot opaque={hotOpaque}, diff vs cool={heatDiff}"); + Check(hotOpaque > 4000, $"Expected > 4000 rendered pixels from heated InventoryGrid shader, got {hotOpaque}"); + Check(heatDiff > 400, $"Expected always-active temp_tex + hit pulse to visibly change > 400 pixels, got {heatDiff}"); + + // Finding 2 GPU check: overheated (350C..550C+) must obey blend_premul_alpha (out_rgb <= out_a) + testGrid.InjectHardpointHeat("hp.engine.rear", 45000f); + testGrid.InjectHardpointHeat("hp.weapon.main", 25000f); + testGrid.StepHeat(0.05f); + float hotTemp = testGrid.Temperature[1, 3]; + Check(hotTemp >= 350f, $"Expected overheated cell >= 350C for premul test, got {hotTemp:F1}C"); + vpGrid.SetGrid(testGrid); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var overheatImg = gridVp.GetTexture().GetImage(); + int premulViolations = CountPremulViolations(overheatImg, 0.01f); + GD.Print($"SMOKE INFO: InventoryGrid GPU overheat ({hotTemp:F1}C) premul violations={premulViolations}"); + Check(premulViolations == 0, $"Expected 0 blend_premul_alpha violations (max(RGB) > A + 0.01) on overheated grid, got {premulViolations}"); + + // Finding 1 GPU check: asymmetric heated Raptor chassis must leave 0 lit pixels in inactive cell holes + var raptorGrid = new ChassisGrid(Catalog.Raptor); + Check(raptorGrid.TryMount(Catalog.CopperRad, "hp.radiator.sh_l"), "Expected CopperRad on Raptor hp.radiator.sh_l"); + Check(raptorGrid.TryMount(Catalog.CopperRad, "hp.radiator.sh_r"), "Expected CopperRad on Raptor hp.radiator.sh_r"); + Check(raptorGrid.TryMount(Catalog.Autocannon, "hp.weapon.arm_l"), "Expected Autocannon on Raptor hp.weapon.arm_l"); + Check(raptorGrid.TryMount(Catalog.TurboCore, "hp.engine.chest"), "Expected TurboCore on Raptor hp.engine.chest"); + Check(raptorGrid.TryMount(Catalog.Autocannon, "hp.weapon.arm_r"), "Expected Autocannon on Raptor hp.weapon.arm_r"); + raptorGrid.InjectHardpointHeat("hp.engine.chest", 1800f); + raptorGrid.StepHeat(0.25f); + + vpGrid.SetGrid(raptorGrid); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var raptorImg = gridVp.GetTexture().GetImage(); + int raptorHoleScanned = 0; + int raptorHoleLit = 0; + int rw = raptorImg.GetWidth(); + int rh = raptorImg.GetHeight(); + for (int py = 0; py < rh; py++) + { + for (int px = 0; px < rw; px++) + { + if (vpGrid.TryGetCellAt(new Vector2(px + 0.5f, py + 0.5f), out var cell) && !Catalog.Raptor.IsActive(cell.X, cell.Y)) + { + raptorHoleScanned++; + Color c = raptorImg.GetPixel(px, py); + if (MathF.Max(MathF.Max(c.R, c.G), MathF.Max(c.B, c.A)) > 0.001f) + { + raptorHoleLit++; + } + } + } + } + GD.Print($"SMOKE INFO: Asymmetric Raptor hole lit pixels={raptorHoleLit} (scanned {raptorHoleScanned} hole px)"); + Check(raptorHoleScanned > 1000, $"Expected > 1000 inactive hole pixels scanned on Raptor, got {raptorHoleScanned}"); + Check(raptorHoleLit == 0, $"Expected 0 lit/opaque pixels in inactive Raptor cell holes, got {raptorHoleLit}"); + + // Cut 14b GPU check: HbGpuCanvas overlay re-emits on temp-only change & compatibility highlights update when Cargo[0] swaps at unchanged index 0 + { + raptorGrid.Cargo.Clear(); + Check(raptorGrid.TryAddCargo(Catalog.Autocannon), "Expected Autocannon in Raptor Cargo[0]"); + vpGrid.SetGrid(raptorGrid, selectedCargoIndex: 0); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + int emitCountBeforeTemp = vpGrid.OverlayEmitCount; + string? tagBeforeTemp = vpGrid.GetLastEmittedLabel("hp.engine.chest"); + var cargoImgWeapon = gridVp.GetTexture().GetImage(); + + // Temp-only change (no armor hit, no mount change) + raptorGrid.InjectHardpointHeat("hp.engine.chest", 4200f); + raptorGrid.StepHeat(0.1f); + vpGrid.SetGrid(raptorGrid, selectedCargoIndex: 0); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + int emitCountAfterTemp = vpGrid.OverlayEmitCount; + string? tagAfterTemp = vpGrid.GetLastEmittedLabel("hp.engine.chest"); + Check(emitCountAfterTemp > emitCountBeforeTemp, + $"Expected InventoryGridControl HbGpu overlay to re-emit on temp-only change ({emitCountBeforeTemp} -> {emitCountAfterTemp})"); + Check(!string.Equals(tagBeforeTemp, tagAfterTemp, StringComparison.Ordinal), + $"Expected engine temp label text to update on temp-only change ('{tagBeforeTemp}' -> '{tagAfterTemp}')"); + + // Cargo[0] replacement at unchanged selectedCargoIndex == 0 (Weapon -> Radiator) + raptorGrid.Cargo[0] = Catalog.CopperRad; + vpGrid.SetGrid(raptorGrid, selectedCargoIndex: 0); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var cargoImgRad = gridVp.GetTexture().GetImage(); + int cargoDiff = CountDifferentPixels(cargoImgWeapon, cargoImgRad, 0.05f); + GD.Print($"SMOKE INFO: InventoryGrid Cargo[0] swap diff pixels={cargoDiff}, label '{tagBeforeTemp}'->'{tagAfterTemp}'"); + Check(cargoDiff > 50, + $"Expected Cargo[0] replacement at unchanged index 0 to update compatibility highlight pixels (>50), got {cargoDiff}"); + Check(vpGrid.StandaloneCanvas is { LastDrawCallCount: 1 }, + $"Expected standalone InventoryGridControl HbGpuCanvas to render in 1 draw call, got {vpGrid.StandaloneCanvas?.LastDrawCallCount ?? -1}"); + } + + gridVp.QueueFree(); + + // Cut 14b Vulkan single-draw-call verification on live Hud.HbCanvas + _main.Hud.Sync(_main.Session); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + var hudHb = _main.Hud.HbCanvas; + Check(hudHb.LastDrawCallCount == 1, $"Expected Hud.HbCanvas LastDrawCallCount == 1, got {hudHb.LastDrawCallCount}"); + Check(hudHb.TryReadbackRgba8(out byte[] hudRgba, out int hudW, out int hudH), + "Expected Hud.HbCanvas.TryReadbackRgba8 to succeed on Vulkan"); + int hudNonZero = 0; + int hudPremulViol = 0; + for (int i = 0; i + 3 < hudRgba.Length; i += 4) + { + byte r = hudRgba[i], g = hudRgba[i + 1], b = hudRgba[i + 2], a = hudRgba[i + 3]; + if (a > 0) hudNonZero++; + if (r > a || g > a || b > a) hudPremulViol++; + } + GD.Print($"SMOKE INFO: Hud.HbCanvas Vulkan {hudW}x{hudH} quads={hudHb.LastQuadCount}, drawCalls={hudHb.LastDrawCallCount}, nonZeroPx={hudNonZero}, premulViol={hudPremulViol}"); + Check(hudNonZero > 4000, $"Expected > 4000 rendered pixels in Hud.HbCanvas, got {hudNonZero}"); + Check(hudPremulViol == 0, $"Expected 0 premul violations in Hud.HbCanvas, got {hudPremulViol}"); + } + + private async Task MaybeCapturePreviewAsync(bool isHeadless) + { + if (isHeadless) return; + + string? previewPath = null; + foreach (string arg in OS.GetCmdlineUserArgs()) + { + const string prefix = "--capture-preview="; + if (arg.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + previewPath = arg[prefix.Length..]; + break; + } + } + + if (string.IsNullOrWhiteSpace(previewPath)) + { + return; + } + + if (!_main.Hud.GarageExpanded) + { + _main.Hud.ToggleGarage(); + } + + // Seed realistic combat telemetry so the preview clearly showcases armor stripping, hit-flash, cargo rack, and thermal heat + var player = _main.Session.ViewState.Contenders[0]; + var grid = player.Grid; + grid.TryAddCargo(Catalog.TouringPlasma); + grid.TryAddCargo(Catalog.GoldRadiator); + grid.InjectHardpointHeat("hp.engine.rear", 1100f); + grid.InjectHardpointHeat("hp.weapon.roof", 750f); + grid.StepHeat(0.15f); + grid.Armor[0, 0] = 0f; + + // Place two nearby rival contenders cleanly in the desert ahead of the player so the preview shows multiple Brokkr GLBs grounded on terrain + float fwdX = MathF.Sin(_main.CameraYaw); + float fwdZ = MathF.Cos(_main.CameraYaw); + float rightX = -fwdZ; + float rightZ = fwdX; + if (_main.Session is LocalArenaSession localPreview && localPreview.Inner.State.Contenders.Count > 2) + { + var r1 = localPreview.Inner.State.Contenders[1]; + if (r1.Alive) + { + localPreview.Inner.SetContenderPose(r1.Id, player.X + fwdX * 19f - rightX * 5.5f, player.Z + fwdZ * 19f - rightZ * 5.5f, _main.CameraYaw + MathF.PI * 0.82f); + } + var r2 = localPreview.Inner.State.Contenders[2]; + if (r2.Alive) + { + localPreview.Inner.SetContenderPose(r2.Id, player.X + fwdX * 26f + rightX * 8.5f, player.Z + fwdZ * 26f + rightZ * 8.5f, _main.CameraYaw - MathF.PI * 0.72f); + } + } + + _main.Arena.Sync(_main.Session, 1.5f, 1f / 60f); + _main.Hud.Sync(_main.Session); + _main.Hud.Schematic.TriggerHitPulse(1, 0, 0.9f); + + if (_main.Arena.GetContenderVisual(player.Id) is { } pVis) + { + Vector3 vehFwd = pVis.Root.GlobalTransform.Basis.Z.Normalized(); + if (pVis.GetMountedGearNode("hp.weapon.roof") is { } roofGun) + { + Vector3 gunFwd = roofGun.GlobalTransform.Basis.Z.Normalized(); + GD.Print($"SMOKE INFO: Preview Jackal yaw={player.Yaw:F3} vehFwd={vehFwd} roofGunFwd={gunFwd} dot={vehFwd.Dot(gunFwd):F3}"); + } + } + + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var frameImg = GetViewport().GetTexture().GetImage(); + var err = frameImg.SavePng(previewPath); + GD.Print($"SMOKE INFO: Saved preview screenshot ({frameImg.GetWidth()}x{frameImg.GetHeight()}) to {previewPath} (err={err})"); + Check(err == Error.Ok, $"Failed to save preview screenshot to {previewPath}: {err}"); + } + + private async Task VerifyCut3bVehiclesAndMechanismsAsync() + { + var cache = _main.Arena.AssetCache; + cache.PreloadAll(); + + Check(cache.Vehicles.Count == 15, $"Expected 15 cached vehicle GLBs, got {cache.Vehicles.Count}"); + Check(cache.Gear.Count == 6, $"Expected 6 cached gear GLBs, got {cache.Gear.Count}"); + + // 1. All 15 vehicles bind 100% of hardpoint AnchorIds and attach/unmount gear cleanly + foreach (var spec in Catalog.AllChassis) + { + var pkg = Catalog.TryGetPackage(spec.Id); + Check(pkg is not null, $"Missing VehiclePackage for '{spec.Id}'"); + if (pkg is null) continue; + + var vis = VehicleVisualInstance.Create(cache, spec.Id, VehicleVisualRole.Player); + Check(CountMeshInstances(vis.Root) == 0, + $"Expected zero MeshInstance3D children on MultiMesh rig '{spec.Id}', got {CountMeshInstances(vis.Root)}"); + Check(vis.BoundHardpointCount == spec.Hardpoints.Length, + $"Expected {spec.Hardpoints.Length} bound hardpoints on '{spec.Id}', got {vis.BoundHardpointCount}"); + Check(vis.Joints.Count == pkg.Joints.Count, + $"Expected {pkg.Joints.Count} bound joints on '{spec.Id}', got {vis.Joints.Count}"); + Check(MathF.Abs(vis.Template.MinY) < 0.05f, + $"Expected grounded GLB MinY ~ 0 on '{spec.Id}', got {vis.Template.MinY:F4}"); + + var grid = Catalog.CreateWithDefaultLoadout(spec); + vis.SyncMountedGear(grid); + int mountedMeshes = 0; + foreach (var m in grid.Mounted) + { + var gNode = vis.GetMountedGearNode(m.HardpointId); + if (gNode is not null) + { + mountedMeshes++; + if (m.Spec.Kind == HardpointKind.Weapon) + { + (string frontPart, string rearPart) = m.Spec.Id switch + { + "mg_762" or "pd_flak" => ("barrel_inner", "receiver"), + "autocannon" or "flak" => ("muzzle_brake_L", "gun_housing"), + "recoilless" => ("sight_tube", "breech_band"), + _ => ("condenser_ring_2", "ivory_cowl") + }; + bool hasCentroids = vis.TryGetMountedWeaponCentroidsInModel( + m.HardpointId, frontPart, rearPart, out Vector3 frontC, out Vector3 rearC); + Check(hasCentroids, + $"Missing weapon submeshes '{frontPart}'/'{rearPart}' on '{spec.Id}.{m.HardpointId}' ({m.Spec.Id})"); + if (hasCentroids) + { + Vector3 muzzleDir = (frontC - rearC).Normalized(); + if (m.Spec.Id == "recoilless") + { + GD.Print($"SMOKE INFO: recoilless {spec.Id}.{m.HardpointId} sight_tube={frontC} breech={rearC} dir={muzzleDir}"); + Check(frontC.Z > rearC.Z + 0.20f, + $"Expected recoilless sight_tube (+Z) ahead of breech_band on '{spec.Id}.{m.HardpointId}', got sight={frontC}, breech={rearC}"); + } + Check(muzzleDir.Z > 0.75f, + $"Expected weapon '{m.Spec.Id}' on '{spec.Id}.{m.HardpointId}' mesh geometry to point forward (+Z), got dir={muzzleDir}"); + } + } + } + } + Check(mountedMeshes == grid.Mounted.Count && mountedMeshes > 0, + $"Expected all {grid.Mounted.Count} default modules on '{spec.Id}' to attach visible gear meshes, got {mountedMeshes}"); + + // Unmount first module and confirm gear node is removed cleanly + if (grid.Mounted.Count > 0) + { + string removedHp = grid.Mounted[0].HardpointId; + grid.Mounted.RemoveAt(0); + vis.SyncMountedGear(grid); + Check(vis.GetMountedGearNode(removedHp) is null, + $"Expected gear node on '{spec.Id}.{removedHp}' to be removed after unmount"); + } + + vis.Root.QueueFree(); + } + + // 2. Rig animator produces real non-zero transforms (> 0.001 rad) with zero NaNs across all mobility archetypes + VerifyRigMotion(cache, "jackal", "joint.wheel_fl", + new VehicleRigDriveInput(new Vector3(0f, 0f, 14f), 0f, 0f, 0f, -1f, 1f, 0f, 1f, 1f / 60f), + minRotRad: 0.001f); + VerifyRigMotion(cache, "hornet", "joint.rotor_l", + new VehicleRigDriveInput(new Vector3(0f, 0f, 10f), 0f, 0f, 0f, 0f, 1f, 1f, 1f, 1f / 60f), + minRotRad: 0.001f); + VerifyRigMotion(cache, "anvil", "joint.turret_yaw", + new VehicleRigDriveInput(Vector3.Zero, 0f, 0.85f, 0f, 0f, 0f, 0f, 1f, 1f / 60f), + minRotRad: 0.001f); + VerifyRigMotion(cache, "manticore", "joint.tail_yaw", + new VehicleRigDriveInput(new Vector3(0f, 0f, 6f), 0f, 0.70f, 18f, 0f, 0.8f, 0f, 1f, 1f / 60f), + minRotRad: 0.001f); + + // Breaker: verify oleo strut slide + scissor torque links + recess ram aiming driven by Newtonian GRF load + { + var breakerVis = VehicleVisualInstance.Create(cache, "breaker", VehicleVisualRole.Player); + Node3D? oleo = breakerVis.GetNamedNode("LegL.Oleo"); + Node3D? scissorUp = breakerVis.GetNamedNode("LegL.TorqueUp"); + Node3D? ram0 = breakerVis.GetNamedNode("LegL.RecessRam0"); + Check(oleo is not null && scissorUp is not null && ram0 is not null, + "Expected Breaker LegL.Oleo, LegL.TorqueUp, and LegL.RecessRam0 nodes to resolve"); + if (oleo is not null && scissorUp is not null && ram0 is not null) + { + Transform3D oleo0 = oleo.Transform; + Transform3D sc0 = scissorUp.Transform; + Transform3D ramRest = ram0.Transform; + Node3D? footL = breakerVis.GetNamedNode("LegL.Foot"); + if (footL is not null) + { + footL.Transform = new Transform3D(new Basis(Vector3.Right, 0.28f) * footL.Transform.Basis, footL.Transform.Origin); + } + for (int s = 0; s < 10; s++) VehicleRigAnimator.StepBreakerLinkages(breakerVis, leftLoadG: 1.85f, rightLoadG: 0.25f, dt: 1f / 60f); + for (int s = 0; s < 10; s++) VehicleRigAnimator.StepBreakerLinkages(breakerVis, leftLoadG: 0.25f, rightLoadG: 1.85f, dt: 1f / 60f); + + float oleoDelta = (oleo.Transform.Origin - oleo0.Origin).Length(); + float scDelta = sc0.Basis.GetRotationQuaternion().AngleTo(scissorUp.Transform.Basis.GetRotationQuaternion()); + float ramDelta = ramRest.Basis.GetRotationQuaternion().AngleTo(ram0.Transform.Basis.GetRotationQuaternion()); + GD.Print($"SMOKE INFO: Breaker mech deltas oleo={oleoDelta:F4}m scissor={scDelta:F4}rad ram={ramDelta:F4}rad"); + Check(oleoDelta > 0.0005f && !HasNaN(oleo.Transform), $"Expected Breaker LegL.Oleo motion > 0.0005m, got {oleoDelta:F5}"); + Check(scDelta > 0.001f && !HasNaN(scissorUp.Transform), $"Expected Breaker LegL.TorqueUp scissor rotation > 0.001rad, got {scDelta:F5}"); + Check(ramDelta > 0.001f && !HasNaN(ram0.Transform), $"Expected Breaker LegL.RecessRam0 aim rotation > 0.001rad, got {ramDelta:F5}"); + } + breakerVis.Root.QueueFree(); + } + + // 3. Part-by-cell armor detachment + hardpoint gear shear into DebrisSystem + { + var debris = new DebrisSystem { Name = "SmokeDebrisTest" }; + AddChild(debris); + var anvilGrid = Catalog.CreateWithDefaultLoadout(Catalog.Anvil); + var anvilVis = VehicleVisualInstance.Create(cache, "anvil", VehicleVisualRole.Player); + AddChild(anvilVis.Root); + anvilVis.SyncMountedGear(anvilGrid); + anvilVis.SyncDamageAndHeat(anvilGrid, debris, Vector3.Zero); + Check(debris.ActiveCount == 0, $"Expected 0 debris before armor strip, got {debris.ActiveCount}"); + + // Pick a cell that has detachable armor/shroud plates + int targetCx = -1, targetCy = -1; + for (int cy = 0; cy < anvilGrid.Spec.Height && targetCx < 0; cy++) + { + for (int cx = 0; cx < anvilGrid.Spec.Width; cx++) + { + if (anvilVis.CountDetachablePartsForCell(cx, cy) > 0) + { + targetCx = cx; + targetCy = cy; + break; + } + } + } + Check(targetCx >= 0, "Expected Anvil to have >= 1 cell with detachable armor/shroud parts"); + + // Strip that armor cell AND strip weapon hardpoint hp.weapon.siege_l + if (targetCx >= 0) + { + anvilGrid.Armor[targetCx, targetCy] = 0f; + } + var siegeHp = anvilGrid.FindHardpoint("hp.weapon.siege_l")!; + for (int dy = 0; dy < siegeHp.Height; dy++) + { + for (int dx = 0; dx < siegeHp.Width; dx++) + { + anvilGrid.Armor[siegeHp.X + dx, siegeHp.Y + dy] = 0f; + } + } + + anvilVis.SyncDamageAndHeat(anvilGrid, debris, new Vector3(2f, 0f, 4f)); + Check(debris.ActiveCount >= 2, + $"Expected >= 2 debris pieces (armor plate + sheared weapon gear), got {debris.ActiveCount}"); + Check(anvilVis.GetMountedGearNode("hp.weapon.siege_l") is null, + "Expected hp.weapon.siege_l gear to shear off when hardpoint becomes non-operational"); + + if (debris.TryGetPiecePosition(0, out Vector3 p0)) + { + for (int s = 0; s < 25; s++) + { + debris.Step(1f / 60f, _main.Session.ViewState.Terrain); + } + debris.TryGetPiecePosition(0, out Vector3 p1); + float moved = p1.DistanceTo(p0); + Check(moved > 0.1f && p1.IsFinite(), + $"Expected debris piece to travel/fall > 0.1m under blast + gravity, got {moved:F3}m"); + } + + anvilVis.Root.QueueFree(); + debris.QueueFree(); + } + + // 4. Full Paladin hull + gear strip detaches every merged cell armor chunk + mounted gear under 256 cap + { + var debris = new DebrisSystem { Name = "SmokePaladinDebrisTest" }; + AddChild(debris); + var palGrid = Catalog.CreateWithDefaultLoadout(Catalog.Paladin); + var palVis = VehicleVisualInstance.Create(cache, "paladin", VehicleVisualRole.Player); + AddChild(palVis.Root); + palVis.SyncMountedGear(palGrid); + + int activeCellCount = 0; + int expectedCellChunks = 0; + for (int cy = 0; cy < palGrid.Spec.Height; cy++) + { + for (int cx = 0; cx < palGrid.Spec.Width; cx++) + { + if (palGrid.Spec.IsActive(cx, cy)) + { + activeCellCount++; + expectedCellChunks += palVis.CountDetachablePartsForCell(cx, cy); + } + palGrid.Armor[cx, cy] = 0f; + } + } + int expectedTotal = expectedCellChunks + palGrid.Mounted.Count; + palVis.SyncDamageAndHeat(palGrid, debris, new Vector3(1f, 0f, 3f)); + GD.Print($"SMOKE INFO: Full Paladin strip debris.ActiveCount={debris.ActiveCount} (activeCells={activeCellCount}, cellChunks={expectedCellChunks}, mounted={palGrid.Mounted.Count})"); + Check(debris.ActiveCount >= activeCellCount && debris.ActiveCount == expectedTotal && debris.ActiveCount <= 256, + $"Expected full Paladin strip to detach {expectedTotal} (>= {activeCellCount} active cells) pieces under 256 cap, got {debris.ActiveCount}"); + palVis.Root.QueueFree(); + debris.QueueFree(); + } + + // 5. All 15 ChassisDrop salvage wrecks ground within 0.05m of terrain & PickedUp frees drops cleanly + { + var drops = _main.Session.ViewState.GroundDrops; + int baseCount = drops.Count; + _main.Arena.Sync(_main.Session, 1.0f, 1f / 60f); + int trackedBefore = _main.Arena.ActiveDropVisualCount; + + int nextId = 90000; + var added = new List(Catalog.AllChassis.Count); + float maxGroundErr = 0f; + for (int i = 0; i < Catalog.AllChassis.Count; i++) + { + var spec = Catalog.AllChassis[i]; + float dx = -80f + i * 11f; + float dz = -40f; + var d = new GroundDrop(nextId++, dx, dz, spec, null); + drops.Add(d); + added.Add(d); + } + + _main.Arena.Sync(_main.Session, 1.0f, 1f / 60f); + Check(_main.Arena.ActiveDropVisualCount == trackedBefore + added.Count, + $"Expected {trackedBefore + added.Count} tracked drop visuals, got {_main.Arena.ActiveDropVisualCount}"); + + for (int i = 0; i < added.Count; i++) + { + var d = added[i]; + bool hasDrop = _main.Arena.TryGetChassisDropVisual(d.Id, out var dropVis, out _); + Check(hasDrop && dropVis is not null, $"Missing ChassisDrop visual for Drop_{d.Id} ('{d.Chassis!.Id}')"); + if (hasDrop && dropVis is not null) + { + dropVis.SetLodState(useStaticLod: false, castShadows: false); + float minWorldY = dropVis.ComputeMinVertexY(); + float terrainY = _main.Session.ViewState.Terrain.SampleHeight(d.X, d.Z); + float err = MathF.Abs(minWorldY - terrainY); + if (err > maxGroundErr) maxGroundErr = err; + Check(err <= 0.05f, + $"ChassisDrop '{d.Chassis!.Id}' buried/floating: minWorldY={minWorldY:F4}m terrainY={terrainY:F4}m err={err:F4}m"); + } + } + GD.Print($"SMOKE INFO: ChassisDrop max ground err={maxGroundErr:F4}m across {added.Count} chassis"); + + // Also verify far LOD (SingleSurfaceLodFarMesh) ChassisDrop grounding stays <= 0.05m across all 15 chassis + float maxFarGroundErr = 0f; + for (int i = 0; i < added.Count; i++) + { + var d = added[i]; + if (_main.Arena.TryGetChassisDropVisual(d.Id, out var dropVis, out _) && dropVis is not null) + { + dropVis.SetLodState(useStaticLod: true, castShadows: false); + float minFarWorldY = dropVis.ComputeMinVertexY(); + float terrainY = _main.Session.ViewState.Terrain.SampleHeight(d.X, d.Z); + float err = MathF.Abs(minFarWorldY - terrainY); + if (err > maxFarGroundErr) maxFarGroundErr = err; + Check(err <= 0.05f, + $"Far LOD ChassisDrop '{d.Chassis!.Id}' buried/floating: minFarWorldY={minFarWorldY:F4}m terrainY={terrainY:F4}m err={err:F4}m"); + } + } + GD.Print($"SMOKE INFO: Far LOD ChassisDrop max ground err={maxFarGroundErr:F4}m across {added.Count} chassis"); + + for (int i = 0; i < added.Count; i++) + { + added[i].PickedUp = true; + } + _main.Arena.Sync(_main.Session, 1.1f, 1f / 60f); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + Check(_main.Arena.ActiveDropVisualCount == trackedBefore, + $"Expected picked-up drops removed from _dropVisuals ({trackedBefore}), got {_main.Arena.ActiveDropVisualCount}"); + + drops.RemoveRange(baseCount, added.Count); + } + + // 6. All 7 walkers (including Kestrel) walk through IClientArenaSession (LocalArenaSession) + Hybrid B FK snapshot cleanly + { + using var localWalk = new LocalArenaSession(seed: 42, mapKind: ArenaMapKind.Desert); + IClientArenaSession walkIface = localWalk; + var walkSession = localWalk.Inner; + for (int cIdx = 1; cIdx < walkSession.State.Contenders.Count; cIdx++) + { + walkSession.SetContenderPose(cIdx, 450f + cIdx * 18f, 450f); + } + + var walkerChecks = new (string Id, string FootNode, string PelvisNode)[] + { + ("raptor", "FootL", "Pelvis"), + ("spectre", "LegL.Ankle", "Pelvis"), + ("manticore", "FootFL", "Hull"), + ("bastion", "Ankle.fl", "Trunk"), + ("breaker", "LegL.Foot", "Pelvis"), + ("paladin", "LegL.Ankle", "Pelvis"), + ("kestrel", "LegL.Foot", "Pelvis"), + }; + + foreach (var (wId, footNodeName, pelvisNodeName) in walkerChecks) + { + var wSpec = Catalog.ChassisById[wId]; + walkSession.SetContenderPose(0, 0f, 0f, 0f); + if (walkIface.LocalContender.Grid.Spec.Id != wId) + { + walkIface.ViewState.SpawnChassisDrop(0f, 0f, wSpec); + Check(walkSession.TrySwapNearbyChassis(0), $"Failed to swap walkSession player to '{wId}'"); + } + + var vis = VehicleVisualInstance.Create(cache, wId, VehicleVisualRole.Player); + float worstRelMinY = float.PositiveInfinity; + float minFootZ = float.PositiveInfinity, maxFootZ = float.NegativeInfinity; + float minFootX = float.PositiveInfinity, maxFootX = float.NegativeInfinity; + Node3D? footNode = vis.GetNamedNode(footNodeName); + Node3D? pelvisNode = vis.GetNamedNode(pelvisNodeName); + Check(footNode is not null && pelvisNode is not null, + $"Missing FK nodes '{footNodeName}'/'{pelvisNodeName}' on walker '{wId}'"); + + var player = walkIface.LocalContender; + for (int step = 0; step < 60; step++) + { + walkIface.SubmitLocalInput(new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: player.X, + AimWorldZ: player.Z + 50f, + Fire: false, + InteractPickup: false, + Brake: false), isPhysicsTick: true); + + bool hasSnap = walkIface.TrySampleInterpolatedWalkerPose(true, player.Id, 1f, out var walkerSnap); + Check(hasSnap, $"Missing WalkerVisualSnapshot for '{wId}' at step {step}"); + if (!hasSnap) break; + + var (interpPos, interpRot, interpVel) = walkIface.GetInterpolatedContenderPose(player.Id, 1f); + var q = new Quaternion(interpRot.X, interpRot.Y, interpRot.Z, interpRot.W); + vis.Root.Transform = new Transform3D(new Basis(q), new Vector3(interpPos.X, interpPos.Y, interpPos.Z)); + VehicleRigAnimator.Update( + vis, + player, + new Vector3(interpVel.X, interpVel.Y, interpVel.Z), + vis.Root.Basis, + 1f / 60f, + in walkerSnap); + + float curMinWorldY = vis.ComputeMinVertexY(relativeToModelRoot: false); + Check(!float.IsNaN(curMinWorldY), $"NaN vertex Y on walker '{wId}' step {step}"); + + if (footNode is not null && pelvisNode is not null) + { + Vector3 fPos = TransformPointToAncestor(footNode, pelvisNode, Vector3.Zero); + if (fPos.Z < minFootZ) minFootZ = fPos.Z; + if (fPos.Z > maxFootZ) maxFootZ = fPos.Z; + if (fPos.X < minFootX) minFootX = fPos.X; + if (fPos.X > maxFootX) maxFootX = fPos.X; + + Vector3 fInModel = TransformPointToAncestor(footNode, vis.ModelRoot, Vector3.Zero); + Vector3 fWorld = vis.Root.Transform * (vis.ModelRoot.Transform * fInModel); + float groundUnderFoot = walkIface.ViewState.Terrain.SampleHeight(fWorld.X, fWorld.Z); + float relMinY = curMinWorldY - groundUnderFoot; + if (relMinY < worstRelMinY) worstRelMinY = relMinY; + } + } + + float zSpan = footNode is not null ? maxFootZ - minFootZ : 0f; + float xSpan = footNode is not null ? maxFootX - minFootX : 0f; + GD.Print($"SMOKE INFO: HybridB Walker {wId} minWorldFootRelY={worstRelMinY:F4}m zSpan={zSpan:F3}m xSpan={xSpan:F3}m"); + Check(worstRelMinY >= -0.25f, + $"Walker '{wId}' plunged below terrain: minRelY={worstRelMinY:F4}m"); + if (footNode is not null) + { + Check(zSpan > 0.12f, + $"Expected walker '{wId}' foot '{footNodeName}' to stride along Z > 0.12m through Hybrid B FK, got {zSpan:F3}m"); + } + vis.Root.QueueFree(); + } + } + + // 7. VehicleRigAnimator.Update with dt == 0 is a strict no-op unless snap == true + { + var anvilVis = VehicleVisualInstance.Create(cache, "anvil", VehicleVisualRole.Player); + var driveInp = new VehicleRigDriveInput( + new Vector3(0f, 0f, 6f), 0f, 0.2f, 5f, 0.2f, 0.5f, 0f, 1f, 1f / 60f); + for (int s = 0; s < 10; s++) + { + VehicleRigAnimator.Update(anvilVis, in driveInp, Basis.Identity); + } + + var beforeTransforms = new Dictionary(); + foreach (var (jid, j) in anvilVis.Joints) + { + beforeTransforms[jid] = j.Node.Transform; + } + + var zeroDtInp = new VehicleRigDriveInput( + new Vector3(0f, 0f, 12f), 0f, 1.9f, 35f, -1f, 1f, 0f, 1f, 0f); + VehicleRigAnimator.Update(anvilVis, in zeroDtInp, Basis.Identity); + + float maxDelta = 0f; + foreach (var (jid, before) in beforeTransforms) + { + Transform3D after = anvilVis.Joints[jid].Node.Transform; + float dOrigin = (after.Origin - before.Origin).Length(); + float dRot = before.Basis.GetRotationQuaternion().AngleTo(after.Basis.GetRotationQuaternion()); + maxDelta = MathF.Max(maxDelta, MathF.Max(dOrigin, dRot)); + } + + VehicleRigAnimator.Update(anvilVis, in zeroDtInp, Basis.Identity, snap: true); + Transform3D snapped = anvilVis.Joints["joint.turret_yaw"].Node.Transform; + float snapDelta = beforeTransforms["joint.turret_yaw"].Basis.GetRotationQuaternion() + .AngleTo(snapped.Basis.GetRotationQuaternion()); + + GD.Print($"SMOKE INFO: Rig dt=0 maxDelta={maxDelta:F6} snapDelta={snapDelta:F4}rad"); + Check(maxDelta < 1e-6f, $"Expected dt == 0 Update (snap=false) to be a strict no-op, got maxDelta={maxDelta:F6}"); + Check(snapDelta > 0.5f, $"Expected dt == 0 Update (snap=true) to snap turret cleanly, got snapDelta={snapDelta:F4}rad"); + anvilVis.Root.QueueFree(); + } + + // 8. Spectator halo sits >= 0.75m above mounted dorsal gear (including Patron with turbo_core) + { + _main.Arena.Sync(_main.Session, 1.5f, 1f / 60f); + bool sawPatron = false; + foreach (var s in _main.Session.ViewState.Spectators.Spectators) + { + if (!s.Alive) continue; + var vis = _main.Arena.GetSpectatorVisual(s.Id); + float? haloY = _main.Arena.GetSpectatorHaloLocalY(s.Id); + Check(vis is not null && haloY.HasValue, $"Missing spectator visual/halo for spectator #{s.Id}"); + if (vis is not null && haloY.HasValue) + { + float topY = vis.ComputeMountedMaxY(); + float clearance = haloY.Value - topY; + if (s.Tier == SpectatorTier.Patron) + { + sawPatron = true; + GD.Print($"SMOKE INFO: Spectator #{s.Id} ({s.Tier}/{s.Grid.Spec.Id}) mountedMaxY={topY:F3}m haloY={haloY.Value:F3}m clearance={clearance:F3}m"); + } + Check(clearance >= 0.74f, + $"Spectator #{s.Id} ({s.Tier}/{s.Grid.Spec.Id}) halo clearance < 0.74m: topY={topY:F3}m haloY={haloY.Value:F3}m clearance={clearance:F3}m"); + } + } + Check(sawPatron, "Expected at least one alive Patron spectator in arena"); + } + + // 9. Finding 3: Stripped distant rig (180m) detaches debris immediately without popping armor back on at far LOD + { + var debris = new DebrisSystem { Name = "SmokeDistantStripTest" }; + AddChild(debris); + var specGrid = Catalog.CreateWithDefaultLoadout(Catalog.Anvil); + var specVis = VehicleVisualInstance.Create(cache, "anvil", VehicleVisualRole.SpectatorPatron); + specVis.Root.Position = new Vector3(0f, 0f, 180f); + AddChild(specVis.Root); + specVis.SyncMountedGear(specGrid); + specVis.SetLodState(useStaticLod: true, castShadows: false); + Check(specVis.IsStaticLod && !specVis.ModelRoot.Visible, + "Expected intact distant rig at 180m to start in static far LOD"); + + int stripCx = -1, stripCy = -1; + for (int cy = 0; cy < specGrid.Spec.Height && stripCx < 0; cy++) + { + for (int cx = 0; cx < specGrid.Spec.Width; cx++) + { + if (specVis.CountDetachablePartsForCell(cx, cy) > 0) + { + stripCx = cx; + stripCy = cy; + break; + } + } + } + Check(stripCx >= 0, "Expected Anvil distant rig to have detachable cell parts"); + if (stripCx >= 0) + { + specGrid.Armor[stripCx, stripCy] = 0f; + } + + specVis.SyncDamageAndHeat(specGrid, debris, Vector3.Zero); + specVis.SetLodState(useStaticLod: true, castShadows: false); + Check(debris.ActiveCount >= 1, + $"Expected distant stripped rig at 180m to detach debris immediately, got {debris.ActiveCount}"); + Check(specVis.HasAnyStrippedCell && !specVis.IsStaticLod && specVis.ModelRoot.Visible, + "Expected distant stripped rig to keep ModelRoot visible without popping armor back on at far LOD"); + + specVis.Root.QueueFree(); + debris.QueueFree(); + } + + // 10. MultiMeshPartPool & PomDecalPool sanity: live arena submits into MultiMeshPartPool and PomDecalPool stamps impacts cleanly + { + var localC = _main.Session.LocalContender; + _main.Arena.PomDecals.StampTestDecal( + new Vector3(localC.X + 2f, _main.Session.ViewState.Terrain.SampleHeight(localC.X + 2f, localC.Z) + 0.03f, localC.Z), + Vector3.Up, 1.2f, tileIndex: 14); + _main.Arena.Sync(_main.Session, 1.6f, 1f / 60f); + Check(_main.Arena.PartPool.TotalSubmittedInstances > 0, + $"Expected MultiMeshPartPool to submit active instances, got {_main.Arena.PartPool.TotalSubmittedInstances}"); + Check(_main.Arena.PomDecals.ActiveCount >= 1, + $"Expected PomDecalPool to hold >= 1 active decal, got {_main.Arena.PomDecals.ActiveCount}"); + + _main.Hud.PushTestHitArc(localC.X + 20f, localC.Z + 10f, WeaponVisualClass.Explosive); + Check(_main.Hud.ActiveHitArcCount >= 1, "Expected Hud HbGpuCanvas to accept incoming hit arc"); + } + + // 11. Finding 1: Merged MultiMeshPartPool meshes preserve real non-white material albedos and intact COLOR_0.R AO + { + foreach (string vid in new[] { "paladin", "jackal" }) + { + var tpl = cache.Vehicles[vid]; + var meshesToCheck = new List { tpl.SingleSurfaceStaticMesh }; + for (int i = 0; i < tpl.StaticRigidParts.Count; i++) meshesToCheck.Add(tpl.StaticRigidParts[i].Mesh); + for (int i = 0; i < tpl.DetachableRigidParts.Count; i++) meshesToCheck.Add(tpl.DetachableRigidParts[i].Mesh); + + float minAo = 1f; + float maxAo = 0f; + int whiteNeutralVerts = 0; + int darkNeutralVerts = 0; + int armorBandVerts = 0; + int totalVerts = 0; + + for (int m = 0; m < meshesToCheck.Count; m++) + { + ArrayMesh am = meshesToCheck[m]; + for (int s = 0; s < am.GetSurfaceCount(); s++) + { + var arr = am.SurfaceGetArrays(s); + if (arr.Count <= (int)Mesh.ArrayType.Color || + arr[(int)Mesh.ArrayType.Color].VariantType != Variant.Type.PackedColorArray || + arr[(int)Mesh.ArrayType.TexUV].VariantType != Variant.Type.PackedVector2Array || + arr[(int)Mesh.ArrayType.TexUV2].VariantType != Variant.Type.PackedVector2Array) + { + Check(false, $"Merged MultiMesh '{vid}' missing Color/UV/UV2 arrays"); + continue; + } + + Color[] cols = arr[(int)Mesh.ArrayType.Color].AsColorArray(); + Vector2[] uv0 = arr[(int)Mesh.ArrayType.TexUV].AsVector2Array(); + Vector2[] uv1 = arr[(int)Mesh.ArrayType.TexUV2].AsVector2Array(); + for (int v = 0; v < cols.Length; v++) + { + totalVerts++; + float ao = cols[v].R; + if (ao < minAo) minAo = ao; + if (ao > maxAo) maxAo = ao; + + int band = (int)MathF.Floor((uv1[v].Y + 0.5f) * 0.5f); + float r = uv0[v].X; + float g = uv0[v].Y; + float b = uv1[v].X; + if (band < 3) + { + if (r > 0.95f && g > 0.95f && b > 0.95f) whiteNeutralVerts++; + if (MathF.Max(r, MathF.Max(g, b)) < 0.15f) darkNeutralVerts++; + } + else if (band == 3) + { + armorBandVerts++; + } + } + } + } + + GD.Print($"SMOKE INFO: MechPaint '{vid}' verts={totalVerts} COLOR_0.R=[{minAo:F4}, {maxAo:F4}] whiteNeutral={whiteNeutralVerts} darkNeutral={darkNeutralVerts} armorBand={armorBandVerts}"); + Check(totalVerts > 0 && minAo >= 0.03f && maxAo > 0.90f, + $"Expected '{vid}' COLOR_0.R AO intact (min >= 0.03, max > 0.90), got [{minAo:F4}, {maxAo:F4}]"); + Check(whiteNeutralVerts == 0, + $"Expected zero white-washed band 0..2 vertices on '{vid}', got {whiteNeutralVerts}"); + Check(darkNeutralVerts > 0 && armorBandVerts > 0, + $"Expected both dark non-white rubber/gunmetal ({darkNeutralVerts}) and olive armor ({armorBandVerts}) vertices on '{vid}'"); + } + Check(VehicleVisualInstance.PerfMaterialDupCount == 0, + $"Expected zero StandardMaterial3D duplicates, got {VehicleVisualInstance.PerfMaterialDupCount}"); + } + + // 12. Cut 5d-2 + Cut 10b: Unified SimEvent -> GpuSparksSystem + VolumetricEmitterPool idempotency + OmniLight3D[2] cap + global rtd_flow_field + CameraJuice + Hud X-flash + { + var particles = _main.Arena.Particles; + var volumetrics = _main.Arena.Volumetrics; + var gpuSparks = _main.Arena.GpuSparks; + particles.ClearAll(); + volumetrics.ClearAll(); + gpuSparks.ClearAll(); + + // Verify Cut 10b structural subtraction & GPUParticles3D / global shader param wiring + Check(!FileAccess.FileExists("res://particle_billboard.gdshader"), + "Expected obsolete particle_billboard.gdshader to be deleted"); + int particleMmiCount = 0; + foreach (Node ch in particles.GetChildren()) + { + if (ch is MultiMeshInstance3D) particleMmiCount++; + } + Check(particleMmiCount == 0, + $"Expected zero MultiMeshInstance3D nodes inside collapsed ParticlePool, found {particleMmiCount}"); + Check(gpuSparks.ParticlesNode.Amount == GpuSparksSystem.Capacity && gpuSparks.ParticlesNode.AmountRatio == 0.0f, + $"Expected GpuSparksSystem Amount={GpuSparksSystem.Capacity} AmountRatio=0.0f, got {gpuSparks.ParticlesNode.Amount} ratio={gpuSparks.ParticlesNode.AmountRatio}"); + + Check(AtmosphereSystem.AreFlowGlobalsRegistered, + "Expected global rtd_flow_* shader parameters registered in AtmosphereSystem"); + + int beforeSparks = gpuSparks.TotalEmittedCount; + int beforeVol = volumetrics.ActiveEmitterCount; + int beforeImp = volumetrics.ActiveImpulseCount; + + int tracerId = _main.Session.ViewState.AllocateTracerId(); + var localC = _main.Session.LocalContender; + Vector3 pPos = new(localC.X, localC.Y, localC.Z); + var shotEvent = new ShotFiredEvent + { + TracerId = tracerId, + IsSpectatorShooter = false, + ShooterId = _main.Session.LocalContenderId, + StartX = pPos.X, + StartY = pPos.Y + 1f, + StartZ = pPos.Z, + EndX = pPos.X + 20f, + EndY = pPos.Y + 1f, + EndZ = pPos.Z, + ColorRgba = 0xFFEEDDAAu, + Ttl = 0.03f, + WeaponClass = (byte)WeaponVisualClass.Explosive, + WeaponId = "recoilless" + }; + + var simBatch = new List { shotEvent }; + var emptyFootsteps = new List(); + _main.Arena.ConsumeEvents(_main.Session, simBatch, emptyFootsteps, 0f, _main.SampleCurrentMapGroundTint); + int afterSparks = gpuSparks.TotalEmittedCount; + int afterVol = volumetrics.ActiveEmitterCount; + int afterImp = volumetrics.ActiveImpulseCount; + Check(afterSparks >= beforeSparks + 1 && afterVol >= beforeVol + 1 && afterImp >= beforeImp + 1, + $"Expected recoilless ShotFiredEvent #{tracerId} to emit GPU muzzle flash/sparks (+{afterSparks - beforeSparks}), volumetric breech puff (+{afterVol - beforeVol}), and flow impulse (+{afterImp - beforeImp})"); + + // Re-consume with dt=0: idempotent TracerId dedupe must NOT double-emit + _main.Arena.ConsumeEvents(_main.Session, simBatch, emptyFootsteps, 0f, _main.SampleCurrentMapGroundTint); + _main.Arena.ConsumeEvents(_main.Session, simBatch, emptyFootsteps, 0f, _main.SampleCurrentMapGroundTint); + Check(gpuSparks.TotalEmittedCount == afterSparks && volumetrics.ActiveEmitterCount == afterVol && volumetrics.ActiveImpulseCount == afterImp, + $"Expected duplicate ShotFiredEvent #{tracerId} across dt=0 frames to spawn once, got sparks {afterSparks}->{gpuSparks.TotalEmittedCount}, vol {afterVol}->{volumetrics.ActiveEmitterCount}"); + + // OmniLight3D[2] pool strictly capped at <= 2 active lights even under 12 simultaneous flashes + particles.ClearAll(); + for (int f = 0; f < 12; f++) + { + particles.TriggerFlashLightForTest( + pPos + new Vector3(f * 2f, 1.5f, 0f), + new Color(1f, 0.7f, 0.3f), + 3.0f, + 12f, + 0.15f, + priority: f); + } + particles.AdvanceAndCommit(0f); + Check(particles.FlashLightPoolSize == 2 && particles.ActiveFlashLightCount <= 2 && particles.PeakFlashLightCount <= 2, + $"Expected OmniLight3D pool capped at <= 2, got active={particles.ActiveFlashLightCount} peak={particles.PeakFlashLightCount}"); + + // Far walker footstep pulse (>70m static LOD, <=110m) emits GPU dust motes + optional volumetric puff + particles.ClearAll(); + volumetrics.ClearAll(); + gpuSparks.ClearAll(); + var farStep = new FootstepPulse( + IsContender: true, + EntityId: 99, + LegIndex: 0, + ChassisId: "bastion", + MassKg: 4600f, + LoadG: 1.25f, + WorldPos: new System.Numerics.Vector3(pPos.X + 85f, pPos.Y, pPos.Z)); + _main.Arena.ConsumeEvents(_main.Session, Array.Empty(), new[] { farStep }, 0f, _main.SampleCurrentMapGroundTint); + Check(gpuSparks.TotalEmittedCount >= 4 && volumetrics.ActiveEmitterCount >= 1, + $"Expected far walker (85m > 70m static LOD) footstep to emit GPU dust motes ({gpuSparks.TotalEmittedCount}) + volumetric puff ({volumetrics.ActiveEmitterCount})"); + particles.ClearAll(); + volumetrics.ClearAll(); + gpuSparks.ClearAll(); + + // CameraJuiceState zero-idle-jitter & ComputeCenterScreenAim invariance under trauma + var juice = _main.CameraJuice; + juice.Reset(); + Check(juice.IsIdle, "Expected CameraJuiceState idle after Reset"); + var (aimIdleX, aimIdleY, aimIdleZ) = _main.ProbeCenterScreenAim(); + juice.ConsumeEvents(simBatch, _main.Session.LocalContenderId, new System.Numerics.Vector3(pPos.X, pPos.Y, pPos.Z), _main.Session); + juice.Update(0.016f, 0f, false); + Check(!juice.IsIdle && juice.RecoilPitchRad > 0f, "Expected CameraJuiceState recoil after local recoilless shot"); + var (aimJuiceX, aimJuiceY, aimJuiceZ) = _main.ProbeCenterScreenAim(); + Check(MathF.Abs(aimIdleX - aimJuiceX) < 1e-4f && MathF.Abs(aimIdleY - aimJuiceY) < 1e-4f && MathF.Abs(aimIdleZ - aimJuiceZ) < 1e-4f, + "Expected ComputeCenterScreenAim to remain strictly invariant during camera recoil/trauma"); + juice.Reset(); + + // Hud reticle hit-marker X-flash + hud_vignette.gdshader falsification + _main.Hud.ResetFeedback(); + Check(!_main.Hud.HasActiveHitMarker && !_main.Hud.IsVignetteVisible, + "Expected HUD hit-marker & vignette inactive when cool and unhit"); + + // Non-local shooter must produce ZERO reticle hit-marker flash + var aiHit = new HitImpactEvent + { + EventId = 8801, + ShooterId = _main.Session.LocalContenderId + 1, + IsContenderShooter = true, + TargetKind = (byte)HitTargetKind.Contender, + TargetId = _main.Session.LocalContenderId + 2, + ArmorDamage = 18f, + CoreDamage = 0f, + Killed = false + }; + _main.Hud.ConsumeEvents(new ISimEvent[] { aiHit }, _main.Session.LocalContenderId, 1.0f, 0.2f); + Check(!_main.Hud.HasActiveHitMarker, "Expected AI/other shooter hit NOT to trigger local reticle hit-marker"); + + // Local shooter hitting Terrain / StaticCover / Airburst must produce ZERO reticle hit-marker flash + var missTerrainHit = new HitImpactEvent + { + EventId = 8810, + ShooterId = _main.Session.LocalContenderId, + IsContenderShooter = true, + TargetKind = (byte)HitTargetKind.Terrain, + TargetId = -1, + ArmorDamage = 0f, + CoreDamage = 0f, + Killed = false + }; + var missCoverHit = new HitImpactEvent + { + EventId = 8811, + ShooterId = _main.Session.LocalContenderId, + IsContenderShooter = true, + TargetKind = (byte)HitTargetKind.StaticCover, + TargetId = 0, + ArmorDamage = 0f, + CoreDamage = 0f, + Killed = false + }; + var missAirburstHit = new HitImpactEvent + { + EventId = 8812, + ShooterId = _main.Session.LocalContenderId, + IsContenderShooter = true, + TargetKind = (byte)HitTargetKind.StaticCover, + TargetId = -1, + IsAirburst = true, + ArmorDamage = 0f, + CoreDamage = 0f, + Killed = false + }; + _main.Hud.ConsumeEvents(new ISimEvent[] { missTerrainHit, missCoverHit, missAirburstHit }, _main.Session.LocalContenderId, 1.0f, 0.2f); + Check(!_main.Hud.HasActiveHitMarker, "Expected Terrain/StaticCover/Airburst miss NOT to trigger local reticle hit-marker"); + + // Local armor hit -> Armor X-flash + var localArmorHit = new HitImpactEvent + { + EventId = 8802, + ShooterId = _main.Session.LocalContenderId, + IsContenderShooter = true, + TargetKind = (byte)HitTargetKind.Contender, + TargetId = _main.Session.LocalContenderId + 1, + ArmorDamage = 22f, + CoreDamage = 0f, + Killed = false + }; + _main.Hud.ConsumeEvents(new ISimEvent[] { localArmorHit }, _main.Session.LocalContenderId, 1.0f, 0.2f); + Check(_main.Hud.HasActiveHitMarker && _main.Hud.ActiveHitMarkerKind == HitMarkerKind.Armor, + $"Expected Armor hit-marker, got {_main.Hud.ActiveHitMarkerKind}"); + + // Local core hit -> Core X-flash + var localCoreHit = new HitImpactEvent + { + EventId = 8803, + ShooterId = _main.Session.LocalContenderId, + IsContenderShooter = true, + TargetKind = (byte)HitTargetKind.Contender, + TargetId = _main.Session.LocalContenderId + 1, + ArmorDamage = 10f, + CoreDamage = 14f, + Killed = false + }; + _main.Hud.ConsumeEvents(new ISimEvent[] { localCoreHit }, _main.Session.LocalContenderId, 1.0f, 0.2f); + Check(_main.Hud.HasActiveHitMarker && _main.Hud.ActiveHitMarkerKind == HitMarkerKind.Core, + $"Expected Core hit-marker, got {_main.Hud.ActiveHitMarkerKind}"); + + // Local kill + overheat -> Kill double-X + vignette active + var localKillHit = new HitImpactEvent + { + EventId = 8804, + ShooterId = _main.Session.LocalContenderId, + IsContenderShooter = true, + TargetKind = (byte)HitTargetKind.Contender, + TargetId = _main.Session.LocalContenderId + 1, + ArmorDamage = 0f, + CoreDamage = 35f, + Killed = true + }; + _main.Hud.ConsumeEvents(new ISimEvent[] { localKillHit }, _main.Session.LocalContenderId, 1.0f, 0.92f); + Check(_main.Hud.HasActiveHitMarker && _main.Hud.ActiveHitMarkerKind == HitMarkerKind.Kill && _main.Hud.IsVignetteVisible, + $"Expected Kill hit-marker & overheat vignette active, got kind={_main.Hud.ActiveHitMarkerKind} vig={_main.Hud.IsVignetteVisible}"); + _main.Hud.ResetFeedback(); + } + + // 13. Loopback IClientArenaSession check: ServerMatchHost + RemoteArenaSession join + snapshot sync + { + using var host = new ServerMatchHost(IPAddress.Loopback, port: 0, seed: 42, mapKind: ArenaMapKind.Desert); + using var remote = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "SmokeClient"); + IClientArenaSession remoteIface = remote; + + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + for (int t = 0; t < 15 && !remote.IsJoined; t++) + { + host.StepOnce(nowMs + t * 16); + remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f); + } + Check(remote.IsJoined && remoteIface.ConnectionStatus.Connected, + $"Expected RemoteArenaSession loopback connect inside Smoke, label='{remoteIface.ConnectionStatus.StateLabel}'"); + for (int t = 0; t < 6; t++) + { + remoteIface.SubmitLocalInput(new PlayerInput(0.5f, 0f, 10f, 10f, false, false, false), isPhysicsTick: true); + host.StepOnce(nowMs + 300 + t * 16); + remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f); + } + Check(remote.LastSnapshotSeq > 0, $"Expected loopback RemoteArenaSession to receive snapshots, got seq={remote.LastSnapshotSeq}"); + Check(remoteIface.LocalContender.Alive, "Expected loopback RemoteArenaSession LocalContender alive"); + } + + // 14. Cut 5d-1: Headless AudioBank, voice-cap/priority/dedupe, and mass-scaled GRF footstep pitch falsification + { + var audio = _main.Audio; + audio.EnsureInitialized(); + Check(audio.Bank.HavenClipCount == 25, $"Expected 25 curated Haven clips in ProceduralAudioBank, got {audio.Bank.HavenClipCount}"); + Check(audio.Bank.ProceduralClipCount == RustToDust.Core.Audio.PcmSynth.CueRegistry.Count, + $"Expected {RustToDust.Core.Audio.PcmSynth.CueRegistry.Count} procedural clips in ProceduralAudioBank, got {audio.Bank.ProceduralClipCount}"); + + audio.ClearAll(); + audio.ResetStatsForTest(); + var localC = _main.Session.LocalContender; + Vector3 listener = new(localC.X, localC.Y, localC.Z); + + var burstEvents = new List(); + // Local player shot first (priority 10) + burstEvents.Add(new ShotFiredEvent + { + TracerId = 90001, + IsSpectatorShooter = false, + ShooterId = _main.Session.LocalContenderId, + StartX = listener.X, + StartY = listener.Y + 1f, + StartZ = listener.Z, + EndX = listener.X + 40f, + EndY = listener.Y + 1f, + EndZ = listener.Z, + WeaponClass = (byte)WeaponVisualClass.KineticLight, + WeaponId = "mg_762" + }); + + // 5-pellet flak salvo from contender 1 -> must dedupe to 1 audio voice + for (int p = 0; p < 5; p++) + { + burstEvents.Add(new ShotFiredEvent + { + TracerId = 90010 + p, + IsSpectatorShooter = false, + ShooterId = 1, + StartX = listener.X + 18f, + StartY = listener.Y + 1f, + StartZ = listener.Z, + EndX = listener.X, + EndY = listener.Y + 1f, + EndZ = listener.Z, + WeaponClass = (byte)WeaponVisualClass.Explosive, + WeaponId = "flak" + }); + } + + // 30 simultaneous distant AI shots (>150m, <240m) trying to saturate all 19 one-shot voices + for (int a = 2; a < 32; a++) + { + burstEvents.Add(new ShotFiredEvent + { + TracerId = 90100 + a, + IsSpectatorShooter = false, + ShooterId = a, + StartX = listener.X + 175f, + StartY = listener.Y + 1f, + StartZ = listener.Z + (a % 5), + EndX = listener.X, + EndY = listener.Y + 1f, + EndZ = listener.Z, + WeaponClass = (byte)WeaponVisualClass.Autocannon, + WeaponId = "autocannon" + }); + } + + // 1 event beyond MaxAudioDistance (260m) -> must be culled (0 voices) + burstEvents.Add(new ShotFiredEvent + { + TracerId = 90999, + IsSpectatorShooter = false, + ShooterId = 99, + StartX = listener.X + 320f, + StartY = listener.Y + 1f, + StartZ = listener.Z, + EndX = listener.X, + EndY = listener.Y + 1f, + EndZ = listener.Z, + WeaponClass = (byte)WeaponVisualClass.Explosive, + WeaponId = "recoilless" + }); + + audio.ConsumeSimEvents(_main.Session, burstEvents, listener); + Check(audio.Active3DVoiceCount <= ArenaAudioSystem.Total3DVoiceCount, + $"Active 3D voices exceeded 24 cap: {audio.Active3DVoiceCount}"); + Check(audio.ActiveOneShotVoiceCount == ArenaAudioSystem.OneShotVoiceCount, + $"Expected 19 saturated one-shot voices, got {audio.ActiveOneShotVoiceCount}"); + Check(audio.DedupedCount == 4, + $"Expected 5-pellet flak salvo to dedupe 4 pellets, got DedupedCount={audio.DedupedCount}"); + Check(audio.RejectedDistanceCount == 1, + $"Expected >260m event to be distance-culled, got RejectedDistanceCount={audio.RejectedDistanceCount}"); + Check(audio.HasActiveVoiceForSource(isLocalSource: true, sourceEntityId: _main.Session.LocalContenderId), + "Expected local player priority-10 voice never to be stolen by distant AI shots"); + + // Footstep mass-scaled pitch verification: Bastion (4600 kg) pitch < Kestrel (1650 kg) pitch + audio.ClearAll(); + var kestrelPulse = new FootstepPulse(true, 0, 0, "kestrel", Catalog.Kestrel.MassKg, 1.0f, new System.Numerics.Vector3(listener.X, listener.Y, listener.Z)); + audio.ConsumeFootsteps(new[] { kestrelPulse }, _main.Session.LocalContenderId, listener); + float? kestrelPitch = audio.GetLastPitchForClipPrefix("footstep_"); + + var bastionPulse = new FootstepPulse(true, 1, 0, "bastion", Catalog.Bastion.MassKg, 1.0f, new System.Numerics.Vector3(listener.X + 10f, listener.Y, listener.Z)); + audio.ConsumeFootsteps(new[] { bastionPulse }, _main.Session.LocalContenderId, listener); + float? bastionPitch = audio.GetLastPitchForClipPrefix("footstep_heavy_"); + + Check(kestrelPitch.HasValue && bastionPitch.HasValue && bastionPitch.Value < kestrelPitch.Value, + $"Expected Bastion pitch ({bastionPitch}) < Kestrel pitch ({kestrelPitch})"); + + // Finding 4: TerrainStampEvent(Crater) + ContenderEliminatedEvent in same batch plays impact_explosion EXACTLY ONCE + audio.ClearAll(); + var victim = _main.Session.ViewState.Contenders[1]; + var killEvents = new ISimEvent[] + { + new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = victim.X, + Z = victim.Z, + Radius = 4.2f, + Depth = 0.3f + }, + new ContenderEliminatedEvent + { + VictimId = victim.Id, + KillerId = _main.Session.LocalContenderId, + IsSpectatorKiller = false + } + }; + audio.ConsumeSimEvents(_main.Session, killEvents, listener); + int expCount = audio.CountActiveVoicesForClip("impact_explosion"); + int ejectCount = audio.CountActiveVoicesForClip("mech_eject"); + Check(expCount == 1 && ejectCount == 1, + $"Expected kill crater+eliminated batch to play impact_explosion=1 & mech_eject=1, got exp={expCount} eject={ejectCount}"); + + // Finding 5: ResetForSession seeds loadout baselines so first equip (1 -> 2) plays mech_quick_bolt + audio.ResetForSession(_main.Session); + var equipEv = new ContenderLoadoutEvent + { + ContenderId = localC.Id, + ChassisId = localC.Grid.Spec.Id, + LoadoutVersion = localC.LoadoutVersion + 1 + }; + audio.ConsumeSimEvents(_main.Session, new ISimEvent[] { equipEv }, listener); + Check(audio.CountActiveUiVoicesForClip("mech_quick_bolt") == 1, + $"Expected first ContenderLoadoutEvent (1 -> 2) after ResetForSession to play mech_quick_bolt, got {audio.CountActiveUiVoicesForClip("mech_quick_bolt")}"); + + // Finding 3: Out-of-PVS deaths spawn zero phantom volumetric emitters, GPU sparks, lights, or audio + audio.ResetForSession(_main.Session); + var particles3 = _main.Arena.Particles; + var volumetrics3 = _main.Arena.Volumetrics; + var gpuSparks3 = _main.Arena.GpuSparks; + particles3.ClearAll(); + volumetrics3.ClearAll(); + gpuSparks3.ClearAll(); + var hiddenSession = new HiddenRemoteDeathsSession(_main.Session); + var spec0 = _main.Session.ViewState.Spectators.Spectators[0]; + var hiddenDeaths = new ISimEvent[] + { + new ContenderEliminatedEvent { VictimId = victim.Id, KillerId = localC.Id, IsSpectatorKiller = false }, + new SpectatorDestroyedEvent { SpectatorId = spec0.Id, KillerContenderId = localC.Id } + }; + particles3.ConsumeEvents(hiddenSession, hiddenDeaths, listener, hasCam: true, _main.SampleCurrentMapGroundTint); + particles3.AdvanceAndCommit(0f); + audio.ConsumeSimEvents(hiddenSession, hiddenDeaths, listener); + Check(gpuSparks3.TotalEmittedCount == 0 && volumetrics3.ActiveEmitterCount == 0 && particles3.ActiveFlashLightCount == 0 && audio.ActiveOneShotVoiceCount == 0, + $"Expected out-of-PVS deaths to spawn 0 VFX/SFX, got sparks={gpuSparks3.TotalEmittedCount} vol={volumetrics3.ActiveEmitterCount} lights={particles3.ActiveFlashLightCount} voices={audio.ActiveOneShotVoiceCount}"); + particles3.ClearAll(); + volumetrics3.ClearAll(); + gpuSparks3.ClearAll(); + + GD.Print($"SMOKE INFO: Audio verified (haven={audio.Bank.HavenClipCount}, proc={audio.Bank.ProceduralClipCount}, dummy={audio.IsDummyAudio}, kestrelPitch={kestrelPitch:F3}, bastionPitch={bastionPitch:F3})"); + } + + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + } + + private void VerifyRigMotion( + VehicleAssetCache cache, + string vehicleId, + string jointId, + VehicleRigDriveInput input, + float minRotRad) + { + var vis = VehicleVisualInstance.Create(cache, vehicleId, VehicleVisualRole.Player); + Check(vis.Joints.TryGetValue(jointId, out var j), $"Missing joint '{jointId}' on '{vehicleId}'"); + if (j is not null) + { + Transform3D before = j.Node.Transform; + for (int s = 0; s < 20; s++) + { + VehicleRigAnimator.Update(vis, in input, Basis.Identity); + } + Transform3D after = j.Node.Transform; + float deltaRad = before.Basis.GetRotationQuaternion().AngleTo(after.Basis.GetRotationQuaternion()); + GD.Print($"SMOKE INFO: Rig {vehicleId}.{jointId} delta={deltaRad:F4}rad"); + Check(deltaRad > minRotRad && !HasNaN(after), + $"Expected {vehicleId}.{jointId} rotation delta > {minRotRad:F4}rad with zero NaNs, got {deltaRad:F5}"); + } + vis.Root.QueueFree(); + } + + private static int CountMeshInstances(Node cur) + { + int count = cur is MeshInstance3D ? 1 : 0; + for (int i = 0; i < cur.GetChildCount(); i++) + { + count += CountMeshInstances(cur.GetChild(i)); + } + return count; + } + + private static Vector3 TransformPointToAncestor(Node3D node, Node3D ancestor, Vector3 localPt) + { + Transform3D xf = Transform3D.Identity; + for (Node? cur = node; cur is Node3D n3d && cur != ancestor; cur = cur.GetParent()) + { + xf = n3d.Transform * xf; + } + return xf * localPt; + } + + private static Vector3? ComputeSubtreeVertexCentroidInAncestor(Node3D subRoot, Node3D ancestor, string partName) + { + Vector3 sum = Vector3.Zero; + int count = 0; + AccumulatePartCentroidRecursive(subRoot, ancestor, partName, ref sum, ref count); + return count > 0 ? sum / count : null; + } + + private static void AccumulatePartCentroidRecursive( + Node cur, + Node3D ancestor, + string partName, + ref Vector3 sum, + ref int count) + { + if (cur is MeshInstance3D mi && mi.Mesh is { } mesh && + mi.Name.ToString().Equals(partName, StringComparison.OrdinalIgnoreCase)) + { + Transform3D toAnc = Transform3D.Identity; + for (Node? p = mi; p is Node3D n3d && p != ancestor; p = p.GetParent()) + { + toAnc = n3d.Transform * toAnc; + } + int surfCount = mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arrays = mesh.SurfaceGetArrays(s); + if (arrays.Count <= (int)Mesh.ArrayType.Vertex || + arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + for (int v = 0; v < verts.Length; v++) + { + sum += toAnc * verts[v]; + count++; + } + } + } + + for (int i = 0; i < cur.GetChildCount(); i++) + { + AccumulatePartCentroidRecursive(cur.GetChild(i), ancestor, partName, ref sum, ref count); + } + } + + private static float ComputeSubtreeMinWorldY(Node3D root, float baseWorldY, bool relativeToModelRoot = false) + { + float minY = float.PositiveInfinity; + if (relativeToModelRoot) + { + Transform3D id = Transform3D.Identity; + for (int i = 0; i < root.GetChildCount(); i++) + { + AccumulateMinYRecursive(root.GetChild(i), id, ref minY); + } + } + else + { + AccumulateMinYRecursive(root, new Transform3D(Basis.Identity, new Vector3(0f, baseWorldY, 0f)), ref minY); + } + return minY; + } + + private static void AccumulateMinYRecursive(Node cur, Transform3D parentXf, ref float minY) + { + Transform3D xf = cur is Node3D n3d ? parentXf * n3d.Transform : parentXf; + if (cur is MeshInstance3D mi && mi.Mesh is { } mesh) + { + int surfCount = mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arrays = mesh.SurfaceGetArrays(s); + if (arrays.Count <= (int)Mesh.ArrayType.Vertex || + arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + for (int v = 0; v < verts.Length; v++) + { + float wy = (xf * verts[v]).Y; + if (wy < minY) + { + minY = wy; + } + } + } + } + for (int i = 0; i < cur.GetChildCount(); i++) + { + AccumulateMinYRecursive(cur.GetChild(i), xf, ref minY); + } + } + + private static bool HasNaN(Transform3D t) + { + return !t.Origin.IsFinite() + || !t.Basis.X.IsFinite() + || !t.Basis.Y.IsFinite() + || !t.Basis.Z.IsFinite(); + } + + private async Task VerifyMaxLoadPaladinGarageAsync() + { + var grid = _main.Session.LocalContender.Grid; + grid.SwapChassis(Catalog.Paladin); + Check(grid.TryMount(Catalog.TouringPlasma, "hp.weapon.sh_l"), "Expected TouringPlasma on Paladin hp.weapon.sh_l"); + Check(grid.TryMount(Catalog.WeldedPlate, "hp.armor.torso"), "Expected WeldedPlate on Paladin hp.armor.torso"); + Check(grid.TryMount(Catalog.TouringPlasma, "hp.weapon.sh_r"), "Expected TouringPlasma on Paladin hp.weapon.sh_r"); + Check(grid.TryMount(Catalog.GildedLance, "hp.weapon.arm_l"), "Expected GildedLance on Paladin hp.weapon.arm_l"); + Check(grid.TryMount(Catalog.NobleCore, "hp.engine.chest"), "Expected NobleCore on Paladin hp.engine.chest"); + Check(grid.TryMount(Catalog.GildedLance, "hp.weapon.arm_r"), "Expected GildedLance on Paladin hp.weapon.arm_r"); + Check(grid.TryMount(Catalog.GoldRadiator, "hp.radiator.back_l"), "Expected GoldRadiator on Paladin hp.radiator.back_l"); + Check(grid.TryMount(Catalog.WeldedPlate, "hp.armor.legs"), "Expected WeldedPlate on Paladin hp.armor.legs"); + Check(grid.TryMount(Catalog.GoldRadiator, "hp.radiator.back_r"), "Expected GoldRadiator on Paladin hp.radiator.back_r"); + + grid.Cargo.Clear(); + var cargoSpecs = new[] + { + Catalog.TouringPlasma, Catalog.GoldRadiator, Catalog.GildedLance, + Catalog.NobleCore, Catalog.Recoilless, Catalog.Autocannon, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate + }; + for (int i = 0; i < cargoSpecs.Length; i++) + { + Check(grid.TryAddCargo(cargoSpecs[i]), $"Expected cargo slot #{i} ({cargoSpecs[i].Name}) to fit on Paladin"); + } + + if (!_main.Hud.GarageExpanded) + { + _main.Hud.ToggleGarage(); + } + _main.Hud.Sync(_main.Session); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + Vector2 vpSize = GetViewport().GetVisibleRect().Size; + Rect2 blRect = _main.Hud.BottomLeftPanelRect; + Rect2 chyronRect = _main.Hud.ChyronPanelRect; + float chyronGap = chyronRect.Position.X - blRect.End.X; + GD.Print($"SMOKE INFO: Max-load Paladin Garage rect={blRect}, chyron gap={chyronGap:F1}px at {vpSize}"); + + Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Max-load Paladin Garage panels overlapped or clipped at {vpSize}"); + Check(blRect.End.X <= 610f, $"Expected max-load Paladin Garage End.X <= 610px, got {blRect.End.X:F1}"); + Check(!blRect.HasPoint(vpSize * 0.5f), $"Expected max-load Paladin Garage not to cover viewport center {vpSize * 0.5f}, rect={blRect}"); + Check(chyronGap > 80f, $"Expected > 80px breathing room between Garage and Chyron, got {chyronGap:F1}px"); + + _main.Hud.ToggleGarage(); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + } + + private async Task VerifySionMapAsync() + { + _main.Reset(42, ArenaMapKind.Sion, skipInitialDrop: true); + Check(_main.Failure is null, $"Sion Reset failed: {_main.Failure}"); + if (_main.Failure is not null) + { + return; + } + + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var sionState = _main.Session.ViewState; + Check(_main.MapKind == ArenaMapKind.Sion && sionState.MapKind == ArenaMapKind.Sion, "Expected Sion map kind after Reset"); + Check(_main.Terrain.Visible && _main.SionMap.Visible, "Expected unified TerrainRenderer and SionMapRenderer buildings visible on Sion"); + Check(_main.Terrain.BakedTileCount == 256, $"Expected 256 unified Sion terrain tiles (16x16), got {_main.Terrain.BakedTileCount}"); + Check(_main.Terrain.ActiveGpuScarSlots == 0, $"Expected 0 active GPU scar slots on clean Sion start, got {_main.Terrain.ActiveGpuScarSlots}"); + Check(_main.SionMap.IsBuilt, "Expected SionMapRenderer.IsBuilt == true"); + Check(_main.SionMap.BuildingTileCount == 36, $"Expected 36 Sion building tiles, got {_main.SionMap.BuildingTileCount}"); + Check(_main.SionMap.ActiveLod1TileCount > 0, $"Expected > 0 LOD1 tiles near Sion spawn, got {_main.SionMap.ActiveLod1TileCount}"); + Check(_main.SionMap.ActiveLod2TileCount > 0, $"Expected > 0 LOD2 tiles in Sion valley, got {_main.SionMap.ActiveLod2TileCount}"); + + var cam = _main.GetViewport().GetCamera3D(); + Check(cam is not null && cam.Far >= 3600f, $"Expected Camera3D.Far >= 3600m on Sion, got {cam?.Far ?? 0f}"); + + var sionMap = sionState.SionMap!; + foreach (var c in sionState.Contenders) + { + Check(!sionMap.IsInsideAnyBuildingXz(c.X, c.Z, 0f), $"Contender {c.Id} spawned inside building at ({c.X:F1}, {c.Z:F1})"); + } + foreach (var d in sionState.GroundDrops) + { + Check(!sionMap.IsInsideAnyBuildingXz(d.X, d.Z, 0f), $"GroundDrop {d.Id} spawned inside building at ({d.X:F1}, {d.Z:F1})"); + } + + Vector2 vpSize = GetViewport().GetVisibleRect().Size; + Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Sion HUD panels overlapped or clipped at {vpSize}"); + + var player = sionState.Contenders[0]; + float startX = player.X; + float startZ = player.Z; + _main.SetScriptedInput(new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: startX + MathF.Sin(player.Yaw) * 50f, + AimWorldZ: startZ + MathF.Cos(player.Yaw) * 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + + for (int i = 0; i < 30; i++) + { + await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame); + Check(float.IsFinite(player.X) && float.IsFinite(player.Y) && float.IsFinite(player.Z), + $"Sion player pose non-finite at frame {i}"); + float gh = sionState.Terrain.SampleHeight(player.X, player.Z); + Check(player.Y - player.Grid.Spec.HalfHeight >= gh - 0.8f, + $"Sion player fell below terrain at frame {i}: bottom={player.Y - player.Grid.Spec.HalfHeight:F2}m < ground={gh:F2}m"); + } + _main.SetScriptedInput(null); + + float disp = MathF.Sqrt((player.X - startX) * (player.X - startX) + (player.Z - startZ) * (player.Z - startZ)); + Check(disp > 1.5f, $"Expected player displacement > 1.5m on Sion after 30 frames, got {disp:F2}m"); + + Color inBoundsTint = _main.Terrain.SampleGroundTint(player.X, player.Z); + Color outBoundsTint = _main.Terrain.SampleGroundTint(9999f, 9999f); + Check(float.IsFinite(inBoundsTint.R) && float.IsFinite(inBoundsTint.G) && float.IsFinite(inBoundsTint.B) && inBoundsTint.R > 0.1f, + $"Expected valid Sion SampleGroundTint at player pos, got {inBoundsTint}"); + Check(MathF.Abs(outBoundsTint.R - 0.56f) < 0.01f && MathF.Abs(outBoundsTint.G - 0.53f) < 0.01f, + $"Expected neutral alpine fallback tint outside Sion bounds, got {outBoundsTint}"); + + // Verify live crater brush on Sion allocates sparse GPU scar slot & depresses GPU height + float sionCpuPre = sionState.Terrain.SampleHeight(player.X, player.Z); + sionState.Terrain.StampCrater(player.X, player.Z, radius: 5.0f, depth: 1.5f); + _main.Terrain.Sync(sionState.Terrain, sionState.SionMap); + Check(_main.Terrain.ActiveGpuScarSlots >= 1, $"Expected >= 1 active GPU scar slot on Sion after crater, got {_main.Terrain.ActiveGpuScarSlots}"); + if (DisplayServer.GetName() != "headless") + { + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + Check(_main.Terrain.TrySampleBakedHeight(player.X, player.Z, out float sionGpuPost), + "Expected TrySampleBakedHeight to succeed on Sion crater tile"); + float sionCpuPost = sionState.Terrain.SampleHeight(player.X, player.Z); + Check(MathF.Abs(sionGpuPost - sionCpuPost) <= 0.25f, + $"Expected Sion GPU crater height ({sionGpuPost:F3}m) to match CPU ({sionCpuPost:F3}m) within 0.25m"); + Check(sionGpuPost < sionCpuPre - 0.8f, + $"Expected Sion GPU crater height ({sionGpuPost:F3}m) to depress below pre-crater ({sionCpuPre:F3}m)"); + } + + GD.Print($"SMOKE INFO: Sion verified (terrainTiles={_main.Terrain.BakedTileCount}, gpuScarSlots={_main.Terrain.ActiveGpuScarSlots}, bldgTiles={_main.SionMap.BuildingTileCount}, lod1={_main.SionMap.ActiveLod1TileCount}, lod2={_main.SionMap.ActiveLod2TileCount}, disp={disp:F2}m, tint=({inBoundsTint.R:F2},{inBoundsTint.G:F2},{inBoundsTint.B:F2}))"); + } + + private async Task VerifyOrbitalDropSequenceAsync() + { + var podTpl = _main.Arena.AssetCache.GetOrLoadDropPod(); + Check(podTpl.CoreMesh.GetSurfaceCount() == 1, $"Expected single-surface DropPod CoreMesh, got {podTpl.CoreMesh.GetSurfaceCount()}"); + Check(podTpl.PetalMesh.GetSurfaceCount() == 1, $"Expected single-surface DropPod PetalMesh, got {podTpl.PetalMesh.GetSurfaceCount()}"); + Check(podTpl.PetalLocalTransforms.Length == 4, $"Expected 4 DropPod petal transforms, got {podTpl.PetalLocalTransforms.Length}"); + Check(podTpl.Size.Y >= 4.0f && podTpl.Size.Y <= 5.2f, $"Unexpected DropPod height {podTpl.Size.Y:F2}m"); + + // Verify COLOR_0 weathering exists on both CoreMesh and PetalMesh + var coreArr = podTpl.CoreMesh.SurfaceGetArrays(0); + var petalArr = podTpl.PetalMesh.SurfaceGetArrays(0); + Check(coreArr.Count > (int)Mesh.ArrayType.Color && coreArr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray, + "DropPod CoreMesh missing COLOR_0 weathering array"); + Check(petalArr.Count > (int)Mesh.ArrayType.Color && petalArr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray, + "DropPod PetalMesh missing COLOR_0 weathering array"); + + int bucketsBefore = _main.Arena.PartPool.BucketCount; + _main.Reset(42, ArenaMapKind.Sion, skipInitialDrop: false); + Check(_main.Failure is null, $"Sion Orbital Reset failed: {_main.Failure}"); + if (_main.Failure is not null) + { + return; + } + + _main.SetPhysicsProcess(false); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var session = _main.Session; + var player = session.LocalContender; + Check(player.Lifecycle == ContenderLifecycle.Deploying && player.IsInDropPod, + $"Expected player to start Deploying in DropPod, got {player.Lifecycle}"); + Check(!player.IsGroundedActive, "Expected player IsGroundedActive == false while inside DropPod"); + Check(session.ActivePods.Count >= 50, $"Expected >= 50 Wave 0 active pods (40 gear + 12 contenders), got {session.ActivePods.Count}"); + var pVisDeploying = _main.Arena.GetContenderVisual(player.Id); + Check(pVisDeploying is null || !pVisDeploying.Root.Visible, "Expected ground vehicle visual hidden while inside DropPod"); + + _main.Arena.Sync(session, 0.1f, 1f / 60f, 1f); + int bucketsDuringDrop = _main.Arena.PartPool.BucketCount; + Check(bucketsDuringDrop <= bucketsBefore + 2, + $"Expected DropPod to add <= 2 MultiMeshPartPool buckets (Core + Petal), delta={bucketsDuringDrop - bucketsBefore}"); + + bool sawRetroBurn = false; + bool sawGearEarlyTouchdown = false; + bool sawWideDropFov = false; + int touchdownTick = -1; + int debrisAtTouchdown = 0; + + Check(session.ViewState.SquadSize == 3, $"Expected Solo Sion default SquadSize == 3, got {session.ViewState.SquadSize}"); + + _main.SetScriptedInput(new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: player.X, + AimWorldZ: player.Z + 120f, + Fire: false, + InteractPickup: false, + Brake: false)); + + for (int tick = 0; tick < 2000; tick++) + { + var tickInp = _main.Session.LocalContender.IsInDropPod + ? new PlayerInput(1f, 0f, player.X, player.Z + 120f, false, false, false) + : new PlayerInput(1f, 0f, player.X, player.Z + 60f, false, false, false); + + session.SubmitLocalInput(in tickInp, isPhysicsTick: true); + _main.Arena.Sync(session, (tick + 1) / 60f, 1f / 60f, 1f); + + var evs = new List(32); + session.DrainSimEvents(evs); + _main.Arena.ConsumeEvents(session, evs, Array.Empty(), 1f / 60f, _main.SampleCurrentMapGroundTint); + _main.CameraJuice.ConsumeEvents(evs, session.LocalContenderId, new System.Numerics.Vector3(player.X, player.Y, player.Z), session); + + OrbitalPodPhase podPhase = OrbitalPodPhase.Freefall; + float dropHorizSpeed = player.Speed; + if (player.IsInDropPod) + { + foreach (var pod in session.ActivePods) + { + if (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId == player.Id) + { + podPhase = pod.Phase; + dropHorizSpeed = MathF.Sqrt(pod.VelX * pod.VelX + pod.VelZ * pod.VelZ); + if (pod.Phase == OrbitalPodPhase.RetroBurn) + { + sawRetroBurn = true; + } + break; + } + } + } + _main.CameraJuice.Update(1f / 60f, dropHorizSpeed, player.Grid.Spec.IsVtol, player.IsInDropPod, podPhase); + if (player.IsInDropPod && (CameraJuiceState.BaseFovDeg + _main.CameraJuice.FovOffsetDeg) >= 80f) + { + sawWideDropFov = true; + } + + _main.Audio.UpdateFrame(session, evs, Array.Empty(), _main.Camera.GlobalPosition, 1f / 60f, 1f); + _main.Hud.Sync(session); + + if (!sawGearEarlyTouchdown && session.ViewState.GroundDrops.Count >= 35 && player.IsInDropPod) + { + sawGearEarlyTouchdown = true; + } + + if (!player.IsInDropPod && touchdownTick < 0 && player.IsGroundedActive) + { + touchdownTick = tick; + debrisAtTouchdown = _main.Arena.Debris.ActiveCount; + break; + } + } + + Check(sawGearEarlyTouchdown, $"Expected >= 35 Wave 0 gear drops on ground while player still in pod (drops={session.ViewState.GroundDrops.Count}, inPod={player.IsInDropPod})"); + Check(sawRetroBurn, "Expected local player pod to enter RetroBurn phase"); + Check(sawWideDropFov, $"Expected wide drop-camera FOV >= 80 deg during Freefall, peak offset={_main.CameraJuice.FovOffsetDeg:F2}"); + Check(touchdownTick > 1000 && touchdownTick < 2000, $"Expected Sion 1620m player pod touchdown in (1000, 2000) ticks, got {touchdownTick}"); + Check(debrisAtTouchdown >= 4, $"Expected >= 4 blown-off petals in DebrisSystem on touchdown, got {debrisAtTouchdown}"); + Check(VehicleVisualInstance.PerfMaterialDupCount == 0, $"Expected 0 material duplicates during orbital drop, got {VehicleVisualInstance.PerfMaterialDupCount}"); + + var pVisLanded = _main.Arena.GetContenderVisual(player.Id); + Check(pVisLanded is not null && pVisLanded.Root.Visible, "Expected player ground chassis visual visible immediately on touchdown"); + + // Verify post-touchdown ground driving works cleanly + float landX = player.X; + float landZ = player.Z; + for (int t = 0; t < 30; t++) + { + var driveInp = new PlayerInput(1f, 0f, player.X, player.Z + 60f, false, false, false); + session.SubmitLocalInput(in driveInp, isPhysicsTick: true); + } + float postDisp = MathF.Sqrt((player.X - landX) * (player.X - landX) + (player.Z - landZ) * (player.Z - landZ)); + Check(postDisp > 1.5f, $"Expected post-touchdown driving displacement > 1.5m over 30 ticks, got {postDisp:F2}m"); + + _main.SetScriptedInput(null); + _main.SetPhysicsProcess(true); + + GD.Print($"SMOKE INFO: Cut 6b OrbitalDrop verified (touchdownTick={touchdownTick}, debris={debrisAtTouchdown}, postDisp={postDisp:F2}m, bucketsDelta={bucketsDuringDrop - bucketsBefore}, matDups={VehicleVisualInstance.PerfMaterialDupCount})"); + } + + private async Task VerifyCut7bModularOrdnanceAsync() + { + var cache = _main.Arena.AssetCache; + var partPool = _main.Arena.PartPool; + + // 1. All 16 modular weapon sub-parts loaded with single-surface COLOR_0 meshes and required sockets + Check(cache.WeaponParts.Count == 16, $"Expected 16 cached modular weapon parts, got {cache.WeaponParts.Count}"); + foreach (string pid in VehicleAssetCache.ExpectedWeaponPartIds) + { + var wp = cache.GetOrLoadWeaponPart(pid); + Check(wp.SingleSurfaceMesh.GetSurfaceCount() == 1, + $"Expected 1 surface on modular part '{pid}', got {wp.SingleSurfaceMesh.GetSurfaceCount()}"); + var arr = wp.SingleSurfaceMesh.SurfaceGetArrays(0); + Check(arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray, + $"Modular part '{pid}' missing COLOR_0 attribute"); + if (wp.Slot == "receiver") + { + Check(wp.SocketsLocal.ContainsKey("barrel") && wp.SocketsLocal.ContainsKey("feed"), + $"Receiver '{pid}' missing barrel/feed sockets"); + } + else if (wp.Slot == "barrel") + { + Check(wp.SocketsLocal.ContainsKey("muzzle"), $"Barrel '{pid}' missing muzzle socket"); + } + else if (wp.Slot == "muzzle") + { + Check(wp.SocketsLocal.ContainsKey("muzzle_tip"), $"Muzzle '{pid}' missing muzzle_tip socket"); + } + } + + // 2. Mount 50 distinct procedural weapons across all 5 manufacturers & 20 archetypes -> <= 16 new PartPool buckets, 0 matDups + VehicleVisualInstance.PerfMaterialDupCount = 0; + var testVis = VehicleVisualInstance.Create(cache, "anvil", VehicleVisualRole.Player); + AddChild(testVis.Root); + var testGrid = Catalog.CreateWithDefaultLoadout(Catalog.Anvil); + string? weaponHpId = null; + for (int i = 0; i < testGrid.Spec.Hardpoints.Length; i++) + { + if (testGrid.Spec.Hardpoints[i].Kind == HardpointKind.Weapon && + testGrid.Spec.Hardpoints[i].Height >= 2) + { + weaponHpId = testGrid.Spec.Hardpoints[i].Id; + break; + } + } + Check(weaponHpId is not null, "Expected Anvil to have a 1x2 weapon hardpoint for modular assembly test"); + + // Pre-warm baseline Anvil chassis/cell buckets in PartPool so bucketDelta measures ONLY modular weapon parts + if (weaponHpId is not null) + { + testGrid.Mounted.RemoveAll(m => m.HardpointId == weaponHpId); + } + testVis.SyncMountedGear(testGrid); + partPool.BeginFrame(null); + testVis.SubmitToPool(partPool); + partPool.EndFrame(); + int bucketsBefore = partPool.BucketCount; + + partPool.BeginFrame(null); + if (weaponHpId is not null) + { + for (int w = 0; w < 50; w++) + { + byte mfg = (byte)(w % 5); + byte arch = (byte)(mfg * 4 + (w % 4)); + var pSpec = ProceduralWeaponGenerator.Generate(new ProceduralWeaponKey((ulong)(0xA100 + w), mfg, arch, (byte)(w & 3), 0)); + testGrid.Mounted.RemoveAll(m => m.HardpointId == weaponHpId); + Check(testGrid.TryMount(pSpec.Module, weaponHpId), $"Failed to mount procedural weapon '{pSpec.DisplayName}' on '{weaponHpId}'"); + testVis.SyncMountedGear(testGrid); + testVis.SubmitToPool(partPool); + + if (w < 5) + { + bool hasAim = testVis.TryGetMountedWeaponCentroidsInModel(weaponHpId, "muzzle", "receiver", out Vector3 frontC, out Vector3 rearC); + Check(hasAim && (frontC.Z > rearC.Z + 0.35f), + $"Expected modular weapon '{pSpec.DisplayName}' muzzle ({frontC}) forward of receiver ({rearC})"); + } + } + } + partPool.EndFrame(); + + int bucketDelta = partPool.BucketCount - bucketsBefore; + Check(bucketDelta <= 16, $"Expected 50 procedural weapons to add <= 16 PartPool buckets, added {bucketDelta}"); + Check(VehicleVisualInstance.PerfMaterialDupCount == 0, $"Expected 0 material duplications, got {VehicleVisualInstance.PerfMaterialDupCount}"); + Check(CountMeshInstances(testVis.Root) == 0, $"Expected 0 MeshInstance3D children on modular vehicle rig, got {CountMeshInstances(testVis.Root)}"); + + // Verify shearing a modular weapon hardpoint spawns all 4 sub-parts into DebrisSystem + if (weaponHpId is not null) + { + var testDebris = new DebrisSystem { Name = "SmokeModularShearDebris" }; + AddChild(testDebris); + var hp = testGrid.FindHardpoint(weaponHpId)!; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + testGrid.Armor[hp.X + dx, hp.Y + dy] = 0f; + } + } + testVis.SyncDamageAndHeat(testGrid, testDebris, Vector3.Zero); + Check(testDebris.ActiveCount >= 4, $"Expected >= 4 sheared modular sub-parts in DebrisSystem, got {testDebris.ActiveCount}"); + testDebris.QueueFree(); + } + testVis.Root.QueueFree(); + + // 3. Procedural weapon GroundDrops render with modular parts & clean up on pickup + _main.Reset(77, ArenaMapKind.Desert, skipInitialDrop: true); + _main.SetPhysicsProcess(false); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var state = _main.Session.ViewState; + var player = _main.Session.LocalContender; + int dropsBefore = state.GroundDrops.Count; + _main.Arena.Sync(_main.Session, 1.0f, 1f / 60f, 1f); + int trackedBefore = _main.Arena.ActiveDropVisualCount; + + var procDrops = new List(5); + for (int m = 0; m < 5; m++) + { + var pSpec = ProceduralWeaponGenerator.RollForManufacturer((ManufacturerId)m, tier: 2, seed: (ulong)(0x7700 + m)); + var gd = new GroundDrop(95000 + m, player.X + 4f + m * 6f, player.Z + 8f, null, pSpec.Module); + state.GroundDrops.Add(gd); + procDrops.Add(gd); + } + _main.Arena.Sync(_main.Session, 1.1f, 1f / 60f, 1f); + Check(_main.Arena.ActiveDropVisualCount == trackedBefore + 5, + $"Expected {trackedBefore + 5} tracked drops after adding 5 mfg drops, got {_main.Arena.ActiveDropVisualCount}"); + + // 4. HUD 6 chrome panels, 2-line Borderlands tooltips (Garage + Hover + Pickup Prompt), zero overlap at 1280x720 + var sabotDream = ProceduralWeaponGenerator.CreateDreamSabotSled(); + var droneDream = ProceduralWeaponGenerator.CreateDreamLoiteringDrone(); + var mirvDream = ProceduralWeaponGenerator.CreateDreamMirvMineBlanket(); + + var pGrid = player.Grid; + string? pWeaponHp = null; + HardpointSpec? pWeaponHpSpec = null; + for (int i = 0; i < pGrid.Spec.Hardpoints.Length; i++) + { + if (pGrid.Spec.Hardpoints[i].Kind == HardpointKind.Weapon && pGrid.Spec.Hardpoints[i].Height >= 2) + { + pWeaponHp = pGrid.Spec.Hardpoints[i].Id; + pWeaponHpSpec = pGrid.Spec.Hardpoints[i]; + break; + } + } + if (pWeaponHp is not null && pWeaponHpSpec is not null) + { + pGrid.Mounted.RemoveAll(m => m.HardpointId == pWeaponHp); + Check(pGrid.TryMount(sabotDream.Module, pWeaponHp), "Expected Dream Sabot Sled to mount on player"); + if (!_main.Hud.GarageExpanded) _main.Hud.ToggleGarage(); + _main.Hud.Sync(_main.Session); + _main.Hud.SimulateCellHover(new Vector2I(pWeaponHpSpec.X, pWeaponHpSpec.Y), pWeaponHpSpec); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + Check(_main.Hud.HbCanvas.LastQuadCount > 50, + $"Expected Hud.HbCanvas.LastQuadCount > 50 in Garage mode, got {_main.Hud.HbCanvas.LastQuadCount}"); + Check(_main.Hud.HoverLabelText.Contains(sabotDream.ManufacturerLabel) && _main.Hud.HoverLabelText.Contains('\n'), + $"Expected 2-line Borderlands hover tooltip with manufacturer badge, got: {_main.Hud.HoverLabelText}"); + Check(_main.Hud.GarageDetailsText.Contains(sabotDream.SummaryLine1) && _main.Hud.GarageDetailsText.Contains(sabotDream.SummaryLine2), + $"Expected Garage details to contain SummaryLine1 & SummaryLine2, got: {_main.Hud.GarageDetailsText}"); + + // Check nearby pickup prompt 2-line display + var nearbyDrop = new GroundDrop(95999, player.X + 1.0f, player.Z + 1.0f, null, droneDream.Module); + state.GroundDrops.Add(nearbyDrop); + _main.Hud.Sync(_main.Session); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + Check(_main.Hud.PromptLabelText.Contains(droneDream.ManufacturerLabel) && _main.Hud.PromptLabelText.Contains('\n'), + $"Expected 2-line pickup prompt with manufacturer & summary, got: {_main.Hud.PromptLabelText}"); + + Vector2 vpSize = GetViewport().GetVisibleRect().Size; + Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"HUD overlapped or clipped with procedural tooltip at {vpSize}"); + + nearbyDrop.PickedUp = true; + state.GroundDrops.Remove(nearbyDrop); + if (_main.Hud.GarageExpanded) _main.Hud.ToggleGarage(); + } + + for (int i = 0; i < procDrops.Count; i++) procDrops[i].PickedUp = true; + _main.Arena.Sync(_main.Session, 1.2f, 1f / 60f, 1f); + state.GroundDrops.RemoveRange(dropsBefore, procDrops.Count); + + // 5. ClientOrdnanceMirror + Haven MWO Audio Hooks across Sabot, Loitering Drone, and MIRV Mines + var localSession = (_main.Session as LocalArenaSession)!; + var sim = localSession.Inner; + for (int cIdx = 1; cIdx < sim.State.Contenders.Count; cIdx++) + { + sim.SetContenderPose(cIdx, 480f + cIdx * 12f, 480f); + } + int enemyIdx = sim.State.SquadSize > 1 ? sim.State.SquadSize : 1; + sim.SetContenderPose(0, 0f, 0f, 0f); + sim.SetContenderPose(enemyIdx, 0f, 125f, MathF.PI); // target Anvil/rival 125m ahead (non-ally) + + int audioShotsBefore = _main.Audio.Total3DPlaysRequested; + bool sawMirrorRocket = false; + bool sawSabotTransition = false; + bool sawMirrorDrone = false; + bool sawMirrorMines = false; + + // 5a: Sabot Rocket Sled + if (pWeaponHp is not null) + { + pGrid.Mounted.RemoveAll(m => m.HardpointId == pWeaponHp); + pGrid.TryMount(sabotDream.Module, pWeaponHp); + for (int t = 0; t < 35; t++) + { + var inp = new PlayerInput(0f, 0f, 0f, 125f, Fire: t == 0, InteractPickup: false, Brake: true); + _main.Session.SubmitLocalInput(in inp, isPhysicsTick: true); + var evs = new List(16); + _main.Session.DrainSimEvents(evs); + for (int e = 0; e < evs.Count; e++) + { + if (evs[e] is OrdnanceNodeEvent oe && (OrdnanceEventKind)oe.Kind == OrdnanceEventKind.StageTransition) + { + sawSabotTransition = true; + } + } + _main.Arena.Sync(_main.Session, 2.0f + t / 60f, 1f / 60f, 1f); + _main.Arena.ConsumeEvents(_main.Session, evs, Array.Empty(), 1f / 60f, _main.SampleCurrentMapGroundTint); + _main.Audio.UpdateFrame(_main.Session, evs, Array.Empty(), _main.Camera.GlobalPosition, 1f / 60f, 1f); + if (_main.Arena.OrdnanceMirror.ActiveCount > 0) sawMirrorRocket = true; + } + + // 5b: Loitering Laser Drone + pGrid.Mounted.RemoveAll(m => m.HardpointId == pWeaponHp); + pGrid.TryMount(droneDream.Module, pWeaponHp); + for (int t = 0; t < 95; t++) + { + var inp = new PlayerInput(0f, 0f, 0f, 125f, Fire: t == 0, InteractPickup: false, Brake: true); + _main.Session.SubmitLocalInput(in inp, isPhysicsTick: true); + var evs = new List(16); + _main.Session.DrainSimEvents(evs); + _main.Arena.Sync(_main.Session, 3.0f + t / 60f, 1f / 60f, 1f); + _main.Arena.ConsumeEvents(_main.Session, evs, Array.Empty(), 1f / 60f, _main.SampleCurrentMapGroundTint); + _main.Audio.UpdateFrame(_main.Session, evs, Array.Empty(), _main.Camera.GlobalPosition, 1f / 60f, 1f); + if (t > 70 && _main.Arena.OrdnanceMirror.ActiveCount > 0) sawMirrorDrone = true; + } + + // 5c: MIRV Minefield Blanket + pGrid.Mounted.RemoveAll(m => m.HardpointId == pWeaponHp); + pGrid.TryMount(mirvDream.Module, pWeaponHp); + for (int t = 0; t < 160; t++) + { + var inp = new PlayerInput(0f, 0f, 0f, 85f, Fire: t == 0, InteractPickup: false, Brake: true); + _main.Session.SubmitLocalInput(in inp, isPhysicsTick: true); + var evs = new List(32); + _main.Session.DrainSimEvents(evs); + _main.Arena.Sync(_main.Session, 5.0f + t / 60f, 1f / 60f, 1f); + _main.Arena.ConsumeEvents(_main.Session, evs, Array.Empty(), 1f / 60f, _main.SampleCurrentMapGroundTint); + _main.Audio.UpdateFrame(_main.Session, evs, Array.Empty(), _main.Camera.GlobalPosition, 1f / 60f, 1f); + if (_main.Arena.OrdnanceMirror.ActiveCount >= 6) sawMirrorMines = true; + } + } + + Check(sawMirrorRocket && sawSabotTransition, + $"Expected ClientOrdnanceMirror to track Sabot rocket & StageTransition (rocket={sawMirrorRocket}, trans={sawSabotTransition})"); + Check(sawMirrorDrone, "Expected ClientOrdnanceMirror to maintain active Loitering Laser Drone after climb"); + Check(sawMirrorMines, "Expected ClientOrdnanceMirror to mirror >= 6 MIRV mines after Split"); + Check(_main.Audio.Total3DPlaysRequested > audioShotsBefore, + $"Expected ArenaAudioSystem Haven MWO ordnance cues to trigger (before={audioShotsBefore}, after={_main.Audio.Total3DPlaysRequested})"); + + // Verify MatchResetEvent clears ClientOrdnanceMirror cleanly + _main.Arena.ConsumeEvents(_main.Session, new ISimEvent[] { new MatchResetEvent() }, Array.Empty(), 1f / 60f, _main.SampleCurrentMapGroundTint); + Check(_main.Arena.OrdnanceMirror.ActiveCount == 0, + $"Expected MatchResetEvent to clear ClientOrdnanceMirror, got {_main.Arena.OrdnanceMirror.ActiveCount}"); + + _main.SetPhysicsProcess(true); + GD.Print($"SMOKE INFO: Cut 7b verified (16 parts, bucketDelta={bucketDelta}, matDups={VehicleVisualInstance.PerfMaterialDupCount}, audioPlays={_main.Audio.Total3DPlaysRequested - audioShotsBefore})"); + } + + private void VerifyForwardPlusAtmosphere() + { + string method = RenderingServer.GetCurrentRenderingMethod(); + var cmdArgs = System.Environment.GetCommandLineArgs(); + bool requestedDummy = false; + for (int i = 0; i < cmdArgs.Length; i++) + { + if (cmdArgs[i] == "--rendering-driver=dummy" || + (cmdArgs[i] == "--rendering-driver" && i + 1 < cmdArgs.Length && cmdArgs[i + 1] == "dummy")) + { + requestedDummy = true; + break; + } + } + bool isHeadlessDummy = DisplayServer.GetName() == "headless" && requestedDummy; + Check(method == "forward_plus" || (isHeadlessDummy && method == "dummy"), + $"Expected RenderingMethod 'forward_plus' (or 'dummy' with --rendering-driver dummy), got '{method}'"); + + var sionBaked = AtmosphereLutBaker.GetOrBake(ArenaMapKind.Sion); + var desertBaked = AtmosphereLutBaker.GetOrBake(ArenaMapKind.Desert); + CheckFinitePositiveLut("Sion.Transmittance", sionBaked.TransmittanceImage, AtmosphereLutBaker.TransmittanceWidth, AtmosphereLutBaker.TransmittanceHeight); + CheckFinitePositiveLut("Sion.MultiScattering", sionBaked.MultiScatteringImage, AtmosphereLutBaker.MultiScatteringSize, AtmosphereLutBaker.MultiScatteringSize); + CheckFinitePositiveLut("Sion.SkyView", sionBaked.SkyViewImage, AtmosphereLutBaker.SkyViewWidth, AtmosphereLutBaker.SkyViewHeight); + CheckFinitePositiveLut("Desert.Transmittance", desertBaked.TransmittanceImage, AtmosphereLutBaker.TransmittanceWidth, AtmosphereLutBaker.TransmittanceHeight); + CheckFinitePositiveLut("Desert.MultiScattering", desertBaked.MultiScatteringImage, AtmosphereLutBaker.MultiScatteringSize, AtmosphereLutBaker.MultiScatteringSize); + CheckFinitePositiveLut("Desert.SkyView", desertBaked.SkyViewImage, AtmosphereLutBaker.SkyViewWidth, AtmosphereLutBaker.SkyViewHeight); + + Check(sionBaked.ZenithTransmittanceMean > desertBaked.ZenithTransmittanceMean, + $"Expected Sion zenith transmittance ({sionBaked.ZenithTransmittanceMean:F4}) > Desert ({desertBaked.ZenithTransmittanceMean:F4})"); + Check(desertBaked.HazeColor.R > desertBaked.HazeColor.G && desertBaked.HazeColor.G > desertBaked.HazeColor.B, + $"Expected warm golden Desert haze chromaticity R > G > B, got ({desertBaked.HazeColor.R:F3}, {desertBaked.HazeColor.G:F3}, {desertBaked.HazeColor.B:F3})"); + Check(sionBaked.HazeColor.B > sionBaked.HazeColor.R, + $"Expected cool alpine Sion haze chromaticity B > R, got ({sionBaked.HazeColor.R:F3}, {sionBaked.HazeColor.G:F3}, {sionBaked.HazeColor.B:F3})"); + CheckSkyViewHorizonContinuity("Sion", sionBaked.SkyViewImage); + CheckSkyViewHorizonContinuity("Desert", desertBaked.SkyViewImage); + + var atmo = _main.Atmosphere; + var env = atmo.Environment; + Check(env.TonemapMode == Godot.Environment.ToneMapper.Agx, $"Expected ToneMapper.Agx, got {env.TonemapMode}"); + Check(env.GlowEnabled && env.GlowNormalized, $"Expected GlowEnabled && GlowNormalized, got enabled={env.GlowEnabled} norm={env.GlowNormalized}"); + Check(env.GlowBlendMode == Godot.Environment.GlowBlendModeEnum.Additive, $"Expected GlowBlendModeEnum.Additive, got {env.GlowBlendMode}"); + Check(env.SsrEnabled, "Expected SsrEnabled == true"); + Check(env.SsaoEnabled, "Expected SsaoEnabled == true"); + Check(env.VolumetricFogEnabled && env.VolumetricFogTemporalReprojectionEnabled, + $"Expected VolumetricFogEnabled && TemporalReprojection, got vf={env.VolumetricFogEnabled} tr={env.VolumetricFogTemporalReprojectionEnabled}"); + Check(env.FogEnabled && env.FogAerialPerspective >= 0.20f, + $"Expected FogEnabled && FogAerialPerspective >= 0.20f, got fog={env.FogEnabled} ap={env.FogAerialPerspective:F2}"); + Check(sionBaked.Preset.DepthFogAerialPerspective > 0.7f, + $"Expected Sion DepthFogAerialPerspective > 0.7f, got {sionBaked.Preset.DepthFogAerialPerspective:F2}"); + + var sun = atmo.Sun; + Check(sun.DirectionalShadowMode == DirectionalLight3D.ShadowMode.Parallel4Splits && sun.DirectionalShadowMaxDistance >= 280f, + $"Expected Parallel4Splits & maxDist >= 280m, got {sun.DirectionalShadowMode} maxDist={sun.DirectionalShadowMaxDistance:F1}"); + + Check(GetViewport().UseTaa, "Expected GetViewport().UseTaa == true"); + + int checkedLights = 0; + foreach (Node ch in _main.Arena.Particles.GetChildren()) + { + if (ch is OmniLight3D omni) + { + checkedLights++; + Check(omni.LightVolumetricFogEnergy == 0f, + $"Expected {omni.Name}.LightVolumetricFogEnergy == 0f to prevent temporal fog ghosting, got {omni.LightVolumetricFogEnergy}"); + } + } + Check(checkedLights == ParticlePool.MaxFlashLights, $"Expected {ParticlePool.MaxFlashLights} ParticlePool OmniLight3D nodes, found {checkedLights}"); + + Check(atmo.FilmGrainLayer.Layer == 5 && atmo.FilmGrainLayer.Layer < _main.Hud.Layer, + $"Expected FilmGrainLayer.Layer == 5 < Hud.Layer ({_main.Hud.Layer}), got {atmo.FilmGrainLayer.Layer}"); + + GD.Print($"SMOKE INFO: Cut 8 Forward+ verified (method={method}, sionZenithT={sionBaked.ZenithTransmittanceMean:F4}, desertZenithT={desertBaked.ZenithTransmittanceMean:F4}, desertHaze=({desertBaked.HazeColor.R:F3},{desertBaked.HazeColor.G:F3},{desertBaked.HazeColor.B:F3}), sionHaze=({sionBaked.HazeColor.R:F3},{sionBaked.HazeColor.G:F3},{sionBaked.HazeColor.B:F3}), grainLayer={atmo.FilmGrainLayer.Layer})"); + } + + private async Task VerifyGpuSparksRenderAsync(bool isHeadless) + { + if (isHeadless) + { + return; + } + + var sparkVp = new SubViewport + { + Size = new Vector2I(128, 128), + OwnWorld3D = true, + TransparentBg = true, + RenderTargetUpdateMode = SubViewport.UpdateMode.Always + }; + var env = new Godot.Environment + { + BackgroundMode = Godot.Environment.BGMode.Color, + BackgroundColor = new Color(0f, 0f, 0f, 0f) + }; + sparkVp.AddChild(new WorldEnvironment { Environment = env }); + var cam = new Camera3D + { + Position = new Vector3(0f, 0f, 5.5f), + Current = true + }; + sparkVp.AddChild(cam); + var sparks = new GpuSparksSystem { Name = "SmokeSparkProbe" }; + sparkVp.AddChild(sparks); + AddChild(sparkVp); + cam.LookAt(Vector3.Zero, Vector3.Up); + sparks.EnsureInitialized(); + + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var idleImg = sparkVp.GetTexture().GetImage(); + int idleLit = CountNonZeroAlphaPixels(idleImg, 0.05f); + Check(idleLit == 0, $"Expected 0 rendered spark pixels with AmountRatio=0.0f before EmitParticle, got {idleLit}"); + + sparks.EmitSparkBurst(Vector3.Zero, Vector3.Up, 128, new Color(4.5f, 2.5f, 0.75f, 1.0f), 8.0f, 0.05f); + sparks.EmitMuzzleStarburst(Vector3.Zero, new Color(5.0f, 3.0f, 1.0f, 1.0f), 0.75f, 0.14f); + + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var activeImg = sparkVp.GetTexture().GetImage(); + int brightPixels = 0; + int w = activeImg.GetWidth(); + int h = activeImg.GetHeight(); + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + Color c = activeImg.GetPixel(x, y); + float lum = c.R * 0.2126f + c.G * 0.7152f + c.B * 0.0722f; + if (c.A > 0.05f && lum > 0.35f) + { + brightPixels++; + } + } + } + GD.Print($"SMOKE INFO: GpuSparksSystem Vulkan render probe idleLit={idleLit} brightPixels={brightPixels}"); + Check(brightPixels > 25, $"Expected > 25 bright HDR spark pixels after EmitSparkBurst (start() ACTIVE=true), got {brightPixels}"); + + sparkVp.QueueFree(); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + } + + private void CheckFinitePositiveLut(string label, Image img, int expectedW, int expectedH) + { + Check(img.GetFormat() == Image.Format.Rgbah, $"Expected {label} format Rgbah, got {img.GetFormat()}"); + Check(img.GetWidth() == expectedW && img.GetHeight() == expectedH, + $"Expected {label} size {expectedW}x{expectedH}, got {img.GetWidth()}x{img.GetHeight()}"); + bool allValid = true; + float maxSum = 0f; + int w = img.GetWidth(); + int h = img.GetHeight(); + for (int y = 0; y < h; y += Math.Max(1, h / 8)) + { + for (int x = 0; x < w; x += Math.Max(1, w / 8)) + { + Color c = img.GetPixel(x, y); + if (!float.IsFinite(c.R) || !float.IsFinite(c.G) || !float.IsFinite(c.B) || + c.R < 0f || c.G < 0f || c.B < 0f) + { + allValid = false; + } + maxSum = MathF.Max(maxSum, c.R + c.G + c.B); + } + } + Check(allValid && maxSum > 0f, $"Expected finite positive values in {label} LUT (valid={allValid}, maxSum={maxSum:F4})"); + } + + private void CheckSkyViewHorizonContinuity(string label, Image skyView) + { + int yBelow = AtmosphereLutBaker.SkyViewHeight / 2 - 1; + int yAbove = AtmosphereLutBaker.SkyViewHeight / 2; + float worstRelJump = 0f; + for (int x = 0; x < skyView.GetWidth(); x += 8) + { + Color cBelow = skyView.GetPixel(x, yBelow); + Color cAbove = skyView.GetPixel(x, yAbove); + float lBelow = cBelow.R * 0.2126f + cBelow.G * 0.7152f + cBelow.B * 0.0722f; + float lAbove = cAbove.R * 0.2126f + cAbove.G * 0.7152f + cAbove.B * 0.0722f; + float rel = MathF.Abs(lAbove - lBelow) / MathF.Max(1e-4f, lAbove); + if (rel > worstRelJump) worstRelJump = rel; + } + Check(worstRelJump <= 0.05f, + $"Expected smooth below-horizon SkyView seam <= 5% on {label} (y={yBelow}->y={yAbove}), got {worstRelJump * 100f:F2}%"); + } + + private static int CountPremulViolations(Image img, float tolerance) + { + int count = 0; + int w = img.GetWidth(); + int h = img.GetHeight(); + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + Color c = img.GetPixel(x, y); + float maxRgb = MathF.Max(c.R, MathF.Max(c.G, c.B)); + if (maxRgb > c.A + tolerance) + { + count++; + } + } + } + return count; + } + + private static int CountNonZeroAlphaPixels(Image img, float minAlpha) + { + int count = 0; + int w = img.GetWidth(); + int h = img.GetHeight(); + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (img.GetPixel(x, y).A > minAlpha) count++; + } + } + return count; + } + + private static int CountDifferentPixels(Image a, Image b, float threshold) + { + int count = 0; + int w = Math.Min(a.GetWidth(), b.GetWidth()); + int h = Math.Min(a.GetHeight(), b.GetHeight()); + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + Color ca = a.GetPixel(x, y); + Color cb = b.GetPixel(x, y); + float diff = MathF.Abs(ca.R - cb.R) + MathF.Abs(ca.G - cb.G) + MathF.Abs(ca.B - cb.B) + MathF.Abs(ca.A - cb.A); + if (diff > threshold) count++; + } + } + return count; + } + + private void Check(bool condition, string message) + { + if (!condition) + { + _failures.Add(message); + } + } + + private void Finish() + { + if (_done) return; + _done = true; + foreach (var f in _failures) + { + GD.PrintErr("SMOKE FAIL: " + f); + } + GD.Print(_failures.Count == 0 ? "SMOKE PASS" : $"SMOKE FAILED ({_failures.Count})"); + GetTree().Quit(_failures.Count == 0 ? 0 : 1); + } + + private sealed class HiddenRemoteDeathsSession : IClientArenaSession + { + private readonly IClientArenaSession _inner; + public HiddenRemoteDeathsSession(IClientArenaSession inner) => _inner = inner; + public MatchState ViewState => _inner.ViewState; + public int LocalContenderId => _inner.LocalContenderId; + public ContenderState LocalContender => _inner.LocalContender; + public ClientMatchOutcome LocalOutcome => _inner.LocalOutcome; + public int LocalDetectedByCount => _inner.LocalDetectedByCount; + public IReadOnlyDictionary LocalContenderContacts => _inner.LocalContenderContacts; + public IReadOnlyDictionary LocalSpectatorContacts => _inner.LocalSpectatorContacts; + public NetworkStatusSnapshot ConnectionStatus => _inner.ConnectionStatus; + public IReadOnlyList ActivePods => _inner.ActivePods; + public DropWaveState DropWaveState => _inner.DropWaveState; + public IReadOnlyList PodEvents => _inner.PodEvents; + public bool IsContenderVisible(int contenderId) => contenderId == _inner.LocalContenderId; + public bool IsSpectatorVisible(int spectatorId) => false; + public void BeginRenderFrame(double dt, float physicsAlpha) => _inner.BeginRenderFrame(dt, physicsAlpha); + public void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick) => _inner.SubmitLocalInput(in input, isPhysicsTick); + public void DrainSimEvents(List dest) => _inner.DrainSimEvents(dest); + public bool RequestEquipCargo(int cargoIndex, string hardpointId) => _inner.RequestEquipCargo(cargoIndex, hardpointId); + public void RequestNewMatch(int seed, ArenaMapKind mapKind) => _inner.RequestNewMatch(seed, mapKind); + public (System.Numerics.Vector3 Pos, System.Numerics.Quaternion Rot, System.Numerics.Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) => _inner.GetInterpolatedContenderPose(contenderId, alpha); + public (System.Numerics.Vector3 Pos, System.Numerics.Quaternion Rot, System.Numerics.Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha) => _inner.GetInterpolatedSpectatorPose(spectatorId, alpha); + public bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap) => _inner.TrySampleInterpolatedWalkerPose(isContender, id, alpha, out snap); + public ClientRayHit CastWorldRayClosest(System.Numerics.Vector3 origin, System.Numerics.Vector3 translation) => _inner.CastWorldRayClosest(origin, translation); + public void Dispose() { } + } +} diff --git a/client/tests/Smoke.tscn b/client/tests/Smoke.tscn new file mode 100644 index 0000000..d05be64 --- /dev/null +++ b/client/tests/Smoke.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://tests/Smoke.cs" id="1"] + +[node name="Smoke" type="Node"] +script = ExtResource("1") diff --git a/client/tests/VisualProbe.cs b/client/tests/VisualProbe.cs new file mode 100644 index 0000000..b12c146 --- /dev/null +++ b/client/tests/VisualProbe.cs @@ -0,0 +1,522 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client.Tests; + +/// +/// Live Forward+ (Vulkan) visual verification probe for: +/// - Baked COLOR_0 vertex weathering (AO, edge curvature, per-island hash, rest height) +/// - Brokkr 6-layer MechPaint spatial shader (mech_paint.gdshader) + INSTANCE_CUSTOM scorch/heat +/// - 4x4 POM MultiMesh decal atlas + decal_pom.gdshader in 1 draw call +/// Captures a 1280x720 preview PNG to tools/decals/previews/visual_substrate_preview.png and %TEMP%. +/// +public partial class VisualProbe : Node3D +{ + private readonly List _failures = new(); + private readonly List _disposables = new(); + + public override void _Ready() => _ = RunAsync(); + + public override void _ExitTree() + { + foreach (var d in _disposables) + { + d.Dispose(); + } + _disposables.Clear(); + } + + private void Check(bool cond, string msg) + { + if (!cond) + { + _failures.Add(msg); + GD.PushError("VISUAL_PROBE FAIL: " + msg); + } + } + + private async Task RunAsync() + { + int exitCode = 0; + try + { + string repoRoot = Path.GetFullPath(Path.Combine(ProjectSettings.GlobalizePath("res://"), "..")); + string decalsDir = Path.Combine(repoRoot, "assets", "decals"); + string previewRepoPath = Path.Combine(repoRoot, "tools", "decals", "previews", "visual_substrate_preview.png"); + string previewTempPath = Path.Combine(Path.GetTempPath(), "visual_substrate_preview.png"); + + SetupEnvironment(); + + var mechShader = GD.Load("res://mech_paint.gdshader"); + var decalShader = GD.Load("res://decal_pom.gdshader"); + Check(mechShader is not null, "Failed to load res://mech_paint.gdshader"); + Check(decalShader is not null, "Failed to load res://decal_pom.gdshader"); + if (mechShader is null || decalShader is null) + { + Finish(1); + return; + } + + ImageTexture albedoTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_albedo.png")); + ImageTexture normalTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_normal.png")); + ImageTexture ormhTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_ormh.png")); + + var cache = new VehicleAssetCache(); + _disposables.Add(cache); + var paladinTpl = cache.GetOrLoadVehicle("paladin"); + var jackalTpl = cache.GetOrLoadVehicle("jackal"); + + VerifyBakedVertexColors("paladin", paladinTpl.BakedStaticMesh); + VerifyBakedVertexColors("jackal", jackalTpl.BakedStaticMesh); + + // Ground desert pad + var groundMesh = new PlaneMesh { Size = new Vector2(48f, 48f) }; + var groundMat = new StandardMaterial3D + { + AlbedoColor = new Color(0.42f, 0.34f, 0.24f), + Roughness = 0.94f, + Metallic = 0.02f + }; + AddChild(new MeshInstance3D { Name = "DesertPad", Mesh = groundMesh, MaterialOverride = groundMat }); + + // Shared MechPaint ShaderMaterial variants (zero per-hit cloning) + var paladinArmorMat = MakeMechPaintMat(mechShader, new Color(0.306f, 0.341f, 0.251f), metallic: 0.22f, roughness: 0.58f, wear: 1.05f, grime: 0.95f, mud: 1.15f); + var jackalArmorMat = MakeMechPaintMat(mechShader, new Color(0.388f, 0.345f, 0.255f), metallic: 0.20f, roughness: 0.56f, wear: 1.15f, grime: 0.95f, mud: 1.25f, mudTop: 0.95f); + var gunmetalMat = MakeMechPaintMat(mechShader, new Color(0.173f, 0.188f, 0.180f), metallic: 0.78f, roughness: 0.42f, wear: 0.80f, grime: 1.10f, mud: 1.05f); + var copperMat = MakeMechPaintMat(mechShader, new Color(0.612f, 0.353f, 0.204f), metallic: 0.86f, roughness: 0.34f, wear: 0.65f, grime: 0.90f, mud: 0.80f); + var orangeMat = MakeMechPaintMat(mechShader, new Color(0.851f, 0.424f, 0.153f), metallic: 0.18f, roughness: 0.44f, wear: 1.10f, grime: 0.85f, mud: 0.90f); + var markMat = MakeMechPaintMat(mechShader, new Color(0.760f, 0.730f, 0.640f), metallic: 0.10f, roughness: 0.62f, wear: 0.95f, grime: 0.80f, mud: 0.80f); + + // Spawn Paladin (left-center, 3/4 view toward camera) + var paladinMesh = (ArrayMesh)paladinTpl.BakedStaticMesh.Duplicate(); + ApplyMechPaintSurfaces(paladinMesh, paladinArmorMat, gunmetalMat, copperMat, orangeMat, markMat); + var paladinXf = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(24f)), new Vector3(-2.8f, 0f, -2.4f)); + var paladinMi = new MeshInstance3D + { + Name = "PaladinWeathered", + Mesh = paladinMesh, + Transform = paladinXf + }; + AddChild(paladinMi); + + // Spawn Jackal (right-midground, angled 3/4 toward camera) + var jackalMesh = (ArrayMesh)jackalTpl.BakedStaticMesh.Duplicate(); + ApplyMechPaintSurfaces(jackalMesh, jackalArmorMat, gunmetalMat, copperMat, orangeMat, markMat); + var jackalXf = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(-38f)), new Vector3(3.4f, 0f, 1.2f)); + var jackalMi = new MeshInstance3D + { + Name = "JackalWeathered", + Mesh = jackalMesh, + Transform = jackalXf + }; + AddChild(jackalMi); + + // Foreground angled Armor Showcase Slab (MechPaint via MultiMesh showing clean vs INSTANCE_CUSTOM scorch+heat) + var slabMesh = BuildBeveledShowcaseSlab(3.2f, 1.26f, 0.14f); + var slabMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = slabMesh, + InstanceCount = 2 + }; + var slabXf0 = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(14f)) * new Basis(Vector3.Right, Mathf.DegToRad(-22f)), new Vector3(1.15f, 1.85f, 6.2f)); + var slabXf1 = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(-18f)) * new Basis(Vector3.Right, Mathf.DegToRad(-18f)) * Basis.FromScale(new Vector3(0.45f, 0.55f, 1.0f)), new Vector3(5.35f, 0.85f, 3.8f)); + slabMm.SetInstanceTransform(0, slabXf0); + slabMm.SetInstanceCustomData(0, new Color(0.0f, 0.0f, 0f, 0f)); // clean weathered chest-height plate + slabMm.SetInstanceTransform(1, slabXf1); + slabMm.SetInstanceCustomData(1, new Color(0.90f, 0.48f, 0f, 0f)); // live combat scorch + heat_glow without cloning! + + var slabMmi = new MultiMeshInstance3D + { + Name = "ShowcaseArmorPlates", + Multimesh = slabMm, + MaterialOverride = paladinArmorMat + }; + AddChild(slabMmi); + + // Build 1 single MultiMeshInstance3D batch of POM decals across Paladin, Jackal, and the Showcase Slab + var decalMat = new ShaderMaterial { Shader = decalShader }; + decalMat.SetShaderParameter("albedo_tex", albedoTex); + decalMat.SetShaderParameter("normal_tex", normalTex); + decalMat.SetShaderParameter("ormh_tex", ormhTex); + decalMat.SetShaderParameter("use_instance_custom", true); + decalMat.SetShaderParameter("default_depth_scale", 0.06f); + decalMat.SetShaderParameter("normal_offset", 0.004f); + + var decalPlacements = new List<(Transform3D Xform, Color Custom)>(); + + // Showcase slab POM decals (close 3/4 grazing angle so 3D depth & hot rims are unmistakable) + AddSlabDecal(decalPlacements, slabXf0, -1.16f, 0.30f, 0.07f, 0.48f, tile: 0, heat: 0.0f, opacity: 1.0f, depth: 0.080f); // louvered vent + AddSlabDecal(decalPlacements, slabXf0, -0.58f, 0.30f, 0.07f, 0.48f, tile: 1, heat: 0.0f, opacity: 1.0f, depth: 0.080f); // bolted hatch + AddSlabDecal(decalPlacements, slabXf0, 0.00f, 0.30f, 0.07f, 0.48f, tile: 3, heat: 0.0f, opacity: 1.0f, depth: 0.080f); // slotted intake grille + AddSlabDecal(decalPlacements, slabXf0, 0.58f, 0.30f, 0.07f, 0.48f, tile: 5, heat: 0.0f, opacity: 1.0f, depth: 0.070f); // welded patch + AddSlabDecal(decalPlacements, slabXf0, 1.16f, 0.30f, 0.07f, 0.46f, tile: 8, heat: 0.0f, opacity: 0.96f, depth: 0.03f); // stencil "03" + + AddSlabDecal(decalPlacements, slabXf0, -1.16f, -0.30f, 0.07f, 0.48f, tile: 6, heat: 0.0f, opacity: 1.0f, depth: 0.085f); // lift-lug pocket + AddSlabDecal(decalPlacements, slabXf0, -0.58f, -0.30f, 0.07f, 0.48f, tile: 7, heat: 0.0f, opacity: 0.96f, depth: 0.04f); // hazard chevron + AddSlabDecal(decalPlacements, slabXf0, 0.00f, -0.30f, 0.07f, 0.50f, tile: 12, heat: 0.95f, opacity: 1.0f, depth: 0.095f); // glowing AP hole + AddSlabDecal(decalPlacements, slabXf0, 0.58f, -0.30f, 0.07f, 0.50f, tile: 13, heat: 0.75f, opacity: 1.0f, depth: 0.085f); // shrapnel gouge + AddSlabDecal(decalPlacements, slabXf0, 1.16f, -0.30f, 0.07f, 0.50f, tile: 14, heat: 0.92f, opacity: 1.0f, depth: 0.090f); // molten plasma crater + + // Raycast flush decals directly onto Paladin armor surfaces + TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-2.6f, 8.2f, 3.0f), new Vector3(0f, -0.05f, -1f), 0.72f, tile: 0, heat: 0.0f, opacity: 1.0f, depth: 0.07f); + TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-1.5f, 8.8f, 3.0f), new Vector3(-0.2f, -0.05f, -1f), 0.65f, tile: 8, heat: 0.0f, opacity: 0.95f, depth: 0.03f); + TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-2.8f, 7.1f, 3.0f), new Vector3(0.05f, 0f, -1f), 0.72f, tile: 12, heat: 0.95f, opacity: 1.0f, depth: 0.09f); + TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-3.6f, 7.8f, 3.0f), new Vector3(0.25f, 0f, -1f), 0.65f, tile: 10, heat: 0.0f, opacity: 0.95f, depth: 0.03f); + + // Raycast flush decals onto Jackal armor surfaces + TryAddRayDecal(decalPlacements, jackalMesh, jackalXf, new Vector3(3.4f, 3.0f, 1.5f), new Vector3(0f, -1f, 0.1f), 0.55f, tile: 9, heat: 0.0f, opacity: 0.95f, depth: 0.03f); + TryAddRayDecal(decalPlacements, jackalMesh, jackalXf, new Vector3(3.1f, 2.5f, 2.1f), new Vector3(0.2f, -0.8f, -0.5f), 0.50f, tile: 14, heat: 0.85f, opacity: 1.0f, depth: 0.08f); + + var decalQuad = new QuadMesh { Size = Vector2.One }; + var decalMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = decalQuad, + InstanceCount = decalPlacements.Count + }; + for (int i = 0; i < decalPlacements.Count; i++) + { + decalMm.SetInstanceTransform(i, decalPlacements[i].Xform); + decalMm.SetInstanceCustomData(i, decalPlacements[i].Custom); + } + var decalMmi = new MultiMeshInstance3D + { + Name = "PomDecalsBatch", + Multimesh = decalMm, + MaterialOverride = decalMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + AddChild(decalMmi); + + // Camera framing full Paladin (head to feet) + Jackal + close grazing showcase slab + var cam = new Camera3D + { + Name = "ProbeCamera", + Current = true, + Fov = 48f, + Near = 0.08f, + Far = 200f + }; + AddChild(cam); + cam.GlobalPosition = new Vector3(2.8f, 4.3f, 13.4f); + cam.LookAt(new Vector3(0.0f, 4.4f, 0.2f), Vector3.Up); + + // Wait several rendered frames so Vulkan Forward+ compiles all shaders and finishes drawing + for (int f = 0; f < 6; f++) + { + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + } + + if (DisplayServer.GetName() != "headless") + { + Image? cap = GetViewport().GetTexture()?.GetImage(); + Check(cap is not null && cap.GetWidth() == 1280 && cap.GetHeight() == 720, + $"Expected 1280x720 viewport capture, got {cap?.GetWidth()}x{cap?.GetHeight()}"); + if (cap is not null) + { + Directory.CreateDirectory(Path.GetDirectoryName(previewRepoPath)!); + cap.SavePng(previewRepoPath); + cap.SavePng(previewTempPath); + GD.Print($"VISUAL_PROBE SAVED: {previewRepoPath}"); + GD.Print($"VISUAL_PROBE SAVED: {previewTempPath}"); + } + } + + double drawCalls = RenderingServer.GetRenderingInfo(RenderingServer.RenderingInfo.TotalDrawCallsInFrame); + GD.Print($"VISUAL_PROBE INFO: renderer={RenderingServer.GetVideoAdapterName()} drawCalls={drawCalls} pomDecals={decalPlacements.Count}"); + Check(_failures.Count == 0, $"Encountered {_failures.Count} failures"); + } + catch (Exception ex) + { + Check(false, ex.ToString()); + } + + exitCode = _failures.Count == 0 ? 0 : 1; + GD.Print(exitCode == 0 ? "VISUAL_PROBE RESULT: PASS" : $"VISUAL_PROBE RESULT: FAIL ({_failures.Count})"); + Finish(exitCode); + } + + private void Finish(int code) + { + GetTree().Quit(code); + } + + private void SetupEnvironment() + { + GetViewport().UseTaa = true; + var atmosphere = new AtmosphereSystem { Name = "AtmosphereSystem" }; + AddChild(atmosphere); + atmosphere.ApplyMap(ArenaMapKind.Desert); + atmosphere.Sun.RotationDegrees = new Vector3(-38f, 36f, 0f); + } + + private void VerifyBakedVertexColors(string name, ArrayMesh mesh) + { + int surfCount = mesh.GetSurfaceCount(); + bool foundColor = false; + float minR = 1f, maxR = 0f, minG = 1f, maxG = 0f, minB = 1f, maxB = 0f, minA = 1f, maxA = 0f; + int totalVerts = 0; + for (int s = 0; s < surfCount; s++) + { + var arrays = mesh.SurfaceGetArrays(s); + if (arrays.Count > (int)Mesh.ArrayType.Color && + arrays[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray) + { + Color[] cols = arrays[(int)Mesh.ArrayType.Color].AsColorArray(); + foundColor = true; + totalVerts += cols.Length; + foreach (Color c in cols) + { + if (c.R < minR) minR = c.R; if (c.R > maxR) maxR = c.R; + if (c.G < minG) minG = c.G; if (c.G > maxG) maxG = c.G; + if (c.B < minB) minB = c.B; if (c.B > maxB) maxB = c.B; + if (c.A < minA) minA = c.A; if (c.A > maxA) maxA = c.A; + } + } + } + GD.Print($"COLOR_0 [{name}]: verts={totalVerts} AO=[{minR:F2},{maxR:F2}] Edge=[{minG:F2},{maxG:F2}] Island=[{minB:F2},{maxB:F2}] Height=[{minA:F2},{maxA:F2}]"); + Check(foundColor && totalVerts > 0, $"{name} missing baked COLOR_0 array"); + Check(minR < 0.35f && maxR > 0.85f, $"{name} AO range too narrow [{minR:F2},{maxR:F2}]"); + Check(maxG > 0.65f, $"{name} Edge curvature max too low ({maxG:F2})"); + Check(maxA - minA > 0.15f, $"{name} Rest height span too small [{minA:F2},{maxA:F2}]"); + } + + private static ImageTexture LoadTextureWithMips(string path) + { + var img = Image.LoadFromFile(path); + if (img is null) + { + throw new FileNotFoundException($"Could not load texture '{path}'", path); + } + img.GenerateMipmaps(); + return ImageTexture.CreateFromImage(img); + } + + private static ShaderMaterial MakeMechPaintMat( + Shader shader, + Color baseColor, + float metallic, + float roughness, + float wear, + float grime, + float mud, + float mudTop = 1.45f) + { + var mat = new ShaderMaterial { Shader = shader }; + mat.SetShaderParameter("base_color", baseColor); + mat.SetShaderParameter("metallic", metallic); + mat.SetShaderParameter("roughness", roughness); + mat.SetShaderParameter("wear", wear); + mat.SetShaderParameter("grime", grime); + mat.SetShaderParameter("mud", mud); + mat.SetShaderParameter("mud_top", mudTop); + return mat; + } + + private static void ApplyMechPaintSurfaces( + ArrayMesh mesh, + ShaderMaterial armorMat, + ShaderMaterial gunmetalMat, + ShaderMaterial copperMat, + ShaderMaterial orangeMat, + ShaderMaterial markMat) + { + int n = mesh.GetSurfaceCount(); + for (int s = 0; s < n; s++) + { + Material? orig = mesh.SurfaceGetMaterial(s); + string mName = (orig?.ResourceName ?? string.Empty).ToLowerInvariant(); + if (mName.Contains("glass") || mName.Contains("lamp") || mName.Contains("glow") || mName.Contains("cyan")) + { + continue; + } + if (mName.Contains("copper")) + { + mesh.SurfaceSetMaterial(s, copperMat); + } + else if (mName.Contains("signal") || mName.Contains("orange")) + { + mesh.SurfaceSetMaterial(s, orangeMat); + } + else if (mName.Contains("mark") || mName.Contains("stencil")) + { + mesh.SurfaceSetMaterial(s, markMat); + } + else if (mName.Contains("gunmetal") || mName.Contains("metal") || mName.Contains("steel") || mName.Contains("socket") || mName.Contains("pit") || mName.Contains("rubber")) + { + mesh.SurfaceSetMaterial(s, gunmetalMat); + } + else + { + mesh.SurfaceSetMaterial(s, armorMat); + } + } + } + + private static ArrayMesh BuildBeveledShowcaseSlab(float w, float h, float d) + { + // Build a subdivided box with baked COLOR_0 (flat faces G=0, sharp edges G=1, AO=0.9, island=0.42) + float hw = w * 0.5f, hh = h * 0.5f, hd = d * 0.5f; + var st = new SurfaceTool(); + st.Begin(Mesh.PrimitiveType.Triangles); + + void AddQuad(Vector3 a, Vector3 b, Vector3 c, Vector3 dPt, Vector3 nrm, float edgeA, float edgeB, float edgeC, float edgeD) + { + void V(Vector3 p, Vector2 uv, float edge) + { + float restH = Math.Clamp((p.Y + 4.2f) / 6.0f, 0f, 1f); + st.SetColor(new Color(0.92f, edge, 0.42f, restH)); + st.SetNormal(nrm); + st.SetUV(uv); + st.AddVertex(p); + } + // Clockwise front-face winding for Godot Spatial cull_back + V(a, new Vector2(0, 1), edgeA); + V(c, new Vector2(1, 0), edgeC); + V(b, new Vector2(1, 1), edgeB); + V(a, new Vector2(0, 1), edgeA); + V(dPt, new Vector2(0, 0), edgeD); + V(c, new Vector2(1, 0), edgeC); + } + + // Front (+Z) subdivided 3x1 so center interior vertices have edge=0 and outer corners have edge=0.95 + float x0 = -hw, x1 = -hw * 0.72f, x2 = hw * 0.72f, x3 = hw; + float y0 = -hh, y1 = -hh * 0.65f, y2 = hh * 0.65f, y3 = hh; + float[] xs = { x0, x1, x2, x3 }; + float[] ys = { y0, y1, y2, y3 }; + float[,] edges = { + { 0.95f, 0.85f, 0.85f, 0.95f }, + { 0.85f, 0.00f, 0.00f, 0.85f }, + { 0.85f, 0.00f, 0.00f, 0.85f }, + { 0.95f, 0.85f, 0.85f, 0.95f }, + }; + for (int iy = 0; iy < 3; iy++) + { + for (int ix = 0; ix < 3; ix++) + { + AddQuad( + new Vector3(xs[ix], ys[iy], hd), + new Vector3(xs[ix + 1], ys[iy], hd), + new Vector3(xs[ix + 1], ys[iy + 1], hd), + new Vector3(xs[ix], ys[iy + 1], hd), + Vector3.Back, + edges[iy, ix], edges[iy, ix + 1], edges[iy + 1, ix + 1], edges[iy + 1, ix]); + } + } + // Back & sides + AddQuad(new Vector3(hw, -hh, -hd), new Vector3(-hw, -hh, -hd), new Vector3(-hw, hh, -hd), new Vector3(hw, hh, -hd), Vector3.Forward, 0.9f, 0.9f, 0.9f, 0.9f); + AddQuad(new Vector3(-hw, hh, hd), new Vector3(hw, hh, hd), new Vector3(hw, hh, -hd), new Vector3(-hw, hh, -hd), Vector3.Up, 0.95f, 0.95f, 0.95f, 0.95f); + AddQuad(new Vector3(-hw, -hh, -hd), new Vector3(hw, -hh, -hd), new Vector3(hw, -hh, hd), new Vector3(-hw, -hh, hd), Vector3.Down, 0.95f, 0.95f, 0.95f, 0.95f); + AddQuad(new Vector3(-hw, -hh, -hd), new Vector3(-hw, -hh, hd), new Vector3(-hw, hh, hd), new Vector3(-hw, hh, -hd), Vector3.Left, 0.95f, 0.95f, 0.95f, 0.95f); + AddQuad(new Vector3(hw, -hh, hd), new Vector3(hw, -hh, -hd), new Vector3(hw, hh, -hd), new Vector3(hw, hh, hd), Vector3.Right, 0.95f, 0.95f, 0.95f, 0.95f); + st.GenerateTangents(); + return st.Commit(); + } + + private static void AddSlabDecal( + List<(Transform3D, Color)> list, + Transform3D slabXf, + float lx, + float ly, + float lz, + float size, + int tile, + float heat, + float opacity, + float depth) + { + var localXf = new Transform3D(Basis.FromScale(new Vector3(size, size, 1f)), new Vector3(lx, ly, lz)); + list.Add((slabXf * localXf, new Color(tile, heat, opacity, depth))); + } + + private static void TryAddRayDecal( + List<(Transform3D, Color)> list, + ArrayMesh mesh, + Transform3D meshXf, + Vector3 worldOrigin, + Vector3 worldDir, + float size, + int tile, + float heat, + float opacity, + float depth) + { + Transform3D inv = meshXf.AffineInverse(); + Vector3 localOrigin = inv * worldOrigin; + Vector3 localDir = (inv.Basis * worldDir).Normalized(); + + float bestT = float.PositiveInfinity; + Vector3 bestN = Vector3.Back; + + for (int s = 0; s < mesh.GetSurfaceCount(); s++) + { + var arr = mesh.SurfaceGetArrays(s); + if (arr.Count <= (int)Mesh.ArrayType.Vertex) continue; + Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + int[]? indices = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array + ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() + : null; + int triCount = (indices is not null ? indices.Length : verts.Length) / 3; + for (int t = 0; t < triCount; t++) + { + int i0 = indices is not null ? indices[t * 3] : t * 3; + int i1 = indices is not null ? indices[t * 3 + 1] : t * 3 + 1; + int i2 = indices is not null ? indices[t * 3 + 2] : t * 3 + 2; + Vector3 v0 = verts[i0], v1 = verts[i1], v2 = verts[i2]; + if (RayTriangle(localOrigin, localDir, v0, v1, v2, out float hitT)) + { + if (hitT < bestT) + { + Vector3 fn = (v1 - v0).Cross(v2 - v0); + if (fn.LengthSquared() > 1e-10f) + { + fn = fn.Normalized(); + if (fn.Dot(-localDir) < 0f) fn = -fn; + bestT = hitT; + bestN = fn; + } + } + } + } + } + + if (!float.IsFinite(bestT)) + { + return; + } + + Vector3 worldHit = meshXf * (localOrigin + localDir * bestT); + Vector3 worldN = (meshXf.Basis.Inverse().Transposed() * bestN).Normalized(); + Vector3 upRef = MathF.Abs(worldN.Y) > 0.92f ? Vector3.Forward : Vector3.Up; + Vector3 right = upRef.Cross(worldN).Normalized(); + Vector3 up = worldN.Cross(right).Normalized(); + var basis = new Basis(right * size, up * size, worldN); + list.Add((new Transform3D(basis, worldHit), new Color(tile, heat, opacity, depth))); + } + + private static bool RayTriangle(Vector3 orig, Vector3 dir, Vector3 v0, Vector3 v1, Vector3 v2, out float t) + { + t = 0f; + Vector3 e1 = v1 - v0; + Vector3 e2 = v2 - v0; + Vector3 pvec = dir.Cross(e2); + float det = e1.Dot(pvec); + if (MathF.Abs(det) < 1e-7f) return false; + float invDet = 1f / det; + Vector3 tvec = orig - v0; + float u = tvec.Dot(pvec) * invDet; + if (u < 0f || u > 1f) return false; + Vector3 qvec = tvec.Cross(e1); + float v = dir.Dot(qvec) * invDet; + if (v < 0f || u + v > 1f) return false; + t = e2.Dot(qvec) * invDet; + return t > 0.01f; + } +} diff --git a/client/tests/VisualProbe.tscn b/client/tests/VisualProbe.tscn new file mode 100644 index 0000000..1b39cde --- /dev/null +++ b/client/tests/VisualProbe.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://tests/VisualProbe.cs" id="1"] + +[node name="VisualProbe" type="Node3D"] +script = ExtResource("1") diff --git a/client/volumetric_capsule_beam.gdshader b/client/volumetric_capsule_beam.gdshader new file mode 100644 index 0000000..0f3330e --- /dev/null +++ b/client/volumetric_capsule_beam.gdshader @@ -0,0 +1,155 @@ +shader_type spatial; +render_mode unshaded, cull_front, blend_mix, depth_draw_never, depth_test_disabled; + +uniform sampler2D depth_tex : hint_depth_texture, filter_nearest; + +varying flat vec4 v_color; +varying flat vec4 v_custom; +varying flat vec3 v_ro; +varying flat float v_radius; +varying flat float v_halfLen; +varying vec3 v_fragCap; + +void vertex() { + v_color = COLOR; + v_custom = INSTANCE_CUSTOM; + + vec3 eX = normalize(MODEL_MATRIX[0].xyz); + vec3 eY = normalize(MODEL_MATRIX[1].xyz); + vec3 eZ = normalize(MODEL_MATRIX[2].xyz); + v_radius = max(0.005, 0.5 * length(MODEL_MATRIX[0].xyz)); + v_halfLen = max(0.0, 0.5 * length(MODEL_MATRIX[2].xyz) - v_radius); + + vec3 mid = MODEL_MATRIX[3].xyz; + mat3 invR = transpose(mat3(eX, eY, eZ)); + v_ro = invR * (CAMERA_POSITION_WORLD - mid); + + vec3 worldVert = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz; + v_fragCap = invR * (worldVert - mid); +} + +bool hitSphere(vec3 oc, vec3 rd, float r2, out float t0, out float t1) { + float b = dot(oc, rd); + float c = dot(oc, oc) - r2; + float disc = b * b - c; + if (disc <= 0.0) { + return false; + } + float sq = sqrt(disc); + t0 = -b - sq; + t1 = -b + sq; + return true; +} + +bool hitLocalCapsule(vec3 ro, vec3 rd, float h, float r, out float outEnter, out float outExit) { + float r2 = r * r; + if (h < 0.005) { + return hitSphere(ro, rd, r2, outEnter, outExit); + } + + outEnter = 1e9; + outExit = -1e9; + bool hit = false; + + float s0, s1; + if (hitSphere(ro - vec3(0.0, 0.0, -h), rd, r2, s0, s1)) { + outEnter = min(outEnter, s0); + outExit = max(outExit, s1); + hit = true; + } + if (hitSphere(ro - vec3(0.0, 0.0, h), rd, r2, s0, s1)) { + outEnter = min(outEnter, s0); + outExit = max(outExit, s1); + hit = true; + } + + // Infinite Z-axis cylinder x^2 + y^2 <= r^2 clipped to z in [-h, +h] + float a = dot(rd.xy, rd.xy); + float b = dot(ro.xy, rd.xy); + float c = dot(ro.xy, ro.xy) - r2; + float disc = b * b - a * c; + if (disc >= 0.0 && a > 1e-6) { + float sq = sqrt(disc); + float ct0 = (-b - sq) / a; + float ct1 = (-b + sq) / a; + if (abs(rd.z) > 1e-6) { + float tz0 = (-h - ro.z) / rd.z; + float tz1 = (h - ro.z) / rd.z; + ct0 = max(ct0, min(tz0, tz1)); + ct1 = min(ct1, max(tz0, tz1)); + if (ct1 > ct0) { + outEnter = min(outEnter, ct0); + outExit = max(outExit, ct1); + hit = true; + } + } else if (abs(ro.z) <= h) { + outEnter = min(outEnter, ct0); + outExit = max(outExit, ct1); + hit = true; + } + } + + return hit && (outExit > outEnter); +} + +void fragment() { + vec3 rd = normalize(v_fragCap - v_ro); + + float tEnter, tExit; + if (!hitLocalCapsule(v_ro, rd, v_halfLen, v_radius, tEnter, tExit)) { + discard; + } + tEnter = max(0.0, tEnter); + if (tExit <= tEnter) { + discard; + } + + float rawDepth = texture(depth_tex, SCREEN_UV).r; + float tScene = 1e6; + if (rawDepth > 0.0) { + vec4 viewPos = INV_PROJECTION_MATRIX * vec4(SCREEN_UV * 2.0 - 1.0, rawDepth, 1.0); + tScene = length(viewPos.xyz / viewPos.w); + } + + float tClipExit = min(tExit, tScene); + if (tClipExit <= tEnter) { + discard; + } + float depthFade = clamp((tScene - tEnter) / max(0.06, v_radius * 0.45), 0.0, 1.0); + + // Closest approach between clamped ray segment [tEnter, tClipExit] and capsule axis z in [-h, +h] + float xy2 = dot(rd.xy, rd.xy); + float tCyl = xy2 > 1e-6 ? -dot(v_ro.xy, rd.xy) / xy2 : 0.5 * (tEnter + tClipExit); + float tBest = clamp(tCyl, tEnter, tClipExit); + float s = v_ro.z + tBest * rd.z; + if (abs(s) > v_halfLen) { + s = clamp(s, -v_halfLen, v_halfLen); + tBest = clamp(-dot(v_ro - vec3(0.0, 0.0, s), rd), tEnter, tClipExit); + s = clamp(v_ro.z + tBest * rd.z, -v_halfLen, v_halfLen); + } + + vec3 pRay = v_ro + rd * tBest; + float dMin = length(pRay - vec3(0.0, 0.0, s)); + float rFrac = clamp(dMin / v_radius, 0.0, 1.0); + float chord = sqrt(max(0.0, 1.0 - rFrac * rFrac)); + + float coreSharpness = max(1.0, v_custom.x); + float coreFrac = clamp(v_custom.y, 0.08, 0.85); + float core = pow(clamp(1.0 - smoothstep(0.0, coreFrac, rFrac), 0.0, 1.0), coreSharpness); + float sheath = pow(chord, 1.75); + + // Basis.LookingAt puts -Z forward: start (tail) is at +v_halfLen, end (head) is at -v_halfLen + float tailT = v_halfLen > 0.01 ? clamp(0.5 - 0.5 * (s / v_halfLen), 0.0, 1.0) : 1.0; + float axial = mix(1.0, smoothstep(0.0, 0.78, tailT), v_custom.z * step(0.01, v_halfLen)); + float pulse = v_custom.w > 0.0 ? (0.88 + 0.12 * sin(s * 2.4 + TIME * v_custom.w)) : 1.0; + + vec3 hotCore = vec3(3.8, 3.8, 4.0); + vec3 rgb = mix(max(v_color.rgb, vec3(0.0)), hotCore, core * 0.82) * (0.45 + 0.55 * chord) * pulse; + float alpha = clamp(max(core, sheath * 0.85) * axial * depthFade * v_color.a, 0.0, 1.0); + if (alpha < 0.005) { + discard; + } + + ALBEDO = rgb; + ALPHA = alpha; +} diff --git a/client/volumetric_composite.glsl b/client/volumetric_composite.glsl new file mode 100644 index 0000000..327bb28 --- /dev/null +++ b/client/volumetric_composite.glsl @@ -0,0 +1,152 @@ +#version 450 + +layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in; + +#define MAX_TILE_EMITTERS 24u + +struct TileData { + uint count; + float minDepth; + float maxDepth; + uint _pad; + uint packedKeys[MAX_TILE_EMITTERS]; +}; + +layout(set = 0, binding = 0, std140) uniform VolumetricFrame { + mat4 invProj; + vec4 camPosTime; + vec4 camRightAspect; + vec4 camUpTanHalfFov; + vec4 camFwdNearFar; + vec4 sunDirIntensity; + vec4 sunColorExt; + vec4 ambientColorFog; + vec4 viewportInfo; + uvec4 tileGridParams; + vec4 flowOriginVoxel; + vec4 flowInvExtentDt; + ivec4 flowDeltaImpulse; + uvec4 qualityParams; +} u_frame; + +layout(set = 0, binding = 1) uniform sampler2D u_depthTex; +layout(set = 0, binding = 2) uniform sampler2D u_halfVolTex; +layout(set = 0, binding = 3, rgba16f) uniform image2D u_colorImg; +layout(set = 0, binding = 4, std430) readonly buffer TileBuffer { + TileData tiles[]; +} u_tiles; + +float linearizeReverseZ(float rawDepth) { + if (rawDepth <= 0.0) { + return u_frame.viewportInfo.z; + } + float zN = u_frame.ambientColorFog.w; + float zF = u_frame.viewportInfo.z; + return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN)); +} + +float marchQuadMaxDepth(ivec2 mpx, ivec2 marchRes, ivec2 fullRes) { + vec2 ratio = vec2(fullRes) / vec2(marchRes); + ivec2 px0 = clamp(ivec2(floor(vec2(mpx) * ratio)), ivec2(0), fullRes - ivec2(1)); + ivec2 px1 = clamp(ivec2(ceil(vec2(mpx + ivec2(1)) * ratio)) - ivec2(1), px0, fullRes - ivec2(1)); + float dMax = 0.0; + for (int sy = px0.y; sy <= px1.y; sy++) { + for (int sx = px0.x; sx <= px1.x; sx++) { + dMax = max(dMax, linearizeReverseZ(texelFetch(u_depthTex, ivec2(sx, sy), 0).r)); + } + } + return dMax; +} + +void main() { + ivec2 fullRes = ivec2(u_frame.viewportInfo.xy); + ivec2 px = ivec2(gl_GlobalInvocationID.xy); + if (any(greaterThanEqual(px, fullRes))) { + return; + } + + ivec2 marchRes = ivec2(u_frame.tileGridParams.xy); + uint tilesX = u_frame.tileGridParams.z; + bool isFullRes = u_frame.qualityParams.z != 0u; + + vec4 vol; + if (isFullRes) { + ivec2 tileCoord = px / 16; + uint tileIdx = uint(tileCoord.y) * tilesX + uint(tileCoord.x); + if (u_tiles.tiles[tileIdx].count == 0u) { + return; + } + // Direct 1:1 full-res sample bypassing 2x2 bilateral upsample + vol = texelFetch(u_halfVolTex, min(px, marchRes - ivec2(1)), 0); + } else { + vec2 scaleToMarch = vec2(marchRes) / vec2(fullRes); + vec2 hCoord = (vec2(px) + vec2(0.5)) * scaleToMarch - vec2(0.5); + ivec2 h0 = clamp(ivec2(floor(hCoord)), ivec2(0), marchRes - ivec2(1)); + ivec2 h1 = min(h0 + ivec2(1), marchRes - ivec2(1)); + + ivec2 t0 = h0 / 16; + ivec2 t1 = h1 / 16; + if (all(equal(t0, t1))) { + uint tileIdx = uint(t0.y) * tilesX + uint(t0.x); + if (u_tiles.tiles[tileIdx].count == 0u) { + return; + } + } else { + uint anyCount = + u_tiles.tiles[uint(t0.y) * tilesX + uint(t0.x)].count + + u_tiles.tiles[uint(t0.y) * tilesX + uint(t1.x)].count + + u_tiles.tiles[uint(t1.y) * tilesX + uint(t0.x)].count + + u_tiles.tiles[uint(t1.y) * tilesX + uint(t1.x)].count; + if (anyCount == 0u) { + return; + } + } + + float dFull = linearizeReverseZ(texelFetch(u_depthTex, px, 0).r); + vec2 f = clamp(hCoord - vec2(h0), vec2(0.0), vec2(1.0)); + + float depthScale = max(0.45, 0.055 * dFull); + vec4 volSum = vec4(0.0); + float wSum = 0.0; + float wRawSum = 0.0; + float minMarchDepth = 1e9; + + ivec2 offsets[4] = ivec2[4](ivec2(0, 0), ivec2(1, 0), ivec2(0, 1), ivec2(1, 1)); + float spatialW[4] = float[4]( + (1.0 - f.x) * (1.0 - f.y), + f.x * (1.0 - f.y), + (1.0 - f.x) * f.y, + f.x * f.y + ); + + for (int i = 0; i < 4; i++) { + ivec2 hp = min(h0 + offsets[i], marchRes - ivec2(1)); + vec4 vSample = texelFetch(u_halfVolTex, hp, 0); + float dMarch = marchQuadMaxDepth(hp, marchRes, fullRes); + minMarchDepth = min(minMarchDepth, dMarch); + float wDepth = exp(-abs(dFull - dMarch) / depthScale); + float wRaw = spatialW[i] * wDepth; + wRawSum += wRaw; + float w = max(1e-5, wRaw); + volSum += vSample * w; + wSum += w; + } + + // Thin foreground occluder (spark/edge strictly in front of ALL 4 march-res background depth taps): + // do not smear background smoke over it + if (wRawSum < 1e-3 && dFull < minMarchDepth * 0.92) { + return; + } + + vol = volSum / max(1e-5, wSum); + } + + // Skip write when completely transparent + if (vol.a > 0.999 && dot(vol.rgb, vol.rgb) < 1e-7) { + return; + } + + vec4 scene = imageLoad(u_colorImg, px); + scene.rgb = scene.rgb * clamp(vol.a, 0.0, 1.0) + max(vol.rgb, vec3(0.0)); + imageStore(u_colorImg, px, scene); +} diff --git a/client/volumetric_raymarch.glsl b/client/volumetric_raymarch.glsl new file mode 100644 index 0000000..63e61aa --- /dev/null +++ b/client/volumetric_raymarch.glsl @@ -0,0 +1,540 @@ +#version 450 + +layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in; + +#define MAX_TILE_EMITTERS 24u + +struct VolumetricEmitter { + vec4 posRadius; + vec4 endRadiusTemp; + vec4 params; + vec4 tintSoftness; +}; + +struct TileData { + uint count; + float minDepth; + float maxDepth; + uint _pad; + uint packedKeys[MAX_TILE_EMITTERS]; +}; + +layout(set = 0, binding = 0, std140) uniform VolumetricFrame { + mat4 invProj; + vec4 camPosTime; + vec4 camRightAspect; + vec4 camUpTanHalfFov; + vec4 camFwdNearFar; + vec4 sunDirIntensity; + vec4 sunColorExt; + vec4 ambientColorFog; + vec4 viewportInfo; + uvec4 tileGridParams; + vec4 flowOriginVoxel; + vec4 flowInvExtentDt; + ivec4 flowDeltaImpulse; + uvec4 qualityParams; +} u_frame; + +layout(set = 0, binding = 1, std430) readonly buffer EmitterBuffer { + VolumetricEmitter emitters[]; +} u_emitters; + +layout(set = 0, binding = 2, std430) readonly buffer TileBuffer { + TileData tiles[]; +} u_tiles; + +layout(set = 0, binding = 3) uniform sampler2D u_depthTex; +layout(set = 0, binding = 4) uniform sampler3D u_flowField; +layout(set = 0, binding = 5, rgba16f) uniform writeonly image2D u_halfVol; + +shared uint sTileCount; +shared VolumetricEmitter sEmitters[MAX_TILE_EMITTERS]; + +float linearizeReverseZ(float rawDepth) { + if (rawDepth <= 0.0) { + return u_frame.viewportInfo.z; + } + float zN = u_frame.ambientColorFog.w; + float zF = u_frame.viewportInfo.z; + return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN)); +} + +vec3 computeRayDirWorld(vec2 fullUv, out float invCosView) { + vec2 ndcXY = fullUv * 2.0 - 1.0; + float tanY = u_frame.camUpTanHalfFov.w; + float aspect = u_frame.camRightAspect.w; + vec3 viewVec = vec3(ndcXY.x * aspect * tanY, (1.0 - 2.0 * fullUv.y) * tanY, -1.0); + invCosView = length(viewVec); + return normalize(u_frame.camRightAspect.xyz * viewVec.x + + u_frame.camUpTanHalfFov.xyz * viewVec.y + + u_frame.camFwdNearFar.xyz); +} + +// --- Aetheria Volumetric.cginc math (ported cleanly with NaN-safe normalize) --- +float tri(float x) { + return abs(fract(x) - 0.5); +} + +vec3 tri3(vec3 p) { + return vec3( + tri(p.z + tri(p.y)), + tri(p.z + tri(p.x)), + tri(p.y + tri(p.x)) + ); +} + +vec3 safeNorm(vec3 v) { + float l2 = dot(v, v); + return l2 > 1e-8 ? v * inversesqrt(l2) : vec3(0.0, 1.0, 0.0); +} + +vec3 Tri3D(vec3 P, vec3 PGolden) { + vec3 t1 = safeNorm(tri3(P)); + vec3 t2 = safeNorm(tri3(PGolden)); + return cross(t1, t2); +} + +float triNoise3d(vec3 p, float flowTime) { + float z = 1.4; + float rz = 0.001; + vec3 bp = p; + for (int i = 0; i < 2; i++) { + vec3 dg = tri3(bp * 2.0); + p += dg + flowTime; + bp *= 1.8; + z *= 1.5; + p *= 1.2; + rz += tri(p.z + tri(p.x + tri(p.y))) / z; + bp += 0.14; + } + return rz; +} + +vec3 aetheriaFlow(vec3 pos, float flowScale, float scrollSpeed, float time) { + vec3 field = pos / max(0.5, flowScale); + float s1 = time * scrollSpeed; + float s2 = time * scrollSpeed * 1.61803398875; + vec3 fl = Tri3D(field - vec3(0.0, s1, 0.0), field * 1.61803398875 - vec3(0.0, s2, 0.0)); + fl.y *= 0.5; + return fl; +} + +bool intersectSphere(vec3 oc, vec3 rd, float r2, out float t0, out float t1) { + float b = dot(oc, rd); + float c = dot(oc, oc) - r2; + float disc = b * b - c; + if (disc <= 0.0) { + return false; + } + float sq = sqrt(disc); + t0 = -b - sq; + t1 = -b + sq; + return true; +} + +bool intersectCapsule(vec3 ro, vec3 rd, vec3 A, vec3 B, float R, out float outNear, out float outFar) { + float r2 = R * R; + vec3 ba = B - A; + float baba = dot(ba, ba); + if (baba < 0.0025) { + return intersectSphere(ro - A, rd, r2, outNear, outFar); + } + + outNear = 1e9; + outFar = -1e9; + bool hit = false; + + float s0, s1; + if (intersectSphere(ro - A, rd, r2, s0, s1)) { + outNear = min(outNear, s0); + outFar = max(outFar, s1); + hit = true; + } + if (intersectSphere(ro - B, rd, r2, s0, s1)) { + outNear = min(outNear, s0); + outFar = max(outFar, s1); + hit = true; + } + + vec3 oa = ro - A; + float bard = dot(ba, rd); + float baoa = dot(ba, oa); + float rdoa = dot(rd, oa); + float oaoa = dot(oa, oa); + float a = baba - bard * bard; + float b = baba * rdoa - baoa * bard; + float c = baba * oaoa - baoa * baoa - r2 * baba; + float h = b * b - a * c; + if (h >= 0.0 && a > 1e-6) { + float sq = sqrt(h); + float ct0 = (-b - sq) / a; + float ct1 = (-b + sq) / a; + if (abs(bard) > 1e-6) { + float tEnd0 = -baoa / bard; + float tEnd1 = (baba - baoa) / bard; + float tCapMin = min(tEnd0, tEnd1); + float tCapMax = max(tEnd0, tEnd1); + ct0 = max(ct0, tCapMin); + ct1 = min(ct1, tCapMax); + if (ct1 > ct0) { + outNear = min(outNear, ct0); + outFar = max(outFar, ct1); + hit = true; + } + } else if (baoa >= 0.0 && baoa <= baba) { + outNear = min(outNear, ct0); + outFar = max(outFar, ct1); + hit = true; + } + } + return hit && (outFar > outNear); +} + +vec3 blackbodyRamp(float temp) { + // Tuned for AgX (TonemapAgxWhite=6.0) + GlowHdrThreshold=1.0: blazing white-gold cores -> molten orange-red edges + vec3 c0 = vec3(0.55, 0.04, 0.003); + vec3 c1 = vec3(1.85, 0.28, 0.015); + vec3 c2 = vec3(3.60, 0.92, 0.075); + vec3 c3 = vec3(5.60, 2.35, 0.34); + vec3 c4 = vec3(7.60, 4.45, 1.35); + if (temp < 0.35) return mix(c0, c1, smoothstep(0.10, 0.35, temp)); + if (temp < 0.72) return mix(c1, c2, (temp - 0.35) / 0.37); + if (temp < 1.10) return mix(c2, c3, (temp - 0.72) / 0.38); + return mix(c3, c4, clamp((temp - 1.10) / 0.50, 0.0, 1.0)); +} + +float hgPhase(float cosTheta, float g) { + float g2 = g * g; + float denom = max(0.05, 1.0 + g2 - 2.0 * g * cosTheta); + return (1.0 - g2) / (12.5663706 * pow(denom, 1.5)); +} + +void main() { + uint tid = gl_LocalInvocationIndex; + ivec2 tileCoord = ivec2(gl_WorkGroupID.xy); + uint tilesX = u_frame.tileGridParams.z; + uint tileIdx = uint(tileCoord.y) * tilesX + uint(tileCoord.x); + + if (tid == 0u) { + sTileCount = min(u_tiles.tiles[tileIdx].count, MAX_TILE_EMITTERS); + } + memoryBarrierShared(); + barrier(); + + ivec2 marchRes = ivec2(u_frame.tileGridParams.xy); + ivec2 px = ivec2(gl_GlobalInvocationID.xy); + + // Empty-tile fast exit (uniform across workgroup) + if (sTileCount == 0u) { + if (all(lessThan(px, marchRes))) { + imageStore(u_halfVol, px, vec4(0.0, 0.0, 0.0, 1.0)); + } + return; + } + + if (tid < sTileCount) { + uint eIdx = u_tiles.tiles[tileIdx].packedKeys[tid] & 0x7Fu; + sEmitters[tid] = u_emitters.emitters[eIdx]; + } + memoryBarrierShared(); + barrier(); + + if (any(greaterThanEqual(px, marchRes))) { + return; + } + + ivec2 fullRes = ivec2(u_frame.viewportInfo.xy); + bool isFullRes = u_frame.qualityParams.z != 0u; + float dMax = 0.0; + if (isFullRes) { + ivec2 sp = min(px, fullRes - ivec2(1)); + dMax = linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r); + } else { + vec2 ratio = vec2(fullRes) / vec2(marchRes); + ivec2 px0 = clamp(ivec2(floor(vec2(px) * ratio)), ivec2(0), fullRes - ivec2(1)); + ivec2 px1 = clamp(ivec2(ceil(vec2(px + ivec2(1)) * ratio)) - ivec2(1), px0, fullRes - ivec2(1)); + for (int sy = px0.y; sy <= px1.y; sy++) { + for (int sx = px0.x; sx <= px1.x; sx++) { + float linD = linearizeReverseZ(texelFetch(u_depthTex, ivec2(sx, sy), 0).r); + dMax = max(dMax, linD); + } + } + } + + vec2 fullUv = (vec2(px) + vec2(0.5)) / vec2(marchRes); + float invCosView; + vec3 rd = computeRayDirWorld(fullUv, invCosView); + vec3 ro = u_frame.camPosTime.xyz; + float tSceneMax = dMax * invCosView; + + // Exact per-pixel capsule intersections sorted ascending by t0 for monotonic sweep-line + uint hitPack[MAX_TILE_EMITTERS]; + float hitT1[MAX_TILE_EMITTERS]; + uint hitCount = 0u; + float tEndMax = 0.0; + + for (uint k = 0u; k < sTileCount; k++) { + VolumetricEmitter em = sEmitters[k]; + float rBound = max(em.posRadius.w, em.params.y) * 1.95; + float t0, t1; + if (intersectCapsule(ro, rd, em.posRadius.xyz, em.endRadiusTemp.xyz, rBound, t0, t1)) { + t0 = max(2.0, t0); + t1 = min(tSceneMax, t1); + if (t1 > t0 + 1e-3) { + uint key = (floatBitsToUint(t0) & 0xFFFFFFE0u) | (k & 0x1Fu); + uint ins = hitCount; + while (ins > 0u && hitPack[ins - 1u] > key) { + hitPack[ins] = hitPack[ins - 1u]; + hitT1[ins] = hitT1[ins - 1u]; + ins--; + } + hitPack[ins] = key; + hitT1[ins] = t1; + hitCount++; + tEndMax = max(tEndMax, t1); + } + } + } + + if (hitCount == 0u) { + imageStore(u_halfVol, px, vec4(0.0, 0.0, 0.0, 1.0)); + return; + } + + // Interleaved Gradient Noise temporal jitter + float frameF = float(u_frame.tileGridParams.w & 63u); + float ign = fract(52.9829189 * fract(dot(vec2(px) + 5.588238 * frameF, vec2(0.06711056, 0.00583715)))); + + float elapsed = u_frame.camPosTime.w; + vec3 sunDir = u_frame.sunDirIntensity.xyz; + float cosTheta = dot(rd, sunDir); + float phase = mix(hgPhase(cosTheta, 0.68), hgPhase(cosTheta, -0.25), 0.22); + vec3 sunRad = u_frame.sunColorExt.rgb * u_frame.sunDirIntensity.w; + vec3 ambRad = u_frame.ambientColorFog.rgb; + float extScale = u_frame.sunColorExt.w; + + vec3 L = vec3(0.0); + float T = 1.0; + uint nextIdx = 0u; + uint activeMask = 0u; + float t = 0.0; + int steps = 0; + int iter = 0; + int maxSteps = clamp(int(u_frame.qualityParams.x), 1, 64); + int maxIter = clamp(max(int(u_frame.qualityParams.y), maxSteps * 2), 1, 96); + float stepScale = 10.0 / max(float(maxSteps), 1.0); + + while ((nextIdx < hitCount || activeMask != 0u) && t < tEndMax && T >= 0.03 && steps < maxSteps && iter < maxIter) { + // Empty-space jump directly to nextIdx's t0 whenever no emitter is currently active + if (activeMask == 0u) { + float minNext = uintBitsToFloat(hitPack[nextIdx] & 0xFFFFFFE0u); + float nextT1 = hitT1[nextIdx]; + float chord = max(0.0, nextT1 - minNext); + float dsLeap = max(0.16, max(0.42, 0.32 + 0.014 * minNext) * stepScale); + float jitter = ign * min(dsLeap, max(0.05, chord * 0.45)); + t = min(max(t, minNext) + jitter, tEndMax - 1e-4); + if (t >= tEndMax) { + break; + } + } + + float ds = max(0.16, max(0.42, 0.32 + 0.014 * t) * stepScale); + float tLo = t - 0.5 * ds; + float tHi = t + 0.5 * ds; + + // Monotonic sweep-line admission: advance nextIdx forward, never re-scanning earlier entries + while (nextIdx < hitCount) { + float b0 = uintBitsToFloat(hitPack[nextIdx] & 0xFFFFFFE0u); + if (b0 > tHi) { + break; + } + if (hitT1[nextIdx] >= tLo) { + activeMask |= (1u << nextIdx); + } + nextIdx++; + } + + // Retire emitters already exited + uint amCheck = activeMask; + while (amCheck != 0u) { + int bit = findLSB(amCheck); + amCheck &= amCheck - 1u; + if (hitT1[bit] < tLo) { + activeMask &= ~(1u << uint(bit)); + } + } + + if (activeMask == 0u) { + continue; + } + + // Near-camera fade (2.0..6.8m) so lens-adjacent plumes never blind the viewport or stall raymarching + if (t >= 2.0) { + float nearFade = smoothstep(2.0, 6.8, t); + float emitNearFade = smoothstep(2.5, 8.5, t); + if (nearFade > 0.001) { + vec3 worldPos = ro + rd * t; + bool hasFlow = false; + vec4 flowSample = vec4(0.0); + float shock = 0.0; + vec3 stepCurl = vec3(0.0); + + float rhoSum = 0.0; + vec3 albedoSum = vec3(0.0); + vec3 radialSum = vec3(0.0); + float tempSum = 0.0; + float noiseSum = 0.0; + float plasmaSum = 0.0; + + uint am = activeMask; + while (am != 0u) { + int hitSlot = findLSB(am); + am &= am - 1u; + uint k = hitPack[hitSlot] & 0x1Fu; + VolumetricEmitter em = sEmitters[k]; + + uint flags = floatBitsToUint(em.params.w); + uint emType = flags & 0xFu; + float ageNorm = float((flags >> 4u) & 0xFFu) / 255.0; + float seed = float((flags >> 12u) & 0xFFu) * 0.371; + + float rA = em.posRadius.w; + float rB = em.params.y; + float radAvg = max(0.35, 0.5 * (rA + rB)); + + vec3 A = em.posRadius.xyz; + vec3 B = em.endRadiusTemp.xyz; + vec3 ab = B - A; + float ab2 = dot(ab, ab); + + // Conservative squared-distance guard BEFORE sampling 3D flow texture or Tri3D curl (matches 1.95 * rad rBound) + float preSegT = ab2 > 1e-5 ? clamp(dot(worldPos - A, ab) / ab2, 0.0, 1.0) : 0.0; + float preRad = mix(rA, rB, preSegT); + vec3 preDelta = worldPos - (A + ab * preSegT); + float rGuard = 1.15 * preRad + 0.80 * radAvg; + if (dot(preDelta, preDelta) > rGuard * rGuard) { + continue; + } + + if (!hasFlow) { + vec3 flowUv = (worldPos - u_frame.flowOriginVoxel.xyz) * u_frame.flowInvExtentDt.xyz; + flowSample = (all(greaterThanEqual(flowUv, vec3(0.0))) && all(lessThanEqual(flowUv, vec3(1.0)))) + ? textureLod(u_flowField, flowUv, 0.0) + : vec4(0.0); + shock = clamp(flowSample.a, 0.0, 1.5); + stepCurl = aetheriaFlow(worldPos - flowSample.rgb * 0.20, 11.0, 0.68, elapsed); + hasFlow = true; + } + + // Uncuffed 3D flow advection + wind/buoyancy shear + age-grown Tri3D curl bounded inside rBound (1.95 * rad) + vec3 flowOffset = flowSample.rgb * (0.28 + 0.45 * ageNorm); + float advSegT = ab2 > 1e-5 ? clamp(dot((worldPos - flowOffset) - A, ab) / ab2, 0.0, 1.0) : 0.0; + flowOffset += vec3(flowSample.r, 0.0, flowSample.b) * (0.32 * advSegT * (0.35 + ageNorm)); + float fOffLen = length(flowOffset); + if (fOffLen > 0.62 * radAvg) { + flowOffset *= (0.62 * radAvg) / fOffLen; + } + vec3 advectedPos = worldPos - flowOffset; + + float curlScale = mix(0.24, 0.46, clamp(ageNorm * 1.1 + advSegT * 0.45, 0.0, 1.0)) * radAvg; + vec3 evalPos = advectedPos + stepCurl * curlScale; + + float segT = ab2 > 1e-5 ? clamp(dot(evalPos - A, ab) / ab2, 0.0, 1.0) : 0.0; + vec3 closest = A + ab * segT; + float taper = ab2 > 0.15 ? mix(1.02, 0.78, segT) : 1.0; + float rad = mix(rA, rB, segT) * taper; + vec3 radialVec = evalPos - closest; + float distNorm = length(radialVec) / max(0.15, rad); + + if (distNorm < 1.16) { + // True Aetheria gradient-offset pattern (Volumetric.cginc:210-215): + // triNoise3d ONLY offsets the smooth radial SDF gradient by a small centered displacement << 1.0 + vec3 nCoord = (evalPos / max(1.4, rad * 0.95)) * 0.32 + vec3(seed); + float n1 = triNoise3d(nCoord, elapsed * 0.32); + float n2 = triNoise3d(nCoord * 3.6, elapsed * 0.52); + float dispAmp = 0.35 + 0.65 * clamp(distNorm, 0.0, 1.0); + float disp = ((n1 - 0.45 * n2) - 0.11) * 0.88 * dispAmp; + float warpedDist = clamp(distNorm - disp, 0.0, 1.2); + + if (warpedDist < 1.0) { + float softness = clamp(em.tintSoftness.a, 0.18, 0.75); + float falloffEdge = mix(0.04, 0.14, softness); + float profile = 1.0 - smoothstep(falloffEdge, 1.0, warpedDist); + float rho_k = profile * em.params.x * nearFade; + + // Shock-front cavity carving + adiabatic compression rim + rho_k *= clamp(1.0 - shock * 0.42, 0.32, 1.0) * (1.0 + 0.45 * smoothstep(0.2, 0.9, shock)); + + if (rho_k > 1e-4) { + rhoSum += rho_k; + albedoSum += em.tintSoftness.rgb * rho_k; + radialSum += safeNorm(radialVec + vec3(0.0, 0.28 * rad, 0.0)) * rho_k; + + // Tight radial temperature falloff: outer shell cools to un-emissive rolling soot + float coreRadial = pow(clamp(1.0 - warpedDist, 0.0, 1.0), 2.35); + float localTemp = max(em.endRadiusTemp.w * coreRadial, shock * 0.22); + tempSum += localTemp * rho_k; + noiseSum += clamp((n1 - 0.45 * n2) * 2.5 + 0.25, 0.0, 1.0) * rho_k; + if (emType == 3u || emType == 4u) { + plasmaSum += rho_k; + } + } + } + } + } + + if (rhoSum > 0.002) { + float rawDens = rhoSum; + float coreTemp = tempSum / rhoSum; + float stepNoise = noiseSum / rhoSum; + vec3 albedo = albedoSum / rhoSum; + vec3 localUpOrRadial = safeNorm(radialSum); + + // Layer 1 & 2: Aetheria inverse-density charcoal soot contour (CloudShader.shader:96-97 / Volumetric.cginc:234) + // Dense interiors stay deep velvety charcoal soot; rimBoost (1.65) applies strictly to thin outer sunlit vapor edges + float sootContour = 1.0 / (1.0 + 4.6 * rawDens); + float sunAlignment = clamp(dot(localUpOrRadial, sunDir), -1.0, 1.0); + float rimBias = max(0.0, sunAlignment); + float rimFactor = 1.0 + 0.65 * smoothstep(0.25, 0.72, sootContour); + vec3 sunlitEdgeTint = mix(albedo, albedo * 1.35 + vec3(0.045, 0.040, 0.036), sootContour * smoothstep(0.10, 0.78, max(0.0, sunAlignment) + phase)); + float vaporEdgeFade = smoothstep(0.0, 0.08, rawDens); + vec3 skyBounce = max(0.0, localUpOrRadial.y) * 0.08 * ambRad; + vec3 scatterLum = sunlitEdgeTint * (sootContour * vaporEdgeFade * rimFactor) * (sunRad * (rimBias + phase * 2.6) + skyBounce); + + // Layer 3: Sharp turbulent core-only combustion peeking through dark soot crevices + vec3 plasmaEmit = vec3(0.0); + float coreSignal = coreTemp * (0.85 + 0.30 * stepNoise); + float coreGate = smoothstep(0.72, 1.05, coreSignal); + if (coreGate > 0.001) { + float coreGlow = pow(clamp(rawDens, 0.0, 1.4), 2.15) * coreGate; + vec3 bb = blackbodyRamp(coreTemp); + float plasmaMix = plasmaSum / rhoSum; + if (plasmaMix > 0.01) { + bb = mix(bb, albedo * (1.55 + 2.05 * coreTemp), 0.75 * plasmaMix); + } + plasmaEmit = bb * (coreGlow * 5.0) * emitNearFade; + } + + float sigmaT = rawDens * extScale; + float stepTrans = exp(-sigmaT * ds); + // CloudShader.shader:96-97: do NOT multiply scatterLum by sigmaT before dividing by sigmaT + float integDivExt = sigmaT > 1e-4 ? (1.0 - stepTrans) / sigmaT : ds; + vec3 stepLight = (scatterLum + plasmaEmit) * integDivExt * nearFade; + L += T * stepLight; + T *= stepTrans; + steps++; + if (T < 0.03) { + T = 0.0; + break; + } + } + } + } + + t += ds; + iter++; + } + + imageStore(u_halfVol, px, vec4(min(L, vec3(24.0)), clamp(T, 0.0, 1.0))); +} diff --git a/client/volumetric_tile_cull.glsl b/client/volumetric_tile_cull.glsl new file mode 100644 index 0000000..2ca2c59 --- /dev/null +++ b/client/volumetric_tile_cull.glsl @@ -0,0 +1,214 @@ +#version 450 + +layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in; + +#define MAX_TILE_EMITTERS 24u + +struct VolumetricEmitter { + vec4 posRadius; + vec4 endRadiusTemp; + vec4 params; + vec4 tintSoftness; +}; + +struct TileData { + uint count; + float minDepth; + float maxDepth; + uint _pad; + uint packedKeys[MAX_TILE_EMITTERS]; +}; + +layout(set = 0, binding = 0, std140) uniform VolumetricFrame { + mat4 invProj; + vec4 camPosTime; + vec4 camRightAspect; + vec4 camUpTanHalfFov; + vec4 camFwdNearFar; + vec4 sunDirIntensity; + vec4 sunColorExt; + vec4 ambientColorFog; + vec4 viewportInfo; + uvec4 tileGridParams; + vec4 flowOriginVoxel; + vec4 flowInvExtentDt; + ivec4 flowDeltaImpulse; + uvec4 qualityParams; +} u_frame; + +layout(set = 0, binding = 1, std430) readonly buffer EmitterBuffer { + VolumetricEmitter emitters[]; +} u_emitters; + +layout(set = 0, binding = 2, std430) writeonly buffer TileBuffer { + TileData tiles[]; +} u_tiles; + +layout(set = 0, binding = 3) uniform sampler2D u_depthTex; + +shared uint sMinDepthBits; +shared uint sMaxDepthBits; +shared uint sTileCount; +shared uint sKeys[128]; + +float linearizeReverseZ(float rawDepth) { + if (rawDepth <= 0.0) { + return u_frame.viewportInfo.z; + } + float zN = u_frame.ambientColorFog.w; + float zF = u_frame.viewportInfo.z; + return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN)); +} + +void main() { + uint tid = gl_LocalInvocationIndex; + ivec2 tileCoord = ivec2(gl_WorkGroupID.xy); + uint tilesX = u_frame.tileGridParams.z; + uint tileIdx = uint(tileCoord.y) * tilesX + uint(tileCoord.x); + + if (tid == 0u) { + sMinDepthBits = 0x7F7FFFFFu; + sMaxDepthBits = 0u; + sTileCount = 0u; + } + if (tid < 128u) { + sKeys[tid] = 0xFFFFFFFFu; + } + memoryBarrierShared(); + barrier(); + + ivec2 marchRes = ivec2(u_frame.tileGridParams.xy); + ivec2 fullRes = ivec2(u_frame.viewportInfo.xy); + ivec2 mx = ivec2(gl_GlobalInvocationID.xy); + bool isFullRes = u_frame.qualityParams.z != 0u; + + float dMin = u_frame.viewportInfo.z; + float dMax = 0.0; + if (all(lessThan(mx, marchRes))) { + if (isFullRes) { + ivec2 sp = min(mx, fullRes - ivec2(1)); + float linD = linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r); + dMin = linD; + dMax = linD; + } else { + vec2 ratio = vec2(fullRes) / vec2(marchRes); + ivec2 px0 = clamp(ivec2(floor(vec2(mx) * ratio)), ivec2(0), fullRes - ivec2(1)); + ivec2 px1 = clamp(ivec2(ceil(vec2(mx + ivec2(1)) * ratio)) - ivec2(1), px0, fullRes - ivec2(1)); + for (int sy = px0.y; sy <= px1.y; sy++) { + for (int sx = px0.x; sx <= px1.x; sx++) { + float rawD = texelFetch(u_depthTex, ivec2(sx, sy), 0).r; + float linD = linearizeReverseZ(rawD); + dMin = min(dMin, linD); + dMax = max(dMax, linD); + } + } + } + atomicMin(sMinDepthBits, floatBitsToUint(max(0.0, dMin))); + atomicMax(sMaxDepthBits, floatBitsToUint(max(0.0, dMax))); + } + memoryBarrierShared(); + barrier(); + + float tileMinDepth = uintBitsToFloat(sMinDepthBits); + float tileMaxDepth = uintBitsToFloat(sMaxDepthBits); + if (tileMaxDepth <= 0.0) { + tileMaxDepth = u_frame.viewportInfo.z; + } + + // Tile frustum bounds in view space (view looks down -Z, +X right, +Y up) + vec2 uv0 = vec2(tileCoord * 16) / vec2(marchRes); + vec2 uv1 = min(vec2((tileCoord + ivec2(1)) * 16) / vec2(marchRes), vec2(1.0)); + + float tanY = u_frame.camUpTanHalfFov.w; + float aspect = u_frame.camRightAspect.w; + float x0 = (uv0.x * 2.0 - 1.0) * aspect * tanY; + float x1 = (uv1.x * 2.0 - 1.0) * aspect * tanY; + float yTop = (1.0 - 2.0 * uv0.y) * tanY; + float yBot = (1.0 - 2.0 * uv1.y) * tanY; + + vec3 nLeft = normalize(vec3(-1.0, 0.0, -x0)); + vec3 nRight = normalize(vec3(1.0, 0.0, x1)); + vec3 nTop = normalize(vec3(0.0, 1.0, yTop)); + vec3 nBot = normalize(vec3(0.0, -1.0, -yBot)); + + uint emitterCount = min(uint(max(0.0, u_frame.viewportInfo.w + 0.5)), 128u); + if (tid < emitterCount) { + VolumetricEmitter em = u_emitters.emitters[tid]; + float rA = em.posRadius.w; + float rB = em.params.y; + float rBound = max(rA, rB) * 1.95; + + vec3 wA = em.posRadius.xyz - u_frame.camPosTime.xyz; + vec3 wB = em.endRadiusTemp.xyz - u_frame.camPosTime.xyz; + + vec3 camR = u_frame.camRightAspect.xyz; + vec3 camU = u_frame.camUpTanHalfFov.xyz; + vec3 camF = u_frame.camFwdNearFar.xyz; + + // View-space coordinates: +X right, +Y up, -Z forward + vec3 vA = vec3(dot(wA, camR), dot(wA, camU), -dot(wA, camF)); + vec3 vB = vec3(dot(wB, camR), dot(wB, camU), -dot(wB, camF)); + + float dMinEm = min(-vA.z - rBound, -vB.z - rBound); + float dMaxEm = max(-vA.z + rBound, -vB.z + rBound); + + // Reject only behind camera or completely behind tileMaxDepth (NEVER clip against tileMinDepth!) + bool visible = (dMaxEm > 0.0) && (dMinEm < tileMaxDepth); + if (visible) { + if (dot(vA, nLeft) > rBound && dot(vB, nLeft) > rBound) visible = false; + else if (dot(vA, nRight) > rBound && dot(vB, nRight) > rBound) visible = false; + else if (dot(vA, nTop) > rBound && dot(vB, nTop) > rBound) visible = false; + else if (dot(vA, nBot) > rBound && dot(vB, nBot) > rBound) visible = false; + } + + if (visible) { + vec3 ab = vB - vA; + float ab2 = dot(ab, ab); + float segT = ab2 > 1e-5 ? clamp(dot(-vA, ab) / ab2, 0.0, 1.0) : 0.0; + vec3 closest = vA + ab * segT; + float tMinConservative = max(0.0, length(closest) - rBound); + uint packedKey = (floatBitsToUint(tMinConservative) & 0xFFFFFF80u) | (tid & 0x7Fu); + uint slot = atomicAdd(sTileCount, 1u); + if (slot < 128u) { + sKeys[slot] = packedKey; + } + } + } + memoryBarrierShared(); + barrier(); + + // Adaptive Bitonic sort (skip when <= 1; sort smallest power-of-2 >= count up to 128) + uint count = sTileCount; + if (count > 1u) { + uint sortN = count <= 16u ? 16u : (count <= 32u ? 32u : (count <= 64u ? 64u : 128u)); + for (uint k = 2u; k <= sortN; k <<= 1u) { + for (uint j = k >> 1u; j > 0u; j >>= 1u) { + if (tid < sortN) { + uint ixj = tid ^ j; + if (ixj > tid) { + bool ascending = ((tid & k) == 0u); + uint a = sKeys[tid]; + uint b = sKeys[ixj]; + if ((a > b) == ascending) { + sKeys[tid] = b; + sKeys[ixj] = a; + } + } + } + memoryBarrierShared(); + barrier(); + } + } + } + + if (tid == 0u) { + uint outCount = min(sTileCount, MAX_TILE_EMITTERS); + u_tiles.tiles[tileIdx].count = outCount; + u_tiles.tiles[tileIdx].minDepth = tileMinDepth; + u_tiles.tiles[tileIdx].maxDepth = tileMaxDepth; + u_tiles.tiles[tileIdx]._pad = 0u; + } + if (tid < MAX_TILE_EMITTERS) { + u_tiles.tiles[tileIdx].packedKeys[tid] = sKeys[tid]; + } +} diff --git a/native/rtd_hbgpu/CMakeLists.txt b/native/rtd_hbgpu/CMakeLists.txt new file mode 100644 index 0000000..60f55e7 --- /dev/null +++ b/native/rtd_hbgpu/CMakeLists.txt @@ -0,0 +1,89 @@ +cmake_minimum_required(VERSION 3.22) + +project(rtd_hbgpu VERSION 0.1.0 LANGUAGES C CXX) + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +if(MSVC) + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +endif() + +# Resolve pinned HarfBuzz 15.2.0 source +set(RTD_HARFBUZZ_DIR "" CACHE PATH "Path to HarfBuzz 15.2.0 source directory") +if(NOT RTD_HARFBUZZ_DIR AND DEFINED ENV{RTD_HARFBUZZ_DIR} AND EXISTS "$ENV{RTD_HARFBUZZ_DIR}/CMakeLists.txt") + set(RTD_HARFBUZZ_DIR "$ENV{RTD_HARFBUZZ_DIR}") +elseif(NOT RTD_HARFBUZZ_DIR AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../../extern/harfbuzz/CMakeLists.txt") + set(RTD_HARFBUZZ_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../extern/harfbuzz") +elseif(NOT RTD_HARFBUZZ_DIR AND EXISTS "F:/aeth-wt/text-probe-gpu-build2/src/harfbuzz/CMakeLists.txt") + set(RTD_HARFBUZZ_DIR "F:/aeth-wt/text-probe-gpu-build2/src/harfbuzz") +endif() + +# Minimal HarfBuzz configuration: zero ICU/FreeType/Cairo/Glib/Subset/Raster/Vector bloat +set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) +set(HB_HAVE_CAIRO OFF CACHE BOOL "" FORCE) +set(HB_HAVE_FREETYPE OFF CACHE BOOL "" FORCE) +set(HB_HAVE_GRAPHITE2 OFF CACHE BOOL "" FORCE) +set(HB_HAVE_GLIB OFF CACHE BOOL "" FORCE) +set(HB_HAVE_ICU OFF CACHE BOOL "" FORCE) +set(HB_HAVE_GOBJECT OFF CACHE BOOL "" FORCE) +set(HB_HAVE_INTROSPECTION OFF CACHE BOOL "" FORCE) +set(HB_HAVE_CORETEXT OFF CACHE BOOL "" FORCE) +set(HB_HAVE_UNISCRIBE OFF CACHE BOOL "" FORCE) +set(HB_HAVE_GDI OFF CACHE BOOL "" FORCE) +set(HB_HAVE_DIRECTWRITE OFF CACHE BOOL "" FORCE) +set(HB_BUILD_UTILS OFF CACHE BOOL "" FORCE) +set(HB_BUILD_SUBSET OFF CACHE BOOL "" FORCE) +set(HB_BUILD_RASTER OFF CACHE BOOL "" FORCE) +set(HB_BUILD_VECTOR OFF CACHE BOOL "" FORCE) +set(HB_BUILD_GPU ON CACHE BOOL "" FORCE) +set(HB_BUILD_GPU_DEMO OFF CACHE STRING "" FORCE) + +if(RTD_HARFBUZZ_DIR AND EXISTS "${RTD_HARFBUZZ_DIR}/CMakeLists.txt") + add_subdirectory("${RTD_HARFBUZZ_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/harfbuzz" EXCLUDE_FROM_ALL) +else() + include(FetchContent) + FetchContent_Declare( + harfbuzz + URL "https://github.com/harfbuzz/harfbuzz/releases/download/15.2.0/harfbuzz-15.2.0.tar.xz" + URL_HASH SHA256=e2ec49090744383cdbe7df808c1cedaafba06a97be8dc4211fe546ba585f12cb + ) + FetchContent_MakeAvailable(harfbuzz) +endif() + +add_library(rtd_hbgpu SHARED rtd_hbgpu.c) +target_link_libraries(rtd_hbgpu PRIVATE harfbuzz-gpu harfbuzz) +target_include_directories(rtd_hbgpu + PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include" + PRIVATE "${harfbuzz_SOURCE_DIR}/src" +) +if(RTD_HARFBUZZ_DIR) + target_include_directories(rtd_hbgpu PRIVATE "${RTD_HARFBUZZ_DIR}/src") +endif() + +target_compile_features(rtd_hbgpu PRIVATE c_std_17) +target_compile_definitions(rtd_hbgpu PRIVATE RTD_HBGPU_EXPORTS) + +if(MSVC) + set_property(TARGET rtd_hbgpu PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + target_compile_options(harfbuzz PRIVATE $<$:/O2 /GL /Gy>) + target_compile_options(harfbuzz-gpu PRIVATE $<$:/O2 /GL /Gy>) + target_compile_options(rtd_hbgpu PRIVATE $<$:/O2 /GL /Gy>) + target_link_options(rtd_hbgpu PRIVATE $<$:/OPT:REF /OPT:ICF /LTCG>) +elseif(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(rtd_hbgpu PRIVATE $<$:-O2 -ffunction-sections -fdata-sections>) + if(NOT APPLE) + target_link_options(rtd_hbgpu PRIVATE $<$:-Wl,--gc-sections>) + endif() +endif() + +set_target_properties(rtd_hbgpu PROPERTIES + C_VISIBILITY_PRESET hidden + CXX_VISIBILITY_PRESET hidden + VISIBILITY_INLINES_HIDDEN ON + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" +) +if(MINGW) + set_property(TARGET rtd_hbgpu PROPERTY PREFIX "") +endif() diff --git a/native/rtd_hbgpu/include/rtd_hbgpu.h b/native/rtd_hbgpu/include/rtd_hbgpu.h new file mode 100644 index 0000000..e8fa720 --- /dev/null +++ b/native/rtd_hbgpu/include/rtd_hbgpu.h @@ -0,0 +1,124 @@ +#ifndef RTD_HBGPU_H +#define RTD_HBGPU_H + +#include + +#ifdef _WIN32 + #ifdef RTD_HBGPU_EXPORTS + #define RTD_HBGPU_API __declspec(dllexport) + #else + #define RTD_HBGPU_API __declspec(dllimport) + #endif +#else + #if defined(__GNUC__) || defined(__clang__) + #define RTD_HBGPU_API __attribute__((visibility("default"))) + #else + #define RTD_HBGPU_API + #endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct rtd_hb_font rtd_hb_font; + +typedef struct rtd_hb_font_metrics { + int32_t upem; + int32_t ascender; + int32_t descender; + int32_t line_gap; +} rtd_hb_font_metrics; + +typedef struct rtd_hb_shaped_glyph { + uint32_t glyph_id; + uint32_t cluster; + int32_t x_advance; + int32_t y_advance; + int32_t x_offset; + int32_t y_offset; +} rtd_hb_shaped_glyph; + +typedef struct rtd_hb_extents { + int32_t min_x; + int32_t min_y; + int32_t max_x; + int32_t max_y; +} rtd_hb_extents; + +enum { + RTD_HB_STAGE_VERTEX = 0, + RTD_HB_STAGE_FRAGMENT = 1 +}; + +enum { + RTD_HB_SHADER_SHARED = 0, + RTD_HB_SHADER_DRAW = 1 +}; + +enum { + RTD_HB_FEAT_NONE = 0, + RTD_HB_FEAT_CALT = 1u << 0, + RTD_HB_FEAT_LIGA = 1u << 1, + RTD_HB_FEAT_DEFAULT = RTD_HB_FEAT_CALT | RTD_HB_FEAT_LIGA +}; + +enum { + RTD_HB_VERB_MOVE = 0, /* 2 args: x, y */ + RTD_HB_VERB_LINE_TO = 1, /* 2 args: x, y */ + RTD_HB_VERB_QUAD_TO = 2, /* 4 args: cx, cy, x, y */ + RTD_HB_VERB_CUBIC_TO = 3, /* 6 args: c1x, c1y, c2x, c2y, x, y */ + RTD_HB_VERB_CLOSE = 4, /* 0 args */ + RTD_HB_VERB_LINE = 5, /* 7 args: x0, y0, w0, x1, y1, w1, cap (0=butt,1=square) */ + RTD_HB_VERB_RECT = 6, /* 5 args: x, y, w, h, stroke_width (NaN or <0 = filled) */ + RTD_HB_VERB_CIRCLE = 7 /* 4 args: cx, cy, r, stroke_width (NaN or <0 = filled) */ +}; + +RTD_HBGPU_API const char* rtd_hb_version_string(void); + +RTD_HBGPU_API const char* rtd_hb_shader_source(uint32_t stage, uint32_t kind); + +RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create( + const uint8_t* ttf, + uint32_t len, + uint32_t face_index, + rtd_hb_font_metrics* out_metrics); + +RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create_variant( + const rtd_hb_font* base_font, + float wght, + float wdth, + float slnt); + +RTD_HBGPU_API void rtd_hb_font_destroy(rtd_hb_font* f); + +RTD_HBGPU_API uint32_t rtd_hb_shape_utf16( + rtd_hb_font* f, + const uint16_t* utf16, + uint32_t char_len, + uint32_t feature_flags, + rtd_hb_shaped_glyph* out, + uint32_t cap); + +RTD_HBGPU_API int32_t rtd_hb_encode_glyph( + rtd_hb_font* f, + uint32_t glyph_id, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext); + +RTD_HBGPU_API int32_t rtd_hb_encode_path( + uint32_t design_upem, + const uint8_t* verbs, + uint32_t n_verbs, + const float* args, + uint32_t n_args, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext); + +#ifdef __cplusplus +} +#endif + +#endif /* RTD_HBGPU_H */ diff --git a/native/rtd_hbgpu/rtd_hbgpu.c b/native/rtd_hbgpu/rtd_hbgpu.c new file mode 100644 index 0000000..f5ffb2c --- /dev/null +++ b/native/rtd_hbgpu/rtd_hbgpu.c @@ -0,0 +1,348 @@ +#include "rtd_hbgpu.h" + +#include "hb.h" +#include "hb-gpu.h" +#include "hb-ot.h" + +#include +#include +#include + +struct rtd_hb_font { + hb_face_t* face; + hb_font_t* font; + hb_buffer_t* buf; + hb_gpu_draw_t* draw; +}; + +static void fill_extents(const hb_glyph_extents_t* ext, rtd_hb_extents* out_ext) { + if (!out_ext) return; + out_ext->min_x = ext->x_bearing; + out_ext->max_y = ext->y_bearing; + out_ext->max_x = ext->x_bearing + ext->width; + out_ext->min_y = ext->y_bearing + ext->height; +} + +static int32_t finalize_draw_blob( + hb_gpu_draw_t* draw, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext) +{ + hb_glyph_extents_t hb_ext; + memset(&hb_ext, 0, sizeof(hb_ext)); + + hb_blob_t* blob = hb_gpu_draw_encode(draw, &hb_ext); + if (!blob) { + return -1; + } + + unsigned int byte_len = 0; + const char* data = hb_blob_get_data(blob, &byte_len); + fill_extents(&hb_ext, out_ext); + + if (byte_len == 0) { + hb_gpu_draw_recycle_blob(draw, blob); + return 0; + } + + if ((byte_len & 7u) != 0u) { + hb_gpu_draw_recycle_blob(draw, blob); + return -1; + } + + uint32_t texels = byte_len >> 3u; + if (texels > cap_texels || !out_rgba16i) { + hb_gpu_draw_recycle_blob(draw, blob); + return -(int32_t)texels; + } + + memcpy(out_rgba16i, data, byte_len); + hb_gpu_draw_recycle_blob(draw, blob); + return (int32_t)texels; +} + +RTD_HBGPU_API const char* rtd_hb_version_string(void) { + return hb_version_string(); +} + +RTD_HBGPU_API const char* rtd_hb_shader_source(uint32_t stage, uint32_t kind) { + hb_gpu_shader_stage_t hb_stage; + if (stage == RTD_HB_STAGE_VERTEX) { + hb_stage = HB_GPU_SHADER_STAGE_VERTEX; + } else if (stage == RTD_HB_STAGE_FRAGMENT) { + hb_stage = HB_GPU_SHADER_STAGE_FRAGMENT; + } else { + return NULL; + } + + if (kind == RTD_HB_SHADER_SHARED) { + return hb_gpu_shader_source(hb_stage, HB_GPU_SHADER_LANG_GLSL); + } + if (kind == RTD_HB_SHADER_DRAW) { + return hb_gpu_draw_shader_source(hb_stage, HB_GPU_SHADER_LANG_GLSL); + } + return NULL; +} + +RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create( + const uint8_t* ttf, + uint32_t len, + uint32_t face_index, + rtd_hb_font_metrics* out_metrics) +{ + if (!ttf || len == 0) return NULL; + + hb_blob_t* blob = hb_blob_create((const char*)ttf, len, HB_MEMORY_MODE_DUPLICATE, NULL, NULL); + if (!blob || hb_blob_get_length(blob) == 0) { + if (blob) hb_blob_destroy(blob); + return NULL; + } + + hb_face_t* face = hb_face_create(blob, face_index); + hb_blob_destroy(blob); + if (!face || face == hb_face_get_empty()) { + if (face) hb_face_destroy(face); + return NULL; + } + + hb_font_t* font = hb_font_create(face); + hb_buffer_t* buf = hb_buffer_create(); + hb_gpu_draw_t* draw = hb_gpu_draw_create_or_fail(); + if (!font || !buf || !draw) { + if (draw) hb_gpu_draw_destroy(draw); + if (buf) hb_buffer_destroy(buf); + if (font) hb_font_destroy(font); + hb_face_destroy(face); + return NULL; + } + + rtd_hb_font* out = (rtd_hb_font*)calloc(1, sizeof(rtd_hb_font)); + if (!out) { + hb_gpu_draw_destroy(draw); + hb_buffer_destroy(buf); + hb_font_destroy(font); + hb_face_destroy(face); + return NULL; + } + + out->face = face; + out->font = font; + out->buf = buf; + out->draw = draw; + + if (out_metrics) { + hb_font_extents_t fe; + memset(&fe, 0, sizeof(fe)); + hb_font_get_h_extents(font, &fe); + out_metrics->upem = (int32_t)hb_face_get_upem(face); + out_metrics->ascender = fe.ascender; + out_metrics->descender = fe.descender; + out_metrics->line_gap = fe.line_gap; + } + + return out; +} + +RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create_variant( + const rtd_hb_font* base_font, + float wght, + float wdth, + float slnt) +{ + if (!base_font || !base_font->face) return NULL; + + hb_face_t* face = hb_face_reference(base_font->face); + hb_font_t* font = hb_font_create(face); + hb_buffer_t* buf = hb_buffer_create(); + hb_gpu_draw_t* draw = hb_gpu_draw_create_or_fail(); + if (!font || !buf || !draw) { + if (draw) hb_gpu_draw_destroy(draw); + if (buf) hb_buffer_destroy(buf); + if (font) hb_font_destroy(font); + hb_face_destroy(face); + return NULL; + } + + hb_variation_t vars[3] = { + { HB_TAG('w', 'g', 'h', 't'), wght }, + { HB_TAG('w', 'd', 't', 'h'), wdth }, + { HB_TAG('s', 'l', 'n', 't'), slnt } + }; + hb_font_set_variations(font, vars, 3); + + rtd_hb_font* out = (rtd_hb_font*)calloc(1, sizeof(rtd_hb_font)); + if (!out) { + hb_gpu_draw_destroy(draw); + hb_buffer_destroy(buf); + hb_font_destroy(font); + hb_face_destroy(face); + return NULL; + } + + out->face = face; + out->font = font; + out->buf = buf; + out->draw = draw; + return out; +} + +RTD_HBGPU_API void rtd_hb_font_destroy(rtd_hb_font* f) { + if (!f) return; + if (f->draw) hb_gpu_draw_destroy(f->draw); + if (f->buf) hb_buffer_destroy(f->buf); + if (f->font) hb_font_destroy(f->font); + if (f->face) hb_face_destroy(f->face); + free(f); +} + +RTD_HBGPU_API uint32_t rtd_hb_shape_utf16( + rtd_hb_font* f, + const uint16_t* utf16, + uint32_t char_len, + uint32_t feature_flags, + rtd_hb_shaped_glyph* out, + uint32_t cap) +{ + if (!f || !f->font || !f->buf) return 0; + if (char_len == 0 || !utf16) return 0; + + hb_buffer_clear_contents(f->buf); + hb_buffer_add_utf16(f->buf, utf16, (int)char_len, 0, (int)char_len); + hb_buffer_guess_segment_properties(f->buf); + + hb_feature_t feats[2] = { + { HB_TAG('c', 'a', 'l', 't'), (feature_flags & RTD_HB_FEAT_CALT) ? 1u : 0u, HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END }, + { HB_TAG('l', 'i', 'g', 'a'), (feature_flags & RTD_HB_FEAT_LIGA) ? 1u : 0u, HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END } + }; + hb_shape(f->font, f->buf, feats, 2); + + unsigned int count = 0; + const hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(f->buf, &count); + const hb_glyph_position_t* pos = hb_buffer_get_glyph_positions(f->buf, &count); + + if (out && cap > 0) { + uint32_t to_copy = count < cap ? count : cap; + for (uint32_t i = 0; i < to_copy; i++) { + out[i].glyph_id = infos[i].codepoint; + out[i].cluster = infos[i].cluster; + out[i].x_advance = pos[i].x_advance; + out[i].y_advance = pos[i].y_advance; + out[i].x_offset = pos[i].x_offset; + out[i].y_offset = pos[i].y_offset; + } + } + + return count; +} + +RTD_HBGPU_API int32_t rtd_hb_encode_glyph( + rtd_hb_font* f, + uint32_t glyph_id, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext) +{ + if (!f || !f->font || !f->draw) return -1; + + hb_gpu_draw_clear(f->draw); + hb_gpu_draw_glyph(f->draw, f->font, glyph_id); + return finalize_draw_blob(f->draw, out_rgba16i, cap_texels, out_ext); +} + +RTD_HBGPU_API int32_t rtd_hb_encode_path( + uint32_t design_upem, + const uint8_t* verbs, + uint32_t n_verbs, + const float* args, + uint32_t n_args, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext) +{ + if (!verbs || n_verbs == 0 || design_upem == 0) return -1; + + hb_gpu_draw_t* draw = hb_gpu_draw_create_or_fail(); + if (!draw) return -1; + + hb_gpu_draw_set_scale(draw, (int)design_upem, (int)design_upem); + hb_draw_funcs_t* dfuncs = hb_gpu_draw_get_funcs(draw); + hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; + + uint32_t arg_idx = 0; + for (uint32_t i = 0; i < n_verbs; i++) { + switch (verbs[i]) { + case RTD_HB_VERB_MOVE: + if (arg_idx + 2u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_move_to(dfuncs, draw, &st, args[arg_idx], args[arg_idx + 1]); + arg_idx += 2u; + break; + + case RTD_HB_VERB_LINE_TO: + if (arg_idx + 2u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_line_to(dfuncs, draw, &st, args[arg_idx], args[arg_idx + 1]); + arg_idx += 2u; + break; + + case RTD_HB_VERB_QUAD_TO: + if (arg_idx + 4u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_quadratic_to(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], + args[arg_idx + 2], args[arg_idx + 3]); + arg_idx += 4u; + break; + + case RTD_HB_VERB_CUBIC_TO: + if (arg_idx + 6u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_cubic_to(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], + args[arg_idx + 2], args[arg_idx + 3], + args[arg_idx + 4], args[arg_idx + 5]); + arg_idx += 6u; + break; + + case RTD_HB_VERB_CLOSE: + hb_draw_close_path(dfuncs, draw, &st); + break; + + case RTD_HB_VERB_LINE: + if (arg_idx + 7u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_line(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], args[arg_idx + 2], + args[arg_idx + 3], args[arg_idx + 4], args[arg_idx + 5], + args[arg_idx + 6] >= 0.5f ? HB_DRAW_LINE_CAP_SQUARE : HB_DRAW_LINE_CAP_BUTT); + arg_idx += 7u; + break; + + case RTD_HB_VERB_RECT: { + if (arg_idx + 5u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + float sw = args[arg_idx + 4]; + if (sw < 0.0f) sw = NAN; + hb_draw_rectangle(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], + args[arg_idx + 2], args[arg_idx + 3], sw); + arg_idx += 5u; + break; + } + + case RTD_HB_VERB_CIRCLE: { + if (arg_idx + 4u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + float sw = args[arg_idx + 3]; + if (sw < 0.0f) sw = NAN; + hb_draw_circle(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], + args[arg_idx + 2], sw); + arg_idx += 4u; + break; + } + + default: + hb_gpu_draw_destroy(draw); + return -1; + } + } + + int32_t res = finalize_draw_blob(draw, out_rgba16i, cap_texels, out_ext); + hb_gpu_draw_destroy(draw); + return res; +} diff --git a/src/RustToDust.Core/ArenaMapKind.cs b/src/RustToDust.Core/ArenaMapKind.cs new file mode 100644 index 0000000..d202ed7 --- /dev/null +++ b/src/RustToDust.Core/ArenaMapKind.cs @@ -0,0 +1,8 @@ +namespace RustToDust.Core +{ + public enum ArenaMapKind + { + Desert, + Sion + } +} diff --git a/src/RustToDust.Core/ArenaScarLedger.cs b/src/RustToDust.Core/ArenaScarLedger.cs new file mode 100644 index 0000000..d57d041 --- /dev/null +++ b/src/RustToDust.Core/ArenaScarLedger.cs @@ -0,0 +1,384 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; + +namespace RustToDust.Core +{ + [MessagePackObject] + public sealed class TerrainScarEntry + { + [Key(0)] public byte Kind { get; set; } + [Key(1)] public float X { get; set; } + [Key(2)] public float Z { get; set; } + [Key(3)] public float Radius { get; set; } + [Key(4)] public float Depth { get; set; } + [Key(5)] public float Yaw { get; set; } + [Key(6)] public uint Rgb8 { get; set; } + [Key(7), CultElementId] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class BuildingScarEntry + { + [Key(0)] public ushort BldgId { get; set; } + [Key(1)] public ulong CollapsedMask { get; set; } + [Key(2)] public ulong DamagedMask { get; set; } + [Key(3), CultElementId(nameof(BldgId))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class TreeScarEntry + { + [Key(0)] public ushort TreeId { get; set; } + [Key(1)] public byte State { get; set; } + [Key(2), CultElementId(nameof(TreeId))] public string ElementId { get; set; } = string.Empty; + } + + [CultDocument("rtd.arena_scar_ledger", "1"), MessagePackObject] + public sealed class ArenaScarLedgerSnapshot + { + [CultName, Key(0)] public string AssetFingerprint { get; set; } = string.Empty; + [Key(1)] public List Terrain { get; set; } = new(); + [Key(2)] public List Buildings { get; set; } = new(); + [Key(3)] public List Trees { get; set; } = new(); + [Key(4)] public uint LedgerRevision { get; set; } + } + + public sealed class ArenaScarLedger + { + public const int MaxPersistentTerrainScars = 4096; + public const float CraterCoalesceRadiusMeters = TerrainField.CraterCoalesceRadiusMeters; + + private readonly List _terrain = new(); + private readonly Dictionary _buildings = new(); + private readonly Dictionary _trees = new(); + + public ArenaScarLedger(string assetFingerprint = "") + { + AssetFingerprint = assetFingerprint; + } + + public string AssetFingerprint { get; set; } + public uint LedgerRevision { get; private set; } + public bool IsDirty { get; set; } + public IReadOnlyList Terrain => _terrain; + public IReadOnlyDictionary Buildings => _buildings; + public IReadOnlyDictionary Trees => _trees; + + public void RecordTerrainStamp(TerrainStampEvent stamp) => + RecordTerrainStamp(stamp.Kind, stamp.X, stamp.Z, stamp.Radius, stamp.Depth, stamp.Yaw); + + public void RecordTerrainStamp(byte kind, float x, float z, float radius, float depth, float yaw, uint rgb8 = 0) + { + var stampKind = (TerrainStampKind)kind; + if (stampKind == TerrainStampKind.Track) + { + return; + } + + if (stampKind == TerrainStampKind.Crater) + { + radius = Math.Clamp(radius, 1.2f, 16f); + depth = Math.Clamp(MathF.Abs(depth), 0.15f, 4.5f); + } + + float coalesceSq = CraterCoalesceRadiusMeters * CraterCoalesceRadiusMeters; + if (stampKind == TerrainStampKind.Crater || stampKind == TerrainStampKind.Scorch) + { + for (int i = _terrain.Count - 1; i >= 0; i--) + { + var existing = _terrain[i]; + if (existing.Kind != kind) + { + continue; + } + float dx = existing.X - x; + float dz = existing.Z - z; + if (dx * dx + dz * dz < coalesceSq) + { + existing.Radius = MathF.Max(existing.Radius, radius); + existing.Depth = MathF.Max(existing.Depth, depth); + LedgerRevision++; + IsDirty = true; + return; + } + } + } + + if (_terrain.Count >= MaxPersistentTerrainScars) + { + int evictIdx = -1; + for (int i = 0; i < _terrain.Count; i++) + { + if (_terrain[i].Kind == (byte)TerrainStampKind.Scorch) + { + evictIdx = i; + break; + } + } + _terrain.RemoveAt(evictIdx >= 0 ? evictIdx : 0); + } + + _terrain.Add(new TerrainScarEntry + { + Kind = kind, + X = x, + Z = z, + Radius = radius, + Depth = depth, + Yaw = yaw, + Rgb8 = rgb8 + }); + LedgerRevision++; + IsDirty = true; + } + + public void Clear() + { + _terrain.Clear(); + _buildings.Clear(); + _trees.Clear(); + LedgerRevision++; + IsDirty = true; + } + + public ArenaScarLedgerSnapshot ToSnapshot() + { + var snap = new ArenaScarLedgerSnapshot + { + AssetFingerprint = AssetFingerprint, + LedgerRevision = LedgerRevision, + Terrain = new List(_terrain.Count), + Buildings = new List(_buildings.Count), + Trees = new List(_trees.Count) + }; + for (int i = 0; i < _terrain.Count; i++) + { + var t = _terrain[i]; + snap.Terrain.Add(new TerrainScarEntry + { + Kind = t.Kind, + X = t.X, + Z = t.Z, + Radius = t.Radius, + Depth = t.Depth, + Yaw = t.Yaw, + Rgb8 = t.Rgb8 + }); + } + foreach (var b in _buildings.Values) + { + snap.Buildings.Add(new BuildingScarEntry + { + BldgId = b.BldgId, + CollapsedMask = b.CollapsedMask, + DamagedMask = b.DamagedMask + }); + } + foreach (var tr in _trees.Values) + { + snap.Trees.Add(new TreeScarEntry + { + TreeId = tr.TreeId, + State = tr.State + }); + } + return snap; + } + + public void LoadFromSnapshot(ArenaScarLedgerSnapshot snapshot) + { + _terrain.Clear(); + _buildings.Clear(); + _trees.Clear(); + + if (!string.IsNullOrEmpty(AssetFingerprint) && + !string.Equals(snapshot.AssetFingerprint, AssetFingerprint, StringComparison.Ordinal)) + { + return; + } + + for (int i = 0; i < snapshot.Terrain.Count && i < MaxPersistentTerrainScars; i++) + { + var t = snapshot.Terrain[i]; + _terrain.Add(new TerrainScarEntry + { + Kind = t.Kind, + X = t.X, + Z = t.Z, + Radius = t.Radius, + Depth = t.Depth, + Yaw = t.Yaw, + Rgb8 = t.Rgb8 + }); + } + for (int i = 0; i < snapshot.Buildings.Count; i++) + { + var b = snapshot.Buildings[i]; + _buildings[b.BldgId] = new BuildingScarEntry + { + BldgId = b.BldgId, + CollapsedMask = b.CollapsedMask, + DamagedMask = b.DamagedMask + }; + } + for (int i = 0; i < snapshot.Trees.Count; i++) + { + var tr = snapshot.Trees[i]; + _trees[tr.TreeId] = new TreeScarEntry + { + TreeId = tr.TreeId, + State = tr.State + }; + } + LedgerRevision = snapshot.LedgerRevision; + IsDirty = false; + } + + public void ApplyToTerrain(TerrainField terrain) + { + for (int i = 0; i < _terrain.Count; i++) + { + var t = _terrain[i]; + switch ((TerrainStampKind)t.Kind) + { + case TerrainStampKind.Crater: + terrain.StampCrater(t.X, t.Z, t.Radius, t.Depth); + break; + case TerrainStampKind.Scorch: + terrain.StampScorch(t.X, t.Z, t.Radius); + break; + case TerrainStampKind.Rubble: + terrain.StampRubble(t.X, t.Z, t.Radius, t.Depth, t.Yaw); + break; + } + } + } + + public static byte[] CompressSnapshot(ArenaScarLedgerSnapshot snapshot) + { + byte[] raw = MessagePackSerializer.Serialize(snapshot); + using var ms = new MemoryStream(); + using (var zlib = new ZLibStream(ms, CompressionLevel.Optimal, leaveOpen: true)) + { + zlib.Write(raw, 0, raw.Length); + } + return ms.ToArray(); + } + + public static ArenaScarLedgerSnapshot DecompressSnapshot(byte[] compressed) + { + using var src = new MemoryStream(compressed); + using var zlib = new ZLibStream(src, CompressionMode.Decompress); + using var dst = new MemoryStream(); + zlib.CopyTo(dst); + return MessagePackSerializer.Deserialize(dst.ToArray()); + } + } + + public static class ArenaScarLedgerStore + { + public static CultDocumentRegistry Registry { get; } = + CultDocumentRegistry.ForTypes(new[] { typeof(ArenaScarLedgerSnapshot) }); + + public static CultRecordKey LedgerKey(string profile = "default") => new("scars:" + profile); + + public static string GetDefaultPath(ArenaMapKind mapKind, string profile = "default") + { + string baseDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + if (string.IsNullOrWhiteSpace(baseDir)) + { + baseDir = AppContext.BaseDirectory; + } + string mapTag = mapKind == ArenaMapKind.Sion ? "sion" : "desert"; + string safeProfile = string.IsNullOrWhiteSpace(profile) ? "default" : profile.Trim(); + return Path.Combine(baseDir, "RustToDust", "scars", $"{mapTag}_scars_{safeProfile}.cultcache"); + } + + public static CultCache Open(string path, bool writable = false) + { + var options = new CultCacheOpenOptions + { + Registry = Registry, + ReadOnly = !writable, + FlushOnDispose = false, + StoreFlushOnDispose = false, + UseDirectoryStore = false + }; + return CultCacheMessagePack.Create(path, options); + } + + public static ArenaScarLedgerSnapshot Load(string path, string expectedAssetFingerprint) + { + if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) + { + return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint }; + } + + try + { + using var cache = Open(path, writable: false); + var records = cache.GetAll().ToArray(); + if (records.Length == 0) + { + return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint }; + } + + var snap = records[0]; + if (!string.IsNullOrEmpty(expectedAssetFingerprint) && + !string.Equals(snap.AssetFingerprint, expectedAssetFingerprint, StringComparison.Ordinal)) + { + return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint }; + } + return snap; + } + catch + { + return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint }; + } + } + + public static void Save(string path, ArenaScarLedgerSnapshot snapshot, string profile = "default") + { + if (snapshot is null) throw new ArgumentNullException(nameof(snapshot)); + if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Path cannot be empty.", nameof(path)); + + string fullPath = Path.GetFullPath(path); + string dir = Path.GetDirectoryName(fullPath) ?? "."; + Directory.CreateDirectory(dir); + + string workspace = fullPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; + string tempFile = Path.Combine(workspace, "scars.cultcache"); + try + { + Directory.CreateDirectory(workspace); + using (var cache = Open(tempFile, writable: true)) + { + cache.UpsertAsync(typeof(ArenaScarLedgerSnapshot), snapshot, LedgerKey(profile)).GetAwaiter().GetResult(); + cache.FlushAsync().GetAwaiter().GetResult(); + } + + if (File.Exists(fullPath)) + { + File.Replace(tempFile, fullPath, null); + } + else + { + File.Move(tempFile, fullPath); + } + } + finally + { + if (Directory.Exists(workspace)) + { + Directory.Delete(workspace, recursive: true); + } + } + } + } +} diff --git a/src/RustToDust.Core/AssetPathResolver.cs b/src/RustToDust.Core/AssetPathResolver.cs new file mode 100644 index 0000000..fc3f730 --- /dev/null +++ b/src/RustToDust.Core/AssetPathResolver.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace RustToDust.Core +{ + public static class AssetPathResolver + { + private static readonly object Gate = new(); + private static string? _explicitAssetsRoot; + + /// + /// Registers an explicit assets root directory (for example, + /// Path.Combine(OS.GetExecutablePath().GetBaseDir(), "assets") in exported Godot builds). + /// Checked after RTD_ASSETS_DIR and before ancestor probing. + /// + public static void RegisterAssetsRoot(string? assetsDirectory) + { + if (string.IsNullOrWhiteSpace(assetsDirectory)) + { + return; + } + + lock (Gate) + { + _explicitAssetsRoot = Path.GetFullPath(assetsDirectory); + } + } + + public static string LocateSubdirectory( + string relativeSubpath, + Func validator, + string missingDescription) + { + string? envRoot = Environment.GetEnvironmentVariable("RTD_ASSETS_DIR"); + if (!string.IsNullOrWhiteSpace(envRoot)) + { + string envCandidate = Path.Combine(envRoot, relativeSubpath); + if (validator(envCandidate)) + { + return Path.GetFullPath(envCandidate); + } + } + + string? registeredRoot; + lock (Gate) + { + registeredRoot = _explicitAssetsRoot; + } + if (!string.IsNullOrWhiteSpace(registeredRoot)) + { + string regCandidate = Path.Combine(registeredRoot, relativeSubpath); + if (validator(regCandidate)) + { + return Path.GetFullPath(regCandidate); + } + } + + foreach (string start in GetProbeStartDirectories()) + { + var dir = new DirectoryInfo(Path.GetFullPath(start)); + while (dir is not null) + { + string candidate = Path.Combine(dir.FullName, "assets", relativeSubpath); + if (validator(candidate)) + { + return Path.GetFullPath(candidate); + } + dir = dir.Parent; + } + } + + throw new DirectoryNotFoundException( + $"Could not locate 'assets/{relativeSubpath.Replace('\\', '/')}' {missingDescription} from BaseDirectory '{AppContext.BaseDirectory}' or CurrentDirectory '{Directory.GetCurrentDirectory()}'."); + } + + public static string LocateAssetsRoot() + { + string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory(); + return Directory.GetParent(vehiclesDir)?.FullName + ?? throw new DirectoryNotFoundException($"Could not locate assets parent directory of '{vehiclesDir}'."); + } + + private static IEnumerable GetProbeStartDirectories() + { + string? processDir = !string.IsNullOrWhiteSpace(Environment.ProcessPath) + ? Path.GetDirectoryName(Environment.ProcessPath) + : null; + + foreach (string? start in new[] { AppContext.BaseDirectory, processDir, Directory.GetCurrentDirectory() }) + { + if (!string.IsNullOrWhiteSpace(start) && Directory.Exists(start)) + { + yield return start; + } + } + } + } +} diff --git a/src/RustToDust.Core/Audio/PcmSynth.cs b/src/RustToDust.Core/Audio/PcmSynth.cs new file mode 100644 index 0000000..5ecd11d --- /dev/null +++ b/src/RustToDust.Core/Audio/PcmSynth.cs @@ -0,0 +1,972 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace RustToDust.Core.Audio +{ + public enum ProceduralCueId + { + FootstepHeavyThud, + FootstepMedStep, + FootstepLightStep, + LoopEngineWheeled, + LoopEngineTracked, + LoopEngineHover, + LoopRotorVtol, + LoopMechServo, + ImpactRicochet, + ImpactArmorCrunch, + ImpactCore, + ImpactExplosion, + UiHitArmor, + UiHitCore, + UiHitKill, + UiOverheatAlarm, + UiPickupModule, + UiPickupImperial, + PodRetroBurnLoop, + PodSlamImpact, + PodPetalBlow, + UiDropWaveKlaxon + } + + public sealed record PcmClipData( + string Key, + ProceduralCueId CueId, + bool IsLoop, + int SampleRate, + float[] Samples, + byte[] Pcm16Bytes, + int DrySampleCount); + + public readonly record struct WavPcmInfo( + int SampleRate, + int Channels, + int BitsPerSample, + byte[] PcmBytes, + float[] FloatSamples); + + public static class WavFileReader + { + public static WavPcmInfo ReadMonoOrStereo16(string path) + { + byte[] raw = File.ReadAllBytes(path); + return Parse(raw, path); + } + + public static WavPcmInfo Parse(ReadOnlySpan raw, string sourceLabel = "") + { + if (raw.Length < 44) + { + throw new InvalidDataException($"WAV '{sourceLabel}' too short ({raw.Length} bytes)."); + } + if (Encoding.ASCII.GetString(raw[0..4]) != "RIFF" || + Encoding.ASCII.GetString(raw[8..12]) != "WAVE") + { + throw new InvalidDataException($"WAV '{sourceLabel}' missing RIFF/WAVE header."); + } + + int offset = 12; + bool hasFmt = false; + bool hasData = false; + int audioFormat = 0; + int channels = 0; + int sampleRate = 0; + int bitsPerSample = 0; + byte[] pcmBytes = Array.Empty(); + + while (offset + 8 <= raw.Length) + { + string chunkId = Encoding.ASCII.GetString(raw.Slice(offset, 4)); + int chunkSize = BitConverter.ToInt32(raw.Slice(offset + 4, 4)); + int dataStart = offset + 8; + if (chunkSize < 0 || dataStart + chunkSize > raw.Length) + { + throw new InvalidDataException($"WAV '{sourceLabel}' has invalid chunk '{chunkId}' size {chunkSize}."); + } + + if (chunkId == "fmt ") + { + if (chunkSize < 16) + { + throw new InvalidDataException($"WAV '{sourceLabel}' fmt chunk too small ({chunkSize})."); + } + audioFormat = BitConverter.ToUInt16(raw.Slice(dataStart, 2)); + channels = BitConverter.ToUInt16(raw.Slice(dataStart + 2, 2)); + sampleRate = BitConverter.ToInt32(raw.Slice(dataStart + 4, 4)); + bitsPerSample = BitConverter.ToUInt16(raw.Slice(dataStart + 14, 2)); + hasFmt = true; + } + else if (chunkId == "data") + { + pcmBytes = raw.Slice(dataStart, chunkSize).ToArray(); + hasData = true; + } + + int paddedSize = chunkSize + (chunkSize & 1); + offset = dataStart + paddedSize; + } + + if (!hasFmt || !hasData) + { + throw new InvalidDataException($"WAV '{sourceLabel}' missing fmt or data chunk."); + } + if (audioFormat != 1 || bitsPerSample != 16) + { + throw new InvalidDataException($"WAV '{sourceLabel}' must be 16-bit PCM (got fmt={audioFormat}, bits={bitsPerSample})."); + } + + int sampleCount = pcmBytes.Length / 2; + var floats = new float[sampleCount]; + for (int i = 0; i < sampleCount; i++) + { + short s = BitConverter.ToInt16(pcmBytes, i * 2); + floats[i] = s / 32768f; + } + + return new WavPcmInfo(sampleRate, channels, bitsPerSample, pcmBytes, floats); + } + } + + /// + /// Pure-C# deterministic 44.1 kHz mono PCM synthesizer with a cleanly separable + /// wetMixMode room/saturation post-stage. Zero Godot dependency so xUnit + /// and headless client tests validate the exact same waveforms. + /// + public static class PcmSynth + { + public const int SampleRate = 44100; + private const float MaxSafePeak = 0.92f; + + private static readonly (ProceduralCueId Cue, string Key)[] AllCues = + { + (ProceduralCueId.FootstepHeavyThud, "footstep_heavy_thud"), + (ProceduralCueId.FootstepMedStep, "footstep_med_step"), + (ProceduralCueId.FootstepLightStep, "footstep_light_step"), + (ProceduralCueId.LoopEngineWheeled, "loop_engine_wheeled"), + (ProceduralCueId.LoopEngineTracked, "loop_engine_tracked"), + (ProceduralCueId.LoopEngineHover, "loop_engine_hover"), + (ProceduralCueId.LoopRotorVtol, "loop_rotor_vtol"), + (ProceduralCueId.LoopMechServo, "loop_mech_servo"), + (ProceduralCueId.ImpactRicochet, "impact_ricochet"), + (ProceduralCueId.ImpactArmorCrunch, "impact_armor_crunch"), + (ProceduralCueId.ImpactCore, "impact_core"), + (ProceduralCueId.ImpactExplosion, "impact_explosion"), + (ProceduralCueId.UiHitArmor, "ui_hit_armor"), + (ProceduralCueId.UiHitCore, "ui_hit_core"), + (ProceduralCueId.UiHitKill, "ui_hit_kill"), + (ProceduralCueId.UiOverheatAlarm, "ui_overheat_alarm"), + (ProceduralCueId.UiPickupModule, "ui_pickup_module"), + (ProceduralCueId.UiPickupImperial, "ui_pickup_imperial"), + (ProceduralCueId.PodRetroBurnLoop, "pod_retro_burn"), + (ProceduralCueId.PodSlamImpact, "pod_slam"), + (ProceduralCueId.PodPetalBlow, "pod_petal_pop"), + (ProceduralCueId.UiDropWaveKlaxon, "ui_drop_wave") + }; + + public static IReadOnlyList<(ProceduralCueId Cue, string Key)> CueRegistry => AllCues; + + public static Dictionary SynthesizeAll(bool wetMixMode = true) + { + var dict = new Dictionary(AllCues.Length, StringComparer.OrdinalIgnoreCase); + for (int i = 0; i < AllCues.Length; i++) + { + var clip = Synthesize(AllCues[i].Cue, wetMixMode); + dict[clip.Key] = clip; + } + return dict; + } + + public static PcmClipData Synthesize(ProceduralCueId cue, bool wetMixMode = true) + { + GenerateDry(cue, out float[] dry, out bool isLoop, out string key); + int dryLen = dry.Length; + + float[] finalSamples; + if (wetMixMode) + { + finalSamples = ApplyWetRoomStage(dry, isLoop); + } + else + { + finalSamples = dry; + ClampNormalizePeak(finalSamples, MaxSafePeak); + } + + byte[] pcmBytes = FloatToPcm16(finalSamples); + return new PcmClipData(key, cue, isLoop, SampleRate, finalSamples, pcmBytes, dryLen); + } + + public static float[] ApplyWetRoomStage(ReadOnlySpan dry, bool isLoop) + { + if (isLoop) + { + return ApplyWetRoomLoop(dry); + } + + const int tailSamples = (int)(0.20f * SampleRate); + int outLen = dry.Length + tailSamples; + var wet = new float[outLen]; + + // Early reflections (11ms, 19ms, 29ms, 43ms) + ReadOnlySpan tapDelays = stackalloc int[] { 485, 838, 1279, 1896 }; + ReadOnlySpan tapGains = stackalloc float[] { 0.30f, -0.24f, 0.19f, -0.14f }; + + // 4-comb Schroeder/Moorer diffused room tail with one-pole damping + ReadOnlySpan combDelays = stackalloc int[] { 1327, 1621, 1949, 2269 }; + ReadOnlySpan combGains = stackalloc float[] { 0.72f, 0.69f, 0.66f, 0.63f }; + + var combBuf0 = new float[combDelays[0]]; + var combBuf1 = new float[combDelays[1]]; + var combBuf2 = new float[combDelays[2]]; + var combBuf3 = new float[combDelays[3]]; + int idx0 = 0, idx1 = 0, idx2 = 0, idx3 = 0; + float lp0 = 0f, lp1 = 0f, lp2 = 0f, lp3 = 0f; + + const int apDelay = 347; + var apBuf = new float[apDelay]; + int apIdx = 0; + + for (int i = 0; i < outLen; i++) + { + float d = i < dry.Length ? dry[i] : 0f; + + float early = 0f; + for (int t = 0; t < tapDelays.Length; t++) + { + int srcIdx = i - tapDelays[t]; + if (srcIdx >= 0 && srcIdx < dry.Length) + { + early += dry[srcIdx] * tapGains[t]; + } + } + + float c0 = combBuf0[idx0]; + lp0 = lp0 * 0.42f + c0 * 0.58f; + combBuf0[idx0] = d + lp0 * combGains[0]; + idx0 = (idx0 + 1) % combDelays[0]; + + float c1 = combBuf1[idx1]; + lp1 = lp1 * 0.42f + c1 * 0.58f; + combBuf1[idx1] = d + lp1 * combGains[1]; + idx1 = (idx1 + 1) % combDelays[1]; + + float c2 = combBuf2[idx2]; + lp2 = lp2 * 0.42f + c2 * 0.58f; + combBuf2[idx2] = d + lp2 * combGains[2]; + idx2 = (idx2 + 1) % combDelays[2]; + + float c3 = combBuf3[idx3]; + lp3 = lp3 * 0.42f + c3 * 0.58f; + combBuf3[idx3] = d + lp3 * combGains[3]; + idx3 = (idx3 + 1) % combDelays[3]; + + float combSum = (c0 + c1 + c2 + c3) * 0.25f; + + // Allpass diffusion + float apOut = apBuf[apIdx]; + float apIn = combSum + apOut * 0.45f; + apBuf[apIdx] = apIn; + float diffused = apOut - apIn * 0.45f; + apIdx = (apIdx + 1) % apDelay; + + float mixed = d * 0.92f + early * 0.46f + diffused * 0.44f; + wet[i] = MathF.Tanh(mixed * 1.12f); + } + + // Smooth 16ms cosine fade on very end of tail so no abrupt cut + int fadeLen = Math.Min(tailSamples, (int)(0.016f * SampleRate)); + int fadeStart = outLen - fadeLen; + for (int i = 0; i < fadeLen; i++) + { + float g = 0.5f * (1f + MathF.Cos(MathF.PI * (i + 1) / fadeLen)); + wet[fadeStart + i] *= g; + } + + ClampNormalizePeak(wet, MaxSafePeak); + return wet; + } + + private static float[] ApplyWetRoomLoop(ReadOnlySpan dry) + { + int len = dry.Length; + var wet = new float[len]; + + // Circular early reflections + 2-tap circular diffusion preserve exact periodicity at wrap (sample N-1 -> 0) + ReadOnlySpan taps = stackalloc int[] { 331, 617, 1019, 1511 }; + ReadOnlySpan gains = stackalloc float[] { 0.16f, -0.12f, 0.09f, -0.06f }; + + float lp = 0f; + for (int pass = 0; pass < 2; pass++) + { + for (int i = 0; i < len; i++) + { + float d = dry[i]; + float room = 0f; + for (int t = 0; t < taps.Length; t++) + { + int src = (i - taps[t] + len) % len; + room += dry[src] * gains[t]; + } + lp = lp * 0.65f + room * 0.35f; + float mixed = d * 0.90f + room * 0.55f + lp * 0.40f; + wet[i] = MathF.Tanh(mixed * 1.08f); + } + } + + ClampNormalizePeak(wet, MaxSafePeak); + return wet; + } + + private static void GenerateDry(ProceduralCueId cue, out float[] buf, out bool isLoop, out string key) + { + switch (cue) + { + case ProceduralCueId.FootstepHeavyThud: + key = "footstep_heavy_thud"; + isLoop = false; + buf = GenFootstep(durSec: 0.38f, fStart: 88f, fEnd: 32f, clackFreq: 380f, clackMix: 0.22f, gravelMix: 0.34f, seed: 101u); + break; + case ProceduralCueId.FootstepMedStep: + key = "footstep_med_step"; + isLoop = false; + buf = GenFootstep(durSec: 0.30f, fStart: 112f, fEnd: 40f, clackFreq: 520f, clackMix: 0.28f, gravelMix: 0.28f, seed: 102u); + break; + case ProceduralCueId.FootstepLightStep: + key = "footstep_light_step"; + isLoop = false; + buf = GenFootstep(durSec: 0.24f, fStart: 135f, fEnd: 48f, clackFreq: 690f, clackMix: 0.36f, gravelMix: 0.22f, seed: 103u); + break; + case ProceduralCueId.LoopEngineWheeled: + key = "loop_engine_wheeled"; + isLoop = true; + buf = GenLoopWheeled(); + break; + case ProceduralCueId.LoopEngineTracked: + key = "loop_engine_tracked"; + isLoop = true; + buf = GenLoopTracked(); + break; + case ProceduralCueId.LoopEngineHover: + key = "loop_engine_hover"; + isLoop = true; + buf = GenLoopHover(); + break; + case ProceduralCueId.LoopRotorVtol: + key = "loop_rotor_vtol"; + isLoop = true; + buf = GenLoopVtol(); + break; + case ProceduralCueId.LoopMechServo: + key = "loop_mech_servo"; + isLoop = true; + buf = GenLoopServo(); + break; + case ProceduralCueId.ImpactRicochet: + key = "impact_ricochet"; + isLoop = false; + buf = GenRicochet(); + break; + case ProceduralCueId.ImpactArmorCrunch: + key = "impact_armor_crunch"; + isLoop = false; + buf = GenArmorCrunch(); + break; + case ProceduralCueId.ImpactCore: + key = "impact_core"; + isLoop = false; + buf = GenCoreImpact(); + break; + case ProceduralCueId.ImpactExplosion: + key = "impact_explosion"; + isLoop = false; + buf = GenExplosion(); + break; + case ProceduralCueId.UiHitArmor: + key = "ui_hit_armor"; + isLoop = false; + buf = GenUiHitArmor(); + break; + case ProceduralCueId.UiHitCore: + key = "ui_hit_core"; + isLoop = false; + buf = GenUiHitCore(); + break; + case ProceduralCueId.UiHitKill: + key = "ui_hit_kill"; + isLoop = false; + buf = GenUiHitKill(); + break; + case ProceduralCueId.UiOverheatAlarm: + key = "ui_overheat_alarm"; + isLoop = false; + buf = GenUiOverheatAlarm(); + break; + case ProceduralCueId.UiPickupModule: + key = "ui_pickup_module"; + isLoop = false; + buf = GenUiPickupModule(); + break; + case ProceduralCueId.UiPickupImperial: + key = "ui_pickup_imperial"; + isLoop = false; + buf = GenUiPickupImperial(); + break; + case ProceduralCueId.PodRetroBurnLoop: + key = "pod_retro_burn"; + isLoop = true; + buf = GenPodRetroBurnLoop(); + break; + case ProceduralCueId.PodSlamImpact: + key = "pod_slam"; + isLoop = false; + buf = GenPodSlamImpact(); + break; + case ProceduralCueId.PodPetalBlow: + key = "pod_petal_pop"; + isLoop = false; + buf = GenPodPetalBlow(); + break; + case ProceduralCueId.UiDropWaveKlaxon: + key = "ui_drop_wave"; + isLoop = false; + buf = GenUiDropWaveKlaxon(); + break; + default: + throw new ArgumentOutOfRangeException(nameof(cue), cue, null); + } + } + + private static float[] GenFootstep( + float durSec, + float fStart, + float fEnd, + float clackFreq, + float clackMix, + float gravelMix, + uint seed) + { + int n = (int)(durSec * SampleRate); + var s = new float[n]; + uint rng = seed; + float phase = 0f; + float lp = 0f; + float hpPrev = 0f; + float hpOut = 0f; + + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float envAttack = MathF.Min(1f, t / 0.004f); + float subEnv = envAttack * MathF.Exp(-t * (10.5f / durSec * 0.38f)); + float freq = fEnd + (fStart - fEnd) * MathF.Exp(-t * 28f); + phase += MathF.Tau * freq / SampleRate; + float sub = MathF.Sin(phase) * subEnv; + + float clackEnv = envAttack * MathF.Exp(-t * 48f); + float clack = (MathF.Sin(MathF.Tau * clackFreq * t) + 0.5f * MathF.Sin(MathF.Tau * clackFreq * 1.47f * t)) * clackEnv; + + float white = NextSignedNoise(ref rng); + lp = lp * 0.84f + white * 0.16f; + hpOut = 0.90f * (hpOut + lp - hpPrev); + hpPrev = lp; + float gravelEnv = envAttack * MathF.Exp(-t * 16f); + float damperHiss = white * 0.12f * MathF.Exp(-t * 11f); + + float fadeOut = u > 0.85f ? (1f - (u - 0.85f) / 0.15f) : 1f; + s[i] = (sub * 0.82f + clack * clackMix + hpOut * gravelMix + damperHiss) * fadeOut; + } + NormalizePeak(s, 0.86f); + return s; + } + + private static float[] GenLoopWheeled() + { + int n = SampleRate; + var s = new float[n]; + float[] noise = GeneratePeriodicFilteredNoise(n, 0x201u, lpAlpha: 0.06f); + for (int i = 0; i < n; i++) + { + float t = i / (float)n; + // Integer harmonic cosines -> exact 1.000s periodicity with zero-slope wrap + float baseOsc = + MathF.Cos(MathF.Tau * 42f * t) * 0.48f + + MathF.Cos(MathF.Tau * 84f * t) * 0.30f + + MathF.Cos(MathF.Tau * 126f * t) * 0.18f + + MathF.Cos(MathF.Tau * 168f * t) * 0.10f; + float lfo = 0.82f + 0.18f * MathF.Cos(MathF.Tau * 14f * t); + s[i] = baseOsc * lfo + noise[i] * 0.22f; + } + NormalizePeak(s, 0.78f); + return s; + } + + private static float[] GenLoopTracked() + { + int n = SampleRate; + var s = new float[n]; + float[] noise = GeneratePeriodicFilteredNoise(n, 0x202u, lpAlpha: 0.10f); + for (int i = 0; i < n; i++) + { + float t = i / (float)n; + float diesel = + MathF.Cos(MathF.Tau * 32f * t) * 0.52f + + MathF.Cos(MathF.Tau * 64f * t) * 0.34f + + MathF.Cos(MathF.Tau * 96f * t) * 0.20f + + MathF.Cos(MathF.Tau * 160f * t) * 0.10f; + float treadMod = 0.5f + 0.5f * MathF.Cos(MathF.Tau * 18f * t); + float treadClick = MathF.Pow(treadMod, 4f) * MathF.Cos(MathF.Tau * 240f * t) * 0.22f; + s[i] = diesel * (0.85f + 0.15f * treadMod) + treadClick + noise[i] * 0.25f; + } + NormalizePeak(s, 0.80f); + return s; + } + + private static float[] GenLoopHover() + { + int n = SampleRate; + var s = new float[n]; + float[] noise = GeneratePeriodicFilteredNoise(n, 0x203u, lpAlpha: 0.20f); + for (int i = 0; i < n; i++) + { + float t = i / (float)n; + float turbine = + MathF.Cos(MathF.Tau * 55f * t) * 0.36f + + MathF.Cos(MathF.Tau * 110f * t) * 0.26f + + MathF.Cos(MathF.Tau * 220f * t) * 0.14f; + s[i] = turbine + noise[i] * 0.28f; + } + NormalizePeak(s, 0.72f); + return s; + } + + private static float[] GenLoopVtol() + { + int n = SampleRate; + var s = new float[n]; + float[] noise = GeneratePeriodicFilteredNoise(n, 0x204u, lpAlpha: 0.15f); + for (int i = 0; i < n; i++) + { + float t = i / (float)n; + float chop = 0.55f + 0.45f * MathF.Cos(MathF.Tau * 16f * t); + float thump = MathF.Cos(MathF.Tau * 32f * t) * 0.40f + MathF.Cos(MathF.Tau * 64f * t) * 0.24f; + float whine = MathF.Cos(MathF.Tau * 210f * t) * 0.24f + MathF.Cos(MathF.Tau * 420f * t) * 0.10f; + s[i] = (thump + noise[i] * 0.42f) * chop + whine; + } + NormalizePeak(s, 0.80f); + return s; + } + + private static float[] GenLoopServo() + { + int n = SampleRate; + var s = new float[n]; + float[] noise = GeneratePeriodicFilteredNoise(n, 0x205u, lpAlpha: 0.28f); + for (int i = 0; i < n; i++) + { + float t = i / (float)n; + float hum = + MathF.Cos(MathF.Tau * 140f * t) * 0.34f + + MathF.Cos(MathF.Tau * 280f * t) * 0.26f + + MathF.Cos(MathF.Tau * 420f * t) * 0.10f; + float pulse = 0.88f + 0.12f * MathF.Cos(MathF.Tau * 6f * t); + s[i] = hum * pulse + noise[i] * 0.24f; + } + NormalizePeak(s, 0.74f); + return s; + } + + private static float[] GenRicochet() + { + int n = (int)(0.22f * SampleRate); + var s = new float[n]; + float p1 = 0f; + float p2 = 0f; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float attack = MathF.Min(1f, t / 0.002f); + float env = attack * MathF.Exp(-t * 18f); + float f1 = 1650f + 420f * MathF.Exp(-t * 32f); + float f2 = 2480f + 580f * MathF.Exp(-t * 28f); + float fm = MathF.Sin(MathF.Tau * 410f * t) * 0.35f * MathF.Exp(-t * 20f); + p1 += MathF.Tau * f1 / SampleRate; + p2 += MathF.Tau * f2 / SampleRate; + float fadeOut = u > 0.82f ? (1f - (u - 0.82f) / 0.18f) : 1f; + s[i] = (MathF.Sin(p1 + fm) * 0.58f + MathF.Sin(p2) * 0.42f) * env * fadeOut; + } + NormalizePeak(s, 0.82f); + return s; + } + + private static float[] GenArmorCrunch() + { + int n = (int)(0.30f * SampleRate); + var s = new float[n]; + uint rng = 0x302u; + float phase = 0f; + float lp = 0f; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float attack = MathF.Min(1f, t / 0.003f); + float freq = 52f + 88f * MathF.Exp(-t * 30f); + phase += MathF.Tau * freq / SampleRate; + float body = MathF.Sin(phase) * MathF.Exp(-t * 14f); + float clang = (MathF.Sin(MathF.Tau * 610f * t) + 0.6f * MathF.Sin(MathF.Tau * 945f * t)) * MathF.Exp(-t * 26f); + float white = NextSignedNoise(ref rng); + lp = lp * 0.78f + white * 0.22f; + float crunch = lp * MathF.Exp(-t * 17f); + float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f; + s[i] = attack * (body * 0.68f + clang * 0.28f + crunch * 0.55f) * fadeOut; + } + NormalizePeak(s, 0.86f); + return s; + } + + private static float[] GenCoreImpact() + { + int n = (int)(0.34f * SampleRate); + var s = new float[n]; + uint rng = 0x303u; + float phase = 0f; + float lp = 0f; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float attack = MathF.Min(1f, t / 0.0025f); + float freq = 38f + 72f * MathF.Exp(-t * 24f); + phase += MathF.Tau * freq / SampleRate; + float punch = MathF.Sin(phase) * MathF.Exp(-t * 11f); + float snap = MathF.Sin(MathF.Tau * 1180f * t) * MathF.Exp(-t * 34f); + float white = NextSignedNoise(ref rng); + lp = lp * 0.82f + white * 0.18f; + float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f; + s[i] = attack * (punch * 0.76f + snap * 0.34f + lp * 0.45f * MathF.Exp(-t * 14f)) * fadeOut; + } + NormalizePeak(s, 0.88f); + return s; + } + + private static float[] GenExplosion() + { + int n = (int)(1.15f * SampleRate); + var s = new float[n]; + uint rng = 0x304u; + float phase = 0f; + float lp = 0f; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float attack = MathF.Min(1f, t / 0.006f); + float freq = 22f + 43f * MathF.Exp(-t * 9f); + phase += MathF.Tau * freq / SampleRate; + float sub = MathF.Sin(phase) * MathF.Exp(-t * 3.8f); + float white = NextSignedNoise(ref rng); + lp = lp * 0.88f + white * 0.12f; + float roar = lp * MathF.Exp(-t * 3.1f); + float crackle = white * 0.25f * MathF.Exp(-t * 9.5f); + float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f; + s[i] = attack * (sub * 0.70f + roar * 0.78f + crackle) * fadeOut; + } + NormalizePeak(s, 0.88f); + return s; + } + + private static float[] GenUiHitArmor() + { + int n = (int)(0.07f * SampleRate); + var s = new float[n]; + uint rng = 0x401u; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float env = MathF.Min(1f, t / 0.0015f) * MathF.Exp(-t * 58f); + float tone = MathF.Sin(MathF.Tau * 1380f * t) * 0.65f + MathF.Sin(MathF.Tau * 2240f * t) * 0.35f; + float tick = NextSignedNoise(ref rng) * 0.30f * MathF.Exp(-t * 90f); + float fadeOut = u > 0.78f ? (1f - (u - 0.78f) / 0.22f) : 1f; + s[i] = (tone * env + tick) * fadeOut; + } + NormalizePeak(s, 0.80f); + return s; + } + + private static float[] GenUiHitCore() + { + int n = (int)(0.11f * SampleRate); + var s = new float[n]; + uint rng = 0x402u; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float env = MathF.Min(1f, t / 0.0015f) * MathF.Exp(-t * 36f); + float tone = + MathF.Sin(MathF.Tau * 420f * t) * 0.50f + + MathF.Sin(MathF.Tau * 1080f * t) * 0.45f + + MathF.Sin(MathF.Tau * 1760f * t) * 0.25f; + float crunch = NextSignedNoise(ref rng) * 0.25f * MathF.Exp(-t * 60f); + float fadeOut = u > 0.80f ? (1f - (u - 0.80f) / 0.20f) : 1f; + s[i] = (tone * env + crunch) * fadeOut; + } + NormalizePeak(s, 0.84f); + return s; + } + + private static float[] GenUiHitKill() + { + int n = (int)(0.22f * SampleRate); + var s = new float[n]; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float g1 = MathF.Min(1f, t / 0.002f) * MathF.Exp(-t * 24f); + float t2 = t - 0.075f; + float g2 = t2 >= 0f ? MathF.Min(1f, t2 / 0.002f) * MathF.Exp(-t2 * 18f) : 0f; + float tone1 = MathF.Sin(MathF.Tau * 740f * t) + 0.35f * MathF.Sin(MathF.Tau * 1480f * t); + float tone2 = t2 >= 0f ? (MathF.Sin(MathF.Tau * 1110f * t2) + 0.35f * MathF.Sin(MathF.Tau * 2220f * t2)) : 0f; + float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f; + s[i] = (tone1 * g1 * 0.55f + tone2 * g2 * 0.65f) * fadeOut; + } + NormalizePeak(s, 0.85f); + return s; + } + + private static float[] GenUiOverheatAlarm() + { + int n = (int)(0.42f * SampleRate); + var s = new float[n]; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + // Dual-pulse cockpit buzzer + float pulseA = (t < 0.16f) ? MathF.Sin(MathF.PI * (t / 0.16f)) : 0f; + float tB = t - 0.21f; + float pulseB = (tB >= 0f && tB < 0.17f) ? MathF.Sin(MathF.PI * (tB / 0.17f)) : 0f; + float env = pulseA + pulseB; + float wave = + MathF.Sin(MathF.Tau * 880f * t) * 0.55f + + MathF.Sin(MathF.Tau * 1175f * t) * 0.45f; + float fadeOut = u > 0.90f ? (1f - (u - 0.90f) / 0.10f) : 1f; + s[i] = wave * env * fadeOut; + } + NormalizePeak(s, 0.78f); + return s; + } + + private static float[] GenUiPickupModule() + { + int n = (int)(0.18f * SampleRate); + var s = new float[n]; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float clunk = MathF.Sin(MathF.Tau * 240f * t) * MathF.Min(1f, t / 0.002f) * MathF.Exp(-t * 32f); + float t2 = t - 0.055f; + float latch = t2 >= 0f + ? (MathF.Sin(MathF.Tau * 580f * t2) + 0.4f * MathF.Sin(MathF.Tau * 870f * t2)) * MathF.Min(1f, t2 / 0.002f) * MathF.Exp(-t2 * 26f) + : 0f; + float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f; + s[i] = (clunk * 0.65f + latch * 0.55f) * fadeOut; + } + NormalizePeak(s, 0.82f); + return s; + } + + private static float[] GenUiPickupImperial() + { + int n = (int)(0.28f * SampleRate); + var s = new float[n]; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float e1 = MathF.Min(1f, t / 0.003f) * MathF.Exp(-t * 13f); + float t2 = t - 0.055f; + float e2 = t2 >= 0f ? MathF.Min(1f, t2 / 0.003f) * MathF.Exp(-t2 * 12f) : 0f; + float c1 = MathF.Sin(MathF.Tau * 880f * t) + 0.3f * MathF.Sin(MathF.Tau * 1760f * t); + float c2 = t2 >= 0f ? (MathF.Sin(MathF.Tau * 1320f * t2) + 0.35f * MathF.Sin(MathF.Tau * 2640f * t2)) : 0f; + float fadeOut = u > 0.86f ? (1f - (u - 0.86f) / 0.14f) : 1f; + s[i] = (c1 * e1 * 0.48f + c2 * e2 * 0.56f) * fadeOut; + } + NormalizePeak(s, 0.82f); + return s; + } + + private static float[] GenPodRetroBurnLoop() + { + int n = SampleRate; + float[] rumbleNoise = GeneratePeriodicFilteredNoise(n, 0xA17C9311u, lpAlpha: 0.08f); + float[] jetRoar = GeneratePeriodicFilteredNoise(n, 0x55E2B409u, lpAlpha: 0.12f); + var s = new float[n]; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float pulse = 1f + 0.14f * MathF.Sin(MathF.Tau * 19f * t); + float sub = 0.34f * MathF.Sin(MathF.Tau * 46f * t) + 0.22f * MathF.Sin(MathF.Tau * 73f * t); + float turbine = 0.10f * MathF.Sin(MathF.Tau * 184f * t); + s[i] = (sub + turbine + rumbleNoise[i] * 1.85f + jetRoar[i] * 1.35f) * pulse; + } + NormalizePeak(s, 0.84f); + return s; + } + + private static float[] GenPodSlamImpact() + { + int n = (int)(0.62f * SampleRate); + var s = new float[n]; + uint rng = 0x3D18A275u; + float lp = 0f; + float phase = 0f; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float freq = 26f + 98f * MathF.Exp(-t * 28f); + phase += MathF.Tau * freq / SampleRate; + float sub = MathF.Sin(phase) * MathF.Exp(-t * 6.8f); + float white = NextSignedNoise(ref rng); + lp = lp * 0.84f + white * 0.16f; + float crunch = (white * 0.25f + lp * 1.4f) * MathF.Exp(-t * 9.5f); + float bell = (MathF.Sin(MathF.Tau * 210f * t) + 0.45f * MathF.Sin(MathF.Tau * 335f * t)) * MathF.Exp(-t * 14f); + float attack = MathF.Min(1f, t / 0.002f); + float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f; + s[i] = (sub * 0.85f + crunch * 0.55f + bell * 0.26f) * attack * fadeOut; + } + NormalizePeak(s, 0.88f); + return s; + } + + private static float[] GenPodPetalBlow() + { + int n = (int)(0.42f * SampleRate); + var s = new float[n]; + uint rng = 0x71B4C20Eu; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float boltSnap = MathF.Sin(MathF.Tau * (940f - 520f * MathF.Min(1f, t * 14f)) * t) * MathF.Exp(-t * 36f); + float clang = (MathF.Sin(MathF.Tau * 412f * t) + 0.6f * MathF.Sin(MathF.Tau * 685f * t)) * MathF.Exp(-t * 16f); + float hiss = NextSignedNoise(ref rng) * MathF.Exp(-t * 12f); + float attack = MathF.Min(1f, t / 0.0015f); + float fadeOut = u > 0.82f ? (1f - (u - 0.82f) / 0.18f) : 1f; + s[i] = (boltSnap * 0.55f + clang * 0.45f + hiss * 0.48f) * attack * fadeOut; + } + NormalizePeak(s, 0.84f); + return s; + } + + private static float[] GenUiDropWaveKlaxon() + { + int n = (int)(0.54f * SampleRate); + var s = new float[n]; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float e1 = MathF.Min(1f, t / 0.006f) * MathF.Exp(-t * 8.5f); + float t2 = t - 0.18f; + float e2 = t2 >= 0f ? MathF.Min(1f, t2 / 0.006f) * MathF.Exp(-t2 * 7.5f) : 0f; + float horn1 = MathF.Sin(MathF.Tau * 392f * t) + 0.42f * MathF.Sin(MathF.Tau * 588f * t); + float horn2 = t2 >= 0f ? (MathF.Sin(MathF.Tau * 523.25f * t2) + 0.42f * MathF.Sin(MathF.Tau * 784.88f * t2)) : 0f; + float fadeOut = u > 0.86f ? (1f - (u - 0.86f) / 0.14f) : 1f; + s[i] = (horn1 * e1 * 0.48f + horn2 * e2 * 0.54f) * fadeOut; + } + NormalizePeak(s, 0.82f); + return s; + } + + private static float[] GeneratePeriodicFilteredNoise(int n, uint seed, float lpAlpha) + { + int fade = Math.Min(2048, n / 4); + var raw = new float[n + fade]; + uint rng = seed; + float lp = 0f; + float lp2 = 0f; + float smooth = Math.Clamp(lpAlpha, 0.02f, 0.12f); + for (int i = 0; i < raw.Length; i++) + { + float white = NextSignedNoise(ref rng); + lp = lp * (1f - smooth) + white * smooth; + lp2 = lp2 * 0.90f + lp * 0.10f; + raw[i] = lp2; + } + var result = new float[n]; + Array.Copy(raw, result, n); + for (int i = 0; i < fade; i++) + { + float w = i / (float)fade; + result[i] = raw[i] * w + raw[n + i] * (1f - w); + } + return result; + } + + private static float NextSignedNoise(ref uint state) + { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + return ((state & 0xFFFFu) / 32767.5f) - 1f; + } + + private static void NormalizePeak(float[] samples, float targetPeak) + { + float peak = 0f; + for (int i = 0; i < samples.Length; i++) + { + float a = MathF.Abs(samples[i]); + if (a > peak) peak = a; + } + if (peak > 1e-6f) + { + float scale = targetPeak / peak; + for (int i = 0; i < samples.Length; i++) + { + samples[i] *= scale; + } + } + } + + private static void ClampNormalizePeak(float[] samples, float maxPeak) + { + float peak = 0f; + for (int i = 0; i < samples.Length; i++) + { + float a = MathF.Abs(samples[i]); + if (a > peak) peak = a; + } + if (peak > maxPeak && peak > 1e-6f) + { + float scale = maxPeak / peak; + for (int i = 0; i < samples.Length; i++) + { + samples[i] *= scale; + } + } + } + + private static byte[] FloatToPcm16(ReadOnlySpan samples) + { + var bytes = new byte[samples.Length * 2]; + for (int i = 0; i < samples.Length; i++) + { + float clamped = Math.Clamp(samples[i], -1f, 1f); + short val = (short)MathF.Round(clamped * 32767f); + bytes[i * 2] = (byte)(val & 0xFF); + bytes[i * 2 + 1] = (byte)((val >> 8) & 0xFF); + } + return bytes; + } + } +} diff --git a/src/RustToDust.Core/Broadcast.cs b/src/RustToDust.Core/Broadcast.cs new file mode 100644 index 0000000..d4ddd23 --- /dev/null +++ b/src/RustToDust.Core/Broadcast.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; + +namespace RustToDust.Core +{ + public enum BroadcastKind + { + MatchStart, + TouristPull, + ExemplarWakeup, + PatronClearance, + ChassisSwap, + QuickBolt, + Overheat, + Elimination, + Victory, + DropWave + } + + public readonly record struct BroadcastLine(float Timestamp, BroadcastKind Kind, string Text); + + public sealed class BroadcastFeed + { + private const int MaxLines = 32; + private readonly List _lines = new(); + + public IReadOnlyList Lines => _lines; + public BroadcastLine? Latest => _lines.Count > 0 ? _lines[_lines.Count - 1] : null; + public long Version { get; private set; } + public event Action? LineEmitted; + + public void Emit(float timestamp, BroadcastKind kind, string text) + { + if (_lines.Count >= MaxLines) + { + _lines.RemoveAt(0); + } + var line = new BroadcastLine(timestamp, kind, text); + _lines.Add(line); + Version++; + LineEmitted?.Invoke(line); + } + + public void EmitMatchStart(float timestamp, ArenaMapKind mapKind = ArenaMapKind.Desert) => + Emit(timestamp, BroadcastKind.MatchStart, + mapKind == ArenaMapKind.Sion + ? "Imperial Broadcast opens the alpine ring over Sion. Twelve unvarnished rigs enter for the gallery's amusement." + : "Imperial Broadcast opens the desert ring. Twelve unvarnished rigs enter for the gallery's amusement."); + + public void EmitTouristPull(float timestamp, int contenderId) => + Emit(timestamp, BroadcastKind.TouristPull, + $"Contender {contenderId + 1:00} fires on a gilded tourist — crude, lucrative, and deeply impolite."); + + public void EmitExemplarWakeup(float timestamp, int contenderId) => + Emit(timestamp, BroadcastKind.ExemplarWakeup, + $"An ornate exemplar accepts the provocation of Contender {contenderId + 1:00}. The gallery hushes."); + + public void EmitPatronClearance(float timestamp, int contenderId) => + Emit(timestamp, BroadcastKind.PatronClearance, + $"Contender {contenderId + 1:00} breaches the perimeter line; ring patrons take clearance to correct their posture."); + + public void EmitChassisSwap(float timestamp, int contenderId, string chassisName) => + Emit(timestamp, BroadcastKind.ChassisSwap, + $"Contender {contenderId + 1:00} sheds a ruin and mounts a {chassisName}. Vulgar improvisation, yet watchable."); + + public void EmitQuickBolt(float timestamp, int contenderId, string moduleName, string hardpointId) => + Emit(timestamp, BroadcastKind.QuickBolt, + $"Contender {contenderId + 1:00} quick-bolts {moduleName} onto {hardpointId} mid-run. Crude fieldcraft, live fire ready."); + + public void EmitOverheat(float timestamp, int contenderId) => + Emit(timestamp, BroadcastKind.Overheat, + $"Contender {contenderId + 1:00} glows past the thermal plateau — the crowd admires the smoke."); + + public void EmitElimination(float timestamp, string killerLabel, string victimLabel, bool bySpectator) + { + string line = bySpectator + ? $"{killerLabel} restores boundary decorum over {victimLabel}. Order keeps its shine." + : $"{killerLabel} performs a decisive eviction on {victimLabel}. The gallery notes the sincerity."; + Emit(timestamp, BroadcastKind.Elimination, line); + } + + public void EmitVictory(float timestamp, int winnerId, ArenaMapKind mapKind = ArenaMapKind.Desert) => + Emit(timestamp, BroadcastKind.Victory, + $"Contender {winnerId + 1:00} {(mapKind == ArenaMapKind.Sion ? "outlasts the alpine ring" : "outlasts the dust")} and the gallery's patience. Broadcast closes with reluctant applause."); + + public void EmitDropWave(float timestamp, int waveIndex, int gearCount, int respawnCount, bool respawnsClosed) + { + string line = waveIndex == 0 + ? $"Orbital insertion underway: {gearCount} Imperial salvage pods and 12 contender drop capsules inbound." + : respawnsClosed + ? $"Patron Drop Wave {waveIndex}: {gearCount} high-tier salvage pods inbound. Final-ring cutoff reached — redeployments closed." + : $"Patron Drop Wave {waveIndex}: {gearCount} Imperial salvage pods and {respawnCount} redeployed contender(s) inbound."; + Emit(timestamp, BroadcastKind.DropWave, line); + } + } +} diff --git a/src/RustToDust.Core/Catalog.cs b/src/RustToDust.Core/Catalog.cs new file mode 100644 index 0000000..8a7ca81 --- /dev/null +++ b/src/RustToDust.Core/Catalog.cs @@ -0,0 +1,549 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RustToDust.Core +{ + public static class Catalog + { + private static readonly Dictionary _packagesById; + private static readonly Dictionary _chassisById; + private static readonly IReadOnlyList _allChassis; + + static Catalog() + { + var loaded = VehicleCatalogLoader.LoadAll(); + _packagesById = new Dictionary(StringComparer.OrdinalIgnoreCase); + _chassisById = new Dictionary(StringComparer.OrdinalIgnoreCase); + var list = new List(loaded.Count); + + foreach (var (pkg, spec) in loaded) + { + _packagesById[pkg.Id] = pkg; + _chassisById[spec.Id] = spec; + list.Add(spec); + } + + _allChassis = list.AsReadOnly(); + } + + private static ChassisSpec RequireChassis(string id) => + _chassisById.TryGetValue(id, out var spec) + ? spec + : throw new KeyNotFoundException($"Missing chassis '{id}' in loaded vehicle.cc catalog."); + + // ---------------- CHASSIS (15 BROKKR PACKAGES LOADED FROM .CC) ---------------- + + public static ChassisSpec Jackal => RequireChassis("jackal"); + public static ChassisSpec Mule => RequireChassis("mule"); + public static ChassisSpec Ferret => RequireChassis("ferret"); + public static ChassisSpec Hornet => RequireChassis("hornet"); + public static ChassisSpec Mammoth => RequireChassis("mammoth"); + public static ChassisSpec Ironclad => RequireChassis("ironclad"); + public static ChassisSpec Anvil => RequireChassis("anvil"); + public static ChassisSpec Condor => RequireChassis("condor"); + public static ChassisSpec Breaker => RequireChassis("breaker"); + public static ChassisSpec Paladin => RequireChassis("paladin"); + public static ChassisSpec Raptor => RequireChassis("raptor"); + public static ChassisSpec Manticore => RequireChassis("manticore"); + public static ChassisSpec Bastion => RequireChassis("bastion"); + public static ChassisSpec Spectre => RequireChassis("spectre"); + public static ChassisSpec Kestrel => RequireChassis("kestrel"); + + // Backward-compatible aliases for legacy Cut 1/2 call sites + public static ChassisSpec Buggy => Jackal; + public static ChassisSpec Technical => Mule; + public static ChassisSpec Tank => Anvil; + + public static IReadOnlyList AllChassis => _allChassis; + public static IReadOnlyDictionary ChassisById => _chassisById; + public static IReadOnlyDictionary PackagesById => _packagesById; + + public static VehiclePackage? TryGetPackage(string id) => + _packagesById.TryGetValue(id, out var pkg) ? pkg : null; + + public static bool TryGetChassisSpecOrExemplar(string id, out ChassisSpec spec) + { + if (_chassisById.TryGetValue(id, out spec!)) + { + return true; + } + if (string.Equals(id, "exemplar_frame", StringComparison.OrdinalIgnoreCase)) + { + spec = SpectatorRing.ExemplarSpec; + return true; + } + spec = null!; + return false; + } + + // ---------------- HUMAN SALVAGE MODULES (9) ---------------- + + public static readonly ModuleSpec Mg762 = new( + Id: "mg_762", + Name: "7.62 Machine Gun", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 1, + IsImperial: false, + ThermalMass: 5f, + Conductivity: 9f, + OptimalTemp: 65f, + PlateauWidth: 70f, + MinTemp: 0f, + MaxTemp: 155f, + HeatOutput: 34f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 12f, + WeaponRange: 165f, + FireCooldown: 0.22f, + ProjectileSpeed: 220f, + SpreadRad: 0.035f, + BurstCount: 1); + + public static readonly ModuleSpec Autocannon = new( + Id: "autocannon", + Name: "Twin 20mm Autocannon", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 2, + IsImperial: false, + ThermalMass: 10f, + Conductivity: 10f, + OptimalTemp: 75f, + PlateauWidth: 70f, + MinTemp: 0f, + MaxTemp: 170f, + HeatOutput: 75f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 22f, + WeaponRange: 210f, + FireCooldown: 0.34f, + ProjectileSpeed: 250f, + SpreadRad: 0.025f, + BurstCount: 2); + + public static readonly ModuleSpec Flak = new( + Id: "flak", + Name: "Scrap Flak Scattergun", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 1, + IsImperial: false, + ThermalMass: 6f, + Conductivity: 8f, + OptimalTemp: 65f, + PlateauWidth: 70f, + MinTemp: 0f, + MaxTemp: 165f, + HeatOutput: 90f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 8.5f, + WeaponRange: 105f, + FireCooldown: 0.65f, + ProjectileSpeed: 185f, + SpreadRad: 0.14f, + BurstCount: 5); + + public static readonly ModuleSpec PointDefenseFlak = new( + Id: "pd_flak", + Name: "Flak Point-Defense", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 1, + IsImperial: false, + ThermalMass: 6f, + Conductivity: 10f, + OptimalTemp: 65f, + PlateauWidth: 80f, + MinTemp: 0f, + MaxTemp: 165f, + HeatOutput: 24f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 11f, + WeaponRange: 175f, + FireCooldown: 0.24f, + ProjectileSpeed: 340f, + SpreadRad: 0.045f, + BurstCount: 3, + IsWideArc: true, + MinPitchDeg: -10f, + MaxPitchDeg: 85f); + + public static readonly ModuleSpec Recoilless = new( + Id: "recoilless", + Name: "105mm Recoilless Rifle", + Kind: HardpointKind.Weapon, + Width: 2, + Height: 2, + IsImperial: false, + ThermalMass: 18f, + Conductivity: 11f, + OptimalTemp: 75f, + PlateauWidth: 80f, + MinTemp: 0f, + MaxTemp: 185f, + HeatOutput: 190f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 85f, + WeaponRange: 265f, + FireCooldown: 1.45f, + ProjectileSpeed: 280f, + SpreadRad: 0.01f, + BurstCount: 1); + + public static readonly ModuleSpec DieselCore = new( + Id: "diesel_core", + Name: "Salvaged Diesel Core", + Kind: HardpointKind.Engine, + Width: 1, + Height: 1, + IsImperial: false, + ThermalMass: 9f, + Conductivity: 9f, + OptimalTemp: 60f, + PlateauWidth: 80f, + MinTemp: 0f, + MaxTemp: 150f, + HeatOutput: 45f, + CoolingPower: 0f, + ThrustBonus: 4500f, + TurnBonus: 0.4f, + ArmorBonus: 0f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + public static readonly ModuleSpec TurboCore = new( + Id: "turbo_core", + Name: "Supercharged V8", + Kind: HardpointKind.Engine, + Width: 1, + Height: 2, + IsImperial: false, + ThermalMass: 14f, + Conductivity: 10f, + OptimalTemp: 75f, + PlateauWidth: 70f, + MinTemp: 0f, + MaxTemp: 170f, + HeatOutput: 85f, + CoolingPower: 0f, + ThrustBonus: 12500f, + TurnBonus: 0.9f, + ArmorBonus: 0f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + public static readonly ModuleSpec CopperRad = new( + Id: "copper_rad", + Name: "Copper Fin Radiator", + Kind: HardpointKind.Radiator, + Width: 1, + Height: 1, + IsImperial: false, + ThermalMass: 6f, + Conductivity: 15f, + OptimalTemp: 85f, + PlateauWidth: 90f, + MinTemp: 0f, + MaxTemp: 210f, + HeatOutput: 0f, + CoolingPower: 120f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + public static readonly ModuleSpec WeldedPlate = new( + Id: "welded_plate", + Name: "Welded Scrap Plate", + Kind: HardpointKind.Armor, + Width: 1, + Height: 1, + IsImperial: false, + ThermalMass: 12f, + Conductivity: 6f, + OptimalTemp: 60f, + PlateauWidth: 120f, + MinTemp: -20f, + MaxTemp: 240f, + HeatOutput: 0f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 45f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + // ---------------- IMPERIAL TOURIST HIGH-END MODULES (6) ---------------- + + public static readonly ModuleSpec GildedLance = new( + Id: "gilded_lance", + Name: "Gilded Thermal Lance", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 2, + IsImperial: true, + ThermalMass: 11f, + Conductivity: 14f, + OptimalTemp: 90f, + PlateauWidth: 80f, + MinTemp: 0f, + MaxTemp: 210f, + HeatOutput: 95f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 54f, + WeaponRange: 285f, + FireCooldown: 0.55f, + ProjectileSpeed: 400f, + SpreadRad: 0.004f, + BurstCount: 1); + + public static readonly ModuleSpec TouringPlasma = new( + Id: "touring_plasma", + Name: "Touring Plasma Repeater", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 1, + IsImperial: true, + ThermalMass: 8f, + Conductivity: 14f, + OptimalTemp: 95f, + PlateauWidth: 80f, + MinTemp: 0f, + MaxTemp: 205f, + HeatOutput: 68f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 26f, + WeaponRange: 210f, + FireCooldown: 0.18f, + ProjectileSpeed: 310f, + SpreadRad: 0.02f, + BurstCount: 1); + + public static readonly ModuleSpec ImperialAegisPd = new( + Id: "aegis_pd", + Name: "Aegis Imperial PD", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 1, + IsImperial: true, + ThermalMass: 8f, + Conductivity: 16f, + OptimalTemp: 90f, + PlateauWidth: 90f, + MinTemp: 0f, + MaxTemp: 215f, + HeatOutput: 26f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 16f, + WeaponRange: 215f, + FireCooldown: 0.16f, + ProjectileSpeed: 420f, + SpreadRad: 0.015f, + BurstCount: 2, + IsWideArc: true, + MinPitchDeg: -10f, + MaxPitchDeg: 85f); + + public static readonly ModuleSpec GoldRadiator = new( + Id: "gold_radiator", + Name: "Gold-Leaf Phase Radiator", + Kind: HardpointKind.Radiator, + Width: 1, + Height: 1, + IsImperial: true, + ThermalMass: 7f, + Conductivity: 24f, + OptimalTemp: 100f, + PlateauWidth: 110f, + MinTemp: 0f, + MaxTemp: 260f, + HeatOutput: 0f, + CoolingPower: 290f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + public static readonly ModuleSpec NobleCore = new( + Id: "noble_core", + Name: "Overclocked Noble Core", + Kind: HardpointKind.Engine, + Width: 1, + Height: 2, + IsImperial: true, + ThermalMass: 15f, + Conductivity: 16f, + OptimalTemp: 105f, + PlateauWidth: 90f, + MinTemp: 0f, + MaxTemp: 225f, + HeatOutput: 110f, + CoolingPower: 0f, + ThrustBonus: 19500f, + TurnBonus: 1.45f, + ArmorBonus: 0f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + public static readonly ModuleSpec GildedPlate = new( + Id: "gilded_plate", + Name: "Gilded Ceramic Plate", + Kind: HardpointKind.Armor, + Width: 1, + Height: 1, + IsImperial: true, + ThermalMass: 16f, + Conductivity: 4f, + OptimalTemp: 80f, + PlateauWidth: 140f, + MinTemp: -20f, + MaxTemp: 280f, + HeatOutput: 0f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 85f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + public static readonly IReadOnlyList HumanModules = new[] + { + Mg762, Autocannon, Flak, PointDefenseFlak, Recoilless, DieselCore, TurboCore, CopperRad, WeldedPlate + }; + + public static readonly IReadOnlyList ImperialModules = new[] + { + GildedLance, TouringPlasma, ImperialAegisPd, GoldRadiator, NobleCore, GildedPlate + }; + + public static readonly IReadOnlyList AllModules = new[] + { + Mg762, Autocannon, Flak, PointDefenseFlak, Recoilless, DieselCore, TurboCore, CopperRad, WeldedPlate, + GildedLance, TouringPlasma, ImperialAegisPd, GoldRadiator, NobleCore, GildedPlate + }; + + public static readonly IReadOnlyDictionary ModulesById = + AllModules.ToDictionary(m => m.Id, StringComparer.OrdinalIgnoreCase); + + public static bool TryGetModule(string? id, out ModuleSpec spec) + { + if (string.IsNullOrEmpty(id)) + { + spec = null!; + return false; + } + if (ModulesById.TryGetValue(id, out spec!)) + { + return true; + } + if (ProceduralWeaponGenerator.TryParseId(id, out var key)) + { + spec = ProceduralWeaponGenerator.Generate(key).Module; + return true; + } + spec = null!; + return false; + } + + public static ChassisGrid CreateStarterBuggy() + { + var grid = new ChassisGrid(Jackal); + grid.TryMount(Mg762, "hp.weapon.roof"); + grid.TryMount(DieselCore, "hp.engine.rear"); + grid.TryMount(CopperRad, "hp.radiator.rear"); + return grid; + } + + public static int GetChassisUpgradeScore(ChassisSpec spec) => spec.Id.ToLowerInvariant() switch + { + "jackal" => 0, + "hornet" => 1, + "ferret" => 2, + "kestrel" => 3, + "mule" => 4, + "condor" => 5, + "raptor" => 6, + "spectre" => 7, + "manticore" => 8, + "ironclad" => 9, + "breaker" => 10, + "mammoth" => 11, + "paladin" => 12, + "bastion" => 13, + "anvil" => 14, + _ => 0 + }; + + public static ChassisGrid CreateWithDefaultLoadout(ChassisSpec spec) + { + var grid = new ChassisGrid(spec); + if (_packagesById.TryGetValue(spec.Id, out var pkg)) + { + foreach (var kvp in pkg.DefaultLoadout) + { + if (ModulesById.TryGetValue(kvp.Value, out var mod)) + { + grid.TryMount(mod, kvp.Key); + } + } + } + return grid; + } + } +} diff --git a/src/RustToDust.Core/GridChassis.cs b/src/RustToDust.Core/GridChassis.cs new file mode 100644 index 0000000..fdee366 --- /dev/null +++ b/src/RustToDust.Core/GridChassis.cs @@ -0,0 +1,1271 @@ +using System; +using System.Collections.Generic; + +namespace RustToDust.Core +{ + public enum GridPlane + { + Dorsal, + Coronal + } + + public enum MobilityKind + { + Wheeled, + Tracked, + Vtol, + Walker + } + + public enum HardpointKind + { + Weapon, + Engine, + Radiator, + Armor, + Utility + } + + public sealed record HardpointSpec( + string Id, + HardpointKind Kind, + int X, + int Y, + int Width, + int Height, + float ArmorBonus, + float MinPitchDeg = -15f, + float MaxPitchDeg = 45f, + bool IsWideArc = false); + + public sealed record ModuleSpec( + string Id, + string Name, + HardpointKind Kind, + int Width, + int Height, + bool IsImperial, + float ThermalMass, + float Conductivity, + float OptimalTemp, + float PlateauWidth, + float MinTemp, + float MaxTemp, + float HeatOutput, + float CoolingPower, + float ThrustBonus, + float TurnBonus, + float ArmorBonus, + float WeaponDamage, + float WeaponRange, + float FireCooldown, + float ProjectileSpeed, + float SpreadRad, + int BurstCount, + bool IsWideArc = false, + float MinPitchDeg = -15f, + float MaxPitchDeg = 45f, + WeaponVisualClass? VisualClassOverride = null, + float EffectivePowerScore = 0f, + ProceduralWeaponSpec? Procedural = null) + { + /// + /// Exact Aetheria trapezoidal plateau curve: + /// 0 outside [MinTemp, MaxTemp], 1 on [OptimalTemp - PlateauWidth/2, OptimalTemp + PlateauWidth/2], + /// linear ramp between bounds and plateau. + /// + public float Performance(float temperature) + { + if (temperature <= MinTemp || temperature >= MaxTemp) + { + return 0f; + } + + float halfPlateau = PlateauWidth * 0.5f; + float lowPlateau = OptimalTemp - halfPlateau; + float highPlateau = OptimalTemp + halfPlateau; + + if (temperature >= lowPlateau && temperature <= highPlateau) + { + return 1f; + } + + if (temperature < lowPlateau) + { + float span = MathF.Max(1e-5f, lowPlateau - MinTemp); + return Math.Clamp((temperature - MinTemp) / span, 0f, 1f); + } + + float upperSpan = MathF.Max(1e-5f, MaxTemp - highPlateau); + return Math.Clamp((MaxTemp - temperature) / upperSpan, 0f, 1f); + } + } + + public sealed record ChassisSpec( + string Id, + string Name, + GridPlane Plane, + int Width, + int Height, + bool[] Mask, + HardpointSpec[] Hardpoints, + float HullConductivity, + float BaseCellThermalMass, + float BaseCellArmor, + float MassKg, + float BaseThrust, + float BaseTurnRate, + float MaxSpeed, + float HalfWidth, + float HalfHeight, + float HalfLength, + int CargoCapacity, + MobilityKind Mobility = MobilityKind.Wheeled, + float HoverMaxAltitudeM = 0f, + string VehicleClass = "") + { + public bool IsWalker => + Mobility == MobilityKind.Walker || + Plane == GridPlane.Coronal || + string.Equals(Id, "manticore", StringComparison.OrdinalIgnoreCase) || + string.Equals(Id, "bastion", StringComparison.OrdinalIgnoreCase); + + public bool IsVtol => Mobility == MobilityKind.Vtol; + + public bool IsActive(int x, int y) => + x >= 0 && x < Width && y >= 0 && y < Height && Mask[y * Width + x]; + } + + public sealed class MountedModule + { + public MountedModule(ModuleSpec spec, string hardpointId, float initialTemp) + { + Spec = spec; + HardpointId = hardpointId; + CurrentTemp = initialTemp; + CurrentPerformance = spec.Performance(initialTemp); + } + + public ModuleSpec Spec { get; } + public string HardpointId { get; } + public float Cooldown { get; set; } + public float CurrentTemp { get; set; } + public float CurrentPerformance { get; set; } + } + + public readonly record struct HitResult( + int CellX, + int CellY, + float ArmorDamage, + float CoreDamage, + bool CoreDestroyed); + + public sealed class ChassisGrid + { + public const float AmbientTemp = 20f; + public const float RadiationExponent = 1.6f; + public const float RadiationMultiplier = 0.015f; + + private static readonly (int Dx, int Dy)[] CardinalOffsets = + { + (1, 0), (-1, 0), (0, 1), (0, -1) + }; + + private float[,] _netHeat; + private float[,] _cellThermalMass; + private float[,] _cellConductivity; + + public ChassisGrid(ChassisSpec spec) + { + Spec = spec ?? throw new ArgumentNullException(nameof(spec)); + Temperature = new float[spec.Width, spec.Height]; + Armor = new float[spec.Width, spec.Height]; + MaxArmor = new float[spec.Width, spec.Height]; + BorderCells = new bool[spec.Width, spec.Height]; + _netHeat = new float[spec.Width, spec.Height]; + _cellThermalMass = new float[spec.Width, spec.Height]; + _cellConductivity = new float[spec.Width, spec.Height]; + InitializeGridState(spec, preserveCoreRatio: false, previousRatio: 1f); + } + + public ChassisSpec Spec { get; private set; } + public float[,] Temperature { get; private set; } + public float[,] Armor { get; private set; } + public float[,] MaxArmor { get; private set; } + public bool[,] BorderCells { get; private set; } + public List Mounted { get; } = new(); + public List Cargo { get; } = new(); + + public float CoreHp { get; private set; } + public float MaxCoreHp { get; private set; } + public bool IsDestroyed => CoreHp <= 0f; + public int HitSequence { get; private set; } + public int LastHitX { get; private set; } + public int LastHitY { get; private set; } + + public static bool CanFit(HardpointSpec hp, ModuleSpec mod) => + mod.Kind == hp.Kind && mod.Width <= hp.Width && mod.Height <= hp.Height; + + public HardpointSpec? FindHardpoint(string hardpointId) + { + for (int i = 0; i < Spec.Hardpoints.Length; i++) + { + if (Spec.Hardpoints[i].Id == hardpointId) + { + return Spec.Hardpoints[i]; + } + } + return null; + } + + public bool IsHardpointOperational(HardpointSpec hp) + { + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int x = hp.X + dx; + int y = hp.Y + dy; + if (Spec.IsActive(x, y) && Armor[x, y] > 0.01f) + { + return true; + } + } + } + return false; + } + + public bool IsHardpointOperational(string hardpointId) => + FindHardpoint(hardpointId) is { } hp && IsHardpointOperational(hp); + + public MountedModule? GetMountedOn(string hardpointId) + { + for (int i = 0; i < Mounted.Count; i++) + { + if (Mounted[i].HardpointId == hardpointId) + { + return Mounted[i]; + } + } + return null; + } + + public bool TryMount(ModuleSpec mod, string hardpointId, List? displacedOut = null) + { + var hp = FindHardpoint(hardpointId); + if (hp is null || !CanFit(hp, mod)) + { + return false; + } + + var existing = GetMountedOn(hardpointId); + if (existing is not null) + { + Mounted.Remove(existing); + if (Cargo.Count < Spec.CargoCapacity) + { + Cargo.Add(existing.Spec); + } + else + { + displacedOut?.Add(existing.Spec); + } + } + + float avgTemp = GetHardpointAverageTemp(hp); + Mounted.Add(new MountedModule(mod, hardpointId, avgTemp)); + RecalculateArmorAndThermal(grantNewArmorDelta: true); + return true; + } + + public bool TryEquipFromCargo(int cargoIndex, string hardpointId, List? displacedOut = null) + { + if (cargoIndex < 0 || cargoIndex >= Cargo.Count) + { + return false; + } + + var mod = Cargo[cargoIndex]; + var hp = FindHardpoint(hardpointId); + if (hp is null || !CanFit(hp, mod)) + { + return false; + } + + Cargo.RemoveAt(cargoIndex); + if (!TryMount(mod, hardpointId, displacedOut)) + { + Cargo.Insert(cargoIndex, mod); + return false; + } + return true; + } + + public bool TryAddCargo(ModuleSpec mod) + { + if (Cargo.Count >= Spec.CargoCapacity) + { + return false; + } + Cargo.Add(mod); + return true; + } + + public HardpointSpec? FindFirstEmptyCompatibleHardpoint(ModuleSpec mod) + { + for (int i = 0; i < Spec.Hardpoints.Length; i++) + { + var hp = Spec.Hardpoints[i]; + if (GetMountedOn(hp.Id) is null && CanFit(hp, mod)) + { + return hp; + } + } + return null; + } + + public bool TryQuickBoltOrCargo(ModuleSpec mod, out string? boltedHardpointId) + { + var freeHp = FindFirstEmptyCompatibleHardpoint(mod); + if (freeHp is not null && TryMount(mod, freeHp.Id)) + { + boltedHardpointId = freeHp.Id; + return true; + } + + boltedHardpointId = null; + return TryAddCargo(mod); + } + + public void InjectHeat(int x, int y, float heat) + { + if (!Spec.IsActive(x, y) || heat == 0f) + { + return; + } + float tm = MathF.Max(1f, _cellThermalMass[x, y]); + Temperature[x, y] = MathF.Max(AmbientTemp, Temperature[x, y] + heat / tm); + } + + public void InjectHardpointHeat(string hardpointId, float heat) + { + var hp = FindHardpoint(hardpointId); + if (hp is null || heat == 0f) + { + return; + } + + int activeCells = CountActiveCellsInHardpoint(hp); + if (activeCells == 0) + { + return; + } + + float perCell = heat / activeCells; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int x = hp.X + dx; + int y = hp.Y + dy; + if (Spec.IsActive(x, y)) + { + InjectHeat(x, y, perCell); + } + } + } + } + + public void StepHeat(float dt) + { + if (dt <= 0f) + { + return; + } + + int w = Spec.Width; + int h = Spec.Height; + int substeps = Math.Max(1, (int)MathF.Ceiling(dt / 0.02f)); + float subDt = dt / substeps; + + for (int step = 0; step < substeps; step++) + { + Array.Clear(_netHeat, 0, _netHeat.Length); + + // 4-neighbor weighted conduction (conservative pairwise transfer) + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + + float t = Temperature[x, y]; + float c = _cellConductivity[x, y]; + + if (x + 1 < w && Spec.IsActive(x + 1, y)) + { + float pairCond = 0.5f * (c + _cellConductivity[x + 1, y]); + float flow = pairCond * (Temperature[x + 1, y] - t) * subDt; + _netHeat[x, y] += flow; + _netHeat[x + 1, y] -= flow; + } + + if (y + 1 < h && Spec.IsActive(x, y + 1)) + { + float pairCond = 0.5f * (c + _cellConductivity[x, y + 1]); + float flow = pairCond * (Temperature[x, y + 1] - t) * subDt; + _netHeat[x, y] += flow; + _netHeat[x, y + 1] -= flow; + } + } + } + + // Border-only radiative cooling + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y) || !BorderCells[x, y]) + { + continue; + } + + float t = MathF.Max(0f, Temperature[x, y]); + float radLoss = MathF.Pow(t, RadiationExponent) * RadiationMultiplier * subDt; + _netHeat[x, y] -= radLoss; + } + } + + // Active radiator cooling scaled by radiator's Performance(temp) + for (int i = 0; i < Mounted.Count; i++) + { + var mod = Mounted[i]; + if (mod.Spec.Kind != HardpointKind.Radiator || mod.Spec.CoolingPower <= 0f) + { + continue; + } + + var hp = FindHardpoint(mod.HardpointId); + if (hp is null) + { + continue; + } + + float perf = mod.Spec.Performance(mod.CurrentTemp); + if (perf <= 0f) + { + continue; + } + + int activeCells = CountActiveCellsInHardpoint(hp); + if (activeCells == 0) + { + continue; + } + + float coolPerCell = (mod.Spec.CoolingPower * perf * subDt) / activeCells; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int cx = hp.X + dx; + int cy = hp.Y + dy; + if (Spec.IsActive(cx, cy)) + { + _netHeat[cx, cy] -= coolPerCell; + } + } + } + } + + // Integrate temperature with desert ambient floor + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y)) + { + Temperature[x, y] = AmbientTemp; + continue; + } + + float tm = MathF.Max(1f, _cellThermalMass[x, y]); + float next = Temperature[x, y] + _netHeat[x, y] / tm; + Temperature[x, y] = MathF.Max(AmbientTemp, next); + } + } + + UpdateMountedTelemetry(); + } + } + + public HitResult ApplyHit(float localRight, float localForward, float localHeightNorm, float damage, float heatTransfer) + { + (int cx, int cy) = ResolveHitCell(localRight, localForward, localHeightNorm); + if (!Spec.IsActive(cx, cy)) + { + return new HitResult(0, 0, 0f, 0f, IsDestroyed); + } + + if (heatTransfer > 0f) + { + InjectHeat(cx, cy, heatTransfer); + } + + float absorbed = MathF.Min(Armor[cx, cy], MathF.Max(0f, damage)); + Armor[cx, cy] -= absorbed; + float spill = MathF.Max(0f, damage - absorbed); + + if (spill > 0f && CoreHp > 0f) + { + CoreHp = MathF.Max(0f, CoreHp - spill); + } + + HitSequence++; + LastHitX = cx; + LastHitY = cy; + + return new HitResult(cx, cy, absorbed, spill, IsDestroyed); + } + + public List SwapChassis(ChassisSpec next) + { + if (next is null) + { + throw new ArgumentNullException(nameof(next)); + } + + var previousMounted = new List(Mounted.Count); + for (int i = 0; i < Mounted.Count; i++) + { + previousMounted.Add(Mounted[i].Spec); + } + var previousCargo = new List(Cargo); + float coreRatio = MaxCoreHp > 0f ? CoreHp / MaxCoreHp : 1f; + + Mounted.Clear(); + Cargo.Clear(); + + Spec = next; + Temperature = new float[next.Width, next.Height]; + Armor = new float[next.Width, next.Height]; + MaxArmor = new float[next.Width, next.Height]; + BorderCells = new bool[next.Width, next.Height]; + _netHeat = new float[next.Width, next.Height]; + _cellThermalMass = new float[next.Width, next.Height]; + _cellConductivity = new float[next.Width, next.Height]; + + InitializeGridState(next, preserveCoreRatio: true, previousRatio: MathF.Max(0.75f, coreRatio)); + + var dropped = new List(); + + // Transfer every mounted module that fits a free hardpoint on the new chassis + foreach (var mod in previousMounted) + { + HardpointSpec? chosen = null; + for (int i = 0; i < next.Hardpoints.Length; i++) + { + var hp = next.Hardpoints[i]; + if (GetMountedOn(hp.Id) is null && CanFit(hp, mod)) + { + chosen = hp; + break; + } + } + + if (chosen is not null) + { + Mounted.Add(new MountedModule(mod, chosen.Id, AmbientTemp)); + } + else if (Cargo.Count < next.CargoCapacity) + { + Cargo.Add(mod); + } + else + { + dropped.Add(mod); + } + } + + foreach (var item in previousCargo) + { + if (Cargo.Count < next.CargoCapacity) + { + Cargo.Add(item); + } + else + { + dropped.Add(item); + } + } + + RecalculateArmorAndThermal(grantNewArmorDelta: true); + UpdateMountedTelemetry(); + return dropped; + } + + private bool IsOccupiedByHardpoint(int x, int y) + { + for (int i = 0; i < Spec.Hardpoints.Length; i++) + { + var hp = Spec.Hardpoints[i]; + if (x >= hp.X && x < hp.X + hp.Width && y >= hp.Y && y < hp.Y + hp.Height) + { + return true; + } + } + return false; + } + + public void GetLegIntegrities(Span outLegs) + { + if (Spec.Plane == GridPlane.Coronal) + { + int legStartY = Spec.Height <= 5 + ? Math.Max(0, Spec.Height - 1) + : Math.Max(0, Spec.Height - 2); + int leftMaxX = Spec.Width / 2; + int rightMinX = (Spec.Width + 1) / 2; + float curL = 0f, maxL = 0f, curR = 0f, maxR = 0f; + + for (int y = legStartY; y < Spec.Height; y++) + { + for (int x = 0; x < Spec.Width; x++) + { + if (!Spec.IsActive(x, y) || IsOccupiedByHardpoint(x, y)) + { + continue; + } + if (x < leftMaxX) + { + curL += Armor[x, y]; + maxL += MaxArmor[x, y]; + } + else if (x >= rightMinX) + { + curR += Armor[x, y]; + maxR += MaxArmor[x, y]; + } + } + } + + if (outLegs.Length > 0) + { + outLegs[0] = maxL > 0f ? 0.25f + 0.75f * Math.Clamp(curL / maxL, 0f, 1f) : 1f; + } + if (outLegs.Length > 1) + { + outLegs[1] = maxR > 0f ? 0.25f + 0.75f * Math.Clamp(curR / maxR, 0f, 1f) : 1f; + } + for (int i = 2; i < outLegs.Length; i++) + { + outLegs[i] = 1f; + } + return; + } + + if (Spec.IsWalker) + { + int midXLeft = Spec.Width / 2; + int midXRight = (Spec.Width + 1) / 2; + int midY = Spec.Height / 2; + Span cur = stackalloc float[4]; + Span max = stackalloc float[4]; + + for (int y = 0; y < Spec.Height; y++) + { + int rowBase = y < midY ? 0 : 2; + for (int x = 0; x < Spec.Width; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + int legIdx; + if (x < midXLeft) + { + legIdx = rowBase; + } + else if (x >= midXRight) + { + legIdx = rowBase + 1; + } + else + { + continue; + } + cur[legIdx] += Armor[x, y]; + max[legIdx] += MaxArmor[x, y]; + } + } + + int count = Math.Min(4, outLegs.Length); + for (int i = 0; i < count; i++) + { + outLegs[i] = max[i] > 0f ? 0.25f + 0.75f * Math.Clamp(cur[i] / max[i], 0f, 1f) : 1f; + } + for (int i = 4; i < outLegs.Length; i++) + { + outLegs[i] = 1f; + } + return; + } + + outLegs.Fill(1f); + } + + public float LegIntegrity + { + get + { + if (!Spec.IsWalker) + { + return 1f; + } + + Span legs = stackalloc float[4]; + GetLegIntegrities(legs); + return Spec.Plane == GridPlane.Dorsal + ? (legs[0] + legs[1] + legs[2] + legs[3]) * 0.25f + : (legs[0] + legs[1]) * 0.5f; + } + } + + public float ComputeEngineThermalPerformance() + { + float sum = 0f; + int count = 0; + for (int i = 0; i < Mounted.Count; i++) + { + var m = Mounted[i]; + if (m.Spec.Kind == HardpointKind.Engine) + { + sum += m.CurrentPerformance; + count++; + } + } + return count > 0 ? Math.Clamp(sum / count, 0f, 1f) : 0.4f; + } + + public float ComputeDriveThrust() + { + float engineThrust = 0f; + float enginePerfSum = 0f; + int engineCount = 0; + + for (int i = 0; i < Mounted.Count; i++) + { + var m = Mounted[i]; + if (m.Spec.Kind == HardpointKind.Engine) + { + engineThrust += m.Spec.ThrustBonus * m.CurrentPerformance; + enginePerfSum += m.CurrentPerformance; + engineCount++; + } + } + + float baseFactor = engineCount > 0 ? Math.Clamp(enginePerfSum / engineCount, 0.25f, 1f) : 0.4f; + return (Spec.BaseThrust * baseFactor + engineThrust) * LegIntegrity; + } + + public float ComputeTurnRate() + { + float bonus = 0f; + float enginePerfSum = 0f; + int engineCount = 0; + + for (int i = 0; i < Mounted.Count; i++) + { + var m = Mounted[i]; + if (m.Spec.Kind == HardpointKind.Engine) + { + bonus += m.Spec.TurnBonus * m.CurrentPerformance; + enginePerfSum += m.CurrentPerformance; + engineCount++; + } + } + + float baseFactor = engineCount > 0 ? Math.Clamp(enginePerfSum / engineCount, 0.35f, 1f) : 0.5f; + return (Spec.BaseTurnRate * baseFactor + bonus) * (0.5f + 0.5f * LegIntegrity); + } + + public float TotalArmorRatio() + { + float cur = 0f; + float max = 0f; + for (int y = 0; y < Spec.Height; y++) + { + for (int x = 0; x < Spec.Width; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + cur += Armor[x, y]; + max += MaxArmor[x, y]; + } + } + return max > 0f ? cur / max : 0f; + } + + public float ComputeMaxThermalRatio() + { + float worst = 0f; + for (int i = 0; i < Mounted.Count; i++) + { + var m = Mounted[i]; + float span = MathF.Max(1f, m.Spec.MaxTemp - AmbientTemp); + float ratio = Math.Clamp((m.CurrentTemp - AmbientTemp) / span, 0f, 1.5f); + if (ratio > worst) worst = ratio; + } + for (int y = 0; y < Spec.Height; y++) + { + for (int x = 0; x < Spec.Width; x++) + { + if (!Spec.IsActive(x, y)) continue; + float ratio = Math.Clamp((Temperature[x, y] - AmbientTemp) / 380f, 0f, 1.5f); + if (ratio > worst) worst = ratio; + } + } + return worst; + } + + public byte[] QuantizeArmorBytes() + { + int count = 0; + for (int y = 0; y < Spec.Height; y++) + for (int x = 0; x < Spec.Width; x++) + if (Spec.IsActive(x, y)) count++; + + var bytes = new byte[count]; + int idx = 0; + for (int y = 0; y < Spec.Height; y++) + { + for (int x = 0; x < Spec.Width; x++) + { + if (!Spec.IsActive(x, y)) continue; + float max = MathF.Max(0.01f, MaxArmor[x, y]); + float ratio = Math.Clamp(Armor[x, y] / max, 0f, 1f); + bytes[idx++] = (byte)Math.Clamp((int)MathF.Round(ratio * 255f), 0, 255); + } + } + return bytes; + } + + public void ApplyReplicatedArmorBytes(ReadOnlySpan armorBytes) + { + int idx = 0; + for (int y = 0; y < Spec.Height; y++) + { + for (int x = 0; x < Spec.Width; x++) + { + if (!Spec.IsActive(x, y)) continue; + if (idx >= armorBytes.Length) return; + Armor[x, y] = MaxArmor[x, y] * (armorBytes[idx++] / 255f); + } + } + } + + public void ApplyReplicatedDamage(int cellX, int cellY, float cellArmor, float cellTemp, float coreHp, int hitSequence) + { + if (Spec.IsActive(cellX, cellY)) + { + Armor[cellX, cellY] = MathF.Max(0f, cellArmor); + Temperature[cellX, cellY] = MathF.Max(AmbientTemp, cellTemp); + LastHitX = cellX; + LastHitY = cellY; + } + CoreHp = MathF.Max(0f, coreHp); + if (hitSequence > HitSequence) + { + HitSequence = hitSequence; + } + else + { + HitSequence++; + } + UpdateMountedTelemetry(); + } + + public void ApplyReplicatedCoreHpRatio(float coreHpRatio, bool alive) + { + if (MaxCoreHp <= 0f) return; + CoreHp = alive + ? MathF.Max(0.01f, Math.Clamp(coreHpRatio, 0f, 1f) * MaxCoreHp) + : 0f; + } + + public void ApplyReplicatedThermal(ReadOnlySpan quantizedCellTemps, ReadOnlySpan mountedTemps, ReadOnlySpan mountedCooldowns) + { + int idx = 0; + for (int y = 0; y < Spec.Height; y++) + { + for (int x = 0; x < Spec.Width; x++) + { + if (!Spec.IsActive(x, y)) continue; + if (idx < quantizedCellTemps.Length) + { + Temperature[x, y] = AmbientTemp + quantizedCellTemps[idx++] * 2.0f; + } + } + } + + for (int i = 0; i < Mounted.Count; i++) + { + if (i < mountedTemps.Length) + { + Mounted[i].CurrentTemp = mountedTemps[i]; + Mounted[i].CurrentPerformance = Mounted[i].Spec.Performance(mountedTemps[i]); + } + if (i < mountedCooldowns.Length) + { + Mounted[i].Cooldown = mountedCooldowns[i]; + } + } + } + + public void ApplyReplicatedLoadout( + ChassisSpec spec, + float coreHp, + float maxCoreHp, + ReadOnlySpan armorBytes, + IReadOnlyList<(string ModuleId, string HardpointId)> mounted, + IReadOnlyList? cargoIds, + Func moduleResolver) + { + if (!string.Equals(Spec.Id, spec.Id, StringComparison.Ordinal)) + { + Spec = spec; + Temperature = new float[spec.Width, spec.Height]; + Armor = new float[spec.Width, spec.Height]; + MaxArmor = new float[spec.Width, spec.Height]; + BorderCells = new bool[spec.Width, spec.Height]; + _netHeat = new float[spec.Width, spec.Height]; + _cellThermalMass = new float[spec.Width, spec.Height]; + _cellConductivity = new float[spec.Width, spec.Height]; + InitializeGridState(spec, preserveCoreRatio: false, previousRatio: 1f); + } + + Mounted.Clear(); + for (int i = 0; i < mounted.Count; i++) + { + var (modId, hpId) = mounted[i]; + var modSpec = moduleResolver(modId); + if (modSpec is not null) + { + Mounted.Add(new MountedModule(modSpec, hpId, AmbientTemp)); + } + } + + if (cargoIds is not null) + { + Cargo.Clear(); + for (int i = 0; i < cargoIds.Count; i++) + { + var modSpec = moduleResolver(cargoIds[i]); + if (modSpec is not null) + { + Cargo.Add(modSpec); + } + } + } + + RecalculateArmorAndThermal(grantNewArmorDelta: false); + MaxCoreHp = maxCoreHp > 0f ? maxCoreHp : MaxCoreHp; + CoreHp = Math.Clamp(coreHp, 0f, MaxCoreHp); + ApplyReplicatedArmorBytes(armorBytes); + UpdateMountedTelemetry(); + } + + private (int X, int Y) ResolveHitCell(float localRight, float localForward, float localHeightNorm) + { + int w = Spec.Width; + int h = Spec.Height; + + if (Spec.Plane == GridPlane.Coronal) + { + float targetX = (Math.Clamp(localRight, -1f, 1f) * 0.5f + 0.5f) * (w - 1); + float targetY = (1f - Math.Clamp(localHeightNorm, 0f, 1f)) * (h - 1); + + int bestX = 0; + int bestY = 0; + float bestDistSq = float.PositiveInfinity; + + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + float dx = x - targetX; + float dy = y - targetY; + float d2 = dx * dx + dy * dy; + if (d2 < bestDistSq) + { + bestDistSq = d2; + bestX = x; + bestY = y; + } + } + } + return (bestX, bestY); + } + + // GridPlane.Dorsal: map (localRight, localForward) onto the outer active cell facing the hit. + // Row y=0 is front (+localForward), row y=Height-1 is rear (-localForward). + float dirX = localRight; + float dirY = -localForward; + float len = MathF.Sqrt(dirX * dirX + dirY * dirY); + if (len < 1e-4f) + { + dirX = 0f; + dirY = -1f; + } + else + { + dirX /= len; + dirY /= len; + } + + int bestDx = 0; + int bestDy = 0; + float bestScore = float.NegativeInfinity; + + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + + float nx = (x + 0.5f) / w - 0.5f; + float ny = (y + 0.5f) / h - 0.5f; + + float proj = nx * dirX + ny * dirY; + float alignPenalty = ((nx - dirX * 0.5f) * (nx - dirX * 0.5f) + (ny - dirY * 0.5f) * (ny - dirY * 0.5f)) * 0.05f; + float borderBoost = BorderCells[x, y] ? 0.1f : 0f; + float score = proj + borderBoost - alignPenalty; + + if (score > bestScore) + { + bestScore = score; + bestDx = x; + bestDy = y; + } + } + } + + return (bestDx, bestDy); + } + + private void InitializeGridState(ChassisSpec spec, bool preserveCoreRatio, float previousRatio) + { + int activeCount = 0; + for (int y = 0; y < spec.Height; y++) + { + for (int x = 0; x < spec.Width; x++) + { + Temperature[x, y] = AmbientTemp; + if (!spec.IsActive(x, y)) + { + BorderCells[x, y] = false; + continue; + } + + activeCount++; + bool isBorder = false; + for (int i = 0; i < CardinalOffsets.Length; i++) + { + int nx = x + CardinalOffsets[i].Dx; + int ny = y + CardinalOffsets[i].Dy; + if (!spec.IsActive(nx, ny)) + { + isBorder = true; + break; + } + } + BorderCells[x, y] = isBorder; + } + } + + MaxCoreHp = 100f + activeCount * 8f + spec.BaseCellArmor * 2.5f; + CoreHp = preserveCoreRatio ? MaxCoreHp * Math.Clamp(previousRatio, 0.05f, 1f) : MaxCoreHp; + + RecalculateArmorAndThermal(grantNewArmorDelta: false); + for (int y = 0; y < spec.Height; y++) + { + for (int x = 0; x < spec.Width; x++) + { + Armor[x, y] = MaxArmor[x, y]; + } + } + } + + private void RecalculateArmorAndThermal(bool grantNewArmorDelta) + { + int w = Spec.Width; + int h = Spec.Height; + + float[,] previousMax = (float[,])MaxArmor.Clone(); + + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y)) + { + MaxArmor[x, y] = 0f; + Armor[x, y] = 0f; + _cellThermalMass[x, y] = 1f; + _cellConductivity[x, y] = 0f; + continue; + } + + MaxArmor[x, y] = Spec.BaseCellArmor; + _cellThermalMass[x, y] = Spec.BaseCellThermalMass; + _cellConductivity[x, y] = Spec.HullConductivity; + } + } + + for (int i = 0; i < Spec.Hardpoints.Length; i++) + { + var hp = Spec.Hardpoints[i]; + if (hp.ArmorBonus == 0f) + { + continue; + } + + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int x = hp.X + dx; + int y = hp.Y + dy; + if (Spec.IsActive(x, y)) + { + MaxArmor[x, y] += hp.ArmorBonus; + } + } + } + } + + for (int i = 0; i < Mounted.Count; i++) + { + var mod = Mounted[i]; + var hp = FindHardpoint(mod.HardpointId); + if (hp is null) + { + continue; + } + + int activeCells = CountActiveCellsInHardpoint(hp); + if (activeCells == 0) + { + continue; + } + + float tmShare = mod.Spec.ThermalMass / activeCells; + float armorShare = mod.Spec.ArmorBonus / activeCells; + + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int x = hp.X + dx; + int y = hp.Y + dy; + if (!Spec.IsActive(x, y)) + { + continue; + } + + _cellThermalMass[x, y] += tmShare; + _cellConductivity[x, y] = MathF.Max(_cellConductivity[x, y], mod.Spec.Conductivity); + MaxArmor[x, y] += armorShare; + } + } + } + + if (grantNewArmorDelta) + { + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + float delta = MaxArmor[x, y] - previousMax[x, y]; + if (delta > 0f) + { + Armor[x, y] = MathF.Min(MaxArmor[x, y], Armor[x, y] + delta); + } + else + { + Armor[x, y] = MathF.Min(Armor[x, y], MaxArmor[x, y]); + } + } + } + } + } + + private int CountActiveCellsInHardpoint(HardpointSpec hp) + { + int count = 0; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + if (Spec.IsActive(hp.X + dx, hp.Y + dy)) + { + count++; + } + } + } + return count; + } + + private float GetHardpointAverageTemp(HardpointSpec hp) + { + float sum = 0f; + int count = 0; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int x = hp.X + dx; + int y = hp.Y + dy; + if (Spec.IsActive(x, y)) + { + sum += Temperature[x, y]; + count++; + } + } + } + return count > 0 ? sum / count : AmbientTemp; + } + + private void UpdateMountedTelemetry() + { + for (int i = 0; i < Mounted.Count; i++) + { + var mod = Mounted[i]; + var hp = FindHardpoint(mod.HardpointId); + if (hp is null) + { + continue; + } + float avgTemp = GetHardpointAverageTemp(hp); + mod.CurrentTemp = avgTemp; + mod.CurrentPerformance = mod.Spec.Performance(avgTemp); + } + } + } +} diff --git a/src/RustToDust.Core/IClientArenaSession.cs b/src/RustToDust.Core/IClientArenaSession.cs new file mode 100644 index 0000000..04eef6f --- /dev/null +++ b/src/RustToDust.Core/IClientArenaSession.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Numerics; + +namespace RustToDust.Core +{ + public enum ClientMatchOutcome + { + Active, + Victory, + Defeat + } + + public enum NetworkMode + { + Solo, + ListenHost, + RemoteClient + } + + public readonly record struct NetworkStatusSnapshot( + NetworkMode Mode, + bool Connected, + int PingMs, + int ConnectedHumans, + int MaxHumans, + string StateLabel, + string? LastError = null); + + public readonly record struct ClientRayHit( + bool Hit, + ulong StableId, + Vector3 Point, + Vector3 Normal, + float Fraction); + + public interface IClientArenaSession : IDisposable + { + MatchState ViewState { get; } + int LocalContenderId { get; } + ContenderState LocalContender { get; } + ClientMatchOutcome LocalOutcome { get; } + int LocalDetectedByCount { get; } + IReadOnlyDictionary LocalContenderContacts { get; } + IReadOnlyDictionary LocalSpectatorContacts { get; } + NetworkStatusSnapshot ConnectionStatus { get; } + IReadOnlyList ActivePods { get; } + DropWaveState DropWaveState { get; } + IReadOnlyList PodEvents { get; } + LobbySnapshotDto? LobbyState => null; + + bool IsContenderVisible(int contenderId); + bool IsSpectatorVisible(int spectatorId); + + void BeginRenderFrame(double dt, float physicsAlpha); + void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick); + void DrainSimEvents(List dest); + bool RequestEquipCargo(int cargoIndex, string hardpointId); + void RequestNewMatch(int seed, ArenaMapKind mapKind); + bool SetLobbyReady(bool ready) => false; + bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => RequestLobbyConfig(seed, mapKind, LobbyState?.SquadSize ?? 3); + bool RequestLobbyConfig(int seed, ArenaMapKind mapKind, byte squadSize) => false; + bool RequestLobbySquad(byte targetSquadId) => false; + bool RequestLobbyStart() => false; + + (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha); + (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha); + bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap); + ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation); + } +} diff --git a/src/RustToDust.Core/MatchRules.cs b/src/RustToDust.Core/MatchRules.cs new file mode 100644 index 0000000..196674b --- /dev/null +++ b/src/RustToDust.Core/MatchRules.cs @@ -0,0 +1,975 @@ +using System; +using System.Numerics; + +namespace RustToDust.Core +{ + public delegate bool LineOfSightCheck(float ax, float ay, float az, float bx, float by, float bz); + + public struct PhysicalAimTracker + { + public float AimYawWorld; + public float AimPitchRad; + public bool HasTarget; + public int TargetId; + public float EstPosX; + public float EstPosY; + public float EstPosZ; + public float EstVelX; + public float EstVelY; + public float EstVelZ; + public float PrevSampleX; + public float PrevSampleY; + public float PrevSampleZ; + public bool HasPrevSample; + public float DynamicSpreadRad; + + public void Reset(float yaw) + { + AimYawWorld = MatchRules.NormalizeAngle(yaw); + AimPitchRad = 0f; + HasTarget = false; + TargetId = -1; + EstPosX = 0f; + EstPosY = 0f; + EstPosZ = 0f; + EstVelX = 0f; + EstVelY = 0f; + EstVelZ = 0f; + PrevSampleX = 0f; + PrevSampleY = 0f; + PrevSampleZ = 0f; + HasPrevSample = false; + DynamicSpreadRad = 0.012f; + } + } + + public static class AimTrackerHelper + { + private const float TauVel = 0.38f; + private const float TauPos = 0.16f; + + public static void StepTrackedAim( + ref PhysicalAimTracker tracker, + ChassisGrid shooterGrid, + Vector3 shooterEyePos, + float shooterYaw, + float shooterSpeed, + float shooterYawRate, + ContenderState? target, + float dt, + out float aimX, + out float aimY, + out float aimZ, + out bool wantFire, + float maxFireRange = 165f) + { + float coreRatio = shooterGrid.MaxCoreHp > 0f + ? Math.Clamp(shooterGrid.CoreHp / shooterGrid.MaxCoreHp, 0f, 1f) + : 1f; + float healthRatio = 0.5f + 0.5f * coreRatio; + var spec = shooterGrid.Spec; + float yawDegS = Math.Clamp(185f - spec.MassKg * 0.022f, 65f, 165f) * healthRatio; + float pitchDegS = Math.Clamp(135f - spec.MassKg * 0.015f, 52f, 120f) * healthRatio; + const float degToRad = MathF.PI / 180f; + float yawRadS = yawDegS * degToRad; + float pitchRadS = pitchDegS * degToRad; + float safeDt = MathF.Max(1e-4f, dt); + + if (target is null) + { + tracker.HasTarget = false; + tracker.TargetId = -1; + tracker.HasPrevSample = false; + tracker.EstVelX = 0f; + tracker.EstVelY = 0f; + tracker.EstVelZ = 0f; + tracker.DynamicSpreadRad = 0.012f; + + float yawDiff = MatchRules.NormalizeAngle(shooterYaw - tracker.AimYawWorld); + float maxYawStep = yawRadS * 0.45f * safeDt; + tracker.AimYawWorld = MatchRules.NormalizeAngle( + tracker.AimYawWorld + Math.Clamp(yawDiff, -maxYawStep, maxYawStep)); + + float pitchDiff = 0f - tracker.AimPitchRad; + float maxPitchStep = pitchRadS * 0.45f * safeDt; + tracker.AimPitchRad = Math.Clamp( + tracker.AimPitchRad + Math.Clamp(pitchDiff, -maxPitchStep, maxPitchStep), + -1.25f, + 1.35f); + + float cosP = MathF.Cos(tracker.AimPitchRad); + Vector3 idleDir = new Vector3( + MathF.Sin(tracker.AimYawWorld) * cosP, + MathF.Sin(tracker.AimPitchRad), + MathF.Cos(tracker.AimYawWorld) * cosP); + Vector3 idlePt = shooterEyePos + idleDir * 25f; + aimX = idlePt.X; + aimY = idlePt.Y; + aimZ = idlePt.Z; + wantFire = false; + return; + } + + Vector3 targetPos = new Vector3( + target.X, + MatchRules.GetTargetAimY(target.Y, target.Grid.Spec.HalfHeight), + target.Z); + + if (!tracker.HasTarget || tracker.TargetId != target.Id || !tracker.HasPrevSample) + { + tracker.HasTarget = true; + tracker.TargetId = target.Id; + tracker.EstPosX = targetPos.X; + tracker.EstPosY = targetPos.Y; + tracker.EstPosZ = targetPos.Z; + tracker.EstVelX = 0f; + tracker.EstVelY = 0f; + tracker.EstVelZ = 0f; + tracker.PrevSampleX = targetPos.X; + tracker.PrevSampleY = targetPos.Y; + tracker.PrevSampleZ = targetPos.Z; + tracker.HasPrevSample = true; + } + else + { + float alphaVel = 1f - MathF.Exp(-safeDt / TauVel); + float alphaPos = 1f - MathF.Exp(-safeDt / TauPos); + Vector3 prevSample = new Vector3(tracker.PrevSampleX, tracker.PrevSampleY, tracker.PrevSampleZ); + Vector3 rawObsVel = (targetPos - prevSample) / safeDt; + Vector3 obsVel = new Vector3( + Math.Clamp(rawObsVel.X, -70f, 70f), + Math.Clamp(rawObsVel.Y, -70f, 70f), + Math.Clamp(rawObsVel.Z, -70f, 70f)); + tracker.PrevSampleX = targetPos.X; + tracker.PrevSampleY = targetPos.Y; + tracker.PrevSampleZ = targetPos.Z; + + Vector3 estVel = new Vector3(tracker.EstVelX, tracker.EstVelY, tracker.EstVelZ); + estVel += (obsVel - estVel) * alphaVel; + Vector3 estPos = new Vector3(tracker.EstPosX, tracker.EstPosY, tracker.EstPosZ); + estPos = Vector3.Lerp(estPos + estVel * safeDt, targetPos, alphaPos); + + tracker.EstVelX = estVel.X; + tracker.EstVelY = estVel.Y; + tracker.EstVelZ = estVel.Z; + tracker.EstPosX = estPos.X; + tracker.EstPosY = estPos.Y; + tracker.EstPosZ = estPos.Z; + } + + Vector3 toActual = targetPos - shooterEyePos; + float dist = toActual.Length(); + float leadTime = 0.22f * Math.Clamp(dist / 120f, 0f, 1f); + Vector3 leadPos = new Vector3(tracker.EstPosX, tracker.EstPosY, tracker.EstPosZ) + + new Vector3(tracker.EstVelX, tracker.EstVelY, tracker.EstVelZ) * leadTime; + + Vector3 toLead = leadPos - shooterEyePos; + float leadHoriz = MathF.Sqrt(toLead.X * toLead.X + toLead.Z * toLead.Z); + float desiredYaw = leadHoriz > 1e-4f ? MathF.Atan2(toLead.X, toLead.Z) : tracker.AimYawWorld; + float desiredPitch = Math.Clamp(MathF.Atan2(toLead.Y, MathF.Max(1e-3f, leadHoriz)), -1.25f, 1.35f); + + float yawStep = yawRadS * safeDt; + float yawErr = MatchRules.NormalizeAngle(desiredYaw - tracker.AimYawWorld); + tracker.AimYawWorld = MatchRules.NormalizeAngle( + tracker.AimYawWorld + Math.Clamp(yawErr, -yawStep, yawStep)); + + float pitchStep = pitchRadS * safeDt; + float pitchErr = desiredPitch - tracker.AimPitchRad; + tracker.AimPitchRad = Math.Clamp( + tracker.AimPitchRad + Math.Clamp(pitchErr, -pitchStep, pitchStep), + -1.25f, + 1.35f); + + float cosPitch = MathF.Cos(tracker.AimPitchRad); + Vector3 slewedDir = new Vector3( + MathF.Sin(tracker.AimYawWorld) * cosPitch, + MathF.Sin(tracker.AimPitchRad), + MathF.Cos(tracker.AimYawWorld) * cosPitch); + + float rayDist = MathF.Max(10f, dist); + Vector3 aimPt = shooterEyePos + slewedDir * rayDist; + aimX = aimPt.X; + aimY = aimPt.Y; + aimZ = aimPt.Z; + + Vector3 actualDir = dist > 1e-4f ? toActual / dist : slewedDir; + float angErr = MathF.Acos(Math.Clamp(Vector3.Dot(slewedDir, actualDir), -1f, 1f)); + + Vector3 targetVel = new Vector3(target.VelX, target.VelY, target.VelZ); + if (targetVel.LengthSquared() < 1e-4f) + { + targetVel = new Vector3(tracker.EstVelX, tracker.EstVelY, tracker.EstVelZ); + } + Vector3 perpVel = targetVel - actualDir * Vector3.Dot(targetVel, actualDir); + float vPerp = perpVel.Length(); + float crossOmega = vPerp / MathF.Max(8f, dist); + + tracker.DynamicSpreadRad = Math.Clamp( + 0.012f + crossOmega * 0.18f + shooterSpeed * 0.0012f + MathF.Abs(shooterYawRate) * 0.032f, + 0.010f, + 0.145f); + + wantFire = dist <= maxFireRange && angErr <= 0.24f; + } + } + + public static class MatchRules + { + public const float VtolMinClearanceAgl = 2.5f; + + public static float GetObserverEyeY(float y, float halfHeight) => y + halfHeight * 1.4f; + public static float GetTargetAimY(float y, float halfHeight) => y + halfHeight * 0.35f; + + public static (float MinPitchDeg, float MaxPitchDeg) GetEffectivePitchArc(HardpointSpec hp, ModuleSpec? mod) + { + if (mod is not null && mod.IsWideArc) + { + return (MathF.Min(hp.MinPitchDeg, mod.MinPitchDeg), MathF.Max(hp.MaxPitchDeg, mod.MaxPitchDeg)); + } + if (hp.IsWideArc) + { + return (MathF.Min(hp.MinPitchDeg, -10f), MathF.Max(hp.MaxPitchDeg, 85f)); + } + return (hp.MinPitchDeg, hp.MaxPitchDeg); + } + + public static float ComputeLocalPitchDeg(Vector3 aimDelta, Quaternion chassisQuat) + { + Vector3 local = Vector3.Transform(aimDelta, Quaternion.Conjugate(chassisQuat)); + float horiz = MathF.Sqrt(local.X * local.X + local.Z * local.Z); + return MathF.Atan2(local.Y, horiz) * (180f / MathF.PI); + } + + public static float NormalizeAngle(float rad) + { + if (!float.IsFinite(rad)) + { + return 0f; + } + rad = MathF.IEEERemainder(rad, MathF.Tau); + if (rad > MathF.PI) rad -= MathF.Tau; + if (rad < -MathF.PI) rad += MathF.Tau; + return rad; + } + + public static void ApplyHumanInput(MatchState state, int contenderId, in PlayerInput input) + { + if (contenderId < 0 || contenderId >= state.Contenders.Count) + { + return; + } + + var human = state.Contenders[contenderId]; + if (!human.Alive) + { + human.ThrottleCmd = 0f; + human.SteerCmd = 0f; + human.VerticalThrottleCmd = 0f; + human.FireCmd = false; + human.BrakeCmd = true; + return; + } + + if (human.IsInDropPod) + { + human.ThrottleCmd = Math.Clamp(input.Throttle, -1f, 1f); + human.SteerCmd = Math.Clamp(input.Steer, -1f, 1f); + human.VerticalThrottleCmd = 0f; + human.AimX = float.IsFinite(input.AimWorldX) ? input.AimWorldX : human.AimX; + human.AimY = float.IsFinite(input.AimWorldY) ? input.AimWorldY : float.NaN; + human.AimZ = float.IsFinite(input.AimWorldZ) ? input.AimWorldZ : human.AimZ; + human.FireCmd = false; + human.BrakeCmd = false; + state.OrbitalDrop.ApplyPlayerSteerInput(human); + return; + } + + human.ThrottleCmd = Math.Clamp(input.Throttle, -1f, 1f); + human.SteerCmd = Math.Clamp(input.Steer, -1f, 1f); + human.VerticalThrottleCmd = Math.Clamp(input.VerticalThrottle, -1f, 1f); + human.AimX = float.IsFinite(input.AimWorldX) ? input.AimWorldX : human.AimX; + human.AimY = float.IsFinite(input.AimWorldY) ? input.AimWorldY : float.NaN; + human.AimZ = float.IsFinite(input.AimWorldZ) ? input.AimWorldZ : human.AimZ; + human.FireCmd = input.Fire; + human.BrakeCmd = input.Brake; + + if (input.InteractPickup) + { + state.TryInteractNearestDrop(contenderId); + } + } + + public static void UpdateAiContenders(MatchState state, float dt, LineOfSightCheck? hasLos = null) + { + float safeLimit = MathF.Max(30f, state.Spectators.SafeRadius - 25f); + + for (int i = 0; i < state.Contenders.Count; i++) + { + var ai = state.Contenders[i]; + if (ai.IsHuman) + { + continue; + } + if (ai.IsInDropPod) + { + ai.FireCmd = false; + state.OrbitalDrop.UpdateAiPodSteering(ai); + continue; + } + if (!ai.IsGroundedActive) + { + continue; + } + + ai.AiScavengeCooldown = MathF.Max(0f, ai.AiScavengeCooldown - dt); + AutoEquipAiCargo(state, ai); + + float distFromCenter = MathF.Sqrt(ai.X * ai.X + ai.Z * ai.Z); + float goalX = 0f; + float goalZ = 0f; + bool hasGoal = false; + + // 1. Stay inside the shrinking Safe Circle + if (distFromCenter > safeLimit) + { + goalX = 0f; + goalZ = 0f; + hasGoal = true; + } + + // 2. Find nearest hostile contender with actual live line-of-sight + ContenderState? target = null; + float bestEnemyDistSq = 215f * 215f; + float aiEyeY = GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight); + for (int j = 0; j < state.Contenders.Count; j++) + { + var other = state.Contenders[j]; + if (other.Id == ai.Id || state.AreAllies(ai.Id, other.Id) || !other.IsGroundedActive) + { + continue; + } + + float dx = other.X - ai.X; + float dz = other.Z - ai.Z; + float d2 = dx * dx + dz * dz; + if (d2 >= bestEnemyDistSq) + { + continue; + } + + if (hasLos is not null && + !hasLos(ai.X, aiEyeY, ai.Z, other.X, GetTargetAimY(other.Y, other.Grid.Spec.HalfHeight), other.Z)) + { + continue; + } + + bestEnemyDistSq = d2; + target = other; + } + ai.AiTargetContenderId = target?.Id; + + // 3. Scavenge nearby chassis & module upgrades + bool inStarter = string.Equals(ai.Grid.Spec.Id, "jackal", StringComparison.OrdinalIgnoreCase); + if (!hasGoal && ai.AiScavengeCooldown <= 0f) + { + float scavengeRadius = (inStarter || CountMountedWeapons(ai.Grid) < 2) + ? (state.MapKind == ArenaMapKind.Sion ? 340f : 260f) + : 140f; + float scavengeRadiusSq = scavengeRadius * scavengeRadius; + int currentUpgradeScore = Catalog.GetChassisUpgradeScore(ai.Grid.Spec); + + GroundDrop? bestDrop = null; + float bestDropScore = float.PositiveInfinity; + float bestDropDistSq = float.PositiveInfinity; + for (int d = 0; d < state.GroundDrops.Count; d++) + { + var drop = state.GroundDrops[d]; + if (drop.PickedUp) + { + continue; + } + + if (drop.Chassis is not null && + Catalog.GetChassisUpgradeScore(drop.Chassis) <= currentUpgradeScore) + { + continue; + } + + float dx = drop.X - ai.X; + float dz = drop.Z - ai.Z; + float d2 = dx * dx + dz * dz; + if (d2 > scavengeRadiusSq) + { + continue; + } + + float dist = MathF.Sqrt(d2); + float score = (inStarter && drop.Chassis is not null) ? dist * 0.45f : dist; + if (score < bestDropScore) + { + bestDropScore = score; + bestDropDistSq = d2; + bestDrop = drop; + } + } + + if (bestDrop is not null) + { + bool pushScavenge; + if (target is null) + { + pushScavenge = true; + } + else + { + float enemyDist = MathF.Sqrt(bestEnemyDistSq); + if (inStarter) + { + if (bestDrop.Chassis is not null) + { + float dropDist = MathF.Sqrt(bestDropDistSq); + pushScavenge = dropDist < enemyDist * 0.85f || enemyDist > 65f; + } + else + { + pushScavenge = enemyDist > 65f; + } + } + else + { + pushScavenge = enemyDist > 65f; + } + } + + if (pushScavenge) + { + goalX = bestDrop.X; + goalZ = bestDrop.Z; + hasGoal = true; + } + + if (bestDropDistSq <= MatchState.PickupRadius * MatchState.PickupRadius) + { + if (bestDrop.Module is not null) + { + state.TryPickupNearbyModule(ai.Id); + } + else if (bestDrop.Chassis is not null) + { + state.TrySwapNearbyChassis(ai.Id, bestDrop.Id); + } + ai.AiScavengeCooldown = MathF.Max(ai.AiScavengeCooldown, 2.5f); + } + } + } + + // 4. Combat or third-party gunfire investigation + if (target is not null) + { + float dist = MathF.Sqrt(bestEnemyDistSq); + if (!hasGoal) + { + if (dist > 75f) + { + goalX = target.X; + goalZ = target.Z; + } + else + { + // Orbit target instead of ramming headlong + float tangentAngle = MathF.Atan2(ai.Z - target.Z, ai.X - target.X) + 0.7f; + goalX = target.X + MathF.Cos(tangentAngle) * 52f; + goalZ = target.Z + MathF.Sin(tangentAngle) * 52f; + } + hasGoal = true; + } + } + else if (!hasGoal && state.LastGunfireX.HasValue && state.LastGunfireZ.HasValue && + state.Time - state.LastGunfireTime < 12f) + { + float gdx = state.LastGunfireX.Value - ai.X; + float gdz = state.LastGunfireZ.Value - ai.Z; + if (gdx * gdx + gdz * gdz <= 340f * 340f) + { + goalX = state.LastGunfireX.Value; + goalZ = state.LastGunfireZ.Value; + hasGoal = true; + } + } + + if (!hasGoal) + { + float patrolAngle = ai.Id * 0.9f + state.Time * 0.12f; + float r = MathF.Min(safeLimit * 0.65f, state.MapKind == ArenaMapKind.Sion ? 480f : 190f); + goalX = MathF.Cos(patrolAngle) * r; + goalZ = MathF.Sin(patrolAngle) * r; + } + + float toGoalX = goalX - ai.X; + float toGoalZ = goalZ - ai.Z; + float desiredYaw = MathF.Atan2(toGoalX, toGoalZ); + float yawError = NormalizeAngle(desiredYaw - ai.Yaw); + + ai.SteerCmd = Math.Clamp(yawError * 1.8f, -1f, 1f); + ai.ThrottleCmd = MathF.Abs(yawError) > 1.25f ? 0.35f : 0.85f; + ai.BrakeCmd = false; + if (ai.Grid.Spec.IsVtol) + { + float groundH = state.Terrain.SampleHeight(ai.X, ai.Z); + float currentAgl = ai.Y - ai.Grid.Spec.HalfHeight - groundH; + float desiredAgl = target is null + ? MathF.Min(ai.Grid.Spec.HoverMaxAltitudeM * 0.6f, 22f) + : MathF.Min(ai.Grid.Spec.HoverMaxAltitudeM * 0.45f, 14f + 4f * MathF.Sin(state.Time * 0.9f + ai.Id)); + ai.VerticalThrottleCmd = Math.Clamp((desiredAgl - currentAgl) * 0.25f, -1f, 1f); + } + else + { + ai.VerticalThrottleCmd = 0f; + } + + float shooterYawRate = ai.SteerCmd * ai.Grid.ComputeTurnRate(); + AimTrackerHelper.StepTrackedAim( + ref ai.AimTracker, + ai.Grid, + new Vector3(ai.X, aiEyeY, ai.Z), + ai.Yaw, + ai.Speed, + shooterYawRate, + target, + dt, + out float aimX, + out float aimY, + out float aimZ, + out bool wantFire, + maxFireRange: 165f); + + ai.AimX = aimX; + ai.AimY = aimY; + ai.AimZ = aimZ; + ai.AiAimSpreadRad = ai.AimTracker.DynamicSpreadRad; + ai.FireCmd = wantFire; + } + } + + private static int CountMountedWeapons(ChassisGrid grid) + { + int count = 0; + for (int i = 0; i < grid.Mounted.Count; i++) + { + if (grid.Mounted[i].Spec.Kind == HardpointKind.Weapon) + { + count++; + } + } + return count; + } + + public static void ComputeSpectatorBehavior( + SpectatorState spec, + MatchState state, + out float goalX, + out float goalZ, + out float aimX, + out float aimZ, + out bool shouldFire, + float dt = 1f / 60f) + { + float specEyeY = GetObserverEyeY(spec.Y, spec.Grid.Spec.HalfHeight); + if (spec.Stance == SpectatorStance.Neutral || !spec.TargetContenderId.HasValue) + { + (goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes, state.SionMap); + AimTrackerHelper.StepTrackedAim( + ref spec.AimTracker, + spec.Grid, + new Vector3(spec.X, specEyeY, spec.Z), + spec.Yaw, + 0f, + 0f, + target: null, + dt, + out float idleAimX, + out float idleAimY, + out float idleAimZ, + out _); + spec.AimX = idleAimX; + spec.AimY = idleAimY; + spec.AimZ = idleAimZ; + spec.DynamicAimSpreadRad = spec.AimTracker.DynamicSpreadRad; + spec.FireCmd = false; + aimX = 0f; + aimZ = 0f; + shouldFire = false; + return; + } + + ContenderState? target = null; + int targetId = spec.TargetContenderId.Value; + if (targetId >= 0 && targetId < state.Contenders.Count) + { + target = state.Contenders[targetId]; + } + + if (target is null || !target.Alive) + { + (goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes, state.SionMap); + AimTrackerHelper.StepTrackedAim( + ref spec.AimTracker, + spec.Grid, + new Vector3(spec.X, specEyeY, spec.Z), + spec.Yaw, + 0f, + 0f, + target: null, + dt, + out float idleAimX, + out float idleAimY, + out float idleAimZ, + out _); + spec.AimX = idleAimX; + spec.AimY = idleAimY; + spec.AimZ = idleAimZ; + spec.DynamicAimSpreadRad = spec.AimTracker.DynamicSpreadRad; + spec.FireCmd = false; + aimX = 0f; + aimZ = 0f; + shouldFire = false; + return; + } + + // Occluded behind terrain/cover: never shoot through rock! Never fall back to live target.X/Z while occluded. + if (!spec.HasTargetLos) + { + shouldFire = false; + bool hasMemory = spec.TimeSinceLastSeen < SpectatorRing.TargetMemoryDuration; + float focusX = spec.LastKnownTargetX; + float focusZ = spec.LastKnownTargetZ; + AimTrackerHelper.StepTrackedAim( + ref spec.AimTracker, + spec.Grid, + new Vector3(spec.X, specEyeY, spec.Z), + spec.Yaw, + 0f, + 0f, + target: null, + dt, + out _, + out float occAimY, + out _, + out _); + spec.DynamicAimSpreadRad = spec.AimTracker.DynamicSpreadRad; + spec.FireCmd = false; + aimX = focusX; + aimZ = focusZ; + spec.AimX = aimX; + spec.AimY = occAimY; + spec.AimZ = aimZ; + + if (!hasMemory) + { + var (anchorX, anchorZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes, state.SionMap); + float toFocusX = focusX - spec.X; + float toFocusZ = focusZ - spec.Z; + float toFocusLen = MathF.Sqrt(toFocusX * toFocusX + toFocusZ * toFocusZ); + bool hasValidFocus = (focusX != 0f || focusZ != 0f) && toFocusLen > 12f && toFocusLen < 240f; + float centerX = hasValidFocus ? focusX : anchorX; + float centerZ = hasValidFocus ? focusZ : anchorZ; + + float bestX = centerX; + float bestZ = centerZ; + float bestH = state.Terrain.SampleHeight(bestX, bestZ); + float maxBound = state.Terrain.MapHalfExtent - 18f; + for (int k = 0; k < 4; k++) + { + float ang = spec.Id * 0.7f + k * (MathF.PI * 0.5f); + float cx = Math.Clamp(centerX + MathF.Cos(ang) * 26f, -maxBound, maxBound); + float cz = Math.Clamp(centerZ + MathF.Sin(ang) * 26f, -maxBound, maxBound); + if (state.SionMap is not null && state.SionMap.IsInsideAnyBuildingXz(cx, cz, 3.5f)) + { + continue; + } + float h = state.Terrain.SampleHeight(cx, cz); + if (h > bestH) + { + bestH = h; + bestX = cx; + bestZ = cz; + } + } + + goalX = bestX; + goalZ = bestZ; + return; + } + + float fdx = focusX - spec.X; + float fdz = focusZ - spec.Z; + float fLen = MathF.Sqrt(fdx * fdx + fdz * fdz); + if (fLen < 1f) + { + (goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes, state.SionMap); + return; + } + + float dirX = fdx / fLen; + float dirZ = fdz / fLen; + float perpX = -dirZ; + float perpZ = dirX; + float sideSign = (spec.Id & 1) == 0 ? 1f : -1f; + + // Evaluate flanking steps (left flank, right flank, crest-climb toward last-known position) + float step = MathF.Min(42f, fLen * 0.65f); + float cand1X = spec.X + (dirX * 0.65f + perpX * 0.76f * sideSign) * step; + float cand1Z = spec.Z + (dirZ * 0.65f + perpZ * 0.76f * sideSign) * step; + float cand2X = spec.X + (dirX * 0.65f - perpX * 0.76f * sideSign) * step; + float cand2Z = spec.Z + (dirZ * 0.65f - perpZ * 0.76f * sideSign) * step; + + float h1 = state.Terrain.SampleHeight(cand1X, cand1Z); + float h2 = state.Terrain.SampleHeight(cand2X, cand2Z); + + // Prefer the flanking shoulder that gets higher ground (sightline over ridge) unless it is a steep cliff + if (h1 >= h2) + { + goalX = cand1X; + goalZ = cand1Z; + } + else + { + goalX = cand2X; + goalZ = cand2Z; + } + return; + } + + float dx = target.X - spec.X; + float dz = target.Z - spec.Z; + float dist = MathF.Sqrt(dx * dx + dz * dz); + + if (dist > spec.PreferredRange) + { + goalX = target.X; + goalZ = target.Z; + } + else + { + float angle = MathF.Atan2(spec.Z - target.Z, spec.X - target.X) + (spec.Tier == SpectatorTier.Exemplar ? 0.9f : 0.4f); + goalX = target.X + MathF.Cos(angle) * (spec.PreferredRange * 0.85f); + goalZ = target.Z + MathF.Sin(angle) * (spec.PreferredRange * 0.85f); + } + + float specSpeed = MathF.Sqrt(spec.VelX * spec.VelX + spec.VelZ * spec.VelZ); + float desiredYaw = dist > 1e-3f ? MathF.Atan2(dx, dz) : spec.Yaw; + float yawErr = NormalizeAngle(desiredYaw - spec.Yaw); + float yawRate = Math.Clamp(yawErr * 3f, -5f, 5f); + + AimTrackerHelper.StepTrackedAim( + ref spec.AimTracker, + spec.Grid, + new Vector3(spec.X, specEyeY, spec.Z), + spec.Yaw, + specSpeed, + yawRate, + target, + dt, + out aimX, + out float aimY, + out aimZ, + out shouldFire, + maxFireRange: 255f); + + spec.AimX = aimX; + spec.AimY = aimY; + spec.AimZ = aimZ; + spec.DynamicAimSpreadRad = spec.AimTracker.DynamicSpreadRad; + + // Tourists self-throttle when their Imperial weapons run hot + if (shouldFire && spec.Tier == SpectatorTier.Tourist) + { + for (int i = 0; i < spec.Grid.Mounted.Count; i++) + { + var m = spec.Grid.Mounted[i]; + if (m.Spec.Kind == HardpointKind.Weapon && + m.CurrentTemp > m.Spec.OptimalTemp + m.Spec.PlateauWidth * 0.45f) + { + shouldFire = false; + break; + } + } + } + + spec.FireCmd = shouldFire; + } + + public static void AdvanceTracers(MatchState state, float dt) + { + for (int i = state.Tracers.Count - 1; i >= 0; i--) + { + var t = state.Tracers[i]; + float nextTtl = t.Ttl - dt; + if (nextTtl <= 0f) + { + state.Tracers.RemoveAt(i); + } + else + { + state.Tracers[i] = t with { Ttl = nextTtl }; + } + } + } + + public static void AdvanceHitEvents(MatchState state, float dt) + { + for (int i = state.HitEvents.Count - 1; i >= 0; i--) + { + var h = state.HitEvents[i]; + float nextTtl = h.Ttl - dt; + if (nextTtl <= 0f) + { + state.HitEvents.RemoveAt(i); + } + else + { + state.HitEvents[i] = h with { Ttl = nextTtl }; + } + } + } + + public static void UpdateMatchOutcome(MatchState state) + { + if (state.Phase != MatchPhase.Active) + { + return; + } + + state.OrbitalDrop.CheckFinalRingCutoff(); + + bool canRespawn = state.OrbitalDrop.CanAnyWaitingContenderRespawn(); + if (state.SquadSize > 1) + { + uint aliveSquadMask = 0; + ContenderState? lowestActive = null; + ContenderState? lowestWaiting = null; + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (c.Alive) + { + if (c.SquadId < 32) + { + aliveSquadMask |= 1u << c.SquadId; + } + if (lowestActive is null || c.Id < lowestActive.Id) + { + lowestActive = c; + } + } + else if (c.WaitingForRespawn && canRespawn) + { + if (c.SquadId < 32) + { + aliveSquadMask |= 1u << c.SquadId; + } + if (lowestWaiting is null || c.Id < lowestWaiting.Id) + { + lowestWaiting = c; + } + } + } + + int survivingSquads = BitOperations.PopCount(aliveSquadMask); + if (survivingSquads <= 1) + { + var winner = lowestActive ?? lowestWaiting; + state.Phase = MatchPhase.Completed; + state.WinnerContenderId = winner?.Id; + if (winner is not null) + { + state.Broadcast.EmitVictory(state.Time, winner.Id, state.MapKind); + } + } + return; + } + + int aliveCount = 0; + int waitingCount = 0; + ContenderState? survivor = null; + + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (c.Alive) + { + aliveCount++; + survivor = c; + } + else if (c.WaitingForRespawn && canRespawn) + { + waitingCount++; + } + } + + if (aliveCount + waitingCount <= 1) + { + state.Phase = MatchPhase.Completed; + state.WinnerContenderId = survivor?.Id; + if (survivor is not null) + { + state.Broadcast.EmitVictory(state.Time, survivor.Id, state.MapKind); + } + } + } + + private static void AutoEquipAiCargo(MatchState state, ContenderState ai) + { + if (ai.Grid.Cargo.Count == 0) + { + return; + } + + for (int c = ai.Grid.Cargo.Count - 1; c >= 0; c--) + { + var item = ai.Grid.Cargo[c]; + for (int h = 0; h < ai.Grid.Spec.Hardpoints.Length; h++) + { + var hp = ai.Grid.Spec.Hardpoints[h]; + if (!ChassisGrid.CanFit(hp, item)) + { + continue; + } + + var mounted = ai.Grid.GetMountedOn(hp.Id); + if (mounted is null || IsBetterModule(item, mounted.Spec)) + { + state.TryEquipCargo(ai.Id, c, hp.Id); + break; + } + } + } + } + + public static float GetModulePowerScore(ModuleSpec mod) => + mod.EffectivePowerScore > 0f + ? mod.EffectivePowerScore + : mod.WeaponDamage * MathF.Max(1, mod.BurstCount); + + private static bool IsBetterModule(ModuleSpec candidate, ModuleSpec current) + { + if (candidate.Kind == HardpointKind.Weapon && current.Kind == HardpointKind.Weapon) + { + return GetModulePowerScore(candidate) > GetModulePowerScore(current); + } + + if (candidate.IsImperial && !current.IsImperial) + { + return true; + } + + return candidate.Kind switch + { + HardpointKind.Engine => candidate.ThrustBonus > current.ThrustBonus, + HardpointKind.Radiator => candidate.CoolingPower > current.CoolingPower, + HardpointKind.Armor => candidate.ArmorBonus > current.ArmorBonus, + _ => false + }; + } + } +} diff --git a/src/RustToDust.Core/MatchState.cs b/src/RustToDust.Core/MatchState.cs new file mode 100644 index 0000000..1b1ef5e --- /dev/null +++ b/src/RustToDust.Core/MatchState.cs @@ -0,0 +1,2049 @@ +using System; +using System.Collections.Generic; +using System.Numerics; + +namespace RustToDust.Core +{ + public enum MatchPhase + { + Active = 0, + Completed = 1, + Lobby = 2 + } + + public sealed class LobbySlotState + { + public int SlotId { get; init; } + public string Callsign { get; set; } = string.Empty; + public bool IsHuman { get; set; } + public bool IsReady { get; set; } + public byte SquadId { get; set; } + } + + public sealed class LobbyState + { + public const float DefaultCountdownSeconds = 5.0f; + + public LobbyState( + int contenderCount, + ArenaMapKind mapKind, + int seed, + int? hostSlotId = null, + int minHumansToAutoStart = 1, + byte squadSize = 3) + { + SelectedMap = mapKind; + SelectedSeed = seed; + HostSlotId = hostSlotId; + MinHumansToAutoStart = Math.Max(1, minHumansToAutoStart); + SquadSize = (byte)Math.Clamp((int)squadSize, 1, 4); + Slots = new LobbySlotState[contenderCount]; + for (int i = 0; i < contenderCount; i++) + { + Slots[i] = new LobbySlotState + { + SlotId = i, + Callsign = $"Contender {i + 1:00}", + SquadId = SquadSize > 1 ? (byte)(i / SquadSize) : (byte)i + }; + } + } + + public int? HostSlotId { get; set; } + public int MinHumansToAutoStart { get; set; } = 1; + public float? CountdownSeconds { get; set; } + public bool ForceLaunched { get; set; } + public ArenaMapKind SelectedMap { get; set; } + public int SelectedSeed { get; set; } + public byte SquadSize { get; set; } = 3; + public LobbySlotState[] Slots { get; } + } + + public readonly record struct PlayerInput( + float Throttle, + float Steer, + float AimWorldX, + float AimWorldZ, + bool Fire, + bool InteractPickup, + bool Brake, + float AimWorldY = float.NaN, + float VerticalThrottle = 0f); + + public enum WeaponVisualClass + { + KineticLight = 0, + Autocannon = 1, + Explosive = 2, + ThermalBeam = 3, + GaussRail = 4, + PlasmaPpc = 5, + RocketSalvo = 6, + SwarmSmart = 7 + } + + public enum HitTargetKind + { + Terrain, + StaticCover, + Contender, + Spectator + } + + public readonly record struct TracerEvent( + float StartX, + float StartY, + float StartZ, + float EndX, + float EndY, + float EndZ, + uint ColorRgba, + float Ttl, + WeaponVisualClass WeaponClass = WeaponVisualClass.KineticLight, + string WeaponId = "", + int Id = 0); + + public readonly record struct HitFeedbackEvent( + long EventId, + float HitX, + float HitY, + float HitZ, + float NormalX, + float NormalY, + float NormalZ, + float SourceX, + float SourceY, + float SourceZ, + HitTargetKind TargetKind, + int TargetId, + int CellX, + int CellY, + WeaponVisualClass WeaponClass, + string WeaponId, + bool IsAirburst, + float Ttl); + + public readonly record struct ArenaBoxSpec( + float X, + float Y, + float Z, + float HalfX, + float HalfY, + float HalfZ, + bool IsBoundary); + + public sealed class PlayerContactMemory + { + public bool VisibleToPlayer { get; set; } + public float LastSeenAge { get; set; } = float.PositiveInfinity; + public float LastSeenX { get; set; } + public float LastSeenZ { get; set; } + public bool HasEverBeenSeen { get; set; } + public bool FaintHorizonPing { get; set; } + } + + public sealed class ObserverDetectionState + { + public Dictionary ContenderContacts { get; } = new(); + public Dictionary SpectatorContacts { get; } = new(); + public int DetectedByCount { get; set; } + + public PlayerContactMemory GetOrCreateContenderContact(int contenderId) + { + if (!ContenderContacts.TryGetValue(contenderId, out var mem)) + { + mem = new PlayerContactMemory(); + ContenderContacts[contenderId] = mem; + } + return mem; + } + + public PlayerContactMemory GetOrCreateSpectatorContact(int spectatorId) + { + if (!SpectatorContacts.TryGetValue(spectatorId, out var mem)) + { + mem = new PlayerContactMemory(); + SpectatorContacts[spectatorId] = mem; + } + return mem; + } + } + + public sealed class GroundDrop + { + public GroundDrop(int id, float x, float z, ChassisSpec? chassis, ModuleSpec? module) + { + Id = id; + X = x; + Z = z; + Chassis = chassis; + Module = module; + } + + public int Id { get; } + public float X { get; } + public float Z { get; } + public ChassisSpec? Chassis { get; } + public ModuleSpec? Module { get; } + public bool PickedUp { get; set; } + } + + public sealed class ContenderState + { + public ContenderState(int id, string name, bool isHuman, ChassisGrid grid, float x, float z, float yaw) + { + Id = id; + Name = name; + IsHuman = isHuman; + Grid = grid; + X = x; + Y = grid.Spec.HalfHeight + 0.1f; + Z = z; + Yaw = yaw; + AimX = x + MathF.Sin(yaw) * 20f; + AimY = Y; + AimZ = z + MathF.Cos(yaw) * 20f; + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw); + CurrRotX = q.X; + CurrRotY = q.Y; + CurrRotZ = q.Z; + CurrRotW = q.W; + SnapPreviousPose(); + ResetAimTracker(yaw); + } + + public int Id { get; } + public string Name { get; set; } + public bool IsHuman { get; set; } + public byte SquadId { get; set; } + public ChassisGrid Grid { get; set; } + public ContenderLifecycle Lifecycle { get; set; } = ContenderLifecycle.Active; + public int RespawnsRemaining { get; set; } = 1; + public int? ActivePodId { get; set; } + public bool HasTouchdownPose { get; set; } + public bool TouchdownOnRoof { get; set; } + public int LoadoutVersion { get; set; } = 1; + public int DamageVersion { get; set; } = 1; + public float MaxThermalRatio { get; set; } + public float X { get; set; } + public float Y { get; set; } + public float Z { get; set; } + public float Yaw { get; set; } + public float PrevX { get; set; } + public float PrevY { get; set; } + public float PrevZ { get; set; } + public float PrevRotX { get; set; } + public float PrevRotY { get; set; } + public float PrevRotZ { get; set; } + public float PrevRotW { get; set; } = 1f; + public float CurrRotX { get; set; } + public float CurrRotY { get; set; } + public float CurrRotZ { get; set; } + public float CurrRotW { get; set; } = 1f; + public float VelX { get; set; } + public float VelY { get; set; } + public float VelZ { get; set; } + public float AimX { get; set; } + public float AimY { get; set; } + public float AimZ { get; set; } + public PhysicalAimTracker AimTracker; + public float AiAimSpreadRad { get; set; } = 0.012f; + public float Speed { get; set; } + public int Kills { get; set; } + public bool OverheatWarned { get; set; } + + public float ThrottleCmd { get; set; } + public float SteerCmd { get; set; } + public float VerticalThrottleCmd { get; set; } + public float TargetHoverAltAgl { get; set; } = 3.0f; + public bool FireCmd { get; set; } + public bool BrakeCmd { get; set; } + public float AiScavengeCooldown { get; set; } + public int? AiTargetContenderId { get; set; } + public bool AllWeaponsOutOfArc { get; set; } + public int OutOfArcWeaponCount { get; set; } + public int InArcWeaponCount { get; set; } + public int DisabledWeaponCount { get; set; } + + public bool IsInDropPod => Lifecycle == ContenderLifecycle.Deploying; + public bool IsGroundedActive => Lifecycle == ContenderLifecycle.Active && !Grid.IsDestroyed; + public bool WaitingForRespawn => Lifecycle == ContenderLifecycle.WaitingForRespawnWave; + public bool Alive => !Grid.IsDestroyed && (Lifecycle == ContenderLifecycle.Active || Lifecycle == ContenderLifecycle.Deploying); + + public void ResetForRedrop(ChassisGrid grid, float x, float y, float z, float yaw) + { + Grid = grid; + X = x; + Y = y; + Z = z; + Yaw = yaw; + VelX = 0f; + VelY = 0f; + VelZ = 0f; + Speed = 0f; + ThrottleCmd = 0f; + SteerCmd = 0f; + VerticalThrottleCmd = 0f; + TargetHoverAltAgl = grid.Spec.IsVtol ? 10.0f : 3.0f; + FireCmd = false; + BrakeCmd = false; + OverheatWarned = false; + MaxThermalRatio = 0f; + AllWeaponsOutOfArc = false; + OutOfArcWeaponCount = 0; + InArcWeaponCount = 0; + DisabledWeaponCount = 0; + HasTouchdownPose = false; + TouchdownOnRoof = false; + Lifecycle = ContenderLifecycle.Deploying; + LoadoutVersion++; + DamageVersion++; + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw); + CurrRotX = q.X; + CurrRotY = q.Y; + CurrRotZ = q.Z; + CurrRotW = q.W; + SnapPreviousPose(); + ResetAimTracker(yaw); + } + + public void SnapPreviousPose() + { + PrevX = X; + PrevY = Y; + PrevZ = Z; + PrevRotX = CurrRotX; + PrevRotY = CurrRotY; + PrevRotZ = CurrRotZ; + PrevRotW = CurrRotW; + } + + public void ResetAimTracker(float yaw) + { + AimTracker.Reset(yaw); + AiAimSpreadRad = AimTracker.DynamicSpreadRad; + AimX = X + MathF.Sin(yaw) * 25f; + AimY = Y; + AimZ = Z + MathF.Cos(yaw) * 25f; + FireCmd = false; + } + } + + public sealed class MatchState + { + public const int ContenderCount = 12; + public const float ArenaHalfExtent = 772f; + public const float PickupRadius = 7.0f; + public const float ContactGhostDuration = 5.0f; + public const float TouristHorizonMaxRange = 420f; + + public const float SionInitialSafeRadius = 1150f; + public const float SionMinSafeRadius = 120f; + + private int _nextDropId = 1; + private long _nextHitEventId = 1; + private int _nextTracerId = 1; + private readonly bool _pendingSkipInitialDrop; + private readonly List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> _pendingLootTargets; + private readonly List<(int ContenderId, float X, float Z, float Yaw)> _pendingContenderTargets; + + public MatchState( + int seed = 42, + ArenaMapKind mapKind = ArenaMapKind.Desert, + bool skipInitialDrop = false, + bool startInLobby = false, + byte squadSize = 1, + ArenaScarLedgerSnapshot? initialScars = null) + { + Seed = seed; + MapKind = mapKind; + SquadSize = (byte)Math.Clamp((int)squadSize, 1, 4); + _pendingSkipInitialDrop = skipInitialDrop; + Rng = new Random(seed); + Broadcast = new BroadcastFeed(); + OrbitalDrop = new OrbitalDropSystem(this); + _pendingContenderTargets = new List<(int ContenderId, float X, float Z, float Yaw)>(ContenderCount); + + List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> lootTargets; + if (mapKind == ArenaMapKind.Sion) + { + SionMap = SionMapLoader.Load(); + Terrain = TerrainField.LoadSharedHeightmap( + SionMap.Metadata.SizeMeters, + SionMap.Metadata.GridRes, + SionMap.Metadata.TileGrid, + SionMap.BaseDem, + SionMap.BaseDemMinY, + SionMap.BaseDemScale, + SionMap.Metadata.MinY, + SionMap.Metadata.MaxY, + (ulong)seed); + ScarLedger = new ArenaScarLedger(SionMap.AssetFingerprint); + if (initialScars is not null) + { + ApplyPersistentScars(initialScars); + } + Spectators = new SpectatorRing( + seed + 101, + SpectatorRing.DefaultSpectatorCount, + initialRadius: SionInitialSafeRadius, + minRadius: SionMinSafeRadius, + arenaHalfExtent: Terrain.MapHalfExtent); + ArenaCoverBoxes = Array.Empty(); + ArenaBoundaryBoxes = BuildBoundaryBoxes( + Terrain.MapHalfExtent + 4f, + SionMap.Metadata.MinY - 12f, + SionMap.Metadata.MaxY + 140f); + SeatSpectatorsOnSion(); + SpawnContendersSion(); + AssignDefaultSquadIds(); + ApplySquadFormationTargets(); + lootTargets = BuildInitialLootTargetsSion(); + } + else + { + Spectators = new SpectatorRing(seed + 101); + var rawCover = BuildCoverBoxes(); + Terrain = TerrainField.Generate((ulong)seed, rawCover); + ScarLedger = new ArenaScarLedger($"desert:{seed}"); + if (initialScars is not null) + { + ApplyPersistentScars(initialScars); + } + ArenaCoverBoxes = SeatBoxesOnTerrain(rawCover, Terrain); + ArenaBoundaryBoxes = BuildBoundaryBoxes(ArenaHalfExtent, -48f, 72f); + SpawnContenders(); + AssignDefaultSquadIds(); + ApplySquadFormationTargets(); + lootTargets = BuildInitialLootTargetsDesert(); + } + + _pendingLootTargets = lootTargets; + + if (startInLobby) + { + Phase = MatchPhase.Lobby; + Lobby = new LobbyState(ContenderCount, mapKind, seed, squadSize: SquadSize); + for (int i = 0; i < Contenders.Count; i++) + { + Contenders[i].Lifecycle = ContenderLifecycle.Deploying; + } + } + else if (skipInitialDrop) + { + for (int i = 0; i < Contenders.Count; i++) + { + Contenders[i].Lifecycle = ContenderLifecycle.Active; + } + for (int i = 0; i < lootTargets.Count; i++) + { + var t = lootTargets[i]; + if (t.Chassis is not null) SpawnChassisDrop(t.X, t.Z, t.Chassis); + else if (t.Module is not null) SpawnModuleDrop(t.X, t.Z, t.Module); + } + Broadcast.EmitMatchStart(0f, mapKind); + } + else + { + OrbitalDrop.BeginWave0(_pendingContenderTargets, _pendingLootTargets, DefaultDropSurfaceQuery); + Broadcast.EmitMatchStart(0f, mapKind); + } + } + + public bool StartFromLobby(DropSurfaceQuery? surfaceQuery = null) + { + if (Phase != MatchPhase.Lobby) + { + return false; + } + + Phase = MatchPhase.Active; + Time = 0f; + WinnerContenderId = null; + if (Lobby is not null) + { + Lobby.CountdownSeconds = null; + Lobby.ForceLaunched = false; + for (int i = 0; i < Contenders.Count && i < Lobby.Slots.Length; i++) + { + Contenders[i].SquadId = SquadSize > 1 ? Lobby.Slots[i].SquadId : (byte)i; + } + } + ApplySquadFormationTargets(); + + if (_pendingSkipInitialDrop) + { + for (int i = 0; i < Contenders.Count; i++) + { + Contenders[i].Lifecycle = ContenderLifecycle.Active; + } + for (int i = 0; i < _pendingLootTargets.Count; i++) + { + var t = _pendingLootTargets[i]; + if (t.Chassis is not null) SpawnChassisDrop(t.X, t.Z, t.Chassis); + else if (t.Module is not null) SpawnModuleDrop(t.X, t.Z, t.Module); + } + } + else + { + OrbitalDrop.BeginWave0(_pendingContenderTargets, _pendingLootTargets, surfaceQuery ?? DefaultDropSurfaceQuery); + } + + Broadcast.EmitMatchStart(0f, MapKind); + return true; + } + + public int Seed { get; } + public ArenaMapKind MapKind { get; } + public byte SquadSize { get; } + public SionMapData? SionMap { get; } + + public bool AreAllies(int contenderA, int contenderB) => + SquadSize > 1 && + contenderA >= 0 && contenderA < Contenders.Count && + contenderB >= 0 && contenderB < Contenders.Count && + Contenders[contenderA].SquadId == Contenders[contenderB].SquadId; + + public ContenderState? GetSquadLeader(byte squadId) + { + ContenderState? best = null; + for (int i = 0; i < Contenders.Count; i++) + { + var c = Contenders[i]; + if (c.SquadId != squadId) continue; + if (best is null || (c.IsHuman && !best.IsHuman) || (c.IsHuman == best.IsHuman && c.Id < best.Id)) + { + best = c; + } + } + return best; + } + + public int GetSquadMemberRank(int contenderId) + { + if (contenderId < 0 || contenderId >= Contenders.Count || SquadSize <= 1) + { + return 0; + } + var target = Contenders[contenderId]; + int rank = 0; + for (int i = 0; i < Contenders.Count; i++) + { + var c = Contenders[i]; + if (c.Id == target.Id || c.SquadId != target.SquadId) continue; + if ((c.IsHuman && !target.IsHuman) || (c.IsHuman == target.IsHuman && c.Id < target.Id)) + { + rank++; + } + } + return rank; + } + public Random Rng { get; } + public float Time { get; set; } + public MatchPhase Phase { get; set; } = MatchPhase.Active; + public LobbyState? Lobby { get; set; } + public int? WinnerContenderId { get; set; } + + public TerrainField Terrain { get; } + public ArenaScarLedger ScarLedger { get; } + public List Contenders { get; } = new(); + + public void ApplyPersistentScars(ArenaScarLedgerSnapshot snapshot) + { + ScarLedger.LoadFromSnapshot(snapshot); + ScarLedger.ApplyToTerrain(Terrain); + } + + public void ApplyTerrainStamp(TerrainStampEvent stamp, bool recordInLedger = true) + { + switch ((TerrainStampKind)stamp.Kind) + { + case TerrainStampKind.Crater: + Terrain.StampCrater(stamp.X, stamp.Z, stamp.Radius, stamp.Depth); + break; + case TerrainStampKind.Scorch: + Terrain.StampScorch(stamp.X, stamp.Z, stamp.Radius); + break; + case TerrainStampKind.Track: + Terrain.StampTrack(stamp.X, stamp.Z, stamp.Yaw, stamp.Radius, stamp.Length); + return; + case TerrainStampKind.Rubble: + Terrain.StampRubble(stamp.X, stamp.Z, stamp.Radius, stamp.Depth, stamp.Yaw); + break; + } + if (recordInLedger) + { + ScarLedger.RecordTerrainStamp(stamp); + } + } + + public void RepairArenaScars() + { + Terrain.ClearDynamicScars(); + ScarLedger.Clear(); + } + + public bool IsSolidBuildingAtXz(float x, float z, float padding = 0f) => + SionMap is not null && SionMap.IsInsideAnyBuildingXz(x, z, padding); + public SpectatorRing Spectators { get; } + public List GroundDrops { get; } = new(); + public List Tracers { get; } = new(); + public List HitEvents { get; } = new(); + public BroadcastFeed Broadcast { get; } + public OrbitalDropSystem OrbitalDrop { get; } + public List PodEvents { get; } = new(); + public IReadOnlyList ArenaCoverBoxes { get; } + public IReadOnlyList ArenaBoundaryBoxes { get; } + + public Dictionary ObserverStates { get; } = new(); + public IReadOnlyDictionary EmptyContacts { get; } = new Dictionary(); + + public float? LastGunfireX { get; set; } + public float? LastGunfireZ { get; set; } + public float LastGunfireTime { get; set; } = -100f; + + public event Action? ChassisSwapped; + public event Action? LoadoutChanged; + public event Action? DropSpawned; + public event Action? DropPickedUp; + public event Action? ContenderPodTouchedDown; + public event Action? ContenderRespawned; + + internal void NotifyContenderPodTouchedDown(ContenderState c) => ContenderPodTouchedDown?.Invoke(c); + internal void NotifyContenderRespawned(ContenderState c) => ContenderRespawned?.Invoke(c); + + public long AllocateHitEventId() => _nextHitEventId++; + public int AllocateTracerId() => _nextTracerId++; + + public static WeaponVisualClass ClassifyWeaponVisual(ModuleSpec mod) => + mod.VisualClassOverride ?? ClassifyWeaponVisual(mod.Id); + + public static WeaponVisualClass ClassifyWeaponVisual(string weaponId) => weaponId switch + { + "autocannon" => WeaponVisualClass.Autocannon, + "flak" or "recoilless" => WeaponVisualClass.Explosive, + "gilded_lance" or "touring_plasma" or "aegis_pd" => WeaponVisualClass.ThermalBeam, + _ when ProceduralWeaponGenerator.TryParseId(weaponId, out var key) => ProceduralWeaponGenerator.Generate(key).VisualClass, + _ => WeaponVisualClass.KineticLight + }; + + public static bool IsContactOnRadar(PlayerContactMemory? mem) + { + if (mem is null) + { + return false; + } + return mem.VisibleToPlayer || mem.FaintHorizonPing || (mem.HasEverBeenSeen && mem.LastSeenAge <= ContactGhostDuration); + } + + public ObserverDetectionState GetOrCreateObserverState(int observerId) + { + if (!ObserverStates.TryGetValue(observerId, out var obs)) + { + obs = new ObserverDetectionState(); + ObserverStates[observerId] = obs; + } + return obs; + } + + public GroundDrop SpawnModuleDrop(float x, float z, ModuleSpec module) + { + var drop = new GroundDrop(_nextDropId++, x, z, null, module); + GroundDrops.Add(drop); + DropSpawned?.Invoke(drop); + return drop; + } + + public GroundDrop SpawnChassisDrop(float x, float z, ChassisSpec chassis) + { + var drop = new GroundDrop(_nextDropId++, x, z, chassis, null); + GroundDrops.Add(drop); + DropSpawned?.Invoke(drop); + return drop; + } + + public GroundDrop ApplyReplicatedDropSpawned(int dropId, float x, float z, ChassisSpec? chassis, ModuleSpec? module) + { + for (int i = 0; i < GroundDrops.Count; i++) + { + if (GroundDrops[i].Id == dropId) + { + return GroundDrops[i]; + } + } + if (dropId >= _nextDropId) _nextDropId = dropId + 1; + var drop = new GroundDrop(dropId, x, z, chassis, module); + GroundDrops.Add(drop); + return drop; + } + + public void ApplyReplicatedDropPickedUp(int dropId) + { + for (int i = 0; i < GroundDrops.Count; i++) + { + if (GroundDrops[i].Id == dropId) + { + GroundDrops[i].PickedUp = true; + return; + } + } + } + + public bool TryEquipCargo(int contenderId, int cargoIndex, string hardpointId) + { + if (contenderId < 0 || contenderId >= Contenders.Count) + { + return false; + } + + var contender = Contenders[contenderId]; + if (!contender.IsGroundedActive) + { + return false; + } + + var displaced = new List(); + bool ok = contender.Grid.TryEquipFromCargo(cargoIndex, hardpointId, displaced); + if (!ok) + { + return false; + } + + for (int i = 0; i < displaced.Count; i++) + { + SpawnModuleDrop(contender.X + 1.5f, contender.Z + 1.5f, displaced[i]); + } + contender.LoadoutVersion++; + LoadoutChanged?.Invoke(contender); + return true; + } + + public GroundDrop? FindNearestInteractableDrop(int contenderId) + { + if (contenderId < 0 || contenderId >= Contenders.Count) + { + return null; + } + + var contender = Contenders[contenderId]; + if (!contender.IsGroundedActive) + { + return null; + } + + GroundDrop? nearest = null; + float bestDistSq = PickupRadius * PickupRadius; + + for (int i = 0; i < GroundDrops.Count; i++) + { + var d = GroundDrops[i]; + if (d.PickedUp || (d.Module is null && d.Chassis is null)) + { + continue; + } + + float dx = d.X - contender.X; + float dz = d.Z - contender.Z; + float d2 = dx * dx + dz * dz; + if (d2 <= bestDistSq) + { + bestDistSq = d2; + nearest = d; + } + } + + return nearest; + } + + public bool TryInteractNearestDrop(int contenderId) + { + var nearest = FindNearestInteractableDrop(contenderId); + if (nearest is null) + { + return false; + } + + var contender = Contenders[contenderId]; + if (nearest.Module is not null) + { + return ExecuteModuleDropPickup(contenderId, contender, nearest); + } + if (nearest.Chassis is not null) + { + return ExecuteChassisDropSwap(contender, nearest); + } + return false; + } + + public bool TryPickupNearbyModule(int contenderId) + { + if (contenderId < 0 || contenderId >= Contenders.Count) + { + return false; + } + + var contender = Contenders[contenderId]; + if (!contender.IsGroundedActive) + { + return false; + } + + GroundDrop? nearest = null; + float bestDistSq = PickupRadius * PickupRadius; + + for (int i = 0; i < GroundDrops.Count; i++) + { + var d = GroundDrops[i]; + if (d.PickedUp || d.Module is null) + { + continue; + } + + float dx = d.X - contender.X; + float dz = d.Z - contender.Z; + float d2 = dx * dx + dz * dz; + if (d2 <= bestDistSq) + { + bestDistSq = d2; + nearest = d; + } + } + + return nearest is not null && ExecuteModuleDropPickup(contenderId, contender, nearest); + } + + public bool TrySwapNearbyChassis(int contenderId, int? preferredDropId = null) + { + if (contenderId < 0 || contenderId >= Contenders.Count) + { + return false; + } + + var contender = Contenders[contenderId]; + if (!contender.IsGroundedActive) + { + return false; + } + + GroundDrop? chosen = null; + float bestDistSq = PickupRadius * PickupRadius; + + for (int i = 0; i < GroundDrops.Count; i++) + { + var d = GroundDrops[i]; + if (d.PickedUp || d.Chassis is null) + { + continue; + } + if (preferredDropId.HasValue && d.Id != preferredDropId.Value) + { + continue; + } + + float dx = d.X - contender.X; + float dz = d.Z - contender.Z; + float d2 = dx * dx + dz * dz; + if (d2 <= bestDistSq) + { + bestDistSq = d2; + chosen = d; + if (preferredDropId.HasValue) + { + break; + } + } + } + + return chosen is not null && ExecuteChassisDropSwap(contender, chosen); + } + + private bool ExecuteModuleDropPickup(int contenderId, ContenderState contender, GroundDrop drop) + { + if (drop.Module is null) + { + return false; + } + + if (!contender.Grid.TryQuickBoltOrCargo(drop.Module, out string? boltedHardpointId)) + { + return false; + } + + drop.PickedUp = true; + DropPickedUp?.Invoke(drop.Id, contenderId); + if (boltedHardpointId is not null) + { + Broadcast.EmitQuickBolt(Time, contenderId, drop.Module.Name, boltedHardpointId); + } + contender.LoadoutVersion++; + LoadoutChanged?.Invoke(contender); + return true; + } + + private bool ExecuteChassisDropSwap(ContenderState contender, GroundDrop drop) + { + if (drop.Chassis is null) + { + return false; + } + + var oldChassis = contender.Grid.Spec; + var overflow = contender.Grid.SwapChassis(drop.Chassis); + drop.PickedUp = true; + DropPickedUp?.Invoke(drop.Id, contender.Id); + + SpawnChassisDrop(contender.X - 2.2f, contender.Z - 2.2f, oldChassis); + for (int i = 0; i < overflow.Count; i++) + { + SpawnModuleDrop(contender.X + 1.5f + i * 0.7f, contender.Z - 1.5f, overflow[i]); + } + + contender.TargetHoverAltAgl = contender.Grid.Spec.IsVtol ? 10.0f : 3.0f; + contender.VerticalThrottleCmd = 0f; + contender.Y = Terrain.SampleHeight(contender.X, contender.Z) + contender.Grid.Spec.HalfHeight + + (contender.Grid.Spec.IsVtol ? contender.TargetHoverAltAgl : 0.15f); + contender.SnapPreviousPose(); + contender.ResetAimTracker(contender.Yaw); + contender.AiScavengeCooldown = 4.0f; + contender.LoadoutVersion++; + Broadcast.EmitChassisSwap(Time, contender.Id, contender.Grid.Spec.Name); + ChassisSwapped?.Invoke(contender); + LoadoutChanged?.Invoke(contender); + return true; + } + + private float MinDistSqToPlacedContenders(float x, float z) + { + float minSq = float.PositiveInfinity; + for (int k = 0; k < Contenders.Count; k++) + { + float dx = x - Contenders[k].X; + float dz = z - Contenders[k].Z; + float d2 = dx * dx + dz * dz; + if (d2 < minSq) + { + minSq = d2; + } + } + return minSq; + } + + private bool IsSionSpawnOccludedFromPlayer(ContenderState player, float cx, float cz, ChassisSpec spec) + { + float cY = Terrain.SampleHeight(cx, cz) + spec.HalfHeight + 0.15f; + float pEyeY = MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight); + float cAimY = MatchRules.GetTargetAimY(cY, spec.HalfHeight); + float dx = cx - player.X; + float dy = cAimY - pEyeY; + float dz = cz - player.Z; + float dist = MathF.Sqrt(dx * dx + dy * dy + dz * dz); + if (dist <= 0.25f) + { + return false; + } + float invD = 1f / dist; + float nx = dx * invD; + float ny = dy * invD; + float nz = dz * invD; + if (Terrain.Raycast(player.X, pEyeY, player.Z, nx, ny, nz, MathF.Max(0.1f, dist - 0.5f), out _, out _, out _, out _)) + { + return true; + } + return SionMap is not null && SionMap.IntersectsAnyBuildingAabb(player.X, pEyeY, player.Z, nx, ny, nz, dist); + } + + private bool IsNearCoverBox(float x, float z, float pad) + { + for (int i = 0; i < ArenaCoverBoxes.Count; i++) + { + var b = ArenaCoverBoxes[i]; + if (MathF.Abs(x - b.X) <= b.HalfX + pad && MathF.Abs(z - b.Z) <= b.HalfZ + pad) + { + return true; + } + } + return false; + } + + private void SpawnContenders() + { + const float minSepSq = 220f * 220f; + const float minR = 210f; + const float maxR = 540f; + const float ringSpan = maxR - minR; + + static float MinDistSqTo(ReadOnlySpan<(float X, float Z)> placed, int count, float x, float z) + { + float minSq = float.PositiveInfinity; + for (int k = 0; k < count; k++) + { + float dx = x - placed[k].X; + float dz = z - placed[k].Z; + float d2 = dx * dx + dz * dz; + if (d2 < minSq) + { + minSq = d2; + } + } + return minSq; + } + + Span<(float X, float Z)> coords = stackalloc (float X, float Z)[ContenderCount]; + bool allSatisfied = false; + + // Equal-start: all 12 contenders (player + 11 AI) spawn in stock Jackals with >= 220m pairwise separation. + // Retry up to 4 passes (increasing outer-ring bias) before falling back to deterministic outer dodecagon. + for (int retry = 0; retry < 4 && !allSatisfied; retry++) + { + allSatisfied = true; + float innerBiasR = retry == 0 ? 350f : 430f; + float innerSpanR = maxR - innerBiasR; + + for (int i = 0; i < ContenderCount; i++) + { + float x = 0f; + float z = 0f; + float bestX = 0f; + float bestZ = 0f; + float bestMinDistSq = -1f; + bool found = false; + float sectorAngle = (i / (float)ContenderCount) * MathF.Tau; + + for (int attempt = 0; attempt < 64; attempt++) + { + float angle = attempt < 12 + ? sectorAngle + (float)(Rng.NextDouble() - 0.5) * (attempt == 0 ? 0.16f : 0.42f) + : (float)(Rng.NextDouble() * MathF.Tau); + float baseR = attempt < 32 + ? (innerBiasR + (float)Rng.NextDouble() * innerSpanR) + : (minR + (float)Rng.NextDouble() * ringSpan); + float cx = MathF.Cos(angle) * baseR; + float cz = MathF.Sin(angle) * baseR; + + // Nudge radially inside [minR, maxR] if landing on a slope, dune wall, or cover box + for (int step = 0; step < 8; step++) + { + var (_, ny, _) = Terrain.SampleNormal(cx, cz); + bool flatPatch = ny >= 0.96f && + Terrain.SampleNormal(cx + 10f, cz).Ny >= 0.93f && + Terrain.SampleNormal(cx - 10f, cz).Ny >= 0.93f && + Terrain.SampleNormal(cx, cz + 10f).Ny >= 0.93f && + Terrain.SampleNormal(cx, cz - 10f).Ny >= 0.93f; + if (flatPatch && !IsNearCoverBox(cx, cz, 8f)) + { + break; + } + float r = minR + ((baseR - minR + step * 37f) % ringSpan); + cx = MathF.Cos(angle) * r; + cz = MathF.Sin(angle) * r; + } + + if (IsNearCoverBox(cx, cz, 4f)) + { + continue; + } + + float minDistSq = MinDistSqTo(coords, i, cx, cz); + if (minDistSq > bestMinDistSq) + { + bestMinDistSq = minDistSq; + bestX = cx; + bestZ = cz; + } + if (minDistSq >= minSepSq) + { + x = cx; + z = cz; + found = true; + break; + } + } + + if (!found) + { + for (int pass = 0; pass < 2 && !found; pass++) + { + float minNy = pass == 0 ? 0.88f : 0f; + for (float r = maxR; r >= 180f && !found; r -= 12f) + { + for (int a = 0; a < 96; a++) + { + float ang = sectorAngle + (a / 96f) * MathF.Tau; + float cx = MathF.Cos(ang) * r; + float cz = MathF.Sin(ang) * r; + if (minNy > 0f && Terrain.SampleNormal(cx, cz).Ny < minNy) + { + continue; + } + if (IsNearCoverBox(cx, cz, 4f)) + { + continue; + } + if (MinDistSqTo(coords, i, cx, cz) >= minSepSq) + { + x = cx; + z = cz; + found = true; + break; + } + } + } + } + } + + if (!found) + { + allSatisfied = false; + x = bestX; + z = bestZ; + break; + } + + coords[i] = (x, z); + } + } + + if (!allSatisfied) + { + // Deterministic outer dodecagon fallback: chord at r=500m is 258.8m (> 220m) + for (int i = 0; i < ContenderCount; i++) + { + float sectorAngle = (i / (float)ContenderCount) * MathF.Tau; + float chosenX = MathF.Cos(sectorAngle) * 500f; + float chosenZ = MathF.Sin(sectorAngle) * 500f; + bool placed = false; + for (float r = 510f; r >= 460f && !placed; r -= 10f) + { + for (int da = 0; da < 5 && !placed; da++) + { + float ang = sectorAngle + (da - 2) * 0.02f; + float cx = MathF.Cos(ang) * r; + float cz = MathF.Sin(ang) * r; + if (!IsNearCoverBox(cx, cz, 4f) && MinDistSqTo(coords, i, cx, cz) >= minSepSq) + { + chosenX = cx; + chosenZ = cz; + placed = true; + } + } + } + coords[i] = (chosenX, chosenZ); + } + } + + for (int i = 0; i < ContenderCount; i++) + { + float x = coords[i].X; + float z = coords[i].Z; + + float yaw = MathF.Atan2(-x, -z); + string name = $"Contender {i + 1:00}"; + var grid = Catalog.CreateStarterBuggy(); + var contender = new ContenderState(i, name, isHuman: false, grid, x, z, yaw); + contender.Y = Terrain.SampleHeight(x, z) + contender.Grid.Spec.HalfHeight + 0.15f; + contender.AimY = contender.Y; + contender.SnapPreviousPose(); + contender.ResetAimTracker(yaw); + Contenders.Add(contender); + } + } + + private List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> BuildInitialLootTargetsDesert() + { + var targets = new List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)>(40); + // 14 deterministic salvageable chassis wrecks covering all non-starter vehicles in the 15-vehicle roster + var chassisPool = new List(Catalog.AllChassis.Count); + for (int i = 0; i < Catalog.AllChassis.Count; i++) + { + var c = Catalog.AllChassis[i]; + if (!string.Equals(c.Id, Catalog.Jackal.Id, StringComparison.OrdinalIgnoreCase)) + { + chassisPool.Add(c); + } + } + + for (int i = 0; i < chassisPool.Count; i++) + { + float angle = (i / (float)chassisPool.Count) * MathF.Tau + 0.35f; + float r = i >= chassisPool.Count - 3 ? (55f + (i % 3) * 18f) : (135f + (i % 4) * 85f); + var (dx, dz) = FindClearDropPoint(MathF.Cos(angle) * r, MathF.Sin(angle) * r, 3.5f); + targets.Add((dx, dz, chassisPool[i], null)); + } + + // 26 ground salvage module drops spread across canyons, passes, and ruins (including 1x1 Wide-Arc PD + 10 deterministic procedural weapons!) + ModuleSpec[] salvagePool = + { + Catalog.Autocannon, Catalog.Flak, Catalog.PointDefenseFlak, Catalog.Recoilless, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, Catalog.Mg762, + Catalog.DieselCore, Catalog.PointDefenseFlak, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 0).Module, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 1).Module, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 2).Module, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 3).Module, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 4).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 5).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 6).Module, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 7).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 8).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 9).Module + }; + + for (int i = 0; i < salvagePool.Length; i++) + { + float angle = (i / (float)salvagePool.Length) * MathF.Tau + 0.19f; + float r = 75f + (i % 5) * 95f; + var (mx, mz) = FindClearDropPoint(MathF.Cos(angle) * r, MathF.Sin(angle) * r, 2.5f); + targets.Add((mx, mz, null, salvagePool[i])); + } + return targets; + } + + private static IReadOnlyList BuildCoverBoxes() + { + // 36 deterministic ruin walls / cover blocks spaced >= 90m apart across the 1.5km valley + var boxes = new List(36); + + // Inner plaza ring (4 blocks at r = 68m) + for (int i = 0; i < 4; i++) + { + float a = (i / 4f) * MathF.Tau + 0.35f; + bool rot = i % 2 == 0; + boxes.Add(new ArenaBoxSpec( + MathF.Cos(a) * 68f, 2.0f, MathF.Sin(a) * 68f, + rot ? 5.2f : 1.6f, 2.0f, rot ? 1.6f : 5.2f, false)); + } + + // Inner-mid ruins (8 blocks at r = 175m) + for (int i = 0; i < 8; i++) + { + float a = (i / 8f) * MathF.Tau + 0.15f; + bool bunker = i % 3 == 0; + boxes.Add(new ArenaBoxSpec( + MathF.Cos(a) * 175f, 2.3f, MathF.Sin(a) * 175f, + bunker ? 3.8f : (i % 2 == 0 ? 5.8f : 1.8f), + 2.3f, + bunker ? 3.8f : (i % 2 == 0 ? 1.8f : 5.8f), + false)); + } + + // Mid-valley pass ruins (12 blocks at r = 335m) + for (int i = 0; i < 12; i++) + { + float a = (i / 12f) * MathF.Tau + 0.22f; + bool bunker = i % 2 == 0; + boxes.Add(new ArenaBoxSpec( + MathF.Cos(a) * 335f, 2.4f, MathF.Sin(a) * 335f, + bunker ? 4.0f : 6.0f, 2.4f, bunker ? 4.0f : 1.8f, false)); + } + + // Outer rim ruins (12 blocks at r = 515m) + for (int i = 0; i < 12; i++) + { + float a = (i / 12f) * MathF.Tau + 0.08f; + bool tall = i % 3 == 0; + boxes.Add(new ArenaBoxSpec( + MathF.Cos(a) * 515f, tall ? 2.8f : 2.2f, MathF.Sin(a) * 515f, + tall ? 3.6f : 5.6f, tall ? 2.8f : 2.2f, tall ? 3.6f : 1.8f, false)); + } + + return boxes; + } + + private static IReadOnlyList SeatBoxesOnTerrain(IReadOnlyList raw, TerrainField terrain) + { + var seated = new ArenaBoxSpec[raw.Count]; + for (int i = 0; i < raw.Count; i++) + { + var b = raw[i]; + float minY = terrain.SampleHeight(b.X, b.Z); + minY = MathF.Min(minY, terrain.SampleHeight(b.X - b.HalfX, b.Z - b.HalfZ)); + minY = MathF.Min(minY, terrain.SampleHeight(b.X + b.HalfX, b.Z - b.HalfZ)); + minY = MathF.Min(minY, terrain.SampleHeight(b.X - b.HalfX, b.Z + b.HalfZ)); + minY = MathF.Min(minY, terrain.SampleHeight(b.X + b.HalfX, b.Z + b.HalfZ)); + seated[i] = b with { Y = minY + b.HalfY }; + } + return seated; + } + + private void SeatSpectatorsOnSion() + { + for (int i = 0; i < Spectators.Spectators.Count; i++) + { + var spec = Spectators.Spectators[i]; + float pad = MathF.Max(spec.Grid.Spec.HalfWidth, spec.Grid.Spec.HalfLength) + 2.0f; + (float sx, float sz) = FindClearSionPoint(spec.X, spec.Z, pad, minNy: 0.76f, maxSearchRadius: 220f); + spec.X = sx; + spec.Z = sz; + spec.Y = Terrain.SampleHeight(sx, sz) + spec.Grid.Spec.HalfHeight + 0.15f; + spec.Yaw = MathF.Atan2(-sx, -sz); + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, spec.Yaw); + spec.CurrRotX = q.X; + spec.CurrRotY = q.Y; + spec.CurrRotZ = q.Z; + spec.CurrRotW = q.W; + spec.SnapPreviousPose(); + spec.ResetAimTracker(spec.Yaw); + } + } + + private void SpawnContendersSion() + { + const float minSepSq = 220f * 220f; + const float preferOccludedDistSq = 380f * 380f; + + // Slot 0 starts in the open Sion Old Town / Rhone plaza facing Basilique de Valere & Chateau de Tourbillon. + var anchorGrid = Catalog.CreateStarterBuggy(); + float anchorPad = MathF.Max(anchorGrid.Spec.HalfWidth, anchorGrid.Spec.HalfLength) + 2.0f; + (float px, float pz) = FindClearSionPoint(-60f, 360f, anchorPad, minNy: 0.84f, maxSearchRadius: 120f); + float pYaw = MathF.Atan2(150f - px, -260f - pz); + var anchor = new ContenderState(0, "Contender 01", isHuman: false, anchorGrid, px, pz, pYaw); + anchor.Y = Terrain.SampleHeight(px, pz) + anchorGrid.Spec.HalfHeight + 0.15f; + anchor.AimY = anchor.Y; + anchor.SnapPreviousPose(); + anchor.ResetAimTracker(pYaw); + Contenders.Add(anchor); + + for (int i = 1; i < ContenderCount; i++) + { + var grid = Catalog.CreateStarterBuggy(); + float pad = MathF.Max(grid.Spec.HalfWidth, grid.Spec.HalfLength) + 2.0f; + + float x = 0f; + float z = 0f; + bool found = false; + bool hasOpenCloseCandidate = false; + float openCloseX = 0f; + float openCloseZ = 0f; + float bestFallbackX = 0f; + float bestFallbackZ = 0f; + float bestFallbackMinDistSq = -1f; + + for (int attempt = 0; attempt < 48; attempt++) + { + float angle = attempt == 0 + ? ((i - 1) / (float)(ContenderCount - 1)) * MathF.Tau + (float)(Rng.NextDouble() - 0.5) * 0.25f + : (float)(Rng.NextDouble() * MathF.Tau); + float r = attempt < 24 + ? (240f + (float)Rng.NextDouble() * 680f) + : (440f + (float)Rng.NextDouble() * 480f); + float candX = MathF.Cos(angle) * r; + float candZ = MathF.Sin(angle) * r; + + (float cx, float cz) = FindClearSionPoint(candX, candZ, pad, minNy: 0.84f, maxSearchRadius: 280f, avoidContenders: false); + float minDistSq = MinDistSqToPlacedContenders(cx, cz); + if (minDistSq > bestFallbackMinDistSq) + { + bestFallbackMinDistSq = minDistSq; + bestFallbackX = cx; + bestFallbackZ = cz; + } + if (minDistSq < minSepSq) + { + continue; + } + + float playerDistSq = (cx - px) * (cx - px) + (cz - pz) * (cz - pz); + if (playerDistSq >= preferOccludedDistSq || IsSionSpawnOccludedFromPlayer(anchor, cx, cz, grid.Spec)) + { + x = cx; + z = cz; + found = true; + break; + } + + if (!hasOpenCloseCandidate) + { + openCloseX = cx; + openCloseZ = cz; + hasOpenCloseCandidate = true; + } + } + + if (!found) + { + if (hasOpenCloseCandidate) + { + x = openCloseX; + z = openCloseZ; + found = true; + } + else + { + float[] scanRadii = { 900f, 780f, 640f, 500f }; + for (int rIdx = 0; rIdx < scanRadii.Length && !found; rIdx++) + { + float r = scanRadii[rIdx]; + for (int a = 0; a < 36; a++) + { + float ang = (a / 36f) * MathF.Tau; + (float cx, float cz) = FindClearSionPoint( + MathF.Cos(ang) * r, + MathF.Sin(ang) * r, + pad, + minNy: 0.84f, + maxSearchRadius: 240f, + avoidContenders: false); + if (MinDistSqToPlacedContenders(cx, cz) >= minSepSq) + { + x = cx; + z = cz; + found = true; + break; + } + } + } + } + } + + if (!found) + { + x = bestFallbackX; + z = bestFallbackZ; + } + + float yaw = MathF.Atan2(-x, -z); + var contender = new ContenderState(i, $"Contender {i + 1:00}", isHuman: false, grid, x, z, yaw); + contender.Y = Terrain.SampleHeight(x, z) + grid.Spec.HalfHeight + 0.15f; + contender.AimY = contender.Y; + contender.SnapPreviousPose(); + contender.ResetAimTracker(yaw); + Contenders.Add(contender); + } + } + + public static (float FwdOffset, float SideOffset, float AltStagger) GetSquadFormationOffset(int rank) => rank switch + { + 0 => (8f, 0f, 0f), + 1 => (-6f, -16f, 6f), + 2 => (-6f, 16f, 6f), + 3 => (-20f, 0f, 12f), + _ => (-20f - (rank - 3) * 14f, 0f, 12f + (rank - 3) * 6f) + }; + + private void AssignDefaultSquadIds() + { + for (int i = 0; i < Contenders.Count; i++) + { + Contenders[i].SquadId = SquadSize > 1 ? (byte)(i / SquadSize) : (byte)i; + } + } + + public void ApplySquadFormationTargets() + { + _pendingContenderTargets.Clear(); + if (SquadSize <= 1) + { + for (int i = 0; i < Contenders.Count; i++) + { + var c = Contenders[i]; + c.SquadId = (byte)i; + _pendingContenderTargets.Add((c.Id, c.X, c.Z, c.Yaw)); + } + return; + } + + var squadsById = new Dictionary>(); + for (int i = 0; i < Contenders.Count; i++) + { + var c = Contenders[i]; + if (!squadsById.TryGetValue(c.SquadId, out var list)) + { + list = new List(SquadSize); + squadsById[c.SquadId] = list; + } + list.Add(c); + } + + byte slot0Squad = Contenders.Count > 0 ? Contenders[0].SquadId : (byte)0; + var squadGroups = new List<(byte SquadId, List Members)>(squadsById.Count); + foreach (var kv in squadsById) + { + kv.Value.Sort(static (a, b) => + { + int humanCmp = (b.IsHuman ? 1 : 0).CompareTo(a.IsHuman ? 1 : 0); + return humanCmp != 0 ? humanCmp : a.Id.CompareTo(b.Id); + }); + squadGroups.Add((kv.Key, kv.Value)); + } + squadGroups.Sort((a, b) => + { + if (a.SquadId == slot0Squad && b.SquadId != slot0Squad) return -1; + if (b.SquadId == slot0Squad && a.SquadId != slot0Squad) return 1; + return a.SquadId.CompareTo(b.SquadId); + }); + + int squadCount = squadGroups.Count; + Span<(float X, float Z, float Yaw)> anchors = stackalloc (float X, float Z, float Yaw)[squadCount]; + var squadRng = new Random(Seed ^ (SquadSize * 7919)); + const float minAnchorSepSq = 220f * 220f; + + static float MinAnchorDistSq(ReadOnlySpan<(float X, float Z, float Yaw)> placed, int count, float x, float z) + { + float minSq = float.PositiveInfinity; + for (int k = 0; k < count; k++) + { + float dx = x - placed[k].X; + float dz = z - placed[k].Z; + float d2 = dx * dx + dz * dz; + if (d2 < minSq) minSq = d2; + } + return minSq; + } + + if (MapKind == ArenaMapKind.Sion && SionMap is not null) + { + var leader0 = squadGroups[0].Members[0]; + float pad0 = MathF.Max(leader0.Grid.Spec.HalfWidth, leader0.Grid.Spec.HalfLength) + 2.0f; + (float px, float pz) = FindClearSionPoint(-60f, 360f, pad0, minNy: 0.84f, maxSearchRadius: 120f); + float pYaw = MathF.Atan2(150f - px, -260f - pz); + anchors[0] = (px, pz, pYaw); + + for (int s = 1; s < squadCount; s++) + { + var leader = squadGroups[s].Members[0]; + float pad = MathF.Max(leader.Grid.Spec.HalfWidth, leader.Grid.Spec.HalfLength) + 2.0f; + float ax = 0f, az = 0f; + bool found = false; + float bestX = 0f, bestZ = 0f, bestMinDistSq = -1f; + + for (int attempt = 0; attempt < 48; attempt++) + { + float angle = attempt == 0 + ? ((s - 1) / (float)Math.Max(1, squadCount - 1)) * MathF.Tau + (float)(squadRng.NextDouble() - 0.5) * 0.25f + : (float)(squadRng.NextDouble() * MathF.Tau); + float r = attempt < 24 + ? (260f + (float)squadRng.NextDouble() * 640f) + : (440f + (float)squadRng.NextDouble() * 480f); + (float cx, float cz) = FindClearSionPoint( + MathF.Cos(angle) * r, + MathF.Sin(angle) * r, + pad, + minNy: 0.84f, + maxSearchRadius: 280f, + avoidContenders: false); + float d2 = MinAnchorDistSq(anchors, s, cx, cz); + if (d2 > bestMinDistSq) + { + bestMinDistSq = d2; + bestX = cx; + bestZ = cz; + } + if (d2 >= minAnchorSepSq) + { + ax = cx; + az = cz; + found = true; + break; + } + } + + if (!found) + { + float[] scanRadii = { 900f, 780f, 640f, 500f }; + for (int rIdx = 0; rIdx < scanRadii.Length && !found; rIdx++) + { + float r = scanRadii[rIdx]; + for (int a = 0; a < 36; a++) + { + float ang = (a / 36f) * MathF.Tau; + (float cx, float cz) = FindClearSionPoint( + MathF.Cos(ang) * r, + MathF.Sin(ang) * r, + pad, + minNy: 0.84f, + maxSearchRadius: 240f, + avoidContenders: false); + if (MinAnchorDistSq(anchors, s, cx, cz) >= minAnchorSepSq) + { + ax = cx; + az = cz; + found = true; + break; + } + } + } + } + + if (!found) + { + ax = bestX; + az = bestZ; + } + anchors[s] = (ax, az, MathF.Atan2(-ax, -az)); + } + } + else + { + const float minR = 210f; + const float maxR = 540f; + const float ringSpan = maxR - minR; + + for (int s = 0; s < squadCount; s++) + { + float ax = 0f, az = 0f; + bool found = false; + float bestX = 0f, bestZ = 0f, bestMinDistSq = -1f; + float sectorAngle = (s / (float)Math.Max(1, squadCount)) * MathF.Tau; + + for (int attempt = 0; attempt < 64; attempt++) + { + float angle = attempt < 12 + ? sectorAngle + (float)(squadRng.NextDouble() - 0.5) * (attempt == 0 ? 0.16f : 0.42f) + : (float)(squadRng.NextDouble() * MathF.Tau); + float baseR = attempt < 32 + ? (350f + (float)squadRng.NextDouble() * (maxR - 350f)) + : (minR + (float)squadRng.NextDouble() * ringSpan); + float cx = MathF.Cos(angle) * baseR; + float cz = MathF.Sin(angle) * baseR; + + for (int step = 0; step < 8; step++) + { + var (_, ny, _) = Terrain.SampleNormal(cx, cz); + if (ny >= 0.94f && !IsNearCoverBox(cx, cz, 8f)) + { + break; + } + float r = minR + ((baseR - minR + step * 37f) % ringSpan); + cx = MathF.Cos(angle) * r; + cz = MathF.Sin(angle) * r; + } + + if (IsNearCoverBox(cx, cz, 4f)) continue; + + float d2 = MinAnchorDistSq(anchors, s, cx, cz); + if (d2 > bestMinDistSq) + { + bestMinDistSq = d2; + bestX = cx; + bestZ = cz; + } + if (d2 >= minAnchorSepSq) + { + ax = cx; + az = cz; + found = true; + break; + } + } + + if (!found) + { + for (float r = maxR; r >= 200f && !found; r -= 20f) + { + for (int a = 0; a < 48; a++) + { + float ang = sectorAngle + (a / 48f) * MathF.Tau; + float cx = MathF.Cos(ang) * r; + float cz = MathF.Sin(ang) * r; + if (!IsNearCoverBox(cx, cz, 4f) && MinAnchorDistSq(anchors, s, cx, cz) >= minAnchorSepSq) + { + ax = cx; + az = cz; + found = true; + break; + } + } + } + } + + if (!found) + { + ax = bestX; + az = bestZ; + } + anchors[s] = (ax, az, MathF.Atan2(-ax, -az)); + } + } + + Span<(float X, float Z)> placed = stackalloc (float X, float Z)[Contenders.Count]; + int placedCount = 0; + + for (int s = 0; s < squadCount; s++) + { + var (ax, az, aYaw) = anchors[s]; + float sinY = MathF.Sin(aYaw); + float cosY = MathF.Cos(aYaw); + var members = squadGroups[s].Members; + + for (int k = 0; k < members.Count; k++) + { + var c = members[k]; + var (fwdOff, sideOff, _) = GetSquadFormationOffset(k); + float rawX = ax + sinY * fwdOff - cosY * sideOff; + float rawZ = az + cosY * fwdOff + sinY * sideOff; + float pad = MathF.Max(c.Grid.Spec.HalfWidth, c.Grid.Spec.HalfLength) + 2.0f; + + var (tx, tz) = FindClearSquadMemberPoint(rawX, rawZ, pad, placed, placedCount); + placed[placedCount++] = (tx, tz); + + c.X = tx; + c.Z = tz; + c.Yaw = aYaw; + c.Y = Terrain.SampleHeight(tx, tz) + c.Grid.Spec.HalfHeight + 0.15f; + c.AimY = c.Y; + c.SnapPreviousPose(); + c.ResetAimTracker(aYaw); + } + } + + for (int i = 0; i < Contenders.Count; i++) + { + var c = Contenders[i]; + _pendingContenderTargets.Add((c.Id, c.X, c.Z, c.Yaw)); + } + } + + private (float X, float Z) FindClearSquadMemberPoint( + float rawX, + float rawZ, + float pad, + ReadOnlySpan<(float X, float Z)> placed, + int placedCount) + { + float maxB = Terrain.MapHalfExtent - 28f; + float baseX = Math.Clamp(rawX, -maxB, maxB); + float baseZ = Math.Clamp(rawZ, -maxB, maxB); + + if (IsClearSquadMemberCandidate(baseX, baseZ, pad, maxB, minNy: 0.76f, placed, placedCount)) + { + return (baseX, baseZ); + } + + for (int pass = 0; pass < 2; pass++) + { + float minNy = pass == 0 ? 0.76f : 0f; + for (float r = 4f; r <= 120f; r += 4f) + { + for (int a = 0; a < 16; a++) + { + float ang = (a / 16f) * MathF.Tau; + float cx = Math.Clamp(baseX + MathF.Cos(ang) * r, -maxB, maxB); + float cz = Math.Clamp(baseZ + MathF.Sin(ang) * r, -maxB, maxB); + if (IsClearSquadMemberCandidate(cx, cz, pad, maxB, minNy, placed, placedCount)) + { + return (cx, cz); + } + } + } + } + + return FindClearDropPoint(baseX, baseZ, pad); + } + + private bool IsClearSquadMemberCandidate( + float cx, + float cz, + float pad, + float maxB, + float minNy, + ReadOnlySpan<(float X, float Z)> placed, + int placedCount) + { + const float minMemberSepSq = 14.5f * 14.5f; + if (MathF.Abs(cx) > maxB || MathF.Abs(cz) > maxB) return false; + if (MapKind == ArenaMapKind.Sion && SionMap is not null) + { + if (SionMap.IsInsideAnyBuildingXz(cx, cz, pad)) return false; + if (minNy > 0f && Terrain.SampleNormal(cx, cz).Ny < minNy) return false; + } + else if (IsNearCoverBox(cx, cz, pad)) + { + return false; + } + for (int k = 0; k < placedCount; k++) + { + float dx = cx - placed[k].X; + float dz = cz - placed[k].Z; + if (dx * dx + dz * dz < minMemberSepSq) return false; + } + return true; + } + + private List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> BuildInitialLootTargetsSion() + { + var targets = new List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)>(40); + var chassisPool = new List(Catalog.AllChassis.Count); + for (int i = 0; i < Catalog.AllChassis.Count; i++) + { + var c = Catalog.AllChassis[i]; + if (!string.Equals(c.Id, Catalog.Jackal.Id, StringComparison.OrdinalIgnoreCase)) + { + chassisPool.Add(c); + } + } + + var p = Contenders[0]; + float pYaw = p.Yaw; + for (int i = 0; i < chassisPool.Count; i++) + { + float pad = MathF.Max(chassisPool[i].HalfWidth, chassisPool[i].HalfLength) + 3.5f; + float candX; + float candZ; + if (i >= chassisPool.Count - 3) + { + int localIdx = i - (chassisPool.Count - 3); + float localAng = pYaw + (localIdx - 1) * 0.65f; + float localR = 32f + localIdx * 14f; + candX = p.X + MathF.Sin(localAng) * localR; + candZ = p.Z + MathF.Cos(localAng) * localR; + } + else if (i < 3) + { + // 3 chassis drops within 110-190m of ring sectors on Sion + float angle = (i / 3f) * MathF.Tau + 0.4f; + float r = 120f + i * 32f; + candX = MathF.Cos(angle) * r; + candZ = MathF.Sin(angle) * r; + } + else + { + int outerIdx = i - 3; + int outerCount = chassisPool.Count - 6; + float angle = (outerIdx / (float)Math.Max(1, outerCount)) * MathF.Tau + 0.35f; + float r = 260f + (outerIdx % 4) * 185f; + candX = MathF.Cos(angle) * r; + candZ = MathF.Sin(angle) * r; + } + (float dx, float dz) = FindClearSionPoint(candX, candZ, pad, minNy: 0.84f, maxSearchRadius: 240f); + targets.Add((dx, dz, chassisPool[i], null)); + } + + ModuleSpec[] salvagePool = + { + Catalog.Autocannon, Catalog.Flak, Catalog.PointDefenseFlak, Catalog.Recoilless, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, Catalog.Mg762, + Catalog.DieselCore, Catalog.PointDefenseFlak, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 0).Module, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 1).Module, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 2).Module, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 3).Module, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 4).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 5).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 6).Module, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 7).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 8).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 9).Module + }; + + for (int i = 0; i < salvagePool.Length; i++) + { + float candX; + float candZ; + if (i < 2) + { + float ang = pYaw + (i == 0 ? -0.4f : 0.4f); + candX = p.X + MathF.Sin(ang) * 24f; + candZ = p.Z + MathF.Cos(ang) * 24f; + } + else if (i < 6) + { + // Reachable crates within 110-190m of ring sectors on Sion + float angle = ((i - 2) / 4f) * MathF.Tau + 0.25f; + float r = 115f + (i - 2) * 22f; + candX = MathF.Cos(angle) * r; + candZ = MathF.Sin(angle) * r; + } + else + { + int outerIdx = i - 6; + int outerCount = salvagePool.Length - 6; + float angle = (outerIdx / (float)Math.Max(1, outerCount)) * MathF.Tau + 0.19f; + float r = 240f + (outerIdx % 5) * 155f; + candX = MathF.Cos(angle) * r; + candZ = MathF.Sin(angle) * r; + } + (float mx, float mz) = FindClearSionPoint(candX, candZ, pad: 2.5f, minNy: 0.84f, maxSearchRadius: 220f); + targets.Add((mx, mz, null, salvagePool[i])); + } + return targets; + } + + public DropSurfaceSample DefaultDropSurfaceQuery(float x, float z, float footRadius, float referenceMaxY) + { + float terrainY = Terrain.SampleHeight(x, z); + var (nx, ny, nz) = Terrain.SampleNormal(x, z); + Vector3 normal = new(nx, ny, nz); + if (normal.LengthSquared() < 1e-4f) normal = Vector3.UnitY; + else normal = Vector3.Normalize(normal); + + if (SionMap is not null) + { + bool centerOverBuilding = SionMap.TryGetBuildingAt(x, z, 0f, out var centerBldg); + bool lateralWallOverlap = centerOverBuilding || SionMap.TryGetBuildingAt(x, z, footRadius, out _); + + if (centerOverBuilding && centerBldg.RoofY > terrainY + 0.25f && centerBldg.RoofY <= referenceMaxY) + { + bool flat = centerBldg.Class == "Gebaeude Einzelhaus" + && centerBldg.HalfX >= footRadius + 2.2f + && centerBldg.HalfZ >= footRadius + 2.2f; + return new DropSurfaceSample( + centerBldg.RoofY, + Vector3.UnitY, + IsBuildingRoof: true, + IsFlatRoofValid: flat, + IsInsideBuildingFootprint: true, + IsInsideSolidBuilding: centerBldg.RoofY > referenceMaxY - 0.5f); + } + + bool isInsideSolid = centerOverBuilding + && centerBldg.RoofY > terrainY + 0.25f + && centerBldg.RoofY > referenceMaxY - 0.5f; + + return new DropSurfaceSample( + terrainY, + normal, + IsBuildingRoof: false, + IsFlatRoofValid: false, + IsInsideBuildingFootprint: lateralWallOverlap, + IsInsideSolidBuilding: isInsideSolid); + } + + if (ArenaCoverBoxes.Count > 0) + { + for (int i = 0; i < ArenaCoverBoxes.Count; i++) + { + var box = ArenaCoverBoxes[i]; + if (MathF.Abs(x - box.X) <= box.HalfX + footRadius && + MathF.Abs(z - box.Z) <= box.HalfZ + footRadius) + { + float topY = box.Y + box.HalfY; + if (topY <= referenceMaxY) + { + return new DropSurfaceSample( + MathF.Max(terrainY, topY), + Vector3.UnitY, + IsBuildingRoof: false, + IsFlatRoofValid: false, + IsInsideBuildingFootprint: true); + } + } + } + } + + return new DropSurfaceSample( + terrainY, + normal, + IsBuildingRoof: false, + IsFlatRoofValid: false, + IsInsideBuildingFootprint: false); + } + + public (float X, float Z) FindClearDropPoint(float targetX, float targetZ, float pad) + { + if (MapKind == ArenaMapKind.Sion && SionMap is not null) + { + return FindClearSionPoint(targetX, targetZ, pad, minNy: 0.72f, maxSearchRadius: 260f); + } + + float maxB = Terrain.MapHalfExtent - 28f; + float bx = Math.Clamp(targetX, -maxB, maxB); + float bz = Math.Clamp(targetZ, -maxB, maxB); + if (!IsNearCoverBox(bx, bz, pad)) + { + return (bx, bz); + } + for (float r = 6f; r <= 60f; r += 6f) + { + for (int a = 0; a < 12; a++) + { + float ang = (a / 12f) * MathF.Tau; + float cx = Math.Clamp(bx + MathF.Cos(ang) * r, -maxB, maxB); + float cz = Math.Clamp(bz + MathF.Sin(ang) * r, -maxB, maxB); + if (!IsNearCoverBox(cx, cz, pad)) + { + return (cx, cz); + } + } + } + return (bx, bz); + } + + private (float X, float Z) FindClearSionPoint( + float targetX, + float targetZ, + float pad, + float minNy, + float maxSearchRadius = 240f, + bool avoidContenders = false) + { + float maxB = Terrain.MapHalfExtent - 28f; + float baseX = Math.Clamp(targetX, -maxB, maxB); + float baseZ = Math.Clamp(targetZ, -maxB, maxB); + + bool IsValid(float cx, float cz) + { + if (MathF.Abs(cx) > maxB || MathF.Abs(cz) > maxB) + { + return false; + } + if (SionMap is not null && SionMap.IsInsideAnyBuildingXz(cx, cz, pad)) + { + return false; + } + if (minNy > 0f && Terrain.SampleNormal(cx, cz).Ny < minNy) + { + return false; + } + if (avoidContenders) + { + for (int k = 0; k < Contenders.Count; k++) + { + float dx = cx - Contenders[k].X; + float dz = cz - Contenders[k].Z; + if (dx * dx + dz * dz < 22f * 22f) + { + return false; + } + } + } + return true; + } + + if (IsValid(baseX, baseZ)) + { + return (baseX, baseZ); + } + + for (float r = 8f; r <= maxSearchRadius; r += 8f) + { + for (int a = 0; a < 16; a++) + { + float ang = (a / 16f) * MathF.Tau; + float cx = Math.Clamp(baseX + MathF.Cos(ang) * r, -maxB, maxB); + float cz = Math.Clamp(baseZ + MathF.Sin(ang) * r, -maxB, maxB); + if (IsValid(cx, cz)) + { + return (cx, cz); + } + } + } + + // Fallback without minNy slope filter if tightly boxed in + if (minNy > 0f) + { + return FindClearSionPoint(baseX, baseZ, pad, minNy: 0f, maxSearchRadius: maxSearchRadius + 160f, avoidContenders: false); + } + + return (baseX, baseZ); + } + + private static IReadOnlyList BuildBoundaryBoxes(float halfExtent, float minY, float maxY) + { + float wallY = 0.5f * (minY + maxY); + float wallHalfH = MathF.Max(60f, 0.5f * (maxY - minY)); + const float wallHalfThick = 4f; + float span = halfExtent + wallHalfThick; + return new ArenaBoxSpec[] + { + new(0f, wallY, halfExtent, span, wallHalfH, wallHalfThick, true), + new(0f, wallY, -halfExtent, span, wallHalfH, wallHalfThick, true), + new(halfExtent, wallY, 0f, wallHalfThick, wallHalfH, span, true), + new(-halfExtent, wallY, 0f, wallHalfThick, wallHalfH, span, true) + }; + } + } +} diff --git a/src/RustToDust.Core/OrbitalDropSystem.cs b/src/RustToDust.Core/OrbitalDropSystem.cs new file mode 100644 index 0000000..33f56cd --- /dev/null +++ b/src/RustToDust.Core/OrbitalDropSystem.cs @@ -0,0 +1,2000 @@ +using System; +using System.Collections.Generic; +using System.Numerics; + +namespace RustToDust.Core +{ + public enum ContenderLifecycle : byte + { + Deploying = 0, + Active = 1, + WaitingForRespawnWave = 2, + Eliminated = 3 + } + + public enum OrbitalPodKind : byte + { + Contender = 0, + Chassis = 1, + Module = 2 + } + + public enum OrbitalPodPhase : byte + { + Freefall = 0, + RetroBurn = 1, + Popped = 2 + } + + public readonly record struct DropSurfaceSample( + float SurfaceY, + Vector3 Normal, + bool IsBuildingRoof, + bool IsFlatRoofValid, + bool IsInsideBuildingFootprint, + bool IsInsideSolidBuilding = false); + + public delegate DropSurfaceSample DropSurfaceQuery(float x, float z, float footRadius, float referenceMaxY); + + public delegate (float X, float Z) DropClearPointQuery(float x, float z, float pad); + + public readonly record struct DropPodLifecycleEvent( + long EventId, + DropPodEventKind Kind, + int WaveIndex, + int PodId, + OrbitalPodKind PodKind, + int ContenderId, + float X, + float Y, + float Z, + float VelX, + float VelY, + float VelZ, + Vector3 SurfaceNormal, + string? ChassisId, + string? ModuleId, + int DropId, + bool RespawnsClosed, + int GearCount, + int RespawnCount); + + public readonly record struct DropWaveState( + int CurrentWaveIndex, + int NextWaveIndex, + float? NextWaveAtSec, + bool RespawnCutoffReached, + int ActivePodCount, + int WaitingRespawnCount); + + public static class DropWaveConfig + { + public static readonly float[] WaveTimes = { 0f, 85f, 165f, 245f }; + public const int MaxRespawnWave = 2; + public const float SionCutoffRadius = 580f; + public const float DesertCutoffRadius = 260f; + public const float Gravity = 20.0f; + + public static float GetCutoffRadius(ArenaMapKind mapKind) => + mapKind == ArenaMapKind.Sion ? SionCutoffRadius : DesertCutoffRadius; + } + + public readonly record struct OrbitalPodPreset( + float StartAltAgl, + float InitialVelY, + float TerminalSpeed, + float NominalRetroAccel, + float TargetTouchdownSpeed, + float SteerAccel, + float FreefallHorizDrag, + float BurnHorizDrag, + float PodFootRadius, + float SafetyMarginM) + { + public static OrbitalPodPreset GetContender(ArenaMapKind mapKind) => new( + StartAltAgl: mapKind == ArenaMapKind.Sion ? 1620.0f : 840.0f, + InitialVelY: -24.0f, + TerminalSpeed: 62.0f, + NominalRetroAccel: 125.0f, + TargetTouchdownSpeed: 2.1f, + SteerAccel: 118.0f, + FreefallHorizDrag: 0.95f, + BurnHorizDrag: 4.5f, + PodFootRadius: 1.65f, + SafetyMarginM: 4.0f); + + public static OrbitalPodPreset GetGear(ArenaMapKind mapKind) => new( + StartAltAgl: mapKind == ArenaMapKind.Sion ? 1580.0f : 740.0f, + InitialVelY: -44.0f, + TerminalSpeed: 68.0f, + NominalRetroAccel: 140.0f, + TargetTouchdownSpeed: 2.1f, + SteerAccel: 0.0f, + FreefallHorizDrag: 0.95f, + BurnHorizDrag: 4.5f, + PodFootRadius: 1.1f, + SafetyMarginM: 3.5f); + + public static float GetStartAltAgl(OrbitalPodKind kind, ArenaMapKind mapKind) => + kind == OrbitalPodKind.Contender ? GetContender(mapKind).StartAltAgl : GetGear(mapKind).StartAltAgl; + + public static readonly OrbitalPodPreset Contender = GetContender(ArenaMapKind.Desert); + public static readonly OrbitalPodPreset Gear = GetGear(ArenaMapKind.Desert); + } + + public sealed class OrbitalPod + { + public int PodId { get; set; } + public OrbitalPodKind PodKind { get; set; } + public OrbitalPodPhase Phase { get; set; } = OrbitalPodPhase.Freefall; + public int WaveIndex { get; set; } + public int ContenderId { get; set; } = -1; + public ChassisSpec? Chassis { get; set; } + public ModuleSpec? Module { get; set; } + public bool AllowFlatRoofLanding { get; set; } + + public float TargetX { get; set; } + public float TargetZ { get; set; } + + // Y is the pod base (bottom) world Y (minY == 0 in GLB). + public float X { get; set; } + public float Y { get; set; } + public float Z { get; set; } + public float PrevX { get; set; } + public float PrevY { get; set; } + public float PrevZ { get; set; } + + public float VelX { get; set; } + public float VelY { get; set; } + public float VelZ { get; set; } + public float Yaw { get; set; } + + public float CurrRotX { get; set; } + public float CurrRotY { get; set; } + public float CurrRotZ { get; set; } + public float CurrRotW { get; set; } = 1f; + public float PrevRotX { get; set; } + public float PrevRotY { get; set; } + public float PrevRotZ { get; set; } + public float PrevRotW { get; set; } = 1f; + + public float SteerForwardCmd { get; set; } + public float SteerRightCmd { get; set; } + public float LookForwardX { get; set; } + public float LookForwardZ { get; set; } = 1f; + + public float LaunchTime { get; set; } + public float FlightTime { get; set; } + public float BurnElapsed { get; set; } + public float HeatGlow { get; set; } + public float Scorch { get; set; } + public float LastAgl { get; set; } + + public Vector3 TouchdownNormal { get; set; } = Vector3.UnitY; + public float TouchdownSpeed { get; set; } + public bool TouchdownOnRoof { get; set; } + public int GroundDropId { get; set; } + + public void SnapPreviousPose() + { + PrevX = X; + PrevY = Y; + PrevZ = Z; + PrevRotX = CurrRotX; + PrevRotY = CurrRotY; + PrevRotZ = CurrRotZ; + PrevRotW = CurrRotW; + } + } + + public static class OrbitalDropKinematics + { + private const float MaxRetroAccel = 380f; + + public static OrbitalPodPreset GetPreset(OrbitalPodKind kind) => + kind == OrbitalPodKind.Contender ? OrbitalPodPreset.Contender : OrbitalPodPreset.Gear; + + public static bool StepPod( + OrbitalPod pod, + float dt, + TerrainField terrain, + DropSurfaceQuery surfaceQuery, + DropClearPointQuery findClearPoint, + out bool retroBurnStarted, + out DropSurfaceSample touchdownSample) + { + retroBurnStarted = false; + touchdownSample = default; + + if (pod.Phase == OrbitalPodPhase.Popped) + { + return false; + } + + var preset = GetPreset(pod.PodKind); + float maxBound = MathF.Max(16f, terrain.MapHalfExtent - 10f); + float g = DropWaveConfig.Gravity; + float aNetNom = MathF.Max(10f, preset.NominalRetroAccel - g); + float aMax = MathF.Max(aNetNom, MaxRetroAccel - g); + float vTouch = preset.TargetTouchdownSpeed; + + pod.FlightTime += dt; + + // 1. Surface & slope query + DropSurfaceSample sampleNow = surfaceQuery(pod.X, pod.Z, preset.PodFootRadius, pod.Y + 1.0f); + float terrainNow = terrain.SampleHeight(pod.X, pod.Z); + float surfaceNow = sampleNow.IsBuildingRoof + ? MathF.Max(terrainNow, sampleNow.SurfaceY) + : terrainNow; + + float hAgl = pod.Y - surfaceNow; + pod.LastAgl = MathF.Max(0f, hAgl); + + float vyDown = MathF.Max(0f, -pod.VelY); + float hStop = vyDown > vTouch ? (vyDown * vyDown - vTouch * vTouch) / (2f * aMax) : 0f; + + // 2. Horizontal steering & building wall/roof safety (computed first so surfaceRiseRate sees horizontal motion) + float vxNext = pod.VelX; + float vzNext = pod.VelZ; + + if (pod.Phase == OrbitalPodPhase.Freefall && preset.SteerAccel > 0f) + { + Vector2 fwd = new(pod.LookForwardX, pod.LookForwardZ); + if (fwd.LengthSquared() < 1e-4f) + { + fwd = new Vector2(MathF.Sin(pod.Yaw), MathF.Cos(pod.Yaw)); + } + else + { + fwd = Vector2.Normalize(fwd); + } + Vector2 right = new(-fwd.Y, fwd.X); + Vector2 wish = fwd * pod.SteerForwardCmd + right * pod.SteerRightCmd; + float wishLen = wish.Length(); + if (wishLen > 1f) + { + wish /= wishLen; + } + + vxNext += (wish.X * preset.SteerAccel - pod.VelX * preset.FreefallHorizDrag) * dt; + vzNext += (wish.Y * preset.SteerAccel - pod.VelZ * preset.FreefallHorizDrag) * dt; + } + else + { + vxNext += (-pod.VelX * preset.BurnHorizDrag) * dt; + vzNext += (-pod.VelZ * preset.BurnHorizDrag) * dt; + } + + // Roof / building deflection when over an invalid landing spot (start early at < 85m above terrain so gear/AI clear roofs before retro-burn) + bool invalidRoofOrBuilding = + (sampleNow.IsInsideBuildingFootprint || sampleNow.IsBuildingRoof) && + !(pod.AllowFlatRoofLanding && sampleNow.IsFlatRoofValid); + if ((hAgl < 55f || (pod.Y - terrainNow) < 85f) && invalidRoofOrBuilding) + { + var (clearX, clearZ) = findClearPoint(pod.X, pod.Z, preset.PodFootRadius + 1.5f); + float dx = clearX - pod.X; + float dz = clearZ - pod.Z; + float dist = MathF.Sqrt(dx * dx + dz * dz); + if (dist > 0.1f) + { + float maxPull = hAgl < 12f ? 14f : 28f; + float pullSpeed = Math.Clamp(dist * 3.5f, 10f, maxPull); + vxNext = (dx / dist) * pullSpeed; + vzNext = (dz / dist) * pullSpeed; + } + } + + float targetX = Math.Clamp(pod.X + vxNext * dt, -maxBound, maxBound); + float targetZ = Math.Clamp(pod.Z + vzNext * dt, -maxBound, maxBound); + float candDx = targetX - pod.X; + float candDz = targetZ - pod.Z; + float candDist = MathF.Sqrt(candDx * candDx + candDz * candDz); + int subSteps = Math.Clamp((int)MathF.Ceiling(candDist / 0.75f), 1, 4); + + // Lateral Building Wall & Stepped-Roof Guard: swept <= 0.75m horizontal sub-steps reject/slide before wall entry + float curX = pod.X; + float curZ = pod.Z; + DropSurfaceSample curSample = sampleNow; + float curSurfaceY = surfaceNow; + float subDt = dt / subSteps; + + for (int s = 0; s < subSteps; s++) + { + float stepX = Math.Clamp(curX + vxNext * subDt, -maxBound, maxBound); + float stepZ = Math.Clamp(curZ + vzNext * subDt, -maxBound, maxBound); + DropSurfaceSample stepSample = surfaceQuery(stepX, stepZ, preset.PodFootRadius, pod.Y + 1.0f); + if (IsBlockedHorizontalMove(pod, curSample, stepSample, curSurfaceY, hStop)) + { + DropSurfaceSample slideX = surfaceQuery(stepX, curZ, preset.PodFootRadius, pod.Y + 1.0f); + DropSurfaceSample slideZ = surfaceQuery(curX, stepZ, preset.PodFootRadius, pod.Y + 1.0f); + if (!IsBlockedHorizontalMove(pod, curSample, slideX, curSurfaceY, hStop)) + { + curX = stepX; + vzNext = 0f; + curSample = slideX; + } + else if (!IsBlockedHorizontalMove(pod, curSample, slideZ, curSurfaceY, hStop)) + { + curZ = stepZ; + vxNext = 0f; + curSample = slideZ; + } + else + { + vxNext = 0f; + vzNext = 0f; + break; + } + } + else + { + curX = stepX; + curZ = stepZ; + curSample = stepSample; + } + + float subTerrain = terrain.SampleHeight(curX, curZ); + curSurfaceY = curSample.IsBuildingRoof + ? MathF.Max(subTerrain, curSample.SurfaceY) + : subTerrain; + } + + float xCand = curX; + float zCand = curZ; + DropSurfaceSample sampleNext = curSample; + + float terrainNext = terrain.SampleHeight(xCand, zCand); + float surfaceNext = sampleNext.IsBuildingRoof + ? MathF.Max(terrainNext, sampleNext.SurfaceY) + : terrainNext; + + float terrainAhead = MathF.Max( + terrainNext, + terrain.SampleHeight(xCand + vxNext * 0.28f, zCand + vzNext * 0.28f)); + float surfaceAhead = terrainAhead; + if (pod.AllowFlatRoofLanding && (vxNext * vxNext + vzNext * vzNext) > 0.25f) + { + DropSurfaceSample aheadSample = surfaceQuery( + xCand + vxNext * 0.28f, + zCand + vzNext * 0.28f, + preset.PodFootRadius, + pod.Y + 1.0f); + if (aheadSample.IsBuildingRoof && aheadSample.IsFlatRoofValid && aheadSample.SurfaceY <= pod.Y - (hStop + 1.5f)) + { + surfaceAhead = MathF.Max(surfaceAhead, aheadSample.SurfaceY); + } + } + float hEff = pod.Y - MathF.Max(surfaceNext, surfaceAhead); + + // 3. Closing speed & burn trigger (continuous terrain/same-roof slope so vertical building edges never spike vClose) + float vDown = MathF.Max(0f, -pod.VelY); + float surfSlopeRise = (sampleNow.IsBuildingRoof && sampleNext.IsBuildingRoof && MathF.Abs(surfaceNext - surfaceNow) <= 1.0f) + ? MathF.Max(0f, (surfaceNext - surfaceNow) / dt) + : 0f; + float horizSpeed = MathF.Sqrt(pod.VelX * pod.VelX + pod.VelZ * pod.VelZ); + float maxPhysicalRise = MathF.Min(32f, MathF.Max(4.0f, horizSpeed * 1.15f)); + float slopeRiseRate = MathF.Min(maxPhysicalRise, MathF.Max(MathF.Max(0f, (terrainNext - terrainNow) / dt), surfSlopeRise)); + float vClose = vDown + slopeRiseRate; + float hBurn = MathF.Max( + 8.0f, + MathF.Max(0f, vClose * vClose - vTouch * vTouch) / (2f * aNetNom) + preset.SafetyMarginM); + + if (pod.Phase == OrbitalPodPhase.Freefall && hEff <= hBurn) + { + pod.Phase = OrbitalPodPhase.RetroBurn; + retroBurnStarted = true; + } + + // 4. Vertical dynamics (exact closed-form hover-slam) + float vyNext; + if (pod.Phase == OrbitalPodPhase.Freefall) + { + float kAir = g / (preset.TerminalSpeed * preset.TerminalSpeed); + // VelY < 0 while falling, so -kAir * VelY * |VelY| > 0 (upward drag resisting fall) + float ay = -g - kAir * pod.VelY * MathF.Abs(pod.VelY); + vyNext = pod.VelY + ay * dt; + float speedFrac = Math.Clamp(MathF.Abs(vyNext) / preset.TerminalSpeed, 0f, 1f); + pod.HeatGlow = MathF.Max(pod.HeatGlow * 0.96f, speedFrac * 0.85f); + pod.Scorch = MathF.Min(0.45f, pod.Scorch + speedFrac * 0.08f * dt); + } + else + { + pod.BurnElapsed += dt; + float dRem = MathF.Max(0.05f, pod.Y - surfaceNext); + float aNetReq = (vClose * vClose - vTouch * vTouch) / (2f * dRem); + + float aNet; + if (vClose <= vTouch) + { + aNet = dRem > 3.5f ? -g * 0.6f : 0f; + } + else + { + aNet = Math.Clamp(aNetReq, 0f, 380f); + } + + vyNext = pod.VelY + aNet * dt; + if (dRem < 12f && vyNext > -vTouch) + { + vyNext = -vTouch; + } + + pod.HeatGlow = 1.0f; + pod.Scorch = MathF.Min(0.75f, pod.Scorch + 0.45f * dt); + } + + float yCand = pod.Y + vyNext * dt; + + // Tilt pod subtly into horizontal motion during freefall, snap upright in retro-burn + float tiltX = pod.Phase == OrbitalPodPhase.Freefall ? Math.Clamp(vzNext * 0.008f, -0.22f, 0.22f) : 0f; + float tiltZ = pod.Phase == OrbitalPodPhase.Freefall ? Math.Clamp(-vxNext * 0.008f, -0.22f, 0.22f) : 0f; + Quaternion qPod = Quaternion.CreateFromYawPitchRoll(pod.Yaw, tiltX, tiltZ); + pod.CurrRotX = qPod.X; + pod.CurrRotY = qPod.Y; + pod.CurrRotZ = qPod.Z; + pod.CurrRotW = qPod.W; + + pod.X = xCand; + pod.Z = zCand; + pod.VelX = vxNext; + pod.VelZ = vzNext; + + if (yCand <= surfaceNext) + { + // Guarantee 0 building-interior / invalid-roof touchdowns + bool touchInvalidBuilding = + sampleNext.IsInsideSolidBuilding || + (sampleNext.IsBuildingRoof && !(pod.AllowFlatRoofLanding && sampleNext.IsFlatRoofValid)); + if (touchInvalidBuilding) + { + var (clearX, clearZ) = findClearPoint(pod.X, pod.Z, preset.PodFootRadius + 1.5f); + pod.X = Math.Clamp(clearX, -maxBound, maxBound); + pod.Z = Math.Clamp(clearZ, -maxBound, maxBound); + sampleNext = surfaceQuery(pod.X, pod.Z, preset.PodFootRadius, pod.Y + 60f); + terrainNext = terrain.SampleHeight(pod.X, pod.Z); + if (!sampleNext.IsBuildingRoof && !sampleNext.IsInsideSolidBuilding) + { + surfaceNext = terrainNext; + } + else if (pod.AllowFlatRoofLanding && sampleNext.IsFlatRoofValid) + { + surfaceNext = MathF.Max(terrainNext, sampleNext.SurfaceY); + } + else + { + surfaceNext = terrainNext; + sampleNext = new DropSurfaceSample( + terrainNext, + ToNormalVec(terrain.SampleNormal(pod.X, pod.Z)), + IsBuildingRoof: false, + IsFlatRoofValid: false, + IsInsideBuildingFootprint: false, + IsInsideSolidBuilding: false); + } + } + + pod.Y = surfaceNext; + pod.VelY = vyNext; + pod.TouchdownSpeed = MathF.Abs(vyNext); + pod.TouchdownNormal = sampleNext.Normal.LengthSquared() > 1e-4f + ? Vector3.Normalize(sampleNext.Normal) + : Vector3.UnitY; + pod.TouchdownOnRoof = sampleNext.IsBuildingRoof && pod.AllowFlatRoofLanding && sampleNext.IsFlatRoofValid; + pod.Phase = OrbitalPodPhase.Popped; + pod.LastAgl = 0f; + + Quaternion qTouch = Quaternion.CreateFromYawPitchRoll(pod.Yaw, 0f, 0f); + pod.CurrRotX = qTouch.X; + pod.CurrRotY = qTouch.Y; + pod.CurrRotZ = qTouch.Z; + pod.CurrRotW = qTouch.W; + + touchdownSample = sampleNext with { SurfaceY = surfaceNext }; + return true; + } + + pod.Y = yCand; + pod.VelY = vyNext; + pod.LastAgl = MathF.Max(0f, pod.Y - surfaceNext); + return false; + } + + private static bool IsBlockedHorizontalMove( + OrbitalPod pod, + in DropSurfaceSample sampleNow, + in DropSurfaceSample sampleNext, + float surfaceNow, + float hStop) + { + if (sampleNext.SurfaceY > pod.Y - (hStop + 1.5f) && + (sampleNext.SurfaceY > surfaceNow + 0.25f || sampleNext.SurfaceY > pod.Y - 0.5f)) + { + return true; + } + + if (!sampleNow.IsInsideSolidBuilding && sampleNext.IsInsideSolidBuilding) + { + return true; + } + + if (!sampleNow.IsInsideBuildingFootprint && + sampleNext.IsInsideBuildingFootprint && + !sampleNext.IsBuildingRoof) + { + return true; + } + + bool lowOverNextRoof = pod.Phase == OrbitalPodPhase.RetroBurn || pod.Y - sampleNext.SurfaceY < hStop + 6.0f; + + if (lowOverNextRoof && + !pod.AllowFlatRoofLanding && + sampleNext.IsBuildingRoof && + !sampleNow.IsBuildingRoof) + { + return true; + } + + if (pod.AllowFlatRoofLanding && + sampleNext.IsBuildingRoof && + !sampleNext.IsFlatRoofValid && + !sampleNow.IsBuildingRoof && + (pod.Phase == OrbitalPodPhase.RetroBurn || pod.Y - sampleNext.SurfaceY < 8f)) + { + return true; + } + + return false; + } + + private static Vector3 ToNormalVec((float Nx, float Ny, float Nz) n) + { + var v = new Vector3(n.Nx, n.Ny, n.Nz); + return v.LengthSquared() > 1e-4f ? Vector3.Normalize(v) : Vector3.UnitY; + } + } + + public sealed class OrbitalDropSystem + { + private readonly MatchState _state; + private readonly List _activePods = new(); + private readonly List _replicatedPods = new(); + private int _nextPodId = 1; + private long _nextPodEventId = 1; + private int _currentWaveIndex; + private int _nextWaveIndex; + private bool _respawnCutoffReached; + private bool _wave0Started; + + public OrbitalDropSystem(MatchState state) + { + _state = state; + } + + public IReadOnlyList ActivePods => _activePods; + public int CurrentWaveIndex => _currentWaveIndex; + public int NextWaveIndex => _nextWaveIndex; + public bool RespawnCutoffReached => _respawnCutoffReached; + public float? NextWaveAtSec => + _nextWaveIndex < DropWaveConfig.WaveTimes.Length + ? DropWaveConfig.WaveTimes[_nextWaveIndex] + : null; + + public DropWaveState WaveState + { + get + { + int waiting = 0; + for (int i = 0; i < _state.Contenders.Count; i++) + { + if (_state.Contenders[i].WaitingForRespawn) waiting++; + } + return new DropWaveState( + _currentWaveIndex, + _nextWaveIndex, + NextWaveAtSec, + _respawnCutoffReached, + _activePods.Count, + waiting); + } + } + + public long AllocatePodEventId() => _nextPodEventId++; + + public void BeginWave0( + IReadOnlyList<(int ContenderId, float X, float Z, float Yaw)> contenderTargets, + IReadOnlyList<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> gearTargets, + DropSurfaceQuery? surfaceQuery = null) + { + _wave0Started = true; + _currentWaveIndex = 0; + _nextWaveIndex = 1; + _respawnCutoffReached = false; + _activePods.Clear(); + + surfaceQuery ??= _state.DefaultDropSurfaceQuery; + + EmitLifecycleEvent( + DropPodEventKind.WaveAnnounced, + waveIndex: 0, + podId: 0, + podKind: OrbitalPodKind.Contender, + contenderId: -1, + x: 0f, y: 0f, z: 0f, + velX: 0f, velY: 0f, velZ: 0f, + normal: Vector3.UnitY, + chassisId: null, + moduleId: null, + dropId: 0, + respawnsClosed: false, + gearCount: gearTargets.Count, + respawnCount: contenderTargets.Count); + + _state.Broadcast.EmitDropWave(_state.Time, 0, gearTargets.Count, contenderTargets.Count, false); + + for (int i = 0; i < gearTargets.Count; i++) + { + var g = gearTargets[i]; + LaunchGearPod(waveIndex: 0, g.X, g.Z, g.Chassis, g.Module, surfaceQuery); + } + + for (int i = 0; i < contenderTargets.Count; i++) + { + var t = contenderTargets[i]; + if (t.ContenderId < 0 || t.ContenderId >= _state.Contenders.Count) continue; + var c = _state.Contenders[t.ContenderId]; + LaunchContenderPod(c, waveIndex: 0, t.X, t.Z, t.Yaw, surfaceQuery, isRespawn: false); + } + } + + public OrbitalPod LaunchContenderPod( + ContenderState c, + int waveIndex, + float targetX, + float targetZ, + float yaw, + DropSurfaceQuery surfaceQuery, + bool isRespawn) + { + CancelContenderPod(c.Id); + + var preset = OrbitalPodPreset.GetContender(_state.MapKind); + float groundY = ResolveGroundSurfaceY(targetX, targetZ, preset.PodFootRadius, surfaceQuery); + float stagger; + if (_state.SquadSize > 1) + { + (_, _, stagger) = MatchState.GetSquadFormationOffset(_state.GetSquadMemberRank(c.Id)); + } + else + { + stagger = ((c.Id % 3) - 1) * 6f; + } + float startY = groundY + preset.StartAltAgl + stagger; + + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw); + var pod = new OrbitalPod + { + PodId = _nextPodId++, + PodKind = OrbitalPodKind.Contender, + Phase = OrbitalPodPhase.Freefall, + WaveIndex = waveIndex, + ContenderId = c.Id, + Chassis = c.Grid.Spec, + AllowFlatRoofLanding = c.IsHuman && _state.MapKind == ArenaMapKind.Sion, + TargetX = targetX, + TargetZ = targetZ, + X = targetX, + Y = startY, + Z = targetZ, + VelX = 0f, + VelY = preset.InitialVelY, + VelZ = 0f, + Yaw = yaw, + CurrRotX = q.X, + CurrRotY = q.Y, + CurrRotZ = q.Z, + CurrRotW = q.W, + LookForwardX = MathF.Sin(yaw), + LookForwardZ = MathF.Cos(yaw), + LaunchTime = _state.Time, + LastAgl = startY - groundY + }; + pod.SnapPreviousPose(); + _activePods.Add(pod); + + c.Lifecycle = ContenderLifecycle.Deploying; + c.ActivePodId = pod.PodId; + c.HasTouchdownPose = false; + c.TouchdownOnRoof = false; + c.X = pod.X; + c.Y = pod.Y + c.Grid.Spec.HalfHeight; + c.Z = pod.Z; + c.Yaw = yaw; + c.CurrRotX = q.X; + c.CurrRotY = q.Y; + c.CurrRotZ = q.Z; + c.CurrRotW = q.W; + c.VelX = pod.VelX; + c.VelY = pod.VelY; + c.VelZ = pod.VelZ; + c.Speed = 0f; + c.FireCmd = false; + c.ThrottleCmd = 0f; + c.SteerCmd = 0f; + c.SnapPreviousPose(); + c.ResetAimTracker(yaw); + + EmitLifecycleEvent( + DropPodEventKind.PodLaunched, + waveIndex, + pod.PodId, + OrbitalPodKind.Contender, + c.Id, + pod.X, pod.Y, pod.Z, + pod.VelX, pod.VelY, pod.VelZ, + Vector3.UnitY, + c.Grid.Spec.Id, + null, + dropId: 0, + _respawnCutoffReached, + gearCount: 0, + respawnCount: isRespawn ? 1 : 0); + + return pod; + } + + public OrbitalPod LaunchGearPod( + int waveIndex, + float targetX, + float targetZ, + ChassisSpec? chassis, + ModuleSpec? module, + DropSurfaceQuery surfaceQuery) + { + var preset = OrbitalPodPreset.GetGear(_state.MapKind); + float groundY = ResolveGroundSurfaceY(targetX, targetZ, preset.PodFootRadius, surfaceQuery); + float startY = groundY + preset.StartAltAgl; + float yaw = (float)((_nextPodId * 1.17f) % MathF.Tau); + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw); + + var pod = new OrbitalPod + { + PodId = _nextPodId++, + PodKind = chassis is not null ? OrbitalPodKind.Chassis : OrbitalPodKind.Module, + Phase = OrbitalPodPhase.Freefall, + WaveIndex = waveIndex, + ContenderId = -1, + Chassis = chassis, + Module = module, + AllowFlatRoofLanding = false, + TargetX = targetX, + TargetZ = targetZ, + X = targetX, + Y = startY, + Z = targetZ, + VelX = 0f, + VelY = preset.InitialVelY, + VelZ = 0f, + Yaw = yaw, + CurrRotX = q.X, + CurrRotY = q.Y, + CurrRotZ = q.Z, + CurrRotW = q.W, + LaunchTime = _state.Time, + LastAgl = startY - groundY + }; + pod.SnapPreviousPose(); + _activePods.Add(pod); + + EmitLifecycleEvent( + DropPodEventKind.PodLaunched, + waveIndex, + pod.PodId, + pod.PodKind, + contenderId: -1, + pod.X, pod.Y, pod.Z, + pod.VelX, pod.VelY, pod.VelZ, + Vector3.UnitY, + chassis?.Id, + module?.Id, + dropId: 0, + _respawnCutoffReached, + gearCount: 0, + respawnCount: 0); + + return pod; + } + + public void CancelContenderPod(int contenderId, bool emitEvent = true) + { + for (int i = _activePods.Count - 1; i >= 0; i--) + { + var pod = _activePods[i]; + if (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId == contenderId) + { + _activePods.RemoveAt(i); + if (emitEvent) + { + EmitLifecycleEvent( + DropPodEventKind.PodCancelled, + pod.WaveIndex, + pod.PodId, + pod.PodKind, + pod.ContenderId, + pod.X, pod.Y, pod.Z, + 0f, 0f, 0f, + Vector3.UnitY, + pod.Chassis?.Id, + pod.Module?.Id, + dropId: 0, + _respawnCutoffReached, + gearCount: 0, + respawnCount: 0); + } + } + } + if (contenderId >= 0 && contenderId < _state.Contenders.Count) + { + _state.Contenders[contenderId].ActivePodId = null; + } + } + + public void RemoveActivePodAt(int index) + { + if (index >= 0 && index < _activePods.Count) + { + _activePods.RemoveAt(index); + } + } + + public void DeployAllPodsImmediately(DropSurfaceQuery? surfaceQuery = null) + { + surfaceQuery ??= _state.DefaultDropSurfaceQuery; + for (int i = _activePods.Count - 1; i >= 0; i--) + { + var pod = _activePods[i]; + var preset = OrbitalDropKinematics.GetPreset(pod.PodKind); + float groundY = _state.Terrain.SampleHeight(pod.TargetX, pod.TargetZ); + var sample = surfaceQuery(pod.TargetX, pod.TargetZ, preset.PodFootRadius, groundY + 120f); + pod.X = pod.TargetX; + pod.Z = pod.TargetZ; + pod.Y = sample.SurfaceY; + pod.VelX = 0f; + pod.VelY = -preset.TargetTouchdownSpeed; + pod.VelZ = 0f; + pod.TouchdownSpeed = preset.TargetTouchdownSpeed; + pod.TouchdownNormal = sample.Normal; + pod.TouchdownOnRoof = false; + pod.Phase = OrbitalPodPhase.Popped; + HandlePodTouchdown(pod, sample, surfaceQuery, null, emitEvents: false); + _activePods.RemoveAt(i); + } + } + + public void SnapshotPreviousPoses() + { + for (int i = 0; i < _activePods.Count; i++) + { + _activePods[i].SnapPreviousPose(); + } + } + + public void UpdateAiPodSteering(ContenderState ai) + { + if (!ai.IsInDropPod || !ai.ActivePodId.HasValue) + { + return; + } + + OrbitalPod? pod = FindPodById(ai.ActivePodId.Value); + if (pod is null || pod.Phase != OrbitalPodPhase.Freefall) + { + return; + } + + // Squad V-chevron formation-follow above 140m AGL (only while leader is also above 140m split altitude) + if (_state.SquadSize > 1 && pod.LastAgl > 140f) + { + var leader = _state.GetSquadLeader(ai.SquadId); + if (leader is not null && leader.Id != ai.Id && leader.IsInDropPod && leader.ActivePodId.HasValue) + { + var leaderPod = FindPodById(leader.ActivePodId.Value); + if (leaderPod is not null && leaderPod.Phase == OrbitalPodPhase.Freefall && leaderPod.LastAgl > 140f) + { + Vector2 fwd = new(leaderPod.LookForwardX, leaderPod.LookForwardZ); + if (fwd.LengthSquared() < 1e-4f) + { + fwd = new Vector2(MathF.Sin(leaderPod.Yaw), MathF.Cos(leaderPod.Yaw)); + } + else + { + fwd = Vector2.Normalize(fwd); + } + Vector2 right = new(-fwd.Y, fwd.X); + int rank = _state.GetSquadMemberRank(ai.Id); + var (fwdOff, sideOff, _) = MatchState.GetSquadFormationOffset(rank); + float relFwd = fwdOff - 8f; + float formWorldX = fwd.X * relFwd + right.X * sideOff; + float formWorldZ = fwd.Y * relFwd + right.Y * sideOff; + + float fdx = (leaderPod.X + formWorldX) - pod.X; + float fdz = (leaderPod.Z + formWorldZ) - pod.Z; + float fDist = MathF.Sqrt(fdx * fdx + fdz * fdz); + if (fDist > 1.5f) + { + pod.LookForwardX = fdx / fDist; + pod.LookForwardZ = fdz / fDist; + pod.Yaw = MathF.Atan2(pod.LookForwardX, pod.LookForwardZ); + pod.SteerForwardCmd = Math.Clamp(fDist * 0.08f, 0f, 1f); + pod.SteerRightCmd = 0f; + } + else + { + pod.SteerForwardCmd = 0f; + pod.SteerRightCmd = 0f; + } + return; + } + } + } + + // Below 140m AGL (or FFA): split cleanly onto clear ground >= 12m from squadmates + float goalX = 0f; + float goalZ = 0f; + bool hasGoal = false; + bool urgentSplit = false; + float safeLimit = MathF.Max(40f, _state.Spectators.SafeRadius - 35f); + float distFromCenter = MathF.Sqrt(pod.X * pod.X + pod.Z * pod.Z); + + if (_state.SquadSize > 1) + { + bool tooCloseNow = IsTooCloseToSquadmate(ai, pod.X, pod.Z, 15.5f, out float repulseX, out float repulseZ); + float predX = pod.X + pod.VelX * 0.65f; + float predZ = pod.Z + pod.VelZ * 0.65f; + bool tooClosePred = !tooCloseNow && IsTooCloseToSquadmate(ai, predX, predZ, 15.0f, out repulseX, out repulseZ, lookaheadSec: 0.65f); + bool tooCloseToAlly = tooCloseNow || tooClosePred; + + var surfNow = _state.DefaultDropSurfaceQuery(pod.X, pod.Z, OrbitalPodPreset.GetContender(_state.MapKind).PodFootRadius, pod.Y + 1.0f); + bool overInvalidBuilding = surfNow.IsInsideBuildingFootprint || (surfNow.IsBuildingRoof && !pod.AllowFlatRoofLanding); + if (tooCloseToAlly || overInvalidBuilding) + { + urgentSplit = tooCloseToAlly; + float seekX = tooCloseToAlly ? repulseX : pod.X; + float seekZ = tooCloseToAlly ? repulseZ : pod.Z; + var (cx, cz) = FindClearDropPointAvoidingSquadmates( + ai, + seekX, + seekZ, + 4.5f, + 15.5f, + _state.DefaultDropSurfaceQuery, + pod.AllowFlatRoofLanding); + goalX = cx; + goalZ = cz; + hasGoal = true; + } + } + + if (!hasGoal && distFromCenter > safeLimit) + { + hasGoal = true; + } + else if (!hasGoal) + { + float bestSq = 180f * 180f; + for (int i = 0; i < _state.GroundDrops.Count; i++) + { + var d = _state.GroundDrops[i]; + if (d.PickedUp) continue; + if (_state.SquadSize > 1 && + (IsTooCloseToSquadmate(ai, d.X, d.Z, 16.0f, out _, out _) || + IsGroundDropClaimedBySquadmate(ai, pod, d.X, d.Z))) + { + continue; + } + float dx = d.X - pod.X; + float dz = d.Z - pod.Z; + float d2 = dx * dx + dz * dz; + if (d2 < bestSq) + { + bestSq = d2; + goalX = d.X; + goalZ = d.Z; + hasGoal = true; + } + } + } + + if (hasGoal) + { + float dx = goalX - pod.X; + float dz = goalZ - pod.Z; + float len = MathF.Sqrt(dx * dx + dz * dz); + float minLen = urgentSplit ? 0.5f : 4f; + if (len > minLen) + { + pod.LookForwardX = dx / len; + pod.LookForwardZ = dz / len; + pod.SteerForwardCmd = urgentSplit + ? Math.Clamp(len * 0.15f, 0.5f, 1.0f) + : Math.Clamp(len * 0.035f, 0.2f, 0.55f); + pod.SteerRightCmd = 0f; + return; + } + } + + pod.SteerForwardCmd = 0f; + pod.SteerRightCmd = 0f; + } + + private (float X, float Z) FindClearDropPointAvoidingSquadmates( + ContenderState self, + float targetX, + float targetZ, + float pad, + float minSepM, + DropSurfaceQuery surfaceQuery, + bool allowFlatRoofLanding) + { + float footRadius = OrbitalPodPreset.GetContender(_state.MapKind).PodFootRadius; + var (cx, cz) = _state.FindClearDropPoint(targetX, targetZ, pad); + if (!IsTooCloseToSquadmate(self, cx, cz, minSepM, out _, out _)) + { + var surf0 = surfaceQuery(cx, cz, footRadius, _state.Terrain.SampleHeight(cx, cz) + 250f); + if (!surf0.IsInsideBuildingFootprint && !(surf0.IsBuildingRoof && !allowFlatRoofLanding)) + { + return (cx, cz); + } + } + + float baseAngle = self.Id * 2.1f; + float[] radii = { 16f, 24f, 34f, 46f, 60f }; + for (int rIdx = 0; rIdx < radii.Length; rIdx++) + { + float radius = radii[rIdx]; + for (int k = 0; k < 12; k++) + { + float ang = baseAngle + k * (MathF.Tau / 12f); + float rawX = targetX + MathF.Cos(ang) * radius; + float rawZ = targetZ + MathF.Sin(ang) * radius; + var (candX, candZ) = _state.FindClearDropPoint(rawX, rawZ, pad); + if (IsTooCloseToSquadmate(self, candX, candZ, minSepM, out _, out _)) + { + continue; + } + var surf = surfaceQuery(candX, candZ, footRadius, _state.Terrain.SampleHeight(candX, candZ) + 250f); + if (surf.IsInsideBuildingFootprint || (surf.IsBuildingRoof && !allowFlatRoofLanding)) + { + continue; + } + return (candX, candZ); + } + } + + return (cx, cz); + } + + private bool IsGroundDropClaimedBySquadmate(ContenderState self, OrbitalPod selfPod, float dropX, float dropZ) + { + float selfDx = dropX - selfPod.X; + float selfDz = dropZ - selfPod.Z; + float selfDistSq = selfDx * selfDx + selfDz * selfDz; + + for (int i = 0; i < _activePods.Count; i++) + { + var otherPod = _activePods[i]; + if (otherPod.PodKind != OrbitalPodKind.Contender || otherPod.ContenderId == self.Id) continue; + if (!_state.AreAllies(self.Id, otherPod.ContenderId)) continue; + float odx = dropX - otherPod.X; + float odz = dropZ - otherPod.Z; + float otherDistSq = odx * odx + odz * odz; + if (otherDistSq < selfDistSq - 1e-2f || + (MathF.Abs(otherDistSq - selfDistSq) <= 1e-2f && otherPod.ContenderId < self.Id)) + { + return true; + } + } + return false; + } + + private bool IsTooCloseToSquadmate( + ContenderState self, + float x, + float z, + float minSepM, + out float escapeX, + out float escapeZ, + float lookaheadSec = 0f) + { + escapeX = x; + escapeZ = z; + float minSepSq = minSepM * minSepM; + bool any = false; + int closeCount = 0; + float sumRx = 0f; + float sumRz = 0f; + float singleOtherX = x; + float singleOtherZ = z; + + void Accumulate(int otherId, float ox, float oz) + { + float dx = x - ox; + float dz = z - oz; + float d2 = dx * dx + dz * dz; + if (d2 < minSepSq) + { + float dist = MathF.Sqrt(d2); + float nx = dist > 0.1f ? dx / dist : MathF.Cos((self.Id + otherId + 1) * 2.1f); + float nz = dist > 0.1f ? dz / dist : MathF.Sin((self.Id + otherId + 1) * 2.1f); + float weight = MathF.Max(1f, minSepM - dist + 2f); + sumRx += nx * weight; + sumRz += nz * weight; + singleOtherX = ox; + singleOtherZ = oz; + closeCount++; + any = true; + } + } + + for (int i = 0; i < _activePods.Count; i++) + { + var otherPod = _activePods[i]; + if (otherPod.PodKind != OrbitalPodKind.Contender || otherPod.ContenderId == self.Id) continue; + if (!_state.AreAllies(self.Id, otherPod.ContenderId)) continue; + Accumulate(otherPod.ContenderId, otherPod.X + otherPod.VelX * lookaheadSec, otherPod.Z + otherPod.VelZ * lookaheadSec); + } + + for (int i = 0; i < _state.Contenders.Count; i++) + { + var c = _state.Contenders[i]; + if (c.Id == self.Id || !c.Alive || c.IsInDropPod) continue; + if (!_state.AreAllies(self.Id, c.Id)) continue; + Accumulate(c.Id, c.X, c.Z); + } + + if (any) + { + float rLen = MathF.Sqrt(sumRx * sumRx + sumRz * sumRz); + float rx = rLen > 1e-4f ? sumRx / rLen : MathF.Cos(self.Id * 2.1f); + float rz = rLen > 1e-4f ? sumRz / rLen : MathF.Sin(self.Id * 2.1f); + float anchorX = closeCount == 1 ? singleOtherX : x; + float anchorZ = closeCount == 1 ? singleOtherZ : z; + escapeX = anchorX + rx * (minSepM + 4.5f); + escapeZ = anchorZ + rz * (minSepM + 4.5f); + } + return any; + } + + public void ApplyPlayerSteerInput(ContenderState human, DropSurfaceQuery? surfaceQuery = null) + { + if (!human.IsInDropPod || !human.ActivePodId.HasValue) + { + return; + } + var pod = FindPodById(human.ActivePodId.Value); + if (pod is null) + { + return; + } + pod.AllowFlatRoofLanding = human.IsHuman && _state.MapKind == ArenaMapKind.Sion; + pod.SteerForwardCmd = Math.Clamp(human.ThrottleCmd, -1f, 1f); + pod.SteerRightCmd = Math.Clamp(human.SteerCmd, -1f, 1f); + + float dx = human.AimX - pod.X; + float dz = human.AimZ - pod.Z; + float d2 = dx * dx + dz * dz; + if (float.IsFinite(d2) && d2 > 0.25f) + { + float inv = 1f / MathF.Sqrt(d2); + pod.LookForwardX = dx * inv; + pod.LookForwardZ = dz * inv; + pod.Yaw = MathF.Atan2(pod.LookForwardX, pod.LookForwardZ); + } + } + + public void Step( + float dt, + DropSurfaceQuery? surfaceQuery = null, + Action? onPodTouchedDown = null) + { + surfaceQuery ??= _state.DefaultDropSurfaceQuery; + + // 1. Check Final-Ring Cutoff against current ring radius + CheckFinalRingCutoff(); + + // 2. Launch scheduled Patron Drop Waves (1..3) + if (_wave0Started) + { + while (_nextWaveIndex < DropWaveConfig.WaveTimes.Length && + _state.Time >= DropWaveConfig.WaveTimes[_nextWaveIndex]) + { + LaunchScheduledWave(_nextWaveIndex, surfaceQuery); + _nextWaveIndex++; + if (_nextWaveIndex > DropWaveConfig.MaxRespawnWave) + { + TriggerRespawnCutoff(); + } + } + } + + // 3. Step all airborne pods + for (int i = _activePods.Count - 1; i >= 0; i--) + { + var pod = _activePods[i]; + DropClearPointQuery clearQuery = _state.FindClearDropPoint; + if (pod.PodKind == OrbitalPodKind.Contender && + pod.ContenderId >= 0 && + pod.ContenderId < _state.Contenders.Count) + { + var c = _state.Contenders[pod.ContenderId]; + pod.AllowFlatRoofLanding = c.IsHuman && _state.MapKind == ArenaMapKind.Sion; + if (_state.SquadSize > 1) + { + clearQuery = (qx, qz, qpad) => FindClearDropPointAvoidingSquadmates( + c, + qx, + qz, + qpad, + 14.5f, + surfaceQuery, + pod.AllowFlatRoofLanding); + } + } + + bool touched = OrbitalDropKinematics.StepPod( + pod, + dt, + _state.Terrain, + surfaceQuery, + clearQuery, + out bool retroBurnStarted, + out DropSurfaceSample touchSample); + + if (retroBurnStarted) + { + EmitLifecycleEvent( + DropPodEventKind.PodRetroBurnStart, + pod.WaveIndex, + pod.PodId, + pod.PodKind, + pod.ContenderId, + pod.X, pod.Y, pod.Z, + pod.VelX, pod.VelY, pod.VelZ, + Vector3.UnitY, + pod.Chassis?.Id, + pod.Module?.Id, + dropId: 0, + _respawnCutoffReached, + gearCount: 0, + respawnCount: 0); + } + + if (pod.PodKind == OrbitalPodKind.Contender && + pod.ContenderId >= 0 && + pod.ContenderId < _state.Contenders.Count && + !touched) + { + var c = _state.Contenders[pod.ContenderId]; + c.X = pod.X; + c.Y = pod.Y + c.Grid.Spec.HalfHeight; + c.Z = pod.Z; + c.Yaw = pod.Yaw; + c.CurrRotX = pod.CurrRotX; + c.CurrRotY = pod.CurrRotY; + c.CurrRotZ = pod.CurrRotZ; + c.CurrRotW = pod.CurrRotW; + c.VelX = pod.VelX; + c.VelY = pod.VelY; + c.VelZ = pod.VelZ; + c.Speed = MathF.Sqrt(pod.VelX * pod.VelX + pod.VelZ * pod.VelZ); + } + + if (touched) + { + HandlePodTouchdown(pod, touchSample, surfaceQuery, onPodTouchedDown, emitEvents: true); + _activePods.RemoveAt(i); + } + } + } + + public bool CanAnyWaitingContenderRespawn() + { + if (_respawnCutoffReached || _nextWaveIndex > DropWaveConfig.MaxRespawnWave) + { + return false; + } + float cutoff = DropWaveConfig.GetCutoffRadius(_state.MapKind); + return _state.Spectators.SafeRadius > cutoff; + } + + public void OnContenderEliminated(ContenderState victim) + { + CancelContenderPod(victim.Id); + CheckFinalRingCutoff(); + + if (victim.RespawnsRemaining > 0 && CanAnyWaitingContenderRespawn()) + { + victim.Lifecycle = ContenderLifecycle.WaitingForRespawnWave; + } + else + { + victim.Lifecycle = ContenderLifecycle.Eliminated; + } + } + + public void CheckFinalRingCutoff() + { + if (_respawnCutoffReached) + { + EvictWaitingContenders(); + return; + } + + float cutoff = DropWaveConfig.GetCutoffRadius(_state.MapKind); + if (_state.Spectators.SafeRadius <= cutoff || _nextWaveIndex > DropWaveConfig.MaxRespawnWave) + { + TriggerRespawnCutoff(); + } + } + + private void TriggerRespawnCutoff() + { + _respawnCutoffReached = true; + EvictWaitingContenders(); + } + + private void EvictWaitingContenders() + { + for (int i = 0; i < _state.Contenders.Count; i++) + { + var c = _state.Contenders[i]; + if (c.Lifecycle == ContenderLifecycle.WaitingForRespawnWave) + { + c.Lifecycle = ContenderLifecycle.Eliminated; + } + } + } + + private void LaunchScheduledWave(int waveIndex, DropSurfaceQuery surfaceQuery) + { + _currentWaveIndex = waveIndex; + var gearSpecs = BuildEscalatingWaveGear(waveIndex, _state.Seed); + var gearTargets = new List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)>(gearSpecs.Count); + float safeR = MathF.Max(65f, _state.Spectators.SafeRadius * 0.68f); + + for (int i = 0; i < gearSpecs.Count; i++) + { + float ang = (i / (float)Math.Max(1, gearSpecs.Count)) * MathF.Tau + waveIndex * 0.55f + (float)_state.Rng.NextDouble() * 0.25f; + float r = (0.20f + 0.65f * (float)_state.Rng.NextDouble()) * safeR; + float rawX = MathF.Cos(ang) * r; + float rawZ = MathF.Sin(ang) * r; + var (cx, cz) = _state.FindClearDropPoint(rawX, rawZ, 3.5f); + gearTargets.Add((cx, cz, gearSpecs[i].Chassis, gearSpecs[i].Module)); + } + + bool allowRespawnsThisWave = waveIndex <= DropWaveConfig.MaxRespawnWave && + !_respawnCutoffReached && + _state.Spectators.SafeRadius > DropWaveConfig.GetCutoffRadius(_state.MapKind); + + var respawnQueue = new List(); + if (allowRespawnsThisWave) + { + for (int i = 0; i < _state.Contenders.Count; i++) + { + var c = _state.Contenders[i]; + if (c.Lifecycle == ContenderLifecycle.WaitingForRespawnWave && c.RespawnsRemaining > 0) + { + respawnQueue.Add(c); + } + } + } + + bool respawnsClosed = !allowRespawnsThisWave || waveIndex >= DropWaveConfig.MaxRespawnWave; + + EmitLifecycleEvent( + DropPodEventKind.WaveAnnounced, + waveIndex, + podId: 0, + podKind: OrbitalPodKind.Contender, + contenderId: -1, + 0f, 0f, 0f, + 0f, 0f, 0f, + Vector3.UnitY, + chassisId: null, + moduleId: null, + dropId: 0, + respawnsClosed: respawnsClosed, + gearCount: gearTargets.Count, + respawnCount: respawnQueue.Count); + + _state.Broadcast.EmitDropWave(_state.Time, waveIndex, gearTargets.Count, respawnQueue.Count, respawnsClosed); + + for (int i = 0; i < gearTargets.Count; i++) + { + var g = gearTargets[i]; + LaunchGearPod(waveIndex, g.X, g.Z, g.Chassis, g.Module, surfaceQuery); + } + + for (int i = 0; i < respawnQueue.Count; i++) + { + var c = respawnQueue[i]; + c.RespawnsRemaining = Math.Max(0, c.RespawnsRemaining - 1); + float ang = (i / (float)Math.Max(1, respawnQueue.Count)) * MathF.Tau + waveIndex * 0.9f; + float r = MathF.Min(safeR * 0.72f, MathF.Max(80f, safeR * 0.48f)); + var (rx, rz) = _state.FindClearDropPoint(MathF.Cos(ang) * r, MathF.Sin(ang) * r, 4.0f); + float yaw = MathF.Atan2(-rx, -rz); + c.ResetForRedrop(Catalog.CreateStarterBuggy(), rx, 0f, rz, yaw); + LaunchContenderPod(c, waveIndex, rx, rz, yaw, surfaceQuery, isRespawn: true); + _state.NotifyContenderRespawned(c); + } + } + + private static List<(ChassisSpec? Chassis, ModuleSpec? Module)> BuildEscalatingWaveGear(int waveIndex, int matchSeed) + { + var list = new List<(ChassisSpec?, ModuleSpec?)>(8); + ulong seed = (ulong)(uint)matchSeed; + switch (waveIndex) + { + case 1: + list.Add((Catalog.Hornet, null)); + list.Add((Catalog.Condor, null)); + list.Add((null, ProceduralWeaponGenerator.RollForWave(1, seed, 10).Module)); + list.Add((null, ProceduralWeaponGenerator.RollForWave(1, seed, 11).Module)); + list.Add((null, Catalog.Flak)); + list.Add((null, Catalog.TurboCore)); + list.Add((null, Catalog.CopperRad)); + list.Add((null, Catalog.TouringPlasma)); + break; + case 2: + list.Add((Catalog.Paladin, null)); + list.Add((Catalog.Manticore, null)); + list.Add((null, ProceduralWeaponGenerator.RollForWave(2, seed, 20).Module)); + list.Add((null, ProceduralWeaponGenerator.RollForWave(2, seed, 21).Module)); + list.Add((null, Catalog.ImperialAegisPd)); + list.Add((null, Catalog.NobleCore)); + list.Add((null, Catalog.GoldRadiator)); + list.Add((null, Catalog.GildedPlate)); + break; + default: + list.Add((Catalog.Bastion, null)); + list.Add((Catalog.Kestrel, null)); + list.Add((null, ProceduralWeaponGenerator.RollForWave(3, seed, 30).Module)); + list.Add((null, ProceduralWeaponGenerator.RollForWave(3, seed, 31).Module)); + list.Add((null, Catalog.ImperialAegisPd)); + list.Add((null, Catalog.NobleCore)); + break; + } + return list; + } + + private void HandlePodTouchdown( + OrbitalPod pod, + DropSurfaceSample touchSample, + DropSurfaceQuery surfaceQuery, + Action? onPodTouchedDown, + bool emitEvents) + { + if (emitEvents && !touchSample.IsBuildingRoof) + { + _state.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = pod.X, + Z = pod.Z, + Radius = pod.PodKind == OrbitalPodKind.Contender ? 3.4f : 2.1f, + Depth = 0.32f + }); + _state.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Scorch, + X = pod.X, + Z = pod.Z, + Radius = pod.PodKind == OrbitalPodKind.Contender ? 4.2f : 2.6f + }); + } + + // Re-sample ground height after crater stamp + float postCraterSurfaceY = touchSample.IsBuildingRoof + ? touchSample.SurfaceY + : _state.Terrain.SampleHeight(pod.X, pod.Z); + var postSample = touchSample with { SurfaceY = postCraterSurfaceY }; + + if (pod.PodKind == OrbitalPodKind.Contender && + pod.ContenderId >= 0 && + pod.ContenderId < _state.Contenders.Count) + { + var c = _state.Contenders[pod.ContenderId]; + c.ActivePodId = null; + c.Lifecycle = ContenderLifecycle.Active; + c.X = pod.X; + c.Z = pod.Z; + c.Yaw = pod.Yaw; + + // Orient chassis up-vector toward surface normal (blended 0.85f, clamped <= 38 deg) + var spec = c.Grid.Spec; + float physHalfH = spec.IsWalker ? spec.HalfHeight * (spec.Plane == GridPlane.Dorsal ? 0.62f : 0.72f) : spec.HalfHeight; + Quaternion yawQ = Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw); + Vector3 upNorm = postSample.Normal.LengthSquared() > 1e-4f ? Vector3.Normalize(postSample.Normal) : Vector3.UnitY; + Vector3 desiredUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, upNorm, 0.85f)); + const float maxTiltRad = MathF.PI * 38f / 180f; + float tiltAngle = MathF.Acos(Math.Clamp(desiredUp.Y, -1f, 1f)); + if (tiltAngle > maxTiltRad) + { + Vector3 horiz = new(desiredUp.X, 0f, desiredUp.Z); + float hLen = horiz.Length(); + desiredUp = hLen > 1e-4f + ? Vector3.UnitY * MathF.Cos(maxTiltRad) + (horiz / hLen) * MathF.Sin(maxTiltRad) + : Vector3.UnitY; + } + + Quaternion rot = AlignUp(yawQ, desiredUp); + + // Exact zero-penetration corner clearance + float maxReqCenterY = postCraterSurfaceY + physHalfH; + Span localCorners = stackalloc Vector3[4] + { + new Vector3(-spec.HalfWidth, -physHalfH, -spec.HalfLength), + new Vector3( spec.HalfWidth, -physHalfH, -spec.HalfLength), + new Vector3(-spec.HalfWidth, -physHalfH, spec.HalfLength), + new Vector3( spec.HalfWidth, -physHalfH, spec.HalfLength) + }; + for (int k = 0; k < 4; k++) + { + Vector3 r = Vector3.Transform(localCorners[k], rot); + float cornerSurfY; + if (postSample.IsBuildingRoof) + { + var cs = surfaceQuery(pod.X + r.X, pod.Z + r.Z, 0.25f, pod.Y + 6f); + cornerSurfY = cs.IsBuildingRoof ? cs.SurfaceY : _state.Terrain.SampleHeight(pod.X + r.X, pod.Z + r.Z); + } + else + { + cornerSurfY = _state.Terrain.SampleHeight(pod.X + r.X, pod.Z + r.Z); + } + float reqCenter = cornerSurfY - r.Y; + if (reqCenter > maxReqCenterY) + { + maxReqCenterY = reqCenter; + } + } + + float spawnY = maxReqCenterY + 0.04f; + if (spec.IsVtol) + { + spawnY += Math.Clamp(c.TargetHoverAltAgl, MatchRules.VtolMinClearanceAgl, MathF.Max(MatchRules.VtolMinClearanceAgl, spec.HoverMaxAltitudeM)); + } + + c.Y = spawnY; + c.CurrRotX = rot.X; + c.CurrRotY = rot.Y; + c.CurrRotZ = rot.Z; + c.CurrRotW = rot.W; + c.VelX = 0f; + c.VelY = -MathF.Min(pod.TouchdownSpeed, 2.6f); + c.VelZ = 0f; + c.Speed = 0f; + c.HasTouchdownPose = true; + c.TouchdownOnRoof = pod.TouchdownOnRoof; + c.SnapPreviousPose(); + c.ResetAimTracker(c.Yaw); + + _state.NotifyContenderPodTouchedDown(c); + } + else + { + GroundDrop drop = pod.Chassis is not null + ? _state.SpawnChassisDrop(pod.X, pod.Z, pod.Chassis) + : _state.SpawnModuleDrop(pod.X, pod.Z, pod.Module!); + pod.GroundDropId = drop.Id; + } + + onPodTouchedDown?.Invoke(pod, postSample); + + if (emitEvents) + { + EmitLifecycleEvent( + DropPodEventKind.PodTouchdownBlowPetals, + pod.WaveIndex, + pod.PodId, + pod.PodKind, + pod.ContenderId, + pod.X, postCraterSurfaceY, pod.Z, + pod.VelX, pod.VelY, pod.VelZ, + postSample.Normal, + pod.Chassis?.Id, + pod.Module?.Id, + pod.GroundDropId, + _respawnCutoffReached, + gearCount: 0, + respawnCount: 0); + } + } + + private float ResolveGroundSurfaceY(float x, float z, float radius, DropSurfaceQuery surfaceQuery) + { + float terrainY = _state.Terrain.SampleHeight(x, z); + var sample = surfaceQuery(x, z, radius, terrainY + 250f); + return sample.IsBuildingRoof ? MathF.Max(terrainY, sample.SurfaceY) : terrainY; + } + + private OrbitalPod? FindPodById(int podId) + { + for (int i = 0; i < _activePods.Count; i++) + { + if (_activePods[i].PodId == podId) + { + return _activePods[i]; + } + } + return null; + } + + private OrbitalPod? FindContenderPod(int contenderId) + { + for (int i = 0; i < _activePods.Count; i++) + { + if (_activePods[i].PodKind == OrbitalPodKind.Contender && _activePods[i].ContenderId == contenderId) + { + return _activePods[i]; + } + } + return null; + } + + public OrbitalPod SynthesizeReplicatedContenderPod( + int contenderId, + float x, + float y, + float z, + float velX, + float velY, + float velZ, + Quaternion rot, + float yaw, + OrbitalPodPhase phase, + float lastAgl) + { + var existing = FindContenderPod(contenderId); + if (existing is not null) + { + return existing; + } + + int podId = _nextPodId++; + var pod = new OrbitalPod + { + PodId = podId, + PodKind = OrbitalPodKind.Contender, + Phase = phase, + WaveIndex = _currentWaveIndex, + ContenderId = contenderId, + AllowFlatRoofLanding = false, + TargetX = x, + TargetZ = z, + X = x, + Y = y, + Z = z, + VelX = velX, + VelY = velY, + VelZ = velZ, + Yaw = yaw, + CurrRotX = rot.X, + CurrRotY = rot.Y, + CurrRotZ = rot.Z, + CurrRotW = rot.W, + LookForwardX = MathF.Sin(yaw), + LookForwardZ = MathF.Cos(yaw), + LastAgl = lastAgl + }; + pod.SnapPreviousPose(); + _activePods.Add(pod); + if (contenderId >= 0 && contenderId < _state.Contenders.Count) + { + _state.Contenders[contenderId].ActivePodId = podId; + } + return pod; + } + + private void EmitLifecycleEvent( + DropPodEventKind kind, + int waveIndex, + int podId, + OrbitalPodKind podKind, + int contenderId, + float x, + float y, + float z, + float velX, + float velY, + float velZ, + Vector3 normal, + string? chassisId, + string? moduleId, + int dropId, + bool respawnsClosed, + int gearCount, + int respawnCount) + { + var ev = new DropPodLifecycleEvent( + AllocatePodEventId(), + kind, + waveIndex, + podId, + podKind, + contenderId, + x, y, z, + velX, velY, velZ, + normal, + chassisId, + moduleId, + dropId, + respawnsClosed, + gearCount, + respawnCount); + _state.PodEvents.Add(ev); + if (_state.PodEvents.Count > 2048) + { + _state.PodEvents.RemoveRange(0, _state.PodEvents.Count - 2048); + } + } + + public void ApplyReplicatedWaveState(int currentWaveIndex, int nextWaveIndex, bool respawnCutoffReached) + { + _currentWaveIndex = currentWaveIndex; + _nextWaveIndex = nextWaveIndex; + _respawnCutoffReached = respawnCutoffReached; + } + + public void ApplyReplicatedActivePods(IEnumerable pods, DropSurfaceQuery? surfaceQuery = null) + { + surfaceQuery ??= _state.DefaultDropSurfaceQuery; + _activePods.Clear(); + foreach (var dto in pods) + { + var podKind = (OrbitalPodKind)dto.PodKind; + var preset = OrbitalDropKinematics.GetPreset(podKind); + float surfY = ResolveSurfaceUnderPod(dto.X, dto.Y, dto.Z, preset.PodFootRadius, surfaceQuery); + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, dto.Yaw); + bool allowFlatRoof = false; + if (podKind == OrbitalPodKind.Contender && dto.ContenderId >= 0 && dto.ContenderId < _state.Contenders.Count) + { + var c = _state.Contenders[dto.ContenderId]; + c.ActivePodId = dto.PodId; + allowFlatRoof = c.IsHuman && _state.MapKind == ArenaMapKind.Sion; + } + var pod = new OrbitalPod + { + PodId = dto.PodId, + PodKind = podKind, + Phase = (OrbitalPodPhase)dto.Phase, + WaveIndex = dto.WaveIndex, + ContenderId = dto.ContenderId, + Chassis = dto.ChassisId is not null && Catalog.ChassisById.TryGetValue(dto.ChassisId, out var cs) ? cs : null, + Module = Catalog.TryGetModule(dto.ModuleId, out var ms) ? ms : null, + AllowFlatRoofLanding = allowFlatRoof, + TargetX = dto.X, + TargetZ = dto.Z, + X = dto.X, + Y = dto.Y, + Z = dto.Z, + VelX = dto.VelX, + VelY = dto.VelY, + VelZ = dto.VelZ, + Yaw = dto.Yaw, + CurrRotX = q.X, + CurrRotY = q.Y, + CurrRotZ = q.Z, + CurrRotW = q.W, + LookForwardX = MathF.Sin(dto.Yaw), + LookForwardZ = MathF.Cos(dto.Yaw), + LastAgl = MathF.Max(0f, dto.Y - surfY) + }; + pod.SnapPreviousPose(); + _activePods.Add(pod); + if (dto.PodId >= _nextPodId) _nextPodId = dto.PodId + 1; + } + } + + public void ApplyReplicatedDropPodEvent(DropPodEvent ev, DropSurfaceQuery? surfaceQuery = null) + { + surfaceQuery ??= _state.DefaultDropSurfaceQuery; + var kind = (DropPodEventKind)ev.Kind; + switch (kind) + { + case DropPodEventKind.WaveAnnounced: + _currentWaveIndex = ev.WaveIndex; + _nextWaveIndex = Math.Min(DropWaveConfig.WaveTimes.Length, ev.WaveIndex + 1); + _respawnCutoffReached = ev.RespawnsClosed; + break; + case DropPodEventKind.PodLaunched: + { + var podKind = (OrbitalPodKind)ev.PodKind; + var preset = OrbitalDropKinematics.GetPreset(podKind); + float surfY = ResolveSurfaceUnderPod(ev.X, ev.Y, ev.Z, preset.PodFootRadius, surfaceQuery); + float yaw = 0f; + bool allowFlatRoof = false; + if (ev.ContenderId >= 0 && ev.ContenderId < _state.Contenders.Count) + { + var c = _state.Contenders[ev.ContenderId]; + c.Lifecycle = ContenderLifecycle.Deploying; + c.ActivePodId = ev.PodId; + yaw = c.Yaw; + allowFlatRoof = c.IsHuman && _state.MapKind == ArenaMapKind.Sion; + } + else + { + yaw = (float)((ev.PodId * 1.17f) % MathF.Tau); + } + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw); + + var existing = FindPodById(ev.PodId); + if (existing is null && podKind == OrbitalPodKind.Contender && ev.ContenderId >= 0) + { + existing = FindContenderPod(ev.ContenderId); + if (existing is not null) + { + existing.PodId = ev.PodId; + if (ev.PodId >= _nextPodId) _nextPodId = ev.PodId + 1; + if (ev.ContenderId < _state.Contenders.Count) + { + _state.Contenders[ev.ContenderId].ActivePodId = ev.PodId; + } + } + } + if (existing is null) + { + var pod = new OrbitalPod + { + PodId = ev.PodId, + PodKind = podKind, + Phase = OrbitalPodPhase.Freefall, + WaveIndex = ev.WaveIndex, + ContenderId = ev.ContenderId, + Chassis = ev.ChassisId is not null && Catalog.ChassisById.TryGetValue(ev.ChassisId, out var cs) ? cs : null, + Module = Catalog.TryGetModule(ev.ModuleId, out var ms) ? ms : null, + AllowFlatRoofLanding = allowFlatRoof, + TargetX = ev.X, + TargetZ = ev.Z, + X = ev.X, + Y = ev.Y, + Z = ev.Z, + VelX = ev.VelX, + VelY = ev.VelY, + VelZ = ev.VelZ, + Yaw = yaw, + CurrRotX = q.X, + CurrRotY = q.Y, + CurrRotZ = q.Z, + CurrRotW = q.W, + LookForwardX = MathF.Sin(yaw), + LookForwardZ = MathF.Cos(yaw), + LastAgl = MathF.Max(0f, ev.Y - surfY) + }; + pod.SnapPreviousPose(); + _activePods.Add(pod); + } + else + { + existing.X = ev.X; + existing.Y = ev.Y; + existing.Z = ev.Z; + existing.VelX = ev.VelX; + existing.VelY = ev.VelY; + existing.VelZ = ev.VelZ; + existing.LastAgl = MathF.Max(0f, ev.Y - surfY); + } + break; + } + case DropPodEventKind.PodRetroBurnStart: + { + var pod = FindPodById(ev.PodId); + if (pod is null && (OrbitalPodKind)ev.PodKind == OrbitalPodKind.Contender && ev.ContenderId >= 0) + { + pod = FindContenderPod(ev.ContenderId); + if (pod is not null) + { + pod.PodId = ev.PodId; + if (ev.PodId >= _nextPodId) _nextPodId = ev.PodId + 1; + if (ev.ContenderId < _state.Contenders.Count) + { + _state.Contenders[ev.ContenderId].ActivePodId = ev.PodId; + } + } + } + if (pod is not null) + { + var preset = OrbitalDropKinematics.GetPreset(pod.PodKind); + float surfY = ResolveSurfaceUnderPod(ev.X, ev.Y, ev.Z, preset.PodFootRadius, surfaceQuery); + pod.Phase = OrbitalPodPhase.RetroBurn; + pod.X = ev.X; + pod.Y = ev.Y; + pod.Z = ev.Z; + pod.VelX = ev.VelX; + pod.VelY = ev.VelY; + pod.VelZ = ev.VelZ; + pod.LastAgl = MathF.Max(0f, ev.Y - surfY); + } + break; + } + case DropPodEventKind.PodTouchdownBlowPetals: + { + for (int i = _activePods.Count - 1; i >= 0; i--) + { + if (_activePods[i].PodId == ev.PodId) + { + _activePods.RemoveAt(i); + } + } + if (ev.ContenderId >= 0 && ev.ContenderId < _state.Contenders.Count) + { + var c = _state.Contenders[ev.ContenderId]; + c.Lifecycle = ContenderLifecycle.Active; + c.ActivePodId = null; + } + break; + } + case DropPodEventKind.PodCancelled: + { + for (int i = _activePods.Count - 1; i >= 0; i--) + { + if (_activePods[i].PodId == ev.PodId) + { + _activePods.RemoveAt(i); + } + } + if (ev.ContenderId >= 0 && ev.ContenderId < _state.Contenders.Count) + { + var c = _state.Contenders[ev.ContenderId]; + if (c.ActivePodId == ev.PodId) + { + c.ActivePodId = null; + } + } + break; + } + } + + _state.PodEvents.Add(new DropPodLifecycleEvent( + ev.EventId > 0 ? ev.EventId : AllocatePodEventId(), + kind, + ev.WaveIndex, + ev.PodId, + (OrbitalPodKind)ev.PodKind, + ev.ContenderId, + ev.X, ev.Y, ev.Z, + ev.VelX, ev.VelY, ev.VelZ, + new Vector3(ev.NormalX, ev.NormalY, ev.NormalZ), + ev.ChassisId, + ev.ModuleId, + ev.DropId, + ev.RespawnsClosed, + ev.GearCount, + ev.RespawnCount)); + if (_state.PodEvents.Count > 2048) + { + _state.PodEvents.RemoveRange(0, _state.PodEvents.Count - 2048); + } + } + + private float ResolveSurfaceUnderPod(float x, float y, float z, float radius, DropSurfaceQuery surfaceQuery) + { + float terrainY = _state.Terrain.SampleHeight(x, z); + var sample = surfaceQuery(x, z, radius, y + 1.0f); + return sample.IsBuildingRoof ? MathF.Max(terrainY, sample.SurfaceY) : terrainY; + } + + private static Quaternion AlignUp(Quaternion baseYawQ, Vector3 targetUp) + { + Vector3 currentUp = Vector3.Transform(Vector3.UnitY, baseYawQ); + float dot = Math.Clamp(Vector3.Dot(currentUp, targetUp), -1f, 1f); + if (dot > 0.9999f) return baseYawQ; + if (dot < -0.9999f) + { + Vector3 ortho = MathF.Abs(currentUp.X) < 0.9f ? Vector3.UnitX : Vector3.UnitZ; + return Quaternion.Normalize(Quaternion.CreateFromAxisAngle(Vector3.Normalize(Vector3.Cross(currentUp, ortho)), MathF.PI) * baseYawQ); + } + Vector3 axis = Vector3.Normalize(Vector3.Cross(currentUp, targetUp)); + float angle = MathF.Acos(dot); + return Quaternion.Normalize(Quaternion.CreateFromAxisAngle(axis, angle) * baseYawQ); + } + } +} diff --git a/src/RustToDust.Core/OrdnanceGraph.cs b/src/RustToDust.Core/OrdnanceGraph.cs new file mode 100644 index 0000000..5ddb5d4 --- /dev/null +++ b/src/RustToDust.Core/OrdnanceGraph.cs @@ -0,0 +1,440 @@ +using System; +using System.Collections.Generic; + +namespace RustToDust.Core +{ + public enum ManufacturerId : byte + { + ScrapFrontier = 0, + KorrathiIronworks = 1, + AuralianOptics = 2, + VexNineCollective = 3, + ThalassanForge = 4 + } + + public enum WeaponArchetypeKind : byte + { + // ScrapFrontier (0..3) + RotaryAutocannon = 0, + FlakBurstCannon = 1, + SabotSlugCannon = 2, + DumbRocketPod = 3, + + // KorrathiIronworks (4..7) + SabotRocketSled = 4, + MirvMineBlanket = 5, + ClusterSiegeMortar = 6, + GyrojetBunkerBuster = 7, + + // AuralianOptics (8..11) + LoiteringLaserDrone = 8, + RefractingPrismLance = 9, + PulsedBeamSweeper = 10, + ThermalOverloadOrb = 11, + + // VexNineCollective (12..15) + HomingSwarmPod = 12, + AirburstProximitySwarm = 13, + SmartSpiderMineTrap = 14, + PointDefenseWeb = 15, + + // ThalassanForge (16..19) + HypervelocityGaussRail = 16, + PlasmaPoolMortar = 17, + ArcDischargeLance = 18, + RailPlasmaBeam = 19 + } + + public enum OrdnanceAudioClass : byte + { + CannonLight = 0, + CannonHeavy = 1, + RocketSalvo = 2, + LaserHeavy = 3, + GaussRail = 4, + PlasmaPpc = 5 + } + + public enum OrdnanceMotion : byte + { + HitscanBeam = 0, + Ballistic = 1, + RocketBoosted = 2, + HomingMissile = 3, + LoiterOrbit = 4, + StationaryMine = 5 + } + + public enum OrdnanceTriggerKind : byte + { + Impact = 0, + Timeout = 1, + Altitude = 2, + Proximity = 3, + StageElapsed = 4, + Apex = 5 + } + + public enum OrdnanceTriggerAction : byte + { + Detonate = 0, + Split = 1, + Transition = 2, + Fizzle = 3 + } + + public enum OrdnanceVisualShape : byte + { + None = 0, + Bolt = 1, + Rocket = 2, + SabotCarrier = 3, + Drone = 4, + Mine = 5, + Pool = 6 + } + + public sealed class OrdnanceTriggerRule + { + public OrdnanceTriggerKind Kind { get; init; } + public float Threshold { get; init; } + public float MinAge { get; init; } + public OrdnanceTriggerAction Action { get; init; } + public OrdnanceNodeDef? ChildNode { get; init; } + public int SplitCount { get; init; } = 1; + public float SplitConeDeg { get; init; } = 30f; + public bool EjectSabotVfx { get; init; } + } + + public sealed class OrdnanceWhileAliveDef + { + public float Interval { get; init; } = 0.5f; + public int MaxPulses { get; init; } = 8; + public float TriggerScanRadius { get; init; } = 95f; + public bool RequireHostileTarget { get; init; } = true; + public float TargetConeDeg { get; init; } = 75f; + public OrdnanceNodeDef? ChildNode { get; init; } + public float RadialHeat { get; init; } + public float RadialDamage { get; init; } + public float RadialRadius { get; init; } + } + + public sealed class OrdnanceNodeDef + { + public const int MaxAllowedDepth = 4; + public const int MaxShotSubSpawnBudget = 16; + + public byte DefIndex { get; internal set; } + public byte Depth { get; internal set; } + + public OrdnanceMotion Motion { get; init; } = OrdnanceMotion.HitscanBeam; + public float InitialSpeed { get; init; } = 220f; + public float LaunchPitchBiasDeg { get; init; } + public float GravityScale { get; init; } = 1f; + public float ThrustAccel { get; init; } + public float BurnTime { get; init; } + public float MaxSpeed { get; init; } + public float TurnRateRad { get; init; } + public float SeekerConeDeg { get; init; } = 60f; + public float SeekerRange { get; init; } = 220f; + public float LoiterAltitudeAgl { get; init; } = 35f; + public float LoiterOrbitRadius { get; init; } = 15f; + public float LoiterOrbitSpeedRad { get; init; } = 1.45f; + public float ArmDelay { get; init; } + public float ProximityRadius { get; init; } + public bool ProximityIgnoreOwner { get; init; } = true; + public bool IsThermalPool { get; init; } + public float InterceptHp { get; init; } + public float MaxLifetime { get; init; } = 5f; + public float Range { get; init; } = 200f; + + public float DirectDamage { get; init; } + public float SplashDamage { get; init; } + public float SplashRadius { get; init; } + public float HeatTransfer { get; init; } + public float CraterRadius { get; init; } + public float CraterDepth { get; init; } + public float ScorchRadius { get; init; } + public bool CraterFirstBurstOnly { get; init; } + public byte MaxPenetrations { get; init; } + public float PenetrationDamageDecay { get; init; } = 0.72f; + public bool IsAirburst { get; init; } + + public OrdnanceWhileAliveDef? WhileAlive { get; init; } + public OrdnanceTriggerRule[] Triggers { get; init; } = Array.Empty(); + + public WeaponVisualClass VisualClass { get; init; } = WeaponVisualClass.KineticLight; + public OrdnanceAudioClass AudioClass { get; init; } = OrdnanceAudioClass.CannonLight; + public uint ColorRgba { get; init; } = 0xFFE888FFu; + public float TracerTtl { get; init; } = 0.10f; + public OrdnanceVisualShape VisualShape { get; init; } = OrdnanceVisualShape.Bolt; + } + + public static class OrdnanceGraphValidator + { + public static OrdnanceNodeDef[] ValidateAndFlatten(OrdnanceNodeDef root) + { + ArgumentNullException.ThrowIfNull(root); + + var activeStack = new HashSet(ReferenceEqualityComparer.Instance); + var visited = new List(8); + var visitedSet = new Dictionary(ReferenceEqualityComparer.Instance); + + int peakConcurrent = ValidateNode(root, depth: 0, activeStack, visited, visitedSet); + if (peakConcurrent > OrdnanceNodeDef.MaxShotSubSpawnBudget) + { + throw new InvalidOperationException( + $"OrdnanceNodeDef sub-spawn budget {peakConcurrent} exceeds MaxShotSubSpawnBudget {OrdnanceNodeDef.MaxShotSubSpawnBudget}."); + } + + if (visited.Count > 32) + { + throw new InvalidOperationException($"OrdnanceNodeDef tree exceeds 32 flattened nodes (got {visited.Count})."); + } + + for (int i = 0; i < visited.Count; i++) + { + visited[i].DefIndex = (byte)i; + visited[i].Depth = visitedSet[visited[i]]; + } + + return visited.ToArray(); + } + + private static int ValidateNode( + OrdnanceNodeDef node, + int depth, + HashSet activeStack, + List visited, + Dictionary visitedSet) + { + if (depth >= OrdnanceNodeDef.MaxAllowedDepth) + { + throw new InvalidOperationException( + $"OrdnanceNodeDef depth {depth} violates MaxAllowedDepth ({OrdnanceNodeDef.MaxAllowedDepth}, valid 0..{OrdnanceNodeDef.MaxAllowedDepth - 1})."); + } + + if (!activeStack.Add(node)) + { + throw new InvalidOperationException("Cyclic OrdnanceNodeDef graph detected."); + } + + ValidateFiniteFields(node); + + if (!visitedSet.TryGetValue(node, out byte prevDepth)) + { + visitedSet[node] = (byte)depth; + visited.Add(node); + } + else if (depth > prevDepth) + { + visitedSet[node] = (byte)depth; + } + + int whileAliveSubSpawns = 0; + int maxTriggerSubSpawns = 0; + const long BudgetCapSentinel = OrdnanceNodeDef.MaxShotSubSpawnBudget + 1L; + + if (node.WhileAlive is { } wa) + { + if (!float.IsFinite(wa.Interval) || wa.Interval <= 0f || + !float.IsFinite(wa.TriggerScanRadius) || wa.TriggerScanRadius < 0f || + !float.IsFinite(wa.TargetConeDeg) || wa.TargetConeDeg < 0f || + !float.IsFinite(wa.RadialDamage) || wa.RadialDamage < 0f || + !float.IsFinite(wa.RadialHeat) || wa.RadialHeat < 0f || + !float.IsFinite(wa.RadialRadius) || wa.RadialRadius < 0f || + wa.MaxPulses < 0) + { + throw new InvalidOperationException("OrdnanceWhileAliveDef contains invalid non-finite or negative values."); + } + + if (wa.ChildNode is not null) + { + int childBudget = ValidateNode(wa.ChildNode, depth + 1, activeStack, visited, visitedSet); + if (childBudget > 0) + { + int pulses = Math.Clamp(wa.MaxPulses, 1, 32); + whileAliveSubSpawns = (int)Math.Min(BudgetCapSentinel, (long)pulses * childBudget); + } + } + } + + if (node.Triggers is not null) + { + for (int i = 0; i < node.Triggers.Length; i++) + { + var tr = node.Triggers[i]; + if (!float.IsFinite(tr.Threshold) || tr.Threshold < 0f || + !float.IsFinite(tr.MinAge) || tr.MinAge < 0f || + !float.IsFinite(tr.SplitConeDeg) || tr.SplitConeDeg < 0f) + { + throw new InvalidOperationException("OrdnanceTriggerRule contains non-finite or negative values."); + } + + if (tr.Action == OrdnanceTriggerAction.Split) + { + if (tr.SplitCount < 1 || tr.SplitCount > OrdnanceNodeDef.MaxShotSubSpawnBudget) + { + throw new InvalidOperationException( + $"OrdnanceTriggerRule.SplitCount={tr.SplitCount} must be in [1..{OrdnanceNodeDef.MaxShotSubSpawnBudget}]."); + } + if (tr.ChildNode is null) + { + throw new InvalidOperationException("Split trigger requires non-null ChildNode."); + } + int childBudget = ValidateNode(tr.ChildNode, depth + 1, activeStack, visited, visitedSet); + long branchBudget = (long)tr.SplitCount * Math.Max(1, childBudget); + maxTriggerSubSpawns = Math.Max(maxTriggerSubSpawns, (int)Math.Min(BudgetCapSentinel, branchBudget)); + } + else if (tr.Action == OrdnanceTriggerAction.Transition) + { + if (tr.ChildNode is null) + { + throw new InvalidOperationException("Transition trigger requires non-null ChildNode."); + } + int childBudget = ValidateNode(tr.ChildNode, depth + 1, activeStack, visited, visitedSet); + maxTriggerSubSpawns = Math.Max(maxTriggerSubSpawns, (int)Math.Min(BudgetCapSentinel, (long)Math.Max(1, childBudget))); + } + } + } + + int totalSubSpawns = (int)Math.Min(BudgetCapSentinel, (long)whileAliveSubSpawns + maxTriggerSubSpawns); + + activeStack.Remove(node); + return node.Motion == OrdnanceMotion.HitscanBeam + ? totalSubSpawns + : Math.Max(1, totalSubSpawns); + } + + private static void ValidateFiniteFields(OrdnanceNodeDef n) + { + bool valid = + float.IsFinite(n.InitialSpeed) && n.InitialSpeed >= 0f && + float.IsFinite(n.LaunchPitchBiasDeg) && + float.IsFinite(n.GravityScale) && + float.IsFinite(n.ThrustAccel) && n.ThrustAccel >= 0f && + float.IsFinite(n.BurnTime) && n.BurnTime >= 0f && + float.IsFinite(n.MaxSpeed) && n.MaxSpeed >= 0f && + float.IsFinite(n.TurnRateRad) && n.TurnRateRad >= 0f && + float.IsFinite(n.SeekerConeDeg) && + float.IsFinite(n.SeekerRange) && n.SeekerRange >= 0f && + float.IsFinite(n.LoiterAltitudeAgl) && n.LoiterAltitudeAgl >= 0f && + float.IsFinite(n.LoiterOrbitRadius) && n.LoiterOrbitRadius >= 0f && + float.IsFinite(n.LoiterOrbitSpeedRad) && + float.IsFinite(n.ArmDelay) && n.ArmDelay >= 0f && + float.IsFinite(n.ProximityRadius) && n.ProximityRadius >= 0f && + float.IsFinite(n.InterceptHp) && n.InterceptHp >= 0f && + float.IsFinite(n.MaxLifetime) && n.MaxLifetime >= 0f && + float.IsFinite(n.Range) && n.Range >= 0f && + float.IsFinite(n.DirectDamage) && n.DirectDamage >= 0f && + float.IsFinite(n.SplashDamage) && n.SplashDamage >= 0f && + float.IsFinite(n.SplashRadius) && n.SplashRadius >= 0f && + float.IsFinite(n.HeatTransfer) && n.HeatTransfer >= 0f && + float.IsFinite(n.CraterRadius) && n.CraterRadius >= 0f && + float.IsFinite(n.CraterDepth) && n.CraterDepth >= 0f && + float.IsFinite(n.ScorchRadius) && n.ScorchRadius >= 0f && + float.IsFinite(n.PenetrationDamageDecay) && n.PenetrationDamageDecay >= 0f && + float.IsFinite(n.TracerTtl) && n.TracerTtl >= 0f; + + if (!valid) + { + throw new InvalidOperationException("OrdnanceNodeDef contains non-finite or negative scalar field."); + } + } + } + + public static class OrdnanceCatalogMapper + { + private static readonly Dictionary _legacyById = new(StringComparer.OrdinalIgnoreCase); + + static OrdnanceCatalogMapper() + { + RegisterLegacy(Catalog.Mg762, WeaponVisualClass.KineticLight, OrdnanceAudioClass.CannonLight, 0xFFE888FFu, 0.09f); + RegisterLegacy(Catalog.Autocannon, WeaponVisualClass.Autocannon, OrdnanceAudioClass.CannonHeavy, 0xFF9933FFu, 0.10f); + RegisterLegacy(Catalog.Flak, WeaponVisualClass.Explosive, OrdnanceAudioClass.CannonHeavy, 0xFF6622FFu, 0.12f, + craterRadius: 2.0f, craterDepth: 0.35f, craterFirstBurstOnly: true); + RegisterLegacy(Catalog.PointDefenseFlak, WeaponVisualClass.KineticLight, OrdnanceAudioClass.CannonLight, 0xFF8833FFu, 0.09f, + isAirburst: true); + RegisterLegacy(Catalog.Recoilless, WeaponVisualClass.Explosive, OrdnanceAudioClass.CannonHeavy, 0xFF6622FFu, 0.12f, + craterRadius: 4.2f, craterDepth: 1.05f, scorchRadius: 4.5f); + RegisterLegacy(Catalog.GildedLance, WeaponVisualClass.ThermalBeam, OrdnanceAudioClass.LaserHeavy, 0xFFD966FFu, 0.13f); + RegisterLegacy(Catalog.TouringPlasma, WeaponVisualClass.ThermalBeam, OrdnanceAudioClass.PlasmaPpc, 0x5CE6FFFFu, 0.13f); + RegisterLegacy(Catalog.ImperialAegisPd, WeaponVisualClass.ThermalBeam, OrdnanceAudioClass.LaserHeavy, 0x5CE6FFFFu, 0.13f); + } + + private static void RegisterLegacy( + ModuleSpec spec, + WeaponVisualClass visual, + OrdnanceAudioClass audio, + uint colorRgba, + float tracerTtl, + float craterRadius = 0f, + float craterDepth = 0f, + float scorchRadius = 0f, + bool craterFirstBurstOnly = false, + bool isAirburst = false) + { + var root = BuildHitscanFromSpec(spec, visual, audio, colorRgba, tracerTtl, craterRadius, craterDepth, scorchRadius, craterFirstBurstOnly, isAirburst); + OrdnanceGraphValidator.ValidateAndFlatten(root); + _legacyById[spec.Id] = root; + } + + public static OrdnanceNodeDef ResolveRoot(ModuleSpec spec) + { + if (spec.Procedural is { } proc) + { + return proc.RootNode; + } + + if (_legacyById.TryGetValue(spec.Id, out var cached)) + { + return cached; + } + + var visual = MatchState.ClassifyWeaponVisual(spec); + var fallback = BuildHitscanFromSpec(spec, visual, OrdnanceAudioClass.CannonLight, 0xFFE888FFu, 0.10f); + OrdnanceGraphValidator.ValidateAndFlatten(fallback); + return fallback; + } + + private static OrdnanceNodeDef BuildHitscanFromSpec( + ModuleSpec spec, + WeaponVisualClass visual, + OrdnanceAudioClass audio, + uint colorRgba, + float tracerTtl, + float craterRadius = 0f, + float craterDepth = 0f, + float scorchRadius = 0f, + bool craterFirstBurstOnly = false, + bool isAirburst = false) + { + return new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = MathF.Max(100f, spec.ProjectileSpeed), + Range = MathF.Max(5f, spec.WeaponRange), + DirectDamage = spec.WeaponDamage, + HeatTransfer = spec.HeatOutput * 0.25f, + CraterRadius = craterRadius, + CraterDepth = craterDepth, + ScorchRadius = scorchRadius, + CraterFirstBurstOnly = craterFirstBurstOnly, + IsAirburst = isAirburst, + VisualClass = visual, + AudioClass = audio, + ColorRgba = colorRgba, + TracerTtl = tracerTtl, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] + { + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.Impact, + Action = OrdnanceTriggerAction.Detonate + } + } + }; + } + } +} diff --git a/src/RustToDust.Core/ProceduralWeapons.cs b/src/RustToDust.Core/ProceduralWeapons.cs new file mode 100644 index 0000000..4809e57 --- /dev/null +++ b/src/RustToDust.Core/ProceduralWeapons.cs @@ -0,0 +1,1895 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Globalization; +using MessagePack; + +namespace RustToDust.Core +{ + [MessagePackObject] + public readonly record struct ProceduralWeaponKey( + [property: Key(0)] ulong Seed, + [property: Key(1)] byte Manufacturer, + [property: Key(2)] byte Archetype, + [property: Key(3)] byte Tier, + [property: Key(4)] byte Flags); + + public readonly record struct ModularWeaponAssembly( + byte ReceiverIdx, + byte BarrelIdx, + byte FeedIdx, + byte MuzzleIdx, + ManufacturerId Palette, + float VisualScale, + bool IsWideArc) + { + public string ReceiverPartName => ProceduralWeaponParts.ReceiverNames[ReceiverIdx & 3]; + public string BarrelPartName => ProceduralWeaponParts.BarrelNames[BarrelIdx & 3]; + public string FeedPartName => ProceduralWeaponParts.FeedNames[FeedIdx & 3]; + public string MuzzlePartName => ProceduralWeaponParts.MuzzleNames[MuzzleIdx & 3]; + } + + public static class ProceduralWeaponParts + { + public static readonly string[] ReceiverNames = + { + "rx_salvage_frame", + "rx_korrathi_cradle", + "rx_auralian_prism", + "rx_vex_pod_rack" + }; + + public static readonly string[] BarrelNames = + { + "brl_autocannon", + "brl_sabot_rail", + "brl_prism_lance", + "brl_missile_tube" + }; + + public static readonly string[] FeedNames = + { + "fd_belt_drum", + "fd_rotary_loader", + "fd_capacitor_bank", + "fd_swarm_magazine" + }; + + public static readonly string[] MuzzleNames = + { + "mz_slotted_brake", + "mz_mirv_warhead", + "mz_loiter_aero_fin", + "mz_plasma_diffuser" + }; + } + + public sealed class ProceduralWeaponSpec + { + public required ProceduralWeaponKey Key { get; init; } + public required ManufacturerId Manufacturer { get; init; } + public required WeaponArchetypeKind Archetype { get; init; } + public required byte WaveTier { get; init; } + public required string DisplayName { get; init; } + public required string ManufacturerLabel { get; init; } + public required string SummaryLine1 { get; init; } + public required string SummaryLine2 { get; init; } + public required WeaponVisualClass VisualClass { get; init; } + public required OrdnanceAudioClass AudioClass { get; init; } + public required ModularWeaponAssembly Assembly { get; init; } + public required OrdnanceNodeDef RootNode { get; init; } + public required OrdnanceNodeDef[] FlattenedNodes { get; init; } + public required float PowerScore { get; init; } + public required float RecoilMultiplier { get; init; } + public required ModuleSpec Module { get; init; } + } + + public static class ProceduralWeaponGenerator + { + private const int MaxCacheEntries = 2048; + private static readonly ConcurrentDictionary _cache = new(); + + private static readonly string[] MfgCodes = { "SCR", "KOR", "AUR", "VEX", "THL" }; + + private static readonly string[] MfgLabels = + { + "Scrap-Frontier Armament", + "Korrathi Ironworks", + "Auralian Optics", + "Vex-Nine Collective", + "Thalassan Forge" + }; + + private static readonly string[][] PrefixPools = + { + new[] { "Rustbucket", "Gutter", "Jury-Rigged", "Wrenchborn", "Scrapyard" }, + new[] { "Korrathi", "Bastion-Breaker", "Slag-Hammer", "Ironjaw", "Redline" }, + new[] { "Auralian", "Sol-7", "Sun-Glass", "Helios", "Prism-Born" }, + new[] { "Vex-Nine", "Bramble", "Hive-Mind", "Neuro-Weave", "Widowmaker" }, + new[] { "Thalassan", "Abyssal", "Voltaic", "Tide-Breaker", "Deep-Arc" } + }; + + private static readonly string[] TierTags = { "Mk-I", "Mk-II", "Mk-III", "Apex" }; + + private static readonly uint[] MfgColors = + { + 0xFFAA33FFu, // ScrapFrontier amber + 0xF2C422FFu, // Korrathi hazard yellow/orange + 0x38E8FFFFu, // Auralian cyan-gold + 0x7CF230FFu, // Vex-Nine violet-lime + 0x2CB8FFFFu // Thalassan electric blue + }; + + public static string FormatId(ProceduralWeaponKey key) + { + int mfg = Math.Clamp((int)key.Manufacturer, 0, MfgCodes.Length - 1); + int arch = Math.Clamp((int)key.Archetype, 0, 19); + int tier = key.Tier & 0xF; + int flags = key.Flags & 0xF; + return $"proc:{MfgCodes[mfg]}:{arch:X2}:{tier:X1}{flags:X1}:{key.Seed:X16}"; + } + + public static bool TryParseId(string? id, out ProceduralWeaponKey key) + { + key = default; + if (string.IsNullOrWhiteSpace(id) || !id.StartsWith("proc:", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + string[] parts = id.Split(':'); + if (parts.Length != 5) + { + return false; + } + + int mfgIdx = -1; + for (int i = 0; i < MfgCodes.Length; i++) + { + if (string.Equals(parts[1], MfgCodes[i], StringComparison.OrdinalIgnoreCase)) + { + mfgIdx = i; + break; + } + } + if (mfgIdx < 0) + { + return false; + } + + if (!byte.TryParse(parts[2], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte arch) || arch >= 20) + { + return false; + } + + if (parts[3].Length != 2 || + !byte.TryParse(parts[3].AsSpan(0, 1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte tier) || + !byte.TryParse(parts[3].AsSpan(1, 1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte flags)) + { + return false; + } + + if (!ulong.TryParse(parts[4], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong seed)) + { + return false; + } + + key = new ProceduralWeaponKey(seed, (byte)mfgIdx, arch, tier, flags); + return true; + } + + public static ProceduralWeaponSpec CreateDreamSabotSled(ulong seed = 0x5AB0700010001UL, byte tier = 2) => + Generate(new ProceduralWeaponKey(seed, (byte)ManufacturerId.KorrathiIronworks, (byte)WeaponArchetypeKind.SabotRocketSled, tier, 1)); + + public static ProceduralWeaponSpec CreateDreamLoiteringDrone(ulong seed = 0xD204E00020002UL, byte tier = 3) => + Generate(new ProceduralWeaponKey(seed, (byte)ManufacturerId.AuralianOptics, (byte)WeaponArchetypeKind.LoiteringLaserDrone, tier, 1)); + + public static ProceduralWeaponSpec CreateDreamMirvMineBlanket(ulong seed = 0xB1A4E00030003UL, byte tier = 2) => + Generate(new ProceduralWeaponKey(seed, (byte)ManufacturerId.KorrathiIronworks, (byte)WeaponArchetypeKind.MirvMineBlanket, tier, 1)); + + public static ProceduralWeaponSpec CreateDreamWeapon(WeaponArchetypeKind archetype, ulong seed = 0xCAFE00001UL, byte tier = 2) + { + byte mfg = (byte)((int)archetype / 4); + return Generate(new ProceduralWeaponKey(seed, mfg, (byte)archetype, tier, 1)); + } + + public static ProceduralWeaponSpec RollForWave(int wave, ulong matchSeed, int ordinal) + { + ulong h = Mix64(matchSeed ^ ((ulong)(uint)wave * 0x9E3779B97F4A7C15UL) ^ ((ulong)(uint)ordinal * 0xBF58476D1CE4E5B9UL)); + int clampedWave = Math.Clamp(wave, 0, 3); + ManufacturerId mfg = clampedWave switch + { + 0 => (h & 3) == 0 ? ManufacturerId.KorrathiIronworks : ManufacturerId.ScrapFrontier, + 1 => (h % 3) switch + { + 0 => ManufacturerId.ScrapFrontier, + 1 => ManufacturerId.KorrathiIronworks, + _ => ManufacturerId.VexNineCollective + }, + 2 => (h % 3) switch + { + 0 => ManufacturerId.KorrathiIronworks, + 1 => ManufacturerId.VexNineCollective, + _ => ManufacturerId.AuralianOptics + }, + _ => (h % 4) switch + { + 0 => ManufacturerId.KorrathiIronworks, + 1 => ManufacturerId.AuralianOptics, + 2 => ManufacturerId.VexNineCollective, + _ => ManufacturerId.ThalassanForge + } + }; + + byte arch = (byte)((int)mfg * 4 + (int)((h >> 8) & 3)); + return Generate(new ProceduralWeaponKey(h, (byte)mfg, arch, (byte)clampedWave, 0)); + } + + public static ProceduralWeaponSpec RollForManufacturer(ManufacturerId mfg, int tier, ulong seed) + { + ulong h = Mix64(seed ^ ((ulong)(byte)mfg * 0x94D049BB133111EBUL)); + byte arch = (byte)((int)mfg * 4 + (int)((h >> 6) & 3)); + byte clampedTier = (byte)Math.Clamp(tier, 0, 3); + return Generate(new ProceduralWeaponKey(h, (byte)mfg, arch, clampedTier, 0)); + } + + public static ProceduralWeaponSpec Generate(ProceduralWeaponKey key) + { + var normalized = NormalizeKey(key); + if (_cache.TryGetValue(normalized, out var existing)) + { + return existing; + } + + if (_cache.Count >= MaxCacheEntries) + { + _cache.Clear(); + } + + var built = BuildSpec(normalized); + _cache[normalized] = built; + return built; + } + + private static ProceduralWeaponKey NormalizeKey(ProceduralWeaponKey key) + { + byte mfg = (byte)Math.Clamp((int)key.Manufacturer, 0, 4); + byte arch = (byte)Math.Clamp((int)key.Archetype, 0, 19); + byte tier = (byte)(key.Tier & 3); + byte flags = (byte)(key.Flags & 0xF); + return new ProceduralWeaponKey(key.Seed, mfg, arch, tier, flags); + } + + private static ProceduralWeaponSpec BuildSpec(ProceduralWeaponKey key) + { + var mfg = (ManufacturerId)key.Manufacturer; + var arch = (WeaponArchetypeKind)key.Archetype; + byte tier = key.Tier; + bool isCanonicalDream = (key.Flags & 1) != 0; + + ulong rng = Mix64(key.Seed ^ ((ulong)key.Manufacturer << 48) ^ ((ulong)key.Archetype << 32) ^ ((ulong)tier << 16) ^ key.Flags); + + var (rx, brl, fd, mz) = SelectModularParts(mfg, arch, isCanonicalDream, ref rng); + float tierScale = 1f + tier * 0.14f; + float rollDmg = isCanonicalDream ? 1f : Lerp(0.92f, 1.12f, NextFloat(ref rng)); + float rollCd = isCanonicalDream ? 1f : Lerp(0.92f, 1.08f, NextFloat(ref rng)); + float rollHeat = isCanonicalDream ? 1f : Lerp(0.92f, 1.08f, NextFloat(ref rng)); + + // Receiver modifiers + float rxDmgMult = rx switch { 1 => 1.32f, _ => 1.0f }; + float rxCdMult = rx switch { 1 => 1.25f, _ => 1.0f }; + float rxHeatMult = rx switch { 0 => 0.88f, 1 => 1.30f, _ => 1.0f }; + float rxSpreadMult = rx switch { 2 => 0.45f, _ => 1.0f }; + float rxRangeMult = rx switch { 2 => 1.20f, _ => 1.0f }; + int rxBurstAdd = rx == 3 ? 1 : 0; + float rxThermalMassAdd = rx == 0 ? 5f : 0f; + float rxRecoilMult = rx switch { 0 => 1.15f, 2 => 0f, _ => 1.0f }; + + // Barrel modifiers + float brlVelMult = brl == 0 ? 1.25f : 1.0f; + float brlCdMult = brl == 0 ? 0.85f : 1.0f; + float brlEnergyMult = brl == 2 ? 1.25f : 1.0f; + + // Feed modifiers + float fdHeatMult = fd switch { 0 => 0.85f, 1 => 1.28f, 2 => 1.22f, _ => 1.0f }; + float fdCdMult = fd switch { 0 => 0.90f, 1 => 0.68f, _ => 1.0f }; + float fdSpreadAdd = fd == 1 ? 0.012f : 0f; + float fdEnergyMult = fd == 2 ? 1.28f : 1.0f; + float fdThermalMassAdd = fd == 2 ? 4f : 0f; + int fdSplitAdd = fd == 3 ? 3 : 0; + + // Muzzle modifiers + float mzSpreadMult = mz == 0 ? 0.70f : 1.0f; + float mzRecoilMult = mz == 0 ? 0.80f : 1.0f; + + float mfgRecoil = mfg switch + { + ManufacturerId.ScrapFrontier => 1.20f, + ManufacturerId.KorrathiIronworks => 1.45f, + ManufacturerId.AuralianOptics => 0.0f, + ManufacturerId.VexNineCollective => 0.75f, + _ => 0.55f + }; + float recoilMult = mfgRecoil * rxRecoilMult * mzRecoilMult; + + string prefix = PrefixPools[(int)mfg][(int)(NextU64(ref rng) % (ulong)PrefixPools[(int)mfg].Length)]; + string tierTag = TierTags[tier & 3]; + uint colorRgba = MfgColors[(int)mfg]; + + bool isWideArc = arch == WeaponArchetypeKind.PointDefenseWeb; + var assembly = new ModularWeaponAssembly(rx, brl, fd, mz, mfg, VisualScale: 1.0f, IsWideArc: isWideArc); + + var buildCtx = new ArchetypeBuildContext + { + Mfg = mfg, + Arch = arch, + Tier = tier, + TierScale = tierScale, + RollDmg = rollDmg, + RollCd = rollCd, + RollHeat = rollHeat, + RxDmgMult = rxDmgMult, + RxCdMult = rxCdMult, + RxHeatMult = rxHeatMult, + RxSpreadMult = rxSpreadMult, + RxRangeMult = rxRangeMult, + RxBurstAdd = rxBurstAdd, + RxThermalMassAdd = rxThermalMassAdd, + BrlVelMult = brlVelMult, + BrlCdMult = brlCdMult, + BrlEnergyMult = brlEnergyMult, + FdHeatMult = fdHeatMult, + FdCdMult = fdCdMult, + FdSpreadAdd = fdSpreadAdd, + FdEnergyMult = fdEnergyMult, + FdThermalMassAdd = fdThermalMassAdd, + FdSplitAdd = fdSplitAdd, + MzSpreadMult = mzSpreadMult, + BarrelIdx = brl, + MuzzleIdx = mz, + ColorRgba = colorRgba, + Prefix = prefix, + TierTag = tierTag, + IsCanonicalDream = isCanonicalDream + }; + + var built = BuildArchetype(buildCtx); + var flattened = OrdnanceGraphValidator.ValidateAndFlatten(built.Root); + + float powerScore = ComputePowerScore(built.Root, built.BurstCount, built.Cooldown, built.DirectSummaryDmg); + string id = FormatId(key); + bool isImperial = mfg != ManufacturerId.ScrapFrontier; + + var modSpec = new ModuleSpec( + Id: id, + Name: built.DisplayName, + Kind: HardpointKind.Weapon, + Width: 1, + Height: built.Height, + IsImperial: isImperial, + ThermalMass: MathF.Max(5f, built.ThermalMass), + Conductivity: built.Conductivity, + OptimalTemp: built.OptimalTemp, + PlateauWidth: built.PlateauWidth, + MinTemp: 0f, + MaxTemp: built.MaxTemp, + HeatOutput: MathF.Max(8f, built.HeatOutput), + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: built.DirectSummaryDmg, + WeaponRange: built.Range, + FireCooldown: MathF.Max(0.10f, built.Cooldown), + ProjectileSpeed: built.DisplaySpeed, + SpreadRad: MathF.Max(0.001f, built.SpreadRad), + BurstCount: Math.Max(1, built.BurstCount), + IsWideArc: isWideArc, + MinPitchDeg: isWideArc ? -10f : -15f, + MaxPitchDeg: isWideArc ? 85f : 45f, + VisualClassOverride: built.VisualClass, + EffectivePowerScore: powerScore); + + var spec = new ProceduralWeaponSpec + { + Key = key, + Manufacturer = mfg, + Archetype = arch, + WaveTier = tier, + DisplayName = built.DisplayName, + ManufacturerLabel = MfgLabels[(int)mfg], + SummaryLine1 = built.SummaryLine1, + SummaryLine2 = built.SummaryLine2, + VisualClass = built.VisualClass, + AudioClass = built.AudioClass, + Assembly = assembly, + RootNode = built.Root, + FlattenedNodes = flattened, + PowerScore = powerScore, + RecoilMultiplier = recoilMult, + Module = modSpec with { Procedural = null } // temporary placeholder replaced below + }; + + var finalModule = modSpec with { Procedural = spec }; + return new ProceduralWeaponSpec + { + Key = spec.Key, + Manufacturer = spec.Manufacturer, + Archetype = spec.Archetype, + WaveTier = spec.WaveTier, + DisplayName = spec.DisplayName, + ManufacturerLabel = spec.ManufacturerLabel, + SummaryLine1 = spec.SummaryLine1, + SummaryLine2 = spec.SummaryLine2, + VisualClass = spec.VisualClass, + AudioClass = spec.AudioClass, + Assembly = spec.Assembly, + RootNode = spec.RootNode, + FlattenedNodes = spec.FlattenedNodes, + PowerScore = spec.PowerScore, + RecoilMultiplier = spec.RecoilMultiplier, + Module = finalModule + }; + } + + private static (byte Rx, byte Brl, byte Fd, byte Mz) SelectModularParts( + ManufacturerId mfg, + WeaponArchetypeKind arch, + bool isCanonicalDream, + ref ulong rng) + { + if (isCanonicalDream) + { + return arch switch + { + WeaponArchetypeKind.SabotRocketSled => (1, 1, 0, 0), + WeaponArchetypeKind.LoiteringLaserDrone => (2, 3, 2, 2), + WeaponArchetypeKind.MirvMineBlanket => (3, 3, 3, 1), + _ => ((byte)mfg switch { 0 => (byte)0, 1 => (byte)1, 2 => (byte)2, 3 => (byte)3, _ => (byte)2 }, + (byte)((int)arch & 3), + (byte)(((int)arch + 1) & 3), + (byte)(((int)arch + 2) & 3)) + }; + } + + byte rx = arch switch + { + WeaponArchetypeKind.SabotRocketSled => 1, + WeaponArchetypeKind.LoiteringLaserDrone => 2, + WeaponArchetypeKind.MirvMineBlanket => (NextU64(ref rng) & 1) == 0 ? (byte)3 : (byte)1, + _ => (byte)(NextU64(ref rng) % 4) + }; + byte brl = arch switch + { + WeaponArchetypeKind.SabotRocketSled or WeaponArchetypeKind.HypervelocityGaussRail => 1, + WeaponArchetypeKind.LoiteringLaserDrone or WeaponArchetypeKind.MirvMineBlanket or WeaponArchetypeKind.HomingSwarmPod => 3, + WeaponArchetypeKind.RefractingPrismLance or WeaponArchetypeKind.RailPlasmaBeam => 2, + _ => (byte)(NextU64(ref rng) % 4) + }; + byte fd = arch switch + { + WeaponArchetypeKind.MirvMineBlanket or WeaponArchetypeKind.HomingSwarmPod or WeaponArchetypeKind.AirburstProximitySwarm => 3, + WeaponArchetypeKind.LoiteringLaserDrone or WeaponArchetypeKind.ArcDischargeLance or WeaponArchetypeKind.PlasmaPoolMortar => 2, + _ => (byte)(NextU64(ref rng) % 4) + }; + byte mz = arch switch + { + WeaponArchetypeKind.MirvMineBlanket or WeaponArchetypeKind.ClusterSiegeMortar or WeaponArchetypeKind.AirburstProximitySwarm => 1, + WeaponArchetypeKind.LoiteringLaserDrone => 2, + WeaponArchetypeKind.PlasmaPoolMortar or WeaponArchetypeKind.ArcDischargeLance or WeaponArchetypeKind.ThermalOverloadOrb => 3, + _ => (byte)(NextU64(ref rng) % 4) + }; + + return (rx, brl, fd, mz); + } + + private sealed class ArchetypeBuildContext + { + public ManufacturerId Mfg; + public WeaponArchetypeKind Arch; + public byte Tier; + public float TierScale; + public float RollDmg; + public float RollCd; + public float RollHeat; + public float RxDmgMult; + public float RxCdMult; + public float RxHeatMult; + public float RxSpreadMult; + public float RxRangeMult; + public int RxBurstAdd; + public float RxThermalMassAdd; + public float BrlVelMult; + public float BrlCdMult; + public float BrlEnergyMult; + public float FdHeatMult; + public float FdCdMult; + public float FdSpreadAdd; + public float FdEnergyMult; + public float FdThermalMassAdd; + public int FdSplitAdd; + public float MzSpreadMult; + public byte BarrelIdx; + public byte MuzzleIdx; + public uint ColorRgba; + public string Prefix = ""; + public string TierTag = ""; + public bool IsCanonicalDream; + } + + private sealed class BuiltArchetype + { + public string DisplayName = ""; + public string SummaryLine1 = ""; + public string SummaryLine2 = ""; + public WeaponVisualClass VisualClass; + public OrdnanceAudioClass AudioClass; + public OrdnanceNodeDef Root = null!; + public int Height = 1; + public float ThermalMass = 10f; + public float Conductivity = 12f; + public float OptimalTemp = 75f; + public float PlateauWidth = 75f; + public float MaxTemp = 190f; + public float HeatOutput = 60f; + public float DirectSummaryDmg = 30f; + public float Range = 220f; + public float Cooldown = 0.5f; + public float DisplaySpeed = 240f; + public float SpreadRad = 0.02f; + public int BurstCount = 1; + } + + private static BuiltArchetype BuildArchetype(ArchetypeBuildContext c) + { + float baseDmgScale = c.TierScale * c.RollDmg * c.RxDmgMult; + float energyDmgScale = baseDmgScale * c.BrlEnergyMult * c.FdEnergyMult; + float cdScale = c.RollCd * c.RxCdMult * c.BrlCdMult * c.FdCdMult; + float heatScale = c.RollHeat * c.RxHeatMult * c.FdHeatMult; + float spreadScale = c.RxSpreadMult * c.MzSpreadMult; + float velScale = c.BrlVelMult; + + switch (c.Arch) + { + // ---- SCRAP-FRONTIER (0..3) ---- + case WeaponArchetypeKind.RotaryAutocannon: + { + float dmg = 14f * baseDmgScale; + int burst = Math.Clamp(3 + c.RxBurstAdd, 1, 5); + float range = 200f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 260f * velScale, + Range = range, + DirectDamage = dmg, + HeatTransfer = 4f, + VisualClass = WeaponVisualClass.Autocannon, + AudioClass = OrdnanceAudioClass.CannonHeavy, + ColorRgba = c.ColorRgba, + TracerTtl = 0.09f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Rotary Autocannon {c.TierTag}", + SummaryLine1 = $"SCR ROTARY | {dmg:F0}x{burst} DMG | {range:F0}m | 1x2", + SummaryLine2 = "Spin-up twin-drum autocannon shreds exposed hull cells", + VisualClass = WeaponVisualClass.Autocannon, + AudioClass = OrdnanceAudioClass.CannonHeavy, + Root = root, + Height = 2, + ThermalMass = 9f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 9f, + OptimalTemp = 70f, + PlateauWidth = 85f, + MaxTemp = 175f, + HeatOutput = 62f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 0.30f * cdScale, + DisplaySpeed = 260f * velScale, + SpreadRad = (0.032f + c.FdSpreadAdd) * spreadScale, + BurstCount = burst + }; + } + + case WeaponArchetypeKind.FlakBurstCannon: + { + float dmg = 11f * baseDmgScale; + float splash = 9f * baseDmgScale; + int burst = Math.Clamp(4 + c.RxBurstAdd, 1, 6); + float range = 135f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 210f * velScale, + Range = range, + DirectDamage = dmg, + SplashDamage = splash, + SplashRadius = 3.2f, + CraterRadius = 1.6f, + CraterDepth = 0.25f, + CraterFirstBurstOnly = true, + IsAirburst = true, + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.CannonHeavy, + ColorRgba = c.ColorRgba, + TracerTtl = 0.11f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Flak Scatter-Rig {c.TierTag}", + SummaryLine1 = $"SCR FLAK | {dmg:F0}x{burst} AIRBURST | {range:F0}m | 1x1", + SummaryLine2 = "Proximity-timed shrapnel clouds scour light armor & rotors", + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.CannonHeavy, + Root = root, + Height = 1, + ThermalMass = 7f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 9f, + OptimalTemp = 68f, + PlateauWidth = 80f, + MaxTemp = 170f, + HeatOutput = 68f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 0.56f * cdScale, + DisplaySpeed = 210f * velScale, + SpreadRad = (0.11f + c.FdSpreadAdd) * spreadScale, + BurstCount = burst + }; + } + + case WeaponArchetypeKind.SabotSlugCannon: + { + float dmg = 64f * baseDmgScale; + float speed = 340f * velScale; + float range = 270f * c.RxRangeMult; + byte pen = (byte)(c.BarrelIdx == 1 ? 2 : 1); + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = speed, + GravityScale = 0.12f, + MaxLifetime = 1.4f, + Range = range, + DirectDamage = dmg, + MaxPenetrations = pen, + PenetrationDamageDecay = 0.72f, + CraterRadius = 1.8f, + CraterDepth = 0.35f, + VisualClass = WeaponVisualClass.Autocannon, + AudioClass = OrdnanceAudioClass.CannonHeavy, + ColorRgba = c.ColorRgba, + TracerTtl = 0.12f, + VisualShape = OrdnanceVisualShape.SabotCarrier, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 1.4f, Action = OrdnanceTriggerAction.Fizzle } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Sabot Slug-Cannon {c.TierTag}", + SummaryLine1 = $"SCR SABOT | {dmg:F0} AP | {speed:F0}m/s | 1x2", + SummaryLine2 = $"High-velocity tungsten slug punches {pen + 1} hull layers", + VisualClass = WeaponVisualClass.Autocannon, + AudioClass = OrdnanceAudioClass.CannonHeavy, + Root = root, + Height = 2, + ThermalMass = 12f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 10f, + OptimalTemp = 72f, + PlateauWidth = 85f, + MaxTemp = 185f, + HeatOutput = 88f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 1.05f * cdScale, + DisplaySpeed = speed, + SpreadRad = (0.012f + c.FdSpreadAdd) * spreadScale, + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.DumbRocketPod: + { + float dmg = 34f * baseDmgScale; + float splash = 26f * baseDmgScale; + int burst = Math.Clamp(2 + c.RxBurstAdd, 1, 4); + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.RocketBoosted, + InitialSpeed = 75f * velScale, + ThrustAccel = 145f, + BurnTime = 1.2f, + MaxSpeed = 220f * velScale, + MaxLifetime = 2.6f, + Range = 250f * c.RxRangeMult, + DirectDamage = dmg, + SplashDamage = splash, + SplashRadius = 4.6f, + CraterRadius = 2.6f, + CraterDepth = 0.55f, + ScorchRadius = 3.2f, + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.6f, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Rocket Salvo Pod {c.TierTag}", + SummaryLine1 = $"SCR ROCKET | {dmg + splash:F0}x{burst} HE | 220m/s | 1x2", + SummaryLine2 = "Unguided booster salvo saturates ridge lines with HE blast", + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 2, + ThermalMass = 11f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 9f, + OptimalTemp = 70f, + PlateauWidth = 85f, + MaxTemp = 180f, + HeatOutput = 76f * heatScale, + DirectSummaryDmg = dmg + splash * 0.5f, + Range = 250f * c.RxRangeMult, + Cooldown = 1.15f * cdScale, + DisplaySpeed = 220f * velScale, + SpreadRad = (0.045f + c.FdSpreadAdd) * spreadScale, + BurstCount = burst + }; + } + + // ---- KORRATHI IRONWORKS (4..7) ---- + case WeaponArchetypeKind.SabotRocketSled: + { + float s0Dmg = (c.IsCanonicalDream ? 42f : 38f * baseDmgScale); + float s1Direct = (c.IsCanonicalDream ? 74f : 68f * baseDmgScale); + float s1Splash = (c.IsCanonicalDream ? 48f : 44f * baseDmgScale); + float s0Speed = c.IsCanonicalDream ? 240f : 230f * velScale; + float s1MaxSpeed = c.IsCanonicalDream ? 360f : 350f * velScale; + float range = 340f * c.RxRangeMult; + + var stage1 = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.RocketBoosted, + InitialSpeed = 200f, + ThrustAccel = 260f, + BurnTime = 1.4f, + MaxSpeed = s1MaxSpeed, + MaxLifetime = 2.6f, + Range = range, + DirectDamage = s1Direct, + SplashDamage = s1Splash, + SplashRadius = 5.5f, + HeatTransfer = 28f, + CraterRadius = 4.2f, + CraterDepth = 1.0f, + ScorchRadius = 4.6f, + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.6f, Action = OrdnanceTriggerAction.Detonate } + } + }; + + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = s0Speed, + GravityScale = 0.18f, + MaxLifetime = 2.0f, + Range = range, + DirectDamage = s0Dmg, + SplashDamage = 12f, + SplashRadius = 2.4f, + CraterRadius = 1.8f, + CraterDepth = 0.4f, + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.CannonHeavy, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.SabotCarrier, + Triggers = new[] + { + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.StageElapsed, + Threshold = 0.18f, + Action = OrdnanceTriggerAction.Transition, + ChildNode = stage1, + EjectSabotVfx = true + }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.0f, Action = OrdnanceTriggerAction.Detonate } + } + }; + + return new BuiltArchetype + { + DisplayName = c.IsCanonicalDream ? $"Korrathi {c.TierTag} Sabot-Rocket Sled" : $"{c.Prefix} Sabot-Rocket Sled {c.TierTag}", + SummaryLine1 = $"KOR SABOT SLED | {s1Direct:F0}+{s1Splash:F0} AP | {s1MaxSpeed:F0}m/s | 1x2", + SummaryLine2 = "2-stage sabot sled: sheds booster at 0.18s into 360m/s AP warhead", + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 2, + ThermalMass = 16f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 11f, + OptimalTemp = 78f, + PlateauWidth = 80f, + MaxTemp = 195f, + HeatOutput = (c.IsCanonicalDream ? 120f : 115f * heatScale), + DirectSummaryDmg = s1Direct + s1Splash, + Range = range, + Cooldown = (c.IsCanonicalDream ? 1.25f : 1.25f * cdScale), + DisplaySpeed = s1MaxSpeed, + SpreadRad = (c.IsCanonicalDream ? 0.008f : (0.010f + c.FdSpreadAdd) * spreadScale), + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.MirvMineBlanket: + { + int splitCount = c.IsCanonicalDream ? 10 : Math.Clamp(8 + c.FdSplitAdd, 6, 12); + float mineSplash = c.IsCanonicalDream ? 34f : 30f * baseDmgScale; + float range = 220f * c.RxRangeMult; + + var mineStage = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.StationaryMine, + InitialSpeed = 0f, + ArmDelay = 0.6f, + ProximityRadius = 6.5f, + ProximityIgnoreOwner = true, + MaxLifetime = 28f, + InterceptHp = 15f, + SplashDamage = mineSplash, + SplashRadius = 6.5f, + HeatTransfer = 18f, + CraterRadius = 2.2f, + CraterDepth = 0.45f, + ScorchRadius = 2.8f, + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Mine, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Proximity, Threshold = 6.5f, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 28f, Action = OrdnanceTriggerAction.Fizzle } + } + }; + + var bombletStage = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = 26f, + GravityScale = 1.2f, + MaxLifetime = 5.0f, + DirectDamage = 12f, + SplashDamage = 18f, + SplashRadius = 3.5f, + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Mine, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = mineStage }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 5.0f, Action = OrdnanceTriggerAction.Detonate } + } + }; + + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + LaunchPitchBiasDeg = 26f, + InitialSpeed = 72f, + GravityScale = 1.25f, + MaxLifetime = 4.5f, + Range = range, + DirectDamage = 25f, + SplashDamage = 24f, + SplashRadius = 4.5f, + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.Apex, + MinAge = 0.25f, + Action = OrdnanceTriggerAction.Split, + ChildNode = bombletStage, + SplitCount = splitCount, + SplitConeDeg = 48f + }, + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.Impact, + Action = OrdnanceTriggerAction.Split, + ChildNode = bombletStage, + SplitCount = Math.Min(6, splitCount), + SplitConeDeg = 60f + }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 4.5f, Action = OrdnanceTriggerAction.Detonate } + } + }; + + return new BuiltArchetype + { + DisplayName = c.IsCanonicalDream ? $"Korrathi {c.TierTag} MIRV Mine-Blanket" : $"{c.Prefix} MIRV Mine-Blanket {c.TierTag}", + SummaryLine1 = $"KOR MIRV MINES | {splitCount}x{mineSplash:F0} PROX | {range:F0}m | 1x2", + SummaryLine2 = $"Carrier splits at apex into {splitCount} ground-armed proximity mines", + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 2, + ThermalMass = 14f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 10f, + OptimalTemp = 76f, + PlateauWidth = 80f, + MaxTemp = 190f, + HeatOutput = (c.IsCanonicalDream ? 105f : 105f * heatScale), + DirectSummaryDmg = mineSplash * splitCount * 0.35f, + Range = range, + Cooldown = (c.IsCanonicalDream ? 1.55f : 1.55f * cdScale), + DisplaySpeed = 72f, + SpreadRad = (c.IsCanonicalDream ? 0.015f : (0.018f + c.FdSpreadAdd) * spreadScale), + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.ClusterSiegeMortar: + { + int splitCount = Math.Clamp(6 + c.FdSplitAdd, 4, 10); + float subSplash = 28f * baseDmgScale; + float range = 260f * c.RxRangeMult; + var sub = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = 34f, + GravityScale = 1.35f, + MaxLifetime = 4.0f, + DirectDamage = 22f * baseDmgScale, + SplashDamage = subSplash, + SplashRadius = 5.2f, + CraterRadius = 2.8f, + CraterDepth = 0.65f, + ScorchRadius = 3.2f, + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.CannonHeavy, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 4.0f, Action = OrdnanceTriggerAction.Detonate } + } + }; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + LaunchPitchBiasDeg = 34f, + InitialSpeed = 80f, + GravityScale = 1.25f, + MaxLifetime = 4.5f, + Range = range, + DirectDamage = 35f * baseDmgScale, + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.CannonHeavy, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Apex, MinAge = 0.30f, Action = OrdnanceTriggerAction.Split, ChildNode = sub, SplitCount = splitCount, SplitConeDeg = 40f }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Cluster Siege Mortar {c.TierTag}", + SummaryLine1 = $"KOR MORTAR | {splitCount}x{subSplash:F0} HE | {range:F0}m | 1x2", + SummaryLine2 = "High-arc siege shell bursts over cover into HE bomblets", + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.CannonHeavy, + Root = root, + Height = 2, + ThermalMass = 15f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 10f, + OptimalTemp = 78f, + PlateauWidth = 80f, + MaxTemp = 195f, + HeatOutput = 110f * heatScale, + DirectSummaryDmg = subSplash * 3.0f, + Range = range, + Cooldown = 1.65f * cdScale, + DisplaySpeed = 80f, + SpreadRad = (0.024f + c.FdSpreadAdd) * spreadScale, + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.GyrojetBunkerBuster: + { + float dmg = 92f * baseDmgScale; + float splash = 58f * baseDmgScale; + float range = 290f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.RocketBoosted, + InitialSpeed = 110f * velScale, + ThrustAccel = 190f, + BurnTime = 1.5f, + MaxSpeed = 290f * velScale, + MaxLifetime = 2.8f, + Range = range, + DirectDamage = dmg, + SplashDamage = splash, + SplashRadius = 7.0f, + HeatTransfer = 35f, + CraterRadius = 4.8f, + CraterDepth = 1.2f, + ScorchRadius = 5.4f, + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.8f, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Gyrojet Bunker-Buster {c.TierTag}", + SummaryLine1 = $"KOR GYROJET | {dmg:F0}+{splash:F0} HE | 290m/s | 1x2", + SummaryLine2 = "Heavy bunker-buster warhead excavates 4.8m craters on impact", + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 2, + ThermalMass = 16f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 11f, + OptimalTemp = 78f, + PlateauWidth = 80f, + MaxTemp = 195f, + HeatOutput = 135f * heatScale, + DirectSummaryDmg = dmg + splash, + Range = range, + Cooldown = 1.50f * cdScale, + DisplaySpeed = 290f * velScale, + SpreadRad = (0.015f + c.FdSpreadAdd) * spreadScale, + BurstCount = 1 + }; + } + + // ---- AURALIAN OPTICS (8..11) ---- + case WeaponArchetypeKind.LoiteringLaserDrone: + { + float beamDmg = c.IsCanonicalDream ? 18f : 16f * energyDmgScale; + float diveDmg = c.IsCanonicalDream ? 65f : 58f * baseDmgScale; + float diveSplash = c.IsCanonicalDream ? 45f : 40f * baseDmgScale; + float range = 260f * c.RxRangeMult; + + var laserBeam = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 400f, + Range = 130f, + DirectDamage = beamDmg, + HeatTransfer = 18f, + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + ColorRgba = c.ColorRgba, + TracerTtl = 0.16f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + + var diveBomb = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HomingMissile, + InitialSpeed = 48f, + ThrustAccel = 95f, + BurnTime = 2.5f, + MaxSpeed = 115f, + TurnRateRad = 5.2f, + SeekerConeDeg = 135f, + SeekerRange = 160f, + MaxLifetime = 2.5f, + DirectDamage = diveDmg, + SplashDamage = diveSplash, + SplashRadius = 6.0f, + HeatTransfer = 26f, + CraterRadius = 3.2f, + CraterDepth = 0.7f, + ScorchRadius = 3.8f, + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Drone, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.5f, Action = OrdnanceTriggerAction.Detonate } + } + }; + + var loiterStage = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.LoiterOrbit, + LoiterAltitudeAgl = 35f, + LoiterOrbitRadius = 15f, + LoiterOrbitSpeedRad = 1.45f, + MaxLifetime = 4.5f, + InterceptHp = 35f, + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Drone, + WhileAlive = new OrdnanceWhileAliveDef + { + Interval = 0.45f, + MaxPulses = 9, + TriggerScanRadius = 110f, + RequireHostileTarget = true, + TargetConeDeg = 75f, + ChildNode = laserBeam + }, + Triggers = new[] + { + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.Timeout, + Threshold = 4.5f, + Action = OrdnanceTriggerAction.Transition, + ChildNode = diveBomb + } + } + }; + + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.RocketBoosted, + LaunchPitchBiasDeg = 40f, + InitialSpeed = 52f, + ThrustAccel = 60f, + BurnTime = 1.0f, + MaxSpeed = 95f, + MaxLifetime = 2.0f, + Range = range, + DirectDamage = 40f, + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Drone, + Triggers = new[] + { + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.StageElapsed, + Threshold = 1.1f, + Action = OrdnanceTriggerAction.Transition, + ChildNode = loiterStage + }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } + } + }; + + return new BuiltArchetype + { + DisplayName = c.IsCanonicalDream ? $"Auralian {c.TierTag} Loitering Prism-Drone" : $"{c.Prefix} Loitering Prism-Drone {c.TierTag}", + SummaryLine1 = $"AUR DRONE | 9x{beamDmg:F0} LASER + {diveDmg:F0} DIVE | 1x1", + SummaryLine2 = "Orbits at 35m AGL pulsing downward lasers, then dive-bombs on expiry", + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + Root = root, + Height = 1, + ThermalMass = 12f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 14f, + OptimalTemp = 90f, + PlateauWidth = 80f, + MaxTemp = 215f, + HeatOutput = (c.IsCanonicalDream ? 95f : 95f * heatScale), + DirectSummaryDmg = beamDmg * 5f + diveDmg, + Range = range, + Cooldown = (c.IsCanonicalDream ? 2.20f : 2.15f * cdScale), + DisplaySpeed = 95f, + SpreadRad = (c.IsCanonicalDream ? 0.005f : (0.008f + c.FdSpreadAdd) * spreadScale), + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.RefractingPrismLance: + { + float dmg = 58f * energyDmgScale; + float range = 310f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 450f, + Range = range, + DirectDamage = dmg, + HeatTransfer = 34f, + MaxPenetrations = 1, + PenetrationDamageDecay = 0.65f, + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + ColorRgba = c.ColorRgba, + TracerTtl = 0.16f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Refracting Prism-Lance {c.TierTag}", + SummaryLine1 = $"AUR LANCE | {dmg:F0} THERM PIERCE | {range:F0}m | 1x2", + SummaryLine2 = "Zero-recoil coherent prism beam pierces and superheats targets", + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + Root = root, + Height = 2, + ThermalMass = 11f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 14f, + OptimalTemp = 92f, + PlateauWidth = 80f, + MaxTemp = 215f, + HeatOutput = 98f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 0.62f * cdScale, + DisplaySpeed = 450f, + SpreadRad = 0.003f * spreadScale, + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.PulsedBeamSweeper: + { + float dmg = 18f * energyDmgScale; + int burst = Math.Clamp(2 + c.RxBurstAdd, 1, 4); + float range = 230f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 400f, + Range = range, + DirectDamage = dmg, + HeatTransfer = 14f, + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + ColorRgba = c.ColorRgba, + TracerTtl = 0.12f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Pulsed Beam Sweeper {c.TierTag}", + SummaryLine1 = $"AUR SWEEPER | {dmg:F0}x{burst} LASER | {range:F0}m | 1x1", + SummaryLine2 = "Rapid-cycle optical emitter paints enemy radiators with thermal shear", + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + Root = root, + Height = 1, + ThermalMass = 9f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 15f, + OptimalTemp = 90f, + PlateauWidth = 85f, + MaxTemp = 210f, + HeatOutput = 66f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 0.24f * cdScale, + DisplaySpeed = 400f, + SpreadRad = 0.008f * spreadScale, + BurstCount = burst + }; + } + + case WeaponArchetypeKind.ThermalOverloadOrb: + { + float dmg = 38f * energyDmgScale; + float splash = 32f * energyDmgScale; + float range = 240f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = 95f * velScale, + GravityScale = 0.08f, + MaxLifetime = 3.2f, + Range = range, + DirectDamage = dmg, + SplashDamage = splash, + SplashRadius = 6.0f, + HeatTransfer = 65f, + ScorchRadius = 4.0f, + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Pool, + WhileAlive = new OrdnanceWhileAliveDef + { + Interval = 0.25f, + MaxPulses = 12, + RadialHeat = 12f, + RadialDamage = 4f, + RadialRadius = 8.0f + }, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 3.2f, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Thermal Overload Orb {c.TierTag}", + SummaryLine1 = $"AUR ORB | {dmg + splash:F0} + HEAT RADIATION | 95m/s | 1x1", + SummaryLine2 = "Slow incandescent star-orb cooks nearby rigs in flight & spikes on hit", + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + Root = root, + Height = 1, + ThermalMass = 11f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 14f, + OptimalTemp = 92f, + PlateauWidth = 80f, + MaxTemp = 215f, + HeatOutput = 105f * heatScale, + DirectSummaryDmg = dmg + splash, + Range = range, + Cooldown = 1.05f * cdScale, + DisplaySpeed = 95f * velScale, + SpreadRad = 0.008f * spreadScale, + BurstCount = 1 + }; + } + + // ---- VEX-NINE COLLECTIVE (12..15) ---- + case WeaponArchetypeKind.HomingSwarmPod: + { + float dmg = 26f * baseDmgScale; + float splash = 18f * baseDmgScale; + int burst = Math.Clamp(3 + c.RxBurstAdd, 2, 5); + float range = 270f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HomingMissile, + LaunchPitchBiasDeg = 12f, + InitialSpeed = 62f * velScale, + ThrustAccel = 125f, + BurnTime = 2.0f, + MaxSpeed = 165f * velScale, + TurnRateRad = 4.8f, + SeekerConeDeg = 110f, + SeekerRange = range, + InterceptHp = 18f, + MaxLifetime = 3.2f, + Range = range, + DirectDamage = dmg, + SplashDamage = splash, + SplashRadius = 4.0f, + CraterRadius = 2.0f, + CraterDepth = 0.35f, + ScorchRadius = 2.5f, + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 3.2f, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Homing Swarm Pod {c.TierTag}", + SummaryLine1 = $"VEX SWARM | {dmg + splash:F0}x{burst} SEEKER | 165m/s | 1x2", + SummaryLine2 = "Micro-seeker volley curves around ridge cover into locked hulls", + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 2, + ThermalMass = 12f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 12f, + OptimalTemp = 80f, + PlateauWidth = 85f, + MaxTemp = 195f, + HeatOutput = 82f * heatScale, + DirectSummaryDmg = dmg + splash * 0.6f, + Range = range, + Cooldown = 1.15f * cdScale, + DisplaySpeed = 165f * velScale, + SpreadRad = (0.065f + c.FdSpreadAdd) * spreadScale, + BurstCount = burst + }; + } + + case WeaponArchetypeKind.AirburstProximitySwarm: + { + int splitCount = Math.Clamp(5 + c.FdSplitAdd, 4, 9); + float dartDmg = 20f * baseDmgScale; + float range = 270f * c.RxRangeMult; + var dart = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HomingMissile, + InitialSpeed = 85f, + ThrustAccel = 110f, + BurnTime = 1.4f, + MaxSpeed = 175f, + TurnRateRad = 5.4f, + SeekerConeDeg = 125f, + SeekerRange = 90f, + MaxLifetime = 2.0f, + DirectDamage = dartDmg, + SplashDamage = 14f * baseDmgScale, + SplashRadius = 3.4f, + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.0f, Action = OrdnanceTriggerAction.Detonate } + } + }; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.RocketBoosted, + InitialSpeed = 95f * velScale, + ThrustAccel = 140f, + BurnTime = 1.2f, + MaxSpeed = 210f * velScale, + ProximityRadius = 15f, + ProximityIgnoreOwner = true, + MaxLifetime = 2.5f, + Range = range, + DirectDamage = 28f * baseDmgScale, + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Proximity, Threshold = 15f, MinAge = 0.15f, Action = OrdnanceTriggerAction.Split, ChildNode = dart, SplitCount = splitCount, SplitConeDeg = 55f }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.5f, Action = OrdnanceTriggerAction.Split, ChildNode = dart, SplitCount = splitCount, SplitConeDeg = 55f } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Proximity Swarm Carrier {c.TierTag}", + SummaryLine1 = $"VEX AIRBURST | {splitCount}x{dartDmg:F0} DARTS | {range:F0}m | 1x2", + SummaryLine2 = $"Fuses 15m short of target to scatter {splitCount} homing micro-darts", + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 2, + ThermalMass = 12f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 12f, + OptimalTemp = 80f, + PlateauWidth = 85f, + MaxTemp = 195f, + HeatOutput = 88f * heatScale, + DirectSummaryDmg = dartDmg * splitCount * 0.55f, + Range = range, + Cooldown = 1.30f * cdScale, + DisplaySpeed = 210f * velScale, + SpreadRad = (0.020f + c.FdSpreadAdd) * spreadScale, + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.SmartSpiderMineTrap: + { + float mineDmg = 36f * baseDmgScale; + int burst = Math.Clamp(3 + c.RxBurstAdd, 2, 4); + float range = 175f * c.RxRangeMult; + var mine = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.StationaryMine, + ArmDelay = 0.5f, + ProximityRadius = 6.0f, + ProximityIgnoreOwner = true, + MaxLifetime = 26f, + InterceptHp = 16f, + SplashDamage = mineDmg, + SplashRadius = 6.0f, + HeatTransfer = 16f, + CraterRadius = 2.0f, + CraterDepth = 0.4f, + ScorchRadius = 2.6f, + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Mine, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Proximity, Threshold = 6.0f, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 26f, Action = OrdnanceTriggerAction.Fizzle } + } + }; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + LaunchPitchBiasDeg = 18f, + InitialSpeed = 58f, + GravityScale = 1.15f, + MaxLifetime = 4.0f, + Range = range, + DirectDamage = 14f, + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Mine, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = mine }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 4.0f, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Spider-Mine Trap {c.TierTag}", + SummaryLine1 = $"VEX MINES | {burst}x{mineDmg:F0} SMART TRAP | {range:F0}m | 1x1", + SummaryLine2 = "Deploys IFF-safe spider mines that ignore owner & ambush pursuers", + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 1, + ThermalMass = 10f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 12f, + OptimalTemp = 80f, + PlateauWidth = 85f, + MaxTemp = 195f, + HeatOutput = 72f * heatScale, + DirectSummaryDmg = mineDmg, + Range = range, + Cooldown = 1.20f * cdScale, + DisplaySpeed = 58f, + SpreadRad = (0.09f + c.FdSpreadAdd) * spreadScale, + BurstCount = burst + }; + } + + case WeaponArchetypeKind.PointDefenseWeb: + { + float dmg = 15f * energyDmgScale; + int burst = Math.Clamp(3 + c.RxBurstAdd, 2, 5); + float range = 205f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 420f * velScale, + Range = range, + DirectDamage = dmg, + IsAirburst = true, + HeatTransfer = 6f, + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.CannonLight, + ColorRgba = c.ColorRgba, + TracerTtl = 0.09f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Aegis PD-Web {c.TierTag}", + SummaryLine1 = $"VEX WIDE-PD | {dmg:F0}x{burst} +85deg AUTO | {range:F0}m | 1x1", + SummaryLine2 = "Wide-arc automated interceptor web tracks VTOLs & loitering drones", + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.CannonLight, + Root = root, + Height = 1, + ThermalMass = 9f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 15f, + OptimalTemp = 85f, + PlateauWidth = 90f, + MaxTemp = 210f, + HeatOutput = 30f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 0.18f * cdScale, + DisplaySpeed = 420f * velScale, + SpreadRad = (0.022f + c.FdSpreadAdd) * spreadScale, + BurstCount = burst + }; + } + + // ---- THALASSAN FORGE (16..19) ---- + case WeaponArchetypeKind.HypervelocityGaussRail: + { + float dmg = 96f * baseDmgScale; + float speed = 420f * velScale; + float range = 380f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = speed, + GravityScale = 0.02f, + MaxLifetime = 1.2f, + Range = range, + DirectDamage = dmg, + HeatTransfer = 18f, + MaxPenetrations = 2, + PenetrationDamageDecay = 0.75f, + CraterRadius = 2.4f, + CraterDepth = 0.45f, + ScorchRadius = 2.8f, + VisualClass = WeaponVisualClass.GaussRail, + AudioClass = OrdnanceAudioClass.GaussRail, + ColorRgba = c.ColorRgba, + TracerTtl = 0.15f, + VisualShape = OrdnanceVisualShape.SabotCarrier, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 1.2f, Action = OrdnanceTriggerAction.Fizzle } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Gauss Rail-Driver {c.TierTag}", + SummaryLine1 = $"THL GAUSS | {dmg:F0}x3 PIERCE | {speed:F0}m/s | 1x2", + SummaryLine2 = "420m/s electromagnetic slug over-penetrates through 2 armored hulls", + VisualClass = WeaponVisualClass.GaussRail, + AudioClass = OrdnanceAudioClass.GaussRail, + Root = root, + Height = 2, + ThermalMass = 14f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 14f, + OptimalTemp = 92f, + PlateauWidth = 70f, + MaxTemp = 210f, + HeatOutput = 135f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 1.35f * cdScale, + DisplaySpeed = speed, + SpreadRad = 0.004f * spreadScale, + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.PlasmaPoolMortar: + { + float impactSplash = 36f * energyDmgScale; + float poolTickDmg = 12f * energyDmgScale; + float range = 240f * c.RxRangeMult; + var pool = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.StationaryMine, + ArmDelay = 0f, + IsThermalPool = true, + MaxLifetime = 6.0f, + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Pool, + WhileAlive = new OrdnanceWhileAliveDef + { + Interval = 0.5f, + MaxPulses = 12, + RadialDamage = poolTickDmg, + RadialHeat = 22f, + RadialRadius = 6.5f + }, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 6.0f, Action = OrdnanceTriggerAction.Fizzle } } + }; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + LaunchPitchBiasDeg = 22f, + InitialSpeed = 82f * velScale, + GravityScale = 1.1f, + MaxLifetime = 4.0f, + Range = range, + DirectDamage = 28f * energyDmgScale, + SplashDamage = impactSplash, + SplashRadius = 5.5f, + HeatTransfer = 35f, + ScorchRadius = 6.2f, + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Pool, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = pool }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 4.0f, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Plasma Pool Mortar {c.TierTag}", + SummaryLine1 = $"THL PLASMA | {impactSplash:F0} + 6s SCORCH POOL | 1x2", + SummaryLine2 = "Ignites a 6.5m scorching plasma puddle roasting chassis treads", + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + Root = root, + Height = 2, + ThermalMass = 13f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 14f, + OptimalTemp = 95f, + PlateauWidth = 75f, + MaxTemp = 215f, + HeatOutput = 115f * heatScale, + DirectSummaryDmg = impactSplash + poolTickDmg * 4f, + Range = range, + Cooldown = 1.35f * cdScale, + DisplaySpeed = 82f * velScale, + SpreadRad = (0.016f + c.FdSpreadAdd) * spreadScale, + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.ArcDischargeLance: + { + float dmg = 42f * energyDmgScale; + float arcDmg = 18f * energyDmgScale; + float range = 250f * c.RxRangeMult; + var arcBolt = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = 180f, + GravityScale = 0f, + MaxLifetime = 0.22f, + DirectDamage = arcDmg, + HeatTransfer = 18f, + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + ColorRgba = c.ColorRgba, + TracerTtl = 0.12f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 0.22f, Action = OrdnanceTriggerAction.Fizzle } + } + }; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 420f, + Range = range, + DirectDamage = dmg, + HeatTransfer = 28f, + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + ColorRgba = c.ColorRgba, + TracerTtl = 0.14f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Split, ChildNode = arcBolt, SplitCount = 3, SplitConeDeg = 75f } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Arc Discharge Lance {c.TierTag}", + SummaryLine1 = $"THL ARC | {dmg:F0} + 3x{arcDmg:F0} CHAIN | {range:F0}m | 1x2", + SummaryLine2 = "Primary lightning beam forks 3 secondary plasma arcs off hit surface", + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + Root = root, + Height = 2, + ThermalMass = 12f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 15f, + OptimalTemp = 92f, + PlateauWidth = 75f, + MaxTemp = 215f, + HeatOutput = 92f * heatScale, + DirectSummaryDmg = dmg + arcDmg * 1.5f, + Range = range, + Cooldown = 0.72f * cdScale, + DisplaySpeed = 420f, + SpreadRad = 0.008f * spreadScale, + BurstCount = 1 + }; + } + + default: // RailPlasmaBeam + { + float dmg = 68f * energyDmgScale; + float range = 320f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 460f, + Range = range, + DirectDamage = dmg, + HeatTransfer = 44f, + MaxPenetrations = 2, + PenetrationDamageDecay = 0.72f, + ScorchRadius = 2.6f, + VisualClass = WeaponVisualClass.GaussRail, + AudioClass = OrdnanceAudioClass.GaussRail, + ColorRgba = c.ColorRgba, + TracerTtl = 0.16f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Rail-Plasma Beam {c.TierTag}", + SummaryLine1 = $"THL RAIL-PPC | {dmg:F0} PIERCE+HEAT | {range:F0}m | 1x2", + SummaryLine2 = "Superheated magnetic particle beam punches multiple targets & spikes heat", + VisualClass = WeaponVisualClass.GaussRail, + AudioClass = OrdnanceAudioClass.GaussRail, + Root = root, + Height = 2, + ThermalMass = 14f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 15f, + OptimalTemp = 95f, + PlateauWidth = 70f, + MaxTemp = 220f, + HeatOutput = 118f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 0.88f * cdScale, + DisplaySpeed = 460f, + SpreadRad = 0.004f * spreadScale, + BurstCount = 1 + }; + } + } + } + + private static float ComputePowerScore(OrdnanceNodeDef root, int burstCount, float cooldown, float summaryDmg) + { + float effectivePerShot = MathF.Max(summaryDmg, root.DirectDamage + root.SplashDamage * 0.8f); + float dps = (effectivePerShot * MathF.Max(1, burstCount)) / MathF.Max(0.15f, cooldown); + float complexityBonus = 1f; + if (root.Motion is OrdnanceMotion.RocketBoosted or OrdnanceMotion.HomingMissile or OrdnanceMotion.LoiterOrbit) + { + complexityBonus += 0.25f; + } + if (root.Triggers.Length > 1 || root.WhileAlive is not null || root.MaxPenetrations > 0) + { + complexityBonus += 0.35f; + } + return dps * complexityBonus; + } + + private static ulong Mix64(ulong x) + { + x += 0x9E3779B97F4A7C15UL; + x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9UL; + x = (x ^ (x >> 27)) * 0x94D049BB133111EBUL; + return x ^ (x >> 31); + } + + private static ulong NextU64(ref ulong state) + { + state = Mix64(state); + return state; + } + + private static float NextFloat(ref ulong state) => + (NextU64(ref state) & 0xFFFFFFUL) / (float)0x1000000UL; + + private static float Lerp(float a, float b, float t) => a + (b - a) * t; + } +} diff --git a/src/RustToDust.Core/RustToDust.Core.csproj b/src/RustToDust.Core/RustToDust.Core.csproj new file mode 100644 index 0000000..04d0cf7 --- /dev/null +++ b/src/RustToDust.Core/RustToDust.Core.csproj @@ -0,0 +1,14 @@ + + + + net8.0 + enable + disable + + + + + + + + diff --git a/src/RustToDust.Core/SimEvents.cs b/src/RustToDust.Core/SimEvents.cs new file mode 100644 index 0000000..ef9fe75 --- /dev/null +++ b/src/RustToDust.Core/SimEvents.cs @@ -0,0 +1,523 @@ +using System; +using System.Collections.Generic; +using MessagePack; + +namespace RustToDust.Core +{ + public enum TerrainStampKind : byte + { + Crater = 0, + Scorch = 1, + Track = 2, + Rubble = 3 + } + + public enum SlotControlReason : byte + { + Joined = 0, + HandedToAi = 1, + Reclaimed = 2, + Eliminated = 3 + } + + [Union(0, typeof(ShotFiredEvent))] + [Union(1, typeof(HitImpactEvent))] + [Union(2, typeof(TerrainStampEvent))] + [Union(3, typeof(DropSpawnedEvent))] + [Union(4, typeof(DropPickedUpEvent))] + [Union(5, typeof(ContenderLoadoutEvent))] + [Union(6, typeof(EntitySlotControlEvent))] + [Union(7, typeof(BroadcastLineEvent))] + [Union(8, typeof(ContenderEliminatedEvent))] + [Union(9, typeof(SpectatorDestroyedEvent))] + [Union(10, typeof(OverheatAlertEvent))] + [Union(11, typeof(MatchResetEvent))] + [Union(12, typeof(DropPodEvent))] + [Union(13, typeof(OrdnanceNodeEvent))] + [Union(14, typeof(MatchStartedEvent))] + [Union(17, typeof(ArenaRepairEvent))] + public interface ISimEvent + { + } + + [MessagePackObject] + public sealed class OrdnanceNodeEvent : ISimEvent + { + [Key(0)] public int OrdnanceId { get; set; } + [Key(1)] public int ParentOrdnanceId { get; set; } + [Key(2)] public byte Kind { get; set; } + [Key(3)] public bool IsSpectatorShooter { get; set; } + [Key(4)] public int ShooterId { get; set; } + [Key(5)] public ProceduralWeaponKey? WeaponKey { get; set; } + [Key(6)] public byte NodeDefIndex { get; set; } + [Key(7)] public float PosX { get; set; } + [Key(8)] public float PosY { get; set; } + [Key(9)] public float PosZ { get; set; } + [Key(10)] public float VelX { get; set; } + [Key(11)] public float VelY { get; set; } + [Key(12)] public float VelZ { get; set; } + [Key(13)] public int TargetEntityId { get; set; } = -1; + [Key(14)] public bool TargetIsSpectator { get; set; } + [Key(15)] public float SimTime { get; set; } + [Key(16)] public byte VisualShape { get; set; } + [Key(17)] public uint ColorRgba { get; set; } + } + + public enum DropPodEventKind : byte + { + WaveAnnounced = 0, + PodLaunched = 1, + PodRetroBurnStart = 2, + PodTouchdownBlowPetals = 3, + PodCancelled = 4 + } + + [MessagePackObject] + public sealed class DropPodEvent : ISimEvent + { + [Key(0)] public long EventId { get; set; } + [Key(1)] public byte Kind { get; set; } + [Key(2)] public int WaveIndex { get; set; } + [Key(3)] public int PodId { get; set; } + [Key(4)] public byte PodKind { get; set; } + [Key(5)] public int ContenderId { get; set; } = -1; + [Key(6)] public float X { get; set; } + [Key(7)] public float Y { get; set; } + [Key(8)] public float Z { get; set; } + [Key(9)] public float VelX { get; set; } + [Key(10)] public float VelY { get; set; } + [Key(11)] public float VelZ { get; set; } + [Key(12)] public float NormalX { get; set; } + [Key(13)] public float NormalY { get; set; } + [Key(14)] public float NormalZ { get; set; } + [Key(15)] public string? ChassisId { get; set; } + [Key(16)] public string? ModuleId { get; set; } + [Key(17)] public int DropId { get; set; } + [Key(18)] public bool RespawnsClosed { get; set; } + [Key(19)] public int GearCount { get; set; } + [Key(20)] public int RespawnCount { get; set; } + } + + [MessagePackObject] + public sealed class ShotFiredEvent : ISimEvent + { + [Key(0)] public int TracerId { get; set; } + [Key(1)] public bool IsSpectatorShooter { get; set; } + [Key(2)] public int ShooterId { get; set; } + [Key(3)] public float StartX { get; set; } + [Key(4)] public float StartY { get; set; } + [Key(5)] public float StartZ { get; set; } + [Key(6)] public float EndX { get; set; } + [Key(7)] public float EndY { get; set; } + [Key(8)] public float EndZ { get; set; } + [Key(9)] public uint ColorRgba { get; set; } + [Key(10)] public float Ttl { get; set; } + [Key(11)] public byte WeaponClass { get; set; } + [Key(12)] public string WeaponId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class HitImpactEvent : ISimEvent + { + [Key(0)] public long EventId { get; set; } + [Key(1)] public float HitX { get; set; } + [Key(2)] public float HitY { get; set; } + [Key(3)] public float HitZ { get; set; } + [Key(4)] public float NormalX { get; set; } + [Key(5)] public float NormalY { get; set; } + [Key(6)] public float NormalZ { get; set; } + [Key(7)] public float SourceX { get; set; } + [Key(8)] public float SourceY { get; set; } + [Key(9)] public float SourceZ { get; set; } + [Key(10)] public byte TargetKind { get; set; } + [Key(11)] public int TargetId { get; set; } + [Key(12)] public int CellX { get; set; } + [Key(13)] public int CellY { get; set; } + [Key(14)] public byte WeaponClass { get; set; } + [Key(15)] public string WeaponId { get; set; } = string.Empty; + [Key(16)] public bool IsAirburst { get; set; } + [Key(17)] public float Ttl { get; set; } + [Key(18)] public float NewCellArmor { get; set; } + [Key(19)] public float NewCellTemp { get; set; } + [Key(20)] public float NewCoreHp { get; set; } + [Key(21)] public int HitSequence { get; set; } + // Cut 5d/6/7 forward contract fields (Ruling 4) + [Key(22)] public int ShooterId { get; set; } + [Key(23)] public bool IsContenderShooter { get; set; } + [Key(24)] public float ArmorDamage { get; set; } + [Key(25)] public float CoreDamage { get; set; } + [Key(26)] public bool Killed { get; set; } + } + + [MessagePackObject] + public sealed class TerrainStampEvent : ISimEvent + { + [Key(0)] public byte Kind { get; set; } + [Key(1)] public float X { get; set; } + [Key(2)] public float Z { get; set; } + [Key(3)] public float Radius { get; set; } + [Key(4)] public float Depth { get; set; } + [Key(5)] public float Yaw { get; set; } + [Key(6)] public float Length { get; set; } + } + + [MessagePackObject] + public sealed class DropSpawnedEvent : ISimEvent + { + [Key(0)] public int DropId { get; set; } + [Key(1)] public float X { get; set; } + [Key(2)] public float Z { get; set; } + [Key(3)] public string? ChassisId { get; set; } + [Key(4)] public string? ModuleId { get; set; } + } + + [MessagePackObject] + public sealed class DropPickedUpEvent : ISimEvent + { + [Key(0)] public int DropId { get; set; } + [Key(1)] public int ContenderId { get; set; } + } + + [MessagePackObject] + public sealed class MountedSlotDto + { + [Key(0)] public string ModuleId { get; set; } = string.Empty; + [Key(1)] public string HardpointId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class ContenderLoadoutEvent : ISimEvent + { + [Key(0)] public int ContenderId { get; set; } + [Key(1)] public int LoadoutVersion { get; set; } + [Key(2)] public string ChassisId { get; set; } = string.Empty; + [Key(3)] public float CoreHp { get; set; } + [Key(4)] public float MaxCoreHp { get; set; } + [Key(5)] public byte[] ArmorBytes { get; set; } = Array.Empty(); + [Key(6)] public List Mounted { get; set; } = new(); + [Key(7)] public List? CargoIds { get; set; } + } + + [MessagePackObject] + public sealed class EntitySlotControlEvent : ISimEvent + { + [Key(0)] public int ContenderId { get; set; } + [Key(1)] public bool IsHuman { get; set; } + [Key(2)] public string Name { get; set; } = string.Empty; + [Key(3)] public byte Reason { get; set; } + } + + [MessagePackObject] + public sealed class BroadcastLineEvent : ISimEvent + { + [Key(0)] public float Timestamp { get; set; } + [Key(1)] public byte Kind { get; set; } + [Key(2)] public string Text { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class ContenderEliminatedEvent : ISimEvent + { + [Key(0)] public int VictimId { get; set; } + [Key(1)] public int KillerId { get; set; } + [Key(2)] public bool IsSpectatorKiller { get; set; } + [Key(3)] public int KillerKills { get; set; } + [Key(4)] public byte VictimLifecycleByte { get; set; } + } + + [MessagePackObject] + public sealed class SpectatorDestroyedEvent : ISimEvent + { + [Key(0)] public int SpectatorId { get; set; } + [Key(1)] public int KillerContenderId { get; set; } + [Key(2)] public int KillerKills { get; set; } + } + + [MessagePackObject] + public sealed class OverheatAlertEvent : ISimEvent + { + [Key(0)] public int ContenderId { get; set; } + [Key(1)] public bool IsOverheating { get; set; } + } + + [MessagePackObject] + public sealed class ContenderInitialDto + { + [Key(0)] public int Id { get; set; } + [Key(1)] public string Name { get; set; } = string.Empty; + [Key(2)] public bool IsHuman { get; set; } + [Key(3)] public float X { get; set; } + [Key(4)] public float Y { get; set; } + [Key(5)] public float Z { get; set; } + [Key(6)] public float Yaw { get; set; } + [Key(7)] public int Kills { get; set; } + [Key(8)] public ContenderLoadoutEvent Loadout { get; set; } = new(); + [Key(9)] public byte LifecycleByte { get; set; } + [Key(10)] public byte RespawnsRemaining { get; set; } + [Key(11)] public byte SquadId { get; set; } + } + + [MessagePackObject] + public sealed class OrbitalPodDto + { + [Key(0)] public int PodId { get; set; } + [Key(1)] public byte PodKind { get; set; } + [Key(2)] public byte Phase { get; set; } + [Key(3)] public int WaveIndex { get; set; } + [Key(4)] public int ContenderId { get; set; } = -1; + [Key(5)] public float X { get; set; } + [Key(6)] public float Y { get; set; } + [Key(7)] public float Z { get; set; } + [Key(8)] public float VelX { get; set; } + [Key(9)] public float VelY { get; set; } + [Key(10)] public float VelZ { get; set; } + [Key(11)] public float Yaw { get; set; } + [Key(12)] public string? ChassisId { get; set; } + [Key(13)] public string? ModuleId { get; set; } + } + + [MessagePackObject] + public sealed class SpectatorInitialDto + { + [Key(0)] public int Id { get; set; } + [Key(1)] public byte Tier { get; set; } + [Key(2)] public byte Stance { get; set; } + [Key(3)] public float X { get; set; } + [Key(4)] public float Y { get; set; } + [Key(5)] public float Z { get; set; } + [Key(6)] public float Yaw { get; set; } + [Key(7)] public string ChassisId { get; set; } = string.Empty; + [Key(8)] public float CoreHp { get; set; } + [Key(9)] public float MaxCoreHp { get; set; } + [Key(10)] public byte[] ArmorBytes { get; set; } = Array.Empty(); + [Key(11)] public List Mounted { get; set; } = new(); + } + + [MessagePackObject] + public sealed class GroundDropDto + { + [Key(0)] public int Id { get; set; } + [Key(1)] public float X { get; set; } + [Key(2)] public float Z { get; set; } + [Key(3)] public string? ChassisId { get; set; } + [Key(4)] public string? ModuleId { get; set; } + [Key(5)] public bool PickedUp { get; set; } + } + + [MessagePackObject] + public sealed class InitialMatchStateDto + { + [Key(0)] public uint MatchGeneration { get; set; } + [Key(1)] public int Seed { get; set; } + [Key(2)] public byte MapKind { get; set; } + [Key(3)] public float SimTime { get; set; } + [Key(4)] public float SafeRadius { get; set; } + [Key(5)] public byte Phase { get; set; } + [Key(6)] public int? WinnerContenderId { get; set; } + [Key(7)] public List Contenders { get; set; } = new(); + [Key(8)] public List Spectators { get; set; } = new(); + [Key(9)] public List GroundDrops { get; set; } = new(); + [Key(10)] public List TerrainStamps { get; set; } = new(); + [Key(11)] public int ConnectedHumans { get; set; } + [Key(12)] public int CurrentWaveIndex { get; set; } + [Key(13)] public bool RespawnCutoffReached { get; set; } + [Key(14)] public List ActivePods { get; set; } = new(); + [Key(15)] public LobbySnapshotDto? Lobby { get; set; } + [Key(16)] public byte SquadSize { get; set; } = 1; + [Key(17)] public byte[]? ContenderSquadIds { get; set; } + [Key(18)] public byte[]? PersistentScars { get; set; } + } + + [MessagePackObject] + public sealed class LobbySlotDto + { + [Key(0)] public int SlotId { get; set; } + [Key(1)] public string Callsign { get; set; } = string.Empty; + [Key(2)] public bool IsHuman { get; set; } + [Key(3)] public bool IsReady { get; set; } + [Key(4)] public byte SquadId { get; set; } + } + + [MessagePackObject] + public sealed class LobbySnapshotDto + { + [Key(0)] public int? HostSlotId { get; set; } + [Key(1)] public int MinHumansToAutoStart { get; set; } = 1; + [Key(2)] public float? CountdownSeconds { get; set; } + [Key(3)] public bool ForceLaunched { get; set; } + [Key(4)] public byte SelectedMap { get; set; } + [Key(5)] public int SelectedSeed { get; set; } + [Key(6)] public List Slots { get; set; } = new(); + [Key(7)] public byte SquadSize { get; set; } = 3; + } + + [MessagePackObject] + public sealed class MatchStartedEvent : ISimEvent + { + [Key(0)] public uint MatchGeneration { get; set; } + [Key(1)] public byte MapKind { get; set; } + [Key(2)] public int Seed { get; set; } + } + + [MessagePackObject] + public sealed class MatchResetEvent : ISimEvent + { + [Key(0)] public uint MatchGeneration { get; set; } + [Key(1)] public int Seed { get; set; } + [Key(2)] public byte MapKind { get; set; } + [Key(3)] public int AssignedContenderId { get; set; } + [Key(4)] public InitialMatchStateDto FullInitialState { get; set; } = new(); + } + + [Union(0, typeof(JoinReqMsg))] + [Union(1, typeof(JoinAcceptedMsg))] + [Union(2, typeof(JoinRejectedMsg))] + [Union(3, typeof(LeaveMsg))] + [Union(4, typeof(EquipCargoCmdMsg))] + [Union(5, typeof(NewMatchCmdMsg))] + [Union(6, typeof(SimEventBatchMsg))] + [Union(7, typeof(EntitySyncSnapshotMsg))] + [Union(8, typeof(InteractCmdMsg))] + [Union(9, typeof(LobbyReadyCmdMsg))] + [Union(10, typeof(LobbyConfigCmdMsg))] + [Union(11, typeof(LobbyStartCmdMsg))] + [Union(12, typeof(LobbySnapshotMsg))] + [Union(13, typeof(ClientKeepaliveMsg))] + [Union(14, typeof(LobbySquadCmdMsg))] + [Union(15, typeof(RepairArenaCmdMsg))] + public interface ISchemaWireMessage + { + } + + [MessagePackObject] + public sealed class JoinReqMsg : ISchemaWireMessage + { + [Key(0)] public string Callsign { get; set; } = string.Empty; + [Key(1)] public Guid ReconnectToken { get; set; } + [Key(2)] public string ClientVersion { get; set; } = "rtd-5c"; + } + + [MessagePackObject] + public sealed class JoinAcceptedMsg : ISchemaWireMessage + { + [Key(0)] public uint PeerId { get; set; } + [Key(1)] public Guid ReconnectToken { get; set; } + [Key(2)] public int AssignedContenderId { get; set; } + [Key(3)] public uint MatchGeneration { get; set; } + [Key(4)] public InitialMatchStateDto InitialState { get; set; } = new(); + } + + [MessagePackObject] + public sealed class JoinRejectedMsg : ISchemaWireMessage + { + [Key(0)] public string Reason { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class LeaveMsg : ISchemaWireMessage + { + [Key(0)] public string Reason { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class EquipCargoCmdMsg : ISchemaWireMessage + { + [Key(0)] public uint ReqSeq { get; set; } + [Key(1)] public int CargoIndex { get; set; } + [Key(2)] public string HardpointId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class NewMatchCmdMsg : ISchemaWireMessage + { + [Key(0)] public uint ReqSeq { get; set; } + [Key(1)] public int Seed { get; set; } + [Key(2)] public byte MapKind { get; set; } + } + + [MessagePackObject] + public sealed class InteractCmdMsg : ISchemaWireMessage + { + [Key(0)] public ushort ReqSeq { get; set; } + } + + [MessagePackObject] + public sealed class SimEventBatchMsg : ISchemaWireMessage + { + [Key(0)] public ulong BatchSeq { get; set; } + [Key(1)] public uint SimTick { get; set; } + [Key(2)] public float SimTime { get; set; } + [Key(3)] public uint MatchGeneration { get; set; } + [Key(4)] public List Events { get; set; } = new(); + } + + [MessagePackObject] + public sealed class EntitySyncSnapshotMsg : ISchemaWireMessage + { + [Key(0)] public bool IsContender { get; set; } + [Key(1)] public int EntityId { get; set; } + [Key(2)] public bool Alive { get; set; } + [Key(3)] public float PosX { get; set; } + [Key(4)] public float PosY { get; set; } + [Key(5)] public float PosZ { get; set; } + [Key(6)] public float Yaw { get; set; } + [Key(7)] public float CoreHp { get; set; } + [Key(8)] public float MaxCoreHp { get; set; } + [Key(9)] public byte[] ArmorBytes { get; set; } = Array.Empty(); + [Key(10)] public ContenderLoadoutEvent? ContenderLoadout { get; set; } + } + + [MessagePackObject] + public sealed class LobbyReadyCmdMsg : ISchemaWireMessage + { + [Key(0)] public uint ReqSeq { get; set; } + [Key(1)] public bool IsReady { get; set; } + } + + [MessagePackObject] + public sealed class LobbyConfigCmdMsg : ISchemaWireMessage + { + [Key(0)] public uint ReqSeq { get; set; } + [Key(1)] public int Seed { get; set; } + [Key(2)] public byte MapKind { get; set; } + [Key(3)] public byte SquadSize { get; set; } = 3; + } + + [MessagePackObject] + public sealed class LobbySquadCmdMsg : ISchemaWireMessage + { + [Key(0)] public uint ReqSeq { get; set; } + [Key(1)] public byte TargetSquadId { get; set; } + } + + [MessagePackObject] + public sealed class LobbyStartCmdMsg : ISchemaWireMessage + { + [Key(0)] public uint ReqSeq { get; set; } + } + + [MessagePackObject] + public sealed class LobbySnapshotMsg : ISchemaWireMessage + { + [Key(0)] public uint MatchGeneration { get; set; } + [Key(1)] public LobbySnapshotDto Snapshot { get; set; } = new(); + } + + [MessagePackObject] + public sealed class ArenaRepairEvent : ISimEvent + { + [Key(0)] public uint LedgerRevision { get; set; } + } + + [MessagePackObject] + public sealed class RepairArenaCmdMsg : ISchemaWireMessage + { + [Key(0)] public uint ReqSeq { get; set; } + } + + [MessagePackObject] + public sealed class ClientKeepaliveMsg : ISchemaWireMessage + { + [Key(0)] public uint ClientSendMs { get; set; } + } +} diff --git a/src/RustToDust.Core/SionMapLoader.cs b/src/RustToDust.Core/SionMapLoader.cs new file mode 100644 index 0000000..6b01875 --- /dev/null +++ b/src/RustToDust.Core/SionMapLoader.cs @@ -0,0 +1,612 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Numerics; +using System.Text.Json; + +namespace RustToDust.Core +{ + public sealed record SionTileMeta( + int Tx, + int Tz, + string Lod2RelativePath, + string Lod1RelativePath, + string CollisionRelativePath, + int BuildingCount, + Vector3 Center, + Vector3 BoundsMin, + Vector3 BoundsMax); + + public sealed record SionMetadata( + string Name, + string Attribution, + float SizeMeters, + int TileGrid, + float TileSizeMeters, + int GridRes, + float CellSizeMeters, + float MinY, + float MaxY, + string SurfaceTexture, + IReadOnlyList Tiles, + string DemAssetHash = "", + string HeightmapFile = "heightmap_05m.u16z", + float HeightmapMinY = 0f, + float HeightmapScale = 1f, + string SurfaceMaskTexture = "terrain_surface_mask.png", + int BuildingTileGrid = 6, + float BuildingTileSizeMeters = 512f); + + public readonly record struct SionBuildingAabb( + string Id, + string Name, + string Class, + string ArchStyle, + int TileX, + int TileZ, + float CenterX, + float CenterY, + float CenterZ, + float HalfX, + float HalfY, + float HalfZ, + float GroundY, + float RoofY) + { + public bool ContainsXz(float x, float z, float padding = 0f) => + MathF.Abs(x - CenterX) <= HalfX + padding && + MathF.Abs(z - CenterZ) <= HalfZ + padding; + } + + public sealed class SionCollisionMesh + { + public SionCollisionMesh(int tx, int tz, Vector3[] vertices, int[] indices, Vector3 boundsMin, Vector3 boundsMax) + { + Tx = tx; + Tz = tz; + Vertices = vertices; + Indices = indices; + BoundsMin = boundsMin; + BoundsMax = boundsMax; + } + + public int Tx { get; } + public int Tz { get; } + public Vector3[] Vertices { get; } + public int[] Indices { get; } + public Vector3 BoundsMin { get; } + public Vector3 BoundsMax { get; } + } + + public sealed class SionMapData + { + private const int SpatialGridRes = 64; + + private readonly ushort[] _baseDem; + private readonly SionBuildingAabb[] _buildings; + private readonly List[] _cellBuildings; + private readonly float[] _cellMinGroundY; + private readonly float[] _cellMaxRoofY; + private readonly float _halfExtent; + private readonly float _cellSize; + + internal SionMapData( + string directoryPath, + SionMetadata metadata, + ushort[] baseDem, + float baseDemMinY, + float baseDemScale, + SionBuildingAabb[] buildings, + SionCollisionMesh[] collisionMeshes) + { + DirectoryPath = directoryPath; + Metadata = metadata; + _baseDem = baseDem; + BaseDemMinY = baseDemMinY; + BaseDemScale = baseDemScale; + AssetFingerprint = !string.IsNullOrWhiteSpace(metadata.DemAssetHash) + ? $"sion:{metadata.DemAssetHash}" + : $"sion:{metadata.GridRes}:{metadata.CellSizeMeters:F3}"; + _buildings = buildings; + CollisionMeshes = collisionMeshes; + + _halfExtent = metadata.SizeMeters * 0.5f; + _cellSize = metadata.SizeMeters / SpatialGridRes; + + int cellCount = SpatialGridRes * SpatialGridRes; + _cellBuildings = new List[cellCount]; + _cellMinGroundY = new float[cellCount]; + _cellMaxRoofY = new float[cellCount]; + for (int i = 0; i < cellCount; i++) + { + _cellBuildings[i] = new List(2); + _cellMinGroundY[i] = float.PositiveInfinity; + _cellMaxRoofY[i] = float.NegativeInfinity; + } + + for (int bIdx = 0; bIdx < _buildings.Length; bIdx++) + { + ref readonly var b = ref _buildings[bIdx]; + WorldToCell(b.CenterX - b.HalfX, b.CenterZ - b.HalfZ, out int minCx, out int minCz); + WorldToCell(b.CenterX + b.HalfX, b.CenterZ + b.HalfZ, out int maxCx, out int maxCz); + for (int cz = minCz; cz <= maxCz; cz++) + { + for (int cx = minCx; cx <= maxCx; cx++) + { + int cell = cz * SpatialGridRes + cx; + _cellBuildings[cell].Add(bIdx); + if (b.GroundY < _cellMinGroundY[cell]) _cellMinGroundY[cell] = b.GroundY; + if (b.RoofY > _cellMaxRoofY[cell]) _cellMaxRoofY[cell] = b.RoofY; + } + } + } + } + + public string DirectoryPath { get; } + public SionMetadata Metadata { get; } + public ushort[] BaseDem => _baseDem; + public float BaseDemMinY { get; } + public float BaseDemScale { get; } + public string AssetFingerprint { get; } + public float SampleBaseDemAtIndex(int index) => BaseDemMinY + _baseDem[index] * BaseDemScale; + public IReadOnlyList Buildings => _buildings; + public IReadOnlyList CollisionMeshes { get; } + + public bool IsInsideAnyBuildingXz(float x, float z, float padding = 0f) + { + float pad = MathF.Max(0f, padding); + WorldToCell(x - pad, z - pad, out int minCx, out int minCz); + WorldToCell(x + pad, z + pad, out int maxCx, out int maxCz); + + for (int cz = minCz; cz <= maxCz; cz++) + { + for (int cx = minCx; cx <= maxCx; cx++) + { + var list = _cellBuildings[cz * SpatialGridRes + cx]; + for (int i = 0; i < list.Count; i++) + { + if (_buildings[list[i]].ContainsXz(x, z, pad)) + { + return true; + } + } + } + } + return false; + } + + public bool TryGetBuildingAt(float x, float z, float padding, out SionBuildingAabb building) + { + float pad = MathF.Max(0f, padding); + WorldToCell(x - pad, z - pad, out int minCx, out int minCz); + WorldToCell(x + pad, z + pad, out int maxCx, out int maxCz); + + bool found = false; + building = default; + float bestRoofY = float.NegativeInfinity; + + for (int cz = minCz; cz <= maxCz; cz++) + { + for (int cx = minCx; cx <= maxCx; cx++) + { + var list = _cellBuildings[cz * SpatialGridRes + cx]; + for (int i = 0; i < list.Count; i++) + { + ref readonly var b = ref _buildings[list[i]]; + if (b.ContainsXz(x, z, pad) && b.RoofY > bestRoofY) + { + bestRoofY = b.RoofY; + building = b; + found = true; + } + } + } + } + return found; + } + + public bool IntersectsAnyBuildingAabb( + float ox, float oy, float oz, + float dx, float dy, float dz, + float maxDist) + { + if (_buildings.Length == 0 || maxDist <= 0f) + { + return false; + } + + // Clip ray to arena XZ bounds so DDA stays strictly inside [0, SpatialGridRes - 1]. + float tMin = 0f; + float tMax = maxDist; + if (!SlabClip(ox, dx, -_halfExtent, _halfExtent, ref tMin, ref tMax)) return false; + if (!SlabClip(oz, dz, -_halfExtent, _halfExtent, ref tMin, ref tMax)) return false; + + float sx = ox + dx * tMin; + float sz = oz + dz * tMin; + WorldToCell(sx, sz, out int cx, out int cz); + + float ex = ox + dx * tMax; + float ez = oz + dz * tMax; + WorldToCell(ex, ez, out int endCx, out int endCz); + + int stepX = dx > 1e-6f ? 1 : (dx < -1e-6f ? -1 : 0); + int stepZ = dz > 1e-6f ? 1 : (dz < -1e-6f ? -1 : 0); + + float tDeltaX = stepX != 0 ? _cellSize / MathF.Abs(dx) : float.PositiveInfinity; + float tDeltaZ = stepZ != 0 ? _cellSize / MathF.Abs(dz) : float.PositiveInfinity; + + float nextBoundaryX = -_halfExtent + (cx + (stepX > 0 ? 1 : 0)) * _cellSize; + float nextBoundaryZ = -_halfExtent + (cz + (stepZ > 0 ? 1 : 0)) * _cellSize; + + float tMaxX = stepX != 0 ? tMin + MathF.Max(0f, (nextBoundaryX - sx) / dx) : float.PositiveInfinity; + float tMaxZ = stepZ != 0 ? tMin + MathF.Max(0f, (nextBoundaryZ - sz) / dz) : float.PositiveInfinity; + + float curT = tMin; + int maxSteps = SpatialGridRes * 2 + 4; + for (int iter = 0; iter < maxSteps; iter++) + { + float nextT = MathF.Min(tMax, MathF.Min(tMaxX, tMaxZ)); + int cellIdx = cz * SpatialGridRes + cx; + var list = _cellBuildings[cellIdx]; + if (list.Count > 0) + { + float y0 = oy + dy * curT; + float y1 = oy + dy * nextT; + float segMinY = MathF.Min(y0, y1); + float segMaxY = MathF.Max(y0, y1); + if (segMaxY >= _cellMinGroundY[cellIdx] - 0.5f && segMinY <= _cellMaxRoofY[cellIdx] + 0.5f) + { + for (int i = 0; i < list.Count; i++) + { + ref readonly var b = ref _buildings[list[i]]; + if (RayIntersectsBuilding(ox, oy, oz, dx, dy, dz, maxDist, in b)) + { + return true; + } + } + } + } + + if (cx == endCx && cz == endCz) + { + break; + } + + if (tMaxX <= tMaxZ) + { + curT = tMaxX; + tMaxX += tDeltaX; + cx += stepX; + } + else + { + curT = tMaxZ; + tMaxZ += tDeltaZ; + cz += stepZ; + } + + if (cx < 0 || cx >= SpatialGridRes || cz < 0 || cz >= SpatialGridRes || curT > tMax) + { + break; + } + } + + return false; + } + + private void WorldToCell(float x, float z, out int cx, out int cz) + { + float nx = (x + _halfExtent) / _cellSize; + float nz = (z + _halfExtent) / _cellSize; + cx = Math.Clamp((int)MathF.Floor(nx), 0, SpatialGridRes - 1); + cz = Math.Clamp((int)MathF.Floor(nz), 0, SpatialGridRes - 1); + } + + private static bool RayIntersectsBuilding( + float ox, float oy, float oz, + float dx, float dy, float dz, + float maxDist, + in SionBuildingAabb b) + { + float tMin = 0f; + float tMax = maxDist; + if (!SlabClip(ox, dx, b.CenterX - b.HalfX, b.CenterX + b.HalfX, ref tMin, ref tMax)) return false; + if (!SlabClip(oy, dy, b.GroundY, b.RoofY, ref tMin, ref tMax)) return false; + if (!SlabClip(oz, dz, b.CenterZ - b.HalfZ, b.CenterZ + b.HalfZ, ref tMin, ref tMax)) return false; + return tMax >= tMin; + } + + private static bool SlabClip(float o, float d, float minB, float maxB, ref float tMin, ref float tMax) + { + if (MathF.Abs(d) < 1e-6f) + { + return o >= minB && o <= maxB; + } + float invD = 1f / d; + float t1 = (minB - o) * invD; + float t2 = (maxB - o) * invD; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + return tMax >= tMin; + } + } + + public static class SionMapLoader + { + private static readonly object CacheLock = new(); + private static readonly Dictionary Cache = new(StringComparer.OrdinalIgnoreCase); + + public static string LocateSionDirectory() => + AssetPathResolver.LocateSubdirectory( + Path.Combine("maps", "sion"), + IsValidSionDirectory, + "containing metadata.json and heightmap_05m.u16z"); + + private static bool IsValidSionDirectory(string dir) => + Directory.Exists(dir) && + File.Exists(Path.Combine(dir, "metadata.json")) && + File.Exists(Path.Combine(dir, "heightmap_05m.u16z")) && + File.Exists(Path.Combine(dir, "buildings_manifest.json")); + + public static SionMapData Load(string? sionDirectory = null) + { + string root = Path.GetFullPath(sionDirectory ?? LocateSionDirectory()); + lock (CacheLock) + { + if (Cache.TryGetValue(root, out var cached)) + { + return cached; + } + } + + var meta = LoadMetadata(Path.Combine(root, "metadata.json")); + string hmFile = string.IsNullOrWhiteSpace(meta.HeightmapFile) ? "heightmap_05m.u16z" : meta.HeightmapFile; + ushort[] baseDem = LoadHeightmapU16z( + Path.Combine(root, hmFile), + meta.GridRes, + out float demMinY, + out float demScale); + SionBuildingAabb[] buildings = LoadBuildingsManifest(Path.Combine(root, "buildings_manifest.json")); + var colMeshes = new SionCollisionMesh[meta.Tiles.Count]; + for (int i = 0; i < meta.Tiles.Count; i++) + { + var t = meta.Tiles[i]; + string colPath = Path.Combine(root, t.CollisionRelativePath.Replace('/', Path.DirectorySeparatorChar)); + colMeshes[i] = LoadRcolFile(colPath, t.Tx, t.Tz); + } + + var data = new SionMapData(root, meta, baseDem, demMinY, demScale, buildings, colMeshes); + lock (CacheLock) + { + Cache[root] = data; + } + return data; + } + + private static SionMetadata LoadMetadata(string path) + { + using var stream = File.OpenRead(path); + using var doc = JsonDocument.Parse(stream); + var r = doc.RootElement; + + var tilesElem = r.GetProperty("tiles"); + var tiles = new List(tilesElem.GetArrayLength()); + foreach (var te in tilesElem.EnumerateArray()) + { + tiles.Add(new SionTileMeta( + Tx: te.GetProperty("tx").GetInt32(), + Tz: te.GetProperty("tz").GetInt32(), + Lod2RelativePath: te.GetProperty("lod2").GetString() ?? "", + Lod1RelativePath: te.GetProperty("lod1").GetString() ?? "", + CollisionRelativePath: te.GetProperty("collision").GetString() ?? "", + BuildingCount: te.GetProperty("buildingCount").GetInt32(), + Center: ReadVec3(te.GetProperty("center")), + BoundsMin: ReadVec3(te.GetProperty("boundsMin")), + BoundsMax: ReadVec3(te.GetProperty("boundsMax")))); + } + + return new SionMetadata( + Name: r.GetProperty("name").GetString() ?? "Sion", + Attribution: r.GetProperty("attribution").GetString() ?? "Federal Office of Topography swisstopo", + SizeMeters: r.GetProperty("sizeMeters").GetSingle(), + TileGrid: r.GetProperty("tileGrid").GetInt32(), + TileSizeMeters: r.GetProperty("tileSizeMeters").GetSingle(), + GridRes: r.GetProperty("gridRes").GetInt32(), + CellSizeMeters: r.GetProperty("cellSizeMeters").GetSingle(), + MinY: r.GetProperty("minY").GetSingle(), + MaxY: r.GetProperty("maxY").GetSingle(), + SurfaceTexture: r.GetProperty("surfaceTexture").GetString() ?? "terrain_surface.png", + Tiles: tiles, + DemAssetHash: r.TryGetProperty("demAssetHash", out var dh) ? (dh.GetString() ?? "") : "", + HeightmapFile: r.TryGetProperty("heightmapFile", out var hf) ? (hf.GetString() ?? "heightmap_05m.u16z") : "heightmap_05m.u16z", + HeightmapMinY: r.TryGetProperty("heightmapMinY", out var hmin) ? hmin.GetSingle() : 0f, + HeightmapScale: r.TryGetProperty("heightmapScale", out var hsc) ? hsc.GetSingle() : 1f, + SurfaceMaskTexture: r.TryGetProperty("surfaceMaskTexture", out var sm) ? (sm.GetString() ?? "terrain_surface_mask.png") : "terrain_surface_mask.png", + BuildingTileGrid: r.TryGetProperty("buildingTileGrid", out var btg) ? btg.GetInt32() : 6, + BuildingTileSizeMeters: r.TryGetProperty("buildingTileSizeMeters", out var bts) ? bts.GetSingle() : 512f); + } + + private static ushort[] LoadHeightmapU16z(string path, int expectedGridRes, out float minY, out float scale) + { + byte[] fileBytes = File.ReadAllBytes(path); + if (fileBytes.Length < 24) + { + throw new InvalidDataException($"Heightmap file '{path}' too small ({fileBytes.Length} bytes)."); + } + + ReadOnlySpan hdr = fileBytes.AsSpan(0, 24); + if (hdr[0] != (byte)'R' || hdr[1] != (byte)'D' || hdr[2] != (byte)'H' || hdr[3] != (byte)'M') + { + throw new InvalidDataException($"Invalid RDHM magic in '{path}'."); + } + + uint version = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4)); + if (version != 2) + { + throw new InvalidDataException($"Unsupported RDHM version {version} in '{path}'."); + } + + int gridRes = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(8, 4))); + if (gridRes != expectedGridRes) + { + throw new InvalidDataException($"RDHM gridRes mismatch in '{path}': header={gridRes}, metadata={expectedGridRes}."); + } + + minY = BinaryPrimitives.ReadSingleLittleEndian(hdr.Slice(12, 4)); + scale = BinaryPrimitives.ReadSingleLittleEndian(hdr.Slice(16, 4)); + int rawByteCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(20, 4))); + int expectedSamples = gridRes * gridRes; + if (rawByteCount != expectedSamples * 2) + { + throw new InvalidDataException($"RDHM rawByteCount mismatch in '{path}': {rawByteCount} != {expectedSamples * 2}."); + } + + byte[] raw = new byte[rawByteCount]; + using (var ms = new MemoryStream(fileBytes, 24, fileBytes.Length - 24, writable: false)) + using (var zlib = new ZLibStream(ms, CompressionMode.Decompress)) + { + int totalRead = 0; + while (totalRead < rawByteCount) + { + int read = zlib.Read(raw, totalRead, rawByteCount - totalRead); + if (read <= 0) + { + throw new InvalidDataException($"Unexpected EOF decompressing RDHM payload in '{path}' at {totalRead}/{rawByteCount}."); + } + totalRead += read; + } + } + + var heights = new ushort[expectedSamples]; + ReadOnlySpan span = raw; + for (int r = 0; r < gridRes; r++) + { + int rowStart = r * gridRes; + ushort pred = r > 0 ? heights[(r - 1) * gridRes] : (ushort)0; + for (int c = 0; c < gridRes; c++) + { + int idx = rowStart + c; + ushort zz = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(idx * 2, 2)); + short d = unchecked((short)((zz >> 1) ^ -(zz & 1))); + ushort val = unchecked((ushort)(pred + d)); + heights[idx] = val; + pred = val; + } + } + return heights; + } + + private static SionBuildingAabb[] LoadBuildingsManifest(string path) + { + using var stream = File.OpenRead(path); + using var doc = JsonDocument.Parse(stream); + var arr = doc.RootElement.GetProperty("buildings"); + var result = new SionBuildingAabb[arr.GetArrayLength()]; + int idx = 0; + foreach (var b in arr.EnumerateArray()) + { + var tile = b.GetProperty("tile"); + var center = b.GetProperty("center"); + var size = b.GetProperty("size"); + + result[idx++] = new SionBuildingAabb( + Id: b.GetProperty("id").GetString() ?? "", + Name: b.GetProperty("name").GetString() ?? "", + Class: b.GetProperty("class").GetString() ?? "", + ArchStyle: b.GetProperty("archStyle").GetString() ?? "", + TileX: tile[0].GetInt32(), + TileZ: tile[1].GetInt32(), + CenterX: center[0].GetSingle(), + CenterY: center[1].GetSingle(), + CenterZ: center[2].GetSingle(), + HalfX: size[0].GetSingle() * 0.5f, + HalfY: size[1].GetSingle() * 0.5f, + HalfZ: size[2].GetSingle() * 0.5f, + GroundY: b.GetProperty("groundY").GetSingle(), + RoofY: b.GetProperty("roofY").GetSingle()); + } + return result; + } + + public static SionCollisionMesh LoadRcolFile(string path, int expectedTx = -1, int expectedTz = -1) + { + byte[] raw = File.ReadAllBytes(path); + if (raw.Length < 48) + { + throw new InvalidDataException($"RCOL file '{path}' too small ({raw.Length} bytes)."); + } + + ReadOnlySpan s = raw; + if (s[0] != (byte)'R' || s[1] != (byte)'C' || s[2] != (byte)'O' || s[3] != (byte)'L') + { + throw new InvalidDataException($"Invalid RCOL magic in '{path}'."); + } + + uint version = BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(4, 4)); + if (version != 1) + { + throw new InvalidDataException($"Unsupported RCOL version {version} in '{path}'."); + } + + int tx = BinaryPrimitives.ReadInt32LittleEndian(s.Slice(8, 4)); + int tz = BinaryPrimitives.ReadInt32LittleEndian(s.Slice(12, 4)); + if ((expectedTx >= 0 && tx != expectedTx) || (expectedTz >= 0 && tz != expectedTz)) + { + throw new InvalidDataException($"RCOL tile mismatch in '{path}': header=({tx},{tz}), expected=({expectedTx},{expectedTz})."); + } + + int vertexCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(16, 4))); + int indexCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(20, 4))); + if (vertexCount < 3 || indexCount < 3 || indexCount % 3 != 0) + { + throw new InvalidDataException($"Invalid RCOL counts in '{path}': verts={vertexCount}, indices={indexCount}."); + } + + var bmin = new Vector3( + BinaryPrimitives.ReadSingleLittleEndian(s.Slice(24, 4)), + BinaryPrimitives.ReadSingleLittleEndian(s.Slice(28, 4)), + BinaryPrimitives.ReadSingleLittleEndian(s.Slice(32, 4))); + var bmax = new Vector3( + BinaryPrimitives.ReadSingleLittleEndian(s.Slice(36, 4)), + BinaryPrimitives.ReadSingleLittleEndian(s.Slice(40, 4)), + BinaryPrimitives.ReadSingleLittleEndian(s.Slice(44, 4))); + + int expectedBytes = 48 + vertexCount * 12 + indexCount * 4; + if (raw.Length != expectedBytes) + { + throw new InvalidDataException($"RCOL byte length mismatch in '{path}': expected {expectedBytes}, got {raw.Length}."); + } + + var vertices = new Vector3[vertexCount]; + int offset = 48; + for (int i = 0; i < vertexCount; i++) + { + float x = BinaryPrimitives.ReadSingleLittleEndian(s.Slice(offset, 4)); + float y = BinaryPrimitives.ReadSingleLittleEndian(s.Slice(offset + 4, 4)); + float z = BinaryPrimitives.ReadSingleLittleEndian(s.Slice(offset + 8, 4)); + vertices[i] = new Vector3(x, y, z); + offset += 12; + } + + var indices = new int[indexCount]; + for (int i = 0; i < indexCount; i++) + { + int idx = BinaryPrimitives.ReadInt32LittleEndian(s.Slice(offset, 4)); + if ((uint)idx >= (uint)vertexCount) + { + throw new InvalidDataException($"RCOL index {idx} out of range [0..{vertexCount}) in '{path}'."); + } + indices[i] = idx; + offset += 4; + } + + return new SionCollisionMesh(tx, tz, vertices, indices, bmin, bmax); + } + + private static Vector3 ReadVec3(JsonElement arr) => + new(arr[0].GetSingle(), arr[1].GetSingle(), arr[2].GetSingle()); + } +} diff --git a/src/RustToDust.Core/SpectatorRing.cs b/src/RustToDust.Core/SpectatorRing.cs new file mode 100644 index 0000000..d79f70c --- /dev/null +++ b/src/RustToDust.Core/SpectatorRing.cs @@ -0,0 +1,958 @@ +using System; +using System.Collections.Generic; +using System.Numerics; + +namespace RustToDust.Core +{ + public enum SpectatorTier + { + Tourist, + Patron, + Exemplar + } + + public enum SpectatorStance + { + Neutral, + Cleared, + Provoked + } + + public readonly record struct RingContact(int Id, float X, float Z, bool Alive, float Y = 0f, float HalfHeight = 1f); + + public sealed class SpectatorState + { + public SpectatorState( + int id, + SpectatorTier tier, + ChassisGrid grid, + float ringAngle, + float ringOffset, + float radarSignature, + float aimSpreadRad, + float maxSpeed, + float preferredRange) + { + Id = id; + Tier = tier; + Grid = grid; + RingAngle = ringAngle; + RingOffset = ringOffset; + RadarSignature = radarSignature; + AimSpreadRad = aimSpreadRad; + MaxSpeed = maxSpeed; + PreferredRange = preferredRange; + } + + public int Id { get; } + public SpectatorTier Tier { get; } + public ChassisGrid Grid { get; } + public float RingAngle { get; set; } + public float RingOffset { get; } + public float RadarSignature { get; } + public float AimSpreadRad { get; } + public float MaxSpeed { get; } + public float PreferredRange { get; } + + public SpectatorStance Stance { get; set; } = SpectatorStance.Neutral; + public int? TargetContenderId { get; set; } + public bool BroadcastWakeupEmitted { get; set; } + + public bool HasTargetLos { get; set; } + public float LastKnownTargetX { get; set; } + public float LastKnownTargetY { get; set; } + public float LastKnownTargetZ { get; set; } + public float TimeSinceLastSeen { get; set; } = float.PositiveInfinity; + + public bool HasNeutralAnchor { get; set; } + public float NeutralAnchorX { get; set; } + public float NeutralAnchorZ { get; set; } + public float NeutralAnchorSafeRadius { get; set; } + + public float X { get; set; } + public float Y { get; set; } + public float Z { get; set; } + public float Yaw { get; set; } + + public float PrevX { get; set; } + public float PrevY { get; set; } + public float PrevZ { get; set; } + public float PrevRotX { get; set; } + public float PrevRotY { get; set; } + public float PrevRotZ { get; set; } + public float PrevRotW { get; set; } = 1f; + public float CurrRotX { get; set; } + public float CurrRotY { get; set; } + public float CurrRotZ { get; set; } + public float CurrRotW { get; set; } = 1f; + public float VelX { get; set; } + public float VelY { get; set; } + public float VelZ { get; set; } + + public PhysicalAimTracker AimTracker; + public float DynamicAimSpreadRad { get; set; } = 0.012f; + public float AimX { get; set; } + public float AimY { get; set; } + public float AimZ { get; set; } + public bool FireCmd { get; set; } + + public bool Alive => !Grid.IsDestroyed; + + public void SnapPreviousPose() + { + PrevX = X; + PrevY = Y; + PrevZ = Z; + PrevRotX = CurrRotX; + PrevRotY = CurrRotY; + PrevRotZ = CurrRotZ; + PrevRotW = CurrRotW; + } + + public void ResetAimTracker(float yaw) + { + AimTracker.Reset(yaw); + DynamicAimSpreadRad = AimTracker.DynamicSpreadRad; + AimX = X + MathF.Sin(yaw) * 25f; + AimY = Y; + AimZ = Z + MathF.Cos(yaw) * 25f; + FireCmd = false; + } + } + + public sealed class SpectatorRing + { + public const float InitialRadius = 560f; + public const float MinRadius = 85f; + public const float GraceDuration = 45f; + public const float ShrinkDuration = 360f; + public const int DefaultSpectatorCount = 56; + public const float TargetMemoryDuration = 4.0f; + + private sealed class ContenderAwareness + { + public bool HasKnownPos; + public float LastKnownX; + public float LastKnownY; + public float LastKnownZ; + public float TimeSinceSeen = TargetMemoryDuration + 1f; + } + + private readonly List _spectators = new(); + private readonly Dictionary _aliveById = new(); + private readonly Dictionary _awarenessByContender = new(); + + public SpectatorRing( + int seed = 1337, + int count = DefaultSpectatorCount, + float initialRadius = InitialRadius, + float minRadius = MinRadius, + float arenaHalfExtent = TerrainField.HalfExtent) + { + var rng = new Random(seed); + StartRadius = initialRadius; + EndRadius = minRadius; + ArenaHalfExtent = arenaHalfExtent; + SafeRadius = StartRadius; + SpawnRing(rng, count); + } + + public float StartRadius { get; } + public float EndRadius { get; } + public float ArenaHalfExtent { get; } + public float SafeRadius { get; private set; } + public IReadOnlyList Spectators => _spectators; + + public void SetReplicatedSafeRadius(float radius) => SafeRadius = radius; + + public void UpdateSafeRadius(float matchTime) + { + if (matchTime <= GraceDuration) + { + SafeRadius = StartRadius; + return; + } + + float t = Math.Clamp((matchTime - GraceDuration) / ShrinkDuration, 0f, 1f); + SafeRadius = StartRadius + (EndRadius - StartRadius) * t; + } + + public void UpdateClearance(ReadOnlySpan contenders) => + UpdateClearance(contenders, 0f, null); + + public void UpdateClearance( + ReadOnlySpan contenders, + float dt, + Func? hasLos, + int tickIndex = -1) + { + _aliveById.Clear(); + for (int i = 0; i < contenders.Length; i++) + { + _aliveById[contenders[i].Id] = contenders[i].Alive; + } + + // Step 1: Update per-contender ring awareness ONLY from spectators with live LOS. + for (int c = 0; c < contenders.Length; c++) + { + var contender = contenders[c]; + var aw = GetOrCreateAwareness(contender.Id); + if (!contender.Alive || ComputeOutsideDist(contender) <= 0f) + { + aw.HasKnownPos = false; + aw.TimeSinceSeen = TargetMemoryDuration + 1f; + continue; + } + + aw.TimeSinceSeen += dt; + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (!spec.Alive) + { + continue; + } + + if (hasLos is null || hasLos(spec, contender)) + { + aw.HasKnownPos = true; + aw.LastKnownX = contender.X; + aw.LastKnownY = contender.Y; + aw.LastKnownZ = contender.Z; + aw.TimeSinceSeen = 0f; + break; + } + } + } + + // Step 2: Maintain existing Provoked and Cleared assignments sticky while target is valid. + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (!spec.Alive) + { + ResetToNeutral(spec); + continue; + } + + if (spec.Stance == SpectatorStance.Provoked) + { + if (!spec.TargetContenderId.HasValue || + !TryFindAliveContact(contenders, spec.TargetContenderId.Value, out var contact)) + { + ResetToNeutral(spec); + } + else + { + UpdateWatcherTracking(spec, contact, dt, hasLos); + } + } + else if (spec.Stance == SpectatorStance.Cleared) + { + if (!spec.TargetContenderId.HasValue || + !TryFindAliveContact(contenders, spec.TargetContenderId.Value, out var contact) || + ComputeOutsideDist(contact) <= 0f) + { + ResetToNeutral(spec); + } + else + { + UpdateWatcherTracking(spec, contact, dt, hasLos); + } + } + else + { + spec.TargetContenderId = null; + spec.HasTargetLos = false; + spec.TimeSinceLastSeen = TargetMemoryDuration + 1f; + } + } + + // Step 3: Balance Cleared assignments per outside contender without reading occluded coords. + for (int c = 0; c < contenders.Length; c++) + { + var contender = contenders[c]; + if (!contender.Alive) + { + continue; + } + + float outsideDist = ComputeOutsideDist(contender); + if (outsideDist <= 0f) + { + continue; + } + + int allowedCleared = Math.Min(8, 1 + (int)(outsideDist / 12f)); + int currentCleared = CountClearedFor(contender.Id); + + // Drop excess if outsideDist shrank (prefer dropping stale no-LOS watchers first). + while (currentCleared > allowedCleared) + { + int dropIdx = FindExcessClearedToDrop(contender.Id); + if (dropIdx < 0) + { + break; + } + ResetToNeutral(_spectators[dropIdx]); + currentCleared--; + } + + // If full with a stale expired no-LOS watcher while a Neutral watcher has live LOS, rotate one slot. + if (currentCleared == allowedCleared && hasLos is not null && AnyNeutralHasLos(contender, hasLos)) + { + int staleIdx = FindStaleNoLosCleared(contender.Id); + if (staleIdx >= 0) + { + ResetToNeutral(_spectators[staleIdx]); + currentCleared--; + } + } + + // Pass 1: Spectators with direct live LOS to the offender (nearest open-LOS watcher first). + while (currentCleared < allowedCleared) + { + int bestIdx = -1; + float bestDistSq = float.PositiveInfinity; + + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (!spec.Alive || spec.Stance != SpectatorStance.Neutral) + { + continue; + } + + float dx = spec.X - contender.X; + float dz = spec.Z - contender.Z; + float d2 = dx * dx + dz * dz; + if (d2 >= bestDistSq) + { + continue; + } + + if (hasLos is not null && !hasLos(spec, contender)) + { + continue; + } + + bestDistSq = d2; + bestIdx = i; + } + + if (bestIdx < 0) + { + break; + } + + var chosen = _spectators[bestIdx]; + chosen.Stance = SpectatorStance.Cleared; + chosen.TargetContenderId = contender.Id; + chosen.HasTargetLos = true; + chosen.LastKnownTargetX = contender.X; + chosen.LastKnownTargetY = contender.Y; + chosen.LastKnownTargetZ = contender.Z; + chosen.TimeSinceLastSeen = 0f; + currentCleared++; + } + + // Pass 2: Reinforce from already-observed LastKnownPos ONLY (never read live occluded contender.X/Z). + if (currentCleared < allowedCleared && + hasLos is not null && + _awarenessByContender.TryGetValue(contender.Id, out var aw) && + aw.HasKnownPos) + { + const float maxPass2RadiusSq = 240f * 240f; + while (currentCleared < allowedCleared) + { + int bestIdx = -1; + float bestDistSq = float.PositiveInfinity; + + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (!spec.Alive || spec.Stance != SpectatorStance.Neutral) + { + continue; + } + + float dx = spec.X - aw.LastKnownX; + float dz = spec.Z - aw.LastKnownZ; + float d2 = dx * dx + dz * dz; + if (d2 <= maxPass2RadiusSq && d2 < bestDistSq) + { + bestDistSq = d2; + bestIdx = i; + } + } + + if (bestIdx < 0) + { + break; + } + + var chosen = _spectators[bestIdx]; + chosen.Stance = SpectatorStance.Cleared; + chosen.TargetContenderId = contender.Id; + chosen.HasTargetLos = false; + chosen.LastKnownTargetX = aw.LastKnownX; + chosen.LastKnownTargetY = aw.LastKnownY; + chosen.LastKnownTargetZ = aw.LastKnownZ; + chosen.TimeSinceLastSeen = aw.TimeSinceSeen; + currentCleared++; + } + } + } + } + + public bool OnSpectatorDamaged( + SpectatorState spectator, + int attackerContenderId, + float? incomingDirX = null, + float? incomingDirZ = null) + { + if (!spectator.Alive) + { + return false; + } + + if (spectator.Stance == SpectatorStance.Neutral || spectator.Stance == SpectatorStance.Cleared) + { + bool sameTargetWithFreshMemory = spectator.TargetContenderId == attackerContenderId && + (spectator.HasTargetLos || spectator.TimeSinceLastSeen < TargetMemoryDuration); + + spectator.Stance = SpectatorStance.Provoked; + spectator.TargetContenderId = attackerContenderId; + + if (!sameTargetWithFreshMemory) + { + spectator.HasTargetLos = false; + if (_awarenessByContender.TryGetValue(attackerContenderId, out var aw) && + aw.HasKnownPos && + aw.TimeSinceSeen < TargetMemoryDuration) + { + spectator.LastKnownTargetX = aw.LastKnownX; + spectator.LastKnownTargetY = aw.LastKnownY; + spectator.LastKnownTargetZ = aw.LastKnownZ; + spectator.TimeSinceLastSeen = aw.TimeSinceSeen; + } + else if (incomingDirX.HasValue && incomingDirZ.HasValue) + { + float dLen = MathF.Sqrt(incomingDirX.Value * incomingDirX.Value + incomingDirZ.Value * incomingDirZ.Value); + float nx = dLen > 1e-4f ? incomingDirX.Value / dLen : MathF.Sin(spectator.Yaw); + float nz = dLen > 1e-4f ? incomingDirZ.Value / dLen : MathF.Cos(spectator.Yaw); + spectator.LastKnownTargetX = spectator.X + nx * 60f; + spectator.LastKnownTargetY = spectator.Y; + spectator.LastKnownTargetZ = spectator.Z + nz * 60f; + spectator.TimeSinceLastSeen = 0.5f; + } + else + { + spectator.LastKnownTargetX = spectator.X + MathF.Sin(spectator.Yaw) * 40f; + spectator.LastKnownTargetY = spectator.Y; + spectator.LastKnownTargetZ = spectator.Z + MathF.Cos(spectator.Yaw) * 40f; + spectator.TimeSinceLastSeen = TargetMemoryDuration; + } + } + return true; + } + + return false; + } + + private ContenderAwareness GetOrCreateAwareness(int contenderId) + { + if (!_awarenessByContender.TryGetValue(contenderId, out var aw)) + { + aw = new ContenderAwareness(); + _awarenessByContender[contenderId] = aw; + } + return aw; + } + + private float ComputeOutsideDist(in RingContact contact) + { + float distFromCenter = MathF.Sqrt(contact.X * contact.X + contact.Z * contact.Z); + return MathF.Max(0f, distFromCenter - SafeRadius); + } + + private static void ResetToNeutral(SpectatorState spec) + { + spec.Stance = SpectatorStance.Neutral; + spec.TargetContenderId = null; + spec.HasTargetLos = false; + spec.TimeSinceLastSeen = TargetMemoryDuration + 1f; + } + + private static void UpdateWatcherTracking( + SpectatorState spec, + in RingContact contact, + float dt, + Func? hasLos) + { + bool los = hasLos is null || hasLos(spec, contact); + if (los) + { + spec.HasTargetLos = true; + spec.LastKnownTargetX = contact.X; + spec.LastKnownTargetY = contact.Y; + spec.LastKnownTargetZ = contact.Z; + spec.TimeSinceLastSeen = 0f; + } + else + { + spec.HasTargetLos = false; + spec.TimeSinceLastSeen += dt; + } + } + + private static bool TryFindAliveContact(ReadOnlySpan contenders, int id, out RingContact contact) + { + for (int i = 0; i < contenders.Length; i++) + { + if (contenders[i].Id == id && contenders[i].Alive) + { + contact = contenders[i]; + return true; + } + } + contact = default; + return false; + } + + private int FindExcessClearedToDrop(int contenderId) + { + int bestIdx = -1; + bool bestNoLos = false; + float bestAge = -1f; + float bestDistSq = -1f; + + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (!spec.Alive || spec.Stance != SpectatorStance.Cleared || spec.TargetContenderId != contenderId) + { + continue; + } + + bool noLos = !spec.HasTargetLos; + float age = spec.TimeSinceLastSeen; + float dx = spec.X - spec.LastKnownTargetX; + float dz = spec.Z - spec.LastKnownTargetZ; + float d2 = dx * dx + dz * dz; + + if (bestIdx < 0 || + (noLos && !bestNoLos) || + (noLos == bestNoLos && (age > bestAge + 1e-4f || (MathF.Abs(age - bestAge) <= 1e-4f && d2 > bestDistSq)))) + { + bestIdx = i; + bestNoLos = noLos; + bestAge = age; + bestDistSq = d2; + } + } + + return bestIdx; + } + + private bool AnyNeutralHasLos(in RingContact contender, Func hasLos) + { + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (spec.Alive && spec.Stance == SpectatorStance.Neutral && + hasLos(spec, contender)) + { + return true; + } + } + return false; + } + + private int FindStaleNoLosCleared(int contenderId) + { + int bestIdx = -1; + float bestAge = TargetMemoryDuration; + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (spec.Alive && + spec.Stance == SpectatorStance.Cleared && + spec.TargetContenderId == contenderId && + !spec.HasTargetLos && + spec.TimeSinceLastSeen >= bestAge) + { + bestAge = spec.TimeSinceLastSeen; + bestIdx = i; + } + } + return bestIdx; + } + + public void AdvancePerimeterOrbits(float dt) + { + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (!spec.Alive || spec.Stance != SpectatorStance.Neutral) + { + continue; + } + + // Only ostentatious Tourists orbit continuously in plain sight; + // Patrons and Exemplars hold their chosen high-ground / ambush positions. + if (spec.Tier == SpectatorTier.Tourist) + { + spec.RingAngle += 0.02f * dt; + } + } + } + + public (float X, float Z) GetPerimeterSlot(SpectatorState spec) + { + float r = SafeRadius + spec.RingOffset; + return (MathF.Cos(spec.RingAngle) * r, MathF.Sin(spec.RingAngle) * r); + } + + public (float X, float Z) GetNeutralGoal( + SpectatorState spec, + TerrainField? terrain, + IReadOnlyList? coverBoxes, + SionMapData? sionMap = null) + { + if (spec.Tier == SpectatorTier.Tourist && sionMap is null) + { + return GetPerimeterSlot(spec); + } + if (terrain is null) + { + return GetPerimeterSlot(spec); + } + + if (spec.Tier == SpectatorTier.Tourist) + { + // On Sion, keep Tourist perimeter slots clear of buildings as the ring moves + var (px, pz) = GetPerimeterSlot(spec); + float maxB = ArenaHalfExtent - 18f; + px = Math.Clamp(px, -maxB, maxB); + pz = Math.Clamp(pz, -maxB, maxB); + if (!sionMap!.IsInsideAnyBuildingXz(px, pz, 4.0f)) + { + return (px, pz); + } + for (int rStep = 0; rStep <= 4; rStep++) + { + float rr = SafeRadius + spec.RingOffset + rStep * 12f; + for (int aSign = -1; aSign <= 1; aSign += 2) + { + float ang = spec.RingAngle + aSign * (rStep + 1) * 0.03f; + float cx = Math.Clamp(MathF.Cos(ang) * rr, -maxB, maxB); + float cz = Math.Clamp(MathF.Sin(ang) * rr, -maxB, maxB); + if (!sionMap.IsInsideAnyBuildingXz(cx, cz, 4.0f)) + { + return (cx, cz); + } + } + } + return (px, pz); + } + + if (spec.HasNeutralAnchor && MathF.Abs(SafeRadius - spec.NeutralAnchorSafeRadius) < 8f) + { + return (spec.NeutralAnchorX, spec.NeutralAnchorZ); + } + + float bestX = MathF.Cos(spec.RingAngle) * (SafeRadius + spec.RingOffset); + float bestZ = MathF.Sin(spec.RingAngle) * (SafeRadius + spec.RingOffset); + float bestScore = float.NegativeInfinity; + float maxBound = ArenaHalfExtent - 18f; + + for (int ai = -3; ai <= 3; ai++) + { + float angle = spec.RingAngle + ai * 0.075f; + float cosA = MathF.Cos(angle); + float sinA = MathF.Sin(angle); + + for (int ri = 0; ri < 3; ri++) + { + float r = SafeRadius + 18f + ri * 26f; + float cx = Math.Clamp(cosA * r, -maxBound, maxBound); + float cz = Math.Clamp(sinA * r, -maxBound, maxBound); + + if (sionMap is not null) + { + if (sionMap.IsInsideAnyBuildingXz(cx, cz, 3.8f)) + { + continue; + } + if (terrain.SampleNormal(cx, cz).Ny < 0.78f) + { + continue; + } + } + + float distLen = MathF.Sqrt(cx * cx + cz * cz); + float inX = distLen > 1f ? -cx / distLen : 0f; + float inZ = distLen > 1f ? -cz / distLen : -1f; + + float hHere = terrain.SampleHeight(cx, cz); + float hInward = terrain.SampleHeight(cx + inX * 26f, cz + inZ * 26f); + + float score; + if (spec.Tier == SpectatorTier.Patron) + { + // Patrons claim elevated vantage points overlooking the arena interior + score = hHere * 2.0f + MathF.Max(0f, hHere - hInward) * 1.1f; + } + else + { + // Exemplars seek reverse-slope / low-profile / cover-adjacent ambush spots + float reverseSlope = MathF.Max(0f, hInward - hHere) * 3.0f; + float lowProfile = -hHere * 0.8f; + float coverBonus = 0f; + if (coverBoxes is not null) + { + for (int b = 0; b < coverBoxes.Count; b++) + { + var box = coverBoxes[b]; + float bx = box.X - cx; + float bz = box.Z - cz; + float bDist2 = bx * bx + bz * bz; + if (bDist2 < 28f * 28f && bDist2 > 4f * 4f) + { + // Prefer cover standing between the exemplar and the interior + float forwardDot = bx * inX + bz * inZ; + if (forwardDot > 2f) + { + coverBonus = 14f; + break; + } + } + } + } + score = reverseSlope + lowProfile + coverBonus; + } + + if (score > bestScore) + { + bestScore = score; + bestX = cx; + bestZ = cz; + } + } + } + + spec.NeutralAnchorX = bestX; + spec.NeutralAnchorZ = bestZ; + spec.NeutralAnchorSafeRadius = SafeRadius; + spec.HasNeutralAnchor = true; + return (bestX, bestZ); + } + + public int CountClearedFor(int contenderId) + { + int count = 0; + for (int i = 0; i < _spectators.Count; i++) + { + var s = _spectators[i]; + if (s.Alive && s.Stance == SpectatorStance.Cleared && s.TargetContenderId == contenderId) + { + count++; + } + } + return count; + } + + public int CountProvokedFor(int contenderId) + { + int count = 0; + for (int i = 0; i < _spectators.Count; i++) + { + var s = _spectators[i]; + if (s.Alive && s.Stance == SpectatorStance.Provoked && s.TargetContenderId == contenderId) + { + count++; + } + } + return count; + } + + public static List RollSalvageDrops(SpectatorState spec, Random rng) + { + var drops = new List(); + switch (spec.Tier) + { + case SpectatorTier.Tourist: + { + int count = rng.Next(1, 3); + for (int i = 0; i < count; i++) + { + if (rng.NextDouble() < 0.55) + { + ManufacturerId mfg = (rng.Next(3)) switch + { + 0 => ManufacturerId.AuralianOptics, + 1 => ManufacturerId.ThalassanForge, + _ => ManufacturerId.VexNineCollective + }; + ulong seed = ((ulong)(uint)spec.Id << 32) ^ (uint)rng.Next(); + drops.Add(ProceduralWeaponGenerator.RollForManufacturer(mfg, tier: rng.Next(2, 4), seed).Module); + } + else + { + drops.Add(Catalog.ImperialModules[rng.Next(Catalog.ImperialModules.Count)]); + } + } + break; + } + case SpectatorTier.Patron: + { + double roll = rng.NextDouble(); + if (roll < 0.4) + { + ManufacturerId mfg = rng.Next(2) == 0 + ? ManufacturerId.KorrathiIronworks + : ManufacturerId.VexNineCollective; + ulong seed = ((ulong)(uint)spec.Id << 32) ^ (uint)rng.Next(); + drops.Add(ProceduralWeaponGenerator.RollForManufacturer(mfg, tier: rng.Next(1, 3), seed).Module); + } + else if (roll < 0.65) + { + drops.Add(Catalog.ImperialModules[rng.Next(Catalog.ImperialModules.Count)]); + } + else + { + drops.Add(Catalog.HumanModules[rng.Next(Catalog.HumanModules.Count)]); + } + break; + } + case SpectatorTier.Exemplar: + { + if (rng.NextDouble() < 0.4) + { + drops.Add(Catalog.WeldedPlate); + } + break; + } + } + return drops; + } + + private void SpawnRing(Random rng, int count) + { + int touristCount = (int)MathF.Round(count * 0.45f); + int patronCount = (int)MathF.Round(count * 0.35f); + + var tiers = new List(count); + for (int i = 0; i < count; i++) + { + if (i < touristCount) tiers.Add(SpectatorTier.Tourist); + else if (i < touristCount + patronCount) tiers.Add(SpectatorTier.Patron); + else tiers.Add(SpectatorTier.Exemplar); + } + + for (int i = tiers.Count - 1; i > 0; i--) + { + int j = rng.Next(i + 1); + (tiers[i], tiers[j]) = (tiers[j], tiers[i]); + } + + for (int i = 0; i < count; i++) + { + float angle = (i / (float)count) * MathF.Tau; + float ringOffset = 25f + (float)rng.NextDouble() * 50f; + var tier = tiers[i]; + + var spec = CreateSpectator(1000 + i, tier, angle, ringOffset); + (float px, float pz) = GetPerimeterSlot(spec); + spec.X = px; + spec.Y = spec.Grid.Spec.HalfHeight + 0.1f; + spec.Z = pz; + spec.Yaw = MathF.Atan2(-px, -pz); + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, spec.Yaw); + spec.CurrRotX = q.X; + spec.CurrRotY = q.Y; + spec.CurrRotZ = q.Z; + spec.CurrRotW = q.W; + spec.SnapPreviousPose(); + spec.ResetAimTracker(spec.Yaw); + _spectators.Add(spec); + } + } + + private static void MountRequired(ChassisGrid grid, ModuleSpec mod, string hardpointId) + { + if (!grid.TryMount(mod, hardpointId)) + { + throw new InvalidOperationException( + $"Failed to mount '{mod.Id}' onto '{grid.Spec.Id}.{hardpointId}'."); + } + } + + private static SpectatorState CreateSpectator(int id, SpectatorTier tier, float angle, float ringOffset) + { + switch (tier) + { + case SpectatorTier.Tourist: + { + var grid = new ChassisGrid(Catalog.Paladin); + MountRequired(grid, Catalog.GildedLance, "hp.weapon.arm_l"); + MountRequired(grid, Catalog.ImperialAegisPd, "hp.weapon.sh_l"); + MountRequired(grid, Catalog.TouringPlasma, "hp.weapon.sh_r"); + MountRequired(grid, Catalog.NobleCore, "hp.engine.chest"); + MountRequired(grid, Catalog.GoldRadiator, "hp.radiator.back_l"); + MountRequired(grid, Catalog.GildedPlate, "hp.armor.torso"); + return new SpectatorState( + id, tier, grid, angle, ringOffset, + radarSignature: 1.0f, + aimSpreadRad: 0.14f, + maxSpeed: 18f, + preferredRange: 95f); + } + case SpectatorTier.Patron: + { + var grid = new ChassisGrid(Catalog.Raptor); + MountRequired(grid, Catalog.Autocannon, "hp.weapon.arm_l"); + MountRequired(grid, Catalog.Flak, "hp.weapon.arm_r"); + MountRequired(grid, Catalog.TurboCore, "hp.engine.chest"); + MountRequired(grid, Catalog.CopperRad, "hp.radiator.sh_l"); + return new SpectatorState( + id, tier, grid, angle, ringOffset, + radarSignature: 0.6f, + aimSpreadRad: 0.055f, + maxSpeed: 26f, + preferredRange: 82f); + } + default: // Exemplar + { + var grid = new ChassisGrid(ExemplarSpec); + MountRequired(grid, Catalog.GildedLance, "hp.weapon.arm_r"); + MountRequired(grid, Catalog.TouringPlasma, "hp.weapon.arm_l"); + MountRequired(grid, Catalog.NobleCore, "hp.engine.chest"); + MountRequired(grid, Catalog.GoldRadiator, "hp.radiator.sh_l"); + MountRequired(grid, Catalog.GoldRadiator, "hp.radiator.sh_r"); + return new SpectatorState( + id, tier, grid, angle, ringOffset, + radarSignature: 0.18f, + aimSpreadRad: 0.006f, + maxSpeed: 40f, + preferredRange: 58f); + } + } + } + + public static readonly ChassisSpec ExemplarSpec = Catalog.Raptor with + { + Id = "exemplar_frame", + Name = "Exemplar Frame", + BaseCellArmor = 22f, + MassKg = 1150f, + BaseThrust = 26000f, + BaseTurnRate = 6.2f, + MaxSpeed = 40f, + HalfWidth = 0.8f, + HalfHeight = 1.55f, + HalfLength = 0.8f + }; + } +} diff --git a/src/RustToDust.Core/TerrainField.cs b/src/RustToDust.Core/TerrainField.cs new file mode 100644 index 0000000..e207104 --- /dev/null +++ b/src/RustToDust.Core/TerrainField.cs @@ -0,0 +1,1346 @@ +using System; +using System.Collections.Generic; + +namespace RustToDust.Core +{ + public enum TerrainBrushKind + { + DuneRidge, + Mesa, + SalvagePad, + Road, + Crater, + Track, + Scorch, + Rubble + } + + public readonly record struct TerrainBrush( + int Id, + TerrainBrushKind Kind, + float X, + float Z, + float RotationRad, + float RadiusX, + float RadiusZ, + float HeightDelta, + float Roughness, + float Metallic, + float AlbedoR, + float AlbedoG, + float AlbedoB, + bool Dynamic); + + public sealed class TerrainField + { + public const float ArenaSize = 1536f; + public const float HalfExtent = 768f; + public const int DesertTileGridCount = 8; + public const float TileSize = ArenaSize / DesertTileGridCount; // 192m + private const int AccelGridCount = 64; + private const int AccelCellCount = AccelGridCount * AccelGridCount; + public const float MinWorldHeight = -18f; + public const float MaxWorldHeight = 52f; + public const float HeightSpan = MaxWorldHeight - MinWorldHeight; // 70m + public const int MaxDynamicDecals = 256; + public const float CraterCoalesceRadiusMeters = 0.75f; + + private readonly record struct BrushPrecomp( + float CosR, + float SinR, + float InvRx, + float InvRz, + float MaxRadiusSq) + { + public static BrushPrecomp From(in TerrainBrush b) + { + float maxR = MathF.Max(0.1f, MathF.Max(b.RadiusX, b.RadiusZ)); + return new BrushPrecomp( + MathF.Cos(b.RotationRad), + MathF.Sin(b.RotationRad), + 1f / MathF.Max(0.1f, b.RadiusX), + 1f / MathF.Max(0.1f, b.RadiusZ), + maxR * maxR); + } + } + + private readonly List _brushes = new(); + private readonly List _brushPrecomps = new(); + private readonly List[,] _tileBrushIndices; + private readonly List[] _cellBrushIndices = new List[AccelCellCount]; + private readonly float[] _cellMaxHeight = new float[AccelCellCount]; + private readonly float[] _cellBaseMaxHeight = new float[AccelCellCount]; + private readonly Queue _dynamicDecalSlots = new(); + private float[]? _heightmap; + private ushort[]? _sharedU16Heights; + private float _baseMinY; + private float _baseScale; + private readonly float[]?[,] _scarredTileHeights; + private int _nextBrushId = 1; + + public TerrainField(ulong seed, int tileGridCount = DesertTileGridCount) + { + if (tileGridCount <= 0) + { + throw new ArgumentOutOfRangeException(nameof(tileGridCount)); + } + Seed = seed; + TileGridCount = tileGridCount; + StructuralTileVersions = new int[tileGridCount, tileGridCount]; + VisualTileVersions = new int[tileGridCount, tileGridCount]; + _tileBrushIndices = new List[tileGridCount, tileGridCount]; + _scarredTileHeights = new float[tileGridCount, tileGridCount][]; + for (int tz = 0; tz < tileGridCount; tz++) + { + for (int tx = 0; tx < tileGridCount; tx++) + { + _tileBrushIndices[tx, tz] = new List(32); + } + } + for (int c = 0; c < AccelCellCount; c++) + { + _cellBrushIndices[c] = new List(4); + } + } + + public ulong Seed { get; } + public int TileGridCount { get; } + public bool IsHeightmapMode { get; private set; } + public float MapSize { get; private set; } = ArenaSize; + public float MapHalfExtent { get; private set; } = HalfExtent; + public float MapTileSize { get; private set; } = TileSize; + public float MapMinHeight { get; private set; } = MinWorldHeight; + public float MapMaxHeight { get; private set; } = MaxWorldHeight; + public int HeightmapRes { get; private set; } + public float HeightmapCellSize { get; private set; } + public int PhysicsTileResolution => IsHeightmapMode ? ((HeightmapRes - 1) / TileGridCount + 1) : 0; + public ushort[]? SharedU16Heights => _sharedU16Heights; + public float BaseMinY => _baseMinY; + public float BaseScale => _baseScale; + private float AccelCellSize => MapSize / AccelGridCount; + public IReadOnlyList Brushes => _brushes; + public int[,] StructuralTileVersions { get; } + public int[,] VisualTileVersions { get; } + public int[,] TileVersions => VisualTileVersions; + + public static TerrainField LoadHeightmap( + float sizeMeters, + int gridRes, + ReadOnlySpan heights, + float minY, + float maxY, + ulong seed = 0UL) + { + if (sizeMeters <= 0f || !float.IsFinite(sizeMeters)) + { + throw new ArgumentOutOfRangeException(nameof(sizeMeters)); + } + if (gridRes < 2) + { + throw new ArgumentOutOfRangeException(nameof(gridRes)); + } + if (heights.Length != gridRes * gridRes) + { + throw new ArgumentException($"Expected {gridRes * gridRes} height samples, got {heights.Length}.", nameof(heights)); + } + + int tileGridCount = Math.Max(1, (int)MathF.Round(sizeMeters / TileSize)); + var field = new TerrainField(seed, tileGridCount) + { + IsHeightmapMode = true, + MapSize = sizeMeters, + MapHalfExtent = sizeMeters * 0.5f, + MapTileSize = sizeMeters / tileGridCount, + MapMinHeight = minY - 8f, + MapMaxHeight = maxY + 4f, + HeightmapRes = gridRes, + HeightmapCellSize = sizeMeters / (gridRes - 1), + _heightmap = heights.ToArray() + }; + + field.InitializeAccelGridFromHeightmap(gridRes); + return field; + } + + public static TerrainField LoadSharedHeightmap( + float sizeMeters, + int gridRes, + int tileGridCount, + ushort[] sharedU16Heights, + float baseMinY, + float baseScale, + float worldMinY, + float worldMaxY, + ulong seed = 0UL) + { + if (sizeMeters <= 0f || !float.IsFinite(sizeMeters)) + { + throw new ArgumentOutOfRangeException(nameof(sizeMeters)); + } + if (gridRes < 2) + { + throw new ArgumentOutOfRangeException(nameof(gridRes)); + } + if (sharedU16Heights is null || sharedU16Heights.Length != gridRes * gridRes) + { + throw new ArgumentException($"Expected {gridRes * gridRes} u16 height samples, got {sharedU16Heights?.Length ?? 0}.", nameof(sharedU16Heights)); + } + + var field = new TerrainField(seed, tileGridCount) + { + IsHeightmapMode = true, + MapSize = sizeMeters, + MapHalfExtent = sizeMeters * 0.5f, + MapTileSize = sizeMeters / tileGridCount, + MapMinHeight = worldMinY - 8f, + MapMaxHeight = worldMaxY + 4f, + HeightmapRes = gridRes, + HeightmapCellSize = sizeMeters / (gridRes - 1), + _sharedU16Heights = sharedU16Heights, + _baseMinY = baseMinY, + _baseScale = baseScale + }; + + field.InitializeAccelGridFromHeightmap(gridRes); + return field; + } + + private void InitializeAccelGridFromHeightmap(int gridRes) + { + float half = MapHalfExtent; + float cellSize = AccelCellSize; + float invDemStep = 1f / HeightmapCellSize; + + for (int cz = 0; cz < AccelGridCount; cz++) + { + float minZ = -half + cz * cellSize; + float maxZ = minZ + cellSize; + int iz0 = Math.Clamp((int)MathF.Floor((minZ + half) * invDemStep) - 1, 0, gridRes - 1); + int iz1 = Math.Clamp((int)MathF.Ceiling((maxZ + half) * invDemStep) + 1, 0, gridRes - 1); + + for (int cx = 0; cx < AccelGridCount; cx++) + { + float minX = -half + cx * cellSize; + float maxX = minX + cellSize; + int ix0 = Math.Clamp((int)MathF.Floor((minX + half) * invDemStep) - 1, 0, gridRes - 1); + int ix1 = Math.Clamp((int)MathF.Ceiling((maxX + half) * invDemStep) + 1, 0, gridRes - 1); + + float cellMax = float.NegativeInfinity; + for (int iz = iz0; iz <= iz1; iz++) + { + int row = iz * gridRes; + for (int ix = ix0; ix <= ix1; ix++) + { + float h = _sharedU16Heights is not null + ? _baseMinY + _sharedU16Heights[row + ix] * _baseScale + : _heightmap![row + ix]; + if (h > cellMax) + { + cellMax = h; + } + } + } + + int cellIdx = cz * AccelGridCount + cx; + float boundedMax = float.IsNegativeInfinity(cellMax) ? 0f : cellMax + 0.05f; + _cellBaseMaxHeight[cellIdx] = boundedMax; + _cellMaxHeight[cellIdx] = boundedMax; + } + } + + for (int tz = 0; tz < TileGridCount; tz++) + { + for (int tx = 0; tx < TileGridCount; tx++) + { + StructuralTileVersions[tx, tz] = 1; + VisualTileVersions[tx, tz] = 1; + } + } + } + + public IReadOnlyList GetTileBrushIndices(int tx, int tz) => _tileBrushIndices[tx, tz]; + + public static TerrainField Generate(ulong seed, IReadOnlyList coverBoxes) + { + var field = new TerrainField(seed); + var rng = new Random((int)(seed ^ (seed >> 32))); + + // 1. Flat compacted salvage pads around cover ruins & center plaza (keeps cover seated cleanly near ~0m) + field.AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.SalvagePad, + X: 0f, + Z: 0f, + RotationRad: 0f, + RadiusX: 28f, + RadiusZ: 28f, + HeightDelta: 0.20f, + Roughness: 0.90f, + Metallic: 0.05f, + AlbedoR: 0.44f, + AlbedoG: 0.40f, + AlbedoB: 0.35f, + Dynamic: false)); + + for (int i = 0; i < coverBoxes.Count; i++) + { + var box = coverBoxes[i]; + float padR = MathF.Max(box.HalfX, box.HalfZ) + 12f; + field.AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.SalvagePad, + X: box.X, + Z: box.Z, + RotationRad: 0f, + RadiusX: padR, + RadiusZ: padR, + HeightDelta: 0.10f + (float)rng.NextDouble() * 0.25f, + Roughness: 0.92f, + Metallic: 0.04f, + AlbedoR: 0.42f, + AlbedoG: 0.38f, + AlbedoB: 0.34f, + Dynamic: false)); + } + + // 2. Dirt track ring segments around the mid-valley loop (r ~ 260..290m) + const int roadCount = 16; + for (int i = 0; i < roadCount; i++) + { + float angle = (i / (float)roadCount) * MathF.Tau + 0.14f; + float r = 275f + (float)(rng.NextDouble() * 20.0 - 10.0); + float rx = MathF.Cos(angle) * r; + float rz = MathF.Sin(angle) * r; + float tangentRot = angle + MathF.PI * 0.5f; + field.AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Road, + X: rx, + Z: rz, + RotationRad: tangentRot, + RadiusX: 64f, + RadiusZ: 11f, + HeightDelta: -0.22f, + Roughness: 0.94f, + Metallic: 0.02f, + AlbedoR: 0.56f, + AlbedoG: 0.40f, + AlbedoB: 0.25f, + Dynamic: false)); + } + + // 3. Tall flat-topped rust mesas & buttes (+22m..+44m, radius 45..110m) for huge landmarks and full hull-down cover + int mesaCount = 0; + int attempts = 0; + while (mesaCount < 14 && attempts < 500) + { + attempts++; + float angle = (float)(rng.NextDouble() * MathF.Tau); + float dist = 125f + (float)rng.NextDouble() * 520f; + float x = MathF.Cos(angle) * dist; + float z = MathF.Sin(angle) * dist; + float rx = 45f + (float)rng.NextDouble() * 65f; + float rz = 45f + (float)rng.NextDouble() * 65f; + + if (MathF.Abs(field.SampleHeight(x, z)) > 4.0f) + { + continue; + } + + var candidate = new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Mesa, + X: x, + Z: z, + RotationRad: (float)(rng.NextDouble() * MathF.PI), + RadiusX: rx, + RadiusZ: rz, + HeightDelta: 22f + (float)rng.NextDouble() * 22f, + Roughness: 0.86f, + Metallic: 0.08f, + AlbedoR: 0.48f, + AlbedoG: 0.25f, + AlbedoB: 0.17f, + Dynamic: false); + + if (!IsBrushClearOfCover(in candidate, coverBoxes)) + { + continue; + } + + field.AddBrush(candidate); + mesaCount++; + } + + // 4. Sweeping high sand dune ridges (+10m..+26m, RadiusX 90..180m, RadiusZ 30..65m) forming blind crests + int duneCount = 0; + attempts = 0; + while (duneCount < 30 && attempts < 700) + { + attempts++; + float x = (float)(rng.NextDouble() * 1280.0 - 640.0); + float z = (float)(rng.NextDouble() * 1280.0 - 640.0); + float radiusX = 90f + (float)rng.NextDouble() * 90f; + float radiusZ = 30f + (float)rng.NextDouble() * 35f; + + if (field.SampleHeight(x, z) > 15f) + { + continue; + } + + float heightDelta = 10f + (float)rng.NextDouble() * 16f; + float rot = (float)(rng.NextDouble() * MathF.PI); + var candidate = new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.DuneRidge, + X: x, + Z: z, + RotationRad: rot, + RadiusX: radiusX, + RadiusZ: radiusZ, + HeightDelta: heightDelta, + Roughness: 0.89f, + Metallic: 0.02f, + AlbedoR: 0.78f, + AlbedoG: 0.56f, + AlbedoB: 0.34f, + Dynamic: false); + + if (!IsBrushClearOfCover(in candidate, coverBoxes)) + { + continue; + } + + field.AddBrush(candidate); + duneCount++; + } + + // 5. Deep dry canyons / arroyos (-8m..-16m carved washes) letting buggies run concealed below the skyline + int canyonCount = 0; + attempts = 0; + while (canyonCount < 12 && attempts < 450) + { + attempts++; + float x = (float)(rng.NextDouble() * 1160.0 - 580.0); + float z = (float)(rng.NextDouble() * 1160.0 - 580.0); + float radiusX = 42f + (float)rng.NextDouble() * 34f; + float radiusZ = 115f + (float)rng.NextDouble() * 85f; + + float curH = field.SampleHeight(x, z); + if (curH < -2.5f || curH > 12f) + { + continue; + } + + float heightDelta = -(8f + (float)rng.NextDouble() * 7.5f); + float rot = (float)(rng.NextDouble() * MathF.PI); + var candidate = new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.DuneRidge, + X: x, + Z: z, + RotationRad: rot, + RadiusX: radiusX, + RadiusZ: radiusZ, + HeightDelta: heightDelta, + Roughness: 0.96f, + Metallic: 0.02f, + AlbedoR: 0.54f, + AlbedoG: 0.38f, + AlbedoB: 0.25f, + Dynamic: false); + + if (!IsBrushClearOfCover(in candidate, coverBoxes)) + { + continue; + } + + field.AddBrush(candidate); + canyonCount++; + } + + // Bump all initial tile versions to 1 so clients detect initial bake needed + for (int tz = 0; tz < field.TileGridCount; tz++) + { + for (int tx = 0; tx < field.TileGridCount; tx++) + { + field.StructuralTileVersions[tx, tz] = 1; + field.VisualTileVersions[tx, tz] = 1; + } + } + + return field; + } + + public void StampCrater(float x, float z, float radius, float depth) + { + float clampedR = Math.Clamp(radius, 1.2f, 16f); + float clampedDepth = Math.Clamp(MathF.Abs(depth), 0.15f, 4.5f); + + const float coalesceSq = CraterCoalesceRadiusMeters * CraterCoalesceRadiusMeters; + for (int i = _brushes.Count - 1; i >= 0; i--) + { + var existing = _brushes[i]; + if (existing.Kind != TerrainBrushKind.Crater || !existing.Dynamic) + { + continue; + } + + float dx = existing.X - x; + float dz = existing.Z - z; + if (dx * dx + dz * dz < coalesceSq) + { + float newR = MathF.Max(existing.RadiusX, clampedR); + float existingDepth = MathF.Abs(existing.HeightDelta); + float newDepth = MathF.Max(existingDepth, clampedDepth); + if (newR > existing.RadiusX || newDepth > existingDepth) + { + UnregisterBrushFromTiles(i, in existing); + var updated = existing with + { + RadiusX = newR, + RadiusZ = newR, + HeightDelta = -newDepth + }; + _brushes[i] = updated; + _brushPrecomps[i] = BrushPrecomp.From(in updated); + RegisterBrushInTiles(i, in updated, incrementTileVersion: true); + } + return; + } + } + + AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Crater, + X: x, + Z: z, + RotationRad: 0f, + RadiusX: clampedR, + RadiusZ: clampedR, + HeightDelta: -clampedDepth, + Roughness: 0.96f, + Metallic: 0.12f, + AlbedoR: 0.15f, + AlbedoG: 0.12f, + AlbedoB: 0.10f, + Dynamic: true)); + } + + public void StampRubble(float x, float z, float radius, float heightDelta, float yaw = 0f) + { + float clampedR = Math.Clamp(radius, 1.5f, 18f); + float clampedH = Math.Clamp(MathF.Abs(heightDelta), 0.15f, 2.5f); + AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Rubble, + X: x, + Z: z, + RotationRad: yaw, + RadiusX: clampedR, + RadiusZ: clampedR, + HeightDelta: clampedH, + Roughness: 0.97f, + Metallic: 0.05f, + AlbedoR: 0.42f, + AlbedoG: 0.39f, + AlbedoB: 0.35f, + Dynamic: true)); + } + + public void StampTrack(float x, float z, float yaw, float width, float length) + { + SetDynamicDecal(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Track, + X: x, + Z: z, + RotationRad: -yaw + MathF.PI * 0.5f, + RadiusX: Math.Clamp(length * 0.5f, 0.8f, 6f), + RadiusZ: Math.Clamp(width * 0.5f, 0.5f, 4f), + HeightDelta: -0.04f, + Roughness: 0.95f, + Metallic: 0.02f, + AlbedoR: 0.42f, + AlbedoG: 0.29f, + AlbedoB: 0.18f, + Dynamic: true)); + } + + public void StampScorch(float x, float z, float radius) + { + float r = Math.Clamp(radius, 0.8f, 10f); + SetDynamicDecal(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Scorch, + X: x, + Z: z, + RotationRad: 0f, + RadiusX: r, + RadiusZ: r, + HeightDelta: 0f, + Roughness: 0.95f, + Metallic: 0.10f, + AlbedoR: 0.14f, + AlbedoG: 0.11f, + AlbedoB: 0.10f, + Dynamic: true)); + } + + public float SampleBaseHeight(float x, float z) + { + float half = MapHalfExtent; + float cx = Math.Clamp(x, -half, half); + float cz = Math.Clamp(z, -half, half); + + if (_sharedU16Heights is not null) + { + int res = HeightmapRes; + float fx = Math.Clamp((cx + half) / HeightmapCellSize, 0f, res - 1f); + float fz = Math.Clamp((cz + half) / HeightmapCellSize, 0f, res - 1f); + int ix = Math.Clamp((int)fx, 0, res - 2); + int iz = Math.Clamp((int)fz, 0, res - 2); + float tx = Math.Clamp(fx - ix, 0f, 1f); + float tz = Math.Clamp(fz - iz, 0f, 1f); + int row0 = iz * res; + int row1 = row0 + res; + float h00 = _baseMinY + _sharedU16Heights[row0 + ix] * _baseScale; + float h10 = _baseMinY + _sharedU16Heights[row0 + ix + 1] * _baseScale; + float h01 = _baseMinY + _sharedU16Heights[row1 + ix] * _baseScale; + float h11 = _baseMinY + _sharedU16Heights[row1 + ix + 1] * _baseScale; + return (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz; + } + + if (_heightmap is not null) + { + int res = HeightmapRes; + float fx = Math.Clamp((cx + half) / HeightmapCellSize, 0f, res - 1f); + float fz = Math.Clamp((cz + half) / HeightmapCellSize, 0f, res - 1f); + int ix = Math.Clamp((int)fx, 0, res - 2); + int iz = Math.Clamp((int)fz, 0, res - 2); + float tx = Math.Clamp(fx - ix, 0f, 1f); + float tz = Math.Clamp(fz - iz, 0f, 1f); + int row0 = iz * res; + int row1 = row0 + res; + float h00 = _heightmap[row0 + ix]; + float h10 = _heightmap[row0 + ix + 1]; + float h01 = _heightmap[row1 + ix]; + float h11 = _heightmap[row1 + ix + 1]; + return (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz; + } + + return 0f; + } + + public float SampleHeight(float x, float z) + { + float half = MapHalfExtent; + float cx = Math.Clamp(x, -half, half); + float cz = Math.Clamp(z, -half, half); + + float h = SampleBaseHeight(cx, cz); + + if (_brushes.Count > 0) + { + WorldToAccelCell(cx, cz, out int acx, out int acz); + var indices = _cellBrushIndices[acz * AccelGridCount + acx]; + for (int i = 0; i < indices.Count; i++) + { + int idx = indices[i]; + var b = _brushes[idx]; + h += EvaluateBrushHeightFast(in b, _brushPrecomps[idx], cx, cz); + } + } + + return Math.Clamp(h, MapMinHeight, MapMaxHeight); + } + + public void ExtractTilePhysicsHeights(int tx, int tz, Span dst, out float minY, out float maxY) + { + if ((uint)tx >= (uint)TileGridCount || (uint)tz >= (uint)TileGridCount) + { + throw new ArgumentOutOfRangeException(nameof(tx)); + } + if (!IsHeightmapMode) + { + throw new InvalidOperationException("ExtractTilePhysicsHeights requires heightmap mode."); + } + + int samplesPerTile = (HeightmapRes - 1) / TileGridCount; + int side = samplesPerTile + 1; + int count = side * side; + if (dst.Length < count) + { + throw new ArgumentException($"Destination span too small: need {count}, got {dst.Length}.", nameof(dst)); + } + + int gx0 = tx * samplesPerTile; + int gz0 = tz * samplesPerTile; + var tileBrushes = _tileBrushIndices[tx, tz]; + bool hasStructuralBrushes = false; + for (int i = 0; i < tileBrushes.Count; i++) + { + var k = _brushes[tileBrushes[i]].Kind; + if (k != TerrainBrushKind.Track && k != TerrainBrushKind.Scorch) + { + hasStructuralBrushes = true; + break; + } + } + + float minVal = float.PositiveInfinity; + float maxVal = float.NegativeInfinity; + float half = MapHalfExtent; + float step = HeightmapCellSize; + int res = HeightmapRes; + + for (int lz = 0; lz < side; lz++) + { + int gz = gz0 + lz; + int globalRow = gz * res + gx0; + int localRow = lz * side; + float wz = -half + gz * step; + + for (int lx = 0; lx < side; lx++) + { + float h = _sharedU16Heights is not null + ? _baseMinY + _sharedU16Heights[globalRow + lx] * _baseScale + : _heightmap![globalRow + lx]; + + if (hasStructuralBrushes) + { + float wx = -half + (gx0 + lx) * step; + for (int bi = 0; bi < tileBrushes.Count; bi++) + { + int bIdx = tileBrushes[bi]; + var b = _brushes[bIdx]; + if (b.Kind == TerrainBrushKind.Track || b.Kind == TerrainBrushKind.Scorch) + { + continue; + } + h += EvaluateBrushHeightFast(in b, _brushPrecomps[bIdx], wx, wz); + } + } + + float clamped = Math.Clamp(h, MapMinHeight, MapMaxHeight); + dst[localRow + lx] = clamped; + if (clamped < minVal) minVal = clamped; + if (clamped > maxVal) maxVal = clamped; + } + } + + if (hasStructuralBrushes) + { + var cached = _scarredTileHeights[tx, tz]; + if (cached is null || cached.Length != count) + { + cached = new float[count]; + _scarredTileHeights[tx, tz] = cached; + } + dst.Slice(0, count).CopyTo(cached); + } + else + { + _scarredTileHeights[tx, tz] = null; + } + + minY = float.IsPositiveInfinity(minVal) ? 0f : minVal; + maxY = float.IsNegativeInfinity(maxVal) ? 0f : maxVal; + } + + public void ClearDynamicScars() + { + if (_brushes.Count == 0) + { + return; + } + + bool anyDynamic = false; + var staticBrushes = new List(_brushes.Count); + for (int i = 0; i < _brushes.Count; i++) + { + if (_brushes[i].Dynamic) + { + anyDynamic = true; + GetBrushTileBounds(_brushes[i], out int minTx, out int maxTx, out int minTz, out int maxTz); + bool isStructural = _brushes[i].Kind != TerrainBrushKind.Track && _brushes[i].Kind != TerrainBrushKind.Scorch; + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + VisualTileVersions[tx, tz]++; + if (isStructural) + { + StructuralTileVersions[tx, tz]++; + } + _scarredTileHeights[tx, tz] = null; + } + } + } + else + { + staticBrushes.Add(_brushes[i]); + } + } + + if (!anyDynamic) + { + return; + } + + _brushes.Clear(); + _brushPrecomps.Clear(); + _dynamicDecalSlots.Clear(); + for (int tz = 0; tz < TileGridCount; tz++) + { + for (int tx = 0; tx < TileGridCount; tx++) + { + _tileBrushIndices[tx, tz].Clear(); + } + } + for (int c = 0; c < AccelCellCount; c++) + { + _cellBrushIndices[c].Clear(); + _cellMaxHeight[c] = _cellBaseMaxHeight[c]; + } + + for (int i = 0; i < staticBrushes.Count; i++) + { + int idx = _brushes.Count; + var b = staticBrushes[i]; + _brushes.Add(b); + _brushPrecomps.Add(BrushPrecomp.From(in b)); + RegisterBrushInTiles(idx, in b, incrementTileVersion: false); + } + } + + public (float Nx, float Ny, float Nz) SampleNormal(float x, float z) + { + const float eps = 0.5f; + float hL = SampleHeight(x - eps, z); + float hR = SampleHeight(x + eps, z); + float hD = SampleHeight(x, z - eps); + float hU = SampleHeight(x, z + eps); + + float nx = hL - hR; + float ny = 2f * eps; + float nz = hD - hU; + float len = MathF.Sqrt(nx * nx + ny * ny + nz * nz); + if (len < 1e-5f) + { + return (0f, 1f, 0f); + } + return (nx / len, ny / len, nz / len); + } + + public bool Raycast( + float ox, float oy, float oz, + float dx, float dy, float dz, + float maxDistance, + out float hitX, out float hitY, out float hitZ, out float hitDist) + { + float half = MapHalfExtent; + float accelSize = AccelCellSize; + + float prevT = 0f; + float prevDiff = oy - SampleHeight(ox, oz); + if (prevDiff <= 0f) + { + hitX = ox; + hitY = oy; + hitZ = oz; + hitDist = 0f; + return true; + } + + float t = 1.5f; + while (prevT < maxDistance) + { + float ct = MathF.Min(t, maxDistance); + float px = ox + dx * ct; + float py = oy + dy * ct; + float pz = oz + dz * ct; + + float cx = Math.Clamp(px, -half, half); + float cz = Math.Clamp(pz, -half, half); + WorldToAccelCell(cx, cz, out int acx, out int acz); + float cellMax = _cellMaxHeight[acz * AccelGridCount + acx] + 0.02f; + + // Fast-skip consecutive cells strictly below the ray without sampling brushes + while (py > cellMax + 0.02f && + ct < maxDistance && + px >= -half && px <= half && + pz >= -half && pz <= half) + { + float cellMinX = -half + acx * accelSize; + float cellMaxX = cellMinX + accelSize; + float cellMinZ = -half + acz * accelSize; + float cellMaxZ = cellMinZ + accelSize; + float txExit = dx > 1e-6f ? (cellMaxX - px) / dx : (dx < -1e-6f ? (cellMinX - px) / dx : float.PositiveInfinity); + float tzExit = dz > 1e-6f ? (cellMaxZ - pz) / dz : (dz < -1e-6f ? (cellMinZ - pz) / dz : float.PositiveInfinity); + float tExit = MathF.Min(txExit, tzExit); + float advance = MathF.Min(tExit + 0.02f, maxDistance - ct); + if (advance <= 0.02f) + { + break; + } + float ey = py + dy * advance; + if (ey <= cellMax + 0.02f) + { + break; + } + prevT = ct + MathF.Min(tExit, maxDistance - ct); + ct += advance; + px = ox + dx * ct; + py = oy + dy * ct; + pz = oz + dz * ct; + cx = Math.Clamp(px, -half, half); + cz = Math.Clamp(pz, -half, half); + WorldToAccelCell(cx, cz, out acx, out acz); + cellMax = _cellMaxHeight[acz * AccelGridCount + acx] + 0.02f; + } + + if (py <= cellMax) + { + float diff = py - SampleHeight(px, pz); + if (diff <= 0f) + { + // Binary refine between prevT and ct + float lo = prevT; + float hi = ct; + for (int iter = 0; iter < 5; iter++) + { + float mid = 0.5f * (lo + hi); + float mx = ox + dx * mid; + float my = oy + dy * mid; + float mz = oz + dz * mid; + if (my - SampleHeight(mx, mz) > 0f) + { + lo = mid; + } + else + { + hi = mid; + } + } + + hitDist = 0.5f * (lo + hi); + hitX = ox + dx * hitDist; + hitZ = oz + dz * hitDist; + hitY = SampleHeight(hitX, hitZ); + return true; + } + } + + prevT = ct; + if (ct >= maxDistance) + { + break; + } + + float step = ct < 160f ? 1.5f : 2.5f; + t = ct + step; + } + + hitX = 0f; + hitY = 0f; + hitZ = 0f; + hitDist = maxDistance; + return false; + } + + private static float EvaluateBrushHeightFast(in TerrainBrush b, in BrushPrecomp p, float worldX, float worldZ) + { + float dx = worldX - b.X; + float dz = worldZ - b.Z; + if (dx * dx + dz * dz >= p.MaxRadiusSq) + { + return 0f; + } + + float lx = dx * p.CosR + dz * p.SinR; + float lz = -dx * p.SinR + dz * p.CosR; + + float u = lx * p.InvRx; + float v = lz * p.InvRz; + float r2 = u * u + v * v; + if (r2 >= 1f) + { + return 0f; + } + + return EvaluateBrushKernel(in b, u, r2); + } + + public static float EvaluateBrushHeight(in TerrainBrush b, float worldX, float worldZ) + { + float dx = worldX - b.X; + float dz = worldZ - b.Z; + float cosR = MathF.Cos(b.RotationRad); + float sinR = MathF.Sin(b.RotationRad); + float lx = dx * cosR + dz * sinR; + float lz = -dx * sinR + dz * cosR; + + float u = lx / MathF.Max(0.1f, b.RadiusX); + float v = lz / MathF.Max(0.1f, b.RadiusZ); + float r2 = u * u + v * v; + if (r2 >= 1f) + { + return 0f; + } + + return EvaluateBrushKernel(in b, u, r2); + } + + private static float EvaluateBrushKernel(in TerrainBrush b, float u, float r2) + { + switch (b.Kind) + { + case TerrainBrushKind.DuneRidge: + { + float env = 1f - r2; + env *= env; + float ridge = MathF.Max(0f, 1f - u * u); + float asym = 1f + 0.32f * u; + return b.HeightDelta * env * (0.35f + 0.65f * ridge) * asym; + } + case TerrainBrushKind.Mesa: + { + float r = MathF.Sqrt(r2); + float t = Math.Clamp((1f - r) / 0.45f, 0f, 1f); + float plateau = t * t * (3f - 2f * t); + return b.HeightDelta * plateau; + } + case TerrainBrushKind.SalvagePad: + case TerrainBrushKind.Road: + case TerrainBrushKind.Track: + { + float env = 1f - r2; + return b.HeightDelta * env * env; + } + case TerrainBrushKind.Crater: + { + float r = MathF.Sqrt(r2); + float depth = MathF.Abs(b.HeightDelta); + float pitT = Math.Clamp(1f - r / 0.62f, 0f, 1f); + float pit = -depth * pitT * pitT * (3f - 2f * pitT); + float rimT = MathF.Sin(MathF.PI * Math.Clamp((r - 0.55f) / 0.45f, 0f, 1f)); + float rim = (0.32f * depth) * rimT * rimT; + return pit + rim; + } + case TerrainBrushKind.Rubble: + { + float env = 1f - r2; + env *= env; + float mound = 0.72f + 0.28f * MathF.Cos(u * MathF.PI * 2.5f); + return b.HeightDelta * env * mound; + } + default: + return 0f; + } + } + + private TerrainBrush AddBrush(TerrainBrush template) + { + var brush = template with { Id = _nextBrushId++ }; + int index = _brushes.Count; + _brushes.Add(brush); + _brushPrecomps.Add(BrushPrecomp.From(in brush)); + RegisterBrushInTiles(index, in brush, incrementTileVersion: true); + return brush; + } + + private TerrainBrush SetDynamicDecal(TerrainBrush template) + { + var brush = template with { Id = _nextBrushId++ }; + if (_dynamicDecalSlots.Count >= MaxDynamicDecals) + { + int slot = _dynamicDecalSlots.Dequeue(); + var prev = _brushes[slot]; + UnregisterBrushFromTiles(slot, in prev); + _brushes[slot] = brush; + _brushPrecomps[slot] = BrushPrecomp.From(in brush); + RegisterBrushInTiles(slot, in brush, incrementTileVersion: true); + _dynamicDecalSlots.Enqueue(slot); + return brush; + } + + int index = _brushes.Count; + _brushes.Add(brush); + _brushPrecomps.Add(BrushPrecomp.From(in brush)); + RegisterBrushInTiles(index, in brush, incrementTileVersion: true); + _dynamicDecalSlots.Enqueue(index); + return brush; + } + + private bool TryGetBrushCellBounds( + in TerrainBrush b, + in BrushPrecomp p, + int cx, int cz, + out float cellMaxPositiveHeight) + { + float half = MapHalfExtent; + float accelSize = AccelCellSize; + float minX = -half + cx * accelSize; + float maxX = minX + accelSize; + float minZ = -half + cz * accelSize; + float maxZ = minZ + accelSize; + + // Project all 4 cell corners into brush local (lx, lz) + float dx0 = minX - b.X, dx1 = maxX - b.X; + float dz0 = minZ - b.Z, dz1 = maxZ - b.Z; + float lx00 = dx0 * p.CosR + dz0 * p.SinR; + float lx10 = dx1 * p.CosR + dz0 * p.SinR; + float lx01 = dx0 * p.CosR + dz1 * p.SinR; + float lx11 = dx1 * p.CosR + dz1 * p.SinR; + + float lz00 = -dx0 * p.SinR + dz0 * p.CosR; + float lz10 = -dx1 * p.SinR + dz0 * p.CosR; + float lz01 = -dx0 * p.SinR + dz1 * p.CosR; + float lz11 = -dx1 * p.SinR + dz1 * p.CosR; + + float minLx = MathF.Min(MathF.Min(lx00, lx10), MathF.Min(lx01, lx11)); + float maxLx = MathF.Max(MathF.Max(lx00, lx10), MathF.Max(lx01, lx11)); + float minLz = MathF.Min(MathF.Min(lz00, lz10), MathF.Min(lz01, lz11)); + float maxLz = MathF.Max(MathF.Max(lz00, lz10), MathF.Max(lz01, lz11)); + + float absMinLx = (minLx <= 0f && maxLx >= 0f) ? 0f : MathF.Min(MathF.Abs(minLx), MathF.Abs(maxLx)); + float absMinLz = (minLz <= 0f && maxLz >= 0f) ? 0f : MathF.Min(MathF.Abs(minLz), MathF.Abs(maxLz)); + + float minU = absMinLx * p.InvRx; + float minV = absMinLz * p.InvRz; + float minR2 = minU * minU + minV * minV; + if (minR2 >= 1f) + { + cellMaxPositiveHeight = 0f; + return false; + } + + switch (b.Kind) + { + case TerrainBrushKind.DuneRidge: + { + if (b.HeightDelta <= 0f) + { + cellMaxPositiveHeight = 0f; + } + else + { + float env = 1f - minR2; + env *= env; + float ridge = MathF.Max(0f, 1f - minU * minU); + float maxAsym = MathF.Max(0f, 1f + 0.32f * (maxLx * p.InvRx)); + cellMaxPositiveHeight = b.HeightDelta * env * (0.35f + 0.65f * ridge) * maxAsym; + } + break; + } + case TerrainBrushKind.Mesa: + { + if (b.HeightDelta <= 0f) + { + cellMaxPositiveHeight = 0f; + } + else + { + float r = MathF.Sqrt(minR2); + float t = Math.Clamp((1f - r) / 0.45f, 0f, 1f); + cellMaxPositiveHeight = b.HeightDelta * t * t * (3f - 2f * t); + } + break; + } + case TerrainBrushKind.SalvagePad: + case TerrainBrushKind.Road: + case TerrainBrushKind.Track: + { + if (b.HeightDelta <= 0f) + { + cellMaxPositiveHeight = 0f; + } + else + { + float env = 1f - minR2; + cellMaxPositiveHeight = b.HeightDelta * env * env; + } + break; + } + case TerrainBrushKind.Crater: + cellMaxPositiveHeight = 0.33f * MathF.Abs(b.HeightDelta); + break; + case TerrainBrushKind.Rubble: + { + float env = 1f - minR2; + cellMaxPositiveHeight = MathF.Max(0f, b.HeightDelta) * env * env; + break; + } + default: + cellMaxPositiveHeight = 0f; + break; + } + + return true; + } + + private void RecomputeCellMaxHeight(int cx, int cz) + { + int cellIdx = cz * AccelGridCount + cx; + float sum = _cellBaseMaxHeight[cellIdx]; + var indices = _cellBrushIndices[cellIdx]; + for (int i = 0; i < indices.Count; i++) + { + int bIdx = indices[i]; + if (TryGetBrushCellBounds(_brushes[bIdx], _brushPrecomps[bIdx], cx, cz, out float h)) + { + sum += h; + } + } + _cellMaxHeight[cellIdx] = Math.Min(MapMaxHeight, sum); + } + + private void RegisterBrushInTiles(int index, in TerrainBrush brush, bool incrementTileVersion) + { + bool isStructural = brush.Kind != TerrainBrushKind.Track && brush.Kind != TerrainBrushKind.Scorch; + GetBrushTileBounds(in brush, out int minTx, out int maxTx, out int minTz, out int maxTz); + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + _tileBrushIndices[tx, tz].Add(index); + if (incrementTileVersion) + { + VisualTileVersions[tx, tz]++; + if (isStructural) + { + StructuralTileVersions[tx, tz]++; + _scarredTileHeights[tx, tz] = null; + } + } + } + } + + if (brush.Kind != TerrainBrushKind.Scorch) + { + var precomp = _brushPrecomps[index]; + GetBrushAccelBounds(in brush, out int minCx, out int maxCx, out int minCz, out int maxCz); + for (int cz = minCz; cz <= maxCz; cz++) + { + for (int cx = minCx; cx <= maxCx; cx++) + { + if (TryGetBrushCellBounds(in brush, in precomp, cx, cz, out float cellMaxPos)) + { + int cellIdx = cz * AccelGridCount + cx; + _cellBrushIndices[cellIdx].Add(index); + _cellMaxHeight[cellIdx] = Math.Min(MapMaxHeight, _cellMaxHeight[cellIdx] + cellMaxPos); + } + } + } + } + } + + private void UnregisterBrushFromTiles(int index, in TerrainBrush brush) + { + bool isStructural = brush.Kind != TerrainBrushKind.Track && brush.Kind != TerrainBrushKind.Scorch; + GetBrushTileBounds(in brush, out int minTx, out int maxTx, out int minTz, out int maxTz); + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + _tileBrushIndices[tx, tz].Remove(index); + VisualTileVersions[tx, tz]++; + if (isStructural) + { + StructuralTileVersions[tx, tz]++; + _scarredTileHeights[tx, tz] = null; + } + } + } + + if (brush.Kind != TerrainBrushKind.Scorch) + { + GetBrushAccelBounds(in brush, out int minCx, out int maxCx, out int minCz, out int maxCz); + for (int cz = minCz; cz <= maxCz; cz++) + { + for (int cx = minCx; cx <= maxCx; cx++) + { + int cellIdx = cz * AccelGridCount + cx; + _cellBrushIndices[cellIdx].Remove(index); + RecomputeCellMaxHeight(cx, cz); + } + } + } + } + + private void GetBrushAccelBounds(in TerrainBrush brush, out int minCx, out int maxCx, out int minCz, out int maxCz) + { + float half = MapHalfExtent; + float extent = MathF.Max(0.1f, MathF.Max(brush.RadiusX, brush.RadiusZ)) + 0.1f; + WorldToAccelCell(Math.Clamp(brush.X - extent, -half, half), Math.Clamp(brush.Z - extent, -half, half), out minCx, out minCz); + WorldToAccelCell(Math.Clamp(brush.X + extent, -half, half), Math.Clamp(brush.Z + extent, -half, half), out maxCx, out maxCz); + } + + private void WorldToAccelCell(float x, float z, out int cx, out int cz) + { + float half = MapHalfExtent; + float accelSize = AccelCellSize; + float nx = (x + half) / accelSize; + float nz = (z + half) / accelSize; + cx = Math.Clamp((int)MathF.Floor(nx), 0, AccelGridCount - 1); + cz = Math.Clamp((int)MathF.Floor(nz), 0, AccelGridCount - 1); + } + + private void GetBrushTileBounds(in TerrainBrush brush, out int minTx, out int maxTx, out int minTz, out int maxTz) + { + const float gutterPaddingMeters = 3.5f; + float half = MapHalfExtent; + float extent = MathF.Sqrt(brush.RadiusX * brush.RadiusX + brush.RadiusZ * brush.RadiusZ) + gutterPaddingMeters; + float minX = brush.X - extent; + float maxX = brush.X + extent; + float minZ = brush.Z - extent; + float maxZ = brush.Z + extent; + + MapWorldToTile(Math.Clamp(minX, -half, half), Math.Clamp(minZ, -half, half), out minTx, out minTz); + MapWorldToTile(Math.Clamp(maxX, -half, half), Math.Clamp(maxZ, -half, half), out maxTx, out maxTz); + } + + public void MapWorldToTile(float x, float z, out int tx, out int tz) + { + float nx = (x + MapHalfExtent) / MapTileSize; + float nz = (z + MapHalfExtent) / MapTileSize; + tx = Math.Clamp((int)MathF.Floor(nx), 0, TileGridCount - 1); + tz = Math.Clamp((int)MathF.Floor(nz), 0, TileGridCount - 1); + } + + public static void WorldToTile(float x, float z, out int tx, out int tz) + { + float nx = (x + HalfExtent) / TileSize; + float nz = (z + HalfExtent) / TileSize; + tx = Math.Clamp((int)MathF.Floor(nx), 0, DesertTileGridCount - 1); + tz = Math.Clamp((int)MathF.Floor(nz), 0, DesertTileGridCount - 1); + } + + private static bool IsBrushClearOfCover(in TerrainBrush candidate, IReadOnlyList coverBoxes) + { + if (MathF.Abs(EvaluateBrushHeight(in candidate, 0f, 0f)) > 0.25f) + { + return false; + } + + const float margin = 2.0f; + for (int i = 0; i < coverBoxes.Count; i++) + { + var c = coverBoxes[i]; + float hx = c.HalfX + margin; + float hz = c.HalfZ + margin; + + if (MathF.Abs(EvaluateBrushHeight(in candidate, c.X, c.Z)) > 0.25f || + MathF.Abs(EvaluateBrushHeight(in candidate, c.X - hx, c.Z - hz)) > 0.25f || + MathF.Abs(EvaluateBrushHeight(in candidate, c.X + hx, c.Z - hz)) > 0.25f || + MathF.Abs(EvaluateBrushHeight(in candidate, c.X - hx, c.Z + hz)) > 0.25f || + MathF.Abs(EvaluateBrushHeight(in candidate, c.X + hx, c.Z + hz)) > 0.25f) + { + return false; + } + } + return true; + } + } +} diff --git a/src/RustToDust.Core/VehicleCatalogLoader.cs b/src/RustToDust.Core/VehicleCatalogLoader.cs new file mode 100644 index 0000000..06a472c --- /dev/null +++ b/src/RustToDust.Core/VehicleCatalogLoader.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace RustToDust.Core +{ + public static class VehicleCatalogLoader + { + public static string LocateVehiclesDirectory() => + AssetPathResolver.LocateSubdirectory( + "vehicles", + HasVehiclePackages, + "containing vehicle.cc packages"); + + private static bool HasVehiclePackages(string vehiclesDir) + { + if (!Directory.Exists(vehiclesDir)) + { + return false; + } + return Directory.EnumerateFiles(vehiclesDir, "vehicle.cc", SearchOption.AllDirectories).Any(); + } + + public static IReadOnlyList<(VehiclePackage Package, ChassisSpec Spec)> LoadAll(string? vehiclesDirectory = null) + { + string root = vehiclesDirectory ?? LocateVehiclesDirectory(); + if (!Directory.Exists(root)) + { + throw new DirectoryNotFoundException($"Vehicles directory not found: {root}"); + } + + var results = new List<(VehiclePackage Package, ChassisSpec Spec)>(); + foreach (string dir in Directory.GetDirectories(root).OrderBy(d => d, StringComparer.Ordinal)) + { + string ccPath = Path.Combine(dir, "vehicle.cc"); + if (!File.Exists(ccPath)) + { + continue; + } + + var pkg = VehiclePackageStore.Read(ccPath); + var spec = pkg.ToChassisSpec(); + results.Add((pkg, spec)); + } + + if (results.Count == 0) + { + throw new InvalidOperationException($"No vehicle.cc archives found under {root}."); + } + + return results; + } + } +} diff --git a/src/RustToDust.Core/VehiclePackage.cs b/src/RustToDust.Core/VehiclePackage.cs new file mode 100644 index 0000000..2d8a0b0 --- /dev/null +++ b/src/RustToDust.Core/VehiclePackage.cs @@ -0,0 +1,339 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; + +namespace RustToDust.Core +{ + [CultDocument("rtd.vehicle_package", "1"), MessagePackObject] + public sealed class VehiclePackage + { + [CultName, Key(0)] public string Id { get; set; } = string.Empty; + [Key(1)] public string Name { get; set; } = string.Empty; + [Key(2)] public string VehicleClass { get; set; } = string.Empty; + [Key(3)] public MobilityKind Mobility { get; set; } + [Key(4)] public GridPlane Plane { get; set; } + [Key(5)] public int GridWidth { get; set; } + [Key(6)] public int GridHeight { get; set; } + [Key(7)] public string[] Mask { get; set; } = Array.Empty(); + [Key(8)] public float MassKg { get; set; } + [Key(9)] public float MaxSpeed { get; set; } + [Key(10)] public float TurnRate { get; set; } + [Key(11)] public float ThrustNewtons { get; set; } + [Key(12)] public float HoverMaxAltitudeM { get; set; } + [Key(13)] public float ArmorPerCell { get; set; } + [Key(14)] public float Conductivity { get; set; } + [Key(15)] public int CargoCapacity { get; set; } + [Key(16)] public float HalfWidth { get; set; } + [Key(17)] public float HalfHeight { get; set; } + [Key(18)] public float HalfLength { get; set; } + [Key(19)] public string ModelAsset { get; set; } = string.Empty; + [Key(20)] public Dictionary DefaultLoadout { get; set; } = new(); + [Key(21)] public List Hardpoints { get; set; } = new(); + [Key(22)] public List Joints { get; set; } = new(); + [Key(23)] public VehicleMechanismsRecord? Mechanisms { get; set; } + [Key(24)] public List PartCells { get; set; } = new(); + [Key(25)] public float BaseCellThermalMass { get; set; } = 12f; + + public ChassisSpec ToChassisSpec() + { + bool[] boolMask = ParseMaskRows(Mask, GridWidth, GridHeight); + var hps = new HardpointSpec[Hardpoints.Count]; + for (int i = 0; i < Hardpoints.Count; i++) + { + var hp = Hardpoints[i]; + hps[i] = new HardpointSpec( + Id: hp.Id, + Kind: hp.Kind, + X: hp.X, + Y: hp.Y, + Width: hp.W, + Height: hp.H, + ArmorBonus: hp.ArmorBonus, + MinPitchDeg: hp.MinPitchDeg, + MaxPitchDeg: hp.MaxPitchDeg, + IsWideArc: hp.IsWideArc); + } + + return new ChassisSpec( + Id: Id, + Name: Name, + Plane: Plane, + Width: GridWidth, + Height: GridHeight, + Mask: boolMask, + Hardpoints: hps, + HullConductivity: Conductivity, + BaseCellThermalMass: BaseCellThermalMass, + BaseCellArmor: ArmorPerCell, + MassKg: MassKg, + BaseThrust: ThrustNewtons, + BaseTurnRate: TurnRate, + MaxSpeed: MaxSpeed, + HalfWidth: HalfWidth, + HalfHeight: HalfHeight, + HalfLength: HalfLength, + CargoCapacity: CargoCapacity, + Mobility: Mobility, + HoverMaxAltitudeM: HoverMaxAltitudeM, + VehicleClass: VehicleClass); + } + + public static bool[] ParseMaskRows(string[] rows, int width, int height) + { + if (rows.Length != height) + { + throw new InvalidOperationException($"Mask row count {rows.Length} != GridHeight {height}."); + } + + var mask = new bool[width * height]; + for (int y = 0; y < height; y++) + { + if (rows[y].Length != width) + { + throw new InvalidOperationException($"Mask row {y} length {rows[y].Length} != GridWidth {width}."); + } + for (int x = 0; x < width; x++) + { + mask[y * width + x] = rows[y][x] == '#'; + } + } + return mask; + } + } + + [MessagePackObject] + public sealed class VehicleHardpointRecord + { + [Key(0)] public string Id { get; set; } = string.Empty; + [Key(1)] public string AnchorId { get; set; } = string.Empty; + [Key(2)] public HardpointKind Kind { get; set; } + [Key(3)] public int X { get; set; } + [Key(4)] public int Y { get; set; } + [Key(5)] public int W { get; set; } + [Key(6)] public int H { get; set; } + [Key(7)] public float MinPitchDeg { get; set; } + [Key(8)] public float MaxPitchDeg { get; set; } + [Key(9)] public bool IsWideArc { get; set; } + [Key(10)] public float ArmorBonus { get; set; } + [Key(11), CultElementId(nameof(Id))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class VehicleJointRecord + { + [Key(0)] public string Id { get; set; } = string.Empty; + [Key(1)] public string NodeName { get; set; } = string.Empty; + [Key(2)] public float[] Axis { get; set; } = Array.Empty(); + [Key(3)] public float MinVal { get; set; } + [Key(4)] public float MaxVal { get; set; } + [Key(5), CultElementId(nameof(Id))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class VehiclePartCellRecord + { + [Key(0)] public string NodeName { get; set; } = string.Empty; + [Key(1)] public int CellX { get; set; } + [Key(2)] public int CellY { get; set; } + [Key(3)] public string Kind { get; set; } = string.Empty; + [Key(4), CultElementId] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class VehicleMechanismsRecord + { + [Key(0)] public string Frame { get; set; } = string.Empty; + [Key(1)] public float[] RootOrigin { get; set; } = Array.Empty(); + [Key(2)] public List Dofs { get; set; } = new(); + [Key(3)] public List Rams { get; set; } = new(); + [Key(4)] public List Scissors { get; set; } = new(); + [Key(5)] public List Struts { get; set; } = new(); + } + + [MessagePackObject] + public sealed class MechanismDofRecord + { + [Key(0)] public string Name { get; set; } = string.Empty; + [Key(1)] public int Parent { get; set; } + [Key(2)] public string Kind { get; set; } = string.Empty; + [Key(3)] public string? Mechanism { get; set; } + [Key(4)] public string? Side { get; set; } + [Key(5)] public float[] Origin { get; set; } = Array.Empty(); + [Key(6)] public float[] Axis { get; set; } = Array.Empty(); + [Key(7)] public float Lo { get; set; } + [Key(8)] public float Hi { get; set; } + [Key(9)] public int Depth { get; set; } + [Key(10)] public string? StoppedBy { get; set; } + [Key(11)] public float? ComplianceDampingRatio { get; set; } + [Key(12)] public float? ComplianceHertz { get; set; } + [Key(13), CultElementId(nameof(Name))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class MechanismRamRecord + { + [Key(0)] public string Name { get; set; } = string.Empty; + [Key(1)] public string BarrelBone { get; set; } = string.Empty; + [Key(2)] public string RodBone { get; set; } = string.Empty; + [Key(3)] public string[] Spans { get; set; } = Array.Empty(); + [Key(4)] public float Bore { get; set; } + [Key(5)] public float Body { get; set; } + [Key(6)] public float Inner { get; set; } + [Key(7)] public float Extension { get; set; } + [Key(8)] public float Rest { get; set; } + [Key(9)] public float[] Stroke { get; set; } = Array.Empty(); + [Key(10)] public int? AParentDof { get; set; } + [Key(11)] public float[]? APos { get; set; } + [Key(12)] public int? BParentDof { get; set; } + [Key(13)] public float[]? BPos { get; set; } + [Key(14)] public float[]? PinDir { get; set; } + [Key(15), CultElementId(nameof(Name))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class MechanismScissorRecord + { + [Key(0)] public string Name { get; set; } = string.Empty; + [Key(1)] public string UpperBone { get; set; } = string.Empty; + [Key(2)] public string LowerBone { get; set; } = string.Empty; + [Key(3)] public float Arm { get; set; } + [Key(4)] public int? AParentDof { get; set; } + [Key(5)] public float[]? APos { get; set; } + [Key(6)] public int? BParentDof { get; set; } + [Key(7)] public float[]? BPos { get; set; } + [Key(8)] public float[]? OutDir { get; set; } + [Key(9), CultElementId(nameof(Name))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class MechanismStrutRecord + { + [Key(0)] public string Name { get; set; } = string.Empty; + [Key(1)] public string? Side { get; set; } + [Key(2)] public string Dof { get; set; } = string.Empty; + [Key(3)] public float Travel { get; set; } + [Key(4)] public float Hertz { get; set; } + [Key(5)] public float DampingRatio { get; set; } + [Key(6), CultElementId(nameof(Name))] public string ElementId { get; set; } = string.Empty; + } + + public static class VehiclePackageStore + { + public static CultDocumentRegistry Registry { get; } = + CultDocumentRegistry.ForTypes(new[] { typeof(VehiclePackage) }); + + public static CultRecordKey PackageKey(string id) => new("vehicle:" + id); + + public static CultCache Open(string path, bool writable = false) + { + var options = new CultCacheOpenOptions + { + Registry = Registry, + ReadOnly = !writable, + FlushOnDispose = false, + StoreFlushOnDispose = false, + UseDirectoryStore = false + }; + return CultCacheMessagePack.Create(path, options); + } + + public static VehiclePackage Read(string path) + { + if (!File.Exists(path)) + { + throw new FileNotFoundException($"Vehicle package archive not found: {path}", path); + } + + using var cache = Open(path, writable: false); + var records = cache.GetAll().ToArray(); + if (records.Length != 1) + { + throw new InvalidOperationException($"{path} must contain exactly 1 VehiclePackage record, found {records.Length}."); + } + + var pkg = records[0]; + Validate(pkg, path); + return pkg; + } + + public static void Write(string path, VehiclePackage pkg) + { + if (pkg is null) throw new ArgumentNullException(nameof(pkg)); + Validate(pkg, path); + + string fullPath = Path.GetFullPath(path); + string dir = Path.GetDirectoryName(fullPath) ?? "."; + Directory.CreateDirectory(dir); + + string workspace = fullPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; + string tempFile = Path.Combine(workspace, "vehicle.cc"); + try + { + Directory.CreateDirectory(workspace); + using (var cache = Open(tempFile, writable: true)) + { + cache.UpsertAsync(typeof(VehiclePackage), pkg, PackageKey(pkg.Id)).GetAwaiter().GetResult(); + cache.FlushAsync().GetAwaiter().GetResult(); + } + + if (File.Exists(fullPath)) + { + File.Replace(tempFile, fullPath, null); + } + else + { + File.Move(tempFile, fullPath); + } + } + finally + { + if (Directory.Exists(workspace)) + { + Directory.Delete(workspace, recursive: true); + } + } + } + + public static void Validate(VehiclePackage pkg, string sourcePath) + { + if (string.IsNullOrWhiteSpace(pkg.Id)) + throw new InvalidOperationException($"{sourcePath}: VehiclePackage.Id is empty."); + if (string.IsNullOrWhiteSpace(pkg.ModelAsset)) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: ModelAsset is empty."); + if (pkg.GridWidth <= 0 || pkg.GridHeight <= 0) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: invalid grid dimensions {pkg.GridWidth}x{pkg.GridHeight}."); + + bool[] mask = VehiclePackage.ParseMaskRows(pkg.Mask, pkg.GridWidth, pkg.GridHeight); + foreach (var hp in pkg.Hardpoints) + { + if (string.IsNullOrWhiteSpace(hp.Id) || string.IsNullOrWhiteSpace(hp.AnchorId)) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: hardpoint has empty Id or AnchorId."); + if (hp.X < 0 || hp.Y < 0 || hp.W <= 0 || hp.H <= 0 || hp.X + hp.W > pkg.GridWidth || hp.Y + hp.H > pkg.GridHeight) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: hardpoint {hp.Id} out of grid bounds."); + for (int cy = hp.Y; cy < hp.Y + hp.H; cy++) + { + for (int cx = hp.X; cx < hp.X + hp.W; cx++) + { + if (!mask[cy * pkg.GridWidth + cx]) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: hardpoint {hp.Id} covers inactive cell ({cx},{cy})."); + } + } + } + + if (pkg.PartCells.Count == 0) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: PartCells is empty."); + + foreach (var pc in pkg.PartCells) + { + if (pc.CellX < 0 || pc.CellX >= pkg.GridWidth || pc.CellY < 0 || pc.CellY >= pkg.GridHeight || !mask[pc.CellY * pkg.GridWidth + pc.CellX]) + { + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: PartCell '{pc.NodeName}' mapped to inactive/out-of-bounds cell ({pc.CellX},{pc.CellY})."); + } + } + } + } +} diff --git a/src/RustToDust.Core/WalkerVisualSnapshot.cs b/src/RustToDust.Core/WalkerVisualSnapshot.cs new file mode 100644 index 0000000..f1de4e8 --- /dev/null +++ b/src/RustToDust.Core/WalkerVisualSnapshot.cs @@ -0,0 +1,73 @@ +using System; +using System.Numerics; +using System.Runtime.CompilerServices; + +namespace RustToDust.Core +{ + [InlineArray(4)] + public struct LegArray4 + { + private T _element0; + } + + public struct WalkerLegAngles + { + public float HipPitch; + public float HipRoll; + public float KneeFlex; + public float HockFlex; + public float AnklePitch; + + public static WalkerLegAngles Lerp(in WalkerLegAngles a, in WalkerLegAngles b, float t) => new() + { + HipPitch = a.HipPitch + (b.HipPitch - a.HipPitch) * t, + HipRoll = a.HipRoll + (b.HipRoll - a.HipRoll) * t, + KneeFlex = a.KneeFlex + (b.KneeFlex - a.KneeFlex) * t, + HockFlex = a.HockFlex + (b.HockFlex - a.HockFlex) * t, + AnklePitch = a.AnklePitch + (b.AnklePitch - a.AnklePitch) * t + }; + } + + public struct WalkerVisualSnapshot + { + public int LegCount; + public float GeomScale; + public bool IsDigitigrade; + public bool IsArachnidUp; + public Vector3 ComPos; + public Quaternion ComRot; + public LegArray4 LegAngles; + public LegArray4 FootNormal; + public LegArray4 LoadG; + + public static WalkerVisualSnapshot Interpolate(in WalkerVisualSnapshot prev, in WalkerVisualSnapshot curr, float alpha) + { + float t = Math.Clamp(alpha, 0f, 1f); + Quaternion q0 = prev.ComRot.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(prev.ComRot); + Quaternion q1 = curr.ComRot.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(curr.ComRot); + if (Quaternion.Dot(q0, q1) < 0f) + { + q1 = -q1; + } + + WalkerVisualSnapshot res = new() + { + LegCount = curr.LegCount, + GeomScale = curr.GeomScale, + IsDigitigrade = curr.IsDigitigrade, + IsArachnidUp = curr.IsArachnidUp, + ComPos = Vector3.Lerp(prev.ComPos, curr.ComPos, t), + ComRot = Quaternion.Slerp(q0, q1, t) + }; + + for (int i = 0; i < curr.LegCount; i++) + { + res.LegAngles[i] = WalkerLegAngles.Lerp(prev.LegAngles[i], curr.LegAngles[i], t); + Vector3 n = Vector3.Lerp(prev.FootNormal[i], curr.FootNormal[i], t); + res.FootNormal[i] = n.LengthSquared() > 1e-6f ? Vector3.Normalize(n) : Vector3.UnitY; + res.LoadG[i] = prev.LoadG[i] + (curr.LoadG[i] - prev.LoadG[i]) * t; + } + return res; + } + } +} diff --git a/src/RustToDust.Directory/DirectoryDtos.cs b/src/RustToDust.Directory/DirectoryDtos.cs new file mode 100644 index 0000000..1b7268c --- /dev/null +++ b/src/RustToDust.Directory/DirectoryDtos.cs @@ -0,0 +1,45 @@ +using System; + +namespace RustToDust.DirectoryService +{ + public sealed class DirectoryHeartbeatRequest + { + public Guid? ServerId { get; set; } + public string? LeaseToken { get; set; } + public string Name { get; set; } = "Rust to Dust"; + public string? PublicHost { get; set; } + public int UdpPort { get; set; } + public string Map { get; set; } = "desert"; + public int Seed { get; set; } = 42; + public int Humans { get; set; } + public int MaxHumans { get; set; } = 12; + public string Phase { get; set; } = "Active"; + public int Wave { get; set; } + public int ProtocolVersion { get; set; } = 1; + public bool HasPassword { get; set; } + } + + public sealed class DirectoryHeartbeatResponse + { + public Guid ServerId { get; set; } + public string LeaseToken { get; set; } = string.Empty; + public int TtlSeconds { get; set; } + } + + public sealed class DirectoryServerView + { + public Guid ServerId { get; set; } + public string Name { get; set; } = string.Empty; + public string PublicHost { get; set; } = string.Empty; + public int UdpPort { get; set; } + public string Map { get; set; } = string.Empty; + public int Seed { get; set; } + public int Humans { get; set; } + public int MaxHumans { get; set; } + public string Phase { get; set; } = string.Empty; + public int Wave { get; set; } + public int ProtocolVersion { get; set; } + public bool HasPassword { get; set; } + public DateTimeOffset ExpiresAtUtc { get; set; } + } +} diff --git a/src/RustToDust.Directory/DirectoryRegistry.cs b/src/RustToDust.Directory/DirectoryRegistry.cs new file mode 100644 index 0000000..cfa1198 --- /dev/null +++ b/src/RustToDust.Directory/DirectoryRegistry.cs @@ -0,0 +1,421 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Security.Cryptography; +using System.Text; + +namespace RustToDust.DirectoryService +{ + public sealed class DirectoryRegistryOptions + { + public TimeSpan EntryTtl { get; set; } = TimeSpan.FromSeconds(25); + public TimeSpan ReaperInterval { get; set; } = TimeSpan.FromSeconds(5); + public int MaxEntries { get; set; } = 256; + public int MaxEntriesPerIp { get; set; } = 8; + public int HeartbeatLimitPerMinute { get; set; } = 120; + public int ListLimitPerMinute { get; set; } = 60; + public Func UtcNow { get; set; } = () => DateTimeOffset.UtcNow; + } + + public enum DirectoryOpStatus + { + Ok = 200, + NoContent = 204, + BadRequest = 400, + Forbidden = 403, + NotFound = 404, + Conflict = 409, + TooManyRequests = 429, + ServiceUnavailable = 503 + } + + public readonly record struct DirectoryOpResult(DirectoryOpStatus Status, T? Value, string? Error = null); + + public sealed class DirectoryRegistry + { + private sealed class RegistryEntry + { + public Guid ServerId; + public string LeaseToken = string.Empty; + public byte[] LeaseTokenBytes = Array.Empty(); + public string OwnerIp = string.Empty; + public string Name = string.Empty; + public string PublicHost = string.Empty; + public int UdpPort; + public string Map = string.Empty; + public int Seed; + public int Humans; + public int MaxHumans; + public string Phase = string.Empty; + public int Wave; + public int ProtocolVersion; + public bool HasPassword; + public DateTimeOffset ExpiresAtUtc; + } + + private sealed class RateWindow + { + public long MinuteBucket; + public int Count; + } + + private readonly object _gate = new(); + private readonly Dictionary _entries = new(); + private readonly Dictionary _heartbeatRates = new(StringComparer.Ordinal); + private readonly Dictionary _listRates = new(StringComparer.Ordinal); + private readonly DirectoryRegistryOptions _options; + + public DirectoryRegistry(DirectoryRegistryOptions? options = null) + { + _options = options ?? new DirectoryRegistryOptions(); + } + + public int Count + { + get + { + lock (_gate) + { + PurgeExpiredLocked(_options.UtcNow()); + return _entries.Count; + } + } + } + + public DirectoryOpResult UpsertHeartbeat(DirectoryHeartbeatRequest req, IPAddress callerIp) + { + if (req is null) + { + return new(DirectoryOpStatus.BadRequest, null, "Request body required."); + } + + IPAddress normalizedCaller = NormalizeIp(callerIp); + string callerKey = normalizedCaller.ToString(); + DateTimeOffset now = _options.UtcNow(); + + lock (_gate) + { + PurgeExpiredLocked(now); + + if (!AllowRateLocked(_heartbeatRates, callerKey, now, _options.HeartbeatLimitPerMinute)) + { + return new(DirectoryOpStatus.TooManyRequests, null, "Heartbeat rate limit exceeded."); + } + + if (req.UdpPort < 1 || req.UdpPort > 65535) + { + return new(DirectoryOpStatus.BadRequest, null, "udpPort must be in 1..65535."); + } + + string resolvedHost; + if (string.IsNullOrWhiteSpace(req.PublicHost) || + string.Equals(req.PublicHost.Trim(), "auto", StringComparison.OrdinalIgnoreCase)) + { + resolvedHost = callerKey; + } + else + { + resolvedHost = req.PublicHost.Trim(); + if (resolvedHost.Length > 253 || ContainsWhitespaceOrControl(resolvedHost)) + { + return new(DirectoryOpStatus.BadRequest, null, "Invalid publicHost."); + } + + if (!IPAddress.IsLoopback(normalizedCaller) && IsLoopbackOrWildcardHost(resolvedHost)) + { + return new(DirectoryOpStatus.BadRequest, null, "Non-loopback callers cannot advertise a loopback or wildcard publicHost."); + } + } + + string cleanName = SanitizeLabel(req.Name, "Rust to Dust", 48); + string cleanMap = SanitizeLabel(req.Map, "desert", 24).ToLowerInvariant(); + string cleanPhase = SanitizeLabel(req.Phase, "Active", 16); + int maxHumans = Math.Clamp(req.MaxHumans, 1, 12); + int humans = Math.Clamp(req.Humans, 0, maxHumans); + int wave = Math.Max(0, req.Wave); + int protocolVersion = Math.Max(1, req.ProtocolVersion); + + if (req.ServerId is { } serverId && serverId != Guid.Empty) + { + if (!_entries.TryGetValue(serverId, out var existing)) + { + return new(DirectoryOpStatus.Conflict, null, "Unknown or expired serverId."); + } + + if (!VerifyLeaseToken(existing, req.LeaseToken)) + { + return new(DirectoryOpStatus.Forbidden, null, "Invalid leaseToken."); + } + + existing.Name = cleanName; + existing.PublicHost = resolvedHost; + existing.UdpPort = req.UdpPort; + existing.Map = cleanMap; + existing.Seed = req.Seed; + existing.Humans = humans; + existing.MaxHumans = maxHumans; + existing.Phase = cleanPhase; + existing.Wave = wave; + existing.ProtocolVersion = protocolVersion; + existing.HasPassword = req.HasPassword; + existing.ExpiresAtUtc = now + _options.EntryTtl; + + return new(DirectoryOpStatus.Ok, new DirectoryHeartbeatResponse + { + ServerId = existing.ServerId, + LeaseToken = existing.LeaseToken, + TtlSeconds = Math.Max(1, (int)Math.Ceiling(_options.EntryTtl.TotalSeconds)) + }); + } + + if (_entries.Count >= _options.MaxEntries) + { + return new(DirectoryOpStatus.ServiceUnavailable, null, "Directory capacity reached."); + } + + int ipCount = 0; + foreach (var entry in _entries.Values) + { + if (string.Equals(entry.OwnerIp, callerKey, StringComparison.Ordinal)) + { + ipCount++; + } + } + if (ipCount >= _options.MaxEntriesPerIp) + { + return new(DirectoryOpStatus.TooManyRequests, null, "Per-IP server registration limit reached."); + } + + Guid newId = Guid.NewGuid(); + string token = Convert.ToHexString(RandomNumberGenerator.GetBytes(24)).ToLowerInvariant(); + var created = new RegistryEntry + { + ServerId = newId, + LeaseToken = token, + LeaseTokenBytes = Encoding.UTF8.GetBytes(token), + OwnerIp = callerKey, + Name = cleanName, + PublicHost = resolvedHost, + UdpPort = req.UdpPort, + Map = cleanMap, + Seed = req.Seed, + Humans = humans, + MaxHumans = maxHumans, + Phase = cleanPhase, + Wave = wave, + ProtocolVersion = protocolVersion, + HasPassword = req.HasPassword, + ExpiresAtUtc = now + _options.EntryTtl + }; + _entries[newId] = created; + + return new(DirectoryOpStatus.Ok, new DirectoryHeartbeatResponse + { + ServerId = created.ServerId, + LeaseToken = created.LeaseToken, + TtlSeconds = Math.Max(1, (int)Math.Ceiling(_options.EntryTtl.TotalSeconds)) + }); + } + } + + public DirectoryOpResult DeleteServer(Guid serverId, string? leaseToken) + { + if (serverId == Guid.Empty) + { + return new(DirectoryOpStatus.BadRequest, null, "Invalid serverId."); + } + + DateTimeOffset now = _options.UtcNow(); + lock (_gate) + { + PurgeExpiredLocked(now); + + if (!_entries.TryGetValue(serverId, out var existing)) + { + return new(DirectoryOpStatus.NotFound, null, "Server not found."); + } + + if (!VerifyLeaseToken(existing, leaseToken)) + { + return new(DirectoryOpStatus.Forbidden, null, "Invalid leaseToken."); + } + + _entries.Remove(serverId); + return new(DirectoryOpStatus.NoContent, null); + } + } + + public DirectoryOpResult> ListServers(IPAddress callerIp) + { + string callerKey = NormalizeIp(callerIp).ToString(); + DateTimeOffset now = _options.UtcNow(); + + lock (_gate) + { + PurgeExpiredLocked(now); + + if (!AllowRateLocked(_listRates, callerKey, now, _options.ListLimitPerMinute)) + { + return new(DirectoryOpStatus.TooManyRequests, null, "List rate limit exceeded."); + } + + var list = new List(_entries.Count); + foreach (var entry in _entries.Values) + { + list.Add(new DirectoryServerView + { + ServerId = entry.ServerId, + Name = entry.Name, + PublicHost = entry.PublicHost, + UdpPort = entry.UdpPort, + Map = entry.Map, + Seed = entry.Seed, + Humans = entry.Humans, + MaxHumans = entry.MaxHumans, + Phase = entry.Phase, + Wave = entry.Wave, + ProtocolVersion = entry.ProtocolVersion, + HasPassword = entry.HasPassword, + ExpiresAtUtc = entry.ExpiresAtUtc + }); + } + + list.Sort((a, b) => + { + int cmp = b.Humans.CompareTo(a.Humans); + return cmp != 0 ? cmp : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); + }); + + return new(DirectoryOpStatus.Ok, list); + } + } + + public int SweepExpired() + { + DateTimeOffset now = _options.UtcNow(); + lock (_gate) + { + return PurgeExpiredLocked(now); + } + } + + private int PurgeExpiredLocked(DateTimeOffset now) + { + List? expired = null; + foreach (var kv in _entries) + { + if (kv.Value.ExpiresAtUtc <= now) + { + expired ??= new List(); + expired.Add(kv.Key); + } + } + if (expired is not null) + { + for (int i = 0; i < expired.Count; i++) + { + _entries.Remove(expired[i]); + } + } + + long currentBucket = now.ToUnixTimeSeconds() / 60; + PruneRateBucketsLocked(_heartbeatRates, currentBucket); + PruneRateBucketsLocked(_listRates, currentBucket); + + return expired?.Count ?? 0; + } + + private static void PruneRateBucketsLocked(Dictionary buckets, long currentBucket) + { + if (buckets.Count == 0) return; + List? stale = null; + foreach (var kv in buckets) + { + if (kv.Value.MinuteBucket < currentBucket) + { + stale ??= new List(); + stale.Add(kv.Key); + } + } + if (stale is not null) + { + for (int i = 0; i < stale.Count; i++) + { + buckets.Remove(stale[i]); + } + } + } + + private static bool AllowRateLocked(Dictionary buckets, string key, DateTimeOffset now, int limit) + { + if (limit <= 0) return true; + long bucket = now.ToUnixTimeSeconds() / 60; + if (!buckets.TryGetValue(key, out var win) || win.MinuteBucket != bucket) + { + win = new RateWindow { MinuteBucket = bucket, Count = 0 }; + buckets[key] = win; + } + win.Count++; + return win.Count <= limit; + } + + private static bool VerifyLeaseToken(RegistryEntry entry, string? suppliedToken) + { + if (string.IsNullOrEmpty(suppliedToken)) return false; + byte[] suppliedBytes = Encoding.UTF8.GetBytes(suppliedToken); + return suppliedBytes.Length == entry.LeaseTokenBytes.Length && + CryptographicOperations.FixedTimeEquals(entry.LeaseTokenBytes, suppliedBytes); + } + + private static IPAddress NormalizeIp(IPAddress ip) => + ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip; + + private static bool IsLoopbackOrWildcardHost(string host) + { + if (string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase) || + host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (IPAddress.TryParse(host, out var ip)) + { + ip = NormalizeIp(ip); + return IPAddress.IsLoopback(ip) || + ip.Equals(IPAddress.Any) || + ip.Equals(IPAddress.IPv6Any); + } + + return false; + } + + private static bool ContainsWhitespaceOrControl(string value) + { + for (int i = 0; i < value.Length; i++) + { + char ch = value[i]; + if (char.IsWhiteSpace(ch) || char.IsControl(ch)) + { + return true; + } + } + return false; + } + + private static string SanitizeLabel(string? raw, string fallback, int maxLen) + { + if (string.IsNullOrWhiteSpace(raw)) return fallback; + var sb = new StringBuilder(Math.Min(raw.Length, maxLen)); + string trimmed = raw.Trim(); + for (int i = 0; i < trimmed.Length && sb.Length < maxLen; i++) + { + char ch = trimmed[i]; + if (!char.IsControl(ch)) + { + sb.Append(ch); + } + } + return sb.Length == 0 ? fallback : sb.ToString(); + } + } +} diff --git a/src/RustToDust.Directory/Program.cs b/src/RustToDust.Directory/Program.cs new file mode 100644 index 0000000..08cd4d9 --- /dev/null +++ b/src/RustToDust.Directory/Program.cs @@ -0,0 +1,164 @@ +using System; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace RustToDust.DirectoryService +{ + public static class DirectoryApp + { + public static WebApplication Build(string[] args, DirectoryRegistryOptions? options = null) + { + var builder = WebApplication.CreateBuilder(args); + var resolvedOptions = options ?? new DirectoryRegistryOptions(); + var registry = new DirectoryRegistry(resolvedOptions); + + builder.Services.AddSingleton(resolvedOptions); + builder.Services.AddSingleton(registry); + builder.Services.AddHostedService(); + builder.Services.Configure(opts => + { + opts.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; + opts.KnownNetworks.Clear(); + opts.KnownProxies.Clear(); + opts.KnownProxies.Add(IPAddress.Loopback); + opts.KnownProxies.Add(IPAddress.IPv6Loopback); + }); + + var app = builder.Build(); + app.UseForwardedHeaders(); + + app.MapGet("/healthz", (DirectoryRegistry reg) => + Results.Ok(new { status = "ok", activeServers = reg.Count })); + + app.MapGet("/api/v1/servers", (HttpContext ctx, DirectoryRegistry reg) => + { + IPAddress callerIp = ResolveCallerIp(ctx); + var result = reg.ListServers(callerIp); + return result.Status switch + { + DirectoryOpStatus.Ok => Results.Ok(result.Value), + DirectoryOpStatus.TooManyRequests => Results.StatusCode(StatusCodes.Status429TooManyRequests), + _ => Results.BadRequest(new { error = result.Error }) + }; + }); + + app.MapPost("/api/v1/servers/heartbeat", (HttpContext ctx, DirectoryHeartbeatRequest req, DirectoryRegistry reg) => + { + IPAddress callerIp = ResolveCallerIp(ctx); + var result = reg.UpsertHeartbeat(req, callerIp); + return result.Status switch + { + DirectoryOpStatus.Ok => Results.Ok(result.Value), + DirectoryOpStatus.Forbidden => Results.StatusCode(StatusCodes.Status403Forbidden), + DirectoryOpStatus.Conflict => Results.Conflict(new { error = result.Error }), + DirectoryOpStatus.TooManyRequests => Results.StatusCode(StatusCodes.Status429TooManyRequests), + DirectoryOpStatus.ServiceUnavailable => Results.StatusCode(StatusCodes.Status503ServiceUnavailable), + _ => Results.BadRequest(new { error = result.Error }) + }; + }); + + app.MapDelete("/api/v1/servers/{serverId:guid}", (HttpContext ctx, Guid serverId, DirectoryRegistry reg) => + { + string? token = ExtractLeaseToken(ctx); + var result = reg.DeleteServer(serverId, token); + return result.Status switch + { + DirectoryOpStatus.NoContent => Results.NoContent(), + DirectoryOpStatus.Forbidden => Results.StatusCode(StatusCodes.Status403Forbidden), + DirectoryOpStatus.NotFound => Results.NotFound(new { error = result.Error }), + _ => Results.BadRequest(new { error = result.Error }) + }; + }); + + return app; + } + + private static IPAddress ResolveCallerIp(HttpContext ctx) + { + IPAddress remote = ctx.Connection.RemoteIpAddress ?? IPAddress.Loopback; + if (remote.IsIPv4MappedToIPv6) remote = remote.MapToIPv4(); + + // Only trust X-Real-IP when the immediate TCP peer is loopback (e.g. local nginx). + if (IPAddress.IsLoopback(remote) && + ctx.Request.Headers.TryGetValue("X-Real-IP", out var realIpValues)) + { + string raw = realIpValues.ToString().Trim(); + if (IPAddress.TryParse(raw, out var parsed)) + { + return parsed.IsIPv4MappedToIPv6 ? parsed.MapToIPv4() : parsed; + } + } + + return remote; + } + + private static string? ExtractLeaseToken(HttpContext ctx) + { + if (ctx.Request.Headers.TryGetValue("X-Lease-Token", out var headerVal)) + { + string t = headerVal.ToString().Trim(); + if (!string.IsNullOrEmpty(t)) return t; + } + if (ctx.Request.Headers.TryGetValue("Authorization", out var authVal)) + { + string auth = authVal.ToString().Trim(); + if (auth.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + { + string t = auth.Substring("Bearer ".Length).Trim(); + if (!string.IsNullOrEmpty(t)) return t; + } + } + if (ctx.Request.Query.TryGetValue("leaseToken", out var queryVal)) + { + string t = queryVal.ToString().Trim(); + if (!string.IsNullOrEmpty(t)) return t; + } + return null; + } + } + + internal sealed class DirectoryReaperService : BackgroundService + { + private readonly DirectoryRegistry _registry; + private readonly DirectoryRegistryOptions _options; + + public DirectoryReaperService(DirectoryRegistry registry, DirectoryRegistryOptions options) + { + _registry = registry; + _options = options; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + TimeSpan interval = _options.ReaperInterval > TimeSpan.Zero + ? _options.ReaperInterval + : TimeSpan.FromSeconds(5); + using var timer = new PeriodicTimer(interval); + try + { + while (await timer.WaitForNextTickAsync(stoppingToken)) + { + _registry.SweepExpired(); + } + } + catch (OperationCanceledException) + { + } + } + } + + public static class Program + { + public static void Main(string[] args) + { + var app = DirectoryApp.Build(args); + app.Run(); + } + } +} diff --git a/src/RustToDust.Directory/RustToDust.Directory.csproj b/src/RustToDust.Directory/RustToDust.Directory.csproj new file mode 100644 index 0000000..8e854bb --- /dev/null +++ b/src/RustToDust.Directory/RustToDust.Directory.csproj @@ -0,0 +1,10 @@ + + + + net8.0 + LatestMajor + enable + disable + + + diff --git a/src/RustToDust.HbGpu/HbGpuAtlasAllocator.cs b/src/RustToDust.HbGpu/HbGpuAtlasAllocator.cs new file mode 100644 index 0000000..c9d2f83 --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuAtlasAllocator.cs @@ -0,0 +1,175 @@ +using System; +using System.Runtime.InteropServices; + +namespace RustToDust.HbGpu; + +/// +/// Manages texel offsets inside the single 262,144-texel (2.0 MiB) RGBA16I GPU atlas: +/// - Persistent zone: [0 .. 229,376) with a 75% (172,032) watermark reset trigger. +/// - Dynamic scratch ring: [229,376 .. 262,144). +/// Queues uploads into pre-allocated staging storage for zero-GC render-thread commits. +/// +public sealed class HbGpuAtlasAllocator +{ + public const uint TotalTexels = 262_144; + public const uint PersistentCapacity = 229_376; + public const uint PersistentResetWatermark = 172_032; // 75% of PersistentCapacity + public const uint DynamicBase = PersistentCapacity; + public const uint DynamicCapacity = TotalTexels - PersistentCapacity; // 32,768 + public const int BytesPerTexel = 8; + public const int TotalBytes = (int)(TotalTexels * BytesPerTexel); + + public struct UploadChunk + { + public uint AtlasTexelOffset; + public uint ShortOffset; + public uint TexelCount; + } + + private readonly short[] _pendingShorts = new short[TotalTexels * 4]; + private readonly UploadChunk[] _pendingChunks = new UploadChunk[2048]; + private uint _pendingShortCursor; + private int _pendingChunkCount; + + public uint PersistentCursor { get; private set; } + public uint DynamicCursor { get; private set; } + public uint Epoch { get; private set; } = 1; + + public bool NeedsPersistentReset => PersistentCursor > PersistentResetWatermark; + + public int PendingChunkCount => _pendingChunkCount; + + public ReadOnlySpan PendingShortPool => _pendingShorts; + + public ReadOnlySpan PendingChunks => _pendingChunks.AsSpan(0, _pendingChunkCount); + + public void ResetPersistent() + { + PersistentCursor = 0; + Epoch++; + } + + public uint AllocatePersistent(ReadOnlySpan rgba16iShorts) + { + if (rgba16iShorts.IsEmpty || (rgba16iShorts.Length & 3) != 0) + { + throw new ArgumentException("Texel data must be a non-empty multiple of 4 shorts.", nameof(rgba16iShorts)); + } + + uint texels = (uint)(rgba16iShorts.Length >> 2); + if (PersistentCursor + texels > PersistentCapacity) + { + throw new InvalidOperationException( + $"Persistent atlas overflow: cursor={PersistentCursor}, needed={texels}, cap={PersistentCapacity}."); + } + + uint atlasOffset = PersistentCursor; + PersistentCursor += texels; + QueueUpload(atlasOffset, rgba16iShorts, texels); + return atlasOffset; + } + + public uint AllocateDynamic(ReadOnlySpan rgba16iShorts) + { + if (rgba16iShorts.IsEmpty || (rgba16iShorts.Length & 3) != 0) + { + throw new ArgumentException("Texel data must be a non-empty multiple of 4 shorts.", nameof(rgba16iShorts)); + } + + uint texels = (uint)(rgba16iShorts.Length >> 2); + if (texels > DynamicCapacity) + { + throw new InvalidOperationException( + $"Dynamic blob ({texels} texels) exceeds DynamicCapacity ({DynamicCapacity})."); + } + + if (DynamicCursor + texels > DynamicCapacity) + { + DynamicCursor = 0; + } + + uint atlasOffset = DynamicBase + DynamicCursor; + DynamicCursor += texels; + QueueUpload(atlasOffset, rgba16iShorts, texels); + return atlasOffset; + } + + private void QueueUpload(uint atlasOffset, ReadOnlySpan rgba16iShorts, uint texels) + { + if (_pendingChunkCount >= _pendingChunks.Length || + _pendingShortCursor + (uint)rgba16iShorts.Length > (uint)_pendingShorts.Length) + { + // Should never happen in normal HUD usage; reset pending ring head safely if overwhelmed without draining. + throw new InvalidOperationException("Atlas pending upload staging buffer full before render-thread drain."); + } + + rgba16iShorts.CopyTo(_pendingShorts.AsSpan((int)_pendingShortCursor)); + _pendingChunks[_pendingChunkCount++] = new UploadChunk + { + AtlasTexelOffset = atlasOffset, + ShortOffset = _pendingShortCursor, + TexelCount = texels + }; + _pendingShortCursor += (uint)rgba16iShorts.Length; + } + + /// + /// Copies all pending upload chunks into a caller-owned staging byte[] at index 0 + /// and invokes uploadCallback(atlasByteOffset, byteCount). Zero allocations when callback is cached. + /// + public int DrainChunks(byte[] stagingBuffer, Action uploadCallback) + { + int count = _pendingChunkCount; + if (count == 0) + { + return 0; + } + + for (int i = 0; i < count; i++) + { + UploadChunk c = _pendingChunks[i]; + uint byteCount = c.TexelCount * BytesPerTexel; + if (byteCount > (uint)stagingBuffer.Length) + { + throw new InvalidOperationException($"Upload chunk ({byteCount} B) exceeds staging buffer ({stagingBuffer.Length} B)."); + } + Buffer.BlockCopy(_pendingShorts, (int)(c.ShortOffset * sizeof(short)), stagingBuffer, 0, (int)byteCount); + uploadCallback(c.AtlasTexelOffset * BytesPerTexel, byteCount); + } + + _pendingChunkCount = 0; + _pendingShortCursor = 0; + return count; + } + + /// + /// Copies all pending upload chunks into a full 2 MiB mirror buffer at their atlas byte offsets. + /// Returns how many chunks were drained. Zero allocations. + /// + public int DrainToMirror(byte[] atlasMirrorBytes) + { + int count = _pendingChunkCount; + if (count == 0) + { + return 0; + } + + for (int i = 0; i < count; i++) + { + UploadChunk c = _pendingChunks[i]; + int dstOffset = (int)(c.AtlasTexelOffset * BytesPerTexel); + int byteCount = (int)(c.TexelCount * BytesPerTexel); + Buffer.BlockCopy(_pendingShorts, (int)(c.ShortOffset * sizeof(short)), atlasMirrorBytes, dstOffset, byteCount); + } + + _pendingChunkCount = 0; + _pendingShortCursor = 0; + return count; + } + + public void ClearPending() + { + _pendingChunkCount = 0; + _pendingShortCursor = 0; + } +} diff --git a/src/RustToDust.HbGpu/HbGpuBlobCache.cs b/src/RustToDust.HbGpu/HbGpuBlobCache.cs new file mode 100644 index 0000000..368c07a --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuBlobCache.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; + +namespace RustToDust.HbGpu; + +/// +/// Encodes and caches RGBA16I Slug blobs for font glyphs and static/dynamic vector shapes +/// using a pre-allocated 65,536-short (128 KiB) scratch buffer. +/// +public sealed unsafe class HbGpuBlobCache +{ + public const int ScratchShortsCapacity = 65_536; + public const uint ScratchTexelsCapacity = ScratchShortsCapacity / 4; // 16,384 texels + + private readonly HbGpuAtlasAllocator _atlas; + private readonly Dictionary _glyphBlobs = new(512); + private readonly Dictionary _vectorBlobs = new(64); + private readonly short[] _scratchShorts = new short[ScratchShortsCapacity]; + private bool _persistentOverflowPending; + + public HbGpuBlobCache(HbGpuAtlasAllocator atlas) + { + _atlas = atlas ?? throw new ArgumentNullException(nameof(atlas)); + } + + public HbGpuAtlasAllocator Atlas => _atlas; + + public int CachedGlyphCount => _glyphBlobs.Count; + + public int CachedVectorCount => _vectorBlobs.Count; + + public bool IsPersistentOverflowPending => _persistentOverflowPending; + + public bool EnsureBudgetOrReset() + { + if (!_atlas.NeedsPersistentReset && !_persistentOverflowPending) + { + return false; + } + + _atlas.ResetPersistent(); + _glyphBlobs.Clear(); + _vectorBlobs.Clear(); + _persistentOverflowPending = false; + return true; + } + + public CachedBlob GetOrEncodeGlyph( + HbGpuFontCache fonts, + byte fontId, + uint glyphId, + ushort qWght, + ushort qWdth, + short qSlnt) + { + var key = new GlyphBlobKey(fontId, glyphId, qWght, qWdth, qSlnt); + if (_glyphBlobs.TryGetValue(key, out CachedBlob cached)) + { + return cached; + } + + IntPtr fontHandle = fonts.GetOrCreateStyle(new HbGpuStyleKey(fontId, qWght, qWdth, qSlnt)); + int texelCount; + RtdHbExtents ext; + fixed (short* dst = _scratchShorts) + { + texelCount = HbGpuNative.EncodeGlyph(fontHandle, glyphId, dst, ScratchTexelsCapacity, out ext); + } + + if (texelCount < 0) + { + throw new InvalidOperationException($"rtd_hb_encode_glyph failed for glyph {glyphId} (code {texelCount})."); + } + + CachedBlob blob; + if (texelCount == 0) + { + blob = new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); + } + else + { + if (_atlas.PersistentCursor + (uint)texelCount > HbGpuAtlasAllocator.PersistentCapacity) + { + // Never wipe persistent atlas mid-frame while earlier quads reference pre-reset offsets. + // Flag for reset at next BeginFrame() and skip overflow glyphs cleanly for this frame. + _persistentOverflowPending = true; + return new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); + } + + uint offset = _atlas.AllocatePersistent(_scratchShorts.AsSpan(0, texelCount * 4)); + blob = new CachedBlob( + offset, + checked((short)ext.MinX), + checked((short)ext.MinY), + checked((short)ext.MaxX), + checked((short)ext.MaxY), + (uint)texelCount, + IsEmpty: false); + } + + _glyphBlobs[key] = blob; + return blob; + } + + public bool TryGetStaticPath(VectorBlobKey key, out CachedBlob cached) => + _vectorBlobs.TryGetValue(key, out cached); + + public CachedBlob GetOrEncodeStaticPath( + VectorBlobKey key, + uint designUpem, + ReadOnlySpan verbs, + ReadOnlySpan args) + { + if (_vectorBlobs.TryGetValue(key, out CachedBlob cached)) + { + return cached; + } + + int texelCount = EncodePathIntoScratch(designUpem, verbs, args, out RtdHbExtents ext); + CachedBlob blob; + if (texelCount == 0) + { + blob = new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); + } + else + { + if (_atlas.PersistentCursor + (uint)texelCount > HbGpuAtlasAllocator.PersistentCapacity) + { + // Never wipe persistent atlas mid-frame while earlier quads reference pre-reset offsets. + _persistentOverflowPending = true; + return new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); + } + + uint offset = _atlas.AllocatePersistent(_scratchShorts.AsSpan(0, texelCount * 4)); + blob = new CachedBlob( + offset, + checked((short)ext.MinX), + checked((short)ext.MinY), + checked((short)ext.MaxX), + checked((short)ext.MaxY), + (uint)texelCount, + IsEmpty: false); + } + + _vectorBlobs[key] = blob; + return blob; + } + + public CachedBlob EncodeDynamicPath( + uint designUpem, + ReadOnlySpan verbs, + ReadOnlySpan args) + { + int texelCount = EncodePathIntoScratch(designUpem, verbs, args, out RtdHbExtents ext); + if (texelCount == 0) + { + return new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); + } + + uint offset = _atlas.AllocateDynamic(_scratchShorts.AsSpan(0, texelCount * 4)); + return new CachedBlob( + offset, + checked((short)ext.MinX), + checked((short)ext.MinY), + checked((short)ext.MaxX), + checked((short)ext.MaxY), + (uint)texelCount, + IsEmpty: false); + } + + private int EncodePathIntoScratch( + uint designUpem, + ReadOnlySpan verbs, + ReadOnlySpan args, + out RtdHbExtents ext) + { + int texelCount; + fixed (byte* vPtr = verbs) + fixed (float* aPtr = args) + fixed (short* dst = _scratchShorts) + { + texelCount = HbGpuNative.EncodePath( + designUpem, + vPtr, + (uint)verbs.Length, + aPtr, + (uint)args.Length, + dst, + ScratchTexelsCapacity, + out ext); + } + + if (texelCount < 0) + { + throw new InvalidOperationException($"rtd_hb_encode_path failed (code {texelCount})."); + } + + return texelCount; + } +} diff --git a/src/RustToDust.HbGpu/HbGpuCommandWriter.cs b/src/RustToDust.HbGpu/HbGpuCommandWriter.cs new file mode 100644 index 0000000..77fa213 --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuCommandWriter.cs @@ -0,0 +1,247 @@ +using System; + +namespace RustToDust.HbGpu; + +/// +/// Zero-allocation CPU quad builder and text shaper writing 80-byte HbGpuQuadInstance records. +/// +public sealed unsafe class HbGpuCommandWriter +{ + public const int MaxQuads = 4096; + public const int ShapingScratchCapacity = 1024; + + private readonly HbGpuQuadInstance[] _quads = new HbGpuQuadInstance[MaxQuads]; + private readonly RtdHbShapedGlyph[] _shapedScratch = new RtdHbShapedGlyph[ShapingScratchCapacity]; + + public int QuadCount { get; private set; } + + public ReadOnlySpan Quads => _quads.AsSpan(0, QuadCount); + + public HbGpuQuadInstance[] RawBuffer => _quads; + + public void BeginFrame() + { + QuadCount = 0; + } + + public static uint PackClipCoord(float minVal, float maxVal) + { + ushort lo = (ushort)Math.Clamp((int)MathF.Floor(minVal), 0, 65535); + ushort hi = (ushort)Math.Clamp((int)MathF.Ceiling(maxVal), 0, 65535); + return (uint)lo | ((uint)hi << 16); + } + + public static void PackClipRect( + float x, float y, float w, float h, + out uint clipMinPacked, + out uint clipMaxPacked) + { + ushort x0 = (ushort)Math.Clamp((int)MathF.Floor(x), 0, 65535); + ushort y0 = (ushort)Math.Clamp((int)MathF.Floor(y), 0, 65535); + ushort x1 = (ushort)Math.Clamp((int)MathF.Ceiling(x + w), 0, 65535); + ushort y1 = (ushort)Math.Clamp((int)MathF.Ceiling(y + h), 0, 65535); + clipMinPacked = (uint)x0 | ((uint)y0 << 16); + clipMaxPacked = (uint)x1 | ((uint)y1 << 16); + } + + public bool TryAddQuad(in HbGpuQuadInstance quad) + { + if (QuadCount >= MaxQuads) + { + return false; + } + + _quads[QuadCount++] = quad; + return true; + } + + public void DrawBlob( + in CachedBlob blob, + float screenX, + float screenY, + float m00, + float m01, + float m10, + float m11, + float anchorEmX, + float anchorEmY, + float r, + float g, + float b, + float a, + bool stemDarken = false, + uint clipMinPacked = 0, + uint clipMaxPacked = HbGpuQuadInstance.Unclipped, + uint extraFlags = 0u) + { + if (!blob.IsValid || QuadCount >= MaxQuads) + { + return; + } + + _quads[QuadCount++] = new HbGpuQuadInstance + { + EmMinX = blob.MinX, + EmMinY = blob.MinY, + EmMaxX = blob.MaxX, + EmMaxY = blob.MaxY, + AnchorEmX = anchorEmX, + AnchorEmY = anchorEmY, + ScreenX = screenX, + ScreenY = screenY, + M00 = m00, + M01 = m01, + M10 = m10, + M11 = m11, + ColorR = r, + ColorG = g, + ColorB = b, + ColorA = a, + AtlasTexelOffset = blob.AtlasOffset, + Flags = (stemDarken ? HbGpuQuadInstance.FlagStemDarken : 0u) | extraFlags, + ClipMinPacked = clipMinPacked, + ClipMaxPacked = clipMaxPacked + }; + } + + public float MeasureTextWidth( + ReadOnlySpan text, + float fontSizePx, + HbGpuFontCache fonts, + byte fontId = 0, + float wght = 200f, + float wdth = 100f, + float slnt = 0f, + HbGpuFeatureFlags features = HbGpuFeatureFlags.Default) + { + if (text.IsEmpty) + { + return 0f; + } + + HbGpuStyleKey styleKey = HbGpuStyleKey.FromAxes(fontId, wght, wdth, slnt); + IntPtr fontHandle = fonts.GetOrCreateStyle(styleKey); + int upem = fonts.GetMetrics(fontId).Upem; + float scale = fontSizePx / upem; + + uint glyphCount; + fixed (char* textPtr = text) + fixed (RtdHbShapedGlyph* outPtr = _shapedScratch) + { + glyphCount = HbGpuNative.ShapeUtf16( + fontHandle, + textPtr, + (uint)text.Length, + (uint)features, + outPtr, + (uint)_shapedScratch.Length); + } + + int count = (int)Math.Min(glyphCount, (uint)_shapedScratch.Length); + int adv = 0; + for (int i = 0; i < count; i++) + { + adv += _shapedScratch[i].XAdvance; + } + + return adv * scale; + } + + /// + /// Shapes UTF-16 text directly and appends glyph quads. (x, baselineY) is the pen baseline origin in logical pixels (Y-down). + /// Returns the total horizontal advance in logical pixels. + /// + public float DrawTextUtf16( + ReadOnlySpan text, + float x, + float baselineY, + float fontSizePx, + float r, + float g, + float b, + float a, + HbGpuFontCache fonts, + HbGpuBlobCache blobs, + byte fontId = 0, + float wght = 200f, + float wdth = 100f, + float slnt = 0f, + HbGpuFeatureFlags features = HbGpuFeatureFlags.Default, + bool stemDarken = true, + uint clipMinPacked = 0, + uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + if (text.IsEmpty) + { + return 0f; + } + + HbGpuStyleKey styleKey = HbGpuStyleKey.FromAxes(fontId, wght, wdth, slnt); + IntPtr fontHandle = fonts.GetOrCreateStyle(styleKey); + int upem = fonts.GetMetrics(fontId).Upem; + float scale = fontSizePx / upem; + + uint glyphCount; + fixed (char* textPtr = text) + fixed (RtdHbShapedGlyph* outPtr = _shapedScratch) + { + glyphCount = HbGpuNative.ShapeUtf16( + fontHandle, + textPtr, + (uint)text.Length, + (uint)features, + outPtr, + (uint)_shapedScratch.Length); + } + + int count = (int)Math.Min(glyphCount, (uint)_shapedScratch.Length); + float penX = x; + float penY = baselineY; + + for (int i = 0; i < count; i++) + { + RtdHbShapedGlyph sg = _shapedScratch[i]; + CachedBlob blob = blobs.GetOrEncodeGlyph( + fonts, + fontId, + sg.GlyphId, + styleKey.QWght, + styleKey.QWdth, + styleKey.QSlnt); + + if (blob.IsValid && QuadCount < MaxQuads) + { + float gx = penX + sg.XOffset * scale; + float gy = penY - sg.YOffset * scale; // Y-up font offset -> Y-down screen + _quads[QuadCount++] = new HbGpuQuadInstance + { + EmMinX = blob.MinX, + EmMinY = blob.MinY, + EmMaxX = blob.MaxX, + EmMaxY = blob.MaxY, + AnchorEmX = 0f, + AnchorEmY = 0f, + ScreenX = gx, + ScreenY = gy, + M00 = scale, + M01 = 0f, + M10 = 0f, + M11 = -scale, + ColorR = r, + ColorG = g, + ColorB = b, + ColorA = a, + AtlasTexelOffset = blob.AtlasOffset, + Flags = stemDarken ? HbGpuQuadInstance.FlagStemDarken : 0u, + ClipMinPacked = clipMinPacked, + ClipMaxPacked = clipMaxPacked + }; + } + + penX += sg.XAdvance * scale; + penY -= sg.YAdvance * scale; + } + + return penX - x; + } +} diff --git a/src/RustToDust.HbGpu/HbGpuFontCache.cs b/src/RustToDust.HbGpu/HbGpuFontCache.cs new file mode 100644 index 0000000..a40500d --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuFontCache.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace RustToDust.HbGpu; + +/// +/// Owns loaded font faces and lazy quantized-axis (wght, wdth, slnt) hb_font_t* handles. +/// Avoids per-frame hb_font_set_variations thrash. +/// +public sealed unsafe class HbGpuFontCache : IDisposable +{ + private readonly Dictionary _baseFaces = new(); + private readonly Dictionary _metrics = new(); + private readonly Dictionary _styles = new(); + private bool _disposed; + + public byte RegisterFontFromFile(byte fontId, string path, uint faceIndex = 0) + { + ObjectDisposedException.ThrowIf(_disposed, this); + byte[] bytes = File.ReadAllBytes(path); + return RegisterFont(fontId, bytes, faceIndex); + } + + public byte RegisterFont(byte fontId, ReadOnlySpan ttfBytes, uint faceIndex = 0) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (ttfBytes.IsEmpty) + { + throw new ArgumentException("Font bytes cannot be empty.", nameof(ttfBytes)); + } + + if (_baseFaces.TryGetValue(fontId, out IntPtr existing) && existing != IntPtr.Zero) + { + throw new InvalidOperationException($"FontId {fontId} is already registered."); + } + + fixed (byte* ptr = ttfBytes) + { + IntPtr baseHandle = HbGpuNative.FontCreate(ptr, (uint)ttfBytes.Length, faceIndex, out RtdHbFontMetrics metrics); + if (baseHandle == IntPtr.Zero) + { + throw new InvalidOperationException($"rtd_hb_font_create failed for FontId {fontId}."); + } + + _baseFaces[fontId] = baseHandle; + _metrics[fontId] = metrics; + } + + return fontId; + } + + public RtdHbFontMetrics GetMetrics(byte fontId) => _metrics[fontId]; + + public bool TryGetMetrics(byte fontId, out RtdHbFontMetrics metrics) => + _metrics.TryGetValue(fontId, out metrics); + + public IntPtr GetOrCreateStyle(HbGpuStyleKey key) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_styles.TryGetValue(key, out IntPtr handle)) + { + return handle; + } + + if (!_baseFaces.TryGetValue(key.FontId, out IntPtr baseHandle)) + { + throw new KeyNotFoundException($"FontId {key.FontId} is not registered in HbGpuFontCache."); + } + + float wght = key.QWght; + float wdth = key.QWdth * 0.1f; + float slnt = key.QSlnt * 0.1f; + IntPtr variant = HbGpuNative.FontCreateVariant(baseHandle, wght, wdth, slnt); + if (variant == IntPtr.Zero) + { + throw new InvalidOperationException($"rtd_hb_font_create_variant failed for {key}."); + } + + _styles[key] = variant; + return variant; + } + + public IntPtr GetOrCreateStyle(byte fontId, float wght, float wdth, float slnt) => + GetOrCreateStyle(HbGpuStyleKey.FromAxes(fontId, wght, wdth, slnt)); + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + + foreach (IntPtr handle in _styles.Values) + { + if (handle != IntPtr.Zero) + { + HbGpuNative.FontDestroy(handle); + } + } + _styles.Clear(); + + foreach (IntPtr baseHandle in _baseFaces.Values) + { + if (baseHandle != IntPtr.Zero) + { + HbGpuNative.FontDestroy(baseHandle); + } + } + _baseFaces.Clear(); + _metrics.Clear(); + } +} diff --git a/src/RustToDust.HbGpu/HbGpuNative.cs b/src/RustToDust.HbGpu/HbGpuNative.cs new file mode 100644 index 0000000..9e55941 --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuNative.cs @@ -0,0 +1,66 @@ +using System; +using System.Runtime.InteropServices; + +namespace RustToDust.HbGpu; + +public static unsafe class HbGpuNative +{ + public const string LibraryName = "rtd_hbgpu"; + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_version_string")] + private static extern IntPtr NativeVersionString(); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_shader_source")] + private static extern IntPtr NativeShaderSource(uint stage, uint kind); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_font_create")] + public static extern IntPtr FontCreate( + byte* ttf, + uint len, + uint faceIndex, + out RtdHbFontMetrics outMetrics); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_font_create_variant")] + public static extern IntPtr FontCreateVariant( + IntPtr baseFont, + float wght, + float wdth, + float slnt); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_font_destroy")] + public static extern void FontDestroy(IntPtr font); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_shape_utf16")] + public static extern uint ShapeUtf16( + IntPtr font, + char* utf16, + uint charLen, + uint featureFlags, + RtdHbShapedGlyph* outGlyphs, + uint cap); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_encode_glyph")] + public static extern int EncodeGlyph( + IntPtr font, + uint glyphId, + short* outRgba16i, + uint capTexels, + out RtdHbExtents outExt); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_encode_path")] + public static extern int EncodePath( + uint designUpem, + byte* verbs, + uint nVerbs, + float* args, + uint nArgs, + short* outRgba16i, + uint capTexels, + out RtdHbExtents outExt); + + public static string GetVersionString() => + Marshal.PtrToStringUTF8(NativeVersionString()) ?? string.Empty; + + public static string GetShaderSource(HbGpuShaderStage stage, HbGpuShaderKind kind) => + Marshal.PtrToStringUTF8(NativeShaderSource((uint)stage, (uint)kind)) ?? string.Empty; +} diff --git a/src/RustToDust.HbGpu/HbGpuTypes.cs b/src/RustToDust.HbGpu/HbGpuTypes.cs new file mode 100644 index 0000000..07fc309 --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuTypes.cs @@ -0,0 +1,152 @@ +using System; +using System.Runtime.InteropServices; + +namespace RustToDust.HbGpu; + +[StructLayout(LayoutKind.Sequential)] +public struct RtdHbFontMetrics +{ + public int Upem; + public int Ascender; + public int Descender; + public int LineGap; +} + +[StructLayout(LayoutKind.Sequential)] +public struct RtdHbShapedGlyph +{ + public uint GlyphId; + public uint Cluster; + public int XAdvance; + public int YAdvance; + public int XOffset; + public int YOffset; +} + +[StructLayout(LayoutKind.Sequential)] +public struct RtdHbExtents +{ + public int MinX; + public int MinY; + public int MaxX; + public int MaxY; +} + +/// +/// 80-byte GPU quad instance matching the std430 SSBO layout in HbGpuCanvas. +/// +[StructLayout(LayoutKind.Sequential, Pack = 4)] +public struct HbGpuQuadInstance +{ + public float EmMinX; + public float EmMinY; + public float EmMaxX; + public float EmMaxY; + + public float AnchorEmX; + public float AnchorEmY; + public float ScreenX; + public float ScreenY; + + public float M00; + public float M01; + public float M10; + public float M11; + + public float ColorR; + public float ColorG; + public float ColorB; + public float ColorA; + + public uint AtlasTexelOffset; + public uint Flags; + public uint ClipMinPacked; + public uint ClipMaxPacked; + + public const uint FlagStemDarken = 1u; + public const uint FlagSolidRect = 2u; + public const uint Unclipped = 0xFFFFFFFFu; +} + +[Flags] +public enum HbGpuFeatureFlags : uint +{ + None = 0u, + Calt = 1u << 0, + Liga = 1u << 1, + Default = Calt | Liga +} + +public enum HbGpuPathVerb : byte +{ + Move = 0, + LineTo = 1, + QuadTo = 2, + CubicTo = 3, + Close = 4, + Line = 5, + Rect = 6, + Circle = 7 +} + +public enum HbGpuShaderStage : uint +{ + Vertex = 0, + Fragment = 1 +} + +public enum HbGpuShaderKind : uint +{ + Shared = 0, + Draw = 1 +} + +public enum VectorShapeKind : ushort +{ + UnitFilledRect = 1, + UnitCircleFill = 2, + UnitRingStroke = 3, + CornerLBracket = 4, + TargetBracketCorner = 5, + DirectionalArrow = 6, + ChevronTriangle = 7, + DiamondBlip = 8, + HitMarkerArm = 9, + StrippedHatchX = 10, + PanelFrame = 11, + HardpointBracket = 12, + ThermalHeatArc = 13, + IncomingHitArc = 14, + Custom = 100 +} + +public readonly record struct HbGpuStyleKey(byte FontId, ushort QWght, ushort QWdth, short QSlnt) +{ + public static ushort QuantizeWeight(float wght) => + (ushort)Math.Clamp((int)MathF.Round(wght), 100, 1000); + + public static ushort QuantizeWidth(float wdth) => + (ushort)Math.Clamp((int)MathF.Round(wdth * 10f), 500, 2000); + + public static short QuantizeSlant(float slnt) => + (short)Math.Clamp((int)MathF.Round(slnt * 10f), -200, 200); + + public static HbGpuStyleKey FromAxes(byte fontId, float wght, float wdth, float slnt) => + new(fontId, QuantizeWeight(wght), QuantizeWidth(wdth), QuantizeSlant(slnt)); +} + +public readonly record struct GlyphBlobKey(byte FontId, uint GlyphId, ushort QWght, ushort QWdth, short QSlnt); + +public readonly record struct VectorBlobKey(VectorShapeKind Kind, ushort ParamA, ushort ParamB, uint ParamC = 0); + +public readonly record struct CachedBlob( + uint AtlasOffset, + short MinX, + short MinY, + short MaxX, + short MaxY, + uint TexelCount, + bool IsEmpty) +{ + public bool IsValid => TexelCount > 0 && !IsEmpty; +} diff --git a/src/RustToDust.HbGpu/HbGpuVectorShapes.cs b/src/RustToDust.HbGpu/HbGpuVectorShapes.cs new file mode 100644 index 0000000..6ec2ebe --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuVectorShapes.cs @@ -0,0 +1,254 @@ +using System; + +namespace RustToDust.HbGpu; + +/// +/// Encodes canonical UI/HUD vector primitives into HarfBuzz hb-gpu RGBA16I blobs +/// in a 1000-unit design space ([-500 .. +500] or [0 .. 1000]). +/// +public static class HbGpuVectorShapes +{ + public const uint DesignUpem = 1000u; + + private static readonly byte[] RectVerbs = { (byte)HbGpuPathVerb.Rect }; + private static readonly float[] UnitFilledRectArgs = { -500f, -500f, 1000f, 1000f, float.NaN }; + + private static readonly byte[] CircleVerbs = { (byte)HbGpuPathVerb.Circle }; + private static readonly float[] UnitFilledCircleArgs = { 0f, 0f, 500f, float.NaN }; + + // L-corner bracket centered around (0,0) pointing into (+X, +Y), design space 1000x1000 + // Thickness paramB in thousandths (e.g. 100 = 10% of arm length) + private static readonly byte[] CornerBracketVerbs = + { + (byte)HbGpuPathVerb.Move, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.Close + }; + + // Equilateral/tactical chevron pointing +Y (Y-up in design space -> -Y in Y-down screen) + private static readonly byte[] ChevronVerbs = + { + (byte)HbGpuPathVerb.Move, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.Close + }; + private static readonly float[] ChevronArgs = + { + 0f, 500f, + 420f, -380f, + 0f, -140f, + -420f, -380f + }; + + // Solid directional arrow pointing +Y in design space + private static readonly float[] ArrowArgs = + { + 0f, 520f, + 400f, -360f, + 0f, -180f, + -400f, -360f + }; + + // Diamond blip centered at (0,0) + private static readonly float[] DiamondArgs = + { + 0f, 500f, + 500f, 0f, + 0f, -500f, + -500f, 0f + }; + + public static CachedBlob GetUnitFilledRect(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.UnitFilledRect, 0, 0), + DesignUpem, + RectVerbs, + UnitFilledRectArgs); + + public static CachedBlob GetUnitFilledCircle(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.UnitCircleFill, 0, 0), + DesignUpem, + CircleVerbs, + UnitFilledCircleArgs); + + public static CachedBlob GetUnitRingStroke(HbGpuBlobCache cache, ushort strokeUnits = 24) + { + var key = new VectorBlobKey(VectorShapeKind.UnitRingStroke, strokeUnits, 0); + if (cache.TryGetStaticPath(key, out CachedBlob cached)) + { + return cached; + } + + Span args = stackalloc float[4]; + args[0] = 0f; + args[1] = 0f; + args[2] = 500f; + args[3] = strokeUnits; + return cache.GetOrEncodeStaticPath(key, DesignUpem, CircleVerbs, args); + } + + public static CachedBlob GetTargetBracketCorner(HbGpuBlobCache cache, ushort thicknessUnits = 120) + { + var key = new VectorBlobKey(VectorShapeKind.TargetBracketCorner, thicknessUnits, 0); + if (cache.TryGetStaticPath(key, out CachedBlob cached)) + { + return cached; + } + + float t = Math.Clamp((float)thicknessUnits, 10f, 450f); + Span args = stackalloc float[12]; + args[0] = 0f; args[1] = 0f; + args[2] = 1000f; args[3] = 0f; + args[4] = 1000f; args[5] = -t; + args[6] = t; args[7] = -t; + args[8] = t; args[9] = -1000f; + args[10] = 0f; args[11] = -1000f; + return cache.GetOrEncodeStaticPath(key, DesignUpem, CornerBracketVerbs, args); + } + + public static CachedBlob GetChevronTriangle(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.ChevronTriangle, 0, 0), + DesignUpem, + ChevronVerbs, + ChevronArgs); + + public static CachedBlob GetDirectionalArrow(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.DirectionalArrow, 0, 0), + DesignUpem, + ChevronVerbs, + ArrowArgs); + + public static CachedBlob GetDiamondBlip(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.DiamondBlip, 0, 0), + DesignUpem, + ChevronVerbs, + DiamondArgs); + + /// + /// Returns a permanently cached static stroked circular arc in design space (radius=500, Y-up). + /// Eliminates per-frame dynamic atlas uploads for fixed/quantized HUD arcs. + /// + public static CachedBlob GetStaticArcStroke( + HbGpuBlobCache cache, + VectorBlobKey key, + float startRad, + float endRad, + float radius = 500f, + float halfThickness = 32f) + { + if (cache.TryGetStaticPath(key, out CachedBlob cached)) + { + return cached; + } + + float sweep = endRad - startRad; + if (MathF.Abs(sweep) < 1e-4f) + { + return default; + } + + Span verbs = stackalloc byte[19]; // max 1 + 8 + 1 + 8 + 1 + Span args = stackalloc float[100]; // max 2 + 8*6 + 2 + 8*6 + BuildArcPath(startRad, endRad, radius, halfThickness, verbs, args, out int vCount, out int aCount); + return cache.GetOrEncodeStaticPath(key, DesignUpem, verbs[..vCount], args[..aCount]); + } + + /// + /// Encodes a stroked circular arc in design space (radius=500, Y-up) using cubic Bezier segments. + /// Useful for thermal heat arcs and directional incoming-hit arcs. + /// Angles are in radians counter-clockwise from +X (Y-up). + /// + public static CachedBlob EncodeArcStrokeDynamic( + HbGpuBlobCache cache, + float startRad, + float endRad, + float radius = 500f, + float halfThickness = 32f) + { + float sweep = endRad - startRad; + if (MathF.Abs(sweep) < 1e-4f) + { + return default; + } + + Span verbs = stackalloc byte[19]; + Span args = stackalloc float[100]; + BuildArcPath(startRad, endRad, radius, halfThickness, verbs, args, out int vCount, out int aCount); + return cache.EncodeDynamicPath(DesignUpem, verbs[..vCount], args[..aCount]); + } + + private static void BuildArcPath( + float startRad, + float endRad, + float radius, + float halfThickness, + Span verbs, + Span args, + out int v, + out int a) + { + float sweep = endRad - startRad; + int segs = Math.Clamp((int)MathF.Ceiling(MathF.Abs(sweep) / (MathF.PI * 0.4f)), 1, 8); + float rOut = radius + halfThickness; + float rIn = MathF.Max(1f, radius - halfThickness); + float dt = sweep / segs; + float k = (4f / 3f) * MathF.Tan(dt * 0.25f); + + v = 0; + a = 0; + + float ca0 = MathF.Cos(startRad); + float sa0 = MathF.Sin(startRad); + verbs[v++] = (byte)HbGpuPathVerb.Move; + args[a++] = rOut * ca0; + args[a++] = rOut * sa0; + + for (int i = 0; i < segs; i++) + { + float t0 = startRad + i * dt; + float t1 = t0 + dt; + float c0 = MathF.Cos(t0), s0 = MathF.Sin(t0); + float c1 = MathF.Cos(t1), s1 = MathF.Sin(t1); + verbs[v++] = (byte)HbGpuPathVerb.CubicTo; + args[a++] = rOut * (c0 - k * s0); + args[a++] = rOut * (s0 + k * c0); + args[a++] = rOut * (c1 + k * s1); + args[a++] = rOut * (s1 - k * c1); + args[a++] = rOut * c1; + args[a++] = rOut * s1; + } + + float ce = MathF.Cos(endRad); + float se = MathF.Sin(endRad); + verbs[v++] = (byte)HbGpuPathVerb.LineTo; + args[a++] = rIn * ce; + args[a++] = rIn * se; + + for (int i = segs - 1; i >= 0; i--) + { + float t1 = startRad + (i + 1) * dt; + float t0 = startRad + i * dt; + float c1 = MathF.Cos(t1), s1 = MathF.Sin(t1); + float c0 = MathF.Cos(t0), s0 = MathF.Sin(t0); + verbs[v++] = (byte)HbGpuPathVerb.CubicTo; + args[a++] = rIn * (c1 + k * s1); + args[a++] = rIn * (s1 - k * c1); + args[a++] = rIn * (c0 - k * s0); + args[a++] = rIn * (s0 + k * c0); + args[a++] = rIn * c0; + args[a++] = rIn * s0; + } + + verbs[v++] = (byte)HbGpuPathVerb.Close; + } +} diff --git a/src/RustToDust.HbGpu/RustToDust.HbGpu.csproj b/src/RustToDust.HbGpu/RustToDust.HbGpu.csproj new file mode 100644 index 0000000..eb31d97 --- /dev/null +++ b/src/RustToDust.HbGpu/RustToDust.HbGpu.csproj @@ -0,0 +1,42 @@ + + + + net8.0 + enable + disable + true + RustToDust.HbGpu + RustToDust.HbGpu + Release + $(MSBuildThisFileDirectory)..\..\native\rtd_hbgpu + $(MSBuildThisFileDirectory)..\..\artifacts\hbgpu-native\$(HbGpuNativeConfiguration) + C:\Program Files\CMake\bin\cmake.exe + cmake + + + + + + + + + + + + + + diff --git a/src/RustToDust.Net/DirectoryClient.cs b/src/RustToDust.Net/DirectoryClient.cs new file mode 100644 index 0000000..0f44032 --- /dev/null +++ b/src/RustToDust.Net/DirectoryClient.cs @@ -0,0 +1,350 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace RustToDust.Net +{ + public sealed record DirectoryServerInfo( + Guid ServerId, + string Name, + string PublicHost, + int UdpPort, + string Map, + int Seed, + int Humans, + int MaxHumans, + string Phase, + int Wave, + int ProtocolVersion, + bool HasPassword, + DateTimeOffset ExpiresAtUtc); + + public readonly record struct DirectoryHeartbeatSnapshot( + string Name, + string PublicHost, + int UdpPort, + string Map, + int Seed, + int Humans, + int MaxHumans, + string Phase, + int Wave, + int ProtocolVersion = 1, + bool HasPassword = false); + + public static class DirectoryBrowserClient + { + private static readonly HttpClient SharedHttp = new() + { + Timeout = TimeSpan.FromSeconds(5) + }; + + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + public static string NormalizeBaseUrl(string directoryBaseUrl) + { + string trimmed = (directoryBaseUrl ?? string.Empty).Trim(); + while (trimmed.EndsWith('/')) + { + trimmed = trimmed.Substring(0, trimmed.Length - 1); + } + return trimmed; + } + + public static async Task> FetchServersAsync( + string directoryBaseUrl, + CancellationToken ct = default, + HttpClient? httpClient = null) + { + string baseUrl = NormalizeBaseUrl(directoryBaseUrl); + if (string.IsNullOrEmpty(baseUrl)) + { + return Array.Empty(); + } + + HttpClient client = httpClient ?? SharedHttp; + using var req = new HttpRequestMessage(HttpMethod.Get, $"{baseUrl}/api/v1/servers"); + using var resp = await client.SendAsync(req, ct).ConfigureAwait(false); + resp.EnsureSuccessStatusCode(); + var list = await resp.Content.ReadFromJsonAsync>(JsonOptions, ct).ConfigureAwait(false); + return list ?? (IReadOnlyList)Array.Empty(); + } + } + + public sealed class DirectoryReporter : IDisposable, IAsyncDisposable + { + private sealed record HeartbeatBody( + Guid? ServerId, + string? LeaseToken, + string Name, + string? PublicHost, + int UdpPort, + string Map, + int Seed, + int Humans, + int MaxHumans, + string Phase, + int Wave, + int ProtocolVersion, + bool HasPassword); + + private sealed class HeartbeatAck + { + public Guid ServerId { get; set; } + public string LeaseToken { get; set; } = string.Empty; + public int TtlSeconds { get; set; } + } + + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + private readonly string _baseUrl; + private readonly Func _snapshotProvider; + private readonly TimeSpan _heartbeatInterval; + private readonly HttpClient _http; + private readonly bool _ownsHttp; + private readonly CancellationTokenSource _cts = new(); + private readonly SemaphoreSlim _wakeSignal = new(0, 1); + private readonly object _leaseGate = new(); + private readonly Task _loopTask; + + private Guid? _serverId; + private string? _leaseToken; + private int _disposed; + + public DirectoryReporter( + string directoryBaseUrl, + Func snapshotProvider, + TimeSpan? heartbeatInterval = null, + HttpClient? httpClient = null) + { + _baseUrl = DirectoryBrowserClient.NormalizeBaseUrl(directoryBaseUrl); + if (string.IsNullOrEmpty(_baseUrl)) + { + throw new ArgumentException("Directory base URL cannot be empty.", nameof(directoryBaseUrl)); + } + _snapshotProvider = snapshotProvider ?? throw new ArgumentNullException(nameof(snapshotProvider)); + _heartbeatInterval = heartbeatInterval ?? TimeSpan.FromSeconds(10); + if (httpClient is not null) + { + _http = httpClient; + _ownsHttp = false; + } + else + { + _http = new HttpClient { Timeout = TimeSpan.FromSeconds(6) }; + _ownsHttp = true; + } + + _loopTask = Task.Run(RunLoopAsync); + } + + public Guid? CurrentServerId + { + get + { + lock (_leaseGate) + { + return _serverId; + } + } + } + + public string? LastError { get; private set; } + + public void NotifyChanged() + { + if (Volatile.Read(ref _disposed) != 0) return; + try + { + if (_wakeSignal.CurrentCount == 0) + { + _wakeSignal.Release(); + } + } + catch (ObjectDisposedException) + { + } + catch (SemaphoreFullException) + { + } + } + + private async Task RunLoopAsync() + { + while (!_cts.IsCancellationRequested) + { + await SendHeartbeatOnceAsync(_cts.Token).ConfigureAwait(false); + + try + { + bool woken = await _wakeSignal.WaitAsync(_heartbeatInterval, _cts.Token).ConfigureAwait(false); + if (woken && !_cts.IsCancellationRequested) + { + await Task.Delay(250, _cts.Token).ConfigureAwait(false); + while (_wakeSignal.CurrentCount > 0) + { + _wakeSignal.Wait(0); + } + } + } + catch (OperationCanceledException) + { + break; + } + } + } + + private async Task SendHeartbeatOnceAsync(CancellationToken ct) + { + try + { + var snap = _snapshotProvider(); + Guid? curServerId; + string? curLeaseToken; + lock (_leaseGate) + { + curServerId = _serverId; + curLeaseToken = _leaseToken; + } + + var body = new HeartbeatBody( + curServerId, + curLeaseToken, + snap.Name, + snap.PublicHost, + snap.UdpPort, + snap.Map, + snap.Seed, + snap.Humans, + snap.MaxHumans, + snap.Phase, + snap.Wave, + snap.ProtocolVersion, + snap.HasPassword); + + using var resp = await _http.PostAsJsonAsync($"{_baseUrl}/api/v1/servers/heartbeat", body, ct).ConfigureAwait(false); + if (resp.StatusCode == HttpStatusCode.Conflict || resp.StatusCode == HttpStatusCode.NotFound) + { + lock (_leaseGate) + { + _serverId = null; + _leaseToken = null; + } + LastError = $"Directory returned {(int)resp.StatusCode}; resetting lease."; + return; + } + + if (!resp.IsSuccessStatusCode) + { + LastError = $"Directory heartbeat HTTP {(int)resp.StatusCode}"; + return; + } + + var ack = await resp.Content.ReadFromJsonAsync(JsonOptions, ct).ConfigureAwait(false); + if (ack is not null && ack.ServerId != Guid.Empty && !string.IsNullOrEmpty(ack.LeaseToken)) + { + lock (_leaseGate) + { + _serverId = ack.ServerId; + _leaseToken = ack.LeaseToken; + } + LastError = null; + } + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + LastError = ex.Message; + } + } + + private (Guid? ServerId, string? LeaseToken) ReadLeaseSnapshot() + { + lock (_leaseGate) + { + return (_serverId, _leaseToken); + } + } + + private async Task SendDeleteOnceAsync(Guid serverId, string leaseToken) + { + try + { + using var deleteCts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + using var req = new HttpRequestMessage(HttpMethod.Delete, $"{_baseUrl}/api/v1/servers/{serverId}"); + req.Headers.TryAddWithoutValidation("X-Lease-Token", leaseToken); + using var _ = await _http.SendAsync(req, deleteCts.Token).ConfigureAwait(false); + } + catch + { + } + } + + private void DisposeResources() + { + _cts.Dispose(); + _wakeSignal.Dispose(); + if (_ownsHttp) + { + _http.Dispose(); + } + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + + _cts.Cancel(); + try + { + _loopTask.Wait(TimeSpan.FromSeconds(5)); + } + catch + { + } + + var (serverId, leaseToken) = ReadLeaseSnapshot(); + if (serverId is { } sid && !string.IsNullOrEmpty(leaseToken)) + { + SendDeleteOnceAsync(sid, leaseToken).GetAwaiter().GetResult(); + } + + DisposeResources(); + } + + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + + _cts.Cancel(); + try + { + await _loopTask.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); + } + catch + { + } + + var (serverId, leaseToken) = ReadLeaseSnapshot(); + if (serverId is { } sid && !string.IsNullOrEmpty(leaseToken)) + { + await SendDeleteOnceAsync(sid, leaseToken).ConfigureAwait(false); + } + + DisposeResources(); + } + } +} diff --git a/src/RustToDust.Net/ListenHostArenaSession.cs b/src/RustToDust.Net/ListenHostArenaSession.cs new file mode 100644 index 0000000..f035fb0 --- /dev/null +++ b/src/RustToDust.Net/ListenHostArenaSession.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Numerics; +using RustToDust.Core; + +namespace RustToDust.Net +{ + public sealed class ListenHostArenaSession : IClientArenaSession + { + private readonly ServerMatchHost _host; + + public ListenHostArenaSession( + IPAddress bindAddress, + int port, + int seed = 42, + ArenaMapKind mapKind = ArenaMapKind.Desert, + int maxHumans = MatchState.ContenderCount, + bool startInLobby = false, + string serverName = "Rust to Dust", + int minHumansToStart = 1, + byte squadSize = 1) + { + _host = new ServerMatchHost( + bindAddress, + port, + seed, + mapKind, + maxHumans: maxHumans, + autoRestartSec: 0, + allowClientReset: false, + hostContenderId: 0, + startInLobby: startInLobby, + serverName: serverName, + minHumansToStart: minHumansToStart, + squadSize: squadSize); + } + + public ServerMatchHost Host => _host; + public MatchState ViewState => _host.Session.State; + public int LocalContenderId => 0; + public ContenderState LocalContender => _host.Session.State.Contenders[0]; + + public ClientMatchOutcome LocalOutcome => + _host.Session.State.Phase == MatchPhase.Lobby + ? ClientMatchOutcome.Active + : _host.Session.State.Phase == MatchPhase.Active + ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) + : ((_host.Session.State.WinnerContenderId == 0 || + (_host.Session.State.WinnerContenderId.HasValue && _host.Session.State.AreAllies(0, _host.Session.State.WinnerContenderId.Value))) + ? ClientMatchOutcome.Victory + : ClientMatchOutcome.Defeat); + + public int LocalDetectedByCount => + _host.Session.State.ObserverStates.TryGetValue(0, out var obs) ? obs.DetectedByCount : 0; + + public IReadOnlyDictionary LocalContenderContacts => + _host.Session.State.ObserverStates.TryGetValue(0, out var obs) ? obs.ContenderContacts : _host.Session.State.EmptyContacts; + + public IReadOnlyDictionary LocalSpectatorContacts => + _host.Session.State.ObserverStates.TryGetValue(0, out var obs) ? obs.SpectatorContacts : _host.Session.State.EmptyContacts; + + public NetworkStatusSnapshot ConnectionStatus => + new( + NetworkMode.ListenHost, + Connected: true, + PingMs: 0, + ConnectedHumans: _host.ConnectedHumanCount, + MaxHumans: MatchState.ContenderCount, + StateLabel: $"HOST :{_host.BoundPort} ({_host.ConnectedHumanCount}/12)"); + + public IReadOnlyList ActivePods => _host.Session.State.OrbitalDrop.ActivePods; + public DropWaveState DropWaveState => _host.Session.State.OrbitalDrop.WaveState; + public IReadOnlyList PodEvents => _host.Session.State.PodEvents; + public LobbySnapshotDto? LobbyState => _host.BuildLobbySnapshotDto(); + + public bool IsContenderVisible(int contenderId) => true; + public bool IsSpectatorVisible(int spectatorId) => true; + + public void BeginRenderFrame(double dt, float physicsAlpha) + { + _host.PollStatelessPings(); + } + + public void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick) + { + if (!isPhysicsTick) return; + _host.SetHostInput(input); + _host.StepOnce(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + } + + public void DrainSimEvents(List dest) => _host.DrainHostEvents(dest); + + public bool RequestEquipCargo(int cargoIndex, string hardpointId) => + _host.TryEquipHostCargo(cargoIndex, hardpointId); + + public void RepairArenaScars() => _host.RepairArenaScars(); + + public void RequestNewMatch(int seed, ArenaMapKind mapKind) => + _host.ResetMatch(seed, mapKind); + + public bool SetLobbyReady(bool ready) => _host.SetLobbyReady(0, ready); + public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => _host.ConfigureLobby(0, seed, mapKind); + public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind, byte squadSize) => _host.ConfigureLobby(0, seed, mapKind, squadSize); + public bool RequestLobbySquad(byte targetSquadId) => _host.MovePeerToSquad(0, targetSquadId); + public bool RequestLobbyStart() => _host.LaunchFromLobby(0); + + public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) => + _host.Session.GetInterpolatedContenderPose(contenderId, alpha); + + public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha) => + _host.Session.GetInterpolatedSpectatorPose(spectatorId, alpha); + + public bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap) => + _host.Session.TrySampleInterpolatedWalkerPose(isContender, id, alpha, out snap); + + public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation) + { + var hit = _host.Session.CastWorldRayClosest(origin, translation); + return new ClientRayHit( + hit.Hit, + hit.StableId, + new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z), + new Vector3(hit.Normal.X, hit.Normal.Y, hit.Normal.Z), + hit.Fraction); + } + + public void Dispose() + { + _host.Dispose(); + } + } +} diff --git a/src/RustToDust.Net/RemoteArenaSession.cs b/src/RustToDust.Net/RemoteArenaSession.cs new file mode 100644 index 0000000..4c1236d --- /dev/null +++ b/src/RustToDust.Net/RemoteArenaSession.cs @@ -0,0 +1,1996 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Sockets; +using System.Numerics; +using System.Threading; +using GameCult.Mesh; +using GameCult.Networking; +using RustToDust.Core; +using RustToDust.Ymir; +using Ymir.Box3D; + +namespace RustToDust.Net +{ + public sealed class RemoteArenaSession : IClientArenaSession + { + private const int MaxUnackedInputs = 32; + private const float InterpDelaySec = 0.050f; + private const float HardSnapThresholdM = 4.0f; + private const float ErrorDecayTauSec = 0.10f; + private const long ClientDisconnectTimeoutMs = 6000; + + private readonly record struct BufferedInput(uint Seq, PlayerInput Input, WalkerCheckpoint? PreWalker); + + private struct PoseSample + { + public float SimTime; + public Vector3 Pos; + public Quaternion Rot; + public Vector3 Vel; + } + + private struct WalkerSample + { + public float SimTime; + public WalkerVisualSnapshot Snap; + } + + private readonly Socket _socket; + private readonly CultNetRudpSocketTransportConnection _conn; + private readonly string _callsign; + private readonly List _unackedInputs = new(MaxUnackedInputs); + private readonly bool[] _contenderVisible = new bool[MatchState.ContenderCount]; + private readonly bool[] _spectatorVisible = new bool[SpectatorRing.DefaultSpectatorCount]; + private readonly uint[] _lastCombatSpecSeenSeq = new uint[SpectatorRing.DefaultSpectatorCount]; + private readonly List[] _contenderTimeline = new List[MatchState.ContenderCount]; + private readonly List[] _spectatorTimeline = new List[SpectatorRing.DefaultSpectatorCount]; + private readonly Dictionary> _contenderWalkerTimelines = new(); + private readonly Dictionary> _spectatorWalkerTimelines = new(); + private readonly Dictionary _pingSamples = new(); + private readonly List _pendingClientEvents = new(); + + private MatchState _viewState; + private Box3DSoaWorld? _predWorld; + private readonly Box3DPhysicsTileSync _predTileSync = new(); + private Box3DSoaBodyHandle? _predBody; + private WalkerState? _predWalker; + private string _predChassisId = string.Empty; + + public Box3DPhysicsTileSync PredTileSync => _predTileSync; + + private Vector3 _predErrorPos; + private Quaternion _predErrorRot = Quaternion.Identity; + private bool _pendingChassisSwapSnap; + + private Guid _reconnectToken; + private uint _matchGeneration; + private uint _nextInputSeq = 1; + private uint _nextCmdSeq = 1; + private ushort _interactSeq; + private bool _prevInteractPressed; + private long _outLatestSeq = 1; + private long _outSchemaSeq = 1; + private uint _lastSnapshotSeq; + private uint _lastOrbitSeq; + private uint _lastRadarSeq; + private int _localContenderId; + private int _localDetectedByCount; + private float _latestServerSimTime; + private float _renderTime; + private int _pingMs; + private int _connectedHumans = 1; + private long _lastServerPacketUtcMs; + private long _lastKeepaliveUtcMs; + private LobbySnapshotDto? _lobbyState; + private float _podStepAccum; + private float _timeSinceLastPhysicsPodStep; + private bool _physicsPodSteppingActive; + private bool _joinSent; + private bool _joined; + private bool _everJoined; + private string? _lastError; + private bool _disposed; + + public RemoteArenaSession( + IPEndPoint serverEndPoint, + string callsign = "Pilot", + Guid reconnectToken = default) + { + _callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim(); + _reconnectToken = reconnectToken; + + for (int i = 0; i < _contenderTimeline.Length; i++) _contenderTimeline[i] = new List(16); + for (int i = 0; i < _spectatorTimeline.Length; i++) _spectatorTimeline[i] = new List(16); + + _viewState = new MatchState(42, ArenaMapKind.Desert, skipInitialDrop: true); + for (int i = 0; i < _contenderVisible.Length; i++) _contenderVisible[i] = i == 0; + + _socket = new Socket(serverEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp) + { + Blocking = false + }; + _socket.Bind(new IPEndPoint( + serverEndPoint.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any, + 0)); + + _conn = new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions + { + Mode = CultNetRudpSocketMode.Client, + RuntimeId = "rtd-client", + Socket = _socket, + RemoteEndPoint = serverEndPoint, + ConnectionId = 0x52544431, + ResendDelayMs = 100, + MaxFragmentBytes = SnapshotCodec.MaxLatestFrameBytes, + MaxPayloadBytes = 256 * 1024, + MaxPendingReliablePackets = 2048 + }); + _conn.Connect(); + _lastServerPacketUtcMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + } + + public Func? DebugInboundLatestDropFilter { get; set; } + public Guid ReconnectToken => _reconnectToken; + public bool IsJoined => _joined; + public uint LastSnapshotSeq => _lastSnapshotSeq; + public int UnackedInputCount => _unackedInputs.Count; + public Vector3 CurrentPredictionError => _predErrorPos; + public float? PredictedWalkerSimTime => _predWalker is { Initialized: true } ? _predWalker.SimTime : null; + + public MatchState ViewState => _viewState; + public int LocalContenderId => _localContenderId; + public ContenderState LocalContender => _viewState.Contenders[_localContenderId]; + + public ClientMatchOutcome LocalOutcome => + _viewState.Phase == MatchPhase.Lobby + ? ClientMatchOutcome.Active + : _viewState.Phase == MatchPhase.Active + ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) + : ((_viewState.WinnerContenderId == _localContenderId || + (_viewState.WinnerContenderId.HasValue && _viewState.AreAllies(_localContenderId, _viewState.WinnerContenderId.Value))) + ? ClientMatchOutcome.Victory + : ClientMatchOutcome.Defeat); + + public int LocalDetectedByCount => _localDetectedByCount; + + public IReadOnlyDictionary LocalContenderContacts => + _viewState.ObserverStates.TryGetValue(_localContenderId, out var obs) ? obs.ContenderContacts : _viewState.EmptyContacts; + + public IReadOnlyDictionary LocalSpectatorContacts => + _viewState.ObserverStates.TryGetValue(_localContenderId, out var obs) ? obs.SpectatorContacts : _viewState.EmptyContacts; + + public NetworkStatusSnapshot ConnectionStatus => + new( + NetworkMode.RemoteClient, + Connected: _joined && _conn.Connected, + PingMs: _pingMs, + ConnectedHumans: _connectedHumans, + MaxHumans: MatchState.ContenderCount, + StateLabel: (_joined && _conn.Connected) + ? $"ONLINE ({_pingMs} ms)" + : (_lastError is not null ? $"DISCONNECTED ({_lastError})" : (_everJoined ? "DISCONNECTED" : "CONNECTING")), + LastError: _lastError); + + public IReadOnlyList ActivePods => _viewState.OrbitalDrop.ActivePods; + public DropWaveState DropWaveState => _viewState.OrbitalDrop.WaveState; + public IReadOnlyList PodEvents => _viewState.PodEvents; + public LobbySnapshotDto? LobbyState => _viewState.Phase == MatchPhase.Lobby ? _lobbyState : null; + + public bool IsContenderVisible(int contenderId) => + contenderId >= 0 && contenderId < _contenderVisible.Length && _contenderVisible[contenderId]; + + public bool IsSpectatorVisible(int spectatorId) + { + int idx = spectatorId >= 1000 ? spectatorId - 1000 : spectatorId; + return idx >= 0 && idx < _spectatorVisible.Length && _spectatorVisible[idx]; + } + + public bool WaitUntilJoined(TimeSpan timeout) + { + var deadline = DateTimeOffset.UtcNow + timeout; + while (DateTimeOffset.UtcNow < deadline) + { + PumpNetwork(); + if (_joined) return true; + if (_lastError is not null) return false; + Thread.Sleep(2); + } + return _joined; + } + + public void DisconnectGracefully(string reason = "Leave") + { + if (_disposed) return; + try + { + if (_conn.Connected) + { + SendSchemaMessage(new LeaveMsg { Reason = reason }); + _conn.PollResends(); + _conn.Disconnect(); + } + } + catch + { + } + } + + public void BeginRenderFrame(double dt, float physicsAlpha) + { + ObjectDisposedException.ThrowIf(_disposed, this); + + PumpNetwork(); + + float fdt = (float)Math.Max(0.0, dt); + MatchRules.AdvanceTracers(_viewState, fdt); + MatchRules.AdvanceHitEvents(_viewState, fdt); + + if (_joined && fdt > 0f) + { + _timeSinceLastPhysicsPodStep += fdt; + if (_timeSinceLastPhysicsPodStep > 0.08f) + { + _physicsPodSteppingActive = false; + } + if (!_physicsPodSteppingActive) + { + _podStepAccum += fdt; + while (_podStepAccum >= ArenaSession.FixedDt) + { + StepAllReplicatedPods(ArenaSession.FixedDt); + _podStepAccum -= ArenaSession.FixedDt; + } + } + } + + if (_joined) + { + _renderTime += fdt; + float minRender = _latestServerSimTime - 0.16f; + float maxRender = _latestServerSimTime - 0.015f; + if (_renderTime < minRender || _renderTime > _latestServerSimTime + 0.05f) + { + _renderTime = Math.Max(0f, _latestServerSimTime - InterpDelaySec); + } + else if (_renderTime > maxRender && maxRender > 0f) + { + _renderTime = maxRender; + } + } + + if (fdt > 0f) + { + float decay = MathF.Exp(-fdt / ErrorDecayTauSec); + _predErrorPos *= decay; + if (_predErrorPos.LengthSquared() < 1e-8f) + { + _predErrorPos = Vector3.Zero; + } + _predErrorRot = Quaternion.Slerp(_predErrorRot, Quaternion.Identity, 1f - decay); + if (MathF.Abs(_predErrorRot.W) > 0.999999f) + { + _predErrorRot = Quaternion.Identity; + } + } + } + + public void DrainSimEvents(List dest) + { + if (_pendingClientEvents.Count == 0) + { + return; + } + dest.AddRange(_pendingClientEvents); + _pendingClientEvents.Clear(); + } + + public void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (!isPhysicsTick || !_joined) + { + return; + } + + if (input.InteractPickup && !_prevInteractPressed) + { + _interactSeq = _interactSeq == ushort.MaxValue ? (ushort)1 : (ushort)(_interactSeq + 1); + SendSchemaMessage(new InteractCmdMsg { ReqSeq = _interactSeq }); + } + _prevInteractPressed = input.InteractPickup; + + uint seq = _nextInputSeq++; + uint nowMs = unchecked((uint)Environment.TickCount64); + var pkt = new ClientInputPacket(_matchGeneration, seq, nowMs, input, _interactSeq); + byte[] payload = SnapshotCodec.EncodeClientInput(pkt); + byte[] wire = SnapshotCodec.WrapLatest(payload, _matchGeneration, _outLatestSeq++, SnapshotCodec.SchemaInputId); + try + { + _conn.SendLatest(wire); + } + catch (SocketException) + { + } + + WalkerCheckpoint? preWalker = _predWalker is { Initialized: true } + ? _predWalker.CaptureCheckpoint() + : null; + + if (_unackedInputs.Count >= MaxUnackedInputs) + { + _unackedInputs.RemoveAt(0); + } + _unackedInputs.Add(new BufferedInput(seq, input, preWalker)); + + StepLocalPredictionTick(input, updatePreviousPose: true); + StepNonLocalReplicatedPods(ArenaSession.FixedDt); + _physicsPodSteppingActive = true; + _timeSinceLastPhysicsPodStep = 0f; + _podStepAccum = 0f; + } + + public bool RequestEquipCargo(int cargoIndex, string hardpointId) + { + if (!_joined) return false; + SendSchemaMessage(new EquipCargoCmdMsg + { + ReqSeq = _nextCmdSeq++, + CargoIndex = cargoIndex, + HardpointId = hardpointId + }); + return true; + } + + public void RequestNewMatch(int seed, ArenaMapKind mapKind) + { + if (!_joined) return; + SendSchemaMessage(new NewMatchCmdMsg + { + ReqSeq = _nextCmdSeq++, + Seed = seed, + MapKind = (byte)mapKind + }); + } + + public bool SetLobbyReady(bool ready) + { + if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false; + SendSchemaMessage(new LobbyReadyCmdMsg + { + ReqSeq = _nextCmdSeq++, + IsReady = ready + }); + return true; + } + + public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => + RequestLobbyConfig(seed, mapKind, _lobbyState?.SquadSize ?? 0); + + public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind, byte squadSize) + { + if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false; + SendSchemaMessage(new LobbyConfigCmdMsg + { + ReqSeq = _nextCmdSeq++, + Seed = seed, + MapKind = (byte)mapKind, + SquadSize = squadSize + }); + return true; + } + + public bool RequestLobbySquad(byte targetSquadId) + { + if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false; + SendSchemaMessage(new LobbySquadCmdMsg + { + ReqSeq = _nextCmdSeq++, + TargetSquadId = targetSquadId + }); + return true; + } + + public bool RequestLobbyStart() + { + if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false; + SendSchemaMessage(new LobbyStartCmdMsg + { + ReqSeq = _nextCmdSeq++ + }); + return true; + } + + public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) + { + if (contenderId < 0 || contenderId >= _viewState.Contenders.Count) + { + return (Vector3.Zero, Quaternion.Identity, Vector3.Zero); + } + + if (contenderId == _localContenderId) + { + var c = _viewState.Contenders[contenderId]; + float t = Math.Clamp(alpha, 0f, 1f); + var prevPos = new Vector3(c.PrevX, c.PrevY, c.PrevZ); + var currPos = new Vector3(c.X, c.Y, c.Z); + var prevQ = NormalizeQuat(new Quaternion(c.PrevRotX, c.PrevRotY, c.PrevRotZ, c.PrevRotW)); + var currQ = NormalizeQuat(new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW)); + if (Quaternion.Dot(prevQ, currQ) < 0f) currQ = -currQ; + + Vector3 basePos = Vector3.Lerp(prevPos, currPos, t); + Quaternion baseRot = Quaternion.Slerp(prevQ, currQ, t); + return ( + basePos + _predErrorPos, + NormalizeQuat(_predErrorRot * baseRot), + new Vector3(c.VelX, c.VelY, c.VelZ)); + } + + return SamplePoseTimeline(_contenderTimeline[contenderId], _viewState.Contenders[contenderId]); + } + + public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha) + { + var list = _viewState.Spectators.Spectators; + SpectatorState? spec = null; + for (int i = 0; i < list.Count; i++) + { + if (list[i].Id == spectatorId) + { + spec = list[i]; + break; + } + } + int idx = spectatorId >= 1000 ? spectatorId - 1000 : spectatorId; + if (spec is null || idx < 0 || idx >= _spectatorTimeline.Length) + { + return (Vector3.Zero, Quaternion.Identity, Vector3.Zero); + } + + var timeline = _spectatorTimeline[idx]; + if (timeline.Count == 0) + { + return ( + new Vector3(spec.X, spec.Y, spec.Z), + NormalizeQuat(new Quaternion(spec.CurrRotX, spec.CurrRotY, spec.CurrRotZ, spec.CurrRotW)), + new Vector3(spec.VelX, spec.VelY, spec.VelZ)); + } + return SampleTimelineSamples(timeline); + } + + public bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap) + { + if (isContender && id == _localContenderId) + { + if (_predWalker is not null && _predWalker.Initialized) + { + snap = WalkerVisualSnapshot.Interpolate(in _predWalker.PrevSnap, in _predWalker.CurrSnap, alpha); + snap.ComPos += _predErrorPos; + snap.ComRot = NormalizeQuat(_predErrorRot * snap.ComRot); + return true; + } + snap = default; + return false; + } + + int key = !isContender && id >= 1000 ? id - 1000 : id; + var map = isContender ? _contenderWalkerTimelines : _spectatorWalkerTimelines; + if (!map.TryGetValue(key, out var list) || list.Count == 0) + { + snap = default; + return false; + } + + if (list.Count == 1 || _renderTime <= list[0].SimTime) + { + snap = list[0].Snap; + return true; + } + + int last = list.Count - 1; + if (_renderTime >= list[last].SimTime) + { + snap = list[last].Snap; + return true; + } + + for (int i = 0; i < last; i++) + { + var a = list[i]; + var b = list[i + 1]; + if (_renderTime >= a.SimTime && _renderTime <= b.SimTime) + { + float span = MathF.Max(1e-5f, b.SimTime - a.SimTime); + float u = Math.Clamp((_renderTime - a.SimTime) / span, 0f, 1f); + snap = WalkerVisualSnapshot.Interpolate(in a.Snap, in b.Snap, u); + return true; + } + } + + snap = list[last].Snap; + return true; + } + + public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation) + { + float bestFrac = 1.00001f; + ClientRayHit best = default; + + if (_predWorld is not null) + { + var staticHit = _predWorld.CastRayClosest( + (origin.X, origin.Y, origin.Z), + (translation.X, translation.Y, translation.Z)); + if (staticHit.Hit && ArenaSession.IsStaticWorldStableId(staticHit.StableId)) + { + bestFrac = staticHit.Fraction; + best = new ClientRayHit( + true, + staticHit.StableId, + new Vector3(staticHit.Point.X, staticHit.Point.Y, staticHit.Point.Z), + new Vector3(staticHit.Normal.X, staticHit.Normal.Y, staticHit.Normal.Z), + staticHit.Fraction); + } + } + + float len = translation.Length(); + if (len > 1e-5f) + { + Vector3 dir = translation / len; + for (int i = 0; i < _viewState.Contenders.Count; i++) + { + var c = _viewState.Contenders[i]; + if (!c.Alive || c.Id == _localContenderId || !IsContenderVisible(c.Id)) + { + continue; + } + var (pos, rot, _) = GetInterpolatedContenderPose(c.Id, 1f); + var half = new Vector3(c.Grid.Spec.HalfWidth, ArenaSession.GetPhysicsHalfHeight(c.Grid.Spec), c.Grid.Spec.HalfLength); + if (RayIntersectsObb(origin, dir, len, pos, rot, half, out float frac, out Vector3 normal) && frac < bestFrac) + { + bestFrac = frac; + best = new ClientRayHit(true, ArenaSession.ContenderStableIdBase + (ulong)c.Id, origin + translation * frac, normal, frac); + } + } + + for (int i = 0; i < _viewState.Spectators.Spectators.Count; i++) + { + var s = _viewState.Spectators.Spectators[i]; + if (!s.Alive || !IsSpectatorVisible(s.Id)) + { + continue; + } + var (pos, rot, _) = GetInterpolatedSpectatorPose(s.Id, 1f); + var half = new Vector3(s.Grid.Spec.HalfWidth, ArenaSession.GetPhysicsHalfHeight(s.Grid.Spec), s.Grid.Spec.HalfLength); + if (RayIntersectsObb(origin, dir, len, pos, rot, half, out float frac, out Vector3 normal) && frac < bestFrac) + { + bestFrac = frac; + best = new ClientRayHit(true, 3000UL + (ulong)s.Id, origin + translation * frac, normal, frac); + } + } + } + + return best; + } + + public void PumpNetwork() => + PumpNetwork(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + + public void PumpNetwork(long nowUtcMs) + { + if (_disposed) return; + + if (_conn.Connected && !_joinSent) + { + _joinSent = true; + SendSchemaMessage(new JoinReqMsg + { + Callsign = _callsign, + ReconnectToken = _reconnectToken + }); + } + + int loops = 0; + while (loops < 256) + { + CultNetTransportFrame? frame; + try + { + if (!_conn.TryReceiveOnce(out frame)) + { + break; + } + } + catch (SocketException) + { + break; + } + loops++; + if (frame is null) continue; + _lastServerPacketUtcMs = nowUtcMs; + + CultMeshRealtimeFrame rt; + try + { + rt = SnapshotCodec.Unwrap(frame.Payload); + } + catch + { + continue; + } + + if (string.Equals(frame.ChannelId, SnapshotCodec.ChannelSchema, StringComparison.Ordinal)) + { + HandleSchemaFrame(rt.Payload); + } + else if (string.Equals(frame.ChannelId, SnapshotCodec.ChannelLatest, StringComparison.Ordinal)) + { + if (DebugInboundLatestDropFilter is not null && DebugInboundLatestDropFilter(rt.Payload.ToArray())) + { + continue; + } + HandleLatestFrame(rt.Payload.Span); + } + } + + if (_joined && _conn.Connected && _viewState.Phase == MatchPhase.Lobby && (nowUtcMs - _lastKeepaliveUtcMs) >= 1000) + { + _lastKeepaliveUtcMs = nowUtcMs; + SendSchemaMessage(new ClientKeepaliveMsg { ClientSendMs = unchecked((uint)nowUtcMs) }); + } + + try + { + _conn.PollResends(); + } + catch (SocketException) + { + } + + bool transportTimedOut = false; + try + { + transportTimedOut = _conn.CheckTimeout(ClientDisconnectTimeoutMs); + } + catch + { + } + + if (_joined && (!_conn.Connected || transportTimedOut || (nowUtcMs - _lastServerPacketUtcMs) > ClientDisconnectTimeoutMs)) + { + _joined = false; + _lastError ??= "Connection timed out"; + try + { + if (_conn.Connected) + { + _conn.Disconnect(); + } + } + catch + { + } + } + } + + private void HandleSchemaFrame(ReadOnlyMemory payload) + { + ISchemaWireMessage msg; + try + { + msg = SnapshotCodec.DeserializeSchemaMessage(payload); + } + catch + { + return; + } + + switch (msg) + { + case JoinAcceptedMsg accepted: + _reconnectToken = accepted.ReconnectToken; + _localContenderId = accepted.AssignedContenderId; + _matchGeneration = accepted.MatchGeneration; + ApplyInitialMatchState(accepted.InitialState, accepted.AssignedContenderId); + _lastServerPacketUtcMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + _lastError = null; + _joined = true; + _everJoined = true; + break; + case JoinRejectedMsg rejected: + _joined = false; + _lastError = rejected.Reason; + break; + case LeaveMsg leave: + _joined = false; + _lastError = string.IsNullOrWhiteSpace(leave.Reason) ? "Disconnected by server" : leave.Reason; + try + { + if (_conn.Connected) + { + _conn.Disconnect(); + } + } + catch + { + } + break; + case SimEventBatchMsg batch: + if (batch.MatchGeneration == _matchGeneration || ContainsMatchReset(batch.Events)) + { + ApplyEventBatch(batch); + } + break; + case EntitySyncSnapshotMsg sync: + ApplyEntitySync(sync); + break; + case LobbySnapshotMsg lobbySnap: + if (lobbySnap.MatchGeneration == _matchGeneration) + { + ApplyLobbySnapshot(lobbySnap.Snapshot); + } + break; + } + } + + private void ApplyLobbySnapshot(LobbySnapshotDto? snapshot) + { + _lobbyState = snapshot; + if (snapshot is null) return; + for (int i = 0; i < snapshot.Slots.Count && i < _viewState.Contenders.Count; i++) + { + var slot = snapshot.Slots[i]; + if (slot.SlotId >= 0 && slot.SlotId < _viewState.Contenders.Count) + { + var c = _viewState.Contenders[slot.SlotId]; + c.IsHuman = slot.IsHuman; + c.SquadId = slot.SquadId; + if (!string.IsNullOrWhiteSpace(slot.Callsign)) + { + c.Name = slot.Callsign; + } + } + } + _connectedHumans = CountHumanContenders(); + } + + private static bool ContainsMatchReset(List events) + { + for (int i = 0; i < events.Count; i++) + { + if (events[i] is MatchResetEvent) return true; + } + return false; + } + + private void HandleLatestFrame(ReadOnlySpan span) + { + if (!_joined || span.IsEmpty) return; + + try + { + var kind = (LatestPacketKind)span[0]; + switch (kind) + { + case LatestPacketKind.CorePvs: + if (!SnapshotCodec.TryDecodeCorePvs(span, out var core)) return; + if (core.MatchGeneration != _matchGeneration || core.SnapshotSeq <= _lastSnapshotSeq) return; + _lastSnapshotSeq = core.SnapshotSeq; + ApplyCorePvsSnapshot(core); + break; + case LatestPacketKind.SpectatorOrbitHalf: + if (!SnapshotCodec.TryDecodeSpectatorOrbitHalf(span, out var orbit)) return; + if (orbit.MatchGeneration != _matchGeneration || orbit.SnapshotSeq < _lastOrbitSeq) return; + _lastOrbitSeq = orbit.SnapshotSeq; + ApplySpectatorOrbit(orbit); + break; + case LatestPacketKind.RadarContacts: + if (!SnapshotCodec.TryDecodeRadarContacts(span, out var radar)) return; + if (radar.MatchGeneration != _matchGeneration || radar.SnapshotSeq < _lastRadarSeq) return; + _lastRadarSeq = radar.SnapshotSeq; + ApplyRadarContacts(radar); + break; + } + } + catch + { + } + } + + private void ApplyInitialMatchState(InitialMatchStateDto dto, int localContenderId) + { + _localContenderId = localContenderId; + _matchGeneration = dto.MatchGeneration; + _lastSnapshotSeq = 0; + _lastOrbitSeq = 0; + _lastRadarSeq = 0; + _interactSeq = 0; + _prevInteractPressed = false; + _pendingChassisSwapSnap = false; + _unackedInputs.Clear(); + _pendingClientEvents.Clear(); + _predErrorPos = Vector3.Zero; + _predErrorRot = Quaternion.Identity; + Array.Clear(_lastCombatSpecSeenSeq); + + byte initSquadSize = (byte)Math.Clamp((int)dto.SquadSize, 1, 4); + _viewState = new MatchState(dto.Seed, (ArenaMapKind)dto.MapKind, skipInitialDrop: true, squadSize: initSquadSize) + { + Time = dto.SimTime, + Phase = dto.Phase switch + { + 1 => MatchPhase.Completed, + 2 => MatchPhase.Lobby, + _ => MatchPhase.Active + }, + WinnerContenderId = dto.WinnerContenderId + }; + if (dto.ContenderSquadIds is { Length: > 0 } squadIds) + { + int count = Math.Min(squadIds.Length, _viewState.Contenders.Count); + for (int i = 0; i < count; i++) + { + _viewState.Contenders[i].SquadId = squadIds[i]; + } + } + _lobbyState = _viewState.Phase == MatchPhase.Lobby ? dto.Lobby : null; + if (_lobbyState is not null) + { + for (int i = 0; i < _lobbyState.Slots.Count; i++) + { + var slot = _lobbyState.Slots[i]; + if (slot.SlotId >= 0 && slot.SlotId < _viewState.Contenders.Count) + { + _viewState.Contenders[slot.SlotId].SquadId = slot.SquadId; + } + } + } + _lastKeepaliveUtcMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + _viewState.Spectators.SetReplicatedSafeRadius(dto.SafeRadius); + _viewState.OrbitalDrop.ApplyReplicatedWaveState( + dto.CurrentWaveIndex, + Math.Min(DropWaveConfig.WaveTimes.Length, dto.CurrentWaveIndex + 1), + dto.RespawnCutoffReached); + _latestServerSimTime = dto.SimTime; + _renderTime = Math.Max(0f, dto.SimTime - InterpDelaySec); + _podStepAccum = 0f; + _timeSinceLastPhysicsPodStep = 0f; + _physicsPodSteppingActive = false; + + if (dto.PersistentScars is { Length: > 0 }) + { + var snap = ArenaScarLedger.DecompressSnapshot(dto.PersistentScars); + _viewState.ApplyPersistentScars(snap); + } + + for (int i = 0; i < dto.TerrainStamps.Count; i++) + { + ApplyTerrainStamp(dto.TerrainStamps[i]); + } + + _viewState.GroundDrops.Clear(); + for (int i = 0; i < dto.GroundDrops.Count; i++) + { + var gd = dto.GroundDrops[i]; + var d = _viewState.ApplyReplicatedDropSpawned( + gd.Id, + gd.X, + gd.Z, + gd.ChassisId is not null && Catalog.ChassisById.TryGetValue(gd.ChassisId, out var cs) ? cs : null, + Catalog.TryGetModule(gd.ModuleId, out var ms) ? ms : null); + d.PickedUp = gd.PickedUp; + } + + for (int i = 0; i < _viewState.Contenders.Count; i++) + { + _contenderTimeline[i].Clear(); + _contenderVisible[i] = i == _localContenderId; + if (i != _localContenderId) + { + var hidden = _viewState.Contenders[i]; + hidden.X = 0f; + hidden.Y = 0f; + hidden.Z = 0f; + hidden.Kills = 0; + hidden.SnapPreviousPose(); + } + } + + int humans = 0; + for (int i = 0; i < dto.Contenders.Count; i++) + { + var cd = dto.Contenders[i]; + if (cd.Id < 0 || cd.Id >= _viewState.Contenders.Count) continue; + var c = _viewState.Contenders[cd.Id]; + c.Name = cd.Name; + c.IsHuman = cd.IsHuman; + c.SquadId = cd.SquadId; + if (cd.IsHuman) humans++; + c.Lifecycle = (ContenderLifecycle)cd.LifecycleByte; + c.RespawnsRemaining = cd.RespawnsRemaining; + c.X = cd.X; c.Y = cd.Y; c.Z = cd.Z; c.Yaw = cd.Yaw; + c.Kills = cd.Kills; + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, cd.Yaw); + c.CurrRotX = q.X; c.CurrRotY = q.Y; c.CurrRotZ = q.Z; c.CurrRotW = q.W; + c.SnapPreviousPose(); + ApplyLoadoutToContender(c, cd.Loadout); + _contenderTimeline[cd.Id].Clear(); + _contenderVisible[cd.Id] = true; + } + _connectedHumans = dto.ConnectedHumans > 0 ? dto.ConnectedHumans : Math.Max(1, humans); + + for (int i = 0; i < _viewState.Spectators.Spectators.Count; i++) + { + _spectatorTimeline[i].Clear(); + _spectatorVisible[i] = false; + } + + for (int i = 0; i < dto.Spectators.Count; i++) + { + var sd = dto.Spectators[i]; + int sIdx = sd.Id >= 1000 ? sd.Id - 1000 : sd.Id; + if (sIdx < 0 || sIdx >= _viewState.Spectators.Spectators.Count) continue; + var s = _viewState.Spectators.Spectators[sIdx]; + s.Stance = (SpectatorStance)sd.Stance; + s.X = sd.X; s.Y = sd.Y; s.Z = sd.Z; s.Yaw = sd.Yaw; + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, sd.Yaw); + s.CurrRotX = q.X; s.CurrRotY = q.Y; s.CurrRotZ = q.Z; s.CurrRotW = q.W; + s.SnapPreviousPose(); + var mounted = new List<(string, string)>(sd.Mounted.Count); + for (int m = 0; m < sd.Mounted.Count; m++) mounted.Add((sd.Mounted[m].ModuleId, sd.Mounted[m].HardpointId)); + if (Catalog.TryGetChassisSpecOrExemplar(sd.ChassisId, out var spec)) + { + s.Grid.ApplyReplicatedLoadout(spec, sd.CoreHp, sd.MaxCoreHp, sd.ArmorBytes, mounted, null, id => Catalog.TryGetModule(id, out var ms) ? ms : null); + } + _spectatorTimeline[sIdx].Clear(); + _spectatorVisible[sIdx] = true; + } + + _contenderWalkerTimelines.Clear(); + _spectatorWalkerTimelines.Clear(); + + RebuildPredictionWorld(); + _viewState.OrbitalDrop.ApplyReplicatedActivePods(dto.ActivePods, QueryLocalDropSurface); + } + + private void RebuildPredictionWorld() + { + _predWorld?.Dispose(); + _predWorld = new Box3DSoaWorld(capacity: 256, gravityX: 0f, gravityY: -20f, gravityZ: 0f); + _predTileSync.Reset(); + ArenaSession.BuildStaticArena(_predWorld, _viewState, _predTileSync, warmAllActors: false); + var local = LocalContender; + if (_viewState.Terrain.IsHeightmapMode) + { + _predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1); + } + _predBody = null; + _predWalker = null; + _predChassisId = string.Empty; + + var q = NormalizeQuat(new Quaternion(local.CurrRotX, local.CurrRotY, local.CurrRotZ, local.CurrRotW)); + SpawnLocalPredictionBody(new Vector3(local.X, local.Y, local.Z), q, Vector3.Zero, Vector3.Zero); + } + + private void SpawnLocalPredictionBody(Vector3 pos, Quaternion rot, Vector3 vel, Vector3 angVel) + { + if (_predWorld is null) return; + var local = LocalContender; + if (!local.IsGroundedActive) + { + if (_predBody.HasValue) + { + _predWorld.RemoveBody(_predBody.Value); + _predBody = null; + } + _predWalker = null; + _predChassisId = local.Grid.Spec.Id; + return; + } + + if (_predBody.HasValue) + { + _predWorld.RemoveBody(_predBody.Value); + _predBody = null; + } + if (_predWorld.FreeBodySlots < 8) + { + _predWorld.Step(1e-5f, 1); + } + + var spec = local.Grid.Spec; + float physHalfH = ArenaSession.GetPhysicsHalfHeight(spec); + float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength; + float density = spec.MassKg / MathF.Max(0.1f, volume); + + var handle = _predWorld.AddBox( + ArenaSession.ContenderStableIdBase + (ulong)local.Id, + (pos.X, pos.Y, pos.Z), + (spec.HalfWidth, physHalfH, spec.HalfLength), + density, + (rot.X, rot.Y, rot.Z, rot.W), + friction: 0.2f, + restitution: 0.1f); + _predBody = handle; + + var v = _predWorld.View; + float mass = v.Mass[handle.Lane]; + if (mass > 0f) + { + if (vel.LengthSquared() > 1e-8f) + { + _predWorld.ApplyImpulse(handle.Lane, (vel.X * mass, vel.Y * mass, vel.Z * mass), (pos.X, pos.Y, pos.Z)); + } + if (angVel.LengthSquared() > 1e-6f) + { + float ix = mass * (physHalfH * physHalfH + spec.HalfLength * spec.HalfLength) / 3f; + float iy = mass * (spec.HalfWidth * spec.HalfWidth + spec.HalfLength * spec.HalfLength) / 3f; + float iz = mass * (spec.HalfWidth * spec.HalfWidth + physHalfH * physHalfH) / 3f; + Vector3 wLocal = Vector3.Transform(angVel, Quaternion.Conjugate(rot)); + Vector3 lLocal = new(wLocal.X * ix, wLocal.Y * iy, wLocal.Z * iz); + Vector3 L = Vector3.Transform(lLocal, rot); + Vector3 ortho = MathF.Abs(L.Y) < 0.9f * L.Length() ? Vector3.UnitY : Vector3.UnitX; + Vector3 r = Vector3.Cross(L, ortho); + if (r.LengthSquared() > 1e-8f) + { + r = Vector3.Normalize(r); + Vector3 j = Vector3.Cross(L, r) * 0.5f; + _predWorld.ApplyImpulse(handle.Lane, (j.X, j.Y, j.Z), (pos.X + r.X, pos.Y + r.Y, pos.Z + r.Z)); + _predWorld.ApplyImpulse(handle.Lane, (-j.X, -j.Y, -j.Z), (pos.X - r.X, pos.Y - r.Y, pos.Z - r.Z)); + } + } + } + + if (spec.IsWalker) + { + if (_predWalker is null || !string.Equals(_predChassisId, spec.Id, StringComparison.Ordinal)) + { + _predWalker = new WalkerState(spec); + _predWalker.InitializePose(pos, rot, spec.MassKg, _viewState.Terrain); + } + else + { + _predWalker.SyncBodyPoseOnly(pos, rot, spec.MassKg); + } + } + else + { + _predWalker = null; + } + _predChassisId = spec.Id; + } + + private DropSurfaceSample QueryLocalDropSurface(float x, float z, float footRadius, float referenceMaxY) => + ArenaSession.QueryDropSurface(_viewState, _predWorld, x, z, footRadius, referenceMaxY); + + private OrbitalPod? FindActivePodForContender(int contenderId) + { + var pods = _viewState.OrbitalDrop.ActivePods; + for (int i = 0; i < pods.Count; i++) + { + if (pods[i].PodKind == OrbitalPodKind.Contender && pods[i].ContenderId == contenderId) + { + return pods[i]; + } + } + return null; + } + + private void StepAllReplicatedPods(float dt) + { + var local = LocalContender; + if (local.IsInDropPod) + { + var input = new PlayerInput( + local.ThrottleCmd, + local.SteerCmd, + local.AimX, + local.AimZ, + Fire: false, + InteractPickup: false, + Brake: false, + AimWorldY: local.AimY, + VerticalThrottle: 0f); + StepLocalPredictionTick(input, updatePreviousPose: true); + } + StepNonLocalReplicatedPods(dt); + } + + private void StepNonLocalReplicatedPods(float dt) + { + var pods = _viewState.OrbitalDrop.ActivePods; + for (int i = pods.Count - 1; i >= 0; i--) + { + var pod = pods[i]; + if (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId == _localContenderId) + { + if (pod.FlightTime > 75f) + { + _viewState.OrbitalDrop.RemoveActivePodAt(i); + } + continue; + } + + pod.SnapPreviousPose(); + pod.AllowFlatRoofLanding = false; + bool touched = OrbitalDropKinematics.StepPod( + pod, + dt, + _viewState.Terrain, + QueryLocalDropSurface, + _viewState.FindClearDropPoint, + out _, + out _); + if (touched || pod.FlightTime > 75f) + { + _viewState.OrbitalDrop.RemoveActivePodAt(i); + } + } + } + + private void StepLocalPredictionTick(in PlayerInput input, bool updatePreviousPose) + { + var local = LocalContender; + if (updatePreviousPose) + { + local.SnapPreviousPose(); + if (_predWalker is { Initialized: true }) + { + _predWalker.SnapshotPrev(); + } + } + + if (local.IsInDropPod) + { + MatchRules.ApplyHumanInput(_viewState, _localContenderId, input with { InteractPickup = false }); + var localPod = FindActivePodForContender(_localContenderId); + if (localPod is not null) + { + if (updatePreviousPose) + { + localPod.SnapPreviousPose(); + } + localPod.AllowFlatRoofLanding = local.IsHuman && _viewState.MapKind == ArenaMapKind.Sion; + bool touched = OrbitalDropKinematics.StepPod( + localPod, + ArenaSession.FixedDt, + _viewState.Terrain, + QueryLocalDropSurface, + _viewState.FindClearDropPoint, + out _, + out _); + if (touched) + { + localPod.Phase = OrbitalPodPhase.RetroBurn; + localPod.LastAgl = 0f; + localPod.VelY = -OrbitalPodPreset.Contender.TargetTouchdownSpeed; + } + local.X = localPod.X; + local.Y = localPod.Y + local.Grid.Spec.HalfHeight; + local.Z = localPod.Z; + local.Yaw = localPod.Yaw; + local.CurrRotX = localPod.CurrRotX; + local.CurrRotY = localPod.CurrRotY; + local.CurrRotZ = localPod.CurrRotZ; + local.CurrRotW = localPod.CurrRotW; + local.VelX = localPod.VelX; + local.VelY = localPod.VelY; + local.VelZ = localPod.VelZ; + local.Speed = MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ); + } + return; + } + + if (_predWorld is null || !_predBody.HasValue || !local.IsGroundedActive) + { + return; + } + + MatchRules.ApplyHumanInput(_viewState, _localContenderId, input with { InteractPickup = false }); + int subSteps = _viewState.MapKind == ArenaMapKind.Sion ? 1 : ArenaSession.SubStepCount; + ArenaSession.StepContenderPhysicsDrive( + local, + _predWorld.View, + _predBody.Value.Lane, + _viewState.Terrain, + _viewState.MapKind, + _predWalker, + ArenaSession.FixedDt, + injectEngineHeat: false, + world: _predWorld); + if (_viewState.Terrain.IsHeightmapMode) + { + _predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1); + } + _predWorld.Step(ArenaSession.FixedDt, subSteps); + ArenaSession.SyncContenderPoseFromLane(local, _predWorld.View, _predBody.Value.Lane, _predWalker); + } + + private void ApplyCorePvsSnapshot(DecodedCorePvsSnapshot pkt) + { + _viewState.Time = pkt.SimTime; + if (_viewState.Phase == MatchPhase.Lobby && pkt.Phase != MatchPhase.Lobby) + { + _lobbyState = null; + } + _viewState.Phase = pkt.Phase; + _viewState.WinnerContenderId = pkt.WinnerContenderId; + _viewState.Spectators.SetReplicatedSafeRadius(pkt.SafeRadius); + _localDetectedByCount = pkt.DetectedByCount; + _latestServerSimTime = MathF.Max(_latestServerSimTime, pkt.SimTime); + + if (pkt.EchoSendMs != 0) + { + uint nowMs = unchecked((uint)Environment.TickCount64); + int rtt = (int)unchecked(nowMs - pkt.EchoSendMs); + if (rtt >= 0 && rtt < 5000) + { + _pingMs = _pingMs == 0 ? rtt : (int)(_pingMs * 0.7f + rtt * 0.3f); + } + } + + var local = LocalContender; + var prevLocalLifecycle = local.Lifecycle; + local.Lifecycle = pkt.LocalLifecycle; + int nextWaveIdx = pkt.RespawnCutoffReached + ? DropWaveConfig.WaveTimes.Length + : Math.Min(DropWaveConfig.WaveTimes.Length, pkt.CurrentWaveIndex + 1); + _viewState.OrbitalDrop.ApplyReplicatedWaveState(pkt.CurrentWaveIndex, nextWaveIdx, pkt.RespawnCutoffReached); + if (local.Lifecycle != ContenderLifecycle.Deploying) + { + _viewState.OrbitalDrop.CancelContenderPod(local.Id, emitEvent: false); + } + local.InArcWeaponCount = pkt.InArcWeapons; + local.OutOfArcWeaponCount = pkt.OutOfArcWeapons; + local.DisabledWeaponCount = pkt.DisabledWeapons; + local.AllWeaponsOutOfArc = pkt.AllWeaponsOutOfArc; + local.MaxThermalRatio = pkt.LocalMaxThermalRatio; + if (!pkt.LocalAlive && local.Grid.CoreHp > 0f) + { + local.Grid.ApplyReplicatedDamage(0, 0, 0f, local.Grid.Temperature[0, 0], 0f, local.Grid.HitSequence + 1); + } + else if (pkt.LocalAlive && local.Grid.CoreHp <= 0f) + { + local.Grid.ApplyReplicatedDamage(0, 0, local.Grid.Armor[0, 0], local.Grid.Temperature[0, 0], pkt.LocalCoreHp, local.Grid.HitSequence); + } + local.Grid.ApplyReplicatedThermal(pkt.LocalCellTempsQuantized, pkt.LocalMountedTemps, pkt.LocalMountedCooldowns); + + // Option M Reconciliation for local contender + Vector3 prevVisPos = new Vector3(local.X, local.Y, local.Z) + _predErrorPos; + Quaternion currQ = NormalizeQuat(new Quaternion(local.CurrRotX, local.CurrRotY, local.CurrRotZ, local.CurrRotW)); + Quaternion prevVisRot = NormalizeQuat(_predErrorRot * currQ); + + bool chassisChanged = !string.Equals(_predChassisId, local.Grid.Spec.Id, StringComparison.Ordinal); + bool hadSavedPrevSnap = _predWalker is { Initialized: true }; + WalkerVisualSnapshot savedPrevSnap = hadSavedPrevSnap ? _predWalker!.PrevSnap : default; + + // Discard acked inputs + int removeCount = 0; + while (removeCount < _unackedInputs.Count && _unackedInputs[removeCount].Seq <= pkt.AckedInputSeq) + { + removeCount++; + } + if (removeCount > 0) + { + _unackedInputs.RemoveRange(0, removeCount); + } + + WalkerCheckpoint? replayBaseWalker = (!chassisChanged && !_pendingChassisSwapSnap && _unackedInputs.Count > 0) + ? _unackedInputs[0].PreWalker + : null; + + // Snap single-body physics state to authoritative snapshot + local.X = pkt.LocalPos.X; + local.Y = pkt.LocalPos.Y; + local.Z = pkt.LocalPos.Z; + local.CurrRotX = pkt.LocalRot.X; + local.CurrRotY = pkt.LocalRot.Y; + local.CurrRotZ = pkt.LocalRot.Z; + local.CurrRotW = pkt.LocalRot.W; + local.VelX = pkt.LocalVel.X; + local.VelY = pkt.LocalVel.Y; + local.VelZ = pkt.LocalVel.Z; + local.TargetHoverAltAgl = pkt.LocalTargetHoverAltAgl; + if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode) + { + _predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1); + } + SpawnLocalPredictionBody(pkt.LocalPos, pkt.LocalRot, pkt.LocalVel, pkt.LocalAngVel); + + if (local.Lifecycle == ContenderLifecycle.Deploying && + FindActivePodForContender(local.Id) is { } localPod) + { + var qPod = NormalizeQuat(pkt.LocalRot); + var fwdPod = Vector3.Transform(Vector3.UnitZ, qPod); + localPod.X = pkt.LocalPos.X; + localPod.Y = pkt.LocalPos.Y - local.Grid.Spec.HalfHeight; + localPod.Z = pkt.LocalPos.Z; + localPod.VelX = pkt.LocalVel.X; + localPod.VelY = pkt.LocalVel.Y; + localPod.VelZ = pkt.LocalVel.Z; + localPod.CurrRotX = qPod.X; + localPod.CurrRotY = qPod.Y; + localPod.CurrRotZ = qPod.Z; + localPod.CurrRotW = qPod.W; + localPod.Yaw = MathF.Atan2(fwdPod.X, fwdPod.Z); + localPod.Phase = pkt.LocalPodPhase; + var surfSample = QueryLocalDropSurface(localPod.X, localPod.Z, OrbitalPodPreset.Contender.PodFootRadius, localPod.Y + 1.0f); + float terrainY = _viewState.Terrain.SampleHeight(localPod.X, localPod.Z); + float surfY = surfSample.IsBuildingRoof ? MathF.Max(terrainY, surfSample.SurfaceY) : terrainY; + localPod.LastAgl = MathF.Max(0f, localPod.Y - surfY); + } + + if (replayBaseWalker is { } baseCp && + _predWalker is { Initialized: true } && + baseCp.GeomLegCount == _predWalker.Geom.LegCount && + MathF.Abs(baseCp.GeomScale - _predWalker.GeomScale) < 1e-4f) + { + _predWalker.RestoreCheckpoint(in baseCp); + _predWalker.SyncBodyPoseOnly(pkt.LocalPos, pkt.LocalRot, local.Grid.Spec.MassKg); + } + + // Replay unacked inputs + for (int i = 0; i < _unackedInputs.Count; i++) + { + StepLocalPredictionTick(_unackedInputs[i].Input, updatePreviousPose: false); + } + + Vector3 newPredPos = new(local.X, local.Y, local.Z); + Quaternion newPredRot = NormalizeQuat(new Quaternion(local.CurrRotX, local.CurrRotY, local.CurrRotZ, local.CurrRotW)); + + Vector3 deltaPos = prevVisPos - newPredPos; + Quaternion deltaRot = NormalizeQuat(prevVisRot * Quaternion.Inverse(newPredRot)); + if (deltaRot.W < 0f) deltaRot = -deltaRot; + + bool hardSnap = !pkt.LocalAlive || prevLocalLifecycle != local.Lifecycle || (!local.IsGroundedActive && !local.IsInDropPod) || chassisChanged || _pendingChassisSwapSnap || deltaPos.Length() > HardSnapThresholdM; + if (hardSnap) + { + _predErrorPos = Vector3.Zero; + _predErrorRot = Quaternion.Identity; + _pendingChassisSwapSnap = false; + local.SnapPreviousPose(); + if (local.IsInDropPod && FindActivePodForContender(local.Id) is { } lp) + { + lp.SnapPreviousPose(); + } + if (_predWalker is { Initialized: true }) + { + _predWalker.SnapshotPrev(); + } + } + else + { + _predErrorPos = deltaPos; + _predErrorRot = deltaRot; + if (_predWalker is { Initialized: true } && hadSavedPrevSnap) + { + _predWalker.PrevSnap = savedPrevSnap; + } + } + + // Remote contenders in PVS + for (int i = 0; i < MatchState.ContenderCount; i++) + { + if (i == _localContenderId) + { + _contenderVisible[i] = true; + continue; + } + bool inPvs = (pkt.ContenderPvsMask & (1 << i)) != 0; + _contenderVisible[i] = inPvs; + if (!inPvs) + { + _contenderTimeline[i].Clear(); + _viewState.OrbitalDrop.CancelContenderPod(i, emitEvent: false); + } + } + + for (int i = 0; i < pkt.Contenders.Count; i++) + { + var nc = pkt.Contenders[i]; + if (nc.SlotId == _localContenderId || nc.SlotId >= _viewState.Contenders.Count) continue; + var c = _viewState.Contenders[nc.SlotId]; + c.IsHuman = nc.IsHuman; + c.Lifecycle = nc.Lifecycle; + if (nc.Lifecycle != ContenderLifecycle.Deploying) + { + _viewState.OrbitalDrop.CancelContenderPod(c.Id, emitEvent: false); + } + else + { + OrbitalPod? pod = null; + var pods = _viewState.OrbitalDrop.ActivePods; + for (int p = 0; p < pods.Count; p++) + { + if (pods[p].PodKind == OrbitalPodKind.Contender && pods[p].ContenderId == c.Id) + { + pod = pods[p]; + break; + } + } + + float targetY = nc.Pos.Y - c.Grid.Spec.HalfHeight; + var qRemote = NormalizeQuat(nc.Rot); + var fwdRemote = Vector3.Transform(Vector3.UnitZ, qRemote); + float yaw = MathF.Atan2(fwdRemote.X, fwdRemote.Z); + var phase = nc.PodRetroBurn ? OrbitalPodPhase.RetroBurn : OrbitalPodPhase.Freefall; + var surf = QueryLocalDropSurface(nc.Pos.X, nc.Pos.Z, OrbitalPodPreset.Contender.PodFootRadius, targetY + 1.0f); + float ty = _viewState.Terrain.SampleHeight(nc.Pos.X, nc.Pos.Z); + float sy = surf.IsBuildingRoof ? MathF.Max(ty, surf.SurfaceY) : ty; + float agl = MathF.Max(0f, targetY - sy); + + if (pod is null) + { + _viewState.OrbitalDrop.SynthesizeReplicatedContenderPod( + c.Id, nc.Pos.X, targetY, nc.Pos.Z, + nc.Vel.X, nc.Vel.Y, nc.Vel.Z, + qRemote, yaw, phase, agl); + } + else + { + float errSq = (pod.X - nc.Pos.X) * (pod.X - nc.Pos.X) + + (pod.Y - targetY) * (pod.Y - targetY) + + (pod.Z - nc.Pos.Z) * (pod.Z - nc.Pos.Z); + pod.X = nc.Pos.X; + pod.Y = targetY; + pod.Z = nc.Pos.Z; + pod.VelX = nc.Vel.X; + pod.VelY = nc.Vel.Y; + pod.VelZ = nc.Vel.Z; + pod.CurrRotX = qRemote.X; + pod.CurrRotY = qRemote.Y; + pod.CurrRotZ = qRemote.Z; + pod.CurrRotW = qRemote.W; + pod.Yaw = yaw; + pod.Phase = phase; + pod.LastAgl = agl; + if (nc.Snap || errSq > HardSnapThresholdM * HardSnapThresholdM) + { + pod.SnapPreviousPose(); + } + } + } + c.FireCmd = nc.Fire; + c.BrakeCmd = nc.Brake; + c.ThrottleCmd = nc.Throttle; + c.SteerCmd = nc.Steer; + c.MaxThermalRatio = nc.MaxThermalRatio; + c.Grid.ApplyReplicatedCoreHpRatio(nc.CoreHpRatio, nc.Alive); + c.X = nc.Pos.X; c.Y = nc.Pos.Y; c.Z = nc.Pos.Z; + c.CurrRotX = nc.Rot.X; c.CurrRotY = nc.Rot.Y; c.CurrRotZ = nc.Rot.Z; c.CurrRotW = nc.Rot.W; + c.VelX = nc.Vel.X; c.VelY = nc.Vel.Y; c.VelZ = nc.Vel.Z; + c.Speed = MathF.Sqrt(c.VelX * c.VelX + c.VelZ * c.VelZ); + var forward = Vector3.Transform(Vector3.UnitZ, NormalizeQuat(nc.Rot)); + c.Yaw = MathF.Atan2(forward.X, forward.Z); + c.AimX = nc.Pos.X + MathF.Sin(nc.AimYaw) * 25f; + c.AimZ = nc.Pos.Z + MathF.Cos(nc.AimYaw) * 25f; + c.AimY = nc.Pos.Y + MathF.Tan(nc.AimPitchDeg * (MathF.PI / 180f)) * 25f; + if (nc.Snap) + { + _contenderTimeline[nc.SlotId].Clear(); + } + PushPoseSample(_contenderTimeline[nc.SlotId], pkt.SimTime, nc.Pos, nc.Rot, nc.Vel); + } + _connectedHumans = CountHumanContenders(); + + // Combat spectators in PVS (must apply BEFORE walkers so spectator poses are current for walker ComPos/ComRot!) + for (int i = 0; i < pkt.CombatSpectators.Count; i++) + { + var cs = pkt.CombatSpectators[i]; + if (cs.Id < _lastCombatSpecSeenSeq.Length) + { + _lastCombatSpecSeenSeq[cs.Id] = pkt.SnapshotSeq; + } + ApplySpectatorSnapshot(cs, pkt.SimTime); + } + + var allSpecs = _viewState.Spectators.Spectators; + for (int i = 0; i < allSpecs.Count && i < _spectatorVisible.Length; i++) + { + if (_spectatorVisible[i] && + allSpecs[i].Stance != SpectatorStance.Neutral && + pkt.SnapshotSeq > _lastCombatSpecSeenSeq[i] + 2) + { + _spectatorVisible[i] = false; + } + } + + // Walkers in PVS + for (int i = 0; i < pkt.Walkers.Count; i++) + { + var nw = pkt.Walkers[i]; + if (nw.IsContender && nw.EntityId == _localContenderId) + { + continue; + } + var map = nw.IsContender ? _contenderWalkerTimelines : _spectatorWalkerTimelines; + if (!map.TryGetValue(nw.EntityId, out var list)) + { + list = new List(16); + map[nw.EntityId] = list; + } + if (list.Count >= 16) list.RemoveAt(0); + var snap = nw.Snapshot; + if (nw.IsContender && nw.EntityId < _viewState.Contenders.Count) + { + var c = _viewState.Contenders[nw.EntityId]; + var g = WalkerGeometrySpec.GetForChassis(c.Grid.Spec.Id); + snap.GeomScale = g.ModelHalfHeight > 1e-4f ? c.Grid.Spec.HalfHeight / g.ModelHalfHeight : 1f; + snap.IsDigitigrade = g.IsDigitigrade; + snap.IsArachnidUp = g.IsArachnidUp; + snap.ComPos = new Vector3(c.X, c.Y, c.Z); + snap.ComRot = NormalizeQuat(new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW)); + } + else if (!nw.IsContender && nw.EntityId < allSpecs.Count) + { + var s = allSpecs[nw.EntityId]; + var g = WalkerGeometrySpec.GetForChassis(s.Grid.Spec.Id); + snap.GeomScale = g.ModelHalfHeight > 1e-4f ? s.Grid.Spec.HalfHeight / g.ModelHalfHeight : 1f; + snap.IsDigitigrade = g.IsDigitigrade; + snap.IsArachnidUp = g.IsArachnidUp; + snap.ComPos = new Vector3(s.X, s.Y, s.Z); + snap.ComRot = NormalizeQuat(new Quaternion(s.CurrRotX, s.CurrRotY, s.CurrRotZ, s.CurrRotW)); + } + list.Add(new WalkerSample { SimTime = pkt.SimTime, Snap = snap }); + } + } + + private void ApplySpectatorOrbit(DecodedSpectatorOrbitSnapshot orbit) + { + // Clear visibility for neutral spectators in this half before re-marking PVS ones + var specs = _viewState.Spectators.Spectators; + for (int i = orbit.HalfIndex; i < specs.Count; i += 2) + { + if (specs[i].Stance == SpectatorStance.Neutral) + { + _spectatorVisible[i] = false; + } + } + for (int i = 0; i < orbit.Spectators.Count; i++) + { + var ns = orbit.Spectators[i]; + if (ns.Stance != SpectatorStance.Neutral && ns.Id < _lastCombatSpecSeenSeq.Length) + { + _lastCombatSpecSeenSeq[ns.Id] = orbit.SnapshotSeq; + } + ApplySpectatorSnapshot(ns, _latestServerSimTime); + } + } + + private void ApplySpectatorSnapshot(in NetSpectatorState ns, float simTime) + { + if (ns.Id >= _spectatorVisible.Length || ns.Id >= _viewState.Spectators.Spectators.Count) return; + _spectatorVisible[ns.Id] = true; + var s = _viewState.Spectators.Spectators[ns.Id]; + s.Stance = ns.Stance; + s.TargetContenderId = ns.TargetContenderId >= 0 ? ns.TargetContenderId : null; + s.X = ns.Pos.X; s.Y = ns.Pos.Y; s.Z = ns.Pos.Z; + s.CurrRotX = ns.Rot.X; s.CurrRotY = ns.Rot.Y; s.CurrRotZ = ns.Rot.Z; s.CurrRotW = ns.Rot.W; + s.VelX = ns.Vel.X; s.VelY = ns.Vel.Y; s.VelZ = ns.Vel.Z; + if (ns.Snap) _spectatorTimeline[ns.Id].Clear(); + PushPoseSample(_spectatorTimeline[ns.Id], simTime, ns.Pos, ns.Rot, ns.Vel); + } + + private void ApplyRadarContacts(DecodedRadarContactsSnapshot radar) + { + var obs = _viewState.GetOrCreateObserverState(_localContenderId); + obs.ContenderContacts.Clear(); + for (int i = 0; i < radar.Contenders.Count; i++) + { + var rc = radar.Contenders[i]; + obs.ContenderContacts[rc.EntityId] = new PlayerContactMemory + { + VisibleToPlayer = rc.Visible, + FaintHorizonPing = rc.FaintHorizon, + HasEverBeenSeen = rc.HasEverBeenSeen, + LastSeenAge = rc.LastSeenAge, + LastSeenX = rc.LastSeenX, + LastSeenZ = rc.LastSeenZ + }; + } + + obs.SpectatorContacts.Clear(); + for (int i = 0; i < radar.Spectators.Count; i++) + { + var rs = radar.Spectators[i]; + if (rs.EntityId >= _viewState.Spectators.Spectators.Count) continue; + int sId = _viewState.Spectators.Spectators[rs.EntityId].Id; + obs.SpectatorContacts[sId] = new PlayerContactMemory + { + VisibleToPlayer = rs.Visible, + FaintHorizonPing = rs.FaintHorizon, + HasEverBeenSeen = rs.HasEverBeenSeen, + LastSeenAge = rs.LastSeenAge, + LastSeenX = rs.LastSeenX, + LastSeenZ = rs.LastSeenZ + }; + } + } + + private void ApplyEventBatch(SimEventBatchMsg batch) + { + for (int i = 0; i < batch.Events.Count; i++) + { + switch (batch.Events[i]) + { + case ShotFiredEvent shot: + _viewState.Tracers.Add(new TracerEvent( + shot.StartX, shot.StartY, shot.StartZ, + shot.EndX, shot.EndY, shot.EndZ, + shot.ColorRgba, + shot.Ttl, + (WeaponVisualClass)shot.WeaponClass, + shot.WeaponId, + shot.TracerId)); + break; + case HitImpactEvent hit: + _viewState.HitEvents.Add(new HitFeedbackEvent( + hit.EventId, + hit.HitX, hit.HitY, hit.HitZ, + hit.NormalX, hit.NormalY, hit.NormalZ, + hit.SourceX, hit.SourceY, hit.SourceZ, + (HitTargetKind)hit.TargetKind, + hit.TargetId, + hit.CellX, hit.CellY, + (WeaponVisualClass)hit.WeaponClass, + hit.WeaponId, + hit.IsAirburst, + hit.Ttl)); + if (hit.TargetKind == (byte)HitTargetKind.Contender && hit.TargetId >= 0 && hit.TargetId < _viewState.Contenders.Count) + { + _viewState.Contenders[hit.TargetId].Grid.ApplyReplicatedDamage( + hit.CellX, hit.CellY, hit.NewCellArmor, hit.NewCellTemp, hit.NewCoreHp, hit.HitSequence); + } + else if (hit.TargetKind == (byte)HitTargetKind.Spectator) + { + int sIdx = hit.TargetId >= 1000 ? hit.TargetId - 1000 : hit.TargetId; + if (sIdx >= 0 && sIdx < _viewState.Spectators.Spectators.Count) + { + _viewState.Spectators.Spectators[sIdx].Grid.ApplyReplicatedDamage( + hit.CellX, hit.CellY, hit.NewCellArmor, hit.NewCellTemp, hit.NewCoreHp, hit.HitSequence); + } + } + break; + case TerrainStampEvent stamp: + ApplyTerrainStamp(stamp); + break; + case ArenaRepairEvent: + _viewState.RepairArenaScars(); + if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode) + { + _predTileSync.SyncWindow(_predWorld, _viewState.Terrain, LocalContender.X, LocalContender.Z, halfTileRadius: 1); + } + break; + case DropSpawnedEvent ds: + _viewState.ApplyReplicatedDropSpawned( + ds.DropId, ds.X, ds.Z, + ds.ChassisId is not null && Catalog.ChassisById.TryGetValue(ds.ChassisId, out var cs) ? cs : null, + Catalog.TryGetModule(ds.ModuleId, out var ms) ? ms : null); + break; + case DropPickedUpEvent dp: + _viewState.ApplyReplicatedDropPickedUp(dp.DropId); + break; + case ContenderLoadoutEvent cl: + if (cl.ContenderId >= 0 && cl.ContenderId < _viewState.Contenders.Count) + { + string prevChassisId = _viewState.Contenders[cl.ContenderId].Grid.Spec.Id; + ApplyLoadoutToContender(_viewState.Contenders[cl.ContenderId], cl); + if (cl.ContenderId == _localContenderId) + { + var l = LocalContender; + if (!string.Equals(prevChassisId, cl.ChassisId, StringComparison.Ordinal)) + { + _pendingChassisSwapSnap = true; + _predErrorPos = Vector3.Zero; + _predErrorRot = Quaternion.Identity; + if (l.IsGroundedActive) + { + float groundY = _viewState.Terrain.SampleHeight(l.X, l.Z); + l.Y = MathF.Max(l.Y, groundY + l.Grid.Spec.HalfHeight + 0.1f); + } + l.SnapPreviousPose(); + } + if (FindActivePodForContender(l.Id) is { } lp) + { + lp.Chassis = l.Grid.Spec; + } + SpawnLocalPredictionBody( + new Vector3(l.X, l.Y, l.Z), + NormalizeQuat(new Quaternion(l.CurrRotX, l.CurrRotY, l.CurrRotZ, l.CurrRotW)), + new Vector3(l.VelX, l.VelY, l.VelZ), + Vector3.Zero); + } + } + break; + case EntitySlotControlEvent slotCtrl: + if (slotCtrl.ContenderId >= 0 && slotCtrl.ContenderId < _viewState.Contenders.Count) + { + var c = _viewState.Contenders[slotCtrl.ContenderId]; + c.IsHuman = slotCtrl.IsHuman; + c.Name = slotCtrl.Name; + _connectedHumans = CountHumanContenders(); + } + break; + case BroadcastLineEvent bl: + _viewState.Broadcast.Emit(bl.Timestamp, (BroadcastKind)bl.Kind, bl.Text); + break; + case ContenderEliminatedEvent elim: + if (elim.VictimId >= 0 && elim.VictimId < _viewState.Contenders.Count) + { + var v = _viewState.Contenders[elim.VictimId]; + v.Lifecycle = (ContenderLifecycle)elim.VictimLifecycleByte; + v.Grid.ApplyReplicatedDamage(0, 0, 0f, v.Grid.Temperature[0, 0], 0f, v.Grid.HitSequence + 1); + } + if (!elim.IsSpectatorKiller && elim.KillerId >= 0 && elim.KillerId < _viewState.Contenders.Count) + { + _viewState.Contenders[elim.KillerId].Kills = elim.KillerKills; + } + break; + case DropPodEvent dpe: + _viewState.OrbitalDrop.ApplyReplicatedDropPodEvent(dpe, QueryLocalDropSurface); + break; + case OrdnanceNodeEvent: + // Forwarded to _pendingClientEvents; ClientOrdnanceMirror attaches in Cut 7b + break; + case SpectatorDestroyedEvent sdet: + { + int sIdx = sdet.SpectatorId >= 1000 ? sdet.SpectatorId - 1000 : sdet.SpectatorId; + if (sIdx >= 0 && sIdx < _viewState.Spectators.Spectators.Count) + { + var s = _viewState.Spectators.Spectators[sIdx]; + s.Grid.ApplyReplicatedDamage(0, 0, 0f, s.Grid.Temperature[0, 0], 0f, s.Grid.HitSequence + 1); + } + if (sdet.KillerContenderId >= 0 && sdet.KillerContenderId < _viewState.Contenders.Count) + { + _viewState.Contenders[sdet.KillerContenderId].Kills = sdet.KillerKills; + } + break; + } + case MatchResetEvent reset: + ApplyInitialMatchState(reset.FullInitialState, reset.AssignedContenderId); + break; + case MatchStartedEvent started: + if (started.MatchGeneration == _matchGeneration || started.MatchGeneration == 0) + { + _viewState.Phase = MatchPhase.Active; + _lobbyState = null; + } + break; + } + _pendingClientEvents.Add(batch.Events[i]); + } + if (_pendingClientEvents.Count > 4096) + { + _pendingClientEvents.RemoveRange(0, _pendingClientEvents.Count - 4096); + } + } + + private void ApplyEntitySync(EntitySyncSnapshotMsg sync) + { + if (sync.IsContender && sync.EntityId >= 0 && sync.EntityId < _viewState.Contenders.Count) + { + var c = _viewState.Contenders[sync.EntityId]; + string prevChassisId = c.Grid.Spec.Id; + c.X = sync.PosX; c.Y = sync.PosY; c.Z = sync.PosZ; c.Yaw = sync.Yaw; + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, sync.Yaw); + c.CurrRotX = q.X; c.CurrRotY = q.Y; c.CurrRotZ = q.Z; c.CurrRotW = q.W; + c.SnapPreviousPose(); + if (sync.ContenderLoadout is not null) + { + ApplyLoadoutToContender(c, sync.ContenderLoadout); + } + c.Grid.ApplyReplicatedArmorBytes(sync.ArmorBytes); + c.Grid.ApplyReplicatedDamage(0, 0, c.Grid.Armor[0, 0], c.Grid.Temperature[0, 0], sync.Alive ? sync.CoreHp : 0f, c.Grid.HitSequence); + if (sync.EntityId == _localContenderId) + { + if (!string.Equals(prevChassisId, c.Grid.Spec.Id, StringComparison.Ordinal)) + { + _pendingChassisSwapSnap = true; + _predErrorPos = Vector3.Zero; + _predErrorRot = Quaternion.Identity; + } + if (FindActivePodForContender(c.Id) is { } lp) + { + lp.Chassis = c.Grid.Spec; + } + SpawnLocalPredictionBody( + new Vector3(c.X, c.Y, c.Z), + q, + new Vector3(c.VelX, c.VelY, c.VelZ), + Vector3.Zero); + } + _contenderTimeline[c.Id].Clear(); + PushPoseSample(_contenderTimeline[c.Id], _latestServerSimTime, new Vector3(c.X, c.Y, c.Z), q, Vector3.Zero); + } + else if (!sync.IsContender) + { + int sIdx = sync.EntityId >= 1000 ? sync.EntityId - 1000 : sync.EntityId; + if (sIdx >= 0 && sIdx < _viewState.Spectators.Spectators.Count) + { + var s = _viewState.Spectators.Spectators[sIdx]; + s.X = sync.PosX; s.Y = sync.PosY; s.Z = sync.PosZ; s.Yaw = sync.Yaw; + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, sync.Yaw); + s.CurrRotX = q.X; s.CurrRotY = q.Y; s.CurrRotZ = q.Z; s.CurrRotW = q.W; + s.SnapPreviousPose(); + s.Grid.ApplyReplicatedArmorBytes(sync.ArmorBytes); + s.Grid.ApplyReplicatedDamage(0, 0, s.Grid.Armor[0, 0], s.Grid.Temperature[0, 0], sync.Alive ? sync.CoreHp : 0f, s.Grid.HitSequence); + _spectatorTimeline[sIdx].Clear(); + PushPoseSample(_spectatorTimeline[sIdx], _latestServerSimTime, new Vector3(s.X, s.Y, s.Z), q, Vector3.Zero); + } + } + } + + private void ApplyTerrainStamp(TerrainStampEvent stamp) + { + _viewState.ApplyTerrainStamp(stamp, recordInLedger: true); + if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode) + { + _predTileSync.SyncWindow(_predWorld, _viewState.Terrain, LocalContender.X, LocalContender.Z, halfTileRadius: 1); + } + } + + private static void ApplyLoadoutToContender(ContenderState c, ContenderLoadoutEvent cl) + { + if (!Catalog.ChassisById.TryGetValue(cl.ChassisId, out var spec)) return; + var mounted = new List<(string, string)>(cl.Mounted.Count); + for (int i = 0; i < cl.Mounted.Count; i++) + { + mounted.Add((cl.Mounted[i].ModuleId, cl.Mounted[i].HardpointId)); + } + c.LoadoutVersion = cl.LoadoutVersion; + c.Grid.ApplyReplicatedLoadout( + spec, + cl.CoreHp, + cl.MaxCoreHp, + cl.ArmorBytes, + mounted, + cl.CargoIds, + id => Catalog.TryGetModule(id, out var ms) ? ms : null); + } + + private static void PushPoseSample(List timeline, float simTime, Vector3 pos, Quaternion rot, Vector3 vel) + { + if (timeline.Count >= 16) timeline.RemoveAt(0); + timeline.Add(new PoseSample { SimTime = simTime, Pos = pos, Rot = NormalizeQuat(rot), Vel = vel }); + } + + private (Vector3 Pos, Quaternion Rot, Vector3 Vel) SamplePoseTimeline(List timeline, ContenderState fallback) + { + if (timeline.Count == 0) + { + return ( + new Vector3(fallback.X, fallback.Y, fallback.Z), + NormalizeQuat(new Quaternion(fallback.CurrRotX, fallback.CurrRotY, fallback.CurrRotZ, fallback.CurrRotW)), + new Vector3(fallback.VelX, fallback.VelY, fallback.VelZ)); + } + return SampleTimelineSamples(timeline); + } + + private (Vector3 Pos, Quaternion Rot, Vector3 Vel) SampleTimelineSamples(List timeline) + { + if (timeline.Count == 1 || _renderTime <= timeline[0].SimTime) + { + var p = timeline[0]; + return (p.Pos, p.Rot, p.Vel); + } + int last = timeline.Count - 1; + if (_renderTime >= timeline[last].SimTime) + { + var p = timeline[last]; + return (p.Pos, p.Rot, p.Vel); + } + for (int i = 0; i < last; i++) + { + var a = timeline[i]; + var b = timeline[i + 1]; + if (_renderTime >= a.SimTime && _renderTime <= b.SimTime) + { + float span = MathF.Max(1e-5f, b.SimTime - a.SimTime); + float u = Math.Clamp((_renderTime - a.SimTime) / span, 0f, 1f); + Quaternion qa = a.Rot; + Quaternion qb = b.Rot; + if (Quaternion.Dot(qa, qb) < 0f) qb = -qb; + return ( + Vector3.Lerp(a.Pos, b.Pos, u), + Quaternion.Slerp(qa, qb, u), + Vector3.Lerp(a.Vel, b.Vel, u)); + } + } + var tail = timeline[last]; + return (tail.Pos, tail.Rot, tail.Vel); + } + + private static bool RayIntersectsObb( + Vector3 origin, + Vector3 dir, + float maxDist, + Vector3 boxPos, + Quaternion boxRot, + Vector3 halfExtents, + out float frac, + out Vector3 worldNormal) + { + Quaternion inv = Quaternion.Conjugate(NormalizeQuat(boxRot)); + Vector3 lo = Vector3.Transform(origin - boxPos, inv); + Vector3 ld = Vector3.Transform(dir, inv); + + float tMin = 0f; + float tMax = maxDist; + Vector3 localNormal = Vector3.UnitY; + + if (!Slab(lo.X, ld.X, -halfExtents.X, halfExtents.X, new Vector3(1, 0, 0), ref tMin, ref tMax, ref localNormal)) { frac = 1f; worldNormal = Vector3.UnitY; return false; } + if (!Slab(lo.Y, ld.Y, -halfExtents.Y, halfExtents.Y, new Vector3(0, 1, 0), ref tMin, ref tMax, ref localNormal)) { frac = 1f; worldNormal = Vector3.UnitY; return false; } + if (!Slab(lo.Z, ld.Z, -halfExtents.Z, halfExtents.Z, new Vector3(0, 0, 1), ref tMin, ref tMax, ref localNormal)) { frac = 1f; worldNormal = Vector3.UnitY; return false; } + + if (tMax < tMin || tMin < 0f || tMin > maxDist) + { + frac = 1f; + worldNormal = Vector3.UnitY; + return false; + } + + frac = tMin / maxDist; + worldNormal = Vector3.Normalize(Vector3.Transform(localNormal, boxRot)); + return true; + } + + private static bool Slab(float o, float d, float minB, float maxB, Vector3 axis, ref float tMin, ref float tMax, ref Vector3 hitNormal) + { + if (MathF.Abs(d) < 1e-6f) + { + return o >= minB && o <= maxB; + } + float invD = 1f / d; + float t1 = (minB - o) * invD; + float t2 = (maxB - o) * invD; + Vector3 n = -MathF.Sign(d) * axis; + if (t1 > t2) + { + (t1, t2) = (t2, t1); + } + if (t1 > tMin) + { + tMin = t1; + hitNormal = n; + } + tMax = MathF.Min(tMax, t2); + return tMax >= tMin; + } + + private void SendSchemaMessage(ISchemaWireMessage msg) + { + byte[] payload = SnapshotCodec.SerializeSchemaMessage(msg); + byte[] wire = SnapshotCodec.WrapSchema(payload, _matchGeneration, _outSchemaSeq++); + try + { + _conn.SendSchema(wire); + } + catch (SocketException) + { + } + } + + private int CountHumanContenders() + { + int humans = 0; + for (int i = 0; i < _viewState.Contenders.Count; i++) + { + if (_viewState.Contenders[i].IsHuman) humans++; + } + return Math.Max(1, humans); + } + + private static Quaternion NormalizeQuat(Quaternion q) => + q.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(q); + + public void Dispose() + { + if (_disposed) return; + DisconnectGracefully("Disposed"); + _disposed = true; + _predWorld?.Dispose(); + _conn.Dispose(); + _socket.Dispose(); + } + } +} diff --git a/src/RustToDust.Net/RustToDust.Net.csproj b/src/RustToDust.Net/RustToDust.Net.csproj new file mode 100644 index 0000000..35ee846 --- /dev/null +++ b/src/RustToDust.Net/RustToDust.Net.csproj @@ -0,0 +1,18 @@ + + + + net8.0 + enable + disable + Release + + + + + + + + + + + diff --git a/src/RustToDust.Net/ServerMatchHost.cs b/src/RustToDust.Net/ServerMatchHost.cs new file mode 100644 index 0000000..4d7674f --- /dev/null +++ b/src/RustToDust.Net/ServerMatchHost.cs @@ -0,0 +1,2146 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Numerics; +using GameCult.Mesh; +using GameCult.Networking; +using RustToDust.Core; +using RustToDust.Ymir; + +namespace RustToDust.Net +{ + public sealed class ServerMatchHost : IDisposable + { + public const long IdleTimeoutMs = 5000; + + private sealed class ConnectedPeer + { + public uint PeerId; + public CultNetRudpSocketServerPeer TransportPeer = null!; + public string EndpointKey = string.Empty; + public Guid ReconnectToken; + public int AssignedContenderId; + public string Callsign = string.Empty; + public long LastHeardUtcMs; + public uint LastAcceptedInputSeq; + public uint LastEchoSendMs; + public ushort LastInteractSeq; + public bool Active = true; + public readonly EntityPvsTracker[] ContenderTrackers = new EntityPvsTracker[MatchState.ContenderCount]; + public readonly EntityPvsTracker[] SpectatorTrackers = new EntityPvsTracker[SpectatorRing.DefaultSpectatorCount]; + public readonly HashSet SentDropIds = new(); + public readonly HashSet SentPodIds = new(); + public readonly HashSet SentOrdnanceIds = new(); + public readonly HashSet SentTerrainStampIndices = new(); + public readonly int[,] SentTileVersions = new int[16, 16]; + } + + private struct EntityPvsTracker + { + public bool InPvs; + public bool SnapNext; + public int AckedLoadoutVersion; + public int AckedDamageVersion; + public ContenderLifecycle LastLifecycle; + } + + private readonly Socket _socket; + private readonly CultNetRudpSocketTransportServer _server; + private readonly Dictionary _peersByEndpoint = new(StringComparer.Ordinal); + private readonly HashSet _retiredTransportPeers = new(); + private readonly Dictionary _reconnectTokens = new(); + private readonly List _stepEvents = new(); + private readonly List _hostPendingEvents = new(); + private readonly List _terrainStampHistory = new(); + private readonly List[,] _tileStampHistory = new List[16, 16]; + private readonly string? _configuredScarPath; + private readonly ArenaMapKind _initialMapKind; + private readonly bool _persistScars; + private readonly Dictionary _inMemoryScarsByMap = new(); + private readonly int _maxHumans; + private readonly double _autoRestartSec; + private readonly bool _allowClientReset; + private readonly int? _hostContenderId; + private readonly string _serverName; + private readonly int _minHumansToStart; + private readonly bool _restartToLobby; + private readonly byte[] _udpPeekBuf = new byte[65535]; + + private ArenaSession _session; + private byte _squadSize; + private string _hostCallsign = "Host"; + private uint _matchGeneration = 1; + private uint _simTick; + private uint _snapshotSeq; + private ulong _eventBatchSeq = 1; + private long _schemaOutSeq = 1; + private long _latestOutSeq = 1; + private uint _nextPeerId = 1; + private float _roundCompletedElapsed; + private int _lastBroadcastCountdownSec = -1; + private uint _lastScarSaveTick; + private bool _disposed; + + public ServerMatchHost( + IPAddress bindAddress, + int port, + int seed = 42, + ArenaMapKind mapKind = ArenaMapKind.Desert, + int maxHumans = MatchState.ContenderCount, + double autoRestartSec = 8.0, + bool allowClientReset = false, + int? hostContenderId = null, + bool startInLobby = false, + string serverName = "Rust to Dust", + int minHumansToStart = 1, + bool restartToLobby = false, + byte squadSize = 1, + string? scarFilePath = null, + bool persistScars = false, + bool repairScarsOnStart = false) + { + _maxHumans = Math.Clamp(maxHumans, 1, MatchState.ContenderCount); + _autoRestartSec = autoRestartSec; + _allowClientReset = allowClientReset; + _hostContenderId = hostContenderId; + _serverName = string.IsNullOrWhiteSpace(serverName) ? "Rust to Dust" : serverName.Trim(); + _minHumansToStart = Math.Clamp(minHumansToStart, 1, _maxHumans); + _restartToLobby = restartToLobby; + _squadSize = (byte)Math.Clamp((int)squadSize, 1, 4); + _persistScars = persistScars; + _configuredScarPath = scarFilePath; + _initialMapKind = mapKind; + for (int tz = 0; tz < 16; tz++) + { + for (int tx = 0; tx < 16; tx++) + { + _tileStampHistory[tx, tz] = new List(4); + } + } + + _socket = new Socket(bindAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp) + { + Blocking = false + }; + _socket.Bind(new IPEndPoint(bindAddress, port)); + BoundPort = ((IPEndPoint)_socket.LocalEndPoint!).Port; + + _server = new CultNetRudpSocketTransportServer(new CultNetRudpSocketTransportServerOptions + { + RuntimeId = "rtd-server", + Socket = _socket, + ConnectionId = 0x52544431, + ResendDelayMs = 100, + MaxFragmentBytes = SnapshotCodec.MaxLatestFrameBytes, + MaxPayloadBytes = 256 * 1024, + MaxPendingReliablePackets = 2048 + }); + _server.PeerDisconnected += OnTransportPeerDisconnected; + + ArenaScarLedgerSnapshot? initialScars = null; + string? initScarPath = _persistScars ? ResolveScarFilePath(_configuredScarPath, _initialMapKind, mapKind) : null; + if (_persistScars && initScarPath is not null) + { + string fp = GetAssetFingerprint(seed, mapKind); + if (repairScarsOnStart) + { + var emptySnap = new ArenaScarLedgerSnapshot { AssetFingerprint = fp }; + ArenaScarLedgerStore.Save(initScarPath, emptySnap); + } + else + { + initialScars = ArenaScarLedgerStore.Load(initScarPath, fp); + } + } + + _session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize, initialScars: initialScars); + if (hostContenderId.HasValue) + { + _session.SetHumanSlot(hostContenderId.Value, true, "Host"); + } + InitLobbyMetadata(_session); + } + + public int BoundPort { get; } + public ArenaSession Session => _session; + public uint MatchGeneration => _matchGeneration; + public uint SimTick => _simTick; + public string ServerName => _serverName; + public int MaxHumans => _maxHumans; + public int ConnectedHumanCount => _peersByEndpoint.Count + (_hostContenderId.HasValue ? 1 : 0); + public bool AcceptingJoin => ConnectedHumanCount < _maxHumans && (_session.State.Phase == MatchPhase.Lobby || _session.State.Phase == MatchPhase.Active); + public long TransportPacketsDropped => _server.Stats.PacketsDropped; + public CultNetTransportStats TransportStats => _server.Stats; + public LobbyState? Lobby => _session.State.Lobby; + public event Action? LogMessage; + + public void SetHostInput(in PlayerInput input) + { + if (_hostContenderId.HasValue) + { + _session.SetHumanInput(_hostContenderId.Value, input); + } + } + + public void DrainHostEvents(List dest) + { + if (_hostPendingEvents.Count == 0) + { + return; + } + dest.AddRange(_hostPendingEvents); + _hostPendingEvents.Clear(); + } + + public bool TryEquipHostCargo(int cargoIndex, string hardpointId) + { + if (!_hostContenderId.HasValue) return false; + bool ok = _session.TryEquipCargo(_hostContenderId.Value, cargoIndex, hardpointId); + if (ok) + { + _session.DrainStepEvents(_hostPendingEvents); + } + return ok; + } + + public void ResetMatch(int seed, ArenaMapKind mapKind) => + ResetMatch(seed, mapKind, startInLobby: false); + + public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby) => + ResetMatch(seed, mapKind, startInLobby, repairScars: false); + + public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby, bool repairScars) + { + if (_hostContenderId.HasValue && _hostContenderId.Value >= 0 && _hostContenderId.Value < _session.State.Contenders.Count) + { + _hostCallsign = _session.State.Contenders[_hostContenderId.Value].Name; + } + ArenaMapKind prevMapKind = _session.State.MapKind; + if (repairScars && mapKind == prevMapKind) + { + _session.State.RepairArenaScars(); + _inMemoryScarsByMap.Remove(mapKind); + } + _inMemoryScarsByMap[prevMapKind] = _session.State.ScarLedger.ToSnapshot(); + FlushScarLedgerIfDirty(); + + ArenaScarLedgerSnapshot? preservedScars = null; + if (mapKind == prevMapKind) + { + preservedScars = _session.State.ScarLedger.ToSnapshot(); + } + else if (repairScars) + { + _inMemoryScarsByMap.Remove(mapKind); + if (_persistScars) + { + string targetPath = ResolveScarFilePath(_configuredScarPath, _initialMapKind, mapKind); + if (!string.IsNullOrWhiteSpace(targetPath)) + { + var emptySnap = new ArenaScarLedgerSnapshot { AssetFingerprint = GetAssetFingerprint(seed, mapKind) }; + ArenaScarLedgerStore.Save(targetPath, emptySnap); + } + } + } + else + { + string expectedFp = GetAssetFingerprint(seed, mapKind); + if (_inMemoryScarsByMap.TryGetValue(mapKind, out var memScars) && + string.Equals(memScars.AssetFingerprint, expectedFp, StringComparison.Ordinal)) + { + preservedScars = memScars; + } + else if (_persistScars) + { + string targetPath = ResolveScarFilePath(_configuredScarPath, _initialMapKind, mapKind); + preservedScars = ArenaScarLedgerStore.Load(targetPath, expectedFp); + } + } + + _session.Dispose(); + _session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize, initialScars: preservedScars); + _matchGeneration++; + _simTick = 0; + _roundCompletedElapsed = 0f; + _lastBroadcastCountdownSec = -1; + _terrainStampHistory.Clear(); + ClearTileStampHistory(); + _stepEvents.Clear(); + _hostPendingEvents.Clear(); + _reconnectTokens.Clear(); + + if (_hostContenderId.HasValue) + { + _session.SetHumanSlot(_hostContenderId.Value, true, _hostCallsign); + } + InitLobbyMetadata(_session); + + foreach (var peer in _peersByEndpoint.Values) + { + if (!peer.Active) continue; + int slot = peer.AssignedContenderId; + peer.LastAcceptedInputSeq = 0; + peer.LastInteractSeq = 0; + _session.SetHumanSlot(slot, true, peer.Callsign); + _reconnectTokens[peer.ReconnectToken] = (slot, peer.Callsign); + } + + foreach (var peer in _peersByEndpoint.Values) + { + if (!peer.Active) continue; + int slot = peer.AssignedContenderId; + InitPeerTrackers(peer); + var reset = new MatchResetEvent + { + MatchGeneration = _matchGeneration, + Seed = seed, + MapKind = (byte)mapKind, + AssignedContenderId = slot, + FullInitialState = BuildInitialMatchStateDto(slot) + }; + SendSchemaToPeer(peer, new SimEventBatchMsg + { + BatchSeq = _eventBatchSeq++, + SimTick = _simTick, + SimTime = _session.State.Time, + MatchGeneration = _matchGeneration, + Events = new List { reset } + }); + } + } + + public bool SetLobbyReady(int contenderId, bool ready) + { + if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby) + { + return false; + } + if (contenderId < 0 || contenderId >= lobby.Slots.Length || !lobby.Slots[contenderId].IsHuman) + { + return false; + } + + lobby.Slots[contenderId].IsReady = ready; + ReevaluateLobbyCountdown(lobby); + BroadcastLobbySnapshot(); + return true; + } + + public bool ConfigureLobby(int requesterContenderId, int seed, ArenaMapKind mapKind) => + ConfigureLobby(requesterContenderId, seed, mapKind, squadSize: null); + + public bool ConfigureLobby(int requesterContenderId, int seed, ArenaMapKind mapKind, byte? squadSize) + { + if (_session.State.Phase != MatchPhase.Lobby) + { + return false; + } + if (!IsLobbyAuthority(requesterContenderId)) + { + return false; + } + + if (squadSize.HasValue && squadSize.Value >= 1 && squadSize.Value <= 4) + { + _squadSize = squadSize.Value; + } + ResetMatch(seed, mapKind, startInLobby: true); + return true; + } + + public bool MovePeerToSquad(int contenderId, byte targetSquadId) + { + if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby) + { + return false; + } + if (contenderId < 0 || contenderId >= lobby.Slots.Length) + { + return false; + } + byte squadSize = (byte)Math.Clamp((int)lobby.SquadSize, 1, 4); + if (squadSize <= 1) + { + return false; + } + + int maxSquads = (MatchState.ContenderCount + squadSize - 1) / squadSize; + if (targetSquadId >= maxSquads) + { + return false; + } + byte targetSq = targetSquadId; + var srcSlot = lobby.Slots[contenderId]; + byte srcSq = srcSlot.SquadId; + if (srcSq == targetSq) + { + return true; + } + + int targetCount = 0; + LobbySlotState? swapAi = null; + for (int i = 0; i < lobby.Slots.Length; i++) + { + var s = lobby.Slots[i]; + if (s.SquadId == targetSq) + { + targetCount++; + if (!s.IsHuman && swapAi is null) + { + swapAi = s; + } + } + } + + if (targetCount < squadSize) + { + srcSlot.SquadId = targetSq; + _session.State.Contenders[contenderId].SquadId = targetSq; + } + else if (swapAi is not null) + { + swapAi.SquadId = srcSq; + _session.State.Contenders[swapAi.SlotId].SquadId = srcSq; + srcSlot.SquadId = targetSq; + _session.State.Contenders[contenderId].SquadId = targetSq; + } + else + { + return false; + } + + BroadcastLobbySnapshot(); + return true; + } + + public bool LaunchFromLobby(int requesterContenderId) + { + if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby) + { + return false; + } + if (!IsLobbyAuthority(requesterContenderId)) + { + return false; + } + + if (lobby.ForceLaunched) + { + lobby.CountdownSeconds = 0f; + } + else + { + lobby.ForceLaunched = true; + lobby.CountdownSeconds ??= LobbyState.DefaultCountdownSeconds; + _lastBroadcastCountdownSec = (int)MathF.Ceiling(lobby.CountdownSeconds.Value); + BroadcastLobbySnapshot(); + } + return true; + } + + private bool IsLobbyAuthority(int requesterContenderId) => + _hostContenderId.HasValue + ? requesterContenderId == _hostContenderId.Value + : _allowClientReset; + + private void InitLobbyMetadata(ArenaSession session) + { + if (session.State.Lobby is not { } lobby) return; + lobby.HostSlotId = _hostContenderId; + lobby.MinHumansToAutoStart = _minHumansToStart; + lobby.SelectedMap = session.State.MapKind; + lobby.SelectedSeed = session.State.Seed; + lobby.SquadSize = session.State.SquadSize; + lobby.CountdownSeconds = null; + lobby.ForceLaunched = false; + for (int i = 0; i < session.State.Contenders.Count && i < lobby.Slots.Length; i++) + { + var c = session.State.Contenders[i]; + lobby.Slots[i].IsHuman = c.IsHuman; + lobby.Slots[i].Callsign = c.Name; + lobby.Slots[i].IsReady = false; + lobby.Slots[i].SquadId = c.SquadId; + } + } + + private void ReevaluateLobbyCountdown(LobbyState lobby) + { + if (lobby.ForceLaunched) + { + lobby.CountdownSeconds ??= LobbyState.DefaultCountdownSeconds; + return; + } + + int humanCount = 0; + bool allReady = true; + for (int i = 0; i < lobby.Slots.Length; i++) + { + if (!lobby.Slots[i].IsHuman) continue; + humanCount++; + if (!lobby.Slots[i].IsReady) + { + allReady = false; + } + } + + if (humanCount >= lobby.MinHumansToAutoStart && allReady) + { + if (!lobby.CountdownSeconds.HasValue) + { + lobby.CountdownSeconds = LobbyState.DefaultCountdownSeconds; + _lastBroadcastCountdownSec = -1; + } + } + else + { + lobby.CountdownSeconds = null; + _lastBroadcastCountdownSec = -1; + } + } + + public LobbySnapshotDto? BuildLobbySnapshotDto() + { + if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby) + { + return null; + } + + var dto = new LobbySnapshotDto + { + HostSlotId = lobby.HostSlotId, + MinHumansToAutoStart = lobby.MinHumansToAutoStart, + CountdownSeconds = lobby.CountdownSeconds, + ForceLaunched = lobby.ForceLaunched, + SelectedMap = (byte)lobby.SelectedMap, + SelectedSeed = lobby.SelectedSeed, + SquadSize = lobby.SquadSize, + Slots = new List(lobby.Slots.Length) + }; + for (int i = 0; i < lobby.Slots.Length; i++) + { + var s = lobby.Slots[i]; + dto.Slots.Add(new LobbySlotDto + { + SlotId = s.SlotId, + Callsign = s.Callsign, + IsHuman = s.IsHuman, + IsReady = s.IsReady, + SquadId = s.SquadId + }); + } + return dto; + } + + private void BroadcastLobbySnapshot() + { + var dto = BuildLobbySnapshotDto(); + if (dto is null || _peersByEndpoint.Count == 0) return; + + var msg = new LobbySnapshotMsg + { + MatchGeneration = _matchGeneration, + Snapshot = dto + }; + foreach (var peer in _peersByEndpoint.Values) + { + if (peer.Active) + { + SendSchemaToPeer(peer, msg); + } + } + } + + public void PollStatelessPings() + { + if (_disposed) return; + + for (int i = 0; i < 64; i++) + { + try + { + if (!_socket.Poll(0, SelectMode.SelectRead)) + { + break; + } + + // Note: Use Socket.Receive(..., SocketFlags.Peek) rather than ReceiveFrom(byte[], ..., Peek, ref EndPoint); + // on .NET 8/10 Windows, ReceiveFrom(byte[], ..., Peek, ref EndPoint) consumes the datagram instead of peeking. + int peeked = _socket.Receive(_udpPeekBuf, 0, _udpPeekBuf.Length, SocketFlags.Peek); + if (peeked <= 0) + { + break; + } + + if (!SnapshotCodec.HasPingMagic(_udpPeekBuf.AsSpan(0, peeked))) + { + // Leave CultNet RUDP / other traffic untouched for _server.TryReceiveOnce. + break; + } + + EndPoint consumeRemote = _socket.AddressFamily == AddressFamily.InterNetworkV6 + ? new IPEndPoint(IPAddress.IPv6Any, 0) + : new IPEndPoint(IPAddress.Any, 0); + int received = _socket.ReceiveFrom(_udpPeekBuf, 0, _udpPeekBuf.Length, SocketFlags.None, ref consumeRemote); + if (received > 0 && SnapshotCodec.TryDecodePing(_udpPeekBuf.AsSpan(0, received), out ulong clientNonce)) + { + var summary = new ServerPingSummary( + clientNonce, + ProtocolVersion: 1, + MapKind: _session.State.MapKind, + Phase: _session.State.Phase, + Humans: (byte)Math.Clamp(ConnectedHumanCount, 0, byte.MaxValue), + MaxHumans: (byte)Math.Clamp(_maxHumans, 1, byte.MaxValue), + WaveIndex: (byte)Math.Clamp(_session.State.OrbitalDrop.CurrentWaveIndex, 0, byte.MaxValue), + AcceptingJoin: AcceptingJoin, + HasPassword: false, + Seed: _session.State.Seed, + ServerName: _serverName); + byte[] pong = SnapshotCodec.EncodePong(in summary); + _socket.SendTo(pong, consumeRemote); + } + } + catch (SocketException ex) when ( + ex.SocketErrorCode == SocketError.WouldBlock || + ex.SocketErrorCode == SocketError.TimedOut) + { + break; + } + catch (SocketException ex) when ( + ex.SocketErrorCode == SocketError.ConnectionReset || + ex.SocketErrorCode == SocketError.ConnectionAborted || + ex.SocketErrorCode == SocketError.Shutdown) + { + try + { + EndPoint drainRemote = _socket.AddressFamily == AddressFamily.InterNetworkV6 + ? new IPEndPoint(IPAddress.IPv6Any, 0) + : new IPEndPoint(IPAddress.Any, 0); + _socket.ReceiveFrom(_udpPeekBuf, 0, _udpPeekBuf.Length, SocketFlags.None, ref drainRemote); + } + catch + { + } + break; + } + } + } + + public void StepOnce(long nowUtcMs) + { + ObjectDisposedException.ThrowIf(_disposed, this); + + _stepEvents.Clear(); + PollIncoming(nowUtcMs); + SweepTimeouts(nowUtcMs); + + if (_session.State.Phase == MatchPhase.Lobby && + _session.State.Lobby is { } lobby && + lobby.CountdownSeconds.HasValue) + { + lobby.CountdownSeconds = MathF.Max(0f, lobby.CountdownSeconds.Value - ArenaSession.FixedDt); + if (lobby.CountdownSeconds.Value <= 0f) + { + _lastBroadcastCountdownSec = -1; + _session.StartFromLobby(_matchGeneration); + } + else + { + int wholeSec = (int)MathF.Ceiling(lobby.CountdownSeconds.Value); + if (wholeSec != _lastBroadcastCountdownSec) + { + _lastBroadcastCountdownSec = wholeSec; + BroadcastLobbySnapshot(); + } + } + } + + _session.Step(); + _simTick++; + + _session.DrainStepEvents(_stepEvents); + if (_hostContenderId.HasValue && _stepEvents.Count > 0) + { + _hostPendingEvents.AddRange(_stepEvents); + if (_hostPendingEvents.Count > 4096) + { + _hostPendingEvents.RemoveRange(0, _hostPendingEvents.Count - 4096); + } + } + for (int i = 0; i < _stepEvents.Count; i++) + { + if (_stepEvents[i] is TerrainStampEvent ts) + { + int stampIdx = _terrainStampHistory.Count; + _terrainStampHistory.Add(ts); + _session.State.Terrain.MapWorldToTile(ts.X, ts.Z, out int tx, out int tz); + _tileStampHistory[tx, tz].Add(stampIdx); + } + } + + FlushEventsAndPvsEnter(); + BroadcastSnapshots(); + if (_persistScars && (_simTick - _lastScarSaveTick) >= 1800) + { + FlushScarLedgerIfDirty(); + } + try + { + _server.PollResends(); + } + catch (SocketException) + { + } + + if (_autoRestartSec > 0 && _session.State.Phase == MatchPhase.Completed) + { + _roundCompletedElapsed += ArenaSession.FixedDt; + if (_roundCompletedElapsed >= _autoRestartSec) + { + ResetMatch(_session.State.Seed + 1, _session.State.MapKind, startInLobby: _restartToLobby); + } + } + } + + private void PollIncoming(long nowUtcMs) + { + int processed = 0; + while (processed < 256) + { + PollStatelessPings(); + + CultNetRudpSocketServerFrame? serverFrame; + try + { + if (!_server.TryReceiveOnce(out serverFrame)) + { + break; + } + } + catch (SocketException) + { + break; + } + processed++; + if (serverFrame is null || _retiredTransportPeers.Contains(serverFrame.Peer)) + { + continue; + } + + CultMeshRealtimeFrame rtFrame; + try + { + rtFrame = SnapshotCodec.Unwrap(serverFrame.Frame.Payload); + } + catch + { + continue; + } + + string epKey = serverFrame.Peer.RemoteEndPoint.ToString() ?? string.Empty; + + if (string.Equals(serverFrame.Frame.ChannelId, SnapshotCodec.ChannelSchema, StringComparison.Ordinal)) + { + HandleSchemaFrame(serverFrame.Peer, epKey, rtFrame, nowUtcMs); + } + else if (string.Equals(serverFrame.Frame.ChannelId, SnapshotCodec.ChannelLatest, StringComparison.Ordinal)) + { + HandleLatestFrame(serverFrame.Peer, epKey, rtFrame, nowUtcMs); + } + } + } + + private void HandleSchemaFrame(CultNetRudpSocketServerPeer transportPeer, string epKey, CultMeshRealtimeFrame rtFrame, long nowUtcMs) + { + ISchemaWireMessage msg; + try + { + msg = SnapshotCodec.DeserializeSchemaMessage(rtFrame.Payload); + } + catch + { + return; + } + + switch (msg) + { + case JoinReqMsg join: + HandleJoin(transportPeer, epKey, join, nowUtcMs); + break; + case LeaveMsg: + if (_peersByEndpoint.TryGetValue(epKey, out var leaving) && ReferenceEquals(leaving.TransportPeer, transportPeer)) + { + RetirePeer(leaving, SlotControlReason.HandedToAi); + } + break; + case EquipCargoCmdMsg equip: + if (_peersByEndpoint.TryGetValue(epKey, out var eqPeer) && eqPeer.Active && ReferenceEquals(eqPeer.TransportPeer, transportPeer)) + { + eqPeer.LastHeardUtcMs = nowUtcMs; + _session.TryEquipCargo(eqPeer.AssignedContenderId, equip.CargoIndex, equip.HardpointId); + } + break; + case NewMatchCmdMsg newMatch: + if (_peersByEndpoint.TryGetValue(epKey, out var nmPeer) && nmPeer.Active && ReferenceEquals(nmPeer.TransportPeer, transportPeer)) + { + nmPeer.LastHeardUtcMs = nowUtcMs; + if (_allowClientReset) + { + ResetMatch(newMatch.Seed, (ArenaMapKind)newMatch.MapKind); + } + } + break; + case RepairArenaCmdMsg: + if (_peersByEndpoint.TryGetValue(epKey, out var repPeer) && repPeer.Active && ReferenceEquals(repPeer.TransportPeer, transportPeer)) + { + repPeer.LastHeardUtcMs = nowUtcMs; + if (_allowClientReset || (_hostContenderId.HasValue && _hostContenderId.Value == repPeer.AssignedContenderId)) + { + RepairArenaScars(); + } + } + break; + case InteractCmdMsg interactCmd: + if (_peersByEndpoint.TryGetValue(epKey, out var intPeer) && intPeer.Active && ReferenceEquals(intPeer.TransportPeer, transportPeer)) + { + intPeer.LastHeardUtcMs = nowUtcMs; + if (interactCmd.ReqSeq != 0 && interactCmd.ReqSeq != intPeer.LastInteractSeq) + { + intPeer.LastInteractSeq = interactCmd.ReqSeq; + _session.TriggerHumanInteract(intPeer.AssignedContenderId); + } + } + break; + case LobbyReadyCmdMsg readyCmd: + if (_peersByEndpoint.TryGetValue(epKey, out var readyPeer) && readyPeer.Active && ReferenceEquals(readyPeer.TransportPeer, transportPeer)) + { + readyPeer.LastHeardUtcMs = nowUtcMs; + SetLobbyReady(readyPeer.AssignedContenderId, readyCmd.IsReady); + } + break; + case LobbyConfigCmdMsg cfgCmd: + if (_peersByEndpoint.TryGetValue(epKey, out var cfgPeer) && cfgPeer.Active && ReferenceEquals(cfgPeer.TransportPeer, transportPeer)) + { + cfgPeer.LastHeardUtcMs = nowUtcMs; + byte? reqSquadSize = cfgCmd.SquadSize >= 1 && cfgCmd.SquadSize <= 4 ? cfgCmd.SquadSize : null; + ConfigureLobby(cfgPeer.AssignedContenderId, cfgCmd.Seed, (ArenaMapKind)cfgCmd.MapKind, reqSquadSize); + } + break; + case LobbySquadCmdMsg sqCmd: + if (_peersByEndpoint.TryGetValue(epKey, out var sqPeer) && sqPeer.Active && ReferenceEquals(sqPeer.TransportPeer, transportPeer)) + { + sqPeer.LastHeardUtcMs = nowUtcMs; + MovePeerToSquad(sqPeer.AssignedContenderId, sqCmd.TargetSquadId); + } + break; + case LobbyStartCmdMsg: + if (_peersByEndpoint.TryGetValue(epKey, out var startPeer) && startPeer.Active && ReferenceEquals(startPeer.TransportPeer, transportPeer)) + { + startPeer.LastHeardUtcMs = nowUtcMs; + LaunchFromLobby(startPeer.AssignedContenderId); + } + break; + case ClientKeepaliveMsg: + if (_peersByEndpoint.TryGetValue(epKey, out var keepPeer) && keepPeer.Active && ReferenceEquals(keepPeer.TransportPeer, transportPeer)) + { + keepPeer.LastHeardUtcMs = nowUtcMs; + } + break; + } + } + + private void HandleJoin(CultNetRudpSocketServerPeer transportPeer, string epKey, JoinReqMsg join, long nowUtcMs) + { + if (_peersByEndpoint.TryGetValue(epKey, out var existing)) + { + if (ReferenceEquals(existing.TransportPeer, transportPeer) && existing.Active) + { + existing.LastHeardUtcMs = nowUtcMs; + SendJoinAccepted(existing); + return; + } + RetirePeer(existing, SlotControlReason.HandedToAi); + } + + if (ConnectedHumanCount >= _maxHumans) + { + SendSchemaRaw(transportPeer, new JoinRejectedMsg { Reason = "Server human capacity reached." }); + return; + } + + string callsign = string.IsNullOrWhiteSpace(join.Callsign) ? $"Pilot-{_nextPeerId}" : join.Callsign.Trim(); + if (callsign.Length > 24) callsign = callsign.Substring(0, 24); + + int slotId = -1; + SlotControlReason reason = SlotControlReason.Joined; + + if (join.ReconnectToken != Guid.Empty && _reconnectTokens.TryGetValue(join.ReconnectToken, out var saved)) + { + if (saved.SlotId >= 0 && saved.SlotId < _session.State.Contenders.Count) + { + var cand = _session.State.Contenders[saved.SlotId]; + if (!cand.Alive) + { + SendSchemaRaw(transportPeer, new JoinRejectedMsg { Reason = "Chassis destroyed." }); + return; + } + if (cand.IsHuman || saved.SlotId == _hostContenderId) + { + SendSchemaRaw(transportPeer, new JoinRejectedMsg { Reason = "Slot already occupied." }); + return; + } + slotId = saved.SlotId; + reason = SlotControlReason.Reclaimed; + } + } + + if (slotId < 0) + { + for (int i = 0; i < _session.State.Contenders.Count; i++) + { + if (i == _hostContenderId) continue; + var c = _session.State.Contenders[i]; + if (c.Alive && !c.IsHuman) + { + slotId = i; + break; + } + } + } + + if (slotId < 0) + { + SendSchemaRaw(transportPeer, new JoinRejectedMsg { Reason = "No alive contender slots available." }); + return; + } + + Guid token = join.ReconnectToken != Guid.Empty ? join.ReconnectToken : Guid.NewGuid(); + _reconnectTokens[token] = (slotId, callsign); + _session.SetHumanSlot(slotId, true, callsign); + + var peer = new ConnectedPeer + { + PeerId = _nextPeerId++, + TransportPeer = transportPeer, + EndpointKey = epKey, + ReconnectToken = token, + AssignedContenderId = slotId, + Callsign = callsign, + LastHeardUtcMs = nowUtcMs + }; + InitPeerTrackers(peer); + _peersByEndpoint[epKey] = peer; + + SendJoinAccepted(peer); + if (_session.State.Phase == MatchPhase.Lobby && _session.State.Lobby is { } lobby) + { + if (!lobby.ForceLaunched) + { + lobby.CountdownSeconds = null; + _lastBroadcastCountdownSec = -1; + } + BroadcastLobbySnapshot(); + } + LogMessage?.Invoke($"[tick {_simTick}] Peer #{peer.PeerId} '{callsign}' joined slot {slotId} ({epKey}), humans={ConnectedHumanCount}/{_maxHumans}"); + + _stepEvents.Add(new EntitySlotControlEvent + { + ContenderId = slotId, + IsHuman = true, + Name = callsign, + Reason = (byte)reason + }); + } + + private void HandleLatestFrame(CultNetRudpSocketServerPeer transportPeer, string epKey, CultMeshRealtimeFrame rtFrame, long nowUtcMs) + { + if (!_peersByEndpoint.TryGetValue(epKey, out var peer) || !peer.Active || !ReferenceEquals(peer.TransportPeer, transportPeer)) + { + return; + } + + peer.LastHeardUtcMs = nowUtcMs; + ClientInputPacket pkt; + try + { + if (!SnapshotCodec.TryDecodeClientInput(rtFrame.Payload.Span, out pkt)) + { + return; + } + } + catch + { + return; + } + + if (pkt.MatchGeneration != _matchGeneration || pkt.InputSeq <= peer.LastAcceptedInputSeq) + { + return; + } + + peer.LastAcceptedInputSeq = pkt.InputSeq; + peer.LastEchoSendMs = pkt.ClientSendMs; + bool triggerInteract = pkt.Input.InteractPickup; + if (pkt.InteractSeq != 0) + { + if (pkt.InteractSeq != peer.LastInteractSeq) + { + peer.LastInteractSeq = pkt.InteractSeq; + triggerInteract = true; + } + else + { + triggerInteract = false; + } + } + _session.SetHumanInput(peer.AssignedContenderId, pkt.Input with { InteractPickup = triggerInteract }); + } + + private void SweepTimeouts(long nowUtcMs) + { + List? timedOut = null; + foreach (var peer in _peersByEndpoint.Values) + { + if (peer.Active && (nowUtcMs - peer.LastHeardUtcMs) > IdleTimeoutMs) + { + timedOut ??= new List(); + timedOut.Add(peer); + } + } + if (timedOut is null) return; + for (int i = 0; i < timedOut.Count; i++) + { + RetirePeer(timedOut[i], SlotControlReason.HandedToAi); + } + } + + private void OnTransportPeerDisconnected(CultNetRudpSocketServerPeer transportPeer) + { + string epKey = transportPeer.RemoteEndPoint.ToString() ?? string.Empty; + if (_peersByEndpoint.TryGetValue(epKey, out var peer) && ReferenceEquals(peer.TransportPeer, transportPeer)) + { + RetirePeer(peer, SlotControlReason.HandedToAi); + } + } + + private void RetirePeer(ConnectedPeer peer, SlotControlReason reason) + { + if (!peer.Active) return; + if (!_retiredTransportPeers.Contains(peer.TransportPeer)) + { + SendSchemaRaw(peer.TransportPeer, new LeaveMsg + { + Reason = reason == SlotControlReason.HandedToAi ? "Connection timed out" : "Disconnected" + }); + } + peer.Active = false; + _peersByEndpoint.Remove(peer.EndpointKey); + _retiredTransportPeers.Add(peer.TransportPeer); + + int slot = peer.AssignedContenderId; + if (slot >= 0 && slot < _session.State.Contenders.Count) + { + _session.SetHumanSlot(slot, false); + var c = _session.State.Contenders[slot]; + _stepEvents.Add(new EntitySlotControlEvent + { + ContenderId = slot, + IsHuman = false, + Name = c.Name, + Reason = (byte)reason + }); + } + if (_session.State.Phase == MatchPhase.Lobby && _session.State.Lobby is { } lobby) + { + ReevaluateLobbyCountdown(lobby); + BroadcastLobbySnapshot(); + } + LogMessage?.Invoke($"[tick {_simTick}] Peer #{peer.PeerId} '{peer.Callsign}' disconnected from slot {slot} ({reason}), humans={ConnectedHumanCount}/{_maxHumans}"); + } + + private void InitPeerTrackers(ConnectedPeer peer) + { + for (int i = 0; i < _session.State.Contenders.Count; i++) + { + var c = _session.State.Contenders[i]; + bool inPvs = c.Id == peer.AssignedContenderId || _session.IsEntityInPeerPvs(peer.AssignedContenderId, true, c.Id); + peer.ContenderTrackers[i] = new EntityPvsTracker + { + InPvs = inPvs, + SnapNext = false, + AckedLoadoutVersion = inPvs ? c.LoadoutVersion : -1, + AckedDamageVersion = inPvs ? c.DamageVersion : -1, + LastLifecycle = c.Lifecycle + }; + } + for (int i = 0; i < _session.State.Spectators.Spectators.Count; i++) + { + var s = _session.State.Spectators.Spectators[i]; + bool inPvs = _session.IsEntityInPeerPvs(peer.AssignedContenderId, false, s.Id); + peer.SpectatorTrackers[i] = new EntityPvsTracker + { + InPvs = inPvs, + SnapNext = false, + AckedLoadoutVersion = inPvs ? 1 : -1, + AckedDamageVersion = inPvs ? s.Grid.HitSequence : -1 + }; + } + peer.SentDropIds.Clear(); + for (int i = 0; i < _session.State.GroundDrops.Count; i++) + { + var d = _session.State.GroundDrops[i]; + if (!d.PickedUp && _session.IsPointInPeerPvs(peer.AssignedContenderId, d.X, _session.State.Terrain.SampleHeight(d.X, d.Z) + 0.5f, d.Z)) + { + peer.SentDropIds.Add(d.Id); + } + } + peer.SentPodIds.Clear(); + peer.SentOrdnanceIds.Clear(); + peer.SentTerrainStampIndices.Clear(); + Array.Clear(peer.SentTileVersions); + for (int i = 0; i < _terrainStampHistory.Count; i++) + { + peer.SentTerrainStampIndices.Add(i); + } + var terrain = _session.State.Terrain; + for (int tz = 0; tz < terrain.TileGridCount; tz++) + { + for (int tx = 0; tx < terrain.TileGridCount; tx++) + { + peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz]; + } + } + var activePods = _session.State.OrbitalDrop.ActivePods; + for (int i = 0; i < activePods.Count; i++) + { + var pod = activePods[i]; + if (IsPodVisibleToPeer(peer.AssignedContenderId, pod)) + { + peer.SentPodIds.Add(pod.PodId); + } + } + } + + private bool IsPodVisibleToPeer(int obsId, OrbitalPod pod) + { + if (pod.PodKind == OrbitalPodKind.Contender) + { + return pod.ContenderId == obsId || + _session.State.AreAllies(obsId, pod.ContenderId) || + _session.IsEntityInPeerPvs(obsId, true, pod.ContenderId); + } + return _session.IsPointInPeerPvs(obsId, pod.X, pod.Y + 2.0f, pod.Z); + } + + private void FlushEventsAndPvsEnter() + { + if (_peersByEndpoint.Count == 0) return; + + foreach (var peer in _peersByEndpoint.Values) + { + if (!peer.Active) continue; + int obsId = peer.AssignedContenderId; + + // Track PVS transitions & lifecycle snaps + uint enteredPvsMask = 0; + for (int i = 0; i < _session.State.Contenders.Count; i++) + { + var c = _session.State.Contenders[i]; + bool inPvs = c.Id == obsId || _session.IsEntityInPeerPvs(obsId, true, c.Id); + ref var tracker = ref peer.ContenderTrackers[i]; + if (c.Lifecycle != tracker.LastLifecycle) + { + tracker.SnapNext = true; + tracker.LastLifecycle = c.Lifecycle; + } + if (inPvs && !tracker.InPvs) + { + tracker.SnapNext = true; + if (c.Lifecycle == ContenderLifecycle.Deploying && i < 32) + { + enteredPvsMask |= (1u << i); + } + } + tracker.InPvs = inPvs; + } + + for (int i = 0; i < _session.State.Spectators.Spectators.Count; i++) + { + var s = _session.State.Spectators.Spectators[i]; + bool inPvs = _session.IsEntityInPeerPvs(obsId, false, s.Id); + ref var tracker = ref peer.SpectatorTrackers[i]; + if (inPvs && !tracker.InPvs) + { + tracker.SnapNext = true; + if (tracker.AckedLoadoutVersion != 1 || tracker.AckedDamageVersion != s.Grid.HitSequence) + { + tracker.AckedLoadoutVersion = 1; + tracker.AckedDamageVersion = s.Grid.HitSequence; + SendSchemaToPeer(peer, new EntitySyncSnapshotMsg + { + IsContender = false, + EntityId = s.Id, + Alive = s.Alive, + PosX = s.X, PosY = s.Y, PosZ = s.Z, Yaw = s.Yaw, + CoreHp = s.Grid.CoreHp, + MaxCoreHp = s.Grid.MaxCoreHp, + ArmorBytes = s.Grid.QuantizeArmorBytes() + }); + } + } + tracker.InPvs = inPvs; + } + + var filtered = new List(_stepEvents.Count); + for (int i = 0; i < _session.State.GroundDrops.Count; i++) + { + var d = _session.State.GroundDrops[i]; + if (d.PickedUp || peer.SentDropIds.Contains(d.Id)) continue; + if (_session.IsPointInPeerPvs(obsId, d.X, _session.State.Terrain.SampleHeight(d.X, d.Z) + 0.5f, d.Z)) + { + peer.SentDropIds.Add(d.Id); + filtered.Add(new DropSpawnedEvent + { + DropId = d.Id, + X = d.X, + Z = d.Z, + ChassisId = d.Chassis?.Id, + ModuleId = d.Module?.Id + }); + } + } + + for (int e = 0; e < _stepEvents.Count; e++) + { + var ev = _stepEvents[e]; + switch (ev) + { + case ContenderLoadoutEvent loadout: + if (loadout.ContenderId == obsId || _session.IsEntityInPeerPvs(obsId, true, loadout.ContenderId)) + { + var c = _session.State.Contenders[loadout.ContenderId]; + peer.ContenderTrackers[loadout.ContenderId].AckedLoadoutVersion = c.LoadoutVersion; + peer.ContenderTrackers[loadout.ContenderId].AckedDamageVersion = c.DamageVersion; + filtered.Add(loadout.ContenderId == obsId + ? loadout + : ArenaSession.BuildContenderLoadoutEvent(c, includeCargo: false)); + } + break; + case ShotFiredEvent shot: + { + bool shooterVisible = shot.IsSpectatorShooter + ? _session.IsEntityInPeerPvs(obsId, false, shot.ShooterId) + : (shot.ShooterId == obsId || _session.IsEntityInPeerPvs(obsId, true, shot.ShooterId)); + if (shooterVisible) + { + filtered.Add(shot); + } + break; + } + case HitImpactEvent hit: + { + bool shooterInPvs = (hit.IsContenderShooter && hit.ShooterId == obsId) || + (hit.ShooterId >= 0 && _session.IsEntityInPeerPvs(obsId, hit.IsContenderShooter, hit.ShooterId)); + bool deliver = false; + if (hit.TargetKind == (byte)HitTargetKind.Contender && hit.TargetId >= 0 && hit.TargetId < peer.ContenderTrackers.Length) + { + bool targetInPvs = hit.TargetId == obsId || _session.IsEntityInPeerPvs(obsId, true, hit.TargetId); + if (targetInPvs) + { + peer.ContenderTrackers[hit.TargetId].AckedDamageVersion = _session.State.Contenders[hit.TargetId].DamageVersion; + deliver = true; + } + else if (shooterInPvs && _session.IsPointInPeerPvs(obsId, hit.HitX, hit.HitY + 0.35f, hit.HitZ)) + { + deliver = true; + } + } + else if (hit.TargetKind == (byte)HitTargetKind.Spectator) + { + int specIdx = hit.TargetId >= 1000 ? hit.TargetId - 1000 : hit.TargetId; + bool targetInPvs = specIdx >= 0 && specIdx < peer.SpectatorTrackers.Length && + _session.IsEntityInPeerPvs(obsId, false, specIdx); + if (targetInPvs) + { + peer.SpectatorTrackers[specIdx].AckedDamageVersion = _session.State.Spectators.Spectators[specIdx].Grid.HitSequence; + deliver = true; + } + else if (shooterInPvs && _session.IsPointInPeerPvs(obsId, hit.HitX, hit.HitY + 0.35f, hit.HitZ)) + { + deliver = true; + } + } + else + { + deliver = shooterInPvs || _session.IsPointInPeerPvs(obsId, hit.HitX, hit.HitY + 0.35f, hit.HitZ); + } + + if (deliver) + { + filtered.Add(shooterInPvs ? hit : ScrubHitShooter(hit)); + } + break; + } + case DropSpawnedEvent ds: + if (_session.IsPointInPeerPvs(obsId, ds.X, _session.State.Terrain.SampleHeight(ds.X, ds.Z) + 0.5f, ds.Z)) + { + if (peer.SentDropIds.Add(ds.DropId)) + { + filtered.Add(ds); + } + } + break; + case DropPickedUpEvent dp: + bool pickerInPvs = dp.ContenderId == obsId || + _session.IsEntityInPeerPvs(obsId, true, dp.ContenderId); + if (pickerInPvs || peer.SentDropIds.Contains(dp.DropId)) + { + peer.SentDropIds.Remove(dp.DropId); + filtered.Add(pickerInPvs + ? dp + : new DropPickedUpEvent { DropId = dp.DropId, ContenderId = -1 }); + } + break; + case TerrainStampEvent: + // Delivered via 576m local geometry bubble sync below so distant live fire is never leaked + // while _predWorld stays 1:1 physics-synchronized before the player enters tile range. + break; + case OverheatAlertEvent oh: + if (oh.ContenderId == obsId) + { + filtered.Add(oh); + } + break; + case DropPodEvent dpe: + { + var kind = (DropPodEventKind)dpe.Kind; + bool inPvs = kind == DropPodEventKind.WaveAnnounced || + (dpe.ContenderId == obsId) || + (dpe.PodKind == (byte)OrbitalPodKind.Contender && dpe.ContenderId >= 0 && + _session.IsEntityInPeerPvs(obsId, true, dpe.ContenderId)) || + _session.IsPointInPeerPvs(obsId, dpe.X, dpe.Y + 2.0f, dpe.Z); + + if (kind == DropPodEventKind.PodLaunched) + { + if (inPvs) + { + peer.SentPodIds.Add(dpe.PodId); + filtered.Add(dpe); + } + } + else if (kind == DropPodEventKind.PodTouchdownBlowPetals || kind == DropPodEventKind.PodCancelled) + { + bool wasSent = peer.SentPodIds.Remove(dpe.PodId); + if (inPvs && kind == DropPodEventKind.PodTouchdownBlowPetals) + { + filtered.Add(dpe); + } + else if (wasSent) + { + filtered.Add(new DropPodEvent + { + EventId = dpe.EventId, + Kind = (byte)DropPodEventKind.PodCancelled, + WaveIndex = dpe.WaveIndex, + PodId = dpe.PodId, + PodKind = dpe.PodKind, + ContenderId = dpe.ContenderId == obsId ? obsId : -1, + X = 0f, + Y = 0f, + Z = 0f, + VelX = 0f, + VelY = 0f, + VelZ = 0f, + NormalX = 0f, + NormalY = 1f, + NormalZ = 0f, + DropId = 0, + RespawnsClosed = dpe.RespawnsClosed + }); + } + } + else if (inPvs) + { + filtered.Add(dpe); + } + break; + } + case OrdnanceNodeEvent ord: + { + bool shooterInPvs = ord.IsSpectatorShooter + ? (ord.ShooterId >= 0 && _session.IsEntityInPeerPvs(obsId, false, ord.ShooterId)) + : (ord.ShooterId == obsId || (ord.ShooterId >= 0 && _session.IsEntityInPeerPvs(obsId, true, ord.ShooterId))); + bool pointInPvs = _session.IsPointInPeerPvs(obsId, ord.PosX, ord.PosY + 0.35f, ord.PosZ); + byte kind = ord.Kind; + bool isTerminal = kind is 3 or 4 or 5; // Detonated, Intercepted, Expired + if (isTerminal) + { + bool wasSent = peer.SentOrdnanceIds.Remove(ord.OrdnanceId); + if (pointInPvs) + { + filtered.Add(ord); + } + else if (wasSent) + { + filtered.Add(new OrdnanceNodeEvent + { + OrdnanceId = ord.OrdnanceId, + ParentOrdnanceId = ord.ParentOrdnanceId, + Kind = (byte)OrdnanceEventKind.Expired, + IsSpectatorShooter = ord.IsSpectatorShooter, + ShooterId = shooterInPvs ? ord.ShooterId : -1, + WeaponKey = ord.WeaponKey, + NodeDefIndex = ord.NodeDefIndex, + PosX = 0f, + PosY = 0f, + PosZ = 0f, + VelX = 0f, + VelY = 0f, + VelZ = 0f, + TargetEntityId = -1, + TargetIsSpectator = false, + SimTime = ord.SimTime, + VisualShape = ord.VisualShape, + ColorRgba = ord.ColorRgba + }); + } + } + else if (shooterInPvs || pointInPvs) + { + peer.SentOrdnanceIds.Add(ord.OrdnanceId); + filtered.Add(ord); + } + break; + } + default: + filtered.Add(ev); + break; + } + } + + SyncPeerLocalGeometryBubble(peer, obsId, filtered); + + if (enteredPvsMask != 0) + { + var activePods = _session.State.OrbitalDrop.ActivePods; + for (int i = 0; i < _session.State.Contenders.Count && i < 32; i++) + { + if ((enteredPvsMask & (1u << i)) == 0) continue; + var c = _session.State.Contenders[i]; + if (c.Lifecycle != ContenderLifecycle.Deploying) continue; + for (int p = 0; p < activePods.Count; p++) + { + var pod = activePods[p]; + if (pod.PodKind == OrbitalPodKind.Contender && + pod.ContenderId == c.Id && + peer.SentPodIds.Add(pod.PodId)) + { + filtered.Add(new DropPodEvent + { + EventId = _session.State.OrbitalDrop.AllocatePodEventId(), + Kind = (byte)(pod.Phase == OrbitalPodPhase.RetroBurn + ? DropPodEventKind.PodRetroBurnStart + : DropPodEventKind.PodLaunched), + WaveIndex = pod.WaveIndex, + PodId = pod.PodId, + PodKind = (byte)pod.PodKind, + ContenderId = pod.ContenderId, + X = pod.X, + Y = pod.Y, + Z = pod.Z, + VelX = pod.VelX, + VelY = pod.VelY, + VelZ = pod.VelZ, + NormalX = 0f, + NormalY = 1f, + NormalZ = 0f, + ChassisId = pod.Chassis?.Id, + ModuleId = pod.Module?.Id, + DropId = pod.GroundDropId, + RespawnsClosed = _session.State.OrbitalDrop.RespawnCutoffReached + }); + break; + } + } + } + } + + // Sync any PVS-visible contender (including local player!) whose loadout/damage version still differs + for (int i = 0; i < _session.State.Contenders.Count; i++) + { + ref var tracker = ref peer.ContenderTrackers[i]; + if (!tracker.InPvs) continue; + var c = _session.State.Contenders[i]; + if (tracker.AckedLoadoutVersion != c.LoadoutVersion || tracker.AckedDamageVersion != c.DamageVersion) + { + tracker.AckedLoadoutVersion = c.LoadoutVersion; + tracker.AckedDamageVersion = c.DamageVersion; + SendSchemaToPeer(peer, new EntitySyncSnapshotMsg + { + IsContender = true, + EntityId = c.Id, + Alive = c.Alive, + PosX = c.X, PosY = c.Y, PosZ = c.Z, Yaw = c.Yaw, + CoreHp = c.Grid.CoreHp, + MaxCoreHp = c.Grid.MaxCoreHp, + ArmorBytes = c.Grid.QuantizeArmorBytes(), + ContenderLoadout = ArenaSession.BuildContenderLoadoutEvent(c, includeCargo: c.Id == obsId) + }); + } + } + + if (filtered.Count > 0) + { + SendSchemaToPeer(peer, new SimEventBatchMsg + { + BatchSeq = _eventBatchSeq++, + SimTick = _simTick, + SimTime = _session.State.Time, + MatchGeneration = _matchGeneration, + Events = filtered + }); + } + } + } + + private static HitImpactEvent ScrubHitShooter(HitImpactEvent hit) => new() + { + EventId = hit.EventId, + HitX = hit.HitX, + HitY = hit.HitY, + HitZ = hit.HitZ, + NormalX = hit.NormalX, + NormalY = hit.NormalY, + NormalZ = hit.NormalZ, + SourceX = hit.HitX, + SourceY = hit.HitY, + SourceZ = hit.HitZ, + TargetKind = hit.TargetKind, + TargetId = hit.TargetId, + CellX = hit.CellX, + CellY = hit.CellY, + WeaponClass = hit.WeaponClass, + WeaponId = hit.WeaponId, + IsAirburst = hit.IsAirburst, + Ttl = hit.Ttl, + NewCellArmor = hit.NewCellArmor, + NewCellTemp = hit.NewCellTemp, + NewCoreHp = hit.NewCoreHp, + HitSequence = hit.HitSequence, + ShooterId = -1, + IsContenderShooter = false, + ArmorDamage = hit.ArmorDamage, + CoreDamage = hit.CoreDamage, + Killed = hit.Killed + }; + + private void BroadcastSnapshots() + { + if (_peersByEndpoint.Count == 0) return; + + bool sendCore = (_simTick % 2) == 0; // 30 Hz + bool sendRadar = (_simTick % 6) == 0; // 10 Hz + if (!sendCore && !sendRadar) return; + + if (sendCore) _snapshotSeq++; + + foreach (var peer in _peersByEndpoint.Values) + { + if (!peer.Active) continue; + int obsId = peer.AssignedContenderId; + var local = _session.State.Contenders[obsId]; + + if (sendCore) + { + SendCoreAndOrbit(peer, local); + } + + if (sendRadar) + { + SendRadar(peer, obsId); + } + } + } + + private void SendCoreAndOrbit(ConnectedPeer peer, ContenderState local) + { + int obsId = local.Id; + ushort pvsMask = 0; + var pvsContenders = new List(MatchState.ContenderCount); + var walkerCandidates = new List<(float DistSq, NetWalkerEntry Entry)>(12); + var combatSpecs = new List(12); + var neutralSpecsHalf = new List(28); + + for (int i = 0; i < _session.State.Contenders.Count; i++) + { + var c = _session.State.Contenders[i]; + if (c.Id == obsId) + { + pvsMask |= (ushort)(1 << c.Id); + continue; + } + + if (!_session.IsEntityInPeerPvs(obsId, true, c.Id)) + { + continue; + } + + pvsMask |= (ushort)(1 << c.Id); + bool snap = peer.ContenderTrackers[c.Id].SnapNext; + peer.ContenderTrackers[c.Id].SnapNext = false; + + float pitchDeg = MatchRules.ComputeLocalPitchDeg( + new Vector3(c.AimX - c.X, (float.IsNaN(c.AimY) ? c.Y : c.AimY) - c.Y, c.AimZ - c.Z), + new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW)); + + bool isRetroBurn = false; + if (c.IsInDropPod && c.ActivePodId is { } podId) + { + var pods = _session.State.OrbitalDrop.ActivePods; + for (int p = 0; p < pods.Count; p++) + { + if (pods[p].PodId == podId) + { + isRetroBurn = pods[p].Phase == OrbitalPodPhase.RetroBurn; + break; + } + } + } + + pvsContenders.Add(new NetContenderState + { + SlotId = (byte)c.Id, + Alive = c.Alive, + IsHuman = c.IsHuman, + Fire = c.FireCmd, + Brake = c.BrakeCmd, + Snap = snap, + Lifecycle = c.Lifecycle, + PodRetroBurn = isRetroBurn, + Pos = new Vector3(c.X, c.Y, c.Z), + Rot = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW), + Vel = new Vector3(c.VelX, c.VelY, c.VelZ), + AimYaw = MathF.Atan2(c.AimX - c.X, c.AimZ - c.Z), + AimPitchDeg = pitchDeg, + Throttle = c.ThrottleCmd, + Steer = c.SteerCmd, + CoreHpRatio = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 0f, + MaxThermalRatio = c.MaxThermalRatio + }); + + float d2 = (c.X - local.X) * (c.X - local.X) + (c.Z - local.Z) * (c.Z - local.Z); + if (c.IsGroundedActive && c.Grid.Spec.IsWalker && d2 <= 220f * 220f && + _session.TrySampleInterpolatedWalkerPose(true, c.Id, 1f, out var ws)) + { + walkerCandidates.Add((d2, new NetWalkerEntry { IsContender = true, EntityId = (byte)c.Id, Snapshot = ws })); + } + } + + byte halfIndex = (byte)(_snapshotSeq & 1); + var specs = _session.State.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!_session.IsEntityInPeerPvs(obsId, false, i)) + { + continue; + } + + bool snap = peer.SpectatorTrackers[i].SnapNext; + peer.SpectatorTrackers[i].SnapNext = false; + + var ns = new NetSpectatorState + { + Id = (byte)i, + Alive = s.Alive, + Stance = s.Stance, + Snap = snap, + TargetContenderId = (sbyte)(s.TargetContenderId ?? -1), + Pos = new Vector3(s.X, s.Y, s.Z), + Rot = new Quaternion(s.CurrRotX, s.CurrRotY, s.CurrRotZ, s.CurrRotW), + Vel = new Vector3(s.VelX, s.VelY, s.VelZ) + }; + + if (s.Stance != SpectatorStance.Neutral) + { + combatSpecs.Add(ns); + float d2 = (s.X - local.X) * (s.X - local.X) + (s.Z - local.Z) * (s.Z - local.Z); + if (s.Alive && s.Grid.Spec.IsWalker && d2 <= 220f * 220f && + _session.TrySampleInterpolatedWalkerPose(false, s.Id, 1f, out var sws)) + { + walkerCandidates.Add((d2, new NetWalkerEntry { IsContender = false, EntityId = (byte)i, Snapshot = sws })); + } + } + else if ((i & 1) == halfIndex) + { + neutralSpecsHalf.Add(ns); + } + } + + walkerCandidates.Sort((a, b) => a.DistSq.CompareTo(b.DistSq)); + var walkers = new List(walkerCandidates.Count); + for (int i = 0; i < walkerCandidates.Count; i++) + { + walkers.Add(walkerCandidates[i].Entry); + } + + Vector3 localAngVel = Vector3.Zero; + var body = _session.GetContenderBody(local.Id); + if (body is { } bHandle) + { + var v = _session.World.View; + localAngVel = new Vector3(v.AngularVelocityX[bHandle.Lane], v.AngularVelocityY[bHandle.Lane], v.AngularVelocityZ[bHandle.Lane]); + } + + byte detectedBy = _session.State.ObserverStates.TryGetValue(obsId, out var obsState) + ? (byte)Math.Clamp(obsState.DetectedByCount, 0, 255) + : (byte)0; + + OrbitalPodPhase localPodPhase = OrbitalPodPhase.Freefall; + if (local.IsInDropPod && local.ActivePodId is { } localPodId) + { + var pods = _session.State.OrbitalDrop.ActivePods; + for (int p = 0; p < pods.Count; p++) + { + if (pods[p].PodId == localPodId) + { + localPodPhase = pods[p].Phase; + break; + } + } + } + + var wave = _session.State.OrbitalDrop.WaveState; + ushort nextWaveAtTick = wave.NextWaveAtSec.HasValue + ? (ushort)Math.Clamp((int)MathF.Round(wave.NextWaveAtSec.Value / ArenaSession.FixedDt), 0, ushort.MaxValue - 1) + : ushort.MaxValue; + + byte[] corePayload = SnapshotCodec.EncodeCorePvs( + _matchGeneration, + _snapshotSeq, + _simTick, + _session.State.Time, + peer.LastAcceptedInputSeq, + peer.LastEchoSendMs, + _session.State.Spectators.SafeRadius, + _session.State.Phase, + _session.State.WinnerContenderId, + detectedBy, + pvsMask, + local, + localAngVel, + pvsContenders, + walkers, + combatSpecs, + out int combatSpecsWritten, + (byte)wave.CurrentWaveIndex, + nextWaveAtTick, + wave.RespawnCutoffReached, + localPodPhase); + + SendLatestToPeer(peer, corePayload); + + if (combatSpecsWritten < combatSpecs.Count || neutralSpecsHalf.Count > 0) + { + var packet2Specs = new List((combatSpecs.Count - combatSpecsWritten) + neutralSpecsHalf.Count); + for (int i = combatSpecsWritten; i < combatSpecs.Count; i++) + { + packet2Specs.Add(combatSpecs[i]); + } + packet2Specs.AddRange(neutralSpecsHalf); + byte[] orbitPayload = SnapshotCodec.EncodeSpectatorOrbitHalf( + _matchGeneration, + _snapshotSeq, + halfIndex, + packet2Specs); + SendLatestToPeer(peer, orbitPayload); + } + } + + private void SendRadar(ConnectedPeer peer, int obsId) + { + if (!_session.State.ObserverStates.TryGetValue(obsId, out var obsState)) + { + return; + } + + var cList = new List(12); + foreach (var kv in obsState.ContenderContacts) + { + if (!MatchState.IsContactOnRadar(kv.Value)) continue; + cList.Add(new NetRadarContact + { + EntityId = (byte)kv.Key, + Visible = kv.Value.VisibleToPlayer, + FaintHorizon = kv.Value.FaintHorizonPing, + HasEverBeenSeen = kv.Value.HasEverBeenSeen, + LastSeenAge = kv.Value.LastSeenAge, + LastSeenX = kv.Value.LastSeenX, + LastSeenZ = kv.Value.LastSeenZ + }); + } + + var sList = new List(32); + foreach (var kv in obsState.SpectatorContacts) + { + if (!MatchState.IsContactOnRadar(kv.Value)) continue; + int specIdx = kv.Key >= 1000 ? kv.Key - 1000 : kv.Key; + if (specIdx < 0 || specIdx >= _session.State.Spectators.Spectators.Count) continue; + sList.Add(new NetRadarContact + { + EntityId = (byte)specIdx, + Visible = kv.Value.VisibleToPlayer, + FaintHorizon = kv.Value.FaintHorizonPing, + HasEverBeenSeen = kv.Value.HasEverBeenSeen, + LastSeenAge = kv.Value.LastSeenAge, + LastSeenX = kv.Value.LastSeenX, + LastSeenZ = kv.Value.LastSeenZ + }); + } + + byte[] payload = SnapshotCodec.EncodeRadarContacts(_matchGeneration, _snapshotSeq, cList, sList); + SendLatestToPeer(peer, payload); + } + + private void SendJoinAccepted(ConnectedPeer peer) + { + var msg = new JoinAcceptedMsg + { + PeerId = peer.PeerId, + ReconnectToken = peer.ReconnectToken, + AssignedContenderId = peer.AssignedContenderId, + MatchGeneration = _matchGeneration, + InitialState = BuildInitialMatchStateDto(peer.AssignedContenderId) + }; + SendSchemaToPeer(peer, msg); + } + + private InitialMatchStateDto BuildInitialMatchStateDto(int forContenderId) + { + var squadIds = new byte[_session.State.Contenders.Count]; + for (int i = 0; i < squadIds.Length; i++) + { + squadIds[i] = _session.State.Contenders[i].SquadId; + } + + var dto = new InitialMatchStateDto + { + MatchGeneration = _matchGeneration, + Seed = _session.State.Seed, + MapKind = (byte)_session.State.MapKind, + SquadSize = _session.State.SquadSize, + ContenderSquadIds = squadIds, + SimTime = _session.State.Time, + SafeRadius = _session.State.Spectators.SafeRadius, + Phase = (byte)(_session.State.Phase == MatchPhase.Completed ? 1 : _session.State.Phase == MatchPhase.Lobby ? 2 : 0), + WinnerContenderId = _session.State.WinnerContenderId, + ConnectedHumans = ConnectedHumanCount, + CurrentWaveIndex = _session.State.OrbitalDrop.CurrentWaveIndex, + RespawnCutoffReached = _session.State.OrbitalDrop.RespawnCutoffReached, + Lobby = BuildLobbySnapshotDto() + }; + + var activePods = _session.State.OrbitalDrop.ActivePods; + for (int i = 0; i < activePods.Count; i++) + { + var pod = activePods[i]; + if (!IsPodVisibleToPeer(forContenderId, pod)) + { + continue; + } + dto.ActivePods.Add(new OrbitalPodDto + { + PodId = pod.PodId, + PodKind = (byte)pod.PodKind, + Phase = (byte)pod.Phase, + WaveIndex = pod.WaveIndex, + ContenderId = pod.ContenderId, + X = pod.X, + Y = pod.Y, + Z = pod.Z, + VelX = pod.VelX, + VelY = pod.VelY, + VelZ = pod.VelZ, + Yaw = pod.Yaw, + ChassisId = pod.Chassis?.Id, + ModuleId = pod.Module?.Id + }); + } + + var scarSnap = _session.State.ScarLedger.ToSnapshot(); + if (scarSnap.Terrain.Count > 0 || scarSnap.Buildings.Count > 0 || scarSnap.Trees.Count > 0) + { + dto.PersistentScars = ArenaScarLedger.CompressSnapshot(scarSnap); + } + + for (int i = 0; i < _session.State.Contenders.Count; i++) + { + var c = _session.State.Contenders[i]; + if (c.Id != forContenderId && + !_session.State.AreAllies(forContenderId, c.Id) && + !_session.IsEntityInPeerPvs(forContenderId, true, c.Id)) + { + continue; + } + dto.Contenders.Add(new ContenderInitialDto + { + Id = c.Id, + Name = c.Name, + IsHuman = c.IsHuman, + X = c.X, Y = c.Y, Z = c.Z, Yaw = c.Yaw, + Kills = c.Kills, + Loadout = ArenaSession.BuildContenderLoadoutEvent(c, includeCargo: c.Id == forContenderId), + LifecycleByte = (byte)c.Lifecycle, + RespawnsRemaining = (byte)Math.Clamp(c.RespawnsRemaining, 0, 255), + SquadId = c.SquadId + }); + } + + for (int i = 0; i < _session.State.Spectators.Spectators.Count; i++) + { + var s = _session.State.Spectators.Spectators[i]; + if (!_session.IsEntityInPeerPvs(forContenderId, false, s.Id)) + { + continue; + } + var mounted = new List(s.Grid.Mounted.Count); + for (int m = 0; m < s.Grid.Mounted.Count; m++) + { + mounted.Add(new MountedSlotDto { ModuleId = s.Grid.Mounted[m].Spec.Id, HardpointId = s.Grid.Mounted[m].HardpointId }); + } + dto.Spectators.Add(new SpectatorInitialDto + { + Id = s.Id, + Tier = (byte)s.Tier, + Stance = (byte)s.Stance, + X = s.X, Y = s.Y, Z = s.Z, Yaw = s.Yaw, + ChassisId = s.Grid.Spec.Id, + CoreHp = s.Grid.CoreHp, + MaxCoreHp = s.Grid.MaxCoreHp, + ArmorBytes = s.Grid.QuantizeArmorBytes(), + Mounted = mounted + }); + } + + for (int i = 0; i < _session.State.GroundDrops.Count; i++) + { + var d = _session.State.GroundDrops[i]; + if (d.PickedUp || !_session.IsPointInPeerPvs(forContenderId, d.X, _session.State.Terrain.SampleHeight(d.X, d.Z) + 0.5f, d.Z)) + { + continue; + } + dto.GroundDrops.Add(new GroundDropDto + { + Id = d.Id, + X = d.X, + Z = d.Z, + ChassisId = d.Chassis?.Id, + ModuleId = d.Module?.Id, + PickedUp = d.PickedUp + }); + } + + return dto; + } + + private void SendSchemaToPeer(ConnectedPeer peer, ISchemaWireMessage msg) + { + if (!peer.Active || _retiredTransportPeers.Contains(peer.TransportPeer)) return; + SendSchemaRaw(peer.TransportPeer, msg); + } + + private void SendSchemaRaw(CultNetRudpSocketServerPeer transportPeer, ISchemaWireMessage msg) + { + byte[] payload = SnapshotCodec.SerializeSchemaMessage(msg); + byte[] wire = SnapshotCodec.WrapSchema(payload, _matchGeneration, _schemaOutSeq++); + try + { + _server.SendSchema(transportPeer, wire); + } + catch + { + // Transport peer will be swept by timeout/disconnect + } + } + + private void SendLatestToPeer(ConnectedPeer peer, byte[] payload) + { + if (!peer.Active || _retiredTransportPeers.Contains(peer.TransportPeer)) return; + byte[] wire = SnapshotCodec.WrapLatest(payload, _matchGeneration, _latestOutSeq++); + try + { + _server.Send(peer.TransportPeer, SnapshotCodec.ChannelLatest, wire); + } + catch + { + } + } + + public void RepairArenaScars() + { + _session.RepairArenaScars(); + _inMemoryScarsByMap.Remove(_session.State.MapKind); + _terrainStampHistory.Clear(); + ClearTileStampHistory(); + FlushScarLedgerIfDirty(); + + uint rev = _session.State.ScarLedger.LedgerRevision; + var repairEv = new ArenaRepairEvent { LedgerRevision = rev }; + if (_hostContenderId.HasValue) + { + _hostPendingEvents.Add(repairEv); + } + + foreach (var peer in _peersByEndpoint.Values) + { + if (!peer.Active) continue; + peer.SentTerrainStampIndices.Clear(); + Array.Clear(peer.SentTileVersions); + SendSchemaToPeer(peer, new SimEventBatchMsg + { + BatchSeq = _eventBatchSeq++, + SimTick = _simTick, + SimTime = _session.State.Time, + MatchGeneration = _matchGeneration, + Events = new List { repairEv } + }); + } + } + + private void SyncPeerLocalGeometryBubble(ConnectedPeer peer, int obsId, List filtered) + { + if (_terrainStampHistory.Count == 0 || obsId < 0 || obsId >= _session.State.Contenders.Count) + { + return; + } + var obs = _session.State.Contenders[obsId]; + var terrain = _session.State.Terrain; + terrain.MapWorldToTile(obs.X, obs.Z, out int cx, out int cz); + int grid = terrain.TileGridCount; + int minTx = Math.Max(0, cx - 4); + int maxTx = Math.Min(grid - 1, cx + 4); + int minTz = Math.Max(0, cz - 4); + int maxTz = Math.Min(grid - 1, cz + 4); + const float bubbleRadiusSq = 576f * 576f; + + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + var list = _tileStampHistory[tx, tz]; + if (list.Count == 0) + { + peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz]; + continue; + } + + bool allSent = true; + for (int i = 0; i < list.Count; i++) + { + int stampIdx = list[i]; + if (peer.SentTerrainStampIndices.Contains(stampIdx)) + { + continue; + } + var ts = _terrainStampHistory[stampIdx]; + float dx = obs.X - ts.X; + float dz = obs.Z - ts.Z; + if (dx * dx + dz * dz <= bubbleRadiusSq) + { + peer.SentTerrainStampIndices.Add(stampIdx); + filtered.Add(ts); + } + else + { + allSent = false; + } + } + + if (allSent) + { + peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz]; + } + } + } + } + + private void ClearTileStampHistory() + { + for (int tz = 0; tz < 16; tz++) + { + for (int tx = 0; tx < 16; tx++) + { + _tileStampHistory[tx, tz].Clear(); + } + } + } + + public static string ResolveScarFilePath(string? configuredPath, ArenaMapKind initialMapKind, ArenaMapKind targetMapKind) + { + if (string.IsNullOrWhiteSpace(configuredPath)) + { + return ArenaScarLedgerStore.GetDefaultPath(targetMapKind); + } + + string mapTag = targetMapKind == ArenaMapKind.Sion ? "sion" : "desert"; + if (configuredPath.EndsWith(Path.DirectorySeparatorChar) || + configuredPath.EndsWith(Path.AltDirectorySeparatorChar) || + Directory.Exists(configuredPath)) + { + return Path.Combine(configuredPath, $"{mapTag}_scars_default.cultcache"); + } + + if (targetMapKind == initialMapKind) + { + return configuredPath; + } + + string dir = Path.GetDirectoryName(configuredPath) ?? "."; + string fileName = Path.GetFileName(configuredPath); + string initTag = initialMapKind == ArenaMapKind.Sion ? "sion" : "desert"; + if (fileName.StartsWith(initTag + "_", StringComparison.OrdinalIgnoreCase)) + { + return Path.Combine(dir, mapTag + fileName.Substring(initTag.Length)); + } + + string stem = Path.GetFileNameWithoutExtension(fileName); + string ext = Path.GetExtension(fileName); + return Path.Combine(dir, $"{stem}.{mapTag}{ext}"); + } + + private static string GetAssetFingerprint(int seed, ArenaMapKind mapKind) => + mapKind == ArenaMapKind.Sion ? SionMapLoader.Load().AssetFingerprint : $"desert:{seed}"; + + private void FlushScarLedgerIfDirty() + { + if (!_persistScars) + { + return; + } + string scarPath = ResolveScarFilePath(_configuredScarPath, _initialMapKind, _session.State.MapKind); + if (string.IsNullOrWhiteSpace(scarPath)) + { + return; + } + if (!_session.State.ScarLedger.IsDirty && File.Exists(scarPath)) + { + return; + } + ArenaScarLedgerStore.Save(scarPath, _session.State.ScarLedger.ToSnapshot()); + _session.State.ScarLedger.IsDirty = false; + _lastScarSaveTick = _simTick; + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + FlushScarLedgerIfDirty(); + _server.PeerDisconnected -= OnTransportPeerDisconnected; + _server.Dispose(); + _socket.Dispose(); + _session.Dispose(); + } + } +} diff --git a/src/RustToDust.Net/ServerPingProbe.cs b/src/RustToDust.Net/ServerPingProbe.cs new file mode 100644 index 0000000..a2234dc --- /dev/null +++ b/src/RustToDust.Net/ServerPingProbe.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Threading; +using System.Threading.Tasks; + +namespace RustToDust.Net +{ + public sealed record ServerPingResult( + string Host, + int Port, + IPEndPoint? ResolvedEndPoint, + bool Success, + int RttMs, + ServerPingSummary? Summary); + + public static class ServerPingProbe + { + public static async Task ProbeAsync( + string host, + int port, + TimeSpan timeout, + CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(host) || port < 1 || port > 65535) + { + return new ServerPingResult(host ?? string.Empty, port, null, false, -1, null); + } + + IPAddress? resolvedIp = null; + if (IPAddress.TryParse(host.Trim(), out var parsed)) + { + resolvedIp = parsed; + } + else + { + try + { + var addrs = await Dns.GetHostAddressesAsync(host.Trim(), ct).ConfigureAwait(false); + for (int i = 0; i < addrs.Length; i++) + { + if (addrs[i].AddressFamily == AddressFamily.InterNetwork) + { + resolvedIp = addrs[i]; + break; + } + } + if (resolvedIp is null && addrs.Length > 0) + { + resolvedIp = addrs[0]; + } + } + catch + { + return new ServerPingResult(host, port, null, false, -1, null); + } + } + + if (resolvedIp is null) + { + return new ServerPingResult(host, port, null, false, -1, null); + } + + var ep = new IPEndPoint(resolvedIp, port); + var res = await ProbeAsync(ep, timeout, ct).ConfigureAwait(false); + return res with { Host = host }; + } + + public static async Task ProbeAsync( + IPEndPoint target, + TimeSpan timeout, + CancellationToken ct = default) + { + using var socket = new Socket(target.AddressFamily, SocketType.Dgram, ProtocolType.Udp); + socket.Bind(new IPEndPoint( + target.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any, + 0)); + + ulong nonce = BitConverter.ToUInt64(RandomNumberGenerator.GetBytes(8), 0); + byte[] ping = SnapshotCodec.EncodePing(nonce); + byte[] recvBuf = new byte[512]; + + using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeoutCts.CancelAfter(timeout); + + try + { + long startTs = Stopwatch.GetTimestamp(); + await socket.SendToAsync(ping, SocketFlags.None, target, timeoutCts.Token).ConfigureAwait(false); + + EndPoint anyRemote = target.AddressFamily == AddressFamily.InterNetworkV6 + ? new IPEndPoint(IPAddress.IPv6Any, 0) + : new IPEndPoint(IPAddress.Any, 0); + + while (!timeoutCts.IsCancellationRequested) + { + var res = await socket.ReceiveFromAsync(recvBuf, SocketFlags.None, anyRemote, timeoutCts.Token).ConfigureAwait(false); + if (SnapshotCodec.TryDecodePong(recvBuf.AsSpan(0, res.ReceivedBytes), out var summary) && + summary.ClientNonce == nonce) + { + int rttMs = Math.Max(1, (int)Math.Round(Stopwatch.GetElapsedTime(startTs).TotalMilliseconds)); + return new ServerPingResult(target.Address.ToString(), target.Port, target, true, rttMs, summary); + } + } + } + catch (OperationCanceledException) + { + } + catch (SocketException) + { + } + + return new ServerPingResult(target.Address.ToString(), target.Port, target, false, -1, null); + } + + public static async Task ProbeManyAsync( + IReadOnlyList<(string Host, int Port)> targets, + TimeSpan timeout, + int maxConcurrency = 16, + CancellationToken ct = default) + { + var results = new ServerPingResult[targets.Count]; + using var gate = new SemaphoreSlim(Math.Max(1, maxConcurrency)); + var tasks = new Task[targets.Count]; + + for (int i = 0; i < targets.Count; i++) + { + int idx = i; + var target = targets[i]; + tasks[i] = Task.Run(async () => + { + await gate.WaitAsync(ct).ConfigureAwait(false); + try + { + results[idx] = await ProbeAsync(target.Host, target.Port, timeout, ct).ConfigureAwait(false); + } + finally + { + gate.Release(); + } + }, ct); + } + + await Task.WhenAll(tasks).ConfigureAwait(false); + return results; + } + } +} diff --git a/src/RustToDust.Net/SnapshotCodec.cs b/src/RustToDust.Net/SnapshotCodec.cs new file mode 100644 index 0000000..0f6a904 --- /dev/null +++ b/src/RustToDust.Net/SnapshotCodec.cs @@ -0,0 +1,1126 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Numerics; +using System.Text; +using GameCult.Mesh; +using MessagePack; +using RustToDust.Core; + +namespace RustToDust.Net +{ + public enum LatestPacketKind : byte + { + CorePvs = 1, + SpectatorOrbitHalf = 2, + RadarContacts = 3, + ClientInput = 16 + } + + public readonly record struct ClientInputPacket( + uint MatchGeneration, + uint InputSeq, + uint ClientSendMs, + PlayerInput Input, + ushort InteractSeq = 0); + + public struct NetContenderState + { + public byte SlotId; + public bool Alive; + public bool IsHuman; + public bool Fire; + public bool Brake; + public bool Snap; + public ContenderLifecycle Lifecycle; + public bool PodRetroBurn; + public Vector3 Pos; + public Quaternion Rot; + public Vector3 Vel; + public float AimYaw; + public float AimPitchDeg; + public float Throttle; + public float Steer; + public float CoreHpRatio; + public float MaxThermalRatio; + } + + public struct NetSpectatorState + { + public byte Id; + public bool Alive; + public SpectatorStance Stance; + public bool Snap; + public sbyte TargetContenderId; + public Vector3 Pos; + public Quaternion Rot; + public Vector3 Vel; + } + + public struct NetWalkerEntry + { + public bool IsContender; + public byte EntityId; + public WalkerVisualSnapshot Snapshot; + } + + public struct NetRadarContact + { + public byte EntityId; + public bool Visible; + public bool FaintHorizon; + public bool HasEverBeenSeen; + public float LastSeenAge; + public float LastSeenX; + public float LastSeenZ; + } + + public sealed class DecodedCorePvsSnapshot + { + public uint MatchGeneration; + public uint SnapshotSeq; + public uint SimTick; + public float SimTime; + public uint AckedInputSeq; + public uint EchoSendMs; + public float SafeRadius; + public MatchPhase Phase; + public int? WinnerContenderId; + public byte DetectedByCount; + public int InArcWeapons; + public int OutOfArcWeapons; + public int DisabledWeapons; + public bool AllWeaponsOutOfArc; + public ushort ContenderPvsMask; + public byte CurrentWaveIndex; + public ushort NextWaveAtTick; + public bool RespawnCutoffReached; + + public bool LocalAlive; + public ContenderLifecycle LocalLifecycle; + public OrbitalPodPhase LocalPodPhase; + public Vector3 LocalPos; + public Quaternion LocalRot; + public Vector3 LocalVel; + public Vector3 LocalAngVel; + public float LocalCoreHp; + public float LocalMaxThermalRatio; + public float LocalTargetHoverAltAgl; + public byte[] LocalCellTempsQuantized = Array.Empty(); + public float[] LocalMountedTemps = Array.Empty(); + public float[] LocalMountedCooldowns = Array.Empty(); + + public List Contenders = new(); + public List Walkers = new(); + public List CombatSpectators = new(); + } + + public sealed class DecodedSpectatorOrbitSnapshot + { + public uint MatchGeneration; + public uint SnapshotSeq; + public byte HalfIndex; + public List Spectators = new(); + } + + public sealed class DecodedRadarContactsSnapshot + { + public uint MatchGeneration; + public uint SnapshotSeq; + public List Contenders = new(); + public List Spectators = new(); + } + + public readonly record struct ServerPingSummary( + ulong ClientNonce, + ushort ProtocolVersion, + ArenaMapKind MapKind, + MatchPhase Phase, + byte Humans, + byte MaxHumans, + byte WaveIndex, + bool AcceptingJoin, + bool HasPassword, + int Seed, + string ServerName); + + public static class SnapshotCodec + { + public const int MaxLatestDatagramBytes = 1152; + public const int PingPacketBytes = 32; + public const byte PingWireVersion = 1; + public const byte PingKindRequest = 1; + public const byte PingKindResponse = 2; + public const string ChannelLatest = "latest"; + public const string ChannelSchema = "schema"; + public const string SchemaLatestId = "rtd.snap"; + public const string SchemaInputId = "rtd.in"; + public const string SchemaEventsId = "rtd.evt"; + public const string BodyMatchId = "m"; + + // CultNetRudpPacketCodec fixed header (36) + "latest" (6) = 42 bytes + public const int CultNetRudpLatestOverheadBytes = 42; + // CultMeshRealtimeWireProtocol fixed header (37) + "latest" (6) + "rtd.snap" (8) + "m" (1) = 52 bytes + public const int CultMeshLatestOverheadBytes = 52; + public const int MaxLatestFrameBytes = MaxLatestDatagramBytes - CultNetRudpLatestOverheadBytes; // 1110 bytes + public const int MaxLatestPayloadBytes = MaxLatestFrameBytes - CultMeshLatestOverheadBytes; // 1058 bytes + + public static byte[] WrapLatest(ReadOnlySpan payload, long producerEpoch, long sequence, string schemaId = SchemaLatestId) + { + var frame = new CultMeshRealtimeFrame + { + ChannelId = ChannelLatest, + SchemaId = schemaId, + BodyId = BodyMatchId, + ProducerEpoch = producerEpoch, + Sequence = sequence, + Delivery = CultMeshRealtimeDelivery.LatestOnly, + Payload = payload.ToArray() + }; + byte[] encoded = CultMeshRealtimeWireProtocol.EncodeFrame(frame); + if (encoded.Length > MaxLatestFrameBytes) + { + throw new InvalidOperationException( + $"Latest frame exceeded {MaxLatestFrameBytes}B cap ({encoded.Length}B; UDP wire cap {MaxLatestDatagramBytes}B)."); + } + return encoded; + } + + public static byte[] WrapSchema(ReadOnlySpan payload, long producerEpoch, long sequence, string schemaId = SchemaEventsId) + { + var frame = new CultMeshRealtimeFrame + { + ChannelId = ChannelSchema, + SchemaId = schemaId, + BodyId = BodyMatchId, + ProducerEpoch = producerEpoch, + Sequence = sequence, + Delivery = CultMeshRealtimeDelivery.ReliableOrdered, + Payload = payload.ToArray() + }; + return CultMeshRealtimeWireProtocol.EncodeFrame(frame); + } + + public static CultMeshRealtimeFrame Unwrap(byte[] wireBytes) => + CultMeshRealtimeWireProtocol.DecodeFrame(wireBytes); + + public static byte[] SerializeSchemaMessage(ISchemaWireMessage msg) => + MessagePackSerializer.Serialize(msg); + + public static ISchemaWireMessage DeserializeSchemaMessage(ReadOnlyMemory payload) => + MessagePackSerializer.Deserialize(payload); + + public static byte[] EncodeClientInput(in ClientInputPacket pkt) + { + byte[] buf = new byte[36]; + var span = buf.AsSpan(); + span[0] = (byte)LatestPacketKind.ClientInput; + BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(1), pkt.MatchGeneration); + BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(5), pkt.InputSeq); + BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(9), pkt.ClientSendMs); + BinaryPrimitives.WriteSingleLittleEndian(span.Slice(13), pkt.Input.AimWorldX); + BinaryPrimitives.WriteSingleLittleEndian(span.Slice(17), pkt.Input.AimWorldY); + BinaryPrimitives.WriteSingleLittleEndian(span.Slice(21), pkt.Input.AimWorldZ); + BinaryPrimitives.WriteInt16LittleEndian(span.Slice(25), EncodeSnorm16(pkt.Input.Throttle)); + BinaryPrimitives.WriteInt16LittleEndian(span.Slice(27), EncodeSnorm16(pkt.Input.Steer)); + BinaryPrimitives.WriteInt16LittleEndian(span.Slice(29), EncodeSnorm16(pkt.Input.VerticalThrottle)); + byte flags = 0; + if (pkt.Input.Fire) flags |= 1; + if (pkt.Input.Brake) flags |= 2; + if (pkt.Input.InteractPickup) flags |= 4; + span[31] = flags; + BinaryPrimitives.WriteUInt16LittleEndian(span.Slice(32), pkt.InteractSeq); + return buf; // 36 B + } + + public static bool TryDecodeClientInput(ReadOnlySpan span, out ClientInputPacket pkt) + { + if (span.Length < 32 || span[0] != (byte)LatestPacketKind.ClientInput) + { + pkt = default; + return false; + } + uint gen = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(1)); + uint seq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(5)); + uint sendMs = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(9)); + float ax = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(13)); + float ay = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(17)); + float az = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(21)); + float throttle = DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(25))); + float steer = DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(27))); + float vert = DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(29))); + byte flags = span[31]; + ushort interactSeq = span.Length >= 34 + ? BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(32)) + : (ushort)0; + pkt = new ClientInputPacket( + gen, + seq, + sendMs, + new PlayerInput( + throttle, + steer, + ax, + az, + (flags & 1) != 0, + (flags & 4) != 0, + (flags & 2) != 0, + ay, + vert), + interactSeq); + return true; + } + + public static ClientInputPacket DecodeClientInput(ReadOnlySpan span) + { + if (!TryDecodeClientInput(span, out var pkt)) + { + throw new InvalidOperationException("Invalid ClientInput packet."); + } + return pkt; + } + + public static byte[] EncodeCorePvs( + uint matchGeneration, + uint snapshotSeq, + uint simTick, + float simTime, + uint ackedInputSeq, + uint echoSendMs, + float safeRadius, + MatchPhase phase, + int? winnerContenderId, + byte detectedByCount, + ushort contenderPvsMask, + ContenderState localContender, + Vector3 localAngVel, + IReadOnlyList pvsContenders, + IReadOnlyList pvsWalkers, + IReadOnlyList combatSpectators) => + EncodeCorePvs( + matchGeneration, + snapshotSeq, + simTick, + simTime, + ackedInputSeq, + echoSendMs, + safeRadius, + phase, + winnerContenderId, + detectedByCount, + contenderPvsMask, + localContender, + localAngVel, + pvsContenders, + pvsWalkers, + combatSpectators, + out _); + + public static byte[] EncodeCorePvs( + uint matchGeneration, + uint snapshotSeq, + uint simTick, + float simTime, + uint ackedInputSeq, + uint echoSendMs, + float safeRadius, + MatchPhase phase, + int? winnerContenderId, + byte detectedByCount, + ushort contenderPvsMask, + ContenderState localContender, + Vector3 localAngVel, + IReadOnlyList pvsContenders, + IReadOnlyList pvsWalkers, + IReadOnlyList combatSpectators, + out int combatSpecsWritten, + byte currentWaveIndex = 0, + ushort nextWaveAtTick = ushort.MaxValue, + bool respawnCutoffReached = false, + OrbitalPodPhase localPodPhase = OrbitalPodPhase.Freefall) + { + Span buf = stackalloc byte[MaxLatestPayloadBytes]; + int offset = 0; + + buf[offset++] = (byte)LatestPacketKind.CorePvs; + BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), matchGeneration); offset += 4; + BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), snapshotSeq); offset += 4; + BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), simTick); offset += 4; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), simTime); offset += 4; + BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), ackedInputSeq); offset += 4; + BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), echoSendMs); offset += 4; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), safeRadius); offset += 4; + + byte phaseByte = phase switch + { + MatchPhase.Completed => 1, + MatchPhase.Lobby => 2, + _ => 0 + }; + if (winnerContenderId.HasValue) phaseByte |= 0x04; + buf[offset++] = phaseByte; + buf[offset++] = (byte)(sbyte)(winnerContenderId ?? -1); + buf[offset++] = detectedByCount; + + ushort arc = (ushort)( + (Math.Clamp(localContender.InArcWeaponCount, 0, 15)) | + (Math.Clamp(localContender.OutOfArcWeaponCount, 0, 15) << 4) | + (Math.Clamp(localContender.DisabledWeaponCount, 0, 15) << 8) | + (localContender.AllWeaponsOutOfArc ? (1 << 12) : 0)); + BinaryPrimitives.WriteUInt16LittleEndian(buf.Slice(offset), arc); offset += 2; + BinaryPrimitives.WriteUInt16LittleEndian(buf.Slice(offset), contenderPvsMask); offset += 2; + buf[offset++] = (byte)((currentWaveIndex & 0x07) | (respawnCutoffReached ? 0x80 : 0)); + BinaryPrimitives.WriteUInt16LittleEndian(buf.Slice(offset), nextWaveAtTick); offset += 2; + + // Local prediction + telemetry block + byte localFlags = (byte)( + (localContender.Alive ? 1 : 0) | + (((byte)localContender.Lifecycle & 0x03) << 1) | + (((byte)localPodPhase & 0x03) << 3)); + buf[offset++] = localFlags; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.X); offset += 4; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.Y); offset += 4; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.Z); offset += 4; + WriteQuatSnorm16(buf.Slice(offset), new Quaternion(localContender.CurrRotX, localContender.CurrRotY, localContender.CurrRotZ, localContender.CurrRotW)); + offset += 8; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.VelX); offset += 4; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.VelY); offset += 4; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.VelZ); offset += 4; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localAngVel.X); offset += 4; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localAngVel.Y); offset += 4; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localAngVel.Z); offset += 4; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.Grid.CoreHp); offset += 4; + buf[offset++] = EncodeRatioByte(localContender.MaxThermalRatio, maxVal: 1.5f); + ushort qHoverAlt = (ushort)Math.Clamp((int)MathF.Round(MathF.Max(0f, localContender.TargetHoverAltAgl) * 100f), 0, ushort.MaxValue); + BinaryPrimitives.WriteUInt16LittleEndian(buf.Slice(offset), qHoverAlt); offset += 2; + + int cellCountPos = offset++; + int cellCount = 0; + var grid = localContender.Grid; + for (int y = 0; y < grid.Spec.Height && cellCount < 64; y++) + { + for (int x = 0; x < grid.Spec.Width && cellCount < 64; x++) + { + if (!grid.Spec.IsActive(x, y)) continue; + int qTemp = (int)MathF.Round((grid.Temperature[x, y] - ChassisGrid.AmbientTemp) * 0.5f); + buf[offset++] = (byte)Math.Clamp(qTemp, 0, 255); + cellCount++; + } + } + buf[cellCountPos] = (byte)cellCount; + + int mountedCount = Math.Min(8, grid.Mounted.Count); + buf[offset++] = (byte)mountedCount; + for (int i = 0; i < mountedCount; i++) + { + var m = grid.Mounted[i]; + int qTemp = (int)MathF.Round((m.CurrentTemp - ChassisGrid.AmbientTemp) * 0.5f); + buf[offset++] = (byte)Math.Clamp(qTemp, 0, 255); + int qCd = (int)MathF.Round(m.Cooldown * 25f); + buf[offset++] = (byte)Math.Clamp(qCd, 0, 255); + } + + // PVS Contenders (each 35 B) + int contenderCountPos = offset++; + int contendersWritten = 0; + for (int i = 0; i < pvsContenders.Count; i++) + { + if (offset + 35 > MaxLatestPayloadBytes - 2) + { + break; + } + var c = pvsContenders[i]; + buf[offset++] = c.SlotId; + byte flags = 0; + if (c.Alive) flags |= 1; + if (c.IsHuman) flags |= 2; + if (c.Fire) flags |= 4; + if (c.Brake) flags |= 8; + if (c.Snap) flags |= 16; + flags |= (byte)(((byte)c.Lifecycle & 0x03) << 5); + if (c.PodRetroBurn) flags |= 128; + buf[offset++] = flags; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), c.Pos.X); offset += 4; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), c.Pos.Y); offset += 4; + BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), c.Pos.Z); offset += 4; + WriteQuatSnorm16(buf.Slice(offset), c.Rot); offset += 8; + WriteVelShort(buf.Slice(offset), c.Vel); offset += 6; + BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeAngleShort(c.AimYaw)); offset += 2; + buf[offset++] = (byte)(sbyte)Math.Clamp(MathF.Round(c.AimPitchDeg), -90, 90); + buf[offset++] = EncodeSnorm8(c.Throttle); + buf[offset++] = EncodeSnorm8(c.Steer); + buf[offset++] = EncodeRatioByte(c.CoreHpRatio, 1.0f); + buf[offset++] = EncodeRatioByte(c.MaxThermalRatio, 1.5f); + contendersWritten++; + } + buf[contenderCountPos] = (byte)contendersWritten; + + // Walkers (capped strictly by remaining MTU budget!) + int walkerCountPos = offset++; + int walkersWritten = 0; + for (int i = 0; i < pvsWalkers.Count; i++) + { + var w = pvsWalkers[i]; + int legCount = Math.Clamp(w.Snapshot.LegCount, 0, 4); + int bytesNeeded = 2 + legCount * 13; + if (offset + bytesNeeded > MaxLatestPayloadBytes - 1) + { + break; + } + buf[offset++] = (byte)((w.IsContender ? 0x80 : 0x00) | (w.EntityId & 0x7F)); + buf[offset++] = (byte)legCount; + for (int l = 0; l < legCount; l++) + { + var ang = w.Snapshot.LegAngles[l]; + BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.HipPitch)); offset += 2; + BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.HipRoll)); offset += 2; + BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.KneeFlex)); offset += 2; + BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.HockFlex)); offset += 2; + BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.AnklePitch)); offset += 2; + WriteOctNormal(buf.Slice(offset), w.Snapshot.FootNormal[l]); offset += 2; + buf[offset++] = (byte)Math.Clamp((int)MathF.Round(w.Snapshot.LoadG[l] * 50f), 0, 255); + } + walkersWritten++; + } + buf[walkerCountPos] = (byte)walkersWritten; + + // Active Combat Spectators (26 B each, capped strictly by remaining MTU budget!) + int combatSpecCountPos = offset++; + int specsWritten = 0; + for (int i = 0; i < combatSpectators.Count; i++) + { + if (offset + 26 > MaxLatestPayloadBytes) + { + break; + } + WriteCompactSpectator(buf.Slice(offset), combatSpectators[i]); + offset += 26; + specsWritten++; + } + buf[combatSpecCountPos] = (byte)specsWritten; + combatSpecsWritten = specsWritten; + + return buf.Slice(0, offset).ToArray(); + } + + public static bool TryDecodeCorePvs(ReadOnlySpan span, out DecodedCorePvsSnapshot res) + { + res = null!; + if (span.Length < 92 || span[0] != (byte)LatestPacketKind.CorePvs) + { + return false; + } + int offset = 1; + var decoded = new DecodedCorePvsSnapshot + { + MatchGeneration = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)), + }; + offset += 4; + decoded.SnapshotSeq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4; + decoded.SimTick = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4; + decoded.SimTime = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)); offset += 4; + decoded.AckedInputSeq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4; + decoded.EchoSendMs = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4; + decoded.SafeRadius = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)); offset += 4; + + byte phaseByte = span[offset++]; + decoded.Phase = (phaseByte & 0x03) switch + { + 1 => MatchPhase.Completed, + 2 => MatchPhase.Lobby, + _ => MatchPhase.Active + }; + sbyte winnerRaw = (sbyte)span[offset++]; + decoded.WinnerContenderId = (phaseByte & 0x04) != 0 ? winnerRaw : null; + decoded.DetectedByCount = span[offset++]; + + ushort arc = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(offset)); offset += 2; + decoded.InArcWeapons = arc & 0xF; + decoded.OutOfArcWeapons = (arc >> 4) & 0xF; + decoded.DisabledWeapons = (arc >> 8) & 0xF; + decoded.AllWeaponsOutOfArc = (arc & (1 << 12)) != 0; + decoded.ContenderPvsMask = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(offset)); offset += 2; + byte waveByte = span[offset++]; + decoded.CurrentWaveIndex = (byte)(waveByte & 0x07); + decoded.RespawnCutoffReached = (waveByte & 0x80) != 0; + decoded.NextWaveAtTick = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(offset)); offset += 2; + + byte localFlags = span[offset++]; + decoded.LocalAlive = (localFlags & 1) != 0; + decoded.LocalLifecycle = (ContenderLifecycle)((localFlags >> 1) & 0x03); + decoded.LocalPodPhase = (OrbitalPodPhase)((localFlags >> 3) & 0x03); + decoded.LocalPos = new Vector3( + BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)), + BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 4)), + BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 8))); + offset += 12; + decoded.LocalRot = ReadQuatSnorm16(span.Slice(offset)); offset += 8; + decoded.LocalVel = new Vector3( + BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)), + BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 4)), + BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 8))); + offset += 12; + decoded.LocalAngVel = new Vector3( + BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)), + BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 4)), + BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 8))); + offset += 12; + decoded.LocalCoreHp = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)); offset += 4; + decoded.LocalMaxThermalRatio = span[offset++] / 255f * 1.5f; + decoded.LocalTargetHoverAltAgl = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(offset)) / 100f; offset += 2; + + if (offset >= span.Length) return false; + int cellCount = span[offset++]; + if (cellCount > 64 || offset + cellCount >= span.Length) return false; + decoded.LocalCellTempsQuantized = span.Slice(offset, cellCount).ToArray(); + offset += cellCount; + + int mountedCount = span[offset++]; + if (mountedCount > 16 || offset + mountedCount * 2 >= span.Length) return false; + decoded.LocalMountedTemps = new float[mountedCount]; + decoded.LocalMountedCooldowns = new float[mountedCount]; + for (int i = 0; i < mountedCount; i++) + { + decoded.LocalMountedTemps[i] = ChassisGrid.AmbientTemp + span[offset++] * 2.0f; + decoded.LocalMountedCooldowns[i] = span[offset++] / 25f; + } + + int contenderCount = span[offset++]; + if (contenderCount > MatchState.ContenderCount || offset + contenderCount * 35 >= span.Length) return false; + for (int i = 0; i < contenderCount; i++) + { + byte slotId = span[offset++]; + byte flags = span[offset++]; + Vector3 pos = new( + BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)), + BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 4)), + BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 8))); + offset += 12; + Quaternion rot = ReadQuatSnorm16(span.Slice(offset)); offset += 8; + Vector3 vel = ReadVelShort(span.Slice(offset)); offset += 6; + float aimYaw = DecodeAngleShort(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset))); offset += 2; + float aimPitch = (sbyte)span[offset++]; + float throttle = DecodeSnorm8(span[offset++]); + float steer = DecodeSnorm8(span[offset++]); + float coreRatio = span[offset++] / 255f; + float thermalRatio = span[offset++] / 255f * 1.5f; + + decoded.Contenders.Add(new NetContenderState + { + SlotId = slotId, + Alive = (flags & 1) != 0, + IsHuman = (flags & 2) != 0, + Fire = (flags & 4) != 0, + Brake = (flags & 8) != 0, + Snap = (flags & 16) != 0, + Lifecycle = (ContenderLifecycle)((flags >> 5) & 0x03), + PodRetroBurn = (flags & 128) != 0, + Pos = pos, + Rot = rot, + Vel = vel, + AimYaw = aimYaw, + AimPitchDeg = aimPitch, + Throttle = throttle, + Steer = steer, + CoreHpRatio = coreRatio, + MaxThermalRatio = thermalRatio + }); + } + + int walkerCount = span[offset++]; + for (int i = 0; i < walkerCount; i++) + { + if (offset + 2 > span.Length) return false; + byte tag = span[offset++]; + bool isContender = (tag & 0x80) != 0; + byte entityId = (byte)(tag & 0x7F); + int legCount = span[offset++]; + if (legCount > 4 || offset + legCount * 13 > span.Length) return false; + var snap = new WalkerVisualSnapshot { LegCount = legCount }; + for (int l = 0; l < legCount; l++) + { + snap.LegAngles[l] = new WalkerLegAngles + { + HipPitch = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset))), + HipRoll = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset + 2))), + KneeFlex = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset + 4))), + HockFlex = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset + 6))), + AnklePitch = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset + 8))) + }; + offset += 10; + snap.FootNormal[l] = ReadOctNormal(span.Slice(offset)); offset += 2; + snap.LoadG[l] = span[offset++] / 50f; + } + decoded.Walkers.Add(new NetWalkerEntry + { + IsContender = isContender, + EntityId = entityId, + Snapshot = snap + }); + } + + if (offset >= span.Length) return false; + int specCount = span[offset++]; + if (offset + specCount * 26 > span.Length) return false; + for (int i = 0; i < specCount; i++) + { + decoded.CombatSpectators.Add(ReadCompactSpectator(span.Slice(offset))); + offset += 26; + } + + res = decoded; + return true; + } + + public static DecodedCorePvsSnapshot DecodeCorePvs(ReadOnlySpan span) + { + if (!TryDecodeCorePvs(span, out var res)) + { + throw new InvalidOperationException("Invalid CorePvs snapshot packet."); + } + return res; + } + + public static byte[] EncodeSpectatorOrbitHalf( + uint matchGeneration, + uint snapshotSeq, + byte halfIndex, + IReadOnlyList spectators) + { + Span buf = stackalloc byte[MaxLatestPayloadBytes]; + int offset = 0; + buf[offset++] = (byte)LatestPacketKind.SpectatorOrbitHalf; + BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), matchGeneration); offset += 4; + BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), snapshotSeq); offset += 4; + buf[offset++] = halfIndex; + int countPos = offset++; + int count = 0; + for (int i = 0; i < spectators.Count; i++) + { + if (offset + 26 > MaxLatestPayloadBytes) + { + break; + } + WriteCompactSpectator(buf.Slice(offset), spectators[i]); + offset += 26; + count++; + } + buf[countPos] = (byte)count; + return buf.Slice(0, offset).ToArray(); + } + + public static bool TryDecodeSpectatorOrbitHalf(ReadOnlySpan span, out DecodedSpectatorOrbitSnapshot res) + { + res = null!; + if (span.Length < 11 || span[0] != (byte)LatestPacketKind.SpectatorOrbitHalf) + { + return false; + } + int offset = 1; + var decoded = new DecodedSpectatorOrbitSnapshot + { + MatchGeneration = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)), + }; + offset += 4; + decoded.SnapshotSeq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4; + decoded.HalfIndex = span[offset++]; + int count = span[offset++]; + if (offset + count * 26 > span.Length) + { + return false; + } + for (int i = 0; i < count; i++) + { + decoded.Spectators.Add(ReadCompactSpectator(span.Slice(offset))); + offset += 26; + } + res = decoded; + return true; + } + + public static DecodedSpectatorOrbitSnapshot DecodeSpectatorOrbitHalf(ReadOnlySpan span) + { + if (!TryDecodeSpectatorOrbitHalf(span, out var res)) + { + throw new InvalidOperationException("Invalid SpectatorOrbitHalf packet."); + } + return res; + } + + public static byte[] EncodeRadarContacts( + uint matchGeneration, + uint snapshotSeq, + IReadOnlyList contenders, + IReadOnlyList spectators) + { + Span buf = stackalloc byte[MaxLatestPayloadBytes]; + int offset = 0; + buf[offset++] = (byte)LatestPacketKind.RadarContacts; + BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), matchGeneration); offset += 4; + BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), snapshotSeq); offset += 4; + + int cPos = offset++; + int cWritten = 0; + for (int i = 0; i < contenders.Count; i++) + { + if (offset + 11 > MaxLatestPayloadBytes - 1) break; + WriteRadarContact(buf.Slice(offset), contenders[i]); + offset += 11; + cWritten++; + } + buf[cPos] = (byte)cWritten; + + int sPos = offset++; + int sWritten = 0; + for (int i = 0; i < spectators.Count; i++) + { + if (offset + 11 > MaxLatestPayloadBytes) break; + WriteRadarContact(buf.Slice(offset), spectators[i]); + offset += 11; + sWritten++; + } + buf[sPos] = (byte)sWritten; + return buf.Slice(0, offset).ToArray(); + } + + public static bool TryDecodeRadarContacts(ReadOnlySpan span, out DecodedRadarContactsSnapshot res) + { + res = null!; + if (span.Length < 11 || span[0] != (byte)LatestPacketKind.RadarContacts) + { + return false; + } + int offset = 1; + var decoded = new DecodedRadarContactsSnapshot + { + MatchGeneration = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)), + }; + offset += 4; + decoded.SnapshotSeq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4; + int cCount = span[offset++]; + if (offset + cCount * 11 >= span.Length) + { + return false; + } + for (int i = 0; i < cCount; i++) + { + decoded.Contenders.Add(ReadRadarContact(span.Slice(offset))); + offset += 11; + } + int sCount = span[offset++]; + if (offset + sCount * 11 > span.Length) + { + return false; + } + for (int i = 0; i < sCount; i++) + { + decoded.Spectators.Add(ReadRadarContact(span.Slice(offset))); + offset += 11; + } + res = decoded; + return true; + } + + public static DecodedRadarContactsSnapshot DecodeRadarContacts(ReadOnlySpan span) + { + if (!TryDecodeRadarContacts(span, out var res)) + { + throw new InvalidOperationException("Invalid RadarContacts packet."); + } + return res; + } + + private static void WriteRadarContact(Span dst, in NetRadarContact c) + { + dst[0] = c.EntityId; + byte flags = 0; + if (c.Visible) flags |= 1; + if (c.FaintHorizon) flags |= 2; + if (c.HasEverBeenSeen) flags |= 4; + dst[1] = flags; + int ageSteps = float.IsFinite(c.LastSeenAge) ? (int)MathF.Round(c.LastSeenAge / 0.025f) : 255; + dst[2] = (byte)Math.Clamp(ageSteps, 0, 255); + BinaryPrimitives.WriteSingleLittleEndian(dst.Slice(3), c.LastSeenX); + BinaryPrimitives.WriteSingleLittleEndian(dst.Slice(7), c.LastSeenZ); + } + + private static NetRadarContact ReadRadarContact(ReadOnlySpan src) + { + byte id = src[0]; + byte flags = src[1]; + byte ageSteps = src[2]; + return new NetRadarContact + { + EntityId = id, + Visible = (flags & 1) != 0, + FaintHorizon = (flags & 2) != 0, + HasEverBeenSeen = (flags & 4) != 0, + LastSeenAge = ageSteps >= 255 ? float.PositiveInfinity : ageSteps * 0.025f, + LastSeenX = BinaryPrimitives.ReadSingleLittleEndian(src.Slice(3)), + LastSeenZ = BinaryPrimitives.ReadSingleLittleEndian(src.Slice(7)) + }; + } + + private static void WriteCompactSpectator(Span dst, in NetSpectatorState s) + { + dst[0] = s.Id; + byte flags = (byte)((s.Alive ? 1 : 0) | (((byte)s.Stance & 3) << 1) | (s.Snap ? 8 : 0)); + dst[1] = flags; + dst[2] = (byte)s.TargetContenderId; + WriteInt24(dst.Slice(3), s.Pos.X); + WriteInt24(dst.Slice(6), s.Pos.Y); + WriteInt24(dst.Slice(9), s.Pos.Z); + WriteQuatSnorm16(dst.Slice(12), s.Rot); + WriteVelShort(dst.Slice(20), s.Vel); + } + + private static NetSpectatorState ReadCompactSpectator(ReadOnlySpan src) + { + byte id = src[0]; + byte flags = src[1]; + sbyte target = (sbyte)src[2]; + Vector3 pos = new(ReadInt24(src.Slice(3)), ReadInt24(src.Slice(6)), ReadInt24(src.Slice(9))); + Quaternion rot = ReadQuatSnorm16(src.Slice(12)); + Vector3 vel = ReadVelShort(src.Slice(20)); + return new NetSpectatorState + { + Id = id, + Alive = (flags & 1) != 0, + Stance = (SpectatorStance)((flags >> 1) & 3), + Snap = (flags & 8) != 0, + TargetContenderId = target, + Pos = pos, + Rot = rot, + Vel = vel + }; + } + + private static short EncodeSnorm16(float v) => + (short)Math.Clamp(MathF.Round(Math.Clamp(v, -1f, 1f) * 32767f), -32767, 32767); + + private static float DecodeSnorm16(short v) => v / 32767f; + + private static byte EncodeSnorm8(float v) => + (byte)(sbyte)Math.Clamp(MathF.Round(Math.Clamp(v, -1f, 1f) * 127f), -127, 127); + + private static float DecodeSnorm8(byte b) => (sbyte)b / 127f; + + private static byte EncodeRatioByte(float v, float maxVal) => + (byte)Math.Clamp((int)MathF.Round((Math.Clamp(v, 0f, maxVal) / maxVal) * 255f), 0, 255); + + private static short EncodeAngleShort(float rad) => + (short)Math.Clamp((int)MathF.Round(MatchRules.NormalizeAngle(rad) / MathF.PI * 32767f), -32767, 32767); + + private static float DecodeAngleShort(short v) => (v / 32767f) * MathF.PI; + + private static short EncodeWalkerAngle(float rad) => + (short)Math.Clamp((int)MathF.Round(rad * 4096f), short.MinValue, short.MaxValue); + + private static float DecodeWalkerAngle(short v) => v / 4096f; + + private static void WriteQuatSnorm16(Span dst, Quaternion q) + { + if (q.LengthSquared() < 1e-6f) q = Quaternion.Identity; + else q = Quaternion.Normalize(q); + BinaryPrimitives.WriteInt16LittleEndian(dst, EncodeSnorm16(q.X)); + BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(2), EncodeSnorm16(q.Y)); + BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(4), EncodeSnorm16(q.Z)); + BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(6), EncodeSnorm16(q.W)); + } + + private static Quaternion ReadQuatSnorm16(ReadOnlySpan src) + { + var q = new Quaternion( + DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(src)), + DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(src.Slice(2))), + DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(src.Slice(4))), + DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(src.Slice(6)))); + return q.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(q); + } + + private static void WriteVelShort(Span dst, Vector3 v) + { + BinaryPrimitives.WriteInt16LittleEndian(dst, (short)Math.Clamp((int)MathF.Round(v.X * 100f), -32767, 32767)); + BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(2), (short)Math.Clamp((int)MathF.Round(v.Y * 100f), -32767, 32767)); + BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(4), (short)Math.Clamp((int)MathF.Round(v.Z * 100f), -32767, 32767)); + } + + private static Vector3 ReadVelShort(ReadOnlySpan src) => new( + BinaryPrimitives.ReadInt16LittleEndian(src) / 100f, + BinaryPrimitives.ReadInt16LittleEndian(src.Slice(2)) / 100f, + BinaryPrimitives.ReadInt16LittleEndian(src.Slice(4)) / 100f); + + private static void WriteInt24(Span dst, float meters) + { + int scaled = Math.Clamp((int)MathF.Round(meters * 256f), -8388607, 8388607); + dst[0] = (byte)(scaled & 0xFF); + dst[1] = (byte)((scaled >> 8) & 0xFF); + dst[2] = (byte)((scaled >> 16) & 0xFF); + } + + private static float ReadInt24(ReadOnlySpan src) + { + int v = src[0] | (src[1] << 8) | (src[2] << 16); + if ((v & 0x800000) != 0) + { + v |= unchecked((int)0xFF000000); + } + return v / 256f; + } + + private static void WriteOctNormal(Span dst, Vector3 n) + { + if (n.LengthSquared() < 1e-6f) n = Vector3.UnitY; + else n = Vector3.Normalize(n); + float sum = MathF.Abs(n.X) + MathF.Abs(n.Y) + MathF.Abs(n.Z); + float ox = n.X / sum; + float oy = n.Z / sum; + if (n.Y < 0f) + { + float sx = (1f - MathF.Abs(oy)) * (ox >= 0f ? 1f : -1f); + float sy = (1f - MathF.Abs(ox)) * (oy >= 0f ? 1f : -1f); + ox = sx; + oy = sy; + } + dst[0] = EncodeSnorm8(ox); + dst[1] = EncodeSnorm8(oy); + } + + private static Vector3 ReadOctNormal(ReadOnlySpan src) + { + float ox = DecodeSnorm8(src[0]); + float oy = DecodeSnorm8(src[1]); + float ny = 1f - MathF.Abs(ox) - MathF.Abs(oy); + if (ny < 0f) + { + float oldOx = ox; + ox = (1f - MathF.Abs(oy)) * (oldOx >= 0f ? 1f : -1f); + oy = (1f - MathF.Abs(oldOx)) * (oy >= 0f ? 1f : -1f); + } + var v = new Vector3(ox, ny, oy); + return v.LengthSquared() < 1e-6f ? Vector3.UnitY : Vector3.Normalize(v); + } + + public static bool HasPingMagic(ReadOnlySpan buf) => + buf.Length >= 4 && + buf[0] == (byte)'R' && + buf[1] == (byte)'T' && + buf[2] == (byte)'D' && + buf[3] == (byte)'P'; + + public static byte[] EncodePing(ulong clientNonce) + { + byte[] buf = new byte[PingPacketBytes]; + buf[0] = (byte)'R'; + buf[1] = (byte)'T'; + buf[2] = (byte)'D'; + buf[3] = (byte)'P'; + buf[4] = PingWireVersion; + buf[5] = PingKindRequest; + BinaryPrimitives.WriteUInt64LittleEndian(buf.AsSpan(8, 8), clientNonce); + return buf; + } + + public static bool TryDecodePing(ReadOnlySpan buf, out ulong clientNonce) + { + if (buf.Length < 16 || + !HasPingMagic(buf) || + buf[4] != PingWireVersion || + buf[5] != PingKindRequest) + { + clientNonce = 0; + return false; + } + clientNonce = BinaryPrimitives.ReadUInt64LittleEndian(buf.Slice(8, 8)); + return true; + } + + public static byte[] EncodePong(in ServerPingSummary summary) + { + string rawName = string.IsNullOrWhiteSpace(summary.ServerName) ? "Rust to Dust" : summary.ServerName.Trim(); + Span utf8Buf = stackalloc byte[48]; + Encoding.UTF8.GetEncoder().Convert(rawName.AsSpan(), utf8Buf, flush: true, out _, out int nameBytes, out _); + + byte[] buf = new byte[27 + nameBytes]; + var span = buf.AsSpan(); + span[0] = (byte)'R'; + span[1] = (byte)'T'; + span[2] = (byte)'D'; + span[3] = (byte)'P'; + span[4] = PingWireVersion; + span[5] = PingKindResponse; + BinaryPrimitives.WriteUInt16LittleEndian(span.Slice(6, 2), summary.ProtocolVersion); + BinaryPrimitives.WriteUInt64LittleEndian(span.Slice(8, 8), summary.ClientNonce); + span[16] = (byte)summary.MapKind; + span[17] = summary.Phase switch + { + MatchPhase.Completed => 1, + MatchPhase.Lobby => 2, + _ => 0 + }; + span[18] = summary.Humans; + span[19] = summary.MaxHumans; + span[20] = summary.WaveIndex; + byte flags = 0; + if (summary.AcceptingJoin) flags |= 1; + if (summary.HasPassword) flags |= 2; + span[21] = flags; + BinaryPrimitives.WriteInt32LittleEndian(span.Slice(22, 4), summary.Seed); + span[26] = (byte)nameBytes; + if (nameBytes > 0) + { + utf8Buf.Slice(0, nameBytes).CopyTo(span.Slice(27)); + } + return buf; + } + + public static bool TryDecodePong(ReadOnlySpan buf, out ServerPingSummary summary) + { + if (buf.Length < 27 || + !HasPingMagic(buf) || + buf[4] != PingWireVersion || + buf[5] != PingKindResponse) + { + summary = default; + return false; + } + + int nameLen = buf[26]; + if (nameLen > 64 || 27 + nameLen > buf.Length) + { + summary = default; + return false; + } + + ushort proto = BinaryPrimitives.ReadUInt16LittleEndian(buf.Slice(6, 2)); + ulong nonce = BinaryPrimitives.ReadUInt64LittleEndian(buf.Slice(8, 8)); + ArenaMapKind mapKind = (ArenaMapKind)buf[16]; + MatchPhase phase = buf[17] switch + { + 1 => MatchPhase.Completed, + 2 => MatchPhase.Lobby, + _ => MatchPhase.Active + }; + byte humans = buf[18]; + byte maxHumans = buf[19]; + byte waveIndex = buf[20]; + byte flags = buf[21]; + int seed = BinaryPrimitives.ReadInt32LittleEndian(buf.Slice(22, 4)); + string name = nameLen > 0 ? Encoding.UTF8.GetString(buf.Slice(27, nameLen)) : "Rust to Dust"; + + summary = new ServerPingSummary( + nonce, + proto, + mapKind, + phase, + humans, + maxHumans, + waveIndex, + AcceptingJoin: (flags & 1) != 0, + HasPassword: (flags & 2) != 0, + seed, + name); + return true; + } + } +} diff --git a/src/RustToDust.Server/Program.cs b/src/RustToDust.Server/Program.cs new file mode 100644 index 0000000..5f7ae2b --- /dev/null +++ b/src/RustToDust.Server/Program.cs @@ -0,0 +1,237 @@ +using System; +using System.Diagnostics; +using System.Globalization; +using System.Net; +using System.Threading; +using RustToDust.Core; +using RustToDust.Net; +using RustToDust.Ymir; + +namespace RustToDust.Server +{ + public static class Program + { + public static int Main(string[] args) + { + string bindStr = Environment.GetEnvironmentVariable("RTD_BIND") ?? "127.0.0.1"; + int port = TryParseInt(Environment.GetEnvironmentVariable("RTD_PORT"), 3076); + string mapStr = Environment.GetEnvironmentVariable("RTD_MAP") ?? "desert"; + int seed = TryParseInt(Environment.GetEnvironmentVariable("RTD_SEED"), 42); + int maxHumans = MatchState.ContenderCount; + double autoRestartSec = 8.0; + double durationSec = 0.0; + bool allowClientReset = false; + string? directoryUrl = Environment.GetEnvironmentVariable("RTD_DIRECTORY_URL"); + string serverName = Environment.GetEnvironmentVariable("RTD_SERVER_NAME") ?? "Rust to Dust"; + string publicHost = Environment.GetEnvironmentVariable("RTD_PUBLIC_HOST") ?? "auto"; + bool startInLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_LOBBY"), false); + int minHumansToStart = TryParseInt(Environment.GetEnvironmentVariable("RTD_MIN_HUMANS"), 1); + bool restartToLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_RESTART_TO_LOBBY"), false); + int squadSize = Math.Clamp(TryParseInt(Environment.GetEnvironmentVariable("RTD_SQUAD_SIZE"), 3), 1, 4); + string? scarFilePath = Environment.GetEnvironmentVariable("RTD_SCAR_FILE"); + bool persistScars = TryParseBool(Environment.GetEnvironmentVariable("RTD_PERSIST_SCARS"), true); + bool repairScars = false; + + for (int i = 0; i < args.Length; i++) + { + string a = args[i]; + if (a == "--bind" && i + 1 < args.Length) bindStr = args[++i]; + else if (a.StartsWith("--bind=", StringComparison.Ordinal)) bindStr = a.Substring("--bind=".Length); + else if (a == "--port" && i + 1 < args.Length) port = TryParseInt(args[++i], port); + else if (a.StartsWith("--port=", StringComparison.Ordinal)) port = TryParseInt(a.Substring("--port=".Length), port); + else if (a == "--map" && i + 1 < args.Length) mapStr = args[++i]; + else if (a.StartsWith("--map=", StringComparison.Ordinal)) mapStr = a.Substring("--map=".Length); + else if (a == "--seed" && i + 1 < args.Length) seed = TryParseInt(args[++i], seed); + else if (a.StartsWith("--seed=", StringComparison.Ordinal)) seed = TryParseInt(a.Substring("--seed=".Length), seed); + else if (a == "--max-humans" && i + 1 < args.Length) maxHumans = TryParseInt(args[++i], maxHumans); + else if (a.StartsWith("--max-humans=", StringComparison.Ordinal)) maxHumans = TryParseInt(a.Substring("--max-humans=".Length), maxHumans); + else if (a == "--auto-restart-sec" && i + 1 < args.Length) autoRestartSec = TryParseDouble(args[++i], autoRestartSec); + else if (a.StartsWith("--auto-restart-sec=", StringComparison.Ordinal)) autoRestartSec = TryParseDouble(a.Substring("--auto-restart-sec=".Length), autoRestartSec); + else if (a == "--duration-sec" && i + 1 < args.Length) durationSec = TryParseDouble(args[++i], durationSec); + else if (a.StartsWith("--duration-sec=", StringComparison.Ordinal)) durationSec = TryParseDouble(a.Substring("--duration-sec=".Length), durationSec); + else if (a == "--allow-client-reset") allowClientReset = true; + else if (a == "--assets-dir" && i + 1 < args.Length) Environment.SetEnvironmentVariable("RTD_ASSETS_DIR", args[++i]); + else if (a.StartsWith("--assets-dir=", StringComparison.Ordinal)) Environment.SetEnvironmentVariable("RTD_ASSETS_DIR", a.Substring("--assets-dir=".Length)); + else if (a == "--directory-url" && i + 1 < args.Length) directoryUrl = args[++i]; + else if (a.StartsWith("--directory-url=", StringComparison.Ordinal)) directoryUrl = a.Substring("--directory-url=".Length); + else if (a == "--server-name" && i + 1 < args.Length) serverName = args[++i]; + else if (a.StartsWith("--server-name=", StringComparison.Ordinal)) serverName = a.Substring("--server-name=".Length); + else if (a == "--public-host" && i + 1 < args.Length) publicHost = args[++i]; + else if (a.StartsWith("--public-host=", StringComparison.Ordinal)) publicHost = a.Substring("--public-host=".Length); + else if (a == "--lobby") startInLobby = true; + else if (a == "--min-humans" && i + 1 < args.Length) minHumansToStart = TryParseInt(args[++i], minHumansToStart); + else if (a.StartsWith("--min-humans=", StringComparison.Ordinal)) minHumansToStart = TryParseInt(a.Substring("--min-humans=".Length), minHumansToStart); + else if (a == "--restart-to-lobby") restartToLobby = true; + else if (a == "--squad-size" && i + 1 < args.Length) squadSize = Math.Clamp(TryParseInt(args[++i], squadSize), 1, 4); + else if (a.StartsWith("--squad-size=", StringComparison.Ordinal)) squadSize = Math.Clamp(TryParseInt(a.Substring("--squad-size=".Length), squadSize), 1, 4); + else if (a == "--scar-file" && i + 1 < args.Length) scarFilePath = args[++i]; + else if (a.StartsWith("--scar-file=", StringComparison.Ordinal)) scarFilePath = a.Substring("--scar-file=".Length); + else if (a == "--no-persist-scars") persistScars = false; + else if (a == "--repair-scars") repairScars = true; + } + + if (!IPAddress.TryParse(bindStr, out var bindIp)) + { + Console.Error.WriteLine($"Invalid --bind IP address: '{bindStr}'"); + return 2; + } + + ArenaMapKind mapKind = string.Equals(mapStr, "sion", StringComparison.OrdinalIgnoreCase) + ? ArenaMapKind.Sion + : ArenaMapKind.Desert; + + using var cts = new CancellationTokenSource(); + ConsoleCancelEventHandler cancelHandler = (_, e) => + { + e.Cancel = true; + cts.Cancel(); + }; + EventHandler exitHandler = (_, _) => cts.Cancel(); + Console.CancelKeyPress += cancelHandler; + AppDomain.CurrentDomain.ProcessExit += exitHandler; + + DirectoryReporter? reporter = null; + try + { + using var host = new ServerMatchHost( + bindIp, + port, + seed, + mapKind, + maxHumans, + autoRestartSec, + allowClientReset, + hostContenderId: null, + startInLobby: startInLobby, + serverName: serverName, + minHumansToStart: minHumansToStart, + restartToLobby: restartToLobby, + squadSize: (byte)squadSize, + scarFilePath: scarFilePath, + persistScars: persistScars, + repairScarsOnStart: repairScars); + host.LogMessage += msg => Console.WriteLine(msg); + + static DirectoryHeartbeatSnapshot BuildSnapshot(ServerMatchHost h, string hostAddr) => + new( + h.ServerName, + hostAddr, + h.BoundPort, + h.Session.State.MapKind == ArenaMapKind.Sion ? "sion" : "desert", + h.Session.State.Seed, + h.ConnectedHumanCount, + h.MaxHumans, + h.Session.State.Phase.ToString(), + h.Session.State.OrbitalDrop.CurrentWaveIndex); + + object dirSnapGate = new(); + DirectoryHeartbeatSnapshot cachedDirSnap = BuildSnapshot(host, publicHost); + + if (!string.IsNullOrWhiteSpace(directoryUrl)) + { + reporter = new DirectoryReporter( + directoryUrl, + () => + { + lock (dirSnapGate) + { + return cachedDirSnap; + } + }); + } + + Console.WriteLine($"RustToDust.Server listening on {bindIp}:{host.BoundPort} (name=\"{host.ServerName}\", map={mapKind}, seed={seed}, maxHumans={maxHumans}, lobby={startInLobby})"); + + double tickSec = ArenaSession.FixedDt; + var sw = Stopwatch.StartNew(); + double nextTickSec = sw.Elapsed.TotalSeconds; + double endSec = durationSec > 0.0 ? durationSec : double.PositiveInfinity; + int lastReportedHumans = host.ConnectedHumanCount; + MatchPhase lastReportedPhase = host.Session.State.Phase; + ArenaMapKind lastReportedMap = host.Session.State.MapKind; + int lastReportedSeed = host.Session.State.Seed; + int lastReportedWave = host.Session.State.OrbitalDrop.CurrentWaveIndex; + + while (!cts.IsCancellationRequested && sw.Elapsed.TotalSeconds < endSec) + { + double nowSec = sw.Elapsed.TotalSeconds; + if (nowSec >= nextTickSec) + { + host.StepOnce(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + if (reporter is not null) + { + var state = host.Session.State; + int curHumans = host.ConnectedHumanCount; + int curWave = state.OrbitalDrop.CurrentWaveIndex; + if (curHumans != lastReportedHumans || + state.Phase != lastReportedPhase || + state.MapKind != lastReportedMap || + state.Seed != lastReportedSeed || + curWave != lastReportedWave) + { + lastReportedHumans = curHumans; + lastReportedPhase = state.Phase; + lastReportedMap = state.MapKind; + lastReportedSeed = state.Seed; + lastReportedWave = curWave; + DirectoryHeartbeatSnapshot updated = BuildSnapshot(host, publicHost); + lock (dirSnapGate) + { + cachedDirSnap = updated; + } + reporter.NotifyChanged(); + } + } + + nextTickSec += tickSec; + if (nowSec - nextTickSec > 0.25) + { + nextTickSec = nowSec + tickSec; + } + } + else + { + host.PollStatelessPings(); + double remainingMs = (nextTickSec - nowSec) * 1000.0; + if (remainingMs > 2.0) + { + Thread.Sleep(1); + } + else + { + Thread.Yield(); + } + } + } + + Console.WriteLine($"RustToDust.Server shutting down cleanly after {host.SimTick} ticks."); + return 0; + } + catch (Exception ex) + { + Console.Error.WriteLine($"RustToDust.Server fatal error: {ex}"); + return 1; + } + finally + { + reporter?.Dispose(); + Console.CancelKeyPress -= cancelHandler; + AppDomain.CurrentDomain.ProcessExit -= exitHandler; + } + } + + private static int TryParseInt(string? s, int fallback) => + int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v) ? v : fallback; + + private static double TryParseDouble(string? s, double fallback) => + double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double v) ? v : fallback; + + private static bool TryParseBool(string? s, bool fallback) + { + if (string.IsNullOrWhiteSpace(s)) return fallback; + if (s == "1") return true; + if (s == "0") return false; + return bool.TryParse(s, out bool v) ? v : fallback; + } + } +} diff --git a/src/RustToDust.Server/RustToDust.Server.csproj b/src/RustToDust.Server/RustToDust.Server.csproj new file mode 100644 index 0000000..5ef346d --- /dev/null +++ b/src/RustToDust.Server/RustToDust.Server.csproj @@ -0,0 +1,19 @@ + + + + Exe + net8.0 + LatestMajor + enable + disable + Release + + + + + + + + + + diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs new file mode 100644 index 0000000..1862b8f --- /dev/null +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -0,0 +1,3553 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Numerics; +using RustToDust.Core; +using Ymir.Box3D; + +namespace RustToDust.Ymir +{ + public sealed class ArenaSession : IDisposable, IOrdnanceTargetSink + { + public const float FixedDt = 1f / 60f; + public const int SubStepCount = 4; + public const int WorldBodyCapacity = 1024; + + private const ulong GroundStableId = 1; + private const ulong StaticBoxStableIdBase = 10; + private const ulong StaticMeshStableIdBase = 100; + public const ulong ContenderStableIdBase = 1000; + private const ulong SpectatorStableIdBase = 3000; + + private readonly Box3DSoaWorld _world; + private readonly Box3DPhysicsTileSync _tileSync = new(); + private readonly Dictionary _contenderBodies = new(); + private readonly Dictionary _spectatorBodies = new(); + private readonly Dictionary _contenderWalkers = new(); + private readonly Dictionary _spectatorWalkers = new(); + private readonly Dictionary _entityByStableId = new(); + private readonly float[] _trackDistAccum = new float[MatchState.ContenderCount]; + private readonly PlayerInput[] _humanInputs = new PlayerInput[MatchState.ContenderCount]; + private readonly bool[] _pendingInteract = new bool[MatchState.ContenderCount]; + private readonly bool[,] _contenderPvs = new bool[MatchState.ContenderCount, MatchState.ContenderCount]; + private readonly bool[,] _spectatorPvs; + private readonly List _stepEvents = new(); + private readonly List _ordnanceNetScratch = new(64); + private long _forwardedPodEventId; + private bool _disposed; + + public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false, bool startInLobby = false, byte squadSize = 1, ArenaScarLedgerSnapshot? initialScars = null) + { + State = new MatchState(seed, mapKind, skipInitialDrop, startInLobby, squadSize, initialScars); + Ordnance = new OrdnanceRuntime(this); + _spectatorPvs = new bool[MatchState.ContenderCount, State.Spectators.Spectators.Count]; + _forwardedPodEventId = State.PodEvents.Count > 0 ? State.PodEvents[^1].EventId : 0; + + State.ChassisSwapped += OnContenderChassisSwapped; + State.LoadoutChanged += OnContenderLoadoutChanged; + State.ContenderRespawned += OnContenderLoadoutChanged; + State.DropSpawned += OnDropSpawned; + State.DropPickedUp += OnDropPickedUp; + State.ContenderPodTouchedDown += OnContenderPodTouchedDown; + State.Broadcast.LineEmitted += OnBroadcastLineEmitted; + + if (slot0Human && State.Contenders.Count > 0) + { + State.Contenders[0].IsHuman = true; + State.Contenders[0].Name = "Contender 01 (You)"; + if (State.Contenders[0].ActivePodId is { } podId) + { + foreach (var p in State.OrbitalDrop.ActivePods) + { + if (p.PodId == podId) + { + p.AllowFlatRoofLanding = State.MapKind == ArenaMapKind.Sion; + break; + } + } + } + } + + _world = new Box3DSoaWorld( + capacity: WorldBodyCapacity, + gravityX: 0f, + gravityY: -20f, + gravityZ: 0f); + + BuildStaticArena(_world, State, _tileSync, warmAllActors: true); + SpawnContenderBodies(); + SpawnSpectatorBodies(); + UpdateObserverDetectionMemories(); + } + + public static bool PerfEnabled; + public static double PerfRingMs; + public static double PerfAiMs; + public static double PerfDriveMs; + public static double PerfWorldMs; + public static double PerfBodySyncMs; + public static double PerfDetectMs; + public static double PerfWeaponsMs; + + public MatchState State { get; } + public OrdnanceRuntime Ordnance { get; } + public Box3DSoaWorld World => _world; + public Box3DPhysicsTileSync TileSync => _tileSync; + public bool EnableNetworkPvs { get; set; } = true; + + public void RepairArenaScars() + { + State.RepairArenaScars(); + if (State.Terrain.IsHeightmapMode) + { + int dirtyResidentCount = _tileSync.CountDirtyResidentTiles(State.Terrain); + if (dirtyResidentCount > 0) + { + int budget = _world.FreeBodySlots >= dirtyResidentCount + 32 + ? dirtyResidentCount + : 4; + _tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: budget); + } + } + } + + public static bool IsStaticWorldStableId(ulong stableId) => + stableId < ContenderStableIdBase || stableId >= Box3DPhysicsTileSync.HeightfieldTileStableIdBase; + + public static bool IsStaticBuildingOrCoverStableId(ulong stableId) => + (stableId >= StaticMeshStableIdBase && stableId < ContenderStableIdBase) || + (stableId >= Box3DPhysicsTileSync.BuildingTileStableIdBase && stableId < Box3DPhysicsTileSync.TreeTileStableIdBase); + + public Box3DSoaRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation) + { + return _world.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z)); + } + + public void SetHumanSlot(int contenderId, bool isHuman, string? callsign = null) + { + if (contenderId < 0 || contenderId >= State.Contenders.Count) + { + return; + } + var c = State.Contenders[contenderId]; + bool changed = c.IsHuman != isHuman || (callsign is not null && !string.Equals(c.Name, callsign, StringComparison.Ordinal)); + c.IsHuman = isHuman; + if (callsign is not null) + { + c.Name = callsign; + } + else if (!isHuman) + { + c.Name = $"Contender {contenderId + 1:00}"; + } + + _humanInputs[contenderId] = default; + _pendingInteract[contenderId] = false; + c.ThrottleCmd = 0f; + c.SteerCmd = 0f; + c.VerticalThrottleCmd = 0f; + c.FireCmd = false; + c.BrakeCmd = false; + c.ResetAimTracker(c.Yaw); + + if (isHuman) + { + State.GetOrCreateObserverState(contenderId); + } + if (State.Lobby is { } lobby && contenderId >= 0 && contenderId < lobby.Slots.Length) + { + lobby.Slots[contenderId].IsHuman = isHuman; + lobby.Slots[contenderId].Callsign = c.Name; + if (!isHuman) + { + lobby.Slots[contenderId].IsReady = false; + } + } + if (c.ActivePodId is { } activePodId) + { + for (int p = 0; p < State.OrbitalDrop.ActivePods.Count; p++) + { + if (State.OrbitalDrop.ActivePods[p].PodId == activePodId) + { + State.OrbitalDrop.ActivePods[p].AllowFlatRoofLanding = isHuman && State.MapKind == ArenaMapKind.Sion; + break; + } + } + } + + if (changed) + { + UpdateObserverDetectionMemories(); + } + } + + public void SetHumanInput(int contenderId, in PlayerInput input) + { + if (contenderId < 0 || contenderId >= _humanInputs.Length) + { + return; + } + _humanInputs[contenderId] = input; + if (input.InteractPickup) + { + _pendingInteract[contenderId] = true; + } + } + + public void TriggerHumanInteract(int contenderId) + { + if (contenderId >= 0 && contenderId < _pendingInteract.Length) + { + _pendingInteract[contenderId] = true; + } + } + + public float? GetWalkerSimTime(bool isContender, int id) + { + var dict = isContender ? _contenderWalkers : _spectatorWalkers; + return dict.TryGetValue(id, out var ws) && ws.Initialized ? ws.SimTime : null; + } + + public void DrainStepEvents(List dest) + { + if (_stepEvents.Count == 0) + { + return; + } + dest.AddRange(_stepEvents); + _stepEvents.Clear(); + } + + public bool IsEntityInPeerPvs(int observerContenderId, bool isContender, int entityId) + { + if (observerContenderId < 0 || observerContenderId >= MatchState.ContenderCount) + { + return false; + } + if (isContender) + { + return entityId >= 0 && entityId < MatchState.ContenderCount && _contenderPvs[observerContenderId, entityId]; + } + int specIdx = entityId >= 1000 ? entityId - 1000 : entityId; + return specIdx >= 0 && specIdx < _spectatorPvs.GetLength(1) && _spectatorPvs[observerContenderId, specIdx]; + } + + public bool IsPointInPeerPvs(int observerContenderId, float tx, float ty, float tz) + { + if (observerContenderId < 0 || observerContenderId >= State.Contenders.Count) + { + return false; + } + var obs = State.Contenders[observerContenderId]; + if (!obs.Alive) + { + return false; + } + float obsEyeY = MatchRules.GetObserverEyeY(obs.Y, obs.Grid.Spec.HalfHeight); + return HasLineOfSight(obs.X, obsEyeY, obs.Z, tx, ty, tz) || + HasLineOfSight(obs.X, obsEyeY + 1.0f, obs.Z, tx, ty + 0.5f, tz); + } + + public bool TryEquipCargo(int contenderId, int cargoIndex, string hardpointId) => + State.TryEquipCargo(contenderId, cargoIndex, hardpointId); + + public bool TrySwapNearbyChassis(int contenderId) => + State.TrySwapNearbyChassis(contenderId); + + private void OnDropSpawned(GroundDrop drop) + { + _stepEvents.Add(new DropSpawnedEvent + { + DropId = drop.Id, + X = drop.X, + Z = drop.Z, + ChassisId = drop.Chassis?.Id, + ModuleId = drop.Module?.Id + }); + } + + private void OnDropPickedUp(int dropId, int contenderId) + { + _stepEvents.Add(new DropPickedUpEvent + { + DropId = dropId, + ContenderId = contenderId + }); + } + + private void OnContenderLoadoutChanged(ContenderState c) + { + _stepEvents.Add(BuildContenderLoadoutEvent(c, includeCargo: true)); + } + + private void OnBroadcastLineEmitted(BroadcastLine line) + { + _stepEvents.Add(new BroadcastLineEvent + { + Timestamp = line.Timestamp, + Kind = (byte)line.Kind, + Text = line.Text + }); + } + + public static ContenderLoadoutEvent BuildContenderLoadoutEvent(ContenderState c, bool includeCargo) + { + var mounted = new List(c.Grid.Mounted.Count); + for (int i = 0; i < c.Grid.Mounted.Count; i++) + { + var m = c.Grid.Mounted[i]; + mounted.Add(new MountedSlotDto { ModuleId = m.Spec.Id, HardpointId = m.HardpointId }); + } + + List? cargo = null; + if (includeCargo) + { + cargo = new List(c.Grid.Cargo.Count); + for (int i = 0; i < c.Grid.Cargo.Count; i++) + { + cargo.Add(c.Grid.Cargo[i].Id); + } + } + + return new ContenderLoadoutEvent + { + ContenderId = c.Id, + LoadoutVersion = c.LoadoutVersion, + ChassisId = c.Grid.Spec.Id, + CoreHp = c.Grid.CoreHp, + MaxCoreHp = c.Grid.MaxCoreHp, + ArmorBytes = c.Grid.QuantizeArmorBytes(), + Mounted = mounted, + CargoIds = cargo + }; + } + + public Box3DSoaBodyHandle? GetContenderBody(int contenderId) => + _contenderBodies.TryGetValue(contenderId, out var h) ? h : null; + + public Box3DSoaBodyHandle? GetSpectatorBody(int spectatorId) => + _spectatorBodies.TryGetValue(spectatorId, out var h) ? h : null; + + public void SetContenderPose(int contenderId, float x, float z, float? yaw = null) + { + if (contenderId < 0 || contenderId >= State.Contenders.Count) + { + return; + } + var c = State.Contenders[contenderId]; + State.OrbitalDrop.CancelContenderPod(contenderId); + if (c.Lifecycle == ContenderLifecycle.Deploying || c.Lifecycle == ContenderLifecycle.WaitingForRespawnWave) + { + c.Lifecycle = ContenderLifecycle.Active; + c.HasTouchdownPose = false; + c.TouchdownOnRoof = false; + } + c.X = x; + c.Z = z; + if (yaw.HasValue) c.Yaw = yaw.Value; + + if (_contenderBodies.TryGetValue(contenderId, out var oldHandle)) + { + _world.RemoveBody(oldHandle); + _contenderBodies.Remove(contenderId); + } + _contenderWalkers.Remove(contenderId); + if (State.Terrain.IsHeightmapMode) + { + _tileSync.EnsureTileRegion(_world, State.Terrain, x, z, halfTileRadius: 1); + } + if (c.IsGroundedActive) + { + SpawnContenderBody(c); + } + else + { + c.SnapPreviousPose(); + c.ResetAimTracker(c.Yaw); + } + } + + public void SetSpectatorPose(int spectatorId, float x, float z, float? yaw = null) + { + SpectatorState? spec = null; + int index = -1; + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + if (State.Spectators.Spectators[i].Id == spectatorId) + { + spec = State.Spectators.Spectators[i]; + index = i; + break; + } + } + if (spec is null) + { + return; + } + + spec.X = x; + spec.Z = z; + if (yaw.HasValue) spec.Yaw = yaw.Value; + + if (_spectatorBodies.TryGetValue(spectatorId, out var oldHandle)) + { + _world.RemoveBody(oldHandle); + _spectatorBodies.Remove(spectatorId); + } + _spectatorWalkers.Remove(spectatorId); + if (spec.Alive) + { + SpawnSpectatorBody(index, spec); + } + else + { + spec.SnapPreviousPose(); + spec.ResetAimTracker(spec.Yaw); + } + } + + public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) + { + float t = Math.Clamp(alpha, 0f, 1f); + if (contenderId < 0 || contenderId >= State.Contenders.Count) + { + return (Vector3.Zero, Quaternion.Identity, Vector3.Zero); + } + + var c = State.Contenders[contenderId]; + var prevPos = new Vector3(c.PrevX, c.PrevY, c.PrevZ); + var currPos = new Vector3(c.X, c.Y, c.Z); + var prevQ = new Quaternion(c.PrevRotX, c.PrevRotY, c.PrevRotZ, c.PrevRotW); + var currQ = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW); + prevQ = prevQ.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(prevQ); + currQ = currQ.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(currQ); + if (Quaternion.Dot(prevQ, currQ) < 0f) + { + currQ = -currQ; + } + + return ( + Vector3.Lerp(prevPos, currPos, t), + Quaternion.Slerp(prevQ, currQ, t), + new Vector3(c.VelX, c.VelY, c.VelZ)); + } + + public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha) + { + float t = Math.Clamp(alpha, 0f, 1f); + SpectatorState? spec = null; + var list = State.Spectators.Spectators; + for (int i = 0; i < list.Count; i++) + { + if (list[i].Id == spectatorId) + { + spec = list[i]; + break; + } + } + if (spec is null) + { + return (Vector3.Zero, Quaternion.Identity, Vector3.Zero); + } + + var prevPos = new Vector3(spec.PrevX, spec.PrevY, spec.PrevZ); + var currPos = new Vector3(spec.X, spec.Y, spec.Z); + var prevQ = new Quaternion(spec.PrevRotX, spec.PrevRotY, spec.PrevRotZ, spec.PrevRotW); + var currQ = new Quaternion(spec.CurrRotX, spec.CurrRotY, spec.CurrRotZ, spec.CurrRotW); + prevQ = prevQ.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(prevQ); + currQ = currQ.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(currQ); + if (Quaternion.Dot(prevQ, currQ) < 0f) + { + currQ = -currQ; + } + + return ( + Vector3.Lerp(prevPos, currPos, t), + Quaternion.Slerp(prevQ, currQ, t), + new Vector3(spec.VelX, spec.VelY, spec.VelZ)); + } + + public WalkerState? GetWalkerState(bool isContender, int id) => + isContender + ? (_contenderWalkers.TryGetValue(id, out var cw) ? cw : null) + : (_spectatorWalkers.TryGetValue(id, out var sw) ? sw : null); + + public bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap) + { + var dict = isContender ? _contenderWalkers : _spectatorWalkers; + if (!dict.TryGetValue(id, out var ws) || !ws.Initialized) + { + snap = default; + return false; + } + snap = WalkerVisualSnapshot.Interpolate(in ws.PrevSnap, in ws.CurrSnap, alpha); + return true; + } + + public void AddWalkerRecoilImpulse(bool isContender, int id, Vector3 shotDirWorld, float weaponDamage) + { + var dict = isContender ? _contenderWalkers : _spectatorWalkers; + if (!dict.TryGetValue(id, out var ws)) + { + return; + } + Quaternion qBody = Quaternion.Identity; + if (isContender && id >= 0 && id < State.Contenders.Count) + { + var c = State.Contenders[id]; + qBody = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW); + } + else if (!isContender && _spectatorBodies.TryGetValue(id, out var handle)) + { + var v = _world.View; + int lane = handle.Lane; + qBody = new Quaternion(v.RotationX[lane], v.RotationY[lane], v.RotationZ[lane], v.RotationW[lane]); + } + if (qBody.LengthSquared() < 1e-6f) + { + qBody = Quaternion.Identity; + } + else + { + qBody = Quaternion.Normalize(qBody); + } + ws.AddRecoilImpulse(shotDirWorld, qBody, weaponDamage); + } + + public bool HasLineOfSight(float ax, float ay, float az, float bx, float by, float bz) + { + var delta = new Vector3(bx - ax, by - ay, bz - az); + float dist = delta.Length(); + if (dist <= 0.25f) + { + return true; + } + + Vector3 dir = delta / dist; + // Only static cover/boundary boxes, terrain, and Sion building meshes block LOS. + if (IntersectsAnyStaticBox(ax, ay, az, dir.X, dir.Y, dir.Z, dist)) + { + return false; + } + + if (State.Terrain.Raycast( + ax, ay, az, + dir.X, dir.Y, dir.Z, + MathF.Max(0.1f, dist - 0.5f), + out _, out _, out _, out _)) + { + return false; + } + + if (State.SionMap is { } sionMap && + sionMap.IntersectsAnyBuildingAabb(ax, ay, az, dir.X, dir.Y, dir.Z, dist)) + { + Vector3 castOrigin = new(ax, ay, az); + float remaining = dist; + for (int hop = 0; hop < 4 && remaining > 0.25f; hop++) + { + var hit = _world.CastRayClosest( + (castOrigin.X, castOrigin.Y, castOrigin.Z), + (dir.X * remaining, dir.Y * remaining, dir.Z * remaining)); + if (!hit.Hit) + { + break; + } + if (IsStaticWorldStableId(hit.StableId)) + { + return false; + } + + var hitPt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z); + float step = Vector3.Distance(castOrigin, hitPt) + 0.25f; + castOrigin += dir * step; + remaining -= step; + } + } + + return true; + } + + private bool IntersectsAnyStaticBox(float ox, float oy, float oz, float dx, float dy, float dz, float maxDist) + { + var boxes = State.ArenaCoverBoxes; + for (int i = 0; i < boxes.Count; i++) + { + var b = boxes[i]; + if (RayIntersectsAabb(ox, oy, oz, dx, dy, dz, maxDist, b)) + { + return true; + } + } + var bounds = State.ArenaBoundaryBoxes; + for (int i = 0; i < bounds.Count; i++) + { + var b = bounds[i]; + if (RayIntersectsAabb(ox, oy, oz, dx, dy, dz, maxDist, b)) + { + return true; + } + } + return false; + } + + private static bool RayIntersectsAabb( + float ox, float oy, float oz, + float dx, float dy, float dz, + float maxDist, + in ArenaBoxSpec box) + { + float tMin = 0f; + float tMax = maxDist; + + if (!SlabTest(ox, dx, box.X - box.HalfX, box.X + box.HalfX, ref tMin, ref tMax)) return false; + if (!SlabTest(oy, dy, box.Y - box.HalfY, box.Y + box.HalfY, ref tMin, ref tMax)) return false; + if (!SlabTest(oz, dz, box.Z - box.HalfZ, box.Z + box.HalfZ, ref tMin, ref tMax)) return false; + return tMax >= tMin; + } + + private static bool SlabTest(float o, float d, float minB, float maxB, ref float tMin, ref float tMax) + { + if (MathF.Abs(d) < 1e-6f) + { + return o >= minB && o <= maxB; + } + float invD = 1f / d; + float t1 = (minB - o) * invD; + float t2 = (maxB - o) * invD; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + return tMax >= tMin; + } + + private void SnapshotPreviousPoses() + { + State.OrbitalDrop.SnapshotPreviousPoses(); + for (int i = 0; i < State.Contenders.Count; i++) + { + State.Contenders[i].SnapPreviousPose(); + } + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + State.Spectators.Spectators[i].SnapPreviousPose(); + } + foreach (var ws in _contenderWalkers.Values) + { + if (ws.Initialized) + { + ws.SnapshotPrev(); + } + } + foreach (var ws in _spectatorWalkers.Values) + { + if (ws.Initialized) + { + ws.SnapshotPrev(); + } + } + } + + public void Step() + { + ObjectDisposedException.ThrowIf(_disposed, this); + + SnapshotPreviousPoses(); + + if (State.Phase == MatchPhase.Lobby) + { + MatchRules.AdvanceTracers(State, FixedDt); + MatchRules.AdvanceHitEvents(State, FixedDt); + FlushPodEventsToStepEvents(); + return; + } + + State.Time += FixedDt; + MatchRules.AdvanceTracers(State, FixedDt); + MatchRules.AdvanceHitEvents(State, FixedDt); + State.Spectators.UpdateSafeRadius(State.Time); + State.Spectators.AdvancePerimeterOrbits(FixedDt); + + int subSteps = State.MapKind == ArenaMapKind.Sion ? 1 : SubStepCount; + + void ApplyAllHumanInputs() + { + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.IsHuman) + { + continue; + } + var inp = _humanInputs[i]; + bool interact = _pendingInteract[i]; + _pendingInteract[i] = false; + MatchRules.ApplyHumanInput(State, i, inp with { InteractPickup = interact }); + } + } + + if (!PerfEnabled) + { + UpdateRingClearance(); + ApplyAllHumanInputs(); + MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight); + State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown); + + EnsureActivePhysicsTilesAndFlush(); + ApplyPhysicsDrives(); + _world.Step(FixedDt, subSteps); + SyncBodiesFromWorld(); + + UpdateObserverDetectionMemories(); + StepThermalAndCooldowns(); + ProcessWeapons(); + FlushPodEventsToStepEvents(); + MatchRules.UpdateMatchOutcome(State); + return; + } + + double toMs = 1000.0 / Stopwatch.Frequency; + long t0 = Stopwatch.GetTimestamp(); + UpdateRingClearance(); + long t1 = Stopwatch.GetTimestamp(); + ApplyAllHumanInputs(); + MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight); + State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown); + long t2 = Stopwatch.GetTimestamp(); + EnsureActivePhysicsTilesAndFlush(); + ApplyPhysicsDrives(); + long t3 = Stopwatch.GetTimestamp(); + _world.Step(FixedDt, subSteps); + long t4 = Stopwatch.GetTimestamp(); + SyncBodiesFromWorld(); + long t5 = Stopwatch.GetTimestamp(); + UpdateObserverDetectionMemories(); + long t6 = Stopwatch.GetTimestamp(); + StepThermalAndCooldowns(); + ProcessWeapons(); + long t7 = Stopwatch.GetTimestamp(); + FlushPodEventsToStepEvents(); + MatchRules.UpdateMatchOutcome(State); + + PerfRingMs += (t1 - t0) * toMs; + PerfAiMs += (t2 - t1) * toMs; + PerfDriveMs += (t3 - t2) * toMs; + PerfWorldMs += (t4 - t3) * toMs; + PerfBodySyncMs += (t5 - t4) * toMs; + PerfDetectMs += (t6 - t5) * toMs; + PerfWeaponsMs += (t7 - t6) * toMs; + } + + public bool StartFromLobby(uint matchGeneration = 1) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (State.Phase != MatchPhase.Lobby) + { + return false; + } + + foreach (var kv in _contenderBodies) + { + _world.RemoveBody(kv.Value); + } + _contenderBodies.Clear(); + _contenderWalkers.Clear(); + + if (!State.StartFromLobby(QueryDropSurface)) + { + return false; + } + + SpawnContenderBodies(); + FlushPodEventsToStepEvents(); + _stepEvents.Add(new MatchStartedEvent + { + MatchGeneration = matchGeneration, + MapKind = (byte)State.MapKind, + Seed = State.Seed + }); + UpdateObserverDetectionMemories(); + return true; + } + + public static void BuildStaticArena(Box3DSoaWorld world, MatchState state, Box3DPhysicsTileSync? tileSync = null, bool warmAllActors = true) + { + if (state.MapKind == ArenaMapKind.Sion && state.SionMap is { } sion) + { + if (tileSync is not null && warmAllActors && state.Terrain.IsHeightmapMode) + { + Span needed = stackalloc bool[Box3DPhysicsTileSync.MaxTiles]; + Span immediate = stackalloc bool[Box3DPhysicsTileSync.MaxTiles]; + MarkPhysicsOccupancyTiles(state, needed, immediate); + tileSync.SyncNeededTiles(world, state.Terrain, needed, immediate); + } + + ulong boxId = StaticBoxStableIdBase; + for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++) + { + var b = state.ArenaBoundaryBoxes[i]; + world.AddStaticBox( + boxId++, + (b.X, b.Y, b.Z), + (b.HalfX, b.HalfY, b.HalfZ), + friction: 0.35f, + restitution: 0.1f); + } + + for (int i = 0; i < sion.CollisionMeshes.Count; i++) + { + var col = sion.CollisionMeshes[i]; + world.AddStaticMesh( + StaticMeshStableIdBase + (ulong)i, + (0f, 0f, 0f), + col.Vertices, + col.Indices, + friction: 0.5f, + restitution: 0.05f); + } + return; + } + + // Desert safety floor slab at y = -20m below the lowest possible terrain valley (-18m); + // primary terrain support comes from 4-corner spring-damper sampling of State.Terrain. + world.AddStaticBox( + GroundStableId, + (0f, -20f, 0f), + (800f, 1f, 800f), + friction: 0.25f, + restitution: 0.05f); + + ulong nextId = StaticBoxStableIdBase; + for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++) + { + var b = state.ArenaBoundaryBoxes[i]; + world.AddStaticBox( + nextId++, + (b.X, b.Y, b.Z), + (b.HalfX, b.HalfY, b.HalfZ), + friction: 0.35f, + restitution: 0.1f); + } + + for (int i = 0; i < state.ArenaCoverBoxes.Count; i++) + { + var b = state.ArenaCoverBoxes[i]; + world.AddStaticBox( + nextId++, + (b.X, b.Y, b.Z), + (b.HalfX, b.HalfY, b.HalfZ), + friction: 0.4f, + restitution: 0.05f); + } + } + + private void SpawnContenderBodies() + { + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (c.IsGroundedActive) + { + SpawnContenderBody(c); + } + } + } + + private void OnContenderPodTouchedDown(ContenderState c) + { + if (_contenderBodies.TryGetValue(c.Id, out var oldHandle)) + { + _world.RemoveBody(oldHandle); + _contenderBodies.Remove(c.Id); + } + _contenderWalkers.Remove(c.Id); + if (c.IsGroundedActive) + { + if (State.Terrain.IsHeightmapMode) + { + if (c.IsHuman) + { + _tileSync.EnsureTileRegion(_world, State.Terrain, c.X, c.Z, halfTileRadius: 1); + } + else + { + _tileSync.EnsureTileRegion(_world, State.Terrain, c.X, c.Z, halfTileRadius: 0); + } + } + SpawnContenderBody(c); + } + } + + private void OnPodTouchedDown(OrbitalPod pod, DropSurfaceSample sample) + { + if (!sample.IsBuildingRoof) + { + float craterR = pod.PodKind == OrbitalPodKind.Contender ? 3.4f : 2.1f; + float scorchR = pod.PodKind == OrbitalPodKind.Contender ? 4.2f : 2.6f; + _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = pod.X, Z = pod.Z, Radius = craterR, Depth = 0.32f }); + _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = pod.X, Z = pod.Z, Radius = scorchR }); + } + } + + private void FlushPodEventsToStepEvents() + { + var podEvents = State.PodEvents; + for (int i = 0; i < podEvents.Count; i++) + { + var ev = podEvents[i]; + if (ev.EventId <= _forwardedPodEventId) + { + continue; + } + _forwardedPodEventId = ev.EventId; + _stepEvents.Add(new DropPodEvent + { + EventId = ev.EventId, + Kind = (byte)ev.Kind, + WaveIndex = ev.WaveIndex, + PodId = ev.PodId, + PodKind = (byte)ev.PodKind, + ContenderId = ev.ContenderId, + X = ev.X, + Y = ev.Y, + Z = ev.Z, + VelX = ev.VelX, + VelY = ev.VelY, + VelZ = ev.VelZ, + NormalX = ev.SurfaceNormal.X, + NormalY = ev.SurfaceNormal.Y, + NormalZ = ev.SurfaceNormal.Z, + ChassisId = ev.ChassisId, + ModuleId = ev.ModuleId, + DropId = ev.DropId, + RespawnsClosed = ev.RespawnsClosed, + GearCount = ev.GearCount, + RespawnCount = ev.RespawnCount + }); + } + } + + private static void MarkPhysicsOccupancyTiles(MatchState state, Span needed, Span immediate = default) + { + needed.Clear(); + if (!immediate.IsEmpty) + { + immediate.Clear(); + } + var terrain = state.Terrain; + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (!c.IsGroundedActive) + { + continue; + } + if (!immediate.IsEmpty) + { + Box3DPhysicsTileSync.MarkTileFootprint(terrain, immediate, c.X, c.Z, marginMeters: 0f); + } + if (c.IsHuman) + { + Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, c.X, c.Z, marginMeters: 28f); + } + else + { + Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, c.X, c.Z, marginMeters: 16f); + } + } + for (int i = 0; i < state.Spectators.Spectators.Count; i++) + { + var s = state.Spectators.Spectators[i]; + if (s.Alive && s.Stance != SpectatorStance.Neutral) + { + if (!immediate.IsEmpty) + { + Box3DPhysicsTileSync.MarkTileFootprint(terrain, immediate, s.X, s.Z, marginMeters: 0f); + } + Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, s.X, s.Z, marginMeters: 8f); + } + } + for (int i = 0; i < state.OrbitalDrop.ActivePods.Count; i++) + { + var pod = state.OrbitalDrop.ActivePods[i]; + if (pod.Y - terrain.SampleHeight(pod.X, pod.Z) <= 80f) + { + if (!immediate.IsEmpty) + { + Box3DPhysicsTileSync.MarkTileRegion(terrain, immediate, pod.X, pod.Z, halfTileRadius: 0); + } + Box3DPhysicsTileSync.MarkTileRegion(terrain, needed, pod.X, pod.Z, halfTileRadius: 0); + } + } + } + + private void EnsureActivePhysicsTilesAndFlush() + { + if (!State.Terrain.IsHeightmapMode) + { + return; + } + Span needed = stackalloc bool[Box3DPhysicsTileSync.MaxTiles]; + Span immediate = stackalloc bool[Box3DPhysicsTileSync.MaxTiles]; + MarkPhysicsOccupancyTiles(State, needed, immediate); + _tileSync.SyncNeededTiles(_world, State.Terrain, needed, immediate, maxNewPrefetchPerTick: 1); + _tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: 4); + } + + public DropSurfaceSample QueryDropSurface(float x, float z, float footRadius, float referenceMaxY) + { + return QueryDropSurface(State, _world, x, z, footRadius, referenceMaxY); + } + + public static DropSurfaceSample QueryDropSurface( + MatchState state, + Box3DSoaWorld? world, + float x, + float z, + float footRadius, + float referenceMaxY) + { + float terrainY = state.Terrain.SampleHeight(x, z); + var (nx, ny, nz) = state.Terrain.SampleNormal(x, z); + Vector3 terrainNorm = new(nx, ny, nz); + if (terrainNorm.LengthSquared() < 1e-4f) terrainNorm = Vector3.UnitY; + else terrainNorm = Vector3.Normalize(terrainNorm); + + if (state.MapKind == ArenaMapKind.Sion && state.SionMap is { } sionMap) + { + bool centerOverBuilding = sionMap.TryGetBuildingAt(x, z, 0f, out var centerBldg); + SionBuildingAabb nearBldg = default; + bool lateralWallOverlap = centerOverBuilding || sionMap.TryGetBuildingAt(x, z, footRadius, out nearBldg); + var queryBldg = centerOverBuilding ? centerBldg : nearBldg; + + if (!lateralWallOverlap) + { + return new DropSurfaceSample( + terrainY, + terrainNorm, + IsBuildingRoof: false, + IsFlatRoofValid: false, + IsInsideBuildingFootprint: false, + IsInsideSolidBuilding: false); + } + + if (world is not null) + { + if (centerOverBuilding || referenceMaxY < queryBldg.RoofY + 2.0f) + { + float castStartY = MathF.Max(referenceMaxY, queryBldg.RoofY + 6f); + float castSpan = MathF.Max(20f, castStartY - (terrainY - 12f)); + var centerHit = world.CastRayClosest((x, castStartY, z), (0f, -castSpan, 0f)); + if (centerHit.Hit && + centerHit.StableId >= StaticMeshStableIdBase && + centerHit.StableId < ContenderStableIdBase) + { + float roofY = centerHit.Point.Y; + bool isInsideSolid = roofY > terrainY + 0.1f && roofY > referenceMaxY - 0.5f; + if (roofY > referenceMaxY || roofY <= terrainY + 0.1f) + { + return new DropSurfaceSample( + terrainY, + terrainNorm, + IsBuildingRoof: false, + IsFlatRoofValid: false, + IsInsideBuildingFootprint: true, + IsInsideSolidBuilding: isInsideSolid); + } + + Vector3 roofNorm = new(centerHit.Normal.X, centerHit.Normal.Y, centerHit.Normal.Z); + if (roofNorm.LengthSquared() < 1e-4f) roofNorm = Vector3.UnitY; + else roofNorm = Vector3.Normalize(roofNorm); + + bool flatValid = false; + if (roofNorm.Y >= 0.90f) + { + flatValid = true; + float r = MathF.Max(0.8f, footRadius); + ReadOnlySpan<(float Ox, float Oz)> offsets = stackalloc (float, float)[] + { + (-r, -r), (r, -r), (-r, r), (r, r) + }; + for (int k = 0; k < 4; k++) + { + float cx = x + offsets[k].Ox; + float cz = z + offsets[k].Oz; + var cornerHit = world.CastRayClosest((cx, roofY + 2.5f, cz), (0f, -5.0f, 0f)); + if (!cornerHit.Hit || + cornerHit.StableId < StaticMeshStableIdBase || + cornerHit.StableId >= ContenderStableIdBase || + MathF.Abs(cornerHit.Point.Y - roofY) > 0.45f) + { + flatValid = false; + break; + } + var aboveHit = world.CastRayClosest((cx, roofY + 60f, cz), (0f, -58f, 0f)); + if (aboveHit.Hit && + aboveHit.StableId >= StaticMeshStableIdBase && + aboveHit.StableId < ContenderStableIdBase && + aboveHit.Point.Y > roofY + 0.6f) + { + flatValid = false; + break; + } + } + } + + return new DropSurfaceSample( + MathF.Max(terrainY, roofY), + roofNorm, + IsBuildingRoof: true, + IsFlatRoofValid: flatValid, + IsInsideBuildingFootprint: true, + IsInsideSolidBuilding: isInsideSolid); + } + } + + return new DropSurfaceSample( + terrainY, + terrainNorm, + IsBuildingRoof: false, + IsFlatRoofValid: false, + IsInsideBuildingFootprint: lateralWallOverlap, + IsInsideSolidBuilding: false); + } + } + + return state.DefaultDropSurfaceQuery(x, z, footRadius, referenceMaxY); + } + + public static float GetPhysicsHalfHeight(ChassisSpec spec) => + spec.IsWalker + ? spec.HalfHeight * (spec.Plane == GridPlane.Dorsal ? 0.62f : 0.72f) + : spec.HalfHeight; + + private void SpawnContenderBody(ContenderState c) + { + if (!c.IsGroundedActive) + { + return; + } + var spec = c.Grid.Spec; + float physHalfH = GetPhysicsHalfHeight(spec); + float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength; + float density = spec.MassKg / MathF.Max(0.1f, volume); + Quaternion q; + float spawnY; + float initVelY = 0f; + ulong stableId = ContenderStableIdBase + (ulong)c.Id; + + if (c.HasTouchdownPose) + { + q = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW); + q = q.LengthSquared() < 1e-6f ? Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw) : Quaternion.Normalize(q); + spawnY = c.Y; + initVelY = c.VelY; + } + else + { + q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw); + float clearance = spec.IsVtol + ? Math.Clamp(c.TargetHoverAltAgl, MatchRules.VtolMinClearanceAgl, MathF.Max(MatchRules.VtolMinClearanceAgl, spec.HoverMaxAltitudeM)) + : 0.15f; + spawnY = State.Terrain.SampleHeight(c.X, c.Z) + spec.HalfHeight + clearance; + if (spec.IsWalker && spec.Plane == GridPlane.Dorsal) + { + var (nx, ny, nz) = State.Terrain.SampleNormal(c.X, c.Z); + Vector3 centerNorm = new Vector3(nx, ny, nz); + centerNorm = centerNorm.LengthSquared() > 1e-6f ? Vector3.Normalize(centerNorm) : Vector3.UnitY; + Vector3 fwd = Vector3.Transform(Vector3.UnitZ, q); + fwd.Y = 0f; + fwd = fwd.LengthSquared() > 1e-5f ? Vector3.Normalize(fwd) : Vector3.UnitZ; + Vector3 right = Vector3.Cross(fwd, Vector3.UnitY); + Vector3 hullSlope = WalkerLocomotion.ComputeHullSlopeNormal(State.Terrain, c.X, c.Z, fwd, right, spec.HalfWidth, spec.HalfLength, centerNorm, out _); + q = WalkerLocomotion.AlignUpToSlope(q, hullSlope, 0.90f, 0.350f); + + float minCornerClr = float.PositiveInfinity; + foreach (float sx in new[] { -spec.HalfWidth, spec.HalfWidth }) + { + foreach (float sz in new[] { -spec.HalfLength, spec.HalfLength }) + { + Vector3 corner = new Vector3(c.X, spawnY, c.Z) + Vector3.Transform(new Vector3(sx, -physHalfH, sz), q); + float clr = corner.Y - State.Terrain.SampleHeight(corner.X, corner.Z); + if (clr < minCornerClr) minCornerClr = clr; + } + } + if (minCornerClr < 0.25f) + { + spawnY += MathF.Min(1.2f, 0.25f - minCornerClr); + } + } + c.Y = spawnY; + } + + var handle = _world.AddBox( + stableId, + (c.X, spawnY, c.Z), + (spec.HalfWidth, physHalfH, spec.HalfLength), + density, + (q.X, q.Y, q.Z, q.W), + friction: 0.2f, + restitution: 0.1f); + + _contenderBodies[c.Id] = handle; + _entityByStableId[stableId] = (true, c.Id); + c.CurrRotX = q.X; + c.CurrRotY = q.Y; + c.CurrRotZ = q.Z; + c.CurrRotW = q.W; + c.VelX = 0f; + c.VelY = initVelY; + c.VelZ = 0f; + if (MathF.Abs(initVelY) > 1e-3f) + { + float mass = _world.View.Mass[handle.Lane]; + if (mass > 0f) + { + _world.ApplyImpulse(handle.Lane, (0f, initVelY * mass, 0f), (c.X, spawnY, c.Z)); + } + } + c.SnapPreviousPose(); + c.ResetAimTracker(c.Yaw); + + if (spec.IsWalker) + { + var ws = new WalkerState(spec); + ws.InitializePose(new Vector3(c.X, spawnY, c.Z), q, spec.MassKg, State.Terrain); + _contenderWalkers[c.Id] = ws; + } + else + { + _contenderWalkers.Remove(c.Id); + } + } + + private void OnContenderChassisSwapped(ContenderState c) + { + c.HasTouchdownPose = false; + c.TouchdownOnRoof = false; + if (_contenderBodies.TryGetValue(c.Id, out var oldHandle)) + { + _world.RemoveBody(oldHandle); + _contenderBodies.Remove(c.Id); + } + _contenderWalkers.Remove(c.Id); + if (c.IsGroundedActive) + { + SpawnContenderBody(c); + } + else + { + c.SnapPreviousPose(); + c.ResetAimTracker(c.Yaw); + } + } + + private void SpawnSpectatorBodies() + { + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + SpawnSpectatorBody(i, State.Spectators.Spectators[i]); + } + } + + private void SpawnSpectatorBody(int index, SpectatorState s) + { + var spec = s.Grid.Spec; + float physHalfH = GetPhysicsHalfHeight(spec); + float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength; + float density = spec.MassKg / MathF.Max(0.1f, volume); + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, s.Yaw); + ulong stableId = SpectatorStableIdBase + (ulong)s.Id; + float spawnY = State.Terrain.SampleHeight(s.X, s.Z) + spec.HalfHeight + 0.15f; + s.Y = spawnY; + + var handle = _world.AddBox( + stableId, + (s.X, spawnY, s.Z), + (spec.HalfWidth, physHalfH, spec.HalfLength), + density, + (q.X, q.Y, q.Z, q.W), + friction: 0.2f, + restitution: 0.1f); + + _spectatorBodies[s.Id] = handle; + _entityByStableId[stableId] = (false, index); + s.CurrRotX = q.X; + s.CurrRotY = q.Y; + s.CurrRotZ = q.Z; + s.CurrRotW = q.W; + s.VelX = 0f; + s.VelY = 0f; + s.VelZ = 0f; + s.SnapPreviousPose(); + s.ResetAimTracker(s.Yaw); + + if (spec.IsWalker) + { + var ws = new WalkerState(spec); + ws.InitializePose(new Vector3(s.X, spawnY, s.Z), q, spec.MassKg, State.Terrain); + _spectatorWalkers[s.Id] = ws; + } + else + { + _spectatorWalkers.Remove(s.Id); + } + } + + private void UpdateRingClearance() + { + Span contacts = stackalloc RingContact[State.Contenders.Count]; + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + contacts[i] = new RingContact(c.Id, c.X, c.Z, c.IsGroundedActive, c.Y, c.Grid.Spec.HalfHeight); + } + State.Spectators.UpdateClearance(contacts, FixedDt, HasSpectatorLos); + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (s.Alive && s.Stance != SpectatorStance.Neutral && !s.BroadcastWakeupEmitted && s.TargetContenderId.HasValue) + { + s.BroadcastWakeupEmitted = true; + if (s.Stance == SpectatorStance.Provoked) + { + if (s.Tier == SpectatorTier.Tourist) + { + State.Broadcast.EmitTouristPull(State.Time, s.TargetContenderId.Value); + } + else if (s.Tier == SpectatorTier.Exemplar) + { + State.Broadcast.EmitExemplarWakeup(State.Time, s.TargetContenderId.Value); + } + } + else if (s.Tier == SpectatorTier.Patron) + { + State.Broadcast.EmitPatronClearance(State.Time, s.TargetContenderId.Value); + } + } + else if (s.Stance == SpectatorStance.Neutral) + { + s.BroadcastWakeupEmitted = false; + } + } + } + + private bool HasSpectatorLos(SpectatorState spec, RingContact target) + { + return HasLineOfSight( + spec.X, MatchRules.GetObserverEyeY(spec.Y, spec.Grid.Spec.HalfHeight), spec.Z, + target.X, MatchRules.GetTargetAimY(target.Y, target.HalfHeight), target.Z); + } + + public static void StepContenderPhysicsDrive( + ContenderState c, + Box3DSoaView view, + int lane, + TerrainField terrain, + ArenaMapKind mapKind, + WalkerState? walker, + float dt, + bool injectEngineHeat, + Box3DSoaWorld? world = null) + { + float mass = view.Mass[lane]; + if (mass <= 0f) + { + return; + } + + var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); + var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); + + if (c.Grid.Spec.IsVtol) + { + ApplyVtolFlightDrive(c, lane, mass, pos, q, vel, angVel, view, terrain, dt, injectEngineHeat); + return; + } + + if (c.Grid.Spec.IsWalker && walker is not null) + { + var wFwd = Vector3.Transform(Vector3.UnitZ, q); + wFwd.Y = 0f; + wFwd = wFwd.LengthSquared() < 1e-4f ? Vector3.UnitZ : Vector3.Normalize(wFwd); + float wMaxSpeed = MathF.Max(4f, c.Grid.Spec.MaxSpeed) * c.Grid.LegIntegrity; + Vector3 desiredHorizVel = wFwd * (c.ThrottleCmd * wMaxSpeed); + float wTargetYawVel = -c.SteerCmd * c.Grid.ComputeTurnRate(); + + if (injectEngineHeat && MathF.Abs(c.ThrottleCmd) > 0.05f) + { + for (int m = 0; m < c.Grid.Mounted.Count; m++) + { + var mod = c.Grid.Mounted[m]; + if (mod.Spec.Kind == HardpointKind.Engine && mod.Spec.HeatOutput > 0f) + { + c.Grid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput * MathF.Abs(c.ThrottleCmd) * dt); + } + } + } + + WalkerLocomotion.StepWalker( + walker, c.Grid, terrain, view, lane, mass, + pos, q, vel, angVel, desiredHorizVel, wTargetYawVel, c.BrakeCmd, dt); + return; + } + + ComputeTerrainSupport( + pos, q, vel, angVel, mass, c.Grid.Spec, terrain, mapKind, dt, + out Vector3 supportForce, + out Vector3 supportTorque, + out Vector3 terrainNormal, + out int groundedCorners, + world); + + var forward = Vector3.Transform(Vector3.UnitZ, q); + forward.Y = 0f; + if (forward.LengthSquared() < 1e-4f) forward = Vector3.UnitZ; + else forward = Vector3.Normalize(forward); + + var right = Vector3.Cross(forward, Vector3.UnitY); + var up = Vector3.Transform(Vector3.UnitY, q); + + Vector3 driveForward = forward; + Vector3 driveRight = right; + if (groundedCorners > 0) + { + Vector3 fSlope = forward - terrainNormal * Vector3.Dot(forward, terrainNormal); + if (fSlope.LengthSquared() > 1e-4f) driveForward = Vector3.Normalize(fSlope); + Vector3 rSlope = right - terrainNormal * Vector3.Dot(right, terrainNormal); + if (rSlope.LengthSquared() > 1e-4f) driveRight = Vector3.Normalize(rSlope); + } + + float thrust = c.Grid.ComputeDriveThrust(); + float maxSpeed = MathF.Max(4f, c.Grid.Spec.MaxSpeed); + float forwardSpeed = Vector3.Dot(vel, driveForward); + float lateralSpeed = Vector3.Dot(vel, driveRight); + float gripScale = groundedCorners > 0 ? (0.4f + 0.6f * (groundedCorners / 4f)) : 0.12f; + + Vector3 force = supportForce; + Vector3 effectiveDriveFwd = driveForward; + if (groundedCorners > 0 && terrainNormal.Y < 0.78f) + { + Vector3 cliffHoriz = new Vector3(terrainNormal.X, 0f, terrainNormal.Z); + if (cliffHoriz.LengthSquared() > 1e-4f) + { + cliffHoriz = Vector3.Normalize(cliffHoriz); + float intoCliff = Vector3.Dot(effectiveDriveFwd, cliffHoriz); + if (intoCliff < 0f) + { + effectiveDriveFwd -= cliffHoriz * intoCliff; + effectiveDriveFwd.Y = MathF.Min(effectiveDriveFwd.Y, 0.25f); + } + } + } + force += effectiveDriveFwd * (c.ThrottleCmd * thrust - (thrust / maxSpeed) * forwardSpeed) * gripScale; + force -= driveRight * (lateralSpeed * mass * 8.5f * gripScale); + + if (c.BrakeCmd && groundedCorners > 0) + { + var horizVel = new Vector3(vel.X, 0f, vel.Z); + force -= horizVel * (mass * 7f); + } + + if (injectEngineHeat && MathF.Abs(c.ThrottleCmd) > 0.05f) + { + for (int m = 0; m < c.Grid.Mounted.Count; m++) + { + var mod = c.Grid.Mounted[m]; + if (mod.Spec.Kind == HardpointKind.Engine && mod.Spec.HeatOutput > 0f) + { + c.Grid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput * MathF.Abs(c.ThrottleCmd) * dt); + } + } + } + + float turnRate = c.Grid.ComputeTurnRate(); + float targetYawVel = -c.SteerCmd * turnRate; + float hx = view.Size0[lane]; + float hz = view.Size2[lane]; + float iy = mass * (hx * hx + hz * hz) / 3f; + + Vector3 torque = ComputeRightingTorque(c.Grid.Spec, q, up, angVel, mass, terrainNormal, supportTorque, terrainBlend: 0.85f); + float yawGain = MathF.Abs(targetYawVel) < 1e-3f ? 26f : 16f; + torque.Y = iy * (targetYawVel - angVel.Y) * yawGain; + + view.ForceX[lane] = force.X; + view.ForceY[lane] = force.Y; + view.ForceZ[lane] = force.Z; + view.TorqueX[lane] = torque.X; + view.TorqueY[lane] = torque.Y; + view.TorqueZ[lane] = torque.Z; + } + + private void ApplyPhysicsDrives() + { + var view = _world.View; + + // Contenders + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.IsGroundedActive || !_contenderBodies.TryGetValue(c.Id, out var handle)) + { + continue; + } + + WalkerState? ws = null; + if (c.Grid.Spec.IsWalker && !_contenderWalkers.TryGetValue(c.Id, out ws)) + { + int lane = handle.Lane; + float mass = view.Mass[lane]; + if (mass <= 0f) continue; + ws = new WalkerState(c.Grid.Spec); + ws.InitializePose( + new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]), + new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]), + mass, + State.Terrain); + _contenderWalkers[c.Id] = ws; + } + + StepContenderPhysicsDrive(c, view, handle.Lane, State.Terrain, State.MapKind, ws, FixedDt, injectEngineHeat: true, world: _world); + } + + // Spectators + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive || !_spectatorBodies.TryGetValue(s.Id, out var handle)) + { + continue; + } + + int lane = handle.Lane; + float mass = view.Mass[lane]; + if (mass <= 0f) + { + continue; + } + + MatchRules.ComputeSpectatorBehavior(s, State, out float goalX, out float goalZ, out float aimX, out float aimZ, out _, FixedDt); + + var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); + var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); + var up = Vector3.Transform(Vector3.UnitY, q); + + Vector3 toGoal = new Vector3(goalX - pos.X, 0f, goalZ - pos.Z); + float dist = toGoal.Length(); + + // On Sion, StaticHeightField supports settled Neutral Patrons/Exemplars directly so Box3D can sleep them, + // provided the underlying heightfield tile is currently resident. + if (State.MapKind == ArenaMapKind.Sion && + s.Stance == SpectatorStance.Neutral && + s.Tier != SpectatorTier.Tourist && + dist < 0.9f && + vel.LengthSquared() < 0.16f && + angVel.LengthSquared() < 0.09f && + up.Y > 0.90f) + { + State.Terrain.MapWorldToTile(pos.X, pos.Z, out int stx, out int stz); + if (_tileSync.TryGetResidentHandle(stx, stz, State.Terrain.TileGridCount, out _)) + { + view.ForceX[lane] = 0f; + view.ForceY[lane] = 0f; + view.ForceZ[lane] = 0f; + view.TorqueX[lane] = 0f; + view.TorqueY[lane] = 0f; + view.TorqueZ[lane] = 0f; + continue; + } + } + + Vector3 desiredVel = dist > 0.5f ? Vector3.Normalize(toGoal) * MathF.Min(s.MaxSpeed, dist * 1.5f) : Vector3.Zero; + float desiredYaw = s.Stance == SpectatorStance.Neutral + ? MathF.Atan2(-pos.X, -pos.Z) + : MathF.Atan2(aimX - pos.X, aimZ - pos.Z); + var forward = Vector3.Transform(Vector3.UnitZ, q); + float currentYaw = MathF.Atan2(forward.X, forward.Z); + float yawErr = MatchRules.NormalizeAngle(desiredYaw - currentYaw); + float targetSpecYawVel = Math.Clamp(yawErr * 3f, -5f, 5f); + + if (s.Grid.Spec.IsWalker) + { + if (!_spectatorWalkers.TryGetValue(s.Id, out var ws)) + { + ws = new WalkerState(s.Grid.Spec); + ws.InitializePose(pos, q, mass, State.Terrain); + _spectatorWalkers[s.Id] = ws; + } + + WalkerLocomotion.StepWalker( + ws, s.Grid, State.Terrain, view, lane, mass, + pos, q, vel, angVel, desiredVel, targetSpecYawVel, brakeCmd: false, FixedDt); + continue; + } + + ComputeTerrainSupport( + pos, q, vel, angVel, mass, s.Grid.Spec, State.Terrain, State.MapKind, FixedDt, + out Vector3 supportForce, + out Vector3 supportTorque, + out Vector3 terrainNormal, + out _); + + Vector3 horizVel = new Vector3(vel.X, 0f, vel.Z); + Vector3 force = supportForce + (desiredVel - horizVel) * (mass * 4.5f); + + float hx = view.Size0[lane]; + float hz = view.Size2[lane]; + float iy = mass * (hx * hx + hz * hz) / 3f; + + Vector3 torque = ComputeRightingTorque(s.Grid.Spec, q, up, angVel, mass, terrainNormal, supportTorque, terrainBlend: 0.7f); + torque.Y = iy * (targetSpecYawVel - angVel.Y) * 8f; + + view.ForceX[lane] = force.X; + view.ForceY[lane] = force.Y; + view.ForceZ[lane] = force.Z; + view.TorqueX[lane] = torque.X; + view.TorqueY[lane] = torque.Y; + view.TorqueZ[lane] = torque.Z; + } + } + + private static void ApplyVtolFlightDrive( + ContenderState c, + int lane, + float mass, + Vector3 pos, + Quaternion q, + Vector3 vel, + Vector3 angVel, + Box3DSoaView view, + TerrainField terrain, + float dt, + bool injectEngineHeat) + { + var spec = c.Grid.Spec; + float minAlt = MatchRules.VtolMinClearanceAgl; + float maxAlt = MathF.Max(minAlt, spec.HoverMaxAltitudeM); + const float verticalSpeed = 14f; + float enginePerf = c.Grid.ComputeEngineThermalPerformance(); + c.TargetHoverAltAgl = Math.Clamp(c.TargetHoverAltAgl + c.VerticalThrottleCmd * verticalSpeed * dt, minAlt, maxAlt); + + var forward = Vector3.Transform(Vector3.UnitZ, q); + forward.Y = 0f; + if (forward.LengthSquared() < 1e-4f) forward = Vector3.UnitZ; + else forward = Vector3.Normalize(forward); + var right = Vector3.Cross(forward, Vector3.UnitY); + var up = Vector3.Transform(Vector3.UnitY, q); + + Vector3 horizVel = new Vector3(vel.X, 0f, vel.Z); + float perimDist = MathF.Max(spec.HalfWidth, spec.HalfLength) + 2.5f; + + // Sample terrain at center, 4-point perimeter (HalfLength + 2.5m), and horizontal velocity lookahead (0.20s, 0.35s) + float ghCenter = terrain.SampleHeight(pos.X, pos.Z); + float ghFront = terrain.SampleHeight(pos.X + forward.X * perimDist, pos.Z + forward.Z * perimDist); + float ghBack = terrain.SampleHeight(pos.X - forward.X * perimDist, pos.Z - forward.Z * perimDist); + float ghRight = terrain.SampleHeight(pos.X + right.X * perimDist, pos.Z + right.Z * perimDist); + float ghLeft = terrain.SampleHeight(pos.X - right.X * perimDist, pos.Z - right.Z * perimDist); + float ghLook1 = terrain.SampleHeight(pos.X + horizVel.X * 0.20f, pos.Z + horizVel.Z * 0.20f); + float ghLook2 = terrain.SampleHeight(pos.X + horizVel.X * 0.35f, pos.Z + horizVel.Z * 0.35f); + float ghSafe = MathF.Max( + ghCenter, + MathF.Max( + MathF.Max(ghFront, ghBack), + MathF.Max(MathF.Max(ghRight, ghLeft), MathF.Max(ghLook1, ghLook2)))); + + float ghHullMax = MathF.Max( + ghCenter, + MathF.Max( + MathF.Max( + terrain.SampleHeight(pos.X + forward.X * spec.HalfLength, pos.Z + forward.Z * spec.HalfLength), + terrain.SampleHeight(pos.X - forward.X * spec.HalfLength, pos.Z - forward.Z * spec.HalfLength)), + MathF.Max( + terrain.SampleHeight(pos.X + right.X * spec.HalfWidth, pos.Z + right.Z * spec.HalfWidth), + terrain.SampleHeight(pos.X - right.X * spec.HalfWidth, pos.Z - right.Z * spec.HalfWidth)))); + + var (tnx, tny, tnz) = terrain.SampleNormal(pos.X, pos.Z); + var terrainNormal = new Vector3(tnx, tny, tnz); + + float bottomY = pos.Y - spec.HalfHeight; + float bottomAgl = bottomY - ghHullMax; + float targetCenterY = ghSafe + spec.HalfHeight + c.TargetHoverAltAgl; + float altErr = targetCenterY - pos.Y; + + // Hover lift authority scales with engine thermal performance (overheated 0.00 -> loses climb authority and sinks gently) + float hoverSupportFrac = Math.Clamp(enginePerf / 0.25f, 0f, 1f); + float baseHoverAccel = 20f * (0.85f + 0.15f * hoverSupportFrac); + float altGain = 32f * enginePerf; + float maxEngineLift = mass * (17.5f + 30.5f * enginePerf); + float headroom = MathF.Max(0f, maxAlt - bottomAgl); + float maxSafeClimbVel = MathF.Sqrt(2f * 16f * headroom); + float desiredVelY = 0f; + if (c.VerticalThrottleCmd > 0f && c.TargetHoverAltAgl < maxAlt - 0.05f) + { + desiredVelY = MathF.Min(c.VerticalThrottleCmd * verticalSpeed * enginePerf, maxSafeClimbVel); + } + else if (c.VerticalThrottleCmd < 0f && c.TargetHoverAltAgl > minAlt + 0.05f) + { + desiredVelY = c.VerticalThrottleCmd * verticalSpeed; + } + // Clamp downward hover thrust >= 0 (gravity-only descent — never slam down when flying off a cliff) + float rawHover = mass * (baseHoverAccel + altErr * altGain - (vel.Y - desiredVelY) * 14f); + if (c.VerticalThrottleCmd > 0f && vel.Y > maxSafeClimbVel && bottomAgl > minAlt) + { + rawHover = MathF.Min(rawHover, mass * 16f); + } + float hoverForceY = Math.Clamp(rawHover, 0f, maxEngineLift); + + // Ground-proximity cushion + hard arrest whenever bottom clearance drops below VtolMinClearanceAgl (2.5m) + if (bottomAgl < minAlt) + { + hoverForceY += mass * (minAlt - bottomAgl) * 35f; + if (bottomAgl < 1.2f) + { + hoverForceY += mass * (1.2f - bottomAgl) * 140f; + } + if (vel.Y < 0f) + { + float availDist = MathF.Max(0.15f, bottomAgl - 0.65f); + float reqDecel = (vel.Y * vel.Y) / (2f * availDist) + 20f; + float arrestAccel = MathF.Min(reqDecel, (-vel.Y / dt) + 20f); + hoverForceY += mass * arrestAccel; + } + } + + float thrust = c.Grid.ComputeDriveThrust(); + float maxSpeed = MathF.Max(6f, spec.MaxSpeed); + float forwardSpeed = Vector3.Dot(horizVel, forward); + float lateralSpeed = Vector3.Dot(horizVel, right); + + Vector3 force = Vector3.UnitY * hoverForceY; + + // Steep-cliff deflection: never fly through solid terrain walls + float vDotN = Vector3.Dot(vel, terrainNormal); + if (bottomAgl < minAlt && vDotN < 0f) + { + float deflectMag = MathF.Min(-vDotN * mass * 28f, -vDotN * mass / dt); + force += terrainNormal * deflectMag; + } + + // Direction-agnostic cliff-approach braking (protects forward, reverse, and strafing into steep mesas) + float ghLookMax = MathF.Max(ghLook1, ghLook2); + float lookClearance = bottomY - ghLookMax; + Vector3 driveForce = forward * (c.ThrottleCmd * thrust) - forward * ((thrust / maxSpeed) * forwardSpeed); + + if (ghLookMax > ghCenter + 0.8f && lookClearance < minAlt + 2.0f) + { + float brakeFrac = Math.Clamp(((minAlt + 2.0f) - lookClearance) / 4.0f, 0f, 1f); + float horizSpeed = horizVel.Length(); + if (horizSpeed > 0.1f) + { + Vector3 horizDir = horizVel / horizSpeed; + float intoLook = Vector3.Dot(driveForce, horizDir); + if (intoLook > 0f) + { + driveForce -= horizDir * (intoLook * brakeFrac * 0.95f); + } + float maxBrake = (horizSpeed * mass) / dt; + float desiredBrake = horizSpeed * mass * 16f * brakeFrac; + force -= horizDir * MathF.Min(desiredBrake, maxBrake); + } + } + + Vector3 cliffPush = Vector3.Zero; + if (ghFront > bottomY - minAlt) cliffPush -= forward * Math.Clamp((ghFront - (bottomY - minAlt)) / 2f, 0f, 1f); + if (ghBack > bottomY - minAlt) cliffPush += forward * Math.Clamp((ghBack - (bottomY - minAlt)) / 2f, 0f, 1f); + if (ghRight > bottomY - minAlt) cliffPush -= right * Math.Clamp((ghRight - (bottomY - minAlt)) / 2f, 0f, 1f); + if (ghLeft > bottomY - minAlt) cliffPush += right * Math.Clamp((ghLeft - (bottomY - minAlt)) / 2f, 0f, 1f); + + if (cliffPush.LengthSquared() > 1e-4f) + { + Vector3 cliffDir = Vector3.Normalize(cliffPush); + float driveIntoCliff = Vector3.Dot(driveForce, cliffDir); + if (driveIntoCliff < 0f) + { + driveForce -= cliffDir * driveIntoCliff; + } + float velIntoCliff = Vector3.Dot(horizVel, cliffDir); + if (velIntoCliff < 0f) + { + float stopMag = MathF.Min(-velIntoCliff * mass * 24f, -velIntoCliff * mass / dt); + force += cliffDir * stopMag; + } + force += cliffDir * (mass * 12f * Math.Clamp(cliffPush.Length(), 0f, 1f)); + } + + force += driveForce; + force -= right * (lateralSpeed * mass * 3.8f); + if (c.BrakeCmd) + { + force -= horizVel * (mass * 3.5f); + } + + // Engine heat from hover lift + horizontal thrust + if (injectEngineHeat) + { + float liftWork = 0.25f + 0.55f * MathF.Abs(c.VerticalThrottleCmd); + float heatFraction = MathF.Max(MathF.Abs(c.ThrottleCmd), liftWork); + for (int m = 0; m < c.Grid.Mounted.Count; m++) + { + var mod = c.Grid.Mounted[m]; + if (mod.Spec.Kind == HardpointKind.Engine && mod.Spec.HeatOutput > 0f) + { + c.Grid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput * heatFraction * dt); + } + } + } + + // Gentle bank-into-turn and subtle nose-down pitch into forward thrust + float speedScale = Math.Clamp(MathF.Abs(forwardSpeed) / MathF.Max(8f, maxSpeed * 0.5f), 0f, 1f); + float bankRad = -c.SteerCmd * speedScale * 0.26f; + float nosePitchRad = c.ThrottleCmd * 0.11f; + Vector3 desiredUp = Vector3.Normalize(Vector3.UnitY + right * MathF.Sin(bankRad) + forward * MathF.Sin(nosePitchRad)); + + Vector3 tiltAxis = Vector3.Cross(up, desiredUp); + float maxFoot = MathF.Max(spec.HalfWidth, spec.HalfLength); + float iTilt = MathF.Max(1f, (spec.HalfHeight * spec.HalfHeight + maxFoot * maxFoot) / 3f); + Vector3 torque = tiltAxis * (mass * 30f * iTilt) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * 9.5f * iTilt); + + float turnRate = c.Grid.ComputeTurnRate(); + float targetYawVel = -c.SteerCmd * turnRate; + float hx = view.Size0[lane]; + float hz = view.Size2[lane]; + float iy = mass * (hx * hx + hz * hz) / 3f; + float yawGain = MathF.Abs(targetYawVel) < 1e-3f ? 26f : 16f; + torque.Y = iy * (targetYawVel - angVel.Y) * yawGain; + + view.ForceX[lane] = force.X; + view.ForceY[lane] = force.Y; + view.ForceZ[lane] = force.Z; + view.TorqueX[lane] = torque.X; + view.TorqueY[lane] = torque.Y; + view.TorqueZ[lane] = torque.Z; + } + + private static Vector3 ComputeRightingTorque( + ChassisSpec spec, + Quaternion q, + Vector3 up, + Vector3 angVel, + float mass, + Vector3 terrainNormal, + Vector3 supportTorque, + float terrainBlend) + { + Vector3 desiredUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, terrainBlend)); + + const float maxDesiredTiltRad = MathF.PI * 38f / 180f; // 38 degrees max slope alignment so cliff walls don't back-flip vehicles + { + float dotY = Math.Clamp(desiredUp.Y, -1f, 1f); + if (MathF.Acos(dotY) > maxDesiredTiltRad) + { + Vector3 horiz = new Vector3(desiredUp.X, 0f, desiredUp.Z); + float hLen = horiz.Length(); + desiredUp = hLen > 1e-4f + ? Vector3.UnitY * MathF.Cos(maxDesiredTiltRad) + (horiz / hLen) * MathF.Sin(maxDesiredTiltRad) + : Vector3.UnitY; + } + } + + float upDot = Vector3.Dot(up, desiredUp); + Vector3 tiltAxis = Vector3.Cross(up, desiredUp); + if (upDot < 0.2f) + { + Vector3 fallbackAxis = Vector3.Transform(Vector3.UnitZ, q); + fallbackAxis.Y = 0f; + fallbackAxis = fallbackAxis.LengthSquared() > 1e-4f + ? Vector3.Normalize(fallbackAxis) + : Vector3.UnitX; + + float axisLen = tiltAxis.Length(); + Vector3 recoveryDir = axisLen > 0.15f ? tiltAxis / axisLen : fallbackAxis; + tiltAxis = recoveryDir * MathF.Max(axisLen, 1.0f); + } + + float maxFoot = MathF.Max(spec.HalfWidth, spec.HalfLength); + float iTilt = MathF.Max(1f, (spec.HalfHeight * spec.HalfHeight + maxFoot * maxFoot) / 3f); + float rightingGain = 28f * iTilt; + float dampingGain = 8.5f * iTilt; + + const float tiltLimitRad = MathF.PI * 48f / 180f; + float worldTiltRad = MathF.Acos(Math.Clamp(up.Y, -1f, 1f)); + Vector3 arrestTorque = Vector3.Zero; + if (worldTiltRad > tiltLimitRad) + { + Vector3 toUpright = Vector3.Cross(up, Vector3.UnitY); + if (toUpright.LengthSquared() > 1e-6f) + { + Vector3 uprightDir = Vector3.Normalize(toUpright); + float supOut = Vector3.Dot(supportTorque, uprightDir); + if (supOut < 0f) + { + supportTorque -= uprightDir * supOut; + } + + float angOut = Vector3.Dot(new Vector3(angVel.X, 0f, angVel.Z), uprightDir); + if (angOut < 0f) + { + arrestTorque = uprightDir * (-angOut * mass * iTilt * 18f); + } + } + + rightingGain *= 1f + (worldTiltRad - tiltLimitRad) * 4f; + } + + return supportTorque + arrestTorque + tiltAxis * (mass * rightingGain) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * dampingGain); + } + + private static void ComputeTerrainSupport( + Vector3 pos, + Quaternion q, + Vector3 vel, + Vector3 angVel, + float mass, + ChassisSpec spec, + TerrainField terrain, + ArenaMapKind mapKind, + float dt, + out Vector3 supportForce, + out Vector3 supportTorque, + out Vector3 terrainNormal, + out int groundedCorners, + Box3DSoaWorld? world = null) + { + supportForce = Vector3.Zero; + supportTorque = Vector3.Zero; + groundedCorners = 0; + + var (nx, ny, nz) = terrain.SampleNormal(pos.X, pos.Z); + terrainNormal = new Vector3(nx, ny, nz); + + bool isSion = mapKind == ArenaMapKind.Sion; + float ghCenterRaw = terrain.SampleHeight(pos.X, pos.Z); + float centerGap = (pos.Y - spec.HalfHeight) - ghCenterRaw; + bool checkRoofSupport = isSion && centerGap > 1.5f && world is not null; + if (checkRoofSupport) + { + var centerRoof = world!.CastRayClosest((pos.X, pos.Y + 0.5f, pos.Z), (0f, -6.0f, 0f)); + if (centerRoof.Hit && centerRoof.StableId >= StaticMeshStableIdBase && centerRoof.StableId < ContenderStableIdBase) + { + ghCenterRaw = MathF.Max(ghCenterRaw, centerRoof.Point.Y); + Vector3 rn = new(centerRoof.Normal.X, centerRoof.Normal.Y, centerRoof.Normal.Z); + if (rn.LengthSquared() > 1e-4f) + { + terrainNormal = Vector3.Normalize(rn); + } + centerGap = (pos.Y - spec.HalfHeight) - ghCenterRaw; + } + else + { + checkRoofSupport = false; + } + } + + // Blend smoothly from pure vertical on flat ground to surface normal on steep mesa/dune slopes + float slopeBlend = Math.Clamp((0.985f - terrainNormal.Y) / 0.18f, 0f, 1f); + Vector3 supportDir = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, slopeBlend)); + float orthoScale = MathF.Max(0.35f, terrainNormal.Y); + + float hx = MathF.Min(spec.HalfWidth * 0.9f, 2.4f); + float hz = MathF.Min(spec.HalfLength * 0.9f, 2.8f); + float bottomY = -spec.HalfHeight; + float restTravel = isSion ? 0.22f : 0.20f; + float kSpring = mass * (isSion ? 95f : 85f); + float cDamp = mass * (isSion ? 12.0f : 10.5f); + float maxPen = 0f; + + Span corners = stackalloc Vector3[4] + { + new Vector3(-hx, bottomY, -hz), + new Vector3( hx, bottomY, -hz), + new Vector3(-hx, bottomY, hz), + new Vector3( hx, bottomY, hz) + }; + + for (int k = 0; k < 4; k++) + { + Vector3 r = Vector3.Transform(corners[k], q); + Vector3 wp = pos + r; + float gh = terrain.SampleHeight(wp.X, wp.Z); + if (checkRoofSupport) + { + var cornerRoof = world!.CastRayClosest((wp.X, pos.Y + 0.5f, wp.Z), (0f, -6.0f, 0f)); + if (cornerRoof.Hit && cornerRoof.StableId >= StaticMeshStableIdBase && cornerRoof.StableId < ContenderStableIdBase) + { + gh = MathF.Max(gh, cornerRoof.Point.Y); + } + } + float pen = (gh + restTravel) - wp.Y; + if (pen > 0f) + { + groundedCorners++; + maxPen = MathF.Max(maxPen, pen); + float vCornerN = Vector3.Dot(vel + Vector3.Cross(angVel, r), supportDir); + float penEff = pen * orthoScale; + float bumpExtra = (!isSion && pen > 0.20f) ? mass * 220f * (pen - 0.20f) : 0f; + float fN = Math.Clamp(kSpring * penEff + bumpExtra - cDamp * vCornerN, 0f, mass * (isSion ? 42f : 65f)); + Vector3 cornerForce = supportDir * fN; + supportForce += cornerForce; + supportTorque += Vector3.Cross(r, cornerForce); + } + } + + // Center skid-plate bump-stop prevents belly clipping when straddling sharp ridge crests at speed + float ghCenter = ghCenterRaw; + float centerPen = (ghCenter + 0.08f) - (pos.Y - spec.HalfHeight); + if (!isSion && centerPen > 0f) + { + groundedCorners = Math.Max(groundedCorners, 1); + maxPen = MathF.Max(maxPen, centerPen); + float vCenterN = Vector3.Dot(vel, supportDir); + float centerExtra = centerPen > 0.20f ? mass * 220f * (centerPen - 0.20f) : 0f; + float fCenter = Math.Clamp(mass * 120f * (centerPen * orthoScale) + centerExtra - mass * 10f * vCenterN, 0f, mass * 65f); + supportForce += supportDir * fCenter; + } + else if (isSion && centerPen > 0f) + { + groundedCorners = Math.Max(groundedCorners, 1); + } + + // Prevent large overhangs from catapulting the chassis when the belly center is already well above ground + if (centerGap > 1.2f && supportForce.Y > 0f) + { + float overhangAtten = Math.Clamp(1f - (centerGap - 1.2f) / 1.8f, 0f, 1f); + supportForce *= overhangAtten; + supportTorque *= overhangAtten; + } + + // Base lift attenuation on normal separation velocity vDotN rather than world vel.Y so steep uphill + // climbs (vDotN <= 0) retain full support while separating crests (vDotN > 2.0) don't sky-launch. + float vDotN = Vector3.Dot(vel, terrainNormal); + float sepScale = vDotN > 2.0f ? Math.Clamp(1f - (vDotN - 2.0f) / 2.0f, 0f, 1f) : 1f; + float maxSpringY = vDotN > 2.0f ? mass * 20f * sepScale : mass * (isSion ? 48f : 75f); + if (supportForce.Y > maxSpringY && supportForce.Y > 1e-4f) + { + supportForce *= maxSpringY / supportForce.Y; + } + + // On Desert (flat safety slab only), arrest inward velocity into sloped terrain. + // On Sion, Ymir's StaticHeightField handles rigid normal contact directly without double-bouncing. + if (!isSion && maxPen > 0f && vDotN < 0f) + { + float deflectMag = MathF.Min(-vDotN * mass * 42f, -vDotN * mass / dt); + supportForce += terrainNormal * deflectMag; + } + } + + public static void SyncContenderPoseFromLane(ContenderState c, Box3DSoaView view, int lane, WalkerState? walker) + { + c.X = view.PositionX[lane]; + c.Y = view.PositionY[lane]; + c.Z = view.PositionZ[lane]; + c.CurrRotX = view.RotationX[lane]; + c.CurrRotY = view.RotationY[lane]; + c.CurrRotZ = view.RotationZ[lane]; + c.CurrRotW = view.RotationW[lane]; + var q = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW); + var forward = Vector3.Transform(Vector3.UnitZ, q); + c.Yaw = MathF.Atan2(forward.X, forward.Z); + float vx = view.VelocityX[lane]; + float vy = view.VelocityY[lane]; + float vz = view.VelocityZ[lane]; + c.VelX = vx; + c.VelY = vy; + c.VelZ = vz; + c.Speed = MathF.Sqrt(vx * vx + vz * vz); + if (walker is not null) + { + walker.SyncBodyPoseOnly(new Vector3(c.X, c.Y, c.Z), Quaternion.Normalize(q), view.Mass[lane]); + } + } + + private void SyncBodiesFromWorld() + { + var view = _world.View; + + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.IsGroundedActive || !_contenderBodies.TryGetValue(c.Id, out var handle)) + { + continue; + } + + int lane = handle.Lane; + float prevX = c.X; + float prevZ = c.Z; + _contenderWalkers.TryGetValue(c.Id, out var ws); + SyncContenderPoseFromLane(c, view, lane, ws); + + float stepDist = MathF.Sqrt((c.X - prevX) * (c.X - prevX) + (c.Z - prevZ) * (c.Z - prevZ)); + float groundY = State.Terrain.SampleHeight(c.X, c.Z); + if (c.Speed > 2.0f && !c.TouchdownOnRoof && c.Y - c.Grid.Spec.HalfHeight <= groundY + 0.65f) + { + _trackDistAccum[i] += stepDist; + if (_trackDistAccum[i] >= 2.2f) + { + _trackDistAccum[i] = 0f; + State.Terrain.StampTrack(c.X, c.Z, c.Yaw, c.Grid.Spec.HalfWidth * 1.4f, 2.5f); + } + } + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive || !_spectatorBodies.TryGetValue(s.Id, out var handle)) + { + continue; + } + + int lane = handle.Lane; + s.X = view.PositionX[lane]; + s.Y = view.PositionY[lane]; + s.Z = view.PositionZ[lane]; + s.CurrRotX = view.RotationX[lane]; + s.CurrRotY = view.RotationY[lane]; + s.CurrRotZ = view.RotationZ[lane]; + s.CurrRotW = view.RotationW[lane]; + s.VelX = view.VelocityX[lane]; + s.VelY = view.VelocityY[lane]; + s.VelZ = view.VelocityZ[lane]; + var q = new Quaternion(s.CurrRotX, s.CurrRotY, s.CurrRotZ, s.CurrRotW); + var forward = Vector3.Transform(Vector3.UnitZ, q); + s.Yaw = MathF.Atan2(forward.X, forward.Z); + if (_spectatorWalkers.TryGetValue(s.Id, out var ws)) + { + ws.SyncBodyPoseOnly(new Vector3(s.X, s.Y, s.Z), Quaternion.Normalize(q), view.Mass[lane]); + } + } + } + + private void UpdateObserverDetectionMemories() + { + for (int h = 0; h < State.Contenders.Count; h++) + { + var obs = State.Contenders[h]; + if (!obs.IsHuman && !State.ObserverStates.ContainsKey(obs.Id)) + { + continue; + } + + var memState = State.GetOrCreateObserverState(obs.Id); + if (!obs.Alive) + { + memState.DetectedByCount = 0; + for (int i = 0; i < State.Contenders.Count; i++) + { + _contenderPvs[obs.Id, i] = i == obs.Id; + if (memState.ContenderContacts.TryGetValue(State.Contenders[i].Id, out var mem)) + { + mem.VisibleToPlayer = false; + mem.FaintHorizonPing = false; + } + } + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + _spectatorPvs[obs.Id, i] = false; + if (memState.SpectatorContacts.TryGetValue(State.Spectators.Spectators[i].Id, out var smem)) + { + smem.VisibleToPlayer = false; + smem.FaintHorizonPing = false; + } + } + continue; + } + + float pEyeY = MatchRules.GetObserverEyeY(obs.Y, obs.Grid.Spec.HalfHeight); + float pTargetY = MatchRules.GetTargetAimY(obs.Y, obs.Grid.Spec.HalfHeight); + int detectedBy = 0; + + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (c.Id == obs.Id) + { + _contenderPvs[obs.Id, i] = true; + continue; + } + + var mem = memState.GetOrCreateContenderContact(c.Id); + if (State.AreAllies(obs.Id, c.Id)) + { + bool allyAlive = c.Alive || c.IsInDropPod; + _contenderPvs[obs.Id, i] = allyAlive; + if (allyAlive) + { + mem.VisibleToPlayer = true; + mem.FaintHorizonPing = false; + mem.LastSeenAge = 0f; + mem.LastSeenX = c.X; + mem.LastSeenZ = c.Z; + mem.HasEverBeenSeen = true; + } + else + { + mem.VisibleToPlayer = false; + mem.FaintHorizonPing = false; + mem.LastSeenAge = float.PositiveInfinity; + } + continue; + } + + if (!c.Alive) + { + mem.VisibleToPlayer = false; + mem.FaintHorizonPing = false; + mem.LastSeenAge = float.PositiveInfinity; + _contenderPvs[obs.Id, i] = false; + continue; + } + + float dxC = c.X - obs.X; + float dzC = c.Z - obs.Z; + float distSqC = dxC * dxC + dzC * dzC; + + bool obsSees = HasLineOfSight( + obs.X, pEyeY, obs.Z, + c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z); + + if (obsSees) + { + mem.VisibleToPlayer = true; + mem.FaintHorizonPing = false; + mem.LastSeenAge = 0f; + mem.LastSeenX = c.X; + mem.LastSeenZ = c.Z; + mem.HasEverBeenSeen = true; + } + else + { + mem.VisibleToPlayer = false; + mem.FaintHorizonPing = false; + if (mem.HasEverBeenSeen) + { + mem.LastSeenAge += FixedDt; + } + } + + _contenderPvs[obs.Id, i] = !EnableNetworkPvs || obsSees || ComputeConservativePvs(obs, pEyeY, c.X, c.Y, c.Z, c.Grid.Spec); + + if (distSqC <= 240f * 240f && + HasLineOfSight(c.X, MatchRules.GetObserverEyeY(c.Y, c.Grid.Spec.HalfHeight), c.Z, obs.X, pTargetY, obs.Z)) + { + detectedBy++; + } + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + var mem = memState.GetOrCreateSpectatorContact(s.Id); + if (!s.Alive) + { + mem.VisibleToPlayer = false; + mem.FaintHorizonPing = false; + mem.LastSeenAge = float.PositiveInfinity; + _spectatorPvs[obs.Id, i] = false; + continue; + } + + float sdx = s.X - obs.X; + float sdz = s.Z - obs.Z; + float sDistSq = sdx * sdx + sdz * sdz; + + bool obsSees = HasLineOfSight( + obs.X, pEyeY, obs.Z, + s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z); + + if (obsSees) + { + mem.VisibleToPlayer = true; + mem.FaintHorizonPing = false; + mem.LastSeenAge = 0f; + mem.LastSeenX = s.X; + mem.LastSeenZ = s.Z; + mem.HasEverBeenSeen = true; + } + else + { + mem.VisibleToPlayer = false; + if (mem.HasEverBeenSeen) + { + mem.LastSeenAge += FixedDt; + } + + bool horizonPing = false; + if (s.RadarSignature >= 0.9f && sDistSq <= MatchState.TouristHorizonMaxRange * MatchState.TouristHorizonMaxRange) + { + horizonPing = HasLineOfSight( + obs.X, pEyeY + 14f, obs.Z, + s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight) + 14f, s.Z); + } + mem.FaintHorizonPing = horizonPing; + } + + _spectatorPvs[obs.Id, i] = !EnableNetworkPvs || + obsSees || + ((s.Stance != SpectatorStance.Neutral || sDistSq <= 260f * 260f) && + ComputeConservativePvs(obs, pEyeY, s.X, s.Y, s.Z, s.Grid.Spec)); + + if (s.Stance != SpectatorStance.Neutral && + s.TargetContenderId == obs.Id && + s.HasTargetLos) + { + detectedBy++; + } + } + + memState.DetectedByCount = detectedBy; + } + } + + private bool ComputeConservativePvs( + ContenderState obs, + float obsEyeY, + float tx, + float ty, + float tz, + ChassisSpec targetSpec) + { + float aimY = MatchRules.GetTargetAimY(ty, targetSpec.HalfHeight); + if (HasLineOfSight(obs.X, obsEyeY + 1.0f, obs.Z, tx, aimY, tz)) + { + return true; + } + + float dx = tx - obs.X; + float dz = tz - obs.Z; + float len = MathF.Sqrt(dx * dx + dz * dz); + if (len > 1f) + { + float sideX = (-dz / len) * MathF.Max(1.0f, targetSpec.HalfWidth * 0.85f); + float sideZ = (dx / len) * MathF.Max(1.0f, targetSpec.HalfWidth * 0.85f); + if (HasLineOfSight(obs.X, obsEyeY, obs.Z, tx + sideX, aimY, tz + sideZ) || + HasLineOfSight(obs.X, obsEyeY, obs.Z, tx - sideX, aimY, tz - sideZ)) + { + return true; + } + } + + return false; + } + + private void StepThermalAndCooldowns() + { + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.IsGroundedActive) + { + continue; + } + + c.Grid.StepHeat(FixedDt); + bool anyOverheat = false; + for (int m = 0; m < c.Grid.Mounted.Count; m++) + { + var mod = c.Grid.Mounted[m]; + if (mod.Cooldown > 0f) + { + mod.Cooldown = MathF.Max(0f, mod.Cooldown - FixedDt); + } + if (mod.CurrentTemp > mod.Spec.OptimalTemp + mod.Spec.PlateauWidth * 0.6f) + { + anyOverheat = true; + } + } + + c.MaxThermalRatio = c.Grid.ComputeMaxThermalRatio(); + + if (anyOverheat && !c.OverheatWarned) + { + c.OverheatWarned = true; + State.Broadcast.EmitOverheat(State.Time, c.Id); + _stepEvents.Add(new OverheatAlertEvent { ContenderId = c.Id, IsOverheating = true }); + } + else if (!anyOverheat && c.OverheatWarned) + { + c.OverheatWarned = false; + _stepEvents.Add(new OverheatAlertEvent { ContenderId = c.Id, IsOverheating = false }); + } + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive) + { + continue; + } + + s.Grid.StepHeat(FixedDt); + for (int m = 0; m < s.Grid.Mounted.Count; m++) + { + if (s.Grid.Mounted[m].Cooldown > 0f) + { + s.Grid.Mounted[m].Cooldown = MathF.Max(0f, s.Grid.Mounted[m].Cooldown - FixedDt); + } + } + } + } + + private void ProcessWeapons() + { + var view = _world.View; + + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.IsGroundedActive || !_contenderBodies.TryGetValue(c.Id, out var handle)) + { + continue; + } + + int lane = handle.Lane; + var shooterQuat = new Quaternion( + view.RotationX[lane], + view.RotationY[lane], + view.RotationZ[lane], + view.RotationW[lane]); + ulong shooterStableId = ContenderStableIdBase + (ulong)c.Id; + + if (c.IsHuman) + { + UpdateWeaponArcTelemetry(c, shooterQuat, shooterStableId); + } + + if (c.FireCmd) + { + FireMountedWeapons( + shooterStableId, + shooterContender: c, + shooterLabel: c.Name, + isSpectatorShooter: false, + shooterGrid: c.Grid, + shooterPos: new Vector3(c.X, c.Y, c.Z), + shooterYaw: c.Yaw, + shooterQuat: shooterQuat, + aimX: c.AimX, + aimY: c.AimY, + aimZ: c.AimZ, + extraSpread: c.IsHuman ? 0f : c.AiAimSpreadRad, + view: view); + } + + if (!c.Grid.Spec.IsVtol) + { + TryAutoPointDefenseFire(c, shooterStableId, shooterQuat, view); + } + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive || s.Stance == SpectatorStance.Neutral || !s.FireCmd || !_spectatorBodies.TryGetValue(s.Id, out var specHandle)) + { + continue; + } + + int lane = specHandle.Lane; + var specQuat = new Quaternion( + view.RotationX[lane], + view.RotationY[lane], + view.RotationZ[lane], + view.RotationW[lane]); + ulong shooterStableId = SpectatorStableIdBase + (ulong)s.Id; + FireMountedWeapons( + shooterStableId, + shooterContender: null, + shooterLabel: $"{s.Tier} Spectator", + isSpectatorShooter: true, + shooterGrid: s.Grid, + shooterPos: new Vector3(s.X, s.Y, s.Z), + shooterYaw: s.Yaw, + shooterQuat: specQuat, + aimX: s.AimX, + aimY: s.AimY, + aimZ: s.AimZ, + extraSpread: s.AimSpreadRad + s.DynamicAimSpreadRad, + view: view); + } + + Ordnance.Step(FixedDt); + _ordnanceNetScratch.Clear(); + Ordnance.DrainNetEvents(_ordnanceNetScratch); + for (int i = 0; i < _ordnanceNetScratch.Count; i++) + { + var ev = _ordnanceNetScratch[i]; + _stepEvents.Add(new OrdnanceNodeEvent + { + OrdnanceId = ev.OrdnanceId, + ParentOrdnanceId = ev.ParentOrdnanceId, + Kind = (byte)ev.Kind, + IsSpectatorShooter = ev.IsSpectatorShooter, + ShooterId = ev.ShooterEntityId, + WeaponKey = ev.WeaponKey, + NodeDefIndex = ev.NodeDefIndex, + PosX = ev.Pos.X, + PosY = ev.Pos.Y, + PosZ = ev.Pos.Z, + VelX = ev.Vel.X, + VelY = ev.Vel.Y, + VelZ = ev.Vel.Z, + TargetEntityId = ev.TargetEntityId, + TargetIsSpectator = ev.TargetIsSpectator, + SimTime = ev.SimTime, + VisualShape = ev.VisualShape, + ColorRgba = ev.ColorRgba + }); + } + } + + private void UpdateWeaponArcTelemetry(ContenderState c, Quaternion shooterQuat, ulong shooterStableId) + { + float targetY = !float.IsNaN(c.AimY) ? c.AimY : ResolveAimTargetY(c.AimX, c.AimZ, shooterStableId); + var shooterPos = new Vector3(c.X, c.Y, c.Z); + int inArc = 0; + int outArc = 0; + int disabled = 0; + + for (int m = 0; m < c.Grid.Mounted.Count; m++) + { + var mod = c.Grid.Mounted[m]; + if (mod.Spec.Kind != HardpointKind.Weapon) + { + continue; + } + + var hp = c.Grid.FindHardpoint(mod.HardpointId); + if (hp is null) + { + continue; + } + + if (!c.Grid.IsHardpointOperational(hp)) + { + disabled++; + continue; + } + + Vector3 muzzle = ComputeWeaponMuzzle(shooterPos, c.Yaw, c.Grid.Spec, c.AimX, c.AimZ); + Vector3 aimDelta = new Vector3(c.AimX - muzzle.X, targetY - muzzle.Y, c.AimZ - muzzle.Z); + float pitchDeg = MatchRules.ComputeLocalPitchDeg(aimDelta, shooterQuat); + var (minPitch, maxPitch) = MatchRules.GetEffectivePitchArc(hp, mod.Spec); + if (pitchDeg >= minPitch && pitchDeg <= maxPitch) + { + inArc++; + } + else + { + outArc++; + } + } + + c.InArcWeaponCount = inArc; + c.OutOfArcWeaponCount = outArc; + c.DisabledWeaponCount = disabled; + c.AllWeaponsOutOfArc = outArc > 0 && inArc == 0; + } + + private void TryAutoPointDefenseFire( + ContenderState shooter, + ulong shooterStableId, + Quaternion shooterQuat, + Box3DSoaView view) + { + const float maxPdTrackRange = 140f; + var shooterPos = new Vector3(shooter.X, shooter.Y, shooter.Z); + + for (int m = 0; m < shooter.Grid.Mounted.Count; m++) + { + var mod = shooter.Grid.Mounted[m]; + if (mod.Spec.Kind != HardpointKind.Weapon || + !mod.Spec.IsWideArc || + mod.Cooldown > 0f || + mod.CurrentPerformance <= 0.05f) + { + continue; + } + + // Avoid self-cooking on auto-PD if close to thermal ceiling + if (mod.CurrentTemp > mod.Spec.OptimalTemp + mod.Spec.PlateauWidth * 0.45f) + { + continue; + } + + var hp = shooter.Grid.FindHardpoint(mod.HardpointId); + if (hp is null || !shooter.Grid.IsHardpointOperational(hp)) + { + continue; + } + + var (minPitch, maxPitch) = MatchRules.GetEffectivePitchArc(hp, mod.Spec); + float range = MathF.Min(maxPdTrackRange, MathF.Max(5f, mod.Spec.WeaponRange)); + float rangeSq = range * range; + + ContenderState? bestVtol = null; + float bestDistSq = rangeSq; + + for (int j = 0; j < State.Contenders.Count; j++) + { + var other = State.Contenders[j]; + if (other.Id == shooter.Id || State.AreAllies(shooter.Id, other.Id) || !other.IsGroundedActive || !other.Grid.Spec.IsVtol) + { + continue; + } + + float groundH = State.Terrain.SampleHeight(other.X, other.Z); + float agl = (other.Y - other.Grid.Spec.HalfHeight) - groundH; + if (agl <= 2.0f) + { + continue; + } + + float targetY = MatchRules.GetTargetAimY(other.Y, other.Grid.Spec.HalfHeight); + Vector3 muzzle = ComputeWeaponMuzzle(shooterPos, shooter.Yaw, shooter.Grid.Spec, other.X, other.Z); + Vector3 delta = new Vector3(other.X - muzzle.X, targetY - muzzle.Y, other.Z - muzzle.Z); + float d2 = delta.LengthSquared(); + if (d2 > bestDistSq) + { + continue; + } + + float pitchDeg = MatchRules.ComputeLocalPitchDeg(delta, shooterQuat); + if (pitchDeg < minPitch || pitchDeg > maxPitch) + { + continue; + } + + if (!HasLineOfSight(muzzle.X, muzzle.Y, muzzle.Z, other.X, targetY, other.Z)) + { + continue; + } + + bestDistSq = d2; + bestVtol = other; + } + + if (bestVtol is not null) + { + float aimY = MatchRules.GetTargetAimY(bestVtol.Y, bestVtol.Grid.Spec.HalfHeight); + FireSingleWeapon( + mod, + shooterStableId, + shooter, + shooter.Name, + isSpectatorShooter: false, + shooter.Grid, + shooterPos, + shooter.Yaw, + shooterQuat, + bestVtol.X, + aimY, + bestVtol.Z, + extraSpread: 0f, + view: view); + } + else + { + Vector3 pdMuzzle = ComputeWeaponMuzzle(shooterPos, shooter.Yaw, shooter.Grid.Spec, shooterPos.X, shooterPos.Z + 10f); + if (Ordnance.TryFindBestHostileAirborneOrdnance( + pdMuzzle, + shooterStableId, + shooterQuat, + minPitch, + maxPitch, + range, + out _, + out Vector3 ordPos)) + { + FireSingleWeapon( + mod, + shooterStableId, + shooter, + shooter.Name, + isSpectatorShooter: false, + shooter.Grid, + shooterPos, + shooter.Yaw, + shooterQuat, + ordPos.X, + ordPos.Y, + ordPos.Z, + extraSpread: 0f, + view: view); + } + } + } + } + + private void FireMountedWeapons( + ulong shooterStableId, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + ChassisGrid shooterGrid, + Vector3 shooterPos, + float shooterYaw, + Quaternion shooterQuat, + float aimX, + float aimY, + float aimZ, + float extraSpread, + Box3DSoaView view) + { + float targetY = !float.IsNaN(aimY) ? aimY : ResolveAimTargetY(aimX, aimZ, shooterStableId); + + for (int m = 0; m < shooterGrid.Mounted.Count; m++) + { + var mod = shooterGrid.Mounted[m]; + var hp = shooterGrid.FindHardpoint(mod.HardpointId); + if (mod.Spec.Kind != HardpointKind.Weapon || + mod.Cooldown > 0f || + mod.CurrentPerformance <= 0.05f || + hp is null || + !shooterGrid.IsHardpointOperational(hp)) + { + continue; + } + + FireSingleWeapon( + mod, + shooterStableId, + shooterContender, + shooterLabel, + isSpectatorShooter, + shooterGrid, + shooterPos, + shooterYaw, + shooterQuat, + aimX, + targetY, + aimZ, + extraSpread, + view); + } + } + + private static Vector3 ComputeWeaponMuzzle( + Vector3 shooterPos, + float shooterYaw, + ChassisSpec spec, + float aimX, + float aimZ) + { + Vector3 aimFromCenter = new Vector3(aimX - shooterPos.X, 0f, aimZ - shooterPos.Z); + float aimLen = aimFromCenter.Length(); + Vector3 horizDir = aimLen < 1e-3f + ? new Vector3(MathF.Sin(shooterYaw), 0f, MathF.Cos(shooterYaw)) + : aimFromCenter / aimLen; + + float cosYaw = MathF.Cos(shooterYaw); + float sinYaw = MathF.Sin(shooterYaw); + float localDirX = horizDir.X * cosYaw - horizDir.Z * sinYaw; + float localDirZ = horizDir.X * sinYaw + horizDir.Z * cosYaw; + float clearance = + MathF.Abs(localDirX) * spec.HalfWidth + + MathF.Abs(localDirZ) * spec.HalfLength + + 0.35f; + + float muzzleClearance = aimLen < clearance + 0.45f + ? MathF.Min(clearance, MathF.Max(0.25f, aimLen - 0.45f)) + : clearance; + + return new Vector3( + shooterPos.X + horizDir.X * muzzleClearance, + shooterPos.Y + spec.HalfHeight * 0.25f, + shooterPos.Z + horizDir.Z * muzzleClearance); + } + + private void FireSingleWeapon( + MountedModule mod, + ulong shooterStableId, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + ChassisGrid shooterGrid, + Vector3 shooterPos, + float shooterYaw, + Quaternion shooterQuat, + float aimX, + float targetY, + float aimZ, + float extraSpread, + Box3DSoaView view) + { + var hp = shooterGrid.FindHardpoint(mod.HardpointId); + Vector3 muzzle = ComputeWeaponMuzzle(shooterPos, shooterYaw, shooterGrid.Spec, aimX, aimZ); + Vector3 aimDelta = new Vector3(aimX - muzzle.X, targetY - muzzle.Y, aimZ - muzzle.Z); + if (hp is not null) + { + float pitchDeg = MatchRules.ComputeLocalPitchDeg(aimDelta, shooterQuat); + var (minPitch, maxPitch) = MatchRules.GetEffectivePitchArc(hp, mod.Spec); + if (pitchDeg < minPitch || pitchDeg > maxPitch) + { + return; + } + } + + Vector3 baseAim = aimDelta.LengthSquared() < 1e-4f + ? Vector3.UnitZ + : Vector3.Normalize(aimDelta); + + float totalSpread = mod.Spec.SpreadRad + extraSpread; + float aimDist = aimDelta.Length(); + OrdnanceNodeDef rootDef = OrdnanceCatalogMapper.ResolveRoot(mod.Spec); + ulong targetStableId = ResolveTargetEntityStableId(aimX, targetY, aimZ, shooterStableId); + int shooterEntityId = isSpectatorShooter + ? (int)(shooterStableId - SpectatorStableIdBase) + : (shooterContender?.Id ?? -1); + + Ordnance.FireWeapon(new OrdnanceFireRequest( + Module: mod, + ShooterStableId: shooterStableId, + ShooterContender: shooterContender, + ShooterLabel: shooterLabel, + IsSpectatorShooter: isSpectatorShooter, + ShooterEntityId: shooterEntityId, + ShooterPos: shooterPos, + MuzzlePos: muzzle, + AimDir: baseAim, + AimDist: aimDist, + SpreadRad: totalSpread, + TargetEntityStableId: targetStableId, + RootDef: rootDef, + WeaponKey: mod.Spec.Procedural?.Key)); + + shooterGrid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput); + mod.Cooldown = mod.Spec.FireCooldown; + + if (shooterGrid.Spec.IsWalker) + { + bool isContenderShooter = !isSpectatorShooter; + int entityId = (int)(shooterStableId - (isContenderShooter ? ContenderStableIdBase : SpectatorStableIdBase)); + float recoilScale = mod.Spec.Procedural?.RecoilMultiplier ?? 1f; + AddWalkerRecoilImpulse(isContenderShooter, entityId, baseAim, mod.Spec.WeaponDamage * recoilScale); + } + + if (shooterContender is not null) + { + State.LastGunfireX = shooterPos.X; + State.LastGunfireZ = shooterPos.Z; + State.LastGunfireTime = State.Time; + } + } + + private ulong ResolveTargetEntityStableId(float aimX, float aimY, float aimZ, ulong shooterStableId) + { + const float maxLockRadiusSq = 10f * 10f; + float bestDistSq = maxLockRadiusSq; + ulong bestId = 0; + + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.IsGroundedActive) + { + continue; + } + ulong stable = ContenderStableIdBase + (ulong)c.Id; + if (stable == shooterStableId) + { + continue; + } + if (shooterStableId >= ContenderStableIdBase && shooterStableId < SpectatorStableIdBase) + { + int shooterCid = (int)(shooterStableId - ContenderStableIdBase); + if (State.AreAllies(shooterCid, c.Id)) + { + continue; + } + } + float dx = c.X - aimX; + float dy = c.Y - aimY; + float dz = c.Z - aimZ; + float d2 = dx * dx + dy * dy + dz * dz; + if (d2 < bestDistSq) + { + bestDistSq = d2; + bestId = stable; + } + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive || s.Stance == SpectatorStance.Neutral) + { + continue; + } + ulong stable = SpectatorStableIdBase + (ulong)s.Id; + if (stable == shooterStableId) + { + continue; + } + float dx = s.X - aimX; + float dy = s.Y - aimY; + float dz = s.Z - aimZ; + float d2 = dx * dx + dy * dy + dz * dz; + if (d2 < bestDistSq) + { + bestDistSq = d2; + bestId = stable; + } + } + + return bestId; + } + + private void ApplyHitToTarget( + (bool IsContender, int Index) targetRef, + (float X, float Y, float Z) hitPoint, + Vector3 shotDir, + Vector3 shooterPos, + WeaponVisualClass weaponClass, + string weaponId, + bool isPdFlak, + float damage, + float heatTransfer, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + int shooterEntityId, + Box3DSoaView view) + { + if (targetRef.IsContender) + { + var target = State.Contenders[targetRef.Index]; + if (shooterContender is not null && shooterContender.Id != target.Id && State.AreAllies(shooterContender.Id, target.Id)) + { + return; + } + if (!target.IsGroundedActive || !_contenderBodies.TryGetValue(target.Id, out var body)) + { + return; + } + + var (localRight, localForward, localHeightNorm) = ComputeLocalHitCoords(hitPoint, body.Lane, target.Grid.Spec, view); + Vector3 hitNormal = ComputeBoxFaceNormal(hitPoint, body.Lane, target.Grid.Spec, view, -shotDir); + var result = target.Grid.ApplyHit(localRight, localForward, localHeightNorm, damage, heatTransfer); + target.DamageVersion++; + long hitId = State.AllocateHitEventId(); + State.HitEvents.Add(new HitFeedbackEvent( + EventId: hitId, + HitX: hitPoint.X, + HitY: hitPoint.Y, + HitZ: hitPoint.Z, + NormalX: hitNormal.X, + NormalY: hitNormal.Y, + NormalZ: hitNormal.Z, + SourceX: shooterPos.X, + SourceY: shooterPos.Y, + SourceZ: shooterPos.Z, + TargetKind: HitTargetKind.Contender, + TargetId: target.Id, + CellX: result.CellX, + CellY: result.CellY, + WeaponClass: weaponClass, + WeaponId: weaponId, + IsAirburst: isPdFlak && target.Grid.Spec.IsVtol, + Ttl: 0.35f)); + + _stepEvents.Add(new HitImpactEvent + { + EventId = hitId, + HitX = hitPoint.X, HitY = hitPoint.Y, HitZ = hitPoint.Z, + NormalX = hitNormal.X, NormalY = hitNormal.Y, NormalZ = hitNormal.Z, + SourceX = shooterPos.X, SourceY = shooterPos.Y, SourceZ = shooterPos.Z, + TargetKind = (byte)HitTargetKind.Contender, + TargetId = target.Id, + CellX = result.CellX, + CellY = result.CellY, + WeaponClass = (byte)weaponClass, + WeaponId = weaponId, + IsAirburst = isPdFlak && target.Grid.Spec.IsVtol, + Ttl = 0.35f, + NewCellArmor = target.Grid.Armor[result.CellX, result.CellY], + NewCellTemp = target.Grid.Temperature[result.CellX, result.CellY], + NewCoreHp = target.Grid.CoreHp, + HitSequence = target.Grid.HitSequence, + ShooterId = shooterEntityId, + IsContenderShooter = !isSpectatorShooter, + ArmorDamage = result.ArmorDamage, + CoreDamage = result.CoreDamage, + Killed = result.CoreDestroyed + }); + + if (result.CoreDestroyed) + { + HandleContenderEliminated(target, shooterContender, shooterEntityId, shooterLabel, isSpectatorShooter); + } + } + else + { + var spec = State.Spectators.Spectators[targetRef.Index]; + if (!spec.Alive || !_spectatorBodies.TryGetValue(spec.Id, out var body)) + { + return; + } + + if (shooterContender is not null) + { + float inDx = shooterContender.X - hitPoint.X; + float inDz = shooterContender.Z - hitPoint.Z; + float inLen = MathF.Sqrt(inDx * inDx + inDz * inDz); + float? inDirX = inLen > 1e-3f ? inDx / inLen : null; + float? inDirZ = inLen > 1e-3f ? inDz / inLen : null; + + bool newlyProvoked = State.Spectators.OnSpectatorDamaged(spec, shooterContender.Id, inDirX, inDirZ); + if (newlyProvoked) + { + spec.BroadcastWakeupEmitted = true; + if (spec.Tier == SpectatorTier.Tourist) + { + State.Broadcast.EmitTouristPull(State.Time, shooterContender.Id); + } + else if (spec.Tier == SpectatorTier.Exemplar) + { + State.Broadcast.EmitExemplarWakeup(State.Time, shooterContender.Id); + } + } + } + + var (localRight, localForward, localHeightNorm) = ComputeLocalHitCoords(hitPoint, body.Lane, spec.Grid.Spec, view); + Vector3 hitNormal = ComputeBoxFaceNormal(hitPoint, body.Lane, spec.Grid.Spec, view, -shotDir); + var result = spec.Grid.ApplyHit(localRight, localForward, localHeightNorm, damage, heatTransfer); + long hitId = State.AllocateHitEventId(); + State.HitEvents.Add(new HitFeedbackEvent( + EventId: hitId, + HitX: hitPoint.X, + HitY: hitPoint.Y, + HitZ: hitPoint.Z, + NormalX: hitNormal.X, + NormalY: hitNormal.Y, + NormalZ: hitNormal.Z, + SourceX: shooterPos.X, + SourceY: shooterPos.Y, + SourceZ: shooterPos.Z, + TargetKind: HitTargetKind.Spectator, + TargetId: spec.Id, + CellX: result.CellX, + CellY: result.CellY, + WeaponClass: weaponClass, + WeaponId: weaponId, + IsAirburst: isPdFlak && spec.Grid.Spec.IsVtol, + Ttl: 0.35f)); + + _stepEvents.Add(new HitImpactEvent + { + EventId = hitId, + HitX = hitPoint.X, HitY = hitPoint.Y, HitZ = hitPoint.Z, + NormalX = hitNormal.X, NormalY = hitNormal.Y, NormalZ = hitNormal.Z, + SourceX = shooterPos.X, SourceY = shooterPos.Y, SourceZ = shooterPos.Z, + TargetKind = (byte)HitTargetKind.Spectator, + TargetId = spec.Id, + CellX = result.CellX, + CellY = result.CellY, + WeaponClass = (byte)weaponClass, + WeaponId = weaponId, + IsAirburst = isPdFlak && spec.Grid.Spec.IsVtol, + Ttl = 0.35f, + NewCellArmor = spec.Grid.Armor[result.CellX, result.CellY], + NewCellTemp = spec.Grid.Temperature[result.CellX, result.CellY], + NewCoreHp = spec.Grid.CoreHp, + HitSequence = spec.Grid.HitSequence, + ShooterId = shooterEntityId, + IsContenderShooter = !isSpectatorShooter, + ArmorDamage = result.ArmorDamage, + CoreDamage = result.CoreDamage, + Killed = result.CoreDestroyed + }); + + if (result.CoreDestroyed) + { + HandleSpectatorDestroyed(spec, shooterContender, shooterLabel); + } + } + } + + public void ForceEliminateContender(int contenderId, ContenderState? killer = null) + { + if (contenderId < 0 || contenderId >= State.Contenders.Count) + { + return; + } + var victim = State.Contenders[contenderId]; + if (!victim.IsGroundedActive && !victim.IsInDropPod) + { + return; + } + victim.Grid.ApplyHit(0f, 0f, 0.5f, 50000f, 0f); + HandleContenderEliminated( + victim, + killer, + killer?.Id ?? -1, + killer?.Name ?? "System", + isSpectatorShooter: false); + } + + private void HandleContenderEliminated( + ContenderState victim, + ContenderState? shooterContender, + int shooterEntityId, + string shooterLabel, + bool isSpectatorShooter) + { + if (_contenderBodies.TryGetValue(victim.Id, out var handle)) + { + _world.RemoveBody(handle); + _contenderBodies.Remove(victim.Id); + } + _contenderWalkers.Remove(victim.Id); + + if (shooterContender is not null) + { + shooterContender.Kills++; + } + + State.SpawnChassisDrop(victim.X, victim.Z, victim.Grid.Spec); + for (int i = 0; i < victim.Grid.Mounted.Count; i++) + { + State.SpawnModuleDrop(victim.X + (i - 1) * 0.9f, victim.Z + 1.2f, victim.Grid.Mounted[i].Spec); + } + + var craterEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = victim.X, Z = victim.Z, Radius = 5.2f, Depth = 1.3f }; + var scorchEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = victim.X, Z = victim.Z, Radius = 6.2f }; + State.ApplyTerrainStamp(craterEv, recordInLedger: true); + State.ApplyTerrainStamp(scorchEv, recordInLedger: true); + State.OrbitalDrop.OnContenderEliminated(victim); + _stepEvents.Add(craterEv); + _stepEvents.Add(scorchEv); + _stepEvents.Add(new ContenderEliminatedEvent + { + VictimId = victim.Id, + KillerId = shooterEntityId, + IsSpectatorKiller = isSpectatorShooter, + KillerKills = shooterContender?.Kills ?? 0, + VictimLifecycleByte = (byte)victim.Lifecycle + }); + State.Broadcast.EmitElimination(State.Time, shooterLabel, victim.Name, isSpectatorShooter); + } + + private void HandleSpectatorDestroyed(SpectatorState spec, ContenderState? shooterContender, string shooterLabel) + { + if (_spectatorBodies.TryGetValue(spec.Id, out var handle)) + { + _world.RemoveBody(handle); + _spectatorBodies.Remove(spec.Id); + } + _spectatorWalkers.Remove(spec.Id); + + if (shooterContender is not null) + { + shooterContender.Kills++; + } + + var drops = SpectatorRing.RollSalvageDrops(spec, State.Rng); + for (int i = 0; i < drops.Count; i++) + { + State.SpawnModuleDrop(spec.X + (i - 0.5f) * 1.1f, spec.Z, drops[i]); + } + + var specCraterEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = spec.X, Z = spec.Z, Radius = 4.5f, Depth = 1.1f }; + var specScorchEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = spec.X, Z = spec.Z, Radius = 5.4f }; + State.ApplyTerrainStamp(specCraterEv, recordInLedger: true); + State.ApplyTerrainStamp(specScorchEv, recordInLedger: true); + _stepEvents.Add(specCraterEv); + _stepEvents.Add(specScorchEv); + _stepEvents.Add(new SpectatorDestroyedEvent + { + SpectatorId = spec.Id, + KillerContenderId = shooterContender?.Id ?? -1, + KillerKills = shooterContender?.Kills ?? 0 + }); + State.Broadcast.EmitElimination(State.Time, shooterLabel, $"{spec.Tier} Spectator", false); + } + + bool IOrdnanceTargetSink.TryResolveActor(ulong stableId, out bool isContender, out int index) + { + if (_entityByStableId.TryGetValue(stableId, out var entry)) + { + isContender = entry.IsContender; + index = entry.Index; + return true; + } + isContender = false; + index = -1; + return false; + } + + Vector3 IOrdnanceTargetSink.GetActorAimPosition(bool isContender, int index) + { + if (isContender) + { + var c = State.Contenders[index]; + return new Vector3(c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z); + } + var s = State.Spectators.Spectators[index]; + return new Vector3(s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z); + } + + void IOrdnanceTargetSink.ApplyDirectHit( + ulong targetStableId, + (float X, float Y, float Z) hitPoint, + Vector3 shotDir, + Vector3 shooterPos, + WeaponVisualClass weaponClass, + string weaponId, + bool isAirburst, + float damage, + float heatTransfer, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + int shooterEntityId) + { + if (!_entityByStableId.TryGetValue(targetStableId, out var targetRef)) + { + return; + } + ApplyHitToTarget( + targetRef, + hitPoint, + shotDir, + shooterPos, + weaponClass, + weaponId, + isAirburst, + damage, + heatTransfer, + shooterContender, + shooterLabel, + isSpectatorShooter, + shooterEntityId, + _world.View); + } + + void IOrdnanceTargetSink.ApplySplashDamage( + Vector3 center, + float radius, + float splashDamage, + float heatTransfer, + WeaponVisualClass weaponClass, + string weaponId, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + int shooterEntityId, + ulong ignoreStableId) + { + if (radius <= 0.1f || (splashDamage <= 0f && heatTransfer <= 0f)) + { + return; + } + + var view = _world.View; + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.IsGroundedActive) + { + continue; + } + if (shooterContender is not null && shooterContender.Id != c.Id && State.AreAllies(shooterContender.Id, c.Id)) + { + continue; + } + ulong cStable = ContenderStableIdBase + (ulong)c.Id; + if (cStable == ignoreStableId) + { + continue; + } + + Vector3 cPos = new(c.X, c.Y, c.Z); + float bodyPad = MathF.Max(c.Grid.Spec.HalfWidth, c.Grid.Spec.HalfLength); + float rawDist = Vector3.Distance(center, cPos); + float effDist = MathF.Max(0f, rawDist - bodyPad); + if (effDist > radius) + { + continue; + } + + float atten = 1f - 0.55f * Math.Clamp(effDist / radius, 0f, 1f); + Vector3 shotDir = rawDist > 1e-4f ? Vector3.Normalize(cPos - center) : Vector3.UnitY; + Vector3 hitPt = cPos - shotDir * MathF.Min(rawDist, bodyPad * 0.7f); + ApplyHitToTarget( + (true, i), + (hitPt.X, hitPt.Y, hitPt.Z), + shotDir, + center, + weaponClass, + weaponId, + isPdFlak: false, + splashDamage * atten, + heatTransfer * atten, + shooterContender, + shooterLabel, + isSpectatorShooter, + shooterEntityId, + view); + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive) + { + continue; + } + ulong sStable = SpectatorStableIdBase + (ulong)s.Id; + if (sStable == ignoreStableId) + { + continue; + } + + Vector3 sPos = new(s.X, s.Y, s.Z); + float bodyPad = MathF.Max(s.Grid.Spec.HalfWidth, s.Grid.Spec.HalfLength); + float rawDist = Vector3.Distance(center, sPos); + float effDist = MathF.Max(0f, rawDist - bodyPad); + if (effDist > radius) + { + continue; + } + + float atten = 1f - 0.55f * Math.Clamp(effDist / radius, 0f, 1f); + Vector3 shotDir = rawDist > 1e-4f ? Vector3.Normalize(sPos - center) : Vector3.UnitY; + Vector3 hitPt = sPos - shotDir * MathF.Min(rawDist, bodyPad * 0.7f); + ApplyHitToTarget( + (false, i), + (hitPt.X, hitPt.Y, hitPt.Z), + shotDir, + center, + weaponClass, + weaponId, + isPdFlak: false, + splashDamage * atten, + heatTransfer * atten, + shooterContender, + shooterLabel, + isSpectatorShooter, + shooterEntityId, + view); + } + } + + void IOrdnanceTargetSink.EmitTracer( + Vector3 start, + Vector3 end, + uint colorRgba, + float ttl, + WeaponVisualClass weaponClass, + string weaponId, + bool isSpectatorShooter, + int shooterEntityId) + { + int tracerId = State.AllocateTracerId(); + State.Tracers.Add(new TracerEvent( + start.X, start.Y, start.Z, + end.X, end.Y, end.Z, + colorRgba, + ttl, + weaponClass, + weaponId, + tracerId)); + _stepEvents.Add(new ShotFiredEvent + { + TracerId = tracerId, + IsSpectatorShooter = isSpectatorShooter, + ShooterId = shooterEntityId, + StartX = start.X, StartY = start.Y, StartZ = start.Z, + EndX = end.X, EndY = end.Y, EndZ = end.Z, + ColorRgba = colorRgba, + Ttl = ttl, + WeaponClass = (byte)weaponClass, + WeaponId = weaponId + }); + } + + void IOrdnanceTargetSink.EmitNonActorHit( + HitTargetKind targetKind, + int targetId, + Vector3 hitPoint, + Vector3 normal, + Vector3 shooterPos, + WeaponVisualClass weaponClass, + string weaponId, + bool isAirburst, + bool isSpectatorShooter, + int shooterEntityId) + { + long hitId = State.AllocateHitEventId(); + State.HitEvents.Add(new HitFeedbackEvent( + EventId: hitId, + HitX: hitPoint.X, + HitY: hitPoint.Y, + HitZ: hitPoint.Z, + NormalX: normal.X, + NormalY: normal.Y, + NormalZ: normal.Z, + SourceX: shooterPos.X, + SourceY: shooterPos.Y, + SourceZ: shooterPos.Z, + TargetKind: targetKind, + TargetId: targetId, + CellX: 0, + CellY: 0, + WeaponClass: weaponClass, + WeaponId: weaponId, + IsAirburst: isAirburst, + Ttl: 0.35f)); + _stepEvents.Add(new HitImpactEvent + { + EventId = hitId, + HitX = hitPoint.X, HitY = hitPoint.Y, HitZ = hitPoint.Z, + NormalX = normal.X, NormalY = normal.Y, NormalZ = normal.Z, + SourceX = shooterPos.X, SourceY = shooterPos.Y, SourceZ = shooterPos.Z, + TargetKind = (byte)targetKind, + TargetId = targetId, + WeaponClass = (byte)weaponClass, + WeaponId = weaponId, + IsAirburst = isAirburst, + Ttl = 0.35f, + ShooterId = shooterEntityId, + IsContenderShooter = !isSpectatorShooter + }); + } + + void IOrdnanceTargetSink.StampTerrainImpact(float x, float z, float craterRadius, float craterDepth, float scorchRadius) + { + if (craterRadius > 0f && craterDepth > 0f) + { + var ev = new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = x, + Z = z, + Radius = craterRadius, + Depth = craterDepth + }; + State.ApplyTerrainStamp(ev, recordInLedger: true); + _stepEvents.Add(ev); + } + if (scorchRadius > 0f) + { + var ev = new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Scorch, + X = x, + Z = z, + Radius = scorchRadius + }; + State.ApplyTerrainStamp(ev, recordInLedger: true); + _stepEvents.Add(ev); + } + } + + private static Vector3 ComputeBoxFaceNormal( + (float X, float Y, float Z) hitPoint, + int lane, + ChassisSpec spec, + Box3DSoaView view, + Vector3 fallback) + { + var bodyPos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var bodyQuat = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var local = Vector3.Transform(new Vector3(hitPoint.X, hitPoint.Y, hitPoint.Z) - bodyPos, Quaternion.Conjugate(bodyQuat)); + + float nx = MathF.Abs(local.X) / MathF.Max(0.1f, spec.HalfWidth); + float ny = MathF.Abs(local.Y) / MathF.Max(0.1f, spec.HalfHeight); + float nz = MathF.Abs(local.Z) / MathF.Max(0.1f, spec.HalfLength); + + Vector3 localNormal; + if (nx >= ny && nx >= nz) + localNormal = new Vector3(local.X >= 0f ? 1f : -1f, 0f, 0f); + else if (ny >= nx && ny >= nz) + localNormal = new Vector3(0f, local.Y >= 0f ? 1f : -1f, 0f); + else + localNormal = new Vector3(0f, 0f, local.Z >= 0f ? 1f : -1f); + + Vector3 worldNormal = Vector3.Transform(localNormal, bodyQuat); + return worldNormal.LengthSquared() > 1e-6f ? Vector3.Normalize(worldNormal) : fallback; + } + + private static (float LocalRight, float LocalForward, float LocalHeightNorm) ComputeLocalHitCoords( + (float X, float Y, float Z) hitPoint, + int lane, + ChassisSpec spec, + Box3DSoaView view) + { + var bodyPos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var bodyQuat = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var local = Vector3.Transform(new Vector3(hitPoint.X, hitPoint.Y, hitPoint.Z) - bodyPos, Quaternion.Conjugate(bodyQuat)); + + float localRight = Math.Clamp(-local.X / MathF.Max(0.1f, spec.HalfWidth), -1f, 1f); + float localForward = Math.Clamp(local.Z / MathF.Max(0.1f, spec.HalfLength), -1f, 1f); + float localHeightNorm = Math.Clamp((local.Y / MathF.Max(0.1f, spec.HalfHeight)) * 0.5f + 0.5f, 0f, 1f); + return (localRight, localForward, localHeightNorm); + } + + private float ResolveAimTargetY(float aimX, float aimZ, ulong shooterStableId) + { + float bestDistSq = 9f * 9f; + float bestY = State.Terrain.SampleHeight(aimX, aimZ) + 0.9f; + + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.IsGroundedActive || ContenderStableIdBase + (ulong)c.Id == shooterStableId) + { + continue; + } + float dx = c.X - aimX; + float dz = c.Z - aimZ; + float d2 = dx * dx + dz * dz; + if (d2 < bestDistSq) + { + bestDistSq = d2; + bestY = c.Y; + } + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive || SpectatorStableIdBase + (ulong)s.Id == shooterStableId) + { + continue; + } + float dx = s.X - aimX; + float dz = s.Z - aimZ; + float d2 = dx * dx + dz * dz; + if (d2 < bestDistSq) + { + bestDistSq = d2; + bestY = s.Y; + } + } + + return bestY; + } + + public void Dispose() + { + if (_disposed) + { + return; + } + _disposed = true; + State.ChassisSwapped -= OnContenderChassisSwapped; + State.LoadoutChanged -= OnContenderLoadoutChanged; + State.ContenderRespawned -= OnContenderLoadoutChanged; + State.DropSpawned -= OnDropSpawned; + State.DropPickedUp -= OnDropPickedUp; + State.ContenderPodTouchedDown -= OnContenderPodTouchedDown; + State.Broadcast.LineEmitted -= OnBroadcastLineEmitted; + _world.Dispose(); + } + } +} diff --git a/src/RustToDust.Ymir/Box3DPhysicsTileSync.cs b/src/RustToDust.Ymir/Box3DPhysicsTileSync.cs new file mode 100644 index 0000000..c85f5de --- /dev/null +++ b/src/RustToDust.Ymir/Box3DPhysicsTileSync.cs @@ -0,0 +1,429 @@ +using System; +using RustToDust.Core; +using Ymir.Box3D; + +namespace RustToDust.Ymir +{ + public sealed class Box3DPhysicsTileSync + { + public const ulong HeightfieldTileStableIdBase = 10_000; + public const ulong BuildingTileStableIdBase = 11_000; + public const ulong TreeTileStableIdBase = 12_000; + public const int MaxTiles = 256; + + private readonly Box3DSoaBodyHandle[] _residentHandles = new Box3DSoaBodyHandle[MaxTiles]; + private readonly bool[] _residentFlags = new bool[MaxTiles]; + private readonly int[] _syncedStructuralVersions = new int[MaxTiles]; + private float[]? _scratchHeights; + + public static bool IsHeightfieldTileStableId(ulong stableId) => + stableId >= HeightfieldTileStableIdBase && stableId < HeightfieldTileStableIdBase + MaxTiles; + + public int ResidentTileCount { get; private set; } + + public bool TryGetResidentHandle(int tx, int tz, int tileGridCount, out Box3DSoaBodyHandle handle) + { + if ((uint)tx < (uint)tileGridCount && (uint)tz < (uint)tileGridCount) + { + int idx = tz * tileGridCount + tx; + if (_residentFlags[idx]) + { + handle = _residentHandles[idx]; + return true; + } + } + handle = default; + return false; + } + + public void Reset() + { + Array.Clear(_residentHandles); + Array.Clear(_residentFlags); + Array.Clear(_syncedStructuralVersions); + ResidentTileCount = 0; + } + + public bool EnsureTileResident(Box3DSoaWorld world, TerrainField terrain, int tx, int tz) + { + if (!terrain.IsHeightmapMode) + { + return false; + } + + int grid = terrain.TileGridCount; + if ((uint)tx >= (uint)grid || (uint)tz >= (uint)grid) + { + return false; + } + + int idx = tz * grid + tx; + int curVer = terrain.StructuralTileVersions[tx, tz]; + if (_residentFlags[idx] && _syncedStructuralVersions[idx] == curVer) + { + return false; + } + + int samplesPerTile = (terrain.HeightmapRes - 1) / grid; + int side = samplesPerTile + 1; + int sampleCount = side * side; + if (_scratchHeights is null || _scratchHeights.Length < sampleCount) + { + _scratchHeights = new float[sampleCount]; + } + + terrain.ExtractTilePhysicsHeights(tx, tz, _scratchHeights, out float minY, out float maxY); + + if (_residentFlags[idx]) + { + world.RemoveBody(_residentHandles[idx]); + ResidentTileCount--; + _residentFlags[idx] = false; + } + + float originX = -terrain.MapHalfExtent + tx * terrain.MapTileSize; + float originZ = -terrain.MapHalfExtent + tz * terrain.MapTileSize; + ulong stableId = HeightfieldTileStableIdBase + (ulong)idx; + var handle = world.AddStaticHeightField( + stableId, + (originX, 0f, originZ), + _scratchHeights.AsSpan(0, sampleCount), + side, + side, + (terrain.HeightmapCellSize, 1.0f, terrain.HeightmapCellSize), + minY - 2f, + maxY + 2f, + friction: 0.15f, + restitution: 0.0f); + + _residentHandles[idx] = handle; + _residentFlags[idx] = true; + _syncedStructuralVersions[idx] = curVer; + ResidentTileCount++; + return true; + } + + public void EnsureTileRegion(Box3DSoaWorld world, TerrainField terrain, float worldX, float worldZ, int halfTileRadius) + { + if (!terrain.IsHeightmapMode) + { + return; + } + + terrain.MapWorldToTile(worldX, worldZ, out int cx, out int cz); + int grid = terrain.TileGridCount; + int minTx = Math.Max(0, cx - halfTileRadius); + int maxTx = Math.Min(grid - 1, cx + halfTileRadius); + int minTz = Math.Max(0, cz - halfTileRadius); + int maxTz = Math.Min(grid - 1, cz + halfTileRadius); + + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + EnsureTileResident(world, terrain, tx, tz); + } + } + } + + public static void MarkTileRegion(TerrainField terrain, Span needed, float worldX, float worldZ, int halfTileRadius) + { + if (!terrain.IsHeightmapMode) + { + return; + } + + terrain.MapWorldToTile(worldX, worldZ, out int cx, out int cz); + int grid = terrain.TileGridCount; + int minTx = Math.Max(0, cx - halfTileRadius); + int maxTx = Math.Min(grid - 1, cx + halfTileRadius); + int minTz = Math.Max(0, cz - halfTileRadius); + int maxTz = Math.Min(grid - 1, cz + halfTileRadius); + + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + needed[tz * grid + tx] = true; + } + } + } + + public static void MarkTileFootprint(TerrainField terrain, Span needed, float worldX, float worldZ, float marginMeters) + { + if (!terrain.IsHeightmapMode) + { + return; + } + + float half = terrain.MapHalfExtent; + float r = MathF.Max(0f, marginMeters); + terrain.MapWorldToTile(Math.Clamp(worldX - r, -half, half), Math.Clamp(worldZ - r, -half, half), out int minTx, out int minTz); + terrain.MapWorldToTile(Math.Clamp(worldX + r, -half, half), Math.Clamp(worldZ + r, -half, half), out int maxTx, out int maxTz); + int grid = terrain.TileGridCount; + + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + needed[tz * grid + tx] = true; + } + } + } + + public void SyncNeededTiles( + Box3DSoaWorld world, + TerrainField terrain, + ReadOnlySpan needed, + ReadOnlySpan immediate = default, + int maxNewPrefetchPerTick = int.MaxValue) + { + if (!terrain.IsHeightmapMode) + { + return; + } + + int grid = terrain.TileGridCount; + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + int idx = tz * grid + tx; + bool keep = needed[idx] || (!immediate.IsEmpty && immediate[idx]); + if (_residentFlags[idx] && !keep) + { + world.RemoveBody(_residentHandles[idx]); + _residentHandles[idx] = default; + _residentFlags[idx] = false; + _syncedStructuralVersions[idx] = 0; + ResidentTileCount--; + } + } + } + + if (!immediate.IsEmpty) + { + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + int idx = tz * grid + tx; + if (immediate[idx] && !_residentFlags[idx]) + { + EnsureTileResident(world, terrain, tx, tz); + } + } + } + } + + int newPrefetch = 0; + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + if (newPrefetch >= maxNewPrefetchPerTick) + { + return; + } + int idx = tz * grid + tx; + if (needed[idx] && !_residentFlags[idx]) + { + if (EnsureTileResident(world, terrain, tx, tz)) + { + newPrefetch++; + } + } + } + } + } + + public void EnsureTilesAlongRay( + Box3DSoaWorld world, + TerrainField terrain, + float ox, float oz, + float dx, float dz, + float maxDistance) + { + if (!terrain.IsHeightmapMode || maxDistance <= 0f) + { + return; + } + + float half = terrain.MapHalfExtent; + float tileSize = terrain.MapTileSize; + int grid = terrain.TileGridCount; + + float tMin = 0f; + float tMax = maxDistance; + if (!SlabClip(ox, dx, -half, half, ref tMin, ref tMax)) return; + if (!SlabClip(oz, dz, -half, half, ref tMin, ref tMax)) return; + + float sx = ox + dx * tMin; + float sz = oz + dz * tMin; + terrain.MapWorldToTile(sx, sz, out int tx, out int tz); + + float ex = ox + dx * tMax; + float ez = oz + dz * tMax; + terrain.MapWorldToTile(ex, ez, out int endTx, out int endTz); + + int stepX = dx > 1e-9f ? 1 : (dx < -1e-9f ? -1 : 0); + int stepZ = dz > 1e-9f ? 1 : (dz < -1e-9f ? -1 : 0); + float tDeltaX = stepX != 0 ? tileSize / MathF.Abs(dx) : float.PositiveInfinity; + float tDeltaZ = stepZ != 0 ? tileSize / MathF.Abs(dz) : float.PositiveInfinity; + + float nextBoundaryX = -half + (tx + (stepX > 0 ? 1 : 0)) * tileSize; + float nextBoundaryZ = -half + (tz + (stepZ > 0 ? 1 : 0)) * tileSize; + float tMaxX = stepX != 0 ? tMin + MathF.Max(0f, (nextBoundaryX - sx) / dx) : float.PositiveInfinity; + float tMaxZ = stepZ != 0 ? tMin + MathF.Max(0f, (nextBoundaryZ - sz) / dz) : float.PositiveInfinity; + + int maxSteps = grid * 2 + 4; + for (int iter = 0; iter < maxSteps; iter++) + { + EnsureTileResident(world, terrain, tx, tz); + if (tx == endTx && tz == endTz) + { + break; + } + + float curT; + if (tMaxX <= tMaxZ) + { + curT = tMaxX; + tMaxX += tDeltaX; + tx += stepX; + } + else + { + curT = tMaxZ; + tMaxZ += tDeltaZ; + tz += stepZ; + } + + if ((uint)tx >= (uint)grid || (uint)tz >= (uint)grid || curT > tMax) + { + break; + } + } + + if ((uint)endTx < (uint)grid && (uint)endTz < (uint)grid) + { + EnsureTileResident(world, terrain, endTx, endTz); + } + } + + public int CountDirtyResidentTiles(TerrainField terrain) + { + if (!terrain.IsHeightmapMode) + { + return 0; + } + + int grid = terrain.TileGridCount; + int count = 0; + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + int idx = tz * grid + tx; + if (_residentFlags[idx] && terrain.StructuralTileVersions[tx, tz] != _syncedStructuralVersions[idx]) + { + count++; + } + } + } + return count; + } + + public int FlushDirtyHeightfields(Box3DSoaWorld world, TerrainField terrain, int maxTilesPerTick = 4) + { + if (!terrain.IsHeightmapMode || maxTilesPerTick <= 0) + { + return 0; + } + + int grid = terrain.TileGridCount; + int rebuilt = 0; + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + int idx = tz * grid + tx; + if (!_residentFlags[idx]) + { + continue; + } + if (terrain.StructuralTileVersions[tx, tz] != _syncedStructuralVersions[idx]) + { + if (world.FreeBodySlots < 8) + { + return rebuilt; + } + if (EnsureTileResident(world, terrain, tx, tz)) + { + rebuilt++; + if (rebuilt >= maxTilesPerTick) + { + return rebuilt; + } + } + } + } + } + return rebuilt; + } + + public void SyncWindow(Box3DSoaWorld world, TerrainField terrain, float centerX, float centerZ, int halfTileRadius = 1) + { + if (!terrain.IsHeightmapMode) + { + return; + } + + terrain.MapWorldToTile(centerX, centerZ, out int cx, out int cz); + int grid = terrain.TileGridCount; + int minTx = Math.Max(0, cx - halfTileRadius); + int maxTx = Math.Min(grid - 1, cx + halfTileRadius); + int minTz = Math.Max(0, cz - halfTileRadius); + int maxTz = Math.Min(grid - 1, cz + halfTileRadius); + + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + int idx = tz * grid + tx; + if (_residentFlags[idx] && (tx < minTx || tx > maxTx || tz < minTz || tz > maxTz)) + { + world.RemoveBody(_residentHandles[idx]); + _residentHandles[idx] = default; + _residentFlags[idx] = false; + _syncedStructuralVersions[idx] = 0; + ResidentTileCount--; + } + } + } + + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + EnsureTileResident(world, terrain, tx, tz); + } + } + } + + private static bool SlabClip(float o, float d, float minB, float maxB, ref float tMin, ref float tMax) + { + if (MathF.Abs(d) < 1e-9f) + { + return o >= minB && o <= maxB; + } + float invD = 1f / d; + float t1 = (minB - o) * invD; + float t2 = (maxB - o) * invD; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + return tMax >= tMin; + } + } +} diff --git a/src/RustToDust.Ymir/LocalArenaSession.cs b/src/RustToDust.Ymir/LocalArenaSession.cs new file mode 100644 index 0000000..c7fd253 --- /dev/null +++ b/src/RustToDust.Ymir/LocalArenaSession.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using RustToDust.Core; + +namespace RustToDust.Ymir +{ + public sealed class LocalArenaSession : IClientArenaSession + { + private readonly List _pendingEvents = new(); + private readonly Dictionary _scarsByMap = new(); + + public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null, bool skipInitialDrop = false, byte squadSize = 1) + { + Inner = new ArenaSession(seed, mapKind, slot0Human: true, skipInitialDrop: skipInitialDrop, squadSize: squadSize) + { + EnableNetworkPvs = false + }; + if (!string.IsNullOrWhiteSpace(callsign)) + { + Inner.SetHumanSlot(0, true, callsign); + } + } + + public ArenaSession Inner { get; private set; } + public MatchState ViewState => Inner.State; + public int LocalContenderId => 0; + public ContenderState LocalContender => Inner.State.Contenders[0]; + + public ClientMatchOutcome LocalOutcome => + Inner.State.Phase == MatchPhase.Lobby + ? ClientMatchOutcome.Active + : Inner.State.Phase == MatchPhase.Active + ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) + : ((Inner.State.WinnerContenderId == LocalContenderId || + (Inner.State.WinnerContenderId.HasValue && Inner.State.AreAllies(LocalContenderId, Inner.State.WinnerContenderId.Value))) + ? ClientMatchOutcome.Victory + : ClientMatchOutcome.Defeat); + + public int LocalDetectedByCount => + Inner.State.ObserverStates.TryGetValue(LocalContenderId, out var obs) ? obs.DetectedByCount : 0; + + public IReadOnlyDictionary LocalContenderContacts => + Inner.State.ObserverStates.TryGetValue(LocalContenderId, out var obs) ? obs.ContenderContacts : Inner.State.EmptyContacts; + + public IReadOnlyDictionary LocalSpectatorContacts => + Inner.State.ObserverStates.TryGetValue(LocalContenderId, out var obs) ? obs.SpectatorContacts : Inner.State.EmptyContacts; + + public NetworkStatusSnapshot ConnectionStatus => + new(NetworkMode.Solo, Connected: true, PingMs: 0, ConnectedHumans: 1, MaxHumans: 1, StateLabel: "SOLO"); + + public IReadOnlyList ActivePods => Inner.State.OrbitalDrop.ActivePods; + public DropWaveState DropWaveState => Inner.State.OrbitalDrop.WaveState; + public IReadOnlyList PodEvents => Inner.State.PodEvents; + public LobbySnapshotDto? LobbyState => null; + + public bool IsContenderVisible(int contenderId) => true; + public bool IsSpectatorVisible(int spectatorId) => true; + + public void BeginRenderFrame(double dt, float physicsAlpha) + { + } + + public void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick) + { + if (!isPhysicsTick) + { + return; + } + Inner.SetHumanInput(0, input); + Inner.Step(); + Inner.DrainStepEvents(_pendingEvents); + if (_pendingEvents.Count > 4096) + { + _pendingEvents.RemoveRange(0, _pendingEvents.Count - 4096); + } + } + + public void DrainSimEvents(List dest) + { + if (_pendingEvents.Count == 0) + { + return; + } + dest.AddRange(_pendingEvents); + _pendingEvents.Clear(); + } + + public bool RequestEquipCargo(int cargoIndex, string hardpointId) + { + bool ok = Inner.TryEquipCargo(0, cargoIndex, hardpointId); + if (ok) + { + Inner.DrainStepEvents(_pendingEvents); + } + return ok; + } + + public void RepairArenaScars() + { + Inner.RepairArenaScars(); + _scarsByMap.Remove(Inner.State.MapKind); + } + + public void RequestNewMatch(int seed, ArenaMapKind mapKind) + { + string? name = LocalContender.Name; + byte squadSize = Inner.State.SquadSize; + _scarsByMap[Inner.State.MapKind] = Inner.State.ScarLedger.ToSnapshot(); + _scarsByMap.TryGetValue(mapKind, out var initialScars); + _pendingEvents.Clear(); + Inner.Dispose(); + Inner = new ArenaSession(seed, mapKind, slot0Human: true, squadSize: squadSize, initialScars: initialScars) + { + EnableNetworkPvs = false + }; + if (!string.IsNullOrWhiteSpace(name)) + { + Inner.SetHumanSlot(0, true, name); + } + } + + public bool SetLobbyReady(bool ready) => false; + public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => false; + public bool RequestLobbyStart() => false; + + public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) => + Inner.GetInterpolatedContenderPose(contenderId, alpha); + + public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha) => + Inner.GetInterpolatedSpectatorPose(spectatorId, alpha); + + public bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap) => + Inner.TrySampleInterpolatedWalkerPose(isContender, id, alpha, out snap); + + public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation) + { + var hit = Inner.CastWorldRayClosest(origin, translation); + return new ClientRayHit( + hit.Hit, + hit.StableId, + new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z), + new Vector3(hit.Normal.X, hit.Normal.Y, hit.Normal.Z), + hit.Fraction); + } + + public void Dispose() + { + Inner.Dispose(); + } + } +} diff --git a/src/RustToDust.Ymir/OrdnanceRuntime.cs b/src/RustToDust.Ymir/OrdnanceRuntime.cs new file mode 100644 index 0000000..643ca4c --- /dev/null +++ b/src/RustToDust.Ymir/OrdnanceRuntime.cs @@ -0,0 +1,1892 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using RustToDust.Core; +using Ymir.Box3D; + +namespace RustToDust.Ymir +{ + public enum OrdnanceEventKind : byte + { + Spawned = 0, + StageTransition = 1, + Split = 2, + Detonated = 3, + Intercepted = 4, + Expired = 5 + } + + public readonly record struct OrdnanceNetEvent( + int OrdnanceId, + int ParentOrdnanceId, + OrdnanceEventKind Kind, + ulong ShooterStableId, + bool IsSpectatorShooter, + int ShooterEntityId, + ProceduralWeaponKey? WeaponKey, + byte NodeDefIndex, + Vector3 Pos, + Vector3 Vel, + int TargetEntityId, + bool TargetIsSpectator, + float SimTime, + byte VisualShape, + uint ColorRgba); + + public readonly record struct OrdnanceFireRequest( + MountedModule Module, + ulong ShooterStableId, + ContenderState? ShooterContender, + string ShooterLabel, + bool IsSpectatorShooter, + int ShooterEntityId, + Vector3 ShooterPos, + Vector3 MuzzlePos, + Vector3 AimDir, + float AimDist, + float SpreadRad, + ulong TargetEntityStableId, + OrdnanceNodeDef RootDef, + ProceduralWeaponKey? WeaponKey); + + public interface IOrdnanceTargetSink + { + Box3DSoaWorld World { get; } + MatchState State { get; } + bool HasLineOfSight(float x0, float y0, float z0, float x1, float y1, float z1); + bool TryResolveActor(ulong stableId, out bool isContender, out int index); + Vector3 GetActorAimPosition(bool isContender, int index); + void ApplyDirectHit( + ulong targetStableId, + (float X, float Y, float Z) hitPoint, + Vector3 shotDir, + Vector3 shooterPos, + WeaponVisualClass weaponClass, + string weaponId, + bool isAirburst, + float damage, + float heatTransfer, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + int shooterEntityId); + void ApplySplashDamage( + Vector3 center, + float radius, + float splashDamage, + float heatTransfer, + WeaponVisualClass weaponClass, + string weaponId, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + int shooterEntityId, + ulong ignoreStableId); + void EmitTracer( + Vector3 start, + Vector3 end, + uint colorRgba, + float ttl, + WeaponVisualClass weaponClass, + string weaponId, + bool isSpectatorShooter, + int shooterEntityId); + void EmitNonActorHit( + HitTargetKind targetKind, + int targetId, + Vector3 hitPoint, + Vector3 normal, + Vector3 shooterPos, + WeaponVisualClass weaponClass, + string weaponId, + bool isAirburst, + bool isSpectatorShooter, + int shooterEntityId); + void StampTerrainImpact(float x, float z, float craterRadius, float craterDepth, float scorchRadius); + } + + public struct LiveOrdnanceInstance + { + public bool Active; + public int OrdnanceId; + public int ParentOrdnanceId; + public ulong ShooterStableId; + public int ShooterContenderId; + public bool IsSpectatorShooter; + public string ShooterLabel; + public string WeaponId; + public ProceduralWeaponKey? WeaponKey; + public OrdnanceNodeDef Def; + public byte Depth; + public Vector3 Pos; + public Vector3 PrevPos; + public Vector3 Vel; + public Vector3 SurfaceNormal; + public Vector3 AnchorPos; + public Vector3 ShooterOriginPos; + public ulong TargetStableId; + public float Age; + public float StageAge; + public float WhileAliveTimer; + public int WhileAliveCount; + public float OrbitAngle; + public float Hp; + public bool Armed; + public bool EjectSabotVfx; + public byte PenetrationsUsed; + public ulong LastPenetratedStableId; + public float DamageScale; + public int CreatedStep; + } + + public sealed class OrdnanceRuntime + { + public const int PoolCapacity = 256; + + private readonly IOrdnanceTargetSink _sink; + private readonly LiveOrdnanceInstance[] _pool = new LiveOrdnanceInstance[PoolCapacity]; + private readonly List _netEvents = new(64); + private int _nextOrdnanceId = 1; + private int _stepCounter; + + public OrdnanceRuntime(IOrdnanceTargetSink sink) + { + _sink = sink ?? throw new ArgumentNullException(nameof(sink)); + } + + public int ActiveCount { get; private set; } + public int MaxObservedDepth { get; private set; } + public ReadOnlySpan PoolSpan => _pool; + + public void Reset() + { + Array.Clear(_pool, 0, _pool.Length); + _netEvents.Clear(); + ActiveCount = 0; + MaxObservedDepth = 0; + _nextOrdnanceId = 1; + _stepCounter = 0; + } + + public void DrainNetEvents(List dest) + { + if (_netEvents.Count == 0) + { + return; + } + dest.AddRange(_netEvents); + _netEvents.Clear(); + } + + public void FireWeapon(in OrdnanceFireRequest req) + { + var mod = req.Module; + int burst = Math.Max(1, mod.Spec.BurstCount); + float perfScale = Math.Clamp(mod.CurrentPerformance, 0.05f, 1.5f); + float spread = MathF.Max(0f, req.SpreadRad); + var rng = _sink.State.Rng; + + for (int b = 0; b < burst; b++) + { + float yawJitter = ((float)rng.NextDouble() * 2f - 1f) * spread; + float pitchJitter = ((float)rng.NextDouble() * 2f - 1f) * (spread * 0.35f); + Vector3 dir = ApplySpread(req.AimDir, yawJitter, pitchJitter); + + if (req.RootDef.Motion == OrdnanceMotion.HitscanBeam) + { + ResolveHitscanBeam( + req.RootDef, + req.MuzzlePos, + dir, + req.AimDist, + req.ShooterPos, + req.ShooterStableId, + req.ShooterContender, + req.ShooterLabel, + req.IsSpectatorShooter, + req.ShooterEntityId, + mod.Spec.Id, + perfScale, + burstIndex: b); + } + else + { + Vector3 launchDir = ApplyPitchBias(dir, req.RootDef.LaunchPitchBiasDeg); + Vector3 vel = launchDir * req.RootDef.InitialSpeed; + SpawnInstance( + parentId: 0, + depth: 0, + req.RootDef, + req.ShooterStableId, + req.ShooterContender?.Id ?? -1, + req.IsSpectatorShooter, + req.ShooterLabel, + mod.Spec.Id, + req.WeaponKey, + req.MuzzlePos, + vel, + Vector3.UnitY, + req.ShooterPos, + req.TargetEntityStableId, + perfScale, + OrdnanceEventKind.Spawned, + createdStep: _stepCounter - 1); + } + } + } + + public void Step(float dt) + { + _stepCounter++; + var state = _sink.State; + + for (int i = 0; i < PoolCapacity; i++) + { + if (!_pool[i].Active || _pool[i].CreatedStep == _stepCounter) + { + continue; + } + + ref var inst = ref _pool[i]; + var def = inst.Def; + + inst.PrevPos = inst.Pos; + inst.Age += dt; + inst.StageAge += dt; + + if (!inst.Armed && inst.StageAge >= def.ArmDelay) + { + inst.Armed = true; + } + + if (def.WhileAlive is { } wa) + { + StepWhileAlive(ref inst, wa, dt); + if (!inst.Active) + { + continue; + } + } + + Vector3 prevVel = inst.Vel; + Vector3 nextPos = AdvanceKinematics(ref inst, dt, state.Terrain); + + if (def.Motion is OrdnanceMotion.Ballistic or OrdnanceMotion.RocketBoosted or OrdnanceMotion.HomingMissile) + { + if (SweepDynamicProjectile(i, nextPos, state.Terrain)) + { + continue; + } + } + else + { + inst.Pos = nextPos; + } + + EvaluatePostStepTriggers(i, prevVel, state.Terrain); + } + } + + public bool TryFindBestHostileAirborneOrdnance( + Vector3 muzzle, + ulong shooterStableId, + Quaternion shooterQuat, + float minPitchDeg, + float maxPitchDeg, + float maxRange, + out int ordnanceId, + out Vector3 targetPos) + { + ordnanceId = 0; + targetPos = Vector3.Zero; + float bestDistSq = maxRange * maxRange; + bool found = false; + bool shooterIsContender = _sink.TryResolveActor(shooterStableId, out bool sIsC, out int shooterContenderId) && sIsC; + + for (int i = 0; i < PoolCapacity; i++) + { + if (!_pool[i].Active) + { + continue; + } + ref readonly var inst = ref _pool[i]; + if (inst.Def.InterceptHp <= 0f || IsFriendlyOrdnance(shooterStableId, shooterIsContender, shooterContenderId, in inst)) + { + continue; + } + if (inst.Def.Motion is not (OrdnanceMotion.LoiterOrbit or OrdnanceMotion.HomingMissile)) + { + continue; + } + + Vector3 delta = inst.Pos - muzzle; + float d2 = delta.LengthSquared(); + if (d2 > bestDistSq || d2 < 1e-3f) + { + continue; + } + + float pitchDeg = MatchRules.ComputeLocalPitchDeg(delta, shooterQuat); + if (pitchDeg < minPitchDeg || pitchDeg > maxPitchDeg) + { + continue; + } + + if (!_sink.HasLineOfSight(muzzle.X, muzzle.Y, muzzle.Z, inst.Pos.X, inst.Pos.Y, inst.Pos.Z)) + { + continue; + } + + bestDistSq = d2; + ordnanceId = inst.OrdnanceId; + targetPos = inst.Pos; + found = true; + } + + return found; + } + + private void StepWhileAlive(ref LiveOrdnanceInstance inst, OrdnanceWhileAliveDef wa, float dt) + { + inst.WhileAliveTimer += dt; + if (inst.WhileAliveTimer < wa.Interval || inst.WhileAliveCount >= wa.MaxPulses) + { + return; + } + + inst.WhileAliveTimer -= wa.Interval; + inst.WhileAliveCount++; + + if (wa.ChildNode is { Motion: OrdnanceMotion.HitscanBeam } childBeam) + { + if (TryAcquireDownwardTarget(in inst, wa, out ulong targetStableId, out Vector3 aimPos)) + { + Vector3 dir = Vector3.Normalize(aimPos - inst.Pos); + ContenderState? shooterContender = !inst.IsSpectatorShooter && + inst.ShooterContenderId >= 0 && + inst.ShooterContenderId < _sink.State.Contenders.Count + ? _sink.State.Contenders[inst.ShooterContenderId] + : null; + + ResolveHitscanBeam( + childBeam, + inst.Pos, + dir, + aimDist: MathF.Max(childBeam.Range, Vector3.Distance(inst.Pos, aimPos) + 5f), + inst.Pos, + inst.ShooterStableId, + shooterContender, + inst.ShooterLabel, + inst.IsSpectatorShooter, + inst.IsSpectatorShooter + ? (int)(inst.ShooterStableId - 3000UL) + : inst.ShooterContenderId, + inst.WeaponId, + inst.DamageScale, + burstIndex: 0); + } + } + + if ((wa.RadialDamage > 0f || wa.RadialHeat > 0f) && wa.RadialRadius > 0.1f) + { + ContenderState? shooterContender = !inst.IsSpectatorShooter && + inst.ShooterContenderId >= 0 && + inst.ShooterContenderId < _sink.State.Contenders.Count + ? _sink.State.Contenders[inst.ShooterContenderId] + : null; + int shooterEntityId = inst.IsSpectatorShooter + ? (int)(inst.ShooterStableId - 3000UL) + : inst.ShooterContenderId; + + _sink.ApplySplashDamage( + inst.Pos, + wa.RadialRadius, + wa.RadialDamage * inst.DamageScale, + wa.RadialHeat * inst.DamageScale, + inst.Def.VisualClass, + inst.WeaponId, + shooterContender, + inst.ShooterLabel, + inst.IsSpectatorShooter, + shooterEntityId, + ignoreStableId: inst.Def.ProximityIgnoreOwner ? inst.ShooterStableId : 0UL); + } + } + + private bool TryAcquireDownwardTarget(in LiveOrdnanceInstance inst, OrdnanceWhileAliveDef wa, out ulong stableId, out Vector3 aimPos) + { + stableId = 0; + aimPos = Vector3.Zero; + float maxRange = MathF.Max(10f, wa.TriggerScanRadius); + float maxRangeSq = maxRange * maxRange; + float minDownCos = MathF.Cos(Math.Clamp(wa.TargetConeDeg, 5f, 89f) * MathF.PI / 180f); + float bestScore = float.PositiveInfinity; + var state = _sink.State; + + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (!c.IsGroundedActive) + { + continue; + } + ulong cStable = ArenaSession.ContenderStableIdBase + (ulong)c.Id; + if (cStable == inst.ShooterStableId) + { + continue; + } + if (!inst.IsSpectatorShooter && inst.ShooterContenderId >= 0 && state.AreAllies(inst.ShooterContenderId, c.Id)) + { + continue; + } + + Vector3 targetPt = _sink.GetActorAimPosition(true, i); + Vector3 delta = targetPt - inst.Pos; + float d2 = delta.LengthSquared(); + if (d2 > maxRangeSq || d2 < 1e-3f) + { + continue; + } + + Vector3 dir = delta / MathF.Sqrt(d2); + if (Vector3.Dot(dir, -Vector3.UnitY) < minDownCos) + { + continue; + } + + if (!_sink.HasLineOfSight(inst.Pos.X, inst.Pos.Y, inst.Pos.Z, targetPt.X, targetPt.Y, targetPt.Z)) + { + continue; + } + + if (d2 < bestScore) + { + bestScore = d2; + stableId = cStable; + aimPos = targetPt; + } + } + + // Never lock onto Neutral Spectators! + for (int i = 0; i < state.Spectators.Spectators.Count; i++) + { + var s = state.Spectators.Spectators[i]; + if (!s.Alive || s.Stance == SpectatorStance.Neutral) + { + continue; + } + ulong sStable = 3000UL + (ulong)s.Id; + if (sStable == inst.ShooterStableId) + { + continue; + } + + Vector3 targetPt = _sink.GetActorAimPosition(false, i); + Vector3 delta = targetPt - inst.Pos; + float d2 = delta.LengthSquared(); + if (d2 > maxRangeSq || d2 < 1e-3f) + { + continue; + } + + Vector3 dir = delta / MathF.Sqrt(d2); + if (Vector3.Dot(dir, -Vector3.UnitY) < minDownCos) + { + continue; + } + + if (!_sink.HasLineOfSight(inst.Pos.X, inst.Pos.Y, inst.Pos.Z, targetPt.X, targetPt.Y, targetPt.Z)) + { + continue; + } + + if (d2 < bestScore) + { + bestScore = d2; + stableId = sStable; + aimPos = targetPt; + } + } + + return stableId != 0; + } + + private Vector3 AdvanceKinematics(ref LiveOrdnanceInstance inst, float dt, TerrainField terrain) + { + var def = inst.Def; + switch (def.Motion) + { + case OrdnanceMotion.Ballistic: + { + inst.Vel.Y -= 20f * def.GravityScale * dt; + return inst.Pos + inst.Vel * dt; + } + + case OrdnanceMotion.RocketBoosted: + { + float speed = inst.Vel.Length(); + Vector3 dir = speed > 1e-4f ? inst.Vel / speed : Vector3.UnitZ; + if (inst.StageAge <= def.BurnTime && def.ThrustAccel > 0f) + { + float maxSpd = def.MaxSpeed > 0f ? def.MaxSpeed : 400f; + speed = MathF.Min(maxSpd, speed + def.ThrustAccel * dt); + inst.Vel = dir * speed; + } + else if (def.GravityScale > 0f) + { + inst.Vel.Y -= 20f * def.GravityScale * 0.25f * dt; + } + return inst.Pos + inst.Vel * dt; + } + + case OrdnanceMotion.HomingMissile: + { + float speed = inst.Vel.Length(); + Vector3 dir = speed > 1e-4f ? inst.Vel / speed : Vector3.UnitZ; + + if (TryResolveHomingTarget(ref inst, dir, out Vector3 targetPos)) + { + Vector3 toTarget = targetPos - inst.Pos; + if (toTarget.LengthSquared() > 1e-4f) + { + Vector3 desiredDir = Vector3.Normalize(toTarget); + float maxTurn = MathF.Max(0.5f, def.TurnRateRad) * dt; + dir = RotateTowards(dir, desiredDir, maxTurn); + } + } + + if (inst.StageAge <= def.BurnTime || def.BurnTime <= 0f) + { + float maxSpd = def.MaxSpeed > 0f ? def.MaxSpeed : 180f; + speed = MathF.Min(maxSpd, speed + def.ThrustAccel * dt); + } + inst.Vel = dir * speed; + return inst.Pos + inst.Vel * dt; + } + + case OrdnanceMotion.LoiterOrbit: + { + // Gently drift anchor toward nearest hostile within 120m so loitering drones track moving targets + if (TryFindNearestHostile(in inst, 120f, ignoreNeutralSpectators: true, out ulong targetId, out Vector3 targetPos)) + { + inst.TargetStableId = targetId; + Vector3 toTarget = new Vector3(targetPos.X - inst.AnchorPos.X, 0f, targetPos.Z - inst.AnchorPos.Z); + float horizDist = toTarget.Length(); + if (horizDist > 4f) + { + inst.AnchorPos += (toTarget / horizDist) * MathF.Min(horizDist, 10f * dt); + } + } + + inst.OrbitAngle += def.LoiterOrbitSpeedRad * dt; + float targetX = inst.AnchorPos.X + MathF.Cos(inst.OrbitAngle) * def.LoiterOrbitRadius; + float targetZ = inst.AnchorPos.Z + MathF.Sin(inst.OrbitAngle) * def.LoiterOrbitRadius; + float groundY = terrain.SampleHeight(targetX, targetZ); + float desiredY = groundY + def.LoiterAltitudeAgl; + float nextY = inst.Pos.Y + (desiredY - inst.Pos.Y) * Math.Clamp(dt * 4.0f, 0f, 1f); + var nextPos = new Vector3(targetX, nextY, targetZ); + inst.Vel = (nextPos - inst.Pos) / MathF.Max(1e-4f, dt); + return nextPos; + } + + case OrdnanceMotion.StationaryMine: + default: + inst.Vel = Vector3.Zero; + return inst.Pos; + } + } + + private bool TryResolveHomingTarget(ref LiveOrdnanceInstance inst, Vector3 currentDir, out Vector3 targetPos) + { + targetPos = Vector3.Zero; + if (inst.TargetStableId != 0 && _sink.TryResolveActor(inst.TargetStableId, out bool isContender, out int idx)) + { + if (isContender) + { + var c = _sink.State.Contenders[idx]; + bool isAlly = !inst.IsSpectatorShooter && inst.ShooterContenderId >= 0 && _sink.State.AreAllies(inst.ShooterContenderId, c.Id); + if (c.IsGroundedActive && !isAlly) + { + targetPos = _sink.GetActorAimPosition(true, idx); + return true; + } + } + else + { + var s = _sink.State.Spectators.Spectators[idx]; + if (s.Alive && s.Stance != SpectatorStance.Neutral) + { + targetPos = _sink.GetActorAimPosition(false, idx); + return true; + } + } + } + + float range = inst.Def.SeekerRange > 0f ? inst.Def.SeekerRange : 180f; + float minCos = MathF.Cos(Math.Clamp(inst.Def.SeekerConeDeg * 0.5f, 10f, 179f) * MathF.PI / 180f); + float bestDistSq = range * range; + ulong bestId = 0; + var state = _sink.State; + + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (!c.IsGroundedActive) + { + continue; + } + ulong cStable = ArenaSession.ContenderStableIdBase + (ulong)c.Id; + if (cStable == inst.ShooterStableId) + { + continue; + } + if (!inst.IsSpectatorShooter && inst.ShooterContenderId >= 0 && state.AreAllies(inst.ShooterContenderId, c.Id)) + { + continue; + } + Vector3 pt = _sink.GetActorAimPosition(true, i); + Vector3 d = pt - inst.Pos; + float d2 = d.LengthSquared(); + if (d2 > bestDistSq || d2 < 1e-4f) + { + continue; + } + if (Vector3.Dot(d / MathF.Sqrt(d2), currentDir) >= minCos) + { + bestDistSq = d2; + bestId = cStable; + targetPos = pt; + } + } + + if (bestId != 0) + { + inst.TargetStableId = bestId; + return true; + } + + return false; + } + + private bool TryFindNearestHostile( + in LiveOrdnanceInstance inst, + float maxRadius, + bool ignoreNeutralSpectators, + out ulong stableId, + out Vector3 targetPos) + { + stableId = 0; + targetPos = Vector3.Zero; + float bestDistSq = maxRadius * maxRadius; + var state = _sink.State; + + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (!c.IsGroundedActive) + { + continue; + } + ulong cStable = ArenaSession.ContenderStableIdBase + (ulong)c.Id; + if (inst.Def.ProximityIgnoreOwner && cStable == inst.ShooterStableId) + { + continue; + } + if (cStable == inst.ShooterStableId && inst.Age < 0.3f) + { + continue; + } + if (!inst.IsSpectatorShooter && inst.ShooterContenderId >= 0 && inst.ShooterContenderId != c.Id && state.AreAllies(inst.ShooterContenderId, c.Id)) + { + continue; + } + + Vector3 pt = _sink.GetActorAimPosition(true, i); + float d2 = Vector3.DistanceSquared(inst.Pos, pt); + // Allow horizontal proximity trigger for mines even on tall walkers + float dx = pt.X - inst.Pos.X; + float dz = pt.Z - inst.Pos.Z; + float dy = MathF.Abs(pt.Y - inst.Pos.Y); + float effectiveDistSq = dx * dx + dz * dz; + if (dy <= maxRadius + c.Grid.Spec.HalfHeight && effectiveDistSq <= bestDistSq && d2 <= (maxRadius + c.Grid.Spec.HalfHeight + 1.5f) * (maxRadius + c.Grid.Spec.HalfHeight + 1.5f)) + { + bestDistSq = effectiveDistSq; + stableId = cStable; + targetPos = pt; + } + } + + if (!ignoreNeutralSpectators) + { + for (int i = 0; i < state.Spectators.Spectators.Count; i++) + { + var s = state.Spectators.Spectators[i]; + if (!s.Alive || s.Stance == SpectatorStance.Neutral) + { + continue; + } + ulong sStable = 3000UL + (ulong)s.Id; + if (sStable == inst.ShooterStableId) + { + continue; + } + Vector3 pt = _sink.GetActorAimPosition(false, i); + float d2 = Vector3.DistanceSquared(inst.Pos, pt); + if (d2 <= bestDistSq) + { + bestDistSq = d2; + stableId = sStable; + targetPos = pt; + } + } + } + + return stableId != 0; + } + + private bool SweepDynamicProjectile(int slotIndex, Vector3 nextPos, TerrainField terrain) + { + ref var inst = ref _pool[slotIndex]; + Vector3 segStart = inst.Pos; + Vector3 segDelta = nextPos - segStart; + float segLen = segDelta.Length(); + if (segLen < 1e-5f) + { + inst.Pos = nextPos; + return false; + } + + Vector3 dir = segDelta / segLen; + Vector3 castOrigin = segStart; + float remaining = segLen; + bool skipSelf = inst.Age < 0.25f; + + for (int hop = 0; hop < 4 && remaining > 1e-4f; hop++) + { + var rayHit = _sink.World.CastRayClosest( + (castOrigin.X, castOrigin.Y, castOrigin.Z), + (dir.X * remaining, dir.Y * remaining, dir.Z * remaining)); + + float boxDist = remaining + 1f; + bool hitBox = false; + ulong hitStableId = 0; + Vector3 boxPoint = Vector3.Zero; + Vector3 boxNormal = -dir; + + if (rayHit.Hit) + { + boxPoint = new Vector3(rayHit.Point.X, rayHit.Point.Y, rayHit.Point.Z); + float hitDistFromStart = Vector3.Distance(segStart, boxPoint); + if ((skipSelf && rayHit.StableId == inst.ShooterStableId) || + (inst.LastPenetratedStableId != 0 && rayHit.StableId == inst.LastPenetratedStableId)) + { + float advance = Vector3.Distance(castOrigin, boxPoint) + 0.12f; + castOrigin += dir * advance; + remaining -= advance; + continue; + } + + hitBox = true; + hitStableId = rayHit.StableId; + boxDist = hitDistFromStart; + Vector3 rn = new(rayHit.Normal.X, rayHit.Normal.Y, rayHit.Normal.Z); + if (rn.LengthSquared() > 1e-4f) + { + boxNormal = Vector3.Normalize(rn); + } + } + + bool hitTerrain = terrain.Raycast( + segStart.X, segStart.Y, segStart.Z, + dir.X, dir.Y, dir.Z, + MathF.Min(segLen, boxDist), + out float tx, out float ty, out float tz, out float terrainDist); + + if (hitTerrain && (!hitBox || terrainDist <= boxDist)) + { + var hitPt = new Vector3(tx, ty, tz); + var (tnx, tny, tnz) = terrain.SampleNormal(tx, tz); + var normal = new Vector3(tnx, tny, tnz); + inst.Pos = hitPt; + HandleProjectileImpact(slotIndex, HitTargetKind.Terrain, -1, 0UL, hitPt, normal, dir); + return !inst.Active; + } + + if (hitBox) + { + if (_sink.TryResolveActor(hitStableId, out bool isContender, out int actorIdx)) + { + if (inst.PenetrationsUsed < inst.Def.MaxPenetrations) + { + ApplyActorDirectHit(in inst, hitStableId, boxPoint, dir); + inst.PenetrationsUsed++; + inst.DamageScale *= inst.Def.PenetrationDamageDecay; + inst.LastPenetratedStableId = hitStableId; + float advance = Vector3.Distance(castOrigin, boxPoint) + 0.15f; + castOrigin += dir * advance; + remaining -= advance; + continue; + } + + inst.Pos = boxPoint; + int targetId = isContender + ? _sink.State.Contenders[actorIdx].Id + : _sink.State.Spectators.Spectators[actorIdx].Id; + HandleProjectileImpact( + slotIndex, + isContender ? HitTargetKind.Contender : HitTargetKind.Spectator, + targetId, + hitStableId, + boxPoint, + boxNormal, + dir); + return !inst.Active; + } + + bool isTerrainTile = Box3DPhysicsTileSync.IsHeightfieldTileStableId(hitStableId); + inst.Pos = boxPoint; + HandleProjectileImpact( + slotIndex, + isTerrainTile ? HitTargetKind.Terrain : HitTargetKind.StaticCover, + isTerrainTile ? -1 : (int)hitStableId, + isTerrainTile ? 0UL : hitStableId, + boxPoint, + boxNormal, + dir); + return !inst.Active; + } + + break; + } + + inst.Pos = nextPos; + return false; + } + + private void HandleProjectileImpact( + int slotIndex, + HitTargetKind targetKind, + int targetId, + ulong targetStableId, + Vector3 hitPoint, + Vector3 surfaceNormal, + Vector3 shotDir) + { + ref var inst = ref _pool[slotIndex]; + var def = inst.Def; + + for (int t = 0; t < def.Triggers.Length; t++) + { + var tr = def.Triggers[t]; + if (tr.Kind != OrdnanceTriggerKind.Impact) + { + continue; + } + if (inst.StageAge < tr.MinAge) + { + continue; + } + + ExecuteTriggerRule(slotIndex, tr, targetKind, targetId, targetStableId, hitPoint, surfaceNormal, shotDir); + return; + } + + // Default fallback on impact if no explicit Impact rule exists + ExecuteDetonate(slotIndex, targetKind, targetId, targetStableId, hitPoint, surfaceNormal, shotDir, burstIndex: 0); + } + + private void EvaluatePostStepTriggers(int slotIndex, Vector3 prevVel, TerrainField terrain) + { + ref var inst = ref _pool[slotIndex]; + if (!inst.Active) + { + return; + } + + var def = inst.Def; + for (int t = 0; t < def.Triggers.Length; t++) + { + var tr = def.Triggers[t]; + if (inst.StageAge < tr.MinAge) + { + continue; + } + + switch (tr.Kind) + { + case OrdnanceTriggerKind.StageElapsed: + if (inst.StageAge >= tr.Threshold) + { + Vector3 dir = inst.Vel.LengthSquared() > 1e-4f ? Vector3.Normalize(inst.Vel) : Vector3.UnitZ; + ExecuteTriggerRule(slotIndex, tr, HitTargetKind.Terrain, -1, 0UL, inst.Pos, Vector3.UnitY, dir); + return; + } + break; + + case OrdnanceTriggerKind.Timeout: + if (inst.StageAge >= tr.Threshold) + { + Vector3 dir = inst.Vel.LengthSquared() > 1e-4f ? Vector3.Normalize(inst.Vel) : -Vector3.UnitY; + ExecuteTriggerRule(slotIndex, tr, HitTargetKind.Terrain, -1, 0UL, inst.Pos, Vector3.UnitY, dir); + return; + } + break; + + case OrdnanceTriggerKind.Apex: + if (inst.Vel.Y <= 0f && (prevVel.Y > 0f || inst.StageAge >= MathF.Max(0.15f, tr.MinAge))) + { + Vector3 dir = inst.Vel.LengthSquared() > 1e-4f ? Vector3.Normalize(inst.Vel) : Vector3.UnitZ; + ExecuteTriggerRule(slotIndex, tr, HitTargetKind.Terrain, -1, 0UL, inst.Pos, Vector3.UnitY, dir); + return; + } + break; + + case OrdnanceTriggerKind.Altitude: + { + float agl = inst.Pos.Y - terrain.SampleHeight(inst.Pos.X, inst.Pos.Z); + if (agl <= tr.Threshold) + { + Vector3 dir = inst.Vel.LengthSquared() > 1e-4f ? Vector3.Normalize(inst.Vel) : -Vector3.UnitY; + ExecuteTriggerRule(slotIndex, tr, HitTargetKind.Terrain, -1, 0UL, inst.Pos, Vector3.UnitY, dir); + return; + } + break; + } + + case OrdnanceTriggerKind.Proximity: + if (inst.Armed && TryFindNearestHostile(in inst, tr.Threshold, ignoreNeutralSpectators: true, out ulong proxTarget, out Vector3 proxPos)) + { + Vector3 dir = (proxPos - inst.Pos).LengthSquared() > 1e-4f + ? Vector3.Normalize(proxPos - inst.Pos) + : Vector3.UnitY; + ExecuteTriggerRule(slotIndex, tr, HitTargetKind.Terrain, -1, proxTarget, inst.Pos, Vector3.UnitY, dir); + return; + } + break; + } + } + + if (def.MaxLifetime > 0f && inst.StageAge >= def.MaxLifetime) + { + EmitNetEvent(in inst, OrdnanceEventKind.Expired); + FreeSlot(slotIndex); + } + } + + private void ExecuteTriggerRule( + int slotIndex, + OrdnanceTriggerRule rule, + HitTargetKind targetKind, + int targetId, + ulong targetStableId, + Vector3 pos, + Vector3 normal, + Vector3 shotDir) + { + ref var inst = ref _pool[slotIndex]; + switch (rule.Action) + { + case OrdnanceTriggerAction.Detonate: + ExecuteDetonate(slotIndex, targetKind, targetId, targetStableId, pos, normal, shotDir, burstIndex: 0); + break; + + case OrdnanceTriggerAction.Fizzle: + EmitNetEvent(in inst, OrdnanceEventKind.Expired); + FreeSlot(slotIndex); + break; + + case OrdnanceTriggerAction.Transition: + { + if (rule.ChildNode is null || inst.Depth + 1 >= OrdnanceNodeDef.MaxAllowedDepth) + { + ExecuteDetonate(slotIndex, targetKind, targetId, targetStableId, pos, normal, shotDir, burstIndex: 0); + return; + } + + var childDef = rule.ChildNode; + Vector3 childPos = pos; + Vector3 childVel = shotDir * childDef.InitialSpeed; + + if (childDef.Motion == OrdnanceMotion.StationaryMine) + { + float gh = _sink.State.Terrain.SampleHeight(pos.X, pos.Z); + if (targetKind is HitTargetKind.Contender or HitTargetKind.Spectator || pos.Y > gh + 3.0f) + { + childPos = new Vector3(pos.X, gh + 0.25f, pos.Z); + } + else + { + childPos = pos + normal * 0.25f; + } + childVel = Vector3.Zero; + } + else if (childDef.Motion == OrdnanceMotion.HomingMissile && inst.TargetStableId != 0) + { + if (_sink.TryResolveActor(inst.TargetStableId, out bool ic, out int idx)) + { + Vector3 tPos = _sink.GetActorAimPosition(ic, idx); + if ((tPos - pos).LengthSquared() > 1e-3f) + { + childVel = Vector3.Normalize(tPos - pos) * childDef.InitialSpeed; + } + } + } + + // Capture parent metadata before freeing + int parentId = inst.OrdnanceId; + byte childDepth = (byte)(inst.Depth + 1); + ulong shooterStableId = inst.ShooterStableId; + int shooterContenderId = inst.ShooterContenderId; + bool isSpec = inst.IsSpectatorShooter; + string shooterLabel = inst.ShooterLabel; + string weaponId = inst.WeaponId; + ProceduralWeaponKey? key = inst.WeaponKey; + Vector3 originPos = inst.ShooterOriginPos; + ulong tgt = inst.TargetStableId; + float scale = inst.DamageScale; + + FreeSlot(slotIndex); + SpawnInstance( + parentId, + childDepth, + childDef, + shooterStableId, + shooterContenderId, + isSpec, + shooterLabel, + weaponId, + key, + childPos, + childVel, + normal, + originPos, + tgt, + scale, + OrdnanceEventKind.StageTransition, + createdStep: _stepCounter); + break; + } + + case OrdnanceTriggerAction.Split: + { + if (rule.ChildNode is null || inst.Depth + 1 >= OrdnanceNodeDef.MaxAllowedDepth) + { + ExecuteDetonate(slotIndex, targetKind, targetId, targetStableId, pos, normal, shotDir, burstIndex: 0); + return; + } + + var childDef = rule.ChildNode; + int count = Math.Clamp(rule.SplitCount, 1, OrdnanceNodeDef.MaxShotSubSpawnBudget); + float coneRad = Math.Clamp(rule.SplitConeDeg, 5f, 170f) * MathF.PI / 180f; + + int parentId = inst.OrdnanceId; + byte childDepth = (byte)(inst.Depth + 1); + ulong shooterStableId = inst.ShooterStableId; + int shooterContenderId = inst.ShooterContenderId; + bool isSpec = inst.IsSpectatorShooter; + string shooterLabel = inst.ShooterLabel; + string weaponId = inst.WeaponId; + ProceduralWeaponKey? key = inst.WeaponKey; + Vector3 originPos = inst.ShooterOriginPos; + ulong tgt = inst.TargetStableId; + float scale = inst.DamageScale; + + EmitNetEvent(in inst, OrdnanceEventKind.Split); + FreeSlot(slotIndex); + + Vector3 forwardBase = new Vector3(shotDir.X, 0f, shotDir.Z); + forwardBase = forwardBase.LengthSquared() > 1e-4f + ? Vector3.Normalize(forwardBase * 0.85f - Vector3.UnitY * 0.55f) + : -Vector3.UnitY; + + if (targetKind is HitTargetKind.Terrain or HitTargetKind.StaticCover or HitTargetKind.Contender) + { + if (childDef.Motion == OrdnanceMotion.Ballistic && Vector3.Dot(shotDir, normal) < 0f) + { + forwardBase = Vector3.Normalize(Vector3.Reflect(shotDir, normal) + normal * 0.35f); + } + } + + var rng = _sink.State.Rng; + for (int k = 0; k < count; k++) + { + float frac = count == 1 ? 0f : (k / (float)count) * MathF.Tau; + float radial = coneRad * (0.35f + 0.65f * ((k % 3 + 1) / 3f)); + float yawOff = MathF.Cos(frac) * radial + ((float)rng.NextDouble() - 0.5f) * 0.08f; + float pitchOff = MathF.Sin(frac) * radial * 0.5f; + Vector3 cDir = ApplySpread(forwardBase, yawOff, pitchOff); + Vector3 cPos = pos + normal * 0.25f; + Vector3 cVel = cDir * childDef.InitialSpeed; + + SpawnInstance( + parentId, + childDepth, + childDef, + shooterStableId, + shooterContenderId, + isSpec, + shooterLabel, + weaponId, + key, + cPos, + cVel, + normal, + originPos, + tgt, + scale, + OrdnanceEventKind.Spawned, + createdStep: _stepCounter); + } + break; + } + } + } + + private void ExecuteDetonate( + int slotIndex, + HitTargetKind targetKind, + int targetId, + ulong targetStableId, + Vector3 hitPoint, + Vector3 surfaceNormal, + Vector3 shotDir, + int burstIndex) + { + ref var inst = ref _pool[slotIndex]; + var def = inst.Def; + + ContenderState? shooterContender = !inst.IsSpectatorShooter && + inst.ShooterContenderId >= 0 && + inst.ShooterContenderId < _sink.State.Contenders.Count + ? _sink.State.Contenders[inst.ShooterContenderId] + : null; + int shooterEntityId = inst.IsSpectatorShooter + ? (int)(inst.ShooterStableId - 3000UL) + : inst.ShooterContenderId; + + ulong directActorId = 0; + if (targetKind is HitTargetKind.Contender or HitTargetKind.Spectator && targetStableId != 0) + { + directActorId = targetStableId; + ApplyActorDirectHit(in inst, targetStableId, hitPoint, shotDir); + } + else if (targetKind == HitTargetKind.Terrain) + { + bool allowCrater = !def.CraterFirstBurstOnly || burstIndex == 0; + if (allowCrater && (def.CraterRadius > 0f || def.ScorchRadius > 0f)) + { + _sink.StampTerrainImpact(hitPoint.X, hitPoint.Z, def.CraterRadius, def.CraterDepth, def.ScorchRadius); + } + _sink.EmitNonActorHit( + HitTargetKind.Terrain, + -1, + hitPoint, + surfaceNormal, + inst.ShooterOriginPos, + def.VisualClass, + inst.WeaponId, + def.IsAirburst, + inst.IsSpectatorShooter, + shooterEntityId); + } + else + { + _sink.EmitNonActorHit( + HitTargetKind.StaticCover, + targetId, + hitPoint, + surfaceNormal, + inst.ShooterOriginPos, + def.VisualClass, + inst.WeaponId, + def.IsAirburst, + inst.IsSpectatorShooter, + shooterEntityId); + } + + if (def.SplashDamage > 0f && def.SplashRadius > 0.1f) + { + if (targetKind != HitTargetKind.Terrain && (def.CraterRadius > 0f || def.ScorchRadius > 0f)) + { + float groundY = _sink.State.Terrain.SampleHeight(hitPoint.X, hitPoint.Z); + if (hitPoint.Y - groundY <= def.SplashRadius) + { + _sink.StampTerrainImpact(hitPoint.X, hitPoint.Z, def.CraterRadius * 0.8f, def.CraterDepth * 0.7f, def.ScorchRadius); + } + } + + _sink.ApplySplashDamage( + hitPoint, + def.SplashRadius, + def.SplashDamage * inst.DamageScale, + def.HeatTransfer * inst.DamageScale, + def.VisualClass, + inst.WeaponId, + shooterContender, + inst.ShooterLabel, + inst.IsSpectatorShooter, + shooterEntityId, + ignoreStableId: directActorId); + } + + EmitNetEvent(in inst, OrdnanceEventKind.Detonated); + FreeSlot(slotIndex); + } + + private void ApplyActorDirectHit(in LiveOrdnanceInstance inst, ulong targetStableId, Vector3 hitPoint, Vector3 shotDir) + { + ContenderState? shooterContender = !inst.IsSpectatorShooter && + inst.ShooterContenderId >= 0 && + inst.ShooterContenderId < _sink.State.Contenders.Count + ? _sink.State.Contenders[inst.ShooterContenderId] + : null; + int shooterEntityId = inst.IsSpectatorShooter + ? (int)(inst.ShooterStableId - 3000UL) + : inst.ShooterContenderId; + + _sink.ApplyDirectHit( + targetStableId, + (hitPoint.X, hitPoint.Y, hitPoint.Z), + shotDir, + inst.ShooterOriginPos, + inst.Def.VisualClass, + inst.WeaponId, + inst.Def.IsAirburst, + inst.Def.DirectDamage * inst.DamageScale, + inst.Def.HeatTransfer * inst.DamageScale, + shooterContender, + inst.ShooterLabel, + inst.IsSpectatorShooter, + shooterEntityId); + } + + private void ResolveHitscanBeam( + OrdnanceNodeDef def, + Vector3 muzzle, + Vector3 dir, + float aimDist, + Vector3 shooterPos, + ulong shooterStableId, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + int shooterEntityId, + string weaponId, + float damageScale, + int burstIndex) + { + float range = MathF.Max(5f, def.Range); + Vector3 castOrigin = muzzle; + float remainingRange = range; + int penetrations = 0; + ulong lastPenetratedId = 0; + float currDmgScale = damageScale; + + bool hitAny = false; + bool hitTerrain = false; + float terrainHitX = 0f, terrainHitY = 0f, terrainHitZ = 0f; + ulong hitStableId = 0; + (float X, float Y, float Z) hitPoint = default; + Vector3 hitNormal = -dir; + + for (int hop = 0; hop < 6 && remainingRange > 0.2f; hop++) + { + var rayHit = _sink.World.CastRayClosest( + (castOrigin.X, castOrigin.Y, castOrigin.Z), + (dir.X * remainingRange, dir.Y * remainingRange, dir.Z * remainingRange)); + + float boxSegDist = rayHit.Hit + ? Vector3.Distance(castOrigin, new Vector3(rayHit.Point.X, rayHit.Point.Y, rayHit.Point.Z)) + : remainingRange; + + bool isSelfOrPenetrated = rayHit.Hit && + (rayHit.StableId == shooterStableId || (lastPenetratedId != 0 && rayHit.StableId == lastPenetratedId)); + if (isSelfOrPenetrated) + { + float skip = MathF.Max(0.15f, boxSegDist + 0.08f); + float skipCheckDist = MathF.Min(remainingRange, skip); + if (_sink.State.Terrain.Raycast( + castOrigin.X, castOrigin.Y, castOrigin.Z, + dir.X, dir.Y, dir.Z, + skipCheckDist, + out float sTx, out float sTy, out float sTz, out float sTDist)) + { + if (!TryHitInterceptableOrdnance(castOrigin, dir, sTDist, shooterStableId, out int ordSlotPre, out float ordDistPre, out Vector3 ordHitPre) || + ordDistPre >= sTDist) + { + hitTerrain = true; + terrainHitX = sTx; + terrainHitY = sTy; + terrainHitZ = sTz; + hitAny = false; + break; + } + ref var targetOrdPre = ref _pool[ordSlotPre]; + targetOrdPre.Hp -= def.DirectDamage * currDmgScale; + if (targetOrdPre.Hp <= 0f) + { + EmitNetEvent(in targetOrdPre, OrdnanceEventKind.Intercepted); + FreeSlot(ordSlotPre); + } + _sink.EmitNonActorHit(HitTargetKind.StaticCover, -1, ordHitPre, -dir, shooterPos, def.VisualClass, weaponId, isAirburst: true, isSpectatorShooter, shooterEntityId); + _sink.EmitTracer(muzzle, ordHitPre, def.ColorRgba, def.TracerTtl, def.VisualClass, weaponId, isSpectatorShooter, shooterEntityId); + return; + } + + castOrigin += dir * skip; + remainingRange = MathF.Max(0f, remainingRange - skip); + continue; + } + + bool hitTerrainSeg = _sink.State.Terrain.Raycast( + castOrigin.X, castOrigin.Y, castOrigin.Z, + dir.X, dir.Y, dir.Z, + boxSegDist, + out float stx, out float sty, out float stz, out float terrainSegDist); + float solidSegDist = (hitTerrainSeg && terrainSegDist <= boxSegDist) ? terrainSegDist : boxSegDist; + + // Also check interceptable airborne ordnance strictly before any solid terrain/Box3D hit + if (TryHitInterceptableOrdnance(castOrigin, dir, solidSegDist, shooterStableId, out int ordSlot, out float ordDist, out Vector3 ordHitPt)) + { + if (ordDist < solidSegDist) + { + ref var targetOrd = ref _pool[ordSlot]; + targetOrd.Hp -= def.DirectDamage * currDmgScale; + if (targetOrd.Hp <= 0f) + { + EmitNetEvent(in targetOrd, OrdnanceEventKind.Intercepted); + FreeSlot(ordSlot); + } + _sink.EmitNonActorHit( + HitTargetKind.StaticCover, + -1, + ordHitPt, + -dir, + shooterPos, + def.VisualClass, + weaponId, + isAirburst: true, + isSpectatorShooter, + shooterEntityId); + _sink.EmitTracer(muzzle, ordHitPt, def.ColorRgba, def.TracerTtl, def.VisualClass, weaponId, isSpectatorShooter, shooterEntityId); + return; + } + } + + if (hitTerrainSeg && (!rayHit.Hit || terrainSegDist <= boxSegDist)) + { + hitTerrain = true; + terrainHitX = stx; + terrainHitY = sty; + terrainHitZ = stz; + hitAny = false; + break; + } + + if (!rayHit.Hit) + { + break; + } + + var ptVec = new Vector3(rayHit.Point.X, rayHit.Point.Y, rayHit.Point.Z); + if (_sink.TryResolveActor(rayHit.StableId, out _, out _) && penetrations < def.MaxPenetrations) + { + _sink.ApplyDirectHit( + rayHit.StableId, + rayHit.Point, + dir, + shooterPos, + def.VisualClass, + weaponId, + def.IsAirburst, + def.DirectDamage * currDmgScale, + def.HeatTransfer * currDmgScale, + shooterContender, + shooterLabel, + isSpectatorShooter, + shooterEntityId); + penetrations++; + currDmgScale *= def.PenetrationDamageDecay; + lastPenetratedId = rayHit.StableId; + float skip = MathF.Max(0.25f, Vector3.Distance(castOrigin, ptVec) + 0.12f); + castOrigin += dir * skip; + remainingRange = MathF.Max(0f, remainingRange - skip); + continue; + } + + if (Box3DPhysicsTileSync.IsHeightfieldTileStableId(rayHit.StableId)) + { + hitTerrain = true; + terrainHitX = rayHit.Point.X; + terrainHitY = rayHit.Point.Y; + terrainHitZ = rayHit.Point.Z; + hitAny = false; + break; + } + + hitAny = true; + hitStableId = rayHit.StableId; + hitPoint = rayHit.Point; + Vector3 rn = new(rayHit.Normal.X, rayHit.Normal.Y, rayHit.Normal.Z); + if (rn.LengthSquared() > 1e-4f) + { + hitNormal = Vector3.Normalize(rn); + } + break; + } + + Vector3 endPt; + if (hitTerrain) + { + float tx = terrainHitX; + float ty = terrainHitY; + float tz = terrainHitZ; + endPt = new Vector3(tx, ty, tz); + bool allowCrater = !def.CraterFirstBurstOnly || burstIndex == 0; + if (allowCrater && (def.CraterRadius > 0f || def.ScorchRadius > 0f)) + { + _sink.StampTerrainImpact(tx, tz, def.CraterRadius, def.CraterDepth, def.ScorchRadius); + } + + var (tnx, tny, tnz) = _sink.State.Terrain.SampleNormal(tx, tz); + _sink.EmitNonActorHit( + HitTargetKind.Terrain, + -1, + endPt, + new Vector3(tnx, tny, tnz), + shooterPos, + def.VisualClass, + weaponId, + isAirburst: false, + isSpectatorShooter, + shooterEntityId); + + if (def.SplashDamage > 0f && def.SplashRadius > 0.1f) + { + _sink.ApplySplashDamage(endPt, def.SplashRadius, def.SplashDamage * currDmgScale, def.HeatTransfer * currDmgScale, def.VisualClass, weaponId, shooterContender, shooterLabel, isSpectatorShooter, shooterEntityId, ignoreStableId: 0UL); + } + + SpawnHitscanImpactChildren(def, endPt, new Vector3(tnx, tny, tnz), dir, shooterStableId, shooterContender, shooterLabel, isSpectatorShooter, shooterPos, weaponId, currDmgScale); + } + else + { + endPt = hitAny + ? new Vector3(hitPoint.X, hitPoint.Y, hitPoint.Z) + : muzzle + dir * range; + + if (hitAny && hitStableId != shooterStableId && _sink.TryResolveActor(hitStableId, out _, out _)) + { + _sink.ApplyDirectHit( + hitStableId, + hitPoint, + dir, + shooterPos, + def.VisualClass, + weaponId, + def.IsAirburst, + def.DirectDamage * currDmgScale, + def.HeatTransfer * currDmgScale, + shooterContender, + shooterLabel, + isSpectatorShooter, + shooterEntityId); + + if (def.SplashDamage > 0f && def.SplashRadius > 0.1f) + { + _sink.ApplySplashDamage(endPt, def.SplashRadius, def.SplashDamage * currDmgScale, def.HeatTransfer * currDmgScale, def.VisualClass, weaponId, shooterContender, shooterLabel, isSpectatorShooter, shooterEntityId, ignoreStableId: hitStableId); + } + + SpawnHitscanImpactChildren(def, endPt, hitNormal, dir, shooterStableId, shooterContender, shooterLabel, isSpectatorShooter, shooterPos, weaponId, currDmgScale); + } + else if (hitAny && hitStableId != shooterStableId) + { + _sink.EmitNonActorHit( + HitTargetKind.StaticCover, + (int)hitStableId, + endPt, + -dir, + shooterPos, + def.VisualClass, + weaponId, + def.IsAirburst, + isSpectatorShooter, + shooterEntityId); + + SpawnHitscanImpactChildren(def, endPt, hitNormal, dir, shooterStableId, shooterContender, shooterLabel, isSpectatorShooter, shooterPos, weaponId, currDmgScale); + } + else if (def.IsAirburst && burstIndex == 0) + { + Vector3 airPt = muzzle + dir * MathF.Min(range, MathF.Max(20f, aimDist)); + _sink.EmitNonActorHit( + HitTargetKind.StaticCover, + -1, + airPt, + -dir, + shooterPos, + def.VisualClass, + weaponId, + isAirburst: true, + isSpectatorShooter, + shooterEntityId); + } + } + + _sink.EmitTracer(muzzle, endPt, def.ColorRgba, def.TracerTtl, def.VisualClass, weaponId, isSpectatorShooter, shooterEntityId); + } + + private void SpawnHitscanImpactChildren( + OrdnanceNodeDef def, + Vector3 hitPt, + Vector3 normal, + Vector3 shotDir, + ulong shooterStableId, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + Vector3 shooterPos, + string weaponId, + float scale) + { + if (def.Depth + 1 >= OrdnanceNodeDef.MaxAllowedDepth) + { + return; + } + + for (int t = 0; t < def.Triggers.Length; t++) + { + var tr = def.Triggers[t]; + if (tr.Kind == OrdnanceTriggerKind.Impact && + tr.Action == OrdnanceTriggerAction.Split && + tr.ChildNode is not null) + { + int count = Math.Clamp(tr.SplitCount, 1, OrdnanceNodeDef.MaxShotSubSpawnBudget); + float coneRad = Math.Clamp(tr.SplitConeDeg, 5f, 170f) * MathF.PI / 180f; + Vector3 bounceBase = Vector3.Normalize(Vector3.Reflect(shotDir, normal) + normal * 0.45f); + var rng = _sink.State.Rng; + + for (int k = 0; k < count; k++) + { + float ang = (k / (float)count) * MathF.Tau; + float yawOff = MathF.Cos(ang) * coneRad * 0.65f + ((float)rng.NextDouble() - 0.5f) * 0.1f; + float pitchOff = MathF.Sin(ang) * coneRad * 0.35f; + Vector3 cDir = ApplySpread(bounceBase, yawOff, pitchOff); + SpawnInstance( + parentId: 0, + depth: (byte)(def.Depth + 1), + tr.ChildNode, + shooterStableId, + shooterContender?.Id ?? -1, + isSpectatorShooter, + shooterLabel, + weaponId, + weaponKey: null, + hitPt + normal * 0.25f, + cDir * tr.ChildNode.InitialSpeed, + normal, + shooterPos, + targetStableId: 0UL, + scale, + OrdnanceEventKind.Spawned, + createdStep: _stepCounter); + } + return; + } + } + } + + private bool IsFriendlyOrdnance( + ulong shooterStableId, + bool shooterIsContender, + int shooterContenderId, + in LiveOrdnanceInstance inst) + { + if (inst.ShooterStableId == shooterStableId) + { + return true; + } + if (!shooterIsContender || shooterContenderId < 0) + { + return false; + } + if (!inst.IsSpectatorShooter && inst.ShooterContenderId >= 0) + { + return _sink.State.AreAllies(shooterContenderId, inst.ShooterContenderId); + } + if (_sink.TryResolveActor(inst.ShooterStableId, out bool instIsContender, out int instContenderId) && + instIsContender && + instContenderId >= 0) + { + return _sink.State.AreAllies(shooterContenderId, instContenderId); + } + return false; + } + + private bool TryHitInterceptableOrdnance( + Vector3 origin, + Vector3 dir, + float maxDist, + ulong shooterStableId, + out int bestSlot, + out float bestDist, + out Vector3 hitPt) + { + bestSlot = -1; + bestDist = maxDist; + hitPt = Vector3.Zero; + bool shooterIsContender = _sink.TryResolveActor(shooterStableId, out bool sIsC, out int shooterContenderId) && sIsC; + + for (int i = 0; i < PoolCapacity; i++) + { + if (!_pool[i].Active) + { + continue; + } + ref readonly var inst = ref _pool[i]; + if (inst.Def.InterceptHp <= 0f || IsFriendlyOrdnance(shooterStableId, shooterIsContender, shooterContenderId, in inst)) + { + continue; + } + + float radius = inst.Def.Motion == OrdnanceMotion.LoiterOrbit ? 1.8f : 1.0f; + Vector3 m = origin - inst.Pos; + float b = Vector3.Dot(m, dir); + float c = Vector3.Dot(m, m) - radius * radius; + if (c > 0f && b > 0f) + { + continue; + } + float discr = b * b - c; + if (discr < 0f) + { + continue; + } + float t = MathF.Max(0f, -b - MathF.Sqrt(discr)); + if (t <= bestDist) + { + bestDist = t; + bestSlot = i; + hitPt = origin + dir * t; + } + } + + return bestSlot >= 0; + } + + private int SpawnInstance( + int parentId, + byte depth, + OrdnanceNodeDef def, + ulong shooterStableId, + int shooterContenderId, + bool isSpectatorShooter, + string shooterLabel, + string weaponId, + ProceduralWeaponKey? weaponKey, + Vector3 pos, + Vector3 vel, + Vector3 normal, + Vector3 shooterOriginPos, + ulong targetStableId, + float damageScale, + OrdnanceEventKind emitKind, + int createdStep) + { + if (depth >= OrdnanceNodeDef.MaxAllowedDepth) + { + return -1; + } + + int slot = FindFreeSlot(); + if (slot < 0) + { + slot = EvictLowestPrioritySlot(); + } + + int id = _nextOrdnanceId++; + if (depth > MaxObservedDepth) + { + MaxObservedDepth = depth; + } + + _pool[slot] = new LiveOrdnanceInstance + { + Active = true, + OrdnanceId = id, + ParentOrdnanceId = parentId, + ShooterStableId = shooterStableId, + ShooterContenderId = shooterContenderId, + IsSpectatorShooter = isSpectatorShooter, + ShooterLabel = shooterLabel, + WeaponId = weaponId, + WeaponKey = weaponKey, + Def = def, + Depth = depth, + Pos = pos, + PrevPos = pos, + Vel = vel, + SurfaceNormal = normal, + AnchorPos = pos, + ShooterOriginPos = shooterOriginPos, + TargetStableId = targetStableId, + Age = 0f, + StageAge = 0f, + WhileAliveTimer = def.WhileAlive is { } wa ? MathF.Max(0f, wa.Interval - 0.1f) : 0f, + WhileAliveCount = 0, + OrbitAngle = 0f, + Hp = def.InterceptHp, + Armed = def.ArmDelay <= 0f, + EjectSabotVfx = false, + PenetrationsUsed = 0, + LastPenetratedStableId = 0, + DamageScale = damageScale, + CreatedStep = createdStep + }; + + ActiveCount++; + EmitNetEvent(in _pool[slot], emitKind); + return slot; + } + + private int FindFreeSlot() + { + for (int i = 0; i < PoolCapacity; i++) + { + if (!_pool[i].Active) + { + return i; + } + } + return -1; + } + + private int EvictLowestPrioritySlot() + { + int bestIdx = 0; + int lowestTier = int.MaxValue; + float oldestAge = -1f; + + for (int i = 0; i < PoolCapacity; i++) + { + ref readonly var inst = ref _pool[i]; + if (!inst.Active) + { + return i; + } + + int tier = inst.Def.Motion switch + { + OrdnanceMotion.StationaryMine => 0, + OrdnanceMotion.Ballistic when inst.Depth > 0 => 1, + OrdnanceMotion.Ballistic or OrdnanceMotion.RocketBoosted => 2, + OrdnanceMotion.HomingMissile => 3, + OrdnanceMotion.LoiterOrbit => 4, + _ => 0 + }; + + if (tier < lowestTier || (tier == lowestTier && inst.Age > oldestAge)) + { + lowestTier = tier; + oldestAge = inst.Age; + bestIdx = i; + } + } + + EmitNetEvent(in _pool[bestIdx], OrdnanceEventKind.Expired); + FreeSlot(bestIdx); + return bestIdx; + } + + private void FreeSlot(int slotIndex) + { + if (_pool[slotIndex].Active) + { + _pool[slotIndex] = default; + ActiveCount--; + } + } + + private void EmitNetEvent(in LiveOrdnanceInstance inst, OrdnanceEventKind kind) + { + int shooterEntityId = inst.IsSpectatorShooter + ? (int)(inst.ShooterStableId - 3000UL) + : inst.ShooterContenderId; + + int targetEntityId = -1; + bool targetIsSpec = false; + if (inst.TargetStableId >= 3000UL) + { + targetIsSpec = true; + targetEntityId = (int)(inst.TargetStableId - 3000UL); + } + else if (inst.TargetStableId >= ArenaSession.ContenderStableIdBase) + { + targetEntityId = (int)(inst.TargetStableId - ArenaSession.ContenderStableIdBase); + } + + _netEvents.Add(new OrdnanceNetEvent( + inst.OrdnanceId, + inst.ParentOrdnanceId, + (byte)kind == (byte)OrdnanceEventKind.Spawned ? OrdnanceEventKind.Spawned : kind, + inst.ShooterStableId, + inst.IsSpectatorShooter, + shooterEntityId, + inst.WeaponKey, + inst.Def.DefIndex, + inst.Pos, + inst.Vel, + targetEntityId, + targetIsSpec, + _sink.State.Time, + (byte)inst.Def.VisualShape, + inst.Def.ColorRgba)); + } + + private static Vector3 ApplyPitchBias(Vector3 dir, float pitchDeg) + { + if (MathF.Abs(pitchDeg) < 0.01f) + { + return dir; + } + Vector3 right = Vector3.Cross(dir, Vector3.UnitY); + if (right.LengthSquared() < 1e-5f) + { + right = Vector3.UnitX; + } + else + { + right = Vector3.Normalize(right); + } + // Cross(dir, UnitY) with positive angle pitches upward (+Y) + float rad = pitchDeg * MathF.PI / 180f; + var q = Quaternion.CreateFromAxisAngle(right, rad); + Vector3 pitched = Vector3.Transform(dir, q); + return pitched.LengthSquared() > 1e-6f ? Vector3.Normalize(pitched) : Vector3.UnitY; + } + + private static Vector3 ApplySpread(Vector3 baseDir, float yawOffset, float pitchOffset) + { + var yawQ = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawOffset); + var rotated = Vector3.Transform(baseDir, yawQ); + var right = Vector3.Cross(rotated, Vector3.UnitY); + if (right.LengthSquared() > 1e-4f) + { + var pitchQ = Quaternion.CreateFromAxisAngle(Vector3.Normalize(right), pitchOffset); + rotated = Vector3.Transform(rotated, pitchQ); + } + return Vector3.Normalize(rotated); + } + + private static Vector3 RotateTowards(Vector3 current, Vector3 target, float maxRadians) + { + float dot = Math.Clamp(Vector3.Dot(current, target), -1f, 1f); + float angle = MathF.Acos(dot); + if (angle <= maxRadians || angle < 1e-4f) + { + return target; + } + float t = maxRadians / angle; + Vector3 lerped = Vector3.Lerp(current, target, t); + return lerped.LengthSquared() > 1e-6f ? Vector3.Normalize(lerped) : target; + } + } +} diff --git a/src/RustToDust.Ymir/RustToDust.Ymir.csproj b/src/RustToDust.Ymir/RustToDust.Ymir.csproj new file mode 100644 index 0000000..7cbb8d7 --- /dev/null +++ b/src/RustToDust.Ymir/RustToDust.Ymir.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + disable + Release + + + + + + + + diff --git a/src/RustToDust.Ymir/WalkerLocomotion.cs b/src/RustToDust.Ymir/WalkerLocomotion.cs new file mode 100644 index 0000000..1a37040 --- /dev/null +++ b/src/RustToDust.Ymir/WalkerLocomotion.cs @@ -0,0 +1,1797 @@ +using System; +using System.Numerics; +using System.Runtime.CompilerServices; +using RustToDust.Core; +using Ymir.Box3D; + +namespace RustToDust.Ymir +{ + public readonly struct WalkerLegSpec + { + public WalkerLegSpec( + Vector3 hipInCom, + Vector2 restFootXZ, + float l1, + float l2, + float l3, + float ankleH, + float kneeBendSign, + bool isArachnidUp) + { + HipInCom = hipInCom; + RestFootXZ = restFootXZ; + L1 = l1; + L2 = l2; + L3 = l3; + AnkleH = ankleH; + KneeBendSign = kneeBendSign; + + if (isArachnidUp) + { + Vector3 rad = new(restFootXZ.X - hipInCom.X, 0f, restFootXZ.Y - hipInCom.Z); + LegFwd0 = rad.LengthSquared() > 1e-6f ? Vector3.Normalize(rad) : Vector3.UnitZ; + LegRight0 = Vector3.Cross(Vector3.UnitY, LegFwd0); + } + else if (MathF.Abs(restFootXZ.X - hipInCom.X) > 0.05f || MathF.Abs(restFootXZ.Y - hipInCom.Z) > 0.05f) + { + Vector3 splay = new( + (restFootXZ.X - hipInCom.X) * kneeBendSign, + 0f, + (restFootXZ.Y - hipInCom.Z) * kneeBendSign); + LegFwd0 = splay.LengthSquared() > 1e-6f ? Vector3.Normalize(splay) : Vector3.UnitZ; + LegRight0 = Vector3.Cross(Vector3.UnitY, LegFwd0); + } + else + { + LegRight0 = Vector3.UnitX; + LegFwd0 = Vector3.UnitZ; + } + + MaxLegReach = l3 > 0f ? (l1 + l2 + l3 - 0.08f) : (l1 + l2 - 0.02f); + MinLegReach = l3 > 0f ? MathF.Max(0.45f, MathF.Abs(l1 - l2) + 0.15f) : (MathF.Abs(l1 - l2) + 0.06f); + } + + public Vector3 HipInCom { get; } + public Vector2 RestFootXZ { get; } + public float L1 { get; } + public float L2 { get; } + public float L3 { get; } + public float AnkleH { get; } + public float KneeBendSign { get; } + public Vector3 LegRight0 { get; } + public Vector3 LegFwd0 { get; } + public float MaxLegReach { get; } + public float MinLegReach { get; } + } + + public sealed class WalkerGeometrySpec + { + public string Id { get; } + public int LegCount { get; } + public bool IsDigitigrade { get; } + public bool IsArachnidUp { get; } + public float ModelHalfHeight { get; } + public float ModelRideHeight { get; } + public float FootHalfW { get; } + public float FootHalfL { get; } + public float SwingArcHeight { get; } + public float MaxStepRadius { get; } + public readonly LegArray4 Legs; + + private WalkerGeometrySpec( + string id, + int legCount, + bool isDigitigrade, + bool isArachnidUp, + float modelHalfHeight, + float modelRideHeight, + float footHalfW, + float footHalfL, + float swingArcHeight, + float maxStepRadius, + LegArray4 legs) + { + Id = id; + LegCount = legCount; + IsDigitigrade = isDigitigrade; + IsArachnidUp = isArachnidUp; + ModelHalfHeight = modelHalfHeight; + ModelRideHeight = modelRideHeight; + FootHalfW = footHalfW; + FootHalfL = footHalfL; + SwingArcHeight = swingArcHeight; + MaxStepRadius = maxStepRadius; + Legs = legs; + } + + public static readonly WalkerGeometrySpec Breaker = BuildBreaker(); + public static readonly WalkerGeometrySpec Paladin = BuildPaladin(); + public static readonly WalkerGeometrySpec Raptor = BuildRaptor(); + public static readonly WalkerGeometrySpec Spectre = BuildSpectre(); + public static readonly WalkerGeometrySpec Kestrel = BuildKestrel(); + public static readonly WalkerGeometrySpec Manticore = BuildManticore(); + public static readonly WalkerGeometrySpec Bastion = BuildBastion(); + + public static WalkerGeometrySpec GetForChassis(string chassisId) => + chassisId.ToLowerInvariant() switch + { + "breaker" => Breaker, + "paladin" => Paladin, + "raptor" => Raptor, + "exemplar_frame" => Raptor, + "spectre" => Spectre, + "kestrel" => Kestrel, + "manticore" => Manticore, + "bastion" => Bastion, + _ => Raptor + }; + + private static WalkerGeometrySpec BuildBreaker() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+1.0809f, +0.2170f, 0f), new Vector2(+1.0809f, 0f), 1.3203f, 1.4396f, 0f, 0.6249f, +1f, false); + legs[1] = new WalkerLegSpec(new Vector3(-1.0809f, +0.2170f, 0f), new Vector2(-1.0809f, 0f), 1.3203f, 1.4396f, 0f, 0.6249f, +1f, false); + return new WalkerGeometrySpec("breaker", 2, false, false, 3.1456f, 2.99f, 0.55f, 0.80f, 0.73f, 2.40f, legs); + } + + private static WalkerGeometrySpec BuildPaladin() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+1.4853f, -0.2004f, +0.05f), new Vector2(+1.4853f, +0.05f), 1.9600f, 2.7200f, 0f, 1.0903f, +1f, false); + legs[1] = new WalkerLegSpec(new Vector3(-1.5047f, -0.1983f, +0.05f), new Vector2(-1.5047f, +0.05f), 1.9600f, 2.7200f, 0f, 1.0903f, +1f, false); + return new WalkerGeometrySpec("paladin", 2, false, false, 5.6581f, 5.52f, 0.82f, 1.20f, 1.08f, 3.60f, legs); + } + + private static WalkerGeometrySpec BuildRaptor() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+1.4000f, +1.1712f, 0f), new Vector2(+1.4000f, 0f), 1.9000f, 1.6000f, 1.7600f, 0.8173f, +1f, false); + legs[1] = new WalkerLegSpec(new Vector3(-1.4000f, +1.1712f, 0f), new Vector2(-1.4000f, 0f), 1.9000f, 1.6000f, 1.7600f, 0.8173f, +1f, false); + return new WalkerGeometrySpec("raptor", 2, true, false, 3.4937f, 3.52f, 0.62f, 0.95f, 0.88f, 3.30f, legs); + } + + private static WalkerGeometrySpec BuildSpectre() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+1.2500f, -0.0970f, +0.2227f), new Vector2(+1.2500f, +0.2227f), 1.7300f, 1.5340f, 1.8370f, 0.7385f, +1f, false); + legs[1] = new WalkerLegSpec(new Vector3(-1.2500f, -0.1199f, +0.1996f), new Vector2(-1.2500f, +0.1996f), 1.7300f, 1.5340f, 1.8370f, 0.7385f, +1f, false); + return new WalkerGeometrySpec("spectre", 2, true, false, 4.4946f, 4.52f, 0.70f, 1.05f, 0.98f, 3.40f, legs); + } + + private static WalkerGeometrySpec BuildKestrel() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+1.3000f, +1.3093f, 0f), new Vector2(+1.3000f, 0f), 2.5760f, 3.0621f, 0f, 0.8500f, +1f, false); + legs[1] = new WalkerLegSpec(new Vector3(-1.3000f, +1.3093f, 0f), new Vector2(-1.3000f, 0f), 2.6252f, 3.0551f, 0f, 0.8500f, +1f, false); + return new WalkerGeometrySpec("kestrel", 2, false, false, 4.8907f, 4.94f, 0.68f, 1.00f, 0.98f, 3.60f, legs); + } + + private static WalkerGeometrySpec BuildManticore() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+1.4200f, -2.4075f, +1.95f), new Vector2(+2.259f, +3.319f), 1.4719f, 1.7205f, 0f, 0.4625f, +1f, true); + legs[1] = new WalkerLegSpec(new Vector3(-1.4200f, -2.4075f, +1.95f), new Vector2(-2.259f, +3.319f), 1.4719f, 1.7205f, 0f, 0.4625f, +1f, true); + legs[2] = new WalkerLegSpec(new Vector3(+1.4800f, -2.3875f, -1.90f), new Vector2(+2.483f, -3.479f), 1.5819f, 1.8711f, 0f, 0.4225f, +1f, true); + legs[3] = new WalkerLegSpec(new Vector3(-1.4800f, -2.3875f, -1.90f), new Vector2(-2.483f, -3.479f), 1.5819f, 1.8711f, 0f, 0.4225f, +1f, true); + return new WalkerGeometrySpec("manticore", 4, false, true, 3.2500f, 3.28f, 0.45f, 0.55f, 0.78f, 2.25f, legs); + } + + private static WalkerGeometrySpec BuildBastion() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+4.2040f, -1.2643f, +4.2453f), new Vector2(+4.359f, +5.264f), 1.8041f, 1.2676f, 0f, 0.8855f, +1f, false); + legs[1] = new WalkerLegSpec(new Vector3(-4.2040f, -1.2643f, +4.2453f), new Vector2(-4.359f, +5.264f), 1.8041f, 1.2676f, 0f, 0.8855f, +1f, false); + legs[2] = new WalkerLegSpec(new Vector3(+3.6871f, -0.1774f, -4.2453f), new Vector2(+5.033f, -6.736f), 4.4637f, 0.9009f, 0f, 0.7259f, -1f, false); + legs[3] = new WalkerLegSpec(new Vector3(-3.6871f, -0.1774f, -4.2453f), new Vector2(-5.033f, -6.736f), 4.4637f, 0.9009f, 0f, 0.7259f, -1f, false); + return new WalkerGeometrySpec("bastion", 4, false, false, 4.8125f, 4.84f, 0.85f, 1.10f, 0.94f, 2.95f, legs); + } + } + + public struct WalkerJointActuator + { + public WalkerLegAngles Theta; + public WalkerLegAngles Omega; + public float RecoilHipImpulse; + public float RecoilKneeImpulse; + } + + public struct WalkerCheckpoint + { + public int GeomLegCount; + public float GeomScale; + public bool Initialized; + public int StanceGroup; + public float SwingTime; + public float SwingPhase; + public float SimTime; + public bool IsAirborne; + public bool WasAirborne; + public float MaxFootSlipM; + public Vector3 LastTotalForce; + public Vector3 LastTotalTorque; + public LegArray4 Planted; + public LegArray4 FootSole; + public LegArray4 SwingStartSole; + public LegArray4 SwingTargetSole; + public LegArray4 FootNormal; + public LegArray4 SwingStartNormal; + public LegArray4 SwingTargetNormal; + public LegArray4 LastGrfY; + public LegArray4 Actuators; + public WalkerVisualSnapshot PrevSnap; + public WalkerVisualSnapshot CurrSnap; + } + + public sealed class WalkerState + { + public const float ArenaGravity = 20f; + public const float FootFriction = 1.10f; + + public WalkerGeometrySpec Geom { get; private set; } + public float GeomScale { get; private set; } + public bool Initialized { get; private set; } + + public int StanceGroup; + public float SwingTime; + public float SwingPhase; + public float SimTime; + public bool IsAirborne; + public bool WasAirborne; + public float MaxFootSlipM; + public Vector3 LastTotalForce; + public Vector3 LastTotalTorque; + + public LegArray4 Planted; + public LegArray4 FootSole; + public LegArray4 SwingStartSole; + public LegArray4 SwingTargetSole; + public LegArray4 FootNormal; + public LegArray4 SwingStartNormal; + public LegArray4 SwingTargetNormal; + public LegArray4 LastGrfY; + public LegArray4 Actuators; + + public WalkerVisualSnapshot PrevSnap; + public WalkerVisualSnapshot CurrSnap; + + public WalkerState(ChassisSpec spec) + { + Geom = WalkerGeometrySpec.GetForChassis(spec.Id); + GeomScale = Geom.ModelHalfHeight > 1e-4f ? spec.HalfHeight / Geom.ModelHalfHeight : 1f; + } + + public void InitializePose(Vector3 comPos, Quaternion qBody, float mass, TerrainField terrain) + { + int n = Geom.LegCount; + StanceGroup = 0; + SwingTime = 0f; + SwingPhase = 0f; + SimTime = 0f; + bool anyCanReach = false; + for (int i = 0; i < n; i++) + { + Vector3 hipW = comPos + Vector3.Transform(Geom.Legs[i].HipInCom * GeomScale, qBody); + float gUnder = terrain.SampleHeight(hipW.X, hipW.Z); + float minAnkle = hipW.Y - (gUnder + Geom.Legs[i].AnkleH * GeomScale); + if (minAnkle <= Geom.Legs[i].MaxLegReach * GeomScale + 0.08f * GeomScale) + { + anyCanReach = true; + break; + } + } + IsAirborne = !anyCanReach; + WasAirborne = IsAirborne; + MaxFootSlipM = 0f; + LastTotalForce = Vector3.Zero; + LastTotalTorque = Vector3.Zero; + + for (int i = 0; i < n; i++) + { + Vector3 restLocal = new(Geom.Legs[i].RestFootXZ.X * GeomScale, 0f, Geom.Legs[i].RestFootXZ.Y * GeomScale); + Vector3 worldPos = comPos + Vector3.Transform(restLocal, qBody); + float gh = terrain.SampleHeight(worldPos.X, worldPos.Z); + Vector3 fn = SampleTerrainNormal(terrain, worldPos.X, worldPos.Z); + + FootSole[i] = new Vector3(worldPos.X, gh, worldPos.Z); + FootNormal[i] = fn; + SwingStartSole[i] = FootSole[i]; + SwingTargetSole[i] = FootSole[i]; + SwingStartNormal[i] = fn; + SwingTargetNormal[i] = fn; + Planted[i] = true; + LastGrfY[i] = (mass * ArenaGravity) / n; + + Vector3 hipWorld = comPos + Vector3.Transform(Geom.Legs[i].HipInCom * GeomScale, qBody); + Vector3 sole = FootSole[i]; + if (WalkerLocomotion.ClampSoleToReach(hipWorld, Geom.Legs[i].AnkleH * GeomScale, Geom.Legs[i].MaxLegReach * GeomScale * 0.96f, terrain, ref sole, out Vector3 clampedN)) + { + fn = clampedN; + FootSole[i] = sole; + FootNormal[i] = fn; + SwingStartSole[i] = sole; + SwingTargetSole[i] = sole; + SwingStartNormal[i] = fn; + SwingTargetNormal[i] = fn; + } + Vector3 ankleWorld = FootSole[i] + fn * (Geom.Legs[i].AnkleH * GeomScale); + WalkerLegAngles initAng = WalkerLocomotion.SolveLegTargetAngles(Geom, GeomScale, i, hipWorld, qBody, ankleWorld, fn, 0f); + Actuators[i] = new WalkerJointActuator + { + Theta = initAng, + Omega = default + }; + } + + CurrSnap = BuildSnapshot(comPos, qBody, mass); + PrevSnap = CurrSnap; + Initialized = true; + } + + public void SnapshotPrev() + { + PrevSnap = CurrSnap; + } + + public WalkerCheckpoint CaptureCheckpoint() => new() + { + GeomLegCount = Geom.LegCount, + GeomScale = GeomScale, + Initialized = Initialized, + StanceGroup = StanceGroup, + SwingTime = SwingTime, + SwingPhase = SwingPhase, + SimTime = SimTime, + IsAirborne = IsAirborne, + WasAirborne = WasAirborne, + MaxFootSlipM = MaxFootSlipM, + LastTotalForce = LastTotalForce, + LastTotalTorque = LastTotalTorque, + Planted = Planted, + FootSole = FootSole, + SwingStartSole = SwingStartSole, + SwingTargetSole = SwingTargetSole, + FootNormal = FootNormal, + SwingStartNormal = SwingStartNormal, + SwingTargetNormal = SwingTargetNormal, + LastGrfY = LastGrfY, + Actuators = Actuators, + PrevSnap = PrevSnap, + CurrSnap = CurrSnap + }; + + public void RestoreCheckpoint(in WalkerCheckpoint cp) + { + Initialized = cp.Initialized; + StanceGroup = cp.StanceGroup; + SwingTime = cp.SwingTime; + SwingPhase = cp.SwingPhase; + SimTime = cp.SimTime; + IsAirborne = cp.IsAirborne; + WasAirborne = cp.WasAirborne; + MaxFootSlipM = cp.MaxFootSlipM; + LastTotalForce = cp.LastTotalForce; + LastTotalTorque = cp.LastTotalTorque; + Planted = cp.Planted; + FootSole = cp.FootSole; + SwingStartSole = cp.SwingStartSole; + SwingTargetSole = cp.SwingTargetSole; + FootNormal = cp.FootNormal; + SwingStartNormal = cp.SwingStartNormal; + SwingTargetNormal = cp.SwingTargetNormal; + LastGrfY = cp.LastGrfY; + Actuators = cp.Actuators; + PrevSnap = cp.PrevSnap; + CurrSnap = cp.CurrSnap; + } + + public void SyncBodyPoseOnly(Vector3 comPos, Quaternion qBody, float mass) + { + CurrSnap.ComPos = comPos; + CurrSnap.ComRot = qBody; + float denom = MathF.Max(1f, 0.5f * mass * ArenaGravity); + for (int i = 0; i < Geom.LegCount; i++) + { + CurrSnap.LoadG[i] = LastGrfY[i] / denom; + } + } + + public void AddRecoilImpulse(Vector3 shotDirWorld, Quaternion qBody, float weaponDamage) + { + if (!Initialized) + { + return; + } + Vector3 shotLocal = Vector3.Transform(shotDirWorld, Quaternion.Conjugate(qBody)); + float dirSign = shotLocal.Z >= -0.2f ? 1f : -1f; + float mag = Math.Clamp(weaponDamage / 55f, 0.12f, 1.35f) * dirSign; + + int n = Geom.LegCount; + for (int i = 0; i < n; i++) + { + float weight = Planted[i] ? 1.0f : 0.25f; + ref var act = ref Actuators[i]; + act.RecoilHipImpulse -= 0.85f * mag * weight; + act.RecoilKneeImpulse += 1.25f * mag * weight; + } + } + + public WalkerVisualSnapshot BuildSnapshot(Vector3 comPos, Quaternion qBody, float mass) + { + WalkerVisualSnapshot snap = new() + { + LegCount = Geom.LegCount, + GeomScale = GeomScale, + IsDigitigrade = Geom.IsDigitigrade, + IsArachnidUp = Geom.IsArachnidUp, + ComPos = comPos, + ComRot = qBody + }; + + float denom = MathF.Max(1f, 0.5f * mass * ArenaGravity); + for (int i = 0; i < Geom.LegCount; i++) + { + snap.LegAngles[i] = Actuators[i].Theta; + snap.FootNormal[i] = FootNormal[i]; + snap.LoadG[i] = LastGrfY[i] / denom; + } + return snap; + } + + internal static Vector3 SampleTerrainNormal(TerrainField terrain, float x, float z) + { + var (nx, ny, nz) = terrain.SampleNormal(x, z); + Vector3 n = new(nx, ny, nz); + return n.LengthSquared() > 1e-6f ? Vector3.Normalize(n) : Vector3.UnitY; + } + } + + public static class WalkerLocomotion + { + private const float Gravity = WalkerState.ArenaGravity; + private const float Mu = WalkerState.FootFriction; + + public static float GetRideHeight(ChassisSpec spec) + { + var geom = WalkerGeometrySpec.GetForChassis(spec.Id); + float scale = geom.ModelHalfHeight > 1e-4f ? spec.HalfHeight / geom.ModelHalfHeight : 1f; + return geom.ModelRideHeight * scale; + } + + internal static Vector3 ComputeHullSlopeNormal( + TerrainField terrain, + float x, + float z, + Vector3 fwd, + Vector3 right, + float halfW, + float halfL, + Vector3 centerNormal, + out float planeCenterY) + { + float w = MathF.Max(1.0f, halfW * 0.90f); + float l = MathF.Max(1.0f, halfL * 0.90f); + + float flX = x - right.X * w + fwd.X * l, flZ = z - right.Z * w + fwd.Z * l; + float frX = x + right.X * w + fwd.X * l, frZ = z + right.Z * w + fwd.Z * l; + float rlX = x - right.X * w - fwd.X * l, rlZ = z - right.Z * w - fwd.Z * l; + float rrX = x + right.X * w - fwd.X * l, rrZ = z + right.Z * w - fwd.Z * l; + + float hCenter = terrain.SampleHeight(x, z); + if (terrain.SampleNormal(flX, flZ).Ny < 0.58f || + terrain.SampleNormal(frX, frZ).Ny < 0.58f || + terrain.SampleNormal(rlX, rlZ).Ny < 0.58f || + terrain.SampleNormal(rrX, rrZ).Ny < 0.58f) + { + planeCenterY = hCenter; + return centerNormal.Y >= 0.78f ? centerNormal : Vector3.UnitY; + } + + float hFL = terrain.SampleHeight(flX, flZ); + float hFR = terrain.SampleHeight(frX, frZ); + float hRL = terrain.SampleHeight(rlX, rlZ); + float hRR = terrain.SampleHeight(rrX, rrZ); + planeCenterY = 0.25f * (hFL + hFR + hRL + hRR); + + float gf = ((hFR + hFL) - (hRR + hRL)) / (4f * l); + float gr = ((hFR + hRR) - (hFL + hRL)) / (4f * w); + Vector3 nPlane = Vector3.Normalize(Vector3.UnitY - fwd * gf - right * gr); + if (nPlane.Y < 0.75f) + { + return centerNormal.Y >= 0.78f ? centerNormal : Vector3.UnitY; + } + return centerNormal.Y >= 0.78f + ? Vector3.Normalize(centerNormal * 0.30f + nPlane * 0.70f) + : nPlane; + } + + internal static Quaternion AlignUpToSlope(Quaternion yawQuat, Vector3 slopeNormal, float alignFraction, float maxTiltRad) + { + Vector3 fwd = Vector3.Transform(Vector3.UnitZ, yawQuat); + fwd.Y = 0f; + fwd = fwd.LengthSquared() > 1e-5f ? Vector3.Normalize(fwd) : Vector3.UnitZ; + Vector3 right = Vector3.Cross(fwd, Vector3.UnitY); + + float slopePitch = MathF.Asin(Math.Clamp(Vector3.Dot(fwd, slopeNormal), -0.45f, 0.45f)) * alignFraction; + float slopeRoll = MathF.Asin(Math.Clamp(Vector3.Dot(right, slopeNormal), -0.40f, 0.40f)) * alignFraction; + Vector3 desUp = Vector3.Normalize(Vector3.UnitY + fwd * MathF.Sin(slopePitch) + right * MathF.Sin(slopeRoll)); + if (MathF.Acos(Math.Clamp(desUp.Y, -1f, 1f)) > maxTiltRad) + { + Vector3 h = new(desUp.X, 0f, desUp.Z); + float hLen = h.Length(); + desUp = hLen > 1e-4f + ? Vector3.UnitY * MathF.Cos(maxTiltRad) + (h / hLen) * MathF.Sin(maxTiltRad) + : Vector3.UnitY; + } + Vector3 axis = Vector3.Cross(Vector3.UnitY, desUp); + float axisLen = axis.Length(); + if (axisLen <= 1e-5f) + { + return yawQuat; + } + float ang = MathF.Acos(Math.Clamp(desUp.Y, -1f, 1f)); + return Quaternion.Normalize(Quaternion.CreateFromAxisAngle(axis / axisLen, ang) * yawQuat); + } + + public static void StepWalker( + WalkerState ws, + ChassisGrid grid, + TerrainField terrain, + Box3DSoaView view, + int lane, + float mass, + Vector3 comPos, + Quaternion qBody, + Vector3 vel, + Vector3 angVel, + Vector3 desiredHorizVel, + float targetYawVel, + bool brakeCmd, + float dt) + { + if (!ws.Initialized) + { + ws.InitializePose(comPos, qBody, mass, terrain); + } + + var geom = ws.Geom; + float scale = ws.GeomScale; + int n = geom.LegCount; + ws.SimTime += dt; + + Span legIntegrities = stackalloc float[4]; + grid.GetLegIntegrities(legIntegrities); + float avgIntegrity = 0f; + bool anyLegSeverelyCrippled = false; + for (int i = 0; i < n; i++) + { + float integ = Math.Clamp(legIntegrities[i], 0.25f, 1f); + legIntegrities[i] = integ; + avgIntegrity += integ; + if (integ < 0.5f) + { + anyLegSeverelyCrippled = true; + } + } + avgIntegrity /= n; + + float desiredSpeed = MathF.Sqrt(desiredHorizVel.X * desiredHorizVel.X + desiredHorizVel.Z * desiredHorizVel.Z); + float horizSpeed = MathF.Sqrt(vel.X * vel.X + vel.Z * vel.Z); + float baseRideHeight = geom.ModelRideHeight * scale; + float physHalfH = geom.ModelHalfHeight * scale * (n == 4 ? 0.62f : 0.72f); + float comGroundY = terrain.SampleHeight(comPos.X, comPos.Z); + Vector3 terrainNormal = WalkerState.SampleTerrainNormal(terrain, comPos.X, comPos.Z); + float crouchSpeedRatio = n == 4 + ? Math.Clamp(horizSpeed / MathF.Max(6f, grid.Spec.MaxSpeed), 0f, 1f) + : Math.Clamp(MathF.Max(horizSpeed, desiredSpeed) / MathF.Max(6f, grid.Spec.MaxSpeed * 0.40f), 0f, 1f); + float restCrouchFrac = n == 4 ? 0f : 0.045f; + float sprintCrouchFrac = n == 4 ? 0.05f : 0.095f; + float crouchFrac = restCrouchFrac + (sprintCrouchFrac - restCrouchFrac) * crouchSpeedRatio; + float crouchDrop = geom.ModelHalfHeight * scale * crouchFrac; + float minSafeRide = physHalfH + 0.45f * scale; + float rideHeight = MathF.Max(minSafeRide, baseRideHeight - crouchDrop); + Vector3 fwd = Vector3.Transform(Vector3.UnitZ, qBody); + fwd.Y = 0f; + fwd = fwd.LengthSquared() > 1e-5f ? Vector3.Normalize(fwd) : Vector3.UnitZ; + Vector3 right = Vector3.Cross(fwd, Vector3.UnitY); + Vector3 up = Vector3.Transform(Vector3.UnitY, qBody); + + Span hipWorld = stackalloc Vector3[4]; + for (int i = 0; i < n; i++) + { + hipWorld[i] = comPos + Vector3.Transform(geom.Legs[i].HipInCom * scale, qBody); + } + + // Determine airborne state before gait step so floating mechs don't drag feet on the ground + bool anyLegCanReachGround = false; + for (int i = 0; i < n; i++) + { + float maxReach = geom.Legs[i].MaxLegReach * scale; + float reachTol = ws.IsAirborne ? -0.04f * maxReach : 0.45f * scale; + float gUnderHip = terrain.SampleHeight(hipWorld[i].X, hipWorld[i].Z); + float minAnkleDist = hipWorld[i].Y - (gUnderHip + geom.Legs[i].AnkleH * scale); + if (minAnkleDist <= maxReach + reachTol) + { + anyLegCanReachGround = true; + break; + } + } + ws.WasAirborne = ws.IsAirborne; + ws.IsAirborne = !anyLegCanReachGround; + + // Landing transition: snap all feet to ground cleanly once on touchdown from air + if (ws.WasAirborne && !ws.IsAirborne) + { + for (int i = 0; i < n; i++) + { + float fx = ws.FootSole[i].X; + float fz = ws.FootSole[i].Z; + ws.FootSole[i] = new Vector3(fx, terrain.SampleHeight(fx, fz), fz); + ws.FootNormal[i] = WalkerState.SampleTerrainNormal(terrain, fx, fz); + ws.SwingStartSole[i] = ws.FootSole[i]; + ws.SwingStartNormal[i] = ws.FootNormal[i]; + ws.SwingTargetSole[i] = ws.FootSole[i]; + ws.SwingTargetNormal[i] = ws.FootNormal[i]; + ws.Planted[i] = true; + } + ws.SwingTime = 0f; + ws.SwingPhase = 0f; + } + + bool idleCmd = desiredSpeed < 0.10f && MathF.Abs(targetYawVel) < 0.05f; + bool stepping = !ws.IsAirborne && + (!idleCmd || horizSpeed >= 0.25f || MathF.Abs(angVel.Y) >= 0.10f); + + float overlap = n == 4 + ? (anyLegSeverelyCrippled ? 0.28f : 0.12f) + : (anyLegSeverelyCrippled ? 0.12f : 0.06f); + + bool anySwinging = false; + for (int i = 0; i < n; i++) + { + if (!ws.Planted[i]) + { + anySwinging = true; + break; + } + } + + // 4B: Gait & Capture-Point Planner (Bug 1, 2, 3 fixed) + float swingToePitch = 0f; + if (ws.IsAirborne) + { + // Dangle feet cleanly below hips when airborne + for (int i = 0; i < n; i++) + { + ws.Planted[i] = false; + Vector3 restLocal = new(geom.Legs[i].RestFootXZ.X * scale, 0f, geom.Legs[i].RestFootXZ.Y * scale); + Vector3 nominal = comPos + Vector3.Transform(restLocal, qBody); + float targetAnkleY = hipWorld[i].Y - (geom.Legs[i].MaxLegReach * 0.88f) * scale; + float targetSoleY = MathF.Max(terrain.SampleHeight(nominal.X, nominal.Z), targetAnkleY - geom.Legs[i].AnkleH * scale); + ws.FootSole[i] = Vector3.Lerp(ws.FootSole[i], new Vector3(nominal.X, targetSoleY, nominal.Z), Math.Clamp(dt * 8f, 0f, 1f)); + ws.FootNormal[i] = Vector3.Normalize(Vector3.Lerp(ws.FootNormal[i], up, Math.Clamp(dt * 6f, 0f, 1f))); + } + ws.SwingTime = 0f; + ws.SwingPhase = 0f; + } + else if (!stepping && !anySwinging) + { + for (int i = 0; i < n; i++) + { + ws.Planted[i] = true; + } + ws.SwingTime = 0f; + ws.SwingPhase = 0f; + } + else + { + float hScale = MathF.Max(0.35f, geom.ModelHalfHeight * scale / 3.1456f); + float baseDur = Math.Clamp(0.46f * MathF.Sqrt(hScale), 0.26f, 0.68f); + float minDur = Math.Clamp((n == 4 ? 0.215f : 0.22f) * MathF.Sqrt(hScale), 0.14f, n == 4 ? 0.240f : 0.36f); + float speedScale = Math.Clamp(horizSpeed / MathF.Max(6f, grid.Spec.MaxSpeed), 0f, 1f); + float latDisturb = MathF.Abs((vel.X - desiredHorizVel.X) * right.X + (vel.Z - desiredHorizVel.Z) * right.Z); + float effectiveDur = baseDur * (1f - 0.30f * speedScale); + + // Bound step duration across all legs so stance travel stays inside physical horizontal leg reach at speed + float speedForDur = MathF.Max(horizSpeed, desiredSpeed * 0.75f); + if (speedForDur > 1.0f) + { + for (int i = 0; i < n; i++) + { + float actualDy = hipWorld[i].Y - (terrain.SampleHeight(hipWorld[i].X, hipWorld[i].Z) + geom.Legs[i].AnkleH * scale); + float nominalDy = MathF.Max(0.25f * scale, MathF.Max(actualDy, rideHeight + geom.Legs[i].HipInCom.Y * scale - geom.Legs[i].AnkleH * scale)); + float availReach = geom.Legs[i].MaxLegReach * scale; + float maxHorizStride = MathF.Sqrt(MathF.Max(0.25f * scale * scale, availReach * availReach - nominalDy * nominalDy)); + effectiveDur = MathF.Min(effectiveDur, (0.88f * maxHorizStride) / speedForDur); + } + } + if (latDisturb > 1.1f) + { + effectiveDur = MathF.Min(effectiveDur, 0.20f); + } + effectiveDur = Math.Clamp(effectiveDur, minDur, 0.68f); + + ws.SwingTime += dt; + ws.SwingPhase += dt / MathF.Max(minDur, effectiveDur); + float u = ws.SwingPhase; + + // Bug 1 Fix: On u >= 1.0f, plant swinging group, flip _stanceGroup, IMMEDIATELY reset _swingTime = 0 & u = 0, + // snapshot _swingStartSole/_swingStartNormal for the new swinging group, and NEVER evaluate swing with stale u >= 1! + if (u >= 1.0f) + { + for (int i = 0; i < n; i++) + { + if (!IsInGroup(n, i, ws.StanceGroup)) + { + float tx = ws.SwingTargetSole[i].X; + float tz = ws.SwingTargetSole[i].Z; + Vector3 tn = WalkerState.SampleTerrainNormal(terrain, tx, tz); + ws.FootSole[i] = new Vector3(tx, terrain.SampleHeight(tx, tz), tz); + ws.FootNormal[i] = tn; + ws.Planted[i] = true; + } + } + + ws.StanceGroup = 1 - ws.StanceGroup; + ws.SwingTime = 0f; + ws.SwingPhase = 0f; + u = 0f; + + if (stepping) + { + for (int i = 0; i < n; i++) + { + if (!IsInGroup(n, i, ws.StanceGroup)) + { + ws.SwingStartSole[i] = ws.FootSole[i]; + ws.SwingStartNormal[i] = ws.FootNormal[i]; + ws.SwingTargetSole[i] = ws.FootSole[i]; + ws.SwingTargetNormal[i] = ws.FootNormal[i]; + ws.Planted[i] = true; // Double-support overlap at u = 0 < overlap + } + else + { + ws.Planted[i] = true; + } + } + } + else + { + for (int i = 0; i < n; i++) + { + ws.Planted[i] = true; + } + } + } + else + { + for (int i = 0; i < n; i++) + { + if (IsInGroup(n, i, ws.StanceGroup)) + { + ws.Planted[i] = true; + } + else + { + bool shouldPlantOverlap = ws.Planted[i] && u < overlap; + if (ws.Planted[i] && !shouldPlantOverlap) + { + // Liftoff transition at u >= overlap: snapshot start pose cleanly + ws.SwingStartSole[i] = ws.FootSole[i]; + ws.SwingStartNormal[i] = ws.FootNormal[i]; + } + ws.Planted[i] = shouldPlantOverlap; + } + } + } + + // Update Capture-Point target & smooth C1 trajectory for non-planted swing feet + float omega0 = MathF.Sqrt(Gravity / MathF.Max(0.5f, rideHeight)); + float kCapture = 0.22f / omega0; + float uSwing = u >= overlap ? Math.Clamp((u - overlap) / MathF.Max(0.05f, 1f - overlap), 0f, 1f) : 0f; + float s = uSwing * uSwing * (3f - 2f * uSwing); + float env = MathF.Sin(MathF.PI * uSwing); + swingToePitch = 0.20f * MathF.Sin(MathF.Tau * uSwing); + + for (int i = 0; i < n; i++) + { + if (ws.Planted[i]) + { + continue; + } + + Vector3 rHip = hipWorld[i] - comPos; + Vector3 vHip = vel + Vector3.Cross(angVel, rHip); + Vector3 vHipDes = desiredHorizVel + Vector3.Cross(new Vector3(0f, targetYawVel, 0f), rHip); + + Vector2 vH = new(vHip.X, vHip.Z); + Vector2 vHDes = new(vHipDes.X, vHipDes.Z); + Vector2 vErr = vH - vHDes; + float vHDesLen = vHDes.Length(); + bool accelFromRest = false; + Vector2 dirDes = Vector2.Zero; + if (vHDesLen > 0.3f) + { + dirDes = vHDes / vHDesLen; + float vAlong = Vector2.Dot(vH, dirDes); + if (vAlong < vHDesLen) + { + // Accelerating up to target speed: avoid pulling swing target behind hip + float alongErr = Vector2.Dot(vErr, dirDes); + if (alongErr < 0f) + { + vErr -= dirDes * alongErr; + } + } + accelFromRest = vAlong < vHDesLen * 0.5f; + } + Vector2 stepOffset = vH * (effectiveDur * 0.56f) + vErr * kCapture; + if (accelFromRest) + { + stepOffset += vHDes * (0.36f * effectiveDur); + float alongStep = Vector2.Dot(stepOffset, dirDes); + if (alongStep < 0f) + { + stepOffset -= dirDes * alongStep; + } + } + + Vector3 restLocal = new(geom.Legs[i].RestFootXZ.X * scale, 0f, geom.Legs[i].RestFootXZ.Y * scale); + if (n == 2 && desiredSpeed > 0.5f) + { + restLocal.X *= 0.85f; + } + else if (n == 4 && desiredSpeed > 0.5f) + { + // Center splayed quadruped swing target modestly toward hip socket during locomotion + float centerT = 0.55f * Math.Clamp(MathF.Max(horizSpeed, desiredSpeed * 0.6f) / MathF.Max(6f, grid.Spec.MaxSpeed), 0f, 1f); + restLocal.X += (geom.Legs[i].HipInCom.X * scale - restLocal.X) * centerT; + restLocal.Z += (geom.Legs[i].HipInCom.Z * scale - restLocal.Z) * centerT; + } + Vector3 nominal = comPos + Vector3.Transform(restLocal, qBody); + + float maxStep = geom.MaxStepRadius * scale * (1f - 0.25f * (1f - legIntegrities[i])); + if (stepOffset.Length() > maxStep) + { + stepOffset = Vector2.Normalize(stepOffset) * maxStep; + } + + float tx = nominal.X + stepOffset.X; + float tz = nominal.Z + stepOffset.Y; + + // Prevent biped feet from crossing the sagittal midline + if (n == 2) + { + float minLat = 0.22f * scale; + float latFromCom = (tx - comPos.X) * right.X + (tz - comPos.Z) * right.Z; + // +X is Left (leg 0), -X is Right (leg 1); note right = Cross(fwd, UnitY) = -X in right-handed frame! + // Wait: Cross(UnitZ, UnitY) = (-1, 0, 0) = -X (Right)! So Left is negative dot with `right`, Right is positive dot with `right`! + if (i == 0 && latFromCom > -minLat) + { + float corr = -minLat - latFromCom; + tx += right.X * corr; + tz += right.Z * corr; + } + else if (i == 1 && latFromCom < minLat) + { + float corr = minLat - latFromCom; + tx += right.X * corr; + tz += right.Z * corr; + } + } + + // Keep swing target inside physical leg reach around hipWorld on terrain + Vector3 tgtSole = new(tx, terrain.SampleHeight(tx, tz), tz); + if (ClampSoleToReach(hipWorld[i], geom.Legs[i].AnkleH * scale, geom.Legs[i].MaxLegReach * scale * 0.985f, terrain, ref tgtSole, out Vector3 tgtNorm)) + { + ws.SwingTargetSole[i] = tgtSole; + ws.SwingTargetNormal[i] = tgtNorm; + } + else + { + ws.SwingTargetSole[i] = tgtSole; + ws.SwingTargetNormal[i] = WalkerState.SampleTerrainNormal(terrain, tgtSole.X, tgtSole.Z); + } + + // Bug 3 Fix: C1 clearance envelope (env == 0 at uSwing == 0 and uSwing == 1) + float sx = ws.SwingStartSole[i].X + (ws.SwingTargetSole[i].X - ws.SwingStartSole[i].X) * s; + float sz = ws.SwingStartSole[i].Z + (ws.SwingTargetSole[i].Z - ws.SwingStartSole[i].Z) * s; + float syBase = ws.SwingStartSole[i].Y + (ws.SwingTargetSole[i].Y - ws.SwingStartSole[i].Y) * s; + float arcLift = geom.SwingArcHeight * scale * env; + float groundUnder = terrain.SampleHeight(sx, sz); + float minGround = groundUnder + 0.05f * scale * env; + ws.FootSole[i] = new Vector3(sx, MathF.Max(syBase + arcLift, minGround), sz); + + // Bug 2 Fix: smooth normal blend (zero 14-deg ankle snap) + Vector3 nBlend = Vector3.Lerp(ws.SwingStartNormal[i], ws.SwingTargetNormal[i], s); + ws.FootNormal[i] = nBlend.LengthSquared() > 1e-6f ? Vector3.Normalize(nBlend) : Vector3.UnitY; + } + } + + // Clamp planted feet to MaxLegReach * geomScale (genuine terrain drag if dragged past reach) + if (!ws.IsAirborne) + { + for (int i = 0; i < n; i++) + { + if (!ws.Planted[i]) + { + continue; + } + float maxReach = geom.Legs[i].MaxLegReach * scale; + Vector3 oldSole = ws.FootSole[i]; + Vector3 clampedSole = oldSole; + if (ClampSoleToReach(hipWorld[i], geom.Legs[i].AnkleH * scale, maxReach, terrain, ref clampedSole, out Vector3 clampedN)) + { + ws.FootSole[i] = clampedSole; + ws.FootNormal[i] = clampedN; + float drag = MathF.Sqrt((clampedSole.X - oldSole.X) * (clampedSole.X - oldSole.X) + + (clampedSole.Z - oldSole.Z) * (clampedSole.Z - oldSole.Z)); + if (drag > ws.MaxFootSlipM) + { + ws.MaxFootSlipM = drag; + } + } + } + } + + // 4C: Pure Newtonian Centroidal GRF Wrench (ZERO magic hull springs or righting torques!) + float rawTerrainRateY = -(terrainNormal.X * vel.X + terrainNormal.Z * vel.Z) / MathF.Max(0.35f, terrainNormal.Y); + float terrainRateY = Math.Clamp(rawTerrainRateY, -12f, 11f); + float plantedYSum = 0f; + int plantedYCount = 0; + float uphillFootGroundY = comGroundY; + for (int i = 0; i < n; i++) + { + if (ws.Planted[i]) + { + plantedYSum += ws.FootSole[i].Y; + plantedYCount++; + Vector3 footNorm = WalkerState.SampleTerrainNormal(terrain, ws.FootSole[i].X, ws.FootSole[i].Z); + if (footNorm.Y >= 0.70f && ws.FootSole[i].Y > uphillFootGroundY) + { + uphillFootGroundY = ws.FootSole[i].Y; + } + } + } + float supportGroundY = plantedYCount > 0 + ? Math.Clamp(plantedYSum / plantedYCount, comGroundY - 0.03f * scale, comGroundY + 0.18f * scale) + : comGroundY; + // Track rising traversable slopes (aheadNormal.Y >= 0.70) from planted uphill feet and forward probe ONLY during active movement + float effectiveGroundY = MathF.Max(supportGroundY, comGroundY); + float maxSpd = MathF.Max(4f, grid.Spec.MaxSpeed); + bool activeMove = horizSpeed > 1.5f || desiredSpeed > 0.05f * maxSpd; + float hullPlaneCenterY = comGroundY; + Vector3 hullSlopeNormal = n == 4 + ? ComputeHullSlopeNormal(terrain, comPos.X, comPos.Z, fwd, right, view.Size0[lane], view.Size2[lane], terrainNormal, out hullPlaneCenterY) + : terrainNormal; + if (activeMove) + { + float slopeGroundY = uphillFootGroundY; + if (n == 4 && hullPlaneCenterY > slopeGroundY) + { + slopeGroundY = hullPlaneCenterY; + } + Vector2 probeVec = horizSpeed > 1.0f + ? new Vector2(vel.X / horizSpeed, vel.Z / horizSpeed) + : new Vector2(desiredHorizVel.X / desiredSpeed, desiredHorizVel.Z / desiredSpeed); + float leadDist = Math.Clamp(MathF.Max(horizSpeed * 0.08f, view.Size2[lane] * 0.65f), 1.5f, 5.5f); + float ax = comPos.X + probeVec.X * leadDist; + float az = comPos.Z + probeVec.Y * leadDist; + Vector3 aheadNorm = WalkerState.SampleTerrainNormal(terrain, ax, az); + if (aheadNorm.Y >= 0.70f) + { + float aheadH = terrain.SampleHeight(ax, az); + if (aheadH > slopeGroundY) + { + slopeGroundY = aheadH; + } + } + if (slopeGroundY > comGroundY) + { + float maxLift = n == 4 ? 0.35f * scale : 0.90f * scale; + float liftFrac = n == 4 ? 0.40f : 0.50f; + float climbLift = MathF.Min(maxLift, (slopeGroundY - comGroundY) * liftFrac); + effectiveGroundY = MathF.Max(effectiveGroundY, comGroundY + climbLift); + } + if (n == 2 && view.Size2[lane] > 2.4f && terrainNormal.Y >= 0.78f) + { + float frontX = comPos.X + fwd.X * view.Size2[lane]; + float frontZ = comPos.Z + fwd.Z * view.Size2[lane]; + if (WalkerState.SampleTerrainNormal(terrain, frontX, frontZ).Y >= 0.78f) + { + float frontH = terrain.SampleHeight(frontX, frontZ); + Vector3 frontCornerRel = fwd * view.Size2[lane] - up * view.Size1[lane]; + float neededGroundY = (frontH + 0.18f * scale - frontCornerRel.Y) - rideHeight; + if (neededGroundY > effectiveGroundY) + { + effectiveGroundY = MathF.Min(comGroundY + 1.15f * scale, neededGroundY); + } + } + } + else if (n == 4 && view.Size2[lane] > 2.4f && terrainNormal.Y >= 0.78f) + { + float fz = view.Size2[lane] * 0.98f; + float fw = view.Size0[lane] * 0.95f; + for (int ci = -1; ci <= 1; ci++) + { + float sx = fw * ci; + float cx = comPos.X + right.X * sx + fwd.X * fz; + float cz = comPos.Z + right.Z * sx + fwd.Z * fz; + if (WalkerState.SampleTerrainNormal(terrain, cx, cz).Y >= 0.58f) + { + float ch = terrain.SampleHeight(cx, cz); + Vector3 cornerRel = right * sx + fwd * fz - up * view.Size1[lane]; + float neededGroundY = (ch + 0.22f * scale - cornerRel.Y) - rideHeight; + if (neededGroundY > effectiveGroundY) + { + effectiveGroundY = MathF.Min(comGroundY + 1.15f * scale, neededGroundY); + } + } + } + } + } + float targetY = effectiveGroundY + rideHeight; + if (!activeMove && !ws.IsAirborne) + { + float maxLegComY = float.PositiveInfinity; + for (int i = 0; i < n; i++) + { + if (!ws.Planted[i]) + { + continue; + } + Vector3 ankle = ws.FootSole[i] + ws.FootNormal[i] * (geom.Legs[i].AnkleH * scale); + Vector3 hipOff = Vector3.Transform(geom.Legs[i].HipInCom * scale, qBody); + float dx = (comPos.X + hipOff.X) - ankle.X; + float dz = (comPos.Z + hipOff.Z) - ankle.Z; + float horizSq = dx * dx + dz * dz; + float maxReach = geom.Legs[i].MaxLegReach * scale * 0.99f; + float remSq = MathF.Max(0f, maxReach * maxReach - horizSq); + float maxComY = ankle.Y - hipOff.Y + MathF.Sqrt(remSq); + if (maxComY < maxLegComY) + { + maxLegComY = maxComY; + } + } + if (!float.IsPositiveInfinity(maxLegComY)) + { + float minIdleRide = geom.ModelHalfHeight * scale * (n == 4 ? 0.72f : 0.80f); + targetY = MathF.Min(targetY, MathF.Max(comGroundY + minIdleRide, maxLegComY)); + } + } + + float fyDes = MathF.Max(0f, + mass * Gravity + + mass * 48f * (targetY - comPos.Y) + + mass * 10.5f * (terrainRateY - vel.Y)); + float penThresh = MathF.Min(view.Size1[lane], geom.ModelHalfHeight * scale * 0.72f); + float hullBottomPen = (comGroundY + penThresh) - comPos.Y; + float slopeMargin = activeMove ? 0.45f * scale : 0.02f * scale; + if (!ws.IsAirborne && activeMove && terrainNormal.Y < 0.99f && terrainNormal.Y >= 0.70f && (vel.Y - terrainRateY) < (n == 4 ? 2.5f : 0.6f) && comPos.Y <= targetY + 0.65f * scale) + { + fyDes = MathF.Max(fyDes, mass * Gravity * 1.10f); + } + else if (!ws.IsAirborne && terrainNormal.Y < 0.975f && (vel.Y - terrainRateY) < 0.4f && comPos.Y <= targetY + slopeMargin) + { + fyDes = MathF.Max(fyDes, mass * Gravity); + } + + Vector3 driveFwd = fwd - terrainNormal * Vector3.Dot(fwd, terrainNormal); + driveFwd = driveFwd.LengthSquared() > 1e-5f ? Vector3.Normalize(driveFwd) : fwd; + Vector3 driveRight = right - terrainNormal * Vector3.Dot(right, terrainNormal); + driveRight = driveRight.LengthSquared() > 1e-5f ? Vector3.Normalize(driveRight) : right; + + // Steep-cliff strip (n.Y < 0.70 sustained ahead): prevent burrowing into vertical Mesa cliff walls without false braking on 1-pixel DEM creases + Vector3 cliffNormal = terrainNormal; + if (desiredSpeed > 0.1f) + { + Vector3 probeDir = Vector3.Normalize(new Vector3(desiredHorizVel.X, 0f, desiredHorizVel.Z)); + float baseProbe = MathF.Max(view.Size2[lane], geom.FootHalfL * scale) + 0.8f * scale; + float lookProbe = baseProbe + 2.0f; + foreach (float pd in new[] { baseProbe, lookProbe }) + { + Vector3 n1 = WalkerState.SampleTerrainNormal(terrain, comPos.X + probeDir.X * pd, comPos.Z + probeDir.Z * pd); + Vector3 n2 = WalkerState.SampleTerrainNormal(terrain, comPos.X + probeDir.X * (pd + 1.5f), comPos.Z + probeDir.Z * (pd + 1.5f)); + Vector3 nAvg = n1 + n2; + Vector3 aheadN = nAvg.LengthSquared() > 1e-5f ? Vector3.Normalize(nAvg) : Vector3.UnitY; + if (aheadN.Y < cliffNormal.Y) + { + cliffNormal = aheadN; + } + } + } + Vector3 effectiveDriveVel = desiredHorizVel; + // Physical grade resistance: fast sprinters moderate uphill speed earlier (>22.3 deg) to avoid dune sky-launch, while 20 m/s siege walkers keep full climb torque up to 23.8 deg + float speedFactor = Math.Clamp((desiredSpeed - 20f) / 6f, 0f, 1f); + float gradeStartNy = 0.915f + 0.010f * speedFactor; + float gradeFloor = 0.42f - 0.04f * speedFactor; + if (terrainNormal.Y < gradeStartNy && terrainNormal.Y >= 0.70f && desiredSpeed > 0.1f) + { + Vector3 downhillHoriz = new(terrainNormal.X, 0f, terrainNormal.Z); + float dhLen = downhillHoriz.Length(); + if (dhLen > 1e-4f) + { + downhillHoriz /= dhLen; + float uphillComp = -Vector3.Dot(effectiveDriveVel, downhillHoriz); + if (uphillComp > 0f) + { + float gradeScale = Math.Clamp((terrainNormal.Y - 0.70f) / MathF.Max(0.05f, gradeStartNy - 0.70f), gradeFloor, 1.0f); + effectiveDriveVel += downhillHoriz * (uphillComp * (1f - gradeScale)); + } + } + } + Vector3 cliffHoriz = Vector3.Zero; + bool onSteepCliff = cliffNormal.Y < 0.70f; + if (onSteepCliff) + { + cliffHoriz = new Vector3(cliffNormal.X, 0f, cliffNormal.Z); + if (cliffHoriz.LengthSquared() > 1e-4f) + { + cliffHoriz = Vector3.Normalize(cliffHoriz); + float intoCliff = Vector3.Dot(effectiveDriveVel, cliffHoriz); + if (intoCliff < 0f) + { + effectiveDriveVel -= cliffHoriz * intoCliff; + } + } + } + + float thrust = grid.ComputeDriveThrust(); + float driveGain = MathF.Max(mass * 5.2f, (thrust / maxSpd) * 2.0f) * avgIntegrity; + float latGain = mass * 8.5f * avgIntegrity; + if (idleCmd) + { + float stopGain = mass * 30f * avgIntegrity; + driveGain = MathF.Max(driveGain, stopGain); + latGain = MathF.Max(latGain, stopGain); + } + Vector3 fwdFlat = new(driveFwd.X, 0f, driveFwd.Z); + fwdFlat = fwdFlat.LengthSquared() > 1e-5f ? Vector3.Normalize(fwdFlat) : fwd; + Vector3 rightFlat = new(driveRight.X, 0f, driveRight.Z); + rightFlat = rightFlat.LengthSquared() > 1e-5f ? Vector3.Normalize(rightFlat) : right; + + float fwdVel = Vector3.Dot(vel, driveFwd); + float fwdDes = Vector3.Dot(effectiveDriveVel, fwdFlat); + float latVel = Vector3.Dot(vel, driveRight); + float latDes = Vector3.Dot(effectiveDriveVel, rightFlat); + + Vector3 horizDriveForce = + fwdFlat * ((fwdDes - fwdVel) * driveGain) + + rightFlat * ((latDes - latVel) * latGain); + + float hx = view.Size0[lane]; + float hy = MathF.Max(view.Size1[lane], geom.ModelHalfHeight * scale); + float hz = view.Size2[lane]; + float maxFoot = MathF.Max(hx, hz); + float iTilt = mass * (hy * hy + maxFoot * maxFoot) / 3f; + float iy = mass * (hx * hx + hz * hz) / 3f; + + if (!idleCmd && !brakeCmd) + { + float maxSelfDrive = MathF.Min(Mu * mass * Gravity, 0.85f * (iTilt * 28f) / MathF.Max(0.5f, rideHeight)) * avgIntegrity; + float driveMag = horizDriveForce.Length(); + if (driveMag > maxSelfDrive && driveMag > 1e-4f) + { + horizDriveForce *= maxSelfDrive / driveMag; + } + } + + if (onSteepCliff && cliffHoriz.LengthSquared() > 1e-4f) + { + float forceIntoCliff = Vector3.Dot(horizDriveForce, cliffHoriz); + if (forceIntoCliff < 0f) + { + horizDriveForce -= cliffHoriz * forceIntoCliff; + } + float velIntoCliff = Vector3.Dot(new Vector3(vel.X, 0f, vel.Z), cliffHoriz); + if (velIntoCliff < 0f) + { + horizDriveForce -= cliffHoriz * (velIntoCliff * mass * 18f); + } + } + + if (brakeCmd) + { + horizDriveForce -= new Vector3(vel.X, 0f, vel.Z) * (mass * 7f); + } + float fxDes = horizDriveForce.X; + float fzDes = horizDriveForce.Z; + + // Inertial attitude PD torque + Dorsal quadruped terrain-slope alignment + subtle accel pitch lean + turn bank + crippled-leg limp sag + yaw PD torque + Vector3 desiredUp; + if (n == 4) + { + float slopePitch = MathF.Asin(Math.Clamp(Vector3.Dot(fwd, hullSlopeNormal), -0.45f, 0.45f)) * 0.85f; + float slopeRoll = MathF.Asin(Math.Clamp(Vector3.Dot(right, hullSlopeNormal), -0.40f, 0.40f)) * 0.85f; + desiredUp = Vector3.Normalize(Vector3.UnitY + fwd * MathF.Sin(slopePitch) + right * MathF.Sin(slopeRoll)); + } + else + { + desiredUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, 0.22f)); + } + // Do not lean quadruped nose down into an uphill slope when accelerating + float accelPitch = (n == 4 && hullSlopeNormal.Y < 0.985f) + ? 0f + : Math.Clamp((fwdDes - fwdVel) * 0.008f + fwdDes * 0.003f, -0.04f, 0.06f); + float limpLatLean = 0f; + float limpFwdLean = 0f; + if (n == 2) + { + // Leg 0 is Left (-right), Leg 1 is Right (+right); lean toward crippled side + limpLatLean = (legIntegrities[1] - legIntegrities[0]) * 0.075f; + } + else if (n == 4) + { + float leftInt = 0.5f * (legIntegrities[0] + legIntegrities[2]); + float rightInt = 0.5f * (legIntegrities[1] + legIntegrities[3]); + float frontInt = 0.5f * (legIntegrities[0] + legIntegrities[1]); + float rearInt = 0.5f * (legIntegrities[2] + legIntegrities[3]); + limpLatLean = (rightInt - leftInt) * 0.075f; + limpFwdLean = (rearInt - frontInt) * 0.065f; + } + Vector3 driveBank = new Vector3(fxDes, 0f, fzDes) / MathF.Max(1f, mass * Gravity) * 0.08f; + if (n == 4 && hullSlopeNormal.Y < 0.985f) + { + // Preserve lateral turn bank only on sloped quadrupeds so uphill drive never pitches nose into hillside + driveBank = right * Vector3.Dot(driveBank, right); + } + desiredUp = Vector3.Normalize(desiredUp + fwd * (accelPitch + limpFwdLean) - right * limpLatLean + driveBank); + + // Cap desiredUp tilt: bipeds <= 8.6 deg, arachnid quadruped <= 14.6 deg, siege quadruped <= 18.3 deg + float maxDesiredTiltRad = n == 4 ? (geom.IsArachnidUp ? 0.255f : 0.320f) : 0.150f; + float dotUp = Math.Clamp(desiredUp.Y, -1f, 1f); + if (MathF.Acos(dotUp) > maxDesiredTiltRad) + { + Vector3 horiz = new(desiredUp.X, 0f, desiredUp.Z); + float hLen = horiz.Length(); + desiredUp = hLen > 1e-4f + ? Vector3.UnitY * MathF.Cos(maxDesiredTiltRad) + (horiz / hLen) * MathF.Sin(maxDesiredTiltRad) + : Vector3.UnitY; + } + + Vector3 tiltAxis = Vector3.Cross(up, desiredUp); + float yawGain = MathF.Abs(targetYawVel) < 1e-3f ? 48f : 22f; + Vector3 torqueDes = new( + iTilt * (tiltAxis.X * 95f - angVel.X * 22f), + iy * (targetYawVel - angVel.Y) * yawGain, + iTilt * (tiltAxis.Z * 95f - angVel.Z * 22f)); + + // Allocate strictly across planted feet inside reach + Span weight = stackalloc float[4]; + Span capMax = stackalloc float[4]; + float weightSum = 0f; + int activeSupportCount = 0; + float sumR2 = 0f; + float footHalfW = geom.FootHalfW * scale; + float footHalfL = geom.FootHalfL * scale; + + for (int i = 0; i < n; i++) + { + ws.LastGrfY[i] = 0f; + capMax[i] = mass * Gravity * (n == 4 ? 1.45f : 1.75f) * legIntegrities[i]; + if (!ws.Planted[i]) + { + continue; + } + Vector3 ankle = ws.FootSole[i] + ws.FootNormal[i] * (geom.Legs[i].AnkleH * scale); + float dist = (ankle - hipWorld[i]).Length(); + float maxLegReach = geom.Legs[i].MaxLegReach * scale; + float hardCutoff = maxLegReach + (n == 4 ? 2.40f * scale : 0.16f * scale); + if (dist > hardCutoff) + { + continue; + } + weight[i] = legIntegrities[i]; + weightSum += weight[i]; + activeSupportCount++; + Vector3 r = ws.FootSole[i] - comPos; + sumR2 += r.X * r.X + r.Z * r.Z; + } + + // Downhill steep-slope safety: never free-fall (weightSum == 0) while a planted foot is within extended reach + if (!ws.IsAirborne && weightSum <= 0f) + { + for (int i = 0; i < n; i++) + { + if (!ws.Planted[i]) + { + continue; + } + Vector3 ankle = ws.FootSole[i] + ws.FootNormal[i] * (geom.Legs[i].AnkleH * scale); + float dist = (ankle - hipWorld[i]).Length(); + if (dist <= geom.Legs[i].MaxLegReach * scale * 1.25f) + { + weight[i] = legIntegrities[i]; + weightSum += weight[i]; + activeSupportCount++; + Vector3 r = ws.FootSole[i] - comPos; + sumR2 += r.X * r.X + r.Z * r.Z; + } + } + } + + Vector3 totalForce = Vector3.Zero; + Vector3 tContact = Vector3.Zero; + Vector3 totalTorque = Vector3.Zero; + + if (weightSum > 0f) + { + if (activeSupportCount >= 2 && sumR2 > 0.25f) + { + // Multi-foot support: Pure Newtonian GRF + Coulomb friction cone + chassis-local CoP + Span footForces = stackalloc Vector3[4]; + float sumRY = 0f; + Vector2 rAvg = Vector2.Zero; + + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + Vector3 r0 = ws.FootSole[i] - comPos; + sumRY += r0.Y; + rAvg.X += r0.X; + rAvg.Y += r0.Z; + } + rAvg /= activeSupportCount; + float avgRY = sumRY / activeSupportCount; + + float sumRelR2 = 0f; + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + Vector3 r0 = ws.FootSole[i] - comPos; + float rx = r0.X - rAvg.X; + float rz = r0.Z - rAvg.Y; + sumRelR2 += rx * rx + rz * rz; + } + + float tauXForFy = torqueDes.X - avgRY * fzDes; + float tauZForFy = torqueDes.Z + avgRY * fxDes; + Span fyLeg = stackalloc float[4]; + Span dfyRaw = stackalloc float[4]; + float dfyScale = 1f; + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + float frac = weight[i] / weightSum; + float fyBase = fyDes * frac; + Vector3 r0 = ws.FootSole[i] - comPos; + float d = (-r0.Z * tauXForFy + r0.X * tauZForFy) / sumR2; + dfyRaw[i] = d; + if (d < -1e-3f) + { + float maxDrop = MathF.Max(0f, fyBase * 0.55f); + dfyScale = MathF.Min(dfyScale, maxDrop / (-d)); + } + else if (d > 1e-3f && fyBase + d > capMax[i]) + { + float maxRise = MathF.Max(0f, capMax[i] - fyBase); + dfyScale = MathF.Min(dfyScale, maxRise / d); + } + } + + float totalFyAlloc = 0f; + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + float frac = weight[i] / weightSum; + fyLeg[i] = Math.Clamp(fyDes * frac + dfyRaw[i] * dfyScale, 0f, capMax[i]); + totalFyAlloc += fyLeg[i]; + } + + // Uniform yaw scaling across active legs prevents unbalanced horizontal shear when one foot is lightly loaded + float sharedYawScale = 1f; + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + float auth = MathF.Min(1f, fyLeg[i] / MathF.Max(1f, (fyDes / activeSupportCount) * 0.45f)); + sharedYawScale = MathF.Min(sharedYawScale, auth); + } + + Vector3 momentFromCenters = Vector3.Zero; + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + float fy = fyLeg[i]; + float weightFrac = weight[i] / weightSum; + + Vector3 r0 = ws.FootSole[i] - comPos; + float fx = fxDes * weightFrac; + float fz = fzDes * weightFrac; + if (sumRelR2 > 0.1f) + { + float relX = r0.X - rAvg.X; + float relZ = r0.Z - rAvg.Y; + fx += (relZ / sumRelR2) * torqueDes.Y * sharedYawScale; + fz += (-relX / sumRelR2) * torqueDes.Y * sharedYawScale; + } + + // Coulomb friction cone clamp: |F_horiz| <= Mu * fy + float maxHoriz = Mu * fy; + float hMag = MathF.Sqrt(fx * fx + fz * fz); + if (hMag > maxHoriz && hMag > 1e-4f) + { + float cScale = maxHoriz / hMag; + fx *= cScale; + fz *= cScale; + } + + footForces[i] = new Vector3(fx, fy, fz); + momentFromCenters += Vector3.Cross(r0, footForces[i]); + ws.LastGrfY[i] = fy; + totalForce += footForces[i]; + } + + // Residual pitch/roll torque realized via physical CoP inside each foot sole in chassis-local (right, fwd) axes + Vector3 tRem = torqueDes - momentFromCenters; + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + Vector3 fLeg = footForces[i]; + float share = totalFyAlloc > 1e-3f ? fLeg.Y / totalFyAlloc : (weight[i] / weightSum); + Vector3 tShare = tRem * share; + float dRightCop = 0f; + float dFwdCop = 0f; + if (fLeg.Y > 100f) + { + dFwdCop = Math.Clamp(Vector3.Dot(tShare, right) / fLeg.Y, -footHalfL, footHalfL); + dRightCop = Math.Clamp(-Vector3.Dot(tShare, fwd) / fLeg.Y, -footHalfW, footHalfW); + } + + Vector3 pCop = ws.FootSole[i] + right * dRightCop + fwd * dFwdCop; + Vector3 tLeg = Vector3.Cross(pCop - comPos, fLeg); + float maxSpinYaw = 0.45f * Mu * fLeg.Y * MathF.Max(0.5f, scale); + float yawRem = (torqueDes.Y - momentFromCenters.Y) * share; + tLeg.Y += Math.Clamp(yawRem, -maxSpinYaw, maxSpinYaw); + tContact += tLeg; + } + } + else + { + // Single-foot support: Coulomb cone + chassis-local CoP + bounded torsional friction + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + float frac = weight[i] / weightSum; + float fy = Math.Clamp(fyDes * frac, 0f, capMax[i]); + float fx = fxDes * frac; + float fz = fzDes * frac; + Vector3 tWant = torqueDes * frac; + + float maxHoriz = Mu * fy; + float hMag = MathF.Sqrt(fx * fx + fz * fz); + if (hMag > maxHoriz && hMag > 1e-4f) + { + float cScale = maxHoriz / hMag; + fx *= cScale; + fz *= cScale; + } + + Vector3 fLeg = new(fx, fy, fz); + Vector3 r0 = ws.FootSole[i] - comPos; + Vector3 tRem = tWant - Vector3.Cross(r0, fLeg); + float dRightCop = 0f; + float dFwdCop = 0f; + if (fy > 100f) + { + dFwdCop = Math.Clamp(Vector3.Dot(tRem, right) / fy, -footHalfL, footHalfL); + dRightCop = Math.Clamp(-Vector3.Dot(tRem, fwd) / fy, -footHalfW, footHalfW); + } + + Vector3 pCop = ws.FootSole[i] + right * dRightCop + fwd * dFwdCop; + Vector3 tLeg = Vector3.Cross(pCop - comPos, fLeg); + float maxSpinYaw = 0.45f * Mu * fy * MathF.Max(0.5f, scale); + tLeg.Y += Math.Clamp(tWant.Y - tLeg.Y, -maxSpinYaw, maxSpinYaw); + + totalForce += fLeg; + tContact += tLeg; + ws.LastGrfY[i] = fy; + } + } + + // Residual pitch/roll stabilization via support-scaled hip/torso angular-momentum authority; + // yaw torque remains 100% foot-driven. + float supportFrac = Math.Clamp(totalForce.Y / MathF.Max(1f, mass * Gravity), 0f, 1f); + float weightedIntegSum = 0f; + for (int i = 0; i < n; i++) + { + weightedIntegSum += ws.LastGrfY[i] * legIntegrities[i]; + } + float stanceIntegrity = totalForce.Y > 1e-3f ? weightedIntegSum / totalForce.Y : avgIntegrity; + Vector3 tRes = torqueDes - tContact; + float resHorizMag = MathF.Sqrt(tRes.X * tRes.X + tRes.Z * tRes.Z); + float maxHipAttitudeTorque = iTilt * 44f * supportFrac * stanceIntegrity; + float attScale = resHorizMag > maxHipAttitudeTorque && resHorizMag > 1e-4f + ? maxHipAttitudeTorque / resHorizMag + : 1f; + float maxHipYawTorque = iy * 200f * supportFrac * stanceIntegrity; + float resYaw = Math.Clamp(tRes.Y, -maxHipYawTorque, maxHipYawTorque); + totalTorque = tContact + new Vector3(tRes.X * attScale, resYaw, tRes.Z * attScale); + } + + // Predictive inelastic ground contact (triggers ONLY on high-speed dune/cliff slam or deep penetration, never gentle stride ripples) + float nextGroundY = terrain.SampleHeight(comPos.X + vel.X * dt, comPos.Z + vel.Z * dt); + float predPen = (nextGroundY + penThresh) - (comPos.Y + vel.Y * dt); + float effectivePen = MathF.Max(hullBottomPen, predPen); + if (effectivePen > 0f) + { + Vector3 contactNorm = WalkerState.SampleTerrainNormal(terrain, comPos.X + vel.X * dt, comPos.Z + vel.Z * dt); + float vInto = Vector3.Dot(vel, contactNorm); + if (effectivePen > 0.02f && (vInto < -5.5f || hullBottomPen > 0.25f)) + { + float penVel = MathF.Min(MathF.Max(0f, hullBottomPen) / dt, 4.0f); + float neededDvN = MathF.Max(0f, -vInto) + penVel; + if (neededDvN > 0f) + { + float currentAccelN = Vector3.Dot(totalForce / mass + new Vector3(0f, -Gravity, 0f), contactNorm); + float accelN = Math.Clamp(neededDvN / dt - currentAccelN, 0f, 1800f); + totalForce += contactNorm * (mass * accelN); + + // Coulomb impact friction absorbs excess grazing speed on high-speed dune/mesa hits (prevents 33 m/s ski-jumps) + Vector3 vTangent = vel - contactNorm * vInto; + float vtMag = vTangent.Length(); + if (vtMag > 0.5f && accelN > 5f) + { + float maxFricAccel = MathF.Min(vtMag / dt, Mu * accelN * 0.65f); + totalForce -= (vTangent / vtMag) * (mass * maxFricAccel); + } + } + } + } + + // Write ONLY planted-foot GRF forces & (pCop - comPos) x fLeg torques! + ws.LastTotalForce = totalForce; + ws.LastTotalTorque = totalTorque; + view.ForceX[lane] = totalForce.X; + view.ForceY[lane] = totalForce.Y; + view.ForceZ[lane] = totalForce.Z; + view.TorqueX[lane] = totalTorque.X; + view.TorqueY[lane] = totalTorque.Y; + view.TorqueZ[lane] = totalTorque.Z; + + // 4D: 2nd-Order Torque-Limited Joint Actuators (2 substeps = 1/120s, NEVER reset on liftoff/touchdown!) + float subDt = dt * 0.5f; + float limbI = MathF.Max(1f, mass * scale * scale * 0.025f); + float kpStance = limbI * 1400f; + float kpSwing = limbI * 950f; + float kdStance = limbI * (2f * 0.88f * MathF.Sqrt(1400f)); + float kdSwing = limbI * (2f * 0.85f * MathF.Sqrt(950f)); + float tauLimitBase = limbI * 850f; + float tauLimitAnkle = limbI * 520f; + + for (int i = 0; i < n; i++) + { + Vector3 ankleWorld = ws.FootSole[i] + ws.FootNormal[i] * (geom.Legs[i].AnkleH * scale); + float legToePitch = ws.Planted[i] ? 0f : swingToePitch; + WalkerLegAngles target = SolveLegTargetAngles(geom, scale, i, hipWorld[i], qBody, ankleWorld, ws.FootNormal[i], legToePitch); + + bool planted = ws.Planted[i]; + float kp = planted ? kpStance : kpSwing; + float kd = planted ? kdStance : kdSwing; + float tauMax = tauLimitBase * legIntegrities[i]; + float tauAnkleMax = tauLimitAnkle * legIntegrities[i]; + + ref var act = ref ws.Actuators[i]; + float recoilHipTorque = act.RecoilHipImpulse / MathF.Max(1e-4f, dt); + float recoilKneeTorque = act.RecoilKneeImpulse / MathF.Max(1e-4f, dt); + act.RecoilHipImpulse = 0f; + act.RecoilKneeImpulse = 0f; + + for (int sub = 0; sub < 2; sub++) + { + StepDof(ref act.Theta.HipPitch, ref act.Omega.HipPitch, target.HipPitch, kp, kd, tauMax, limbI, recoilHipTorque, subDt); + StepDof(ref act.Theta.HipRoll, ref act.Omega.HipRoll, target.HipRoll, kp, kd, tauMax, limbI, 0f, subDt); + StepDof(ref act.Theta.KneeFlex, ref act.Omega.KneeFlex, target.KneeFlex, kp, kd, tauMax, limbI, recoilKneeTorque, subDt); + if (geom.IsDigitigrade) + { + StepDof(ref act.Theta.HockFlex, ref act.Omega.HockFlex, target.HockFlex, kp, kd, tauMax, limbI, 0f, subDt); + } + else + { + act.Theta.HockFlex = 0f; + act.Omega.HockFlex = 0f; + } + StepDof(ref act.Theta.AnklePitch, ref act.Omega.AnklePitch, target.AnklePitch, kp, kd, tauAnkleMax, limbI, 0f, subDt); + } + } + + ws.CurrSnap = ws.BuildSnapshot(comPos, qBody, mass); + } + + private static void StepDof( + ref float theta, + ref float omega, + float target, + float kp, + float kd, + float tauMax, + float inertia, + float recoilTorque, + float dt) + { + float err = MatchRules.NormalizeAngle(target - theta); + float tau = Math.Clamp(kp * err - kd * omega, -tauMax, tauMax) + recoilTorque; + omega += (tau / inertia) * dt; + theta = Math.Clamp(theta + omega * dt, -2.35f, 2.35f); + } + + private static bool IsInGroup(int legCount, int legIdx, int group) + { + if (legCount == 2) + { + return legIdx == group; + } + // Quadruped diagonal gaits: group 0 = {FL(0), BR(3)}, group 1 = {FR(1), BL(2)} + bool isDiag0 = legIdx == 0 || legIdx == 3; + return group == 0 ? isDiag0 : !isDiag0; + } + + internal static bool ClampSoleToReach( + Vector3 hipWorld, + float ankleH, + float maxReach, + TerrainField terrain, + ref Vector3 sole, + out Vector3 normal) + { + normal = WalkerState.SampleTerrainNormal(terrain, sole.X, sole.Z); + Vector3 ankle = sole + normal * ankleH; + if ((ankle - hipWorld).Length() <= maxReach) + { + return false; + } + + float fx = sole.X; + float fz = sole.Z; + for (int iter = 0; iter < 3; iter++) + { + float gh = terrain.SampleHeight(fx, fz); + float dy = (gh + ankleH) - hipWorld.Y; + float maxHoriz = MathF.Sqrt(MathF.Max(0.04f, maxReach * maxReach - dy * dy)); + float dx = fx - hipWorld.X; + float dz = fz - hipWorld.Z; + float hDist = MathF.Sqrt(dx * dx + dz * dz); + if (hDist <= maxHoriz || hDist < 1e-4f) + { + break; + } + float k = maxHoriz / hDist; + fx = hipWorld.X + dx * k; + fz = hipWorld.Z + dz * k; + } + + float finalGh = terrain.SampleHeight(fx, fz); + sole = new Vector3(fx, finalGh, fz); + normal = WalkerState.SampleTerrainNormal(terrain, fx, fz); + return true; + } + + public static WalkerLegAngles SolveLegTargetAngles( + WalkerGeometrySpec geom, + float scale, + int legIdx, + Vector3 hipWorld, + Quaternion qBody, + Vector3 ankleWorld, + Vector3 footNormalWorld, + float swingToePitch) + { + var leg = geom.Legs[legIdx]; + Quaternion qInv = Quaternion.Conjugate(qBody); + Vector3 deltaLocal = Vector3.Transform(ankleWorld - hipWorld, qInv); + Vector3 footNormalLocal = Vector3.Transform(footNormalWorld, qInv); + + Vector3 r0 = leg.LegRight0; + Vector3 u0 = Vector3.UnitY; + Vector3 f0 = leg.LegFwd0; + + float dx = Vector3.Dot(deltaLocal, r0); + float dy = Vector3.Dot(deltaLocal, u0); + float dz = Vector3.Dot(deltaLocal, f0); + + if (geom.IsArachnidUp) + { + float coxaYaw = MathF.Atan2(dx, MathF.Max(0.20f * scale, dz)); + float planarOut = MathF.Sqrt(dx * dx + dz * dz); + float planarUp = dy; + float d = Math.Clamp( + MathF.Sqrt(planarOut * planarOut + planarUp * planarUp), + leg.MinLegReach * scale, + leg.MaxLegReach * scale); + float l1 = leg.L1 * scale; + float l2 = leg.L2 * scale; + float baseElev = MathF.Atan2(planarUp, MathF.Max(0.05f * scale, planarOut)); + float cosAlpha = Math.Clamp((l1 * l1 + d * d - l2 * l2) / (2f * l1 * d), -1f, 1f); + float alpha = MathF.Acos(cosAlpha); + float cosKnee = Math.Clamp((l1 * l1 + l2 * l2 - d * d) / (2f * l1 * l2), -1f, 1f); + + Vector3 legOut = f0 * MathF.Cos(coxaYaw) + r0 * MathF.Sin(coxaYaw); + float anklePitch = MathF.Atan2(Vector3.Dot(footNormalLocal, legOut), MathF.Max(0.2f, Vector3.Dot(footNormalLocal, u0))) + swingToePitch; + + return new WalkerLegAngles + { + HipPitch = baseElev + alpha, + HipRoll = coxaYaw, + KneeFlex = MathF.PI - MathF.Acos(cosKnee), + HockFlex = 0f, + AnklePitch = anklePitch + }; + } + + float hipRoll = MathF.Atan2(dx, MathF.Max(0.25f * scale, -dy)); + float planarDown = MathF.Sqrt(dx * dx + dy * dy); + float planarFwd = dz; + + if (geom.IsDigitigrade) + { + float l1 = leg.L1 * scale; + float l2 = leg.L2 * scale; + float l3 = leg.L3 * scale; + float d = Math.Clamp( + MathF.Sqrt(planarDown * planarDown + planarFwd * planarFwd), + leg.MinLegReach * scale, + leg.MaxLegReach * scale); + float basePitch = MathF.Atan2(planarFwd, MathF.Max(0.05f * scale, planarDown)); + + float crouchFrac = Math.Clamp(1f - d / (l1 + l2 + l3), 0f, 1f); + float phiC = 0.08f + 0.42f * crouchFrac; + float maxHockDist = l1 + l2 - 0.04f * scale; + float minCos = (d * d + l3 * l3 - maxHockDist * maxHockDist) / (2f * d * l3); + if (minCos > MathF.Cos(phiC)) + { + phiC = minCos >= 1f ? 0f : MathF.Acos(Math.Clamp(minCos, -1f, 1f)); + } + + float cannonAngle = basePitch + phiC; + float hockDown = d * MathF.Cos(basePitch) - l3 * MathF.Cos(cannonAngle); + float hockFwd = d * MathF.Sin(basePitch) - l3 * MathF.Sin(cannonAngle); + float dHock = Math.Clamp( + MathF.Sqrt(hockDown * hockDown + hockFwd * hockFwd), + MathF.Abs(l1 - l2) + 0.05f * scale, + l1 + l2 - 0.02f * scale); + float hockBasePitch = MathF.Atan2(hockFwd, MathF.Max(0.02f * scale, hockDown)); + float cosAlpha = Math.Clamp((l1 * l1 + dHock * dHock - l2 * l2) / (2f * l1 * dHock), -1f, 1f); + float alpha = MathF.Acos(cosAlpha); + float cosKnee = Math.Clamp((l1 * l1 + l2 * l2 - dHock * dHock) / (2f * l1 * l2), -1f, 1f); + + float hipPitch = hockBasePitch + alpha; + float kneeFlex = MathF.PI - MathF.Acos(cosKnee); + float shinAngle = hipPitch - kneeFlex; + float hockFlex = cannonAngle - shinAngle; + float anklePitch = MathF.Atan2(Vector3.Dot(footNormalLocal, f0), MathF.Max(0.2f, Vector3.Dot(footNormalLocal, u0))) + swingToePitch; + + return new WalkerLegAngles + { + HipPitch = hipPitch, + HipRoll = hipRoll, + KneeFlex = kneeFlex, + HockFlex = hockFlex, + AnklePitch = anklePitch + }; + } + else + { + float l1 = leg.L1 * scale; + float l2 = leg.L2 * scale; + float d = Math.Clamp( + MathF.Sqrt(planarDown * planarDown + planarFwd * planarFwd), + leg.MinLegReach * scale, + leg.MaxLegReach * scale); + float basePitch = MathF.Atan2(planarFwd, MathF.Max(0.05f * scale, planarDown)); + float cosAlpha = Math.Clamp((l1 * l1 + d * d - l2 * l2) / (2f * l1 * d), -1f, 1f); + float alpha = MathF.Acos(cosAlpha); + float cosKnee = Math.Clamp((l1 * l1 + l2 * l2 - d * d) / (2f * l1 * l2), -1f, 1f); + float kneeFlex = (MathF.PI - MathF.Acos(cosKnee)) * leg.KneeBendSign; + float hipPitch = basePitch + leg.KneeBendSign * alpha; + float anklePitch = MathF.Atan2(Vector3.Dot(footNormalLocal, f0), MathF.Max(0.2f, Vector3.Dot(footNormalLocal, u0))) + swingToePitch; + + return new WalkerLegAngles + { + HipPitch = hipPitch, + HipRoll = hipRoll, + KneeFlex = kneeFlex, + HockFlex = 0f, + AnklePitch = anklePitch + }; + } + } + } +} diff --git a/tests/RustToDust.Tests/ArenaSessionTests.cs b/tests/RustToDust.Tests/ArenaSessionTests.cs new file mode 100644 index 0000000..8a45924 --- /dev/null +++ b/tests/RustToDust.Tests/ArenaSessionTests.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class ArenaSessionTests + { + [Fact] + public void DrivingAndFiring_MovesBuggyInYmirAndBuildsWeaponHeat() + { + using var session = new ArenaSession(seed: 42, slot0Human: true, skipInitialDrop: true); + var player = session.State.Contenders[0]; + float startX = player.X; + float startZ = player.Z; + float startYaw = player.Yaw; + int tracerTicks = 0; + + for (int tick = 0; tick < 120; tick++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 1f, + Steer: 0.45f, + AimWorldX: player.X + 40f, + AimWorldZ: player.Z + 10f, + Fire: true, + InteractPickup: false, + Brake: false)); + session.Step(); + + if (session.State.Tracers.Count > 0) + { + tracerTicks++; + } + } + + float dx = player.X - startX; + float dz = player.Z - startZ; + float displacement = MathF.Sqrt(dx * dx + dz * dz); + float yawDelta = MathF.Abs(MatchRules.NormalizeAngle(player.Yaw - startYaw)); + + Assert.True(displacement > 10f, $"Expected >10m displacement, got {displacement:F2}m"); + Assert.True(yawDelta > 0.2f, $"Expected yaw change >0.2 rad, got {yawDelta:F2} rad"); + + var weapon = player.Grid.GetMountedOn("hp.weapon.roof"); + Assert.NotNull(weapon); + Assert.True(weapon!.CurrentTemp > ChassisGrid.AmbientTemp + 5f); + Assert.True(tracerTicks > 0); + } + + [Fact] + public void ChassisSwap_ToManticoreAndRaptor_ReplacesBodyWithoutLeakingYmirLanes() + { + using var session = new ArenaSession(seed: 77, slot0Human: true, skipInitialDrop: true); + var player = session.State.Contenders[0]; + int initialFreeSlots = session.World.FreeBodySlots; + + // Step once to settle world + session.Step(); + + // Spawn Manticore (Dorsal) right beside player and swap + session.State.SpawnChassisDrop(player.X + 1f, player.Z + 1f, Catalog.Manticore); + Assert.True(session.TrySwapNearbyChassis(0)); + Assert.Equal("manticore", player.Grid.Spec.Id); + Assert.Equal(GridPlane.Dorsal, player.Grid.Spec.Plane); + + // Step so Ymir reclaims old tombstone lane + session.Step(); + Assert.Equal(initialFreeSlots, session.World.FreeBodySlots); + + // Now spawn Raptor (Coronal) beside player and swap + session.State.SpawnChassisDrop(player.X + 1f, player.Z + 1f, Catalog.Raptor); + Assert.True(session.TrySwapNearbyChassis(0)); + Assert.Equal("raptor", player.Grid.Spec.Id); + Assert.Equal(GridPlane.Coronal, player.Grid.Spec.Plane); + + session.Step(); + Assert.Equal(initialFreeSlots, session.World.FreeBodySlots); + } + + [Fact] + public void Raycast_RespectsStaticCoverWalls() + { + using var session = new ArenaSession(seed: 12); + var c0 = session.State.ArenaCoverBoxes[0]; + float rayStartZ = c0.Z - c0.HalfZ - 5f; + float raySpanZ = c0.HalfZ * 2f + 10f; + + // A ray from one side of cover block #0 to the other must hit the static cover wall! + var blockedHit = session.World.CastRayClosest((c0.X, c0.Y, rayStartZ), (0f, 0f, raySpanZ)); + Assert.True(blockedHit.Hit); + Assert.True(blockedHit.Point.Z < c0.Z, $"Expected cover hit before z={c0.Z:F2}, got z={blockedHit.Point.Z:F2}"); + Assert.InRange(blockedHit.StableId, 10UL, 99UL); // Static cover StableId range + + // Ray high above the cover block passes unobstructed + var clearHit = session.World.CastRayClosest((c0.X, c0.Y + c0.HalfY + 2.0f, rayStartZ), (0f, 0f, raySpanZ)); + Assert.False(clearHit.Hit); + } + + [Fact] + public void BroadsideFire_UsesDirectionalSupportRadiusNotMaxExtent() + { + using var session = new ArenaSession(seed: 19, slot0Human: true, skipInitialDrop: true); + var player = session.State.Contenders[0]; + + // Swap to Tank / Anvil (HalfWidth = 1.93m, HalfLength = 2.83m) where broadside vs forward differs by ~0.9m. + session.State.SpawnChassisDrop(player.X + 0.5f, player.Z + 0.5f, Catalog.Tank); + Assert.True(session.TrySwapNearbyChassis(0)); + Assert.Equal(Catalog.Tank.Id, player.Grid.Spec.Id); + + // Step once to settle body, then aim strictly perpendicular (broadside) to player's Yaw. + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, false)); + session.Step(); + float broadsideX = MathF.Cos(player.Yaw); + float broadsideZ = -MathF.Sin(player.Yaw); + + session.SetHumanInput(0, new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: player.X + broadsideX * 30f, + AimWorldZ: player.Z + broadsideZ * 30f, + Fire: true, + InteractPickup: false, + Brake: true)); + session.Step(); + + Assert.NotEmpty(session.State.Tracers); + var tracer = session.State.Tracers[^1]; + float dx = tracer.StartX - player.X; + float dz = tracer.StartZ - player.Z; + float muzzleHorizDist = MathF.Sqrt(dx * dx + dz * dz); + + // Expected broadside clearance = HalfWidth (1.65) + 0.35 = 2.00m (well below HalfLength + 0.55 = 3.20m) + Assert.InRange(muzzleHorizDist, player.Grid.Spec.HalfWidth + 0.25f, player.Grid.Spec.HalfWidth + 0.50f); + } + + [Fact] + public void TracerEvent_AssignsMonotonicId_AndPreservesAcrossAdvance() + { + using var session = new ArenaSession(seed: 19, slot0Human: true, skipInitialDrop: true); + var player = session.State.Contenders[0]; + float aimX = player.X + MathF.Sin(player.Yaw) * 25f; + float aimZ = player.Z + MathF.Cos(player.Yaw) * 25f; + + var ids = new List(); + for (int tick = 0; tick < 30 && ids.Count < 2; tick++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, aimX, aimZ, Fire: true, InteractPickup: false, Brake: true)); + session.Step(); + foreach (var t in session.State.Tracers) + { + if (!ids.Contains(t.Id)) + { + ids.Add(t.Id); + } + } + } + + Assert.True(ids.Count >= 2, $"Expected at least 2 distinct tracer IDs, got {ids.Count}"); + Assert.True(ids[0] > 0 && ids[1] > ids[0], $"Expected monotonic tracer IDs, got [{ids[0]}, {ids[1]}]"); + + int trackedId = session.State.Tracers[^1].Id; + float ttlBefore = session.State.Tracers[^1].Ttl; + MatchRules.AdvanceTracers(session.State, 0.01f); + var after = session.State.Tracers.Find(t => t.Id == trackedId); + Assert.Equal(trackedId, after.Id); + Assert.True(after.Ttl < ttlBefore); + } + } +} diff --git a/tests/RustToDust.Tests/AudioSynthTests.cs b/tests/RustToDust.Tests/AudioSynthTests.cs new file mode 100644 index 0000000..d3c97b9 --- /dev/null +++ b/tests/RustToDust.Tests/AudioSynthTests.cs @@ -0,0 +1,350 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Numerics; +using RustToDust.Client; +using RustToDust.Core; +using RustToDust.Core.Audio; +using RustToDust.Net; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests; + +public sealed class AudioSynthTests +{ + private static readonly string[] ExpectedHavenWavs = + { + "mg_shot_01.wav", "mg_shot_02.wav", "mg_tail.wav", + "ac_light_01.wav", "ac_light_02.wav", "ac_med_01.wav", "ac_rotary.wav", + "flak_blast_01.wav", "flak_blast_02.wav", "cannon_heavy_01.wav", "cannon_heavy_02.wav", + "pd_bark_01.wav", "pd_bark_02.wav", "pd_laser.wav", + "rocket_salvo_01.wav", "rocket_salvo_02.wav", + "plasma_ppc_01.wav", "plasma_ppc_02.wav", "lance_beam_01.wav", "laser_heavy_01.wav", "gauss_rail_01.wav", + "mech_reload_bolt.wav", "mech_quick_bolt.wav", "mech_eject.wav", "mech_turret_servo.wav" + }; + + private static string LocateAssetsAudioDir() + { + string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory(); + string assetsDir = Directory.GetParent(vehiclesDir)?.FullName + ?? throw new DirectoryNotFoundException("Could not locate assets directory."); + return Path.Combine(assetsDir, "audio"); + } + + [Fact] + public void CuratedHavenWavs_AreExactly25ValidMono44100PcmUnderBudgetWithZeroThirdPartyFiles() + { + string audioDir = LocateAssetsAudioDir(); + string havenDir = Path.Combine(audioDir, "haven"); + Assert.True(Directory.Exists(havenDir), $"Missing curated Haven directory: {havenDir}"); + + string[] allAudioFiles = Directory.GetFiles(audioDir, "*", SearchOption.AllDirectories); + foreach (string filePath in allAudioFiles) + { + string name = Path.GetFileName(filePath); + Assert.False(name.StartsWith("SW01_", StringComparison.OrdinalIgnoreCase), $"Forbidden SW01 file found: {name}"); + Assert.False(name.StartsWith("MW4", StringComparison.OrdinalIgnoreCase), $"Forbidden MW4 file found: {name}"); + Assert.False(name.StartsWith("Utilities", StringComparison.OrdinalIgnoreCase), $"Forbidden Utilities file found: {name}"); + Assert.False(string.Equals(name, "desktop.ini", StringComparison.OrdinalIgnoreCase), $"Forbidden desktop.ini found: {filePath}"); + } + + string[] havenFiles = Directory.GetFiles(havenDir); + Assert.Equal(25, havenFiles.Length); + + var actualNames = havenFiles.Select(Path.GetFileName).OrderBy(x => x, StringComparer.Ordinal).ToArray(); + var expectedSorted = ExpectedHavenWavs.OrderBy(x => x, StringComparer.Ordinal).ToArray(); + Assert.Equal(expectedSorted, actualNames); + + long totalBytes = 0; + foreach (string wavPath in havenFiles) + { + totalBytes += new FileInfo(wavPath).Length; + WavPcmInfo info = WavFileReader.ReadMonoOrStereo16(wavPath); + + Assert.Equal(44100, info.SampleRate); + Assert.Equal(1, info.Channels); + Assert.Equal(16, info.BitsPerSample); + Assert.True(info.FloatSamples.Length >= 4410, $"{Path.GetFileName(wavPath)} unexpectedly short."); + + float peak = 0f; + double sumSq = 0.0; + for (int i = 0; i < info.FloatSamples.Length; i++) + { + float s = info.FloatSamples[i]; + Assert.True(float.IsFinite(s)); + float a = MathF.Abs(s); + if (a > peak) peak = a; + sumSq += s * s; + } + double rms = Math.Sqrt(sumSq / info.FloatSamples.Length); + Assert.True(rms > 0.01, $"{Path.GetFileName(wavPath)} is silent (RMS={rms:F5})."); + Assert.True(peak <= 0.95f, $"{Path.GetFileName(wavPath)} clips/exceeds 0.95 (peak={peak:F4})."); + } + + Assert.True(totalBytes < 4L * 1024L * 1024L, $"Curated Haven WAV total size {totalBytes} bytes exceeds 4 MB."); + } + + [Fact] + public void AttributionFile_ExistsAndCreditsHavenKendrick() + { + string attributionPath = Path.Combine(LocateAssetsAudioDir(), "ATTRIBUTION.md"); + Assert.True(File.Exists(attributionPath), $"Missing attribution file: {attributionPath}"); + string text = File.ReadAllText(attributionPath); + Assert.Contains("Haven Kendrick", text, StringComparison.Ordinal); + Assert.Contains("WetMixMode", text, StringComparison.Ordinal); + } + + [Fact] + public void PcmSynth_AllCuesAreFiniteNonSilentNonClippingInBothWetAndDryModes_AndWetAddsTailEnergy() + { + Dictionary wetClips = PcmSynth.SynthesizeAll(wetMixMode: true); + Dictionary dryClips = PcmSynth.SynthesizeAll(wetMixMode: false); + + Assert.Equal(PcmSynth.CueRegistry.Count, wetClips.Count); + Assert.Equal(PcmSynth.CueRegistry.Count, dryClips.Count); + + foreach (var (_, key) in PcmSynth.CueRegistry) + { + PcmClipData wet = wetClips[key]; + PcmClipData dry = dryClips[key]; + + Assert.Equal(44100, wet.SampleRate); + Assert.Equal(44100, dry.SampleRate); + Assert.Equal(wet.IsLoop, dry.IsLoop); + + AssertValidPcmBounds(wet, key + " (wet)"); + AssertValidPcmBounds(dry, key + " (dry)"); + + if (wet.IsLoop) + { + Assert.Equal(44100, wet.Samples.Length); + Assert.Equal(44100, dry.Samples.Length); + float wetWrapDiff = MathF.Abs(wet.Samples[^1] - wet.Samples[0]); + float dryWrapDiff = MathF.Abs(dry.Samples[^1] - dry.Samples[0]); + Assert.True(wetWrapDiff < 0.02f, $"Wet loop '{key}' wrap click: {wetWrapDiff:F5}"); + Assert.True(dryWrapDiff < 0.02f, $"Dry loop '{key}' wrap click: {dryWrapDiff:F5}"); + + // Wet room stage alters loop signal measurably vs dry + double diffSq = 0.0; + for (int i = 0; i < wet.Samples.Length; i++) + { + double d = wet.Samples[i] - dry.Samples[i]; + diffSq += d * d; + } + Assert.True(Math.Sqrt(diffSq / wet.Samples.Length) > 0.005, $"Wet loop '{key}' did not measurably differ from dry."); + } + else + { + // Wet one-shots carry real diffused reverb tail beyond the pure dry buffer length + // and measurably higher late/tail energy than the pure dry buffer. + Assert.True(wet.Samples.Length > dry.Samples.Length, $"Wet one-shot '{key}' should include reverb tail."); + int lateStart = (int)(dry.Samples.Length * 0.90); + double dryLateEnergy = 0.0; + for (int i = lateStart; i < dry.Samples.Length; i++) + { + dryLateEnergy += dry.Samples[i] * dry.Samples[i]; + } + double wetLateEnergy = 0.0; + for (int i = lateStart; i < wet.Samples.Length; i++) + { + wetLateEnergy += wet.Samples[i] * wet.Samples[i]; + } + double postDryEnergy = 0.0; + for (int i = dry.Samples.Length; i < wet.Samples.Length; i++) + { + postDryEnergy += wet.Samples[i] * wet.Samples[i]; + } + Assert.True(postDryEnergy > 0.001, $"Wet one-shot '{key}' has zero post-dry tail energy ({postDryEnergy:F6})."); + Assert.True(wetLateEnergy > dryLateEnergy * 1.15 + 0.001, + $"Wet one-shot '{key}' lacks measurable reverb tail energy (dryLate={dryLateEnergy:F4}, wetLate={wetLateEnergy:F4})."); + } + } + } + + [Fact] + public void WalkerFootstepTracker_TriggersStrictlyOnStanceTouchdownEdges() + { + var tracker = new WalkerFootstepTracker(); + var terrain = new TerrainField(seed: 42); + var pulses = new List(); + + var snap = new WalkerVisualSnapshot + { + LegCount = 2, + GeomScale = 1f, + ComPos = new Vector3(10f, 3f, 20f), + ComRot = Quaternion.Identity + }; + + // 1. Standing still with high load: first sighting + 20 frames -> 0 footsteps (no spawn pop, no spam) + snap.LoadG[0] = 1.0f; + snap.LoadG[1] = 1.0f; + for (int f = 0; f < 20; f++) + { + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses); + } + Assert.Empty(pulses); + + // 2. Airborne (swing) across 20 frames -> 0 footsteps, legs become armed + snap.LoadG[0] = 0.0f; + snap.LoadG[1] = 0.0f; + for (int f = 0; f < 20; f++) + { + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses); + } + Assert.Empty(pulses); + + // 3. Touchdown leg 0 rising across sub-frames -> fires EXACTLY ONCE + snap.LoadG[0] = 0.25f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses); + snap.LoadG[0] = 0.80f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses); + snap.LoadG[0] = 1.40f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses); + Assert.Single(pulses); + Assert.Equal(0, pulses[0].LegIndex); + Assert.InRange(MathF.Abs(pulses[0].WorldPos.Y - terrain.SampleHeight(pulses[0].WorldPos.X, pulses[0].WorldPos.Z)), 0f, 0.01f); + + // 4. Re-arm and bounce faster than 0.18s cooldown -> suppressed by cooldown + pulses.Clear(); + snap.LoadG[0] = 0.02f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.02f, pulses); + snap.LoadG[0] = 0.50f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.02f, pulses); + Assert.Empty(pulses); + + // 5. After cooldown expires (> 0.18s), re-arm + touchdown fires again + snap.LoadG[0] = 0.02f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.20f, pulses); + snap.LoadG[0] = 0.60f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.02f, pulses); + Assert.Single(pulses); + } + + [Fact] + public void ClientArenaSession_DrainSimEvents_WorksInSoloAndLoopbackRemote() + { + using var local = new LocalArenaSession(seed: 42, ArenaMapKind.Desert, "AudioTester", skipInitialDrop: true); + IClientArenaSession localIface = local; + var events = new List(); + + var player = local.Inner.State.Contenders[0]; + var input = new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: player.X + 25f, + AimWorldZ: player.Z, + Fire: true, + InteractPickup: false, + Brake: false); + + for (int i = 0; i < 10; i++) + { + localIface.SubmitLocalInput(in input, isPhysicsTick: true); + } + localIface.DrainSimEvents(events); + Assert.Contains(events, e => e is ShotFiredEvent s && !s.IsSpectatorShooter && s.ShooterId == 0); + + // Draining again returns empty until new steps occur + events.Clear(); + localIface.DrainSimEvents(events); + Assert.Empty(events); + + // Loopback host + remote receives ShotFiredEvent through IClientArenaSession.DrainSimEvents + using var host = new ServerMatchHost(IPAddress.Loopback, port: 0, seed: 42, mapKind: ArenaMapKind.Desert); + using var remote = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "AudioRemote"); + IClientArenaSession remoteIface = remote; + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + for (int t = 0; t < 15 && !remote.IsJoined; t++) + { + host.StepOnce(nowMs + t * 16); + remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f); + } + Assert.True(remote.IsJoined); + host.Session.SetContenderPose(remote.LocalContenderId, 0f, 0f, 0f); + for (int s = 0; s < 4; s++) + { + host.StepOnce(nowMs + 240 + s * 16); + remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f); + } + + var rLocal = remoteIface.LocalContender; + var fireInput = new PlayerInput(0f, 0f, rLocal.X + 30f, rLocal.Z, true, false, false); + for (int t = 0; t < 10; t++) + { + remoteIface.SubmitLocalInput(in fireInput, isPhysicsTick: true); + host.StepOnce(nowMs + 300 + t * 16); + remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f); + } + events.Clear(); + remoteIface.DrainSimEvents(events); + Assert.Contains(events, e => e is ShotFiredEvent); + } + + [Fact] + public void RemoteArenaSession_UpdatesRemoteContenderSpeedAndYawFromSnapshot() + { + using var host = new ServerMatchHost(IPAddress.Loopback, port: 0, seed: 42, mapKind: ArenaMapKind.Desert); + using var remoteA = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Observer"); + using var remoteB = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Driver"); + IClientArenaSession ifaceA = remoteA; + IClientArenaSession ifaceB = remoteB; + + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + for (int t = 0; t < 20 && (!remoteA.IsJoined || !remoteB.IsJoined); t++) + { + host.StepOnce(nowMs + t * 16); + ifaceA.BeginRenderFrame(1.0 / 60.0, 1.0f); + ifaceB.BeginRenderFrame(1.0 / 60.0, 1.0f); + } + Assert.True(remoteA.IsJoined && remoteB.IsJoined); + + int idA = ifaceA.LocalContenderId; + int idB = ifaceB.LocalContenderId; + var hostA = host.Session.State.Contenders[idA]; + var hostB = host.Session.State.Contenders[idB]; + hostB.Grid.SwapChassis(Catalog.Jackal); + host.Session.SetContenderPose(idB, hostA.X + 20f, hostA.Z + 20f, 0.75f); + + for (int t = 0; t < 25; t++) + { + ifaceA.SubmitLocalInput(new PlayerInput(0f, 0f, hostA.X, hostA.Z + 20f, false, false, false), isPhysicsTick: true); + ifaceB.SubmitLocalInput(new PlayerInput(1.0f, 0.25f, hostB.X + 30f, hostB.Z + 30f, false, false, false), isPhysicsTick: true); + host.StepOnce(nowMs + 350 + t * 16); + ifaceA.BeginRenderFrame(1.0 / 60.0, 1.0f); + ifaceB.BeginRenderFrame(1.0 / 60.0, 1.0f); + } + + Assert.True(ifaceA.IsContenderVisible(idB)); + var rivalOnA = ifaceA.ViewState.Contenders[idB]; + float expectedSpeed = MathF.Sqrt(rivalOnA.VelX * rivalOnA.VelX + rivalOnA.VelZ * rivalOnA.VelZ); + Assert.True(rivalOnA.Speed > 2.0f, $"Expected remote moving Jackal Speed > 2.0, got {rivalOnA.Speed}"); + Assert.InRange(MathF.Abs(rivalOnA.Speed - expectedSpeed), 0f, 0.01f); + + var q = Quaternion.Normalize(new Quaternion(rivalOnA.CurrRotX, rivalOnA.CurrRotY, rivalOnA.CurrRotZ, rivalOnA.CurrRotW)); + var fwd = Vector3.Transform(Vector3.UnitZ, q); + float expectedYaw = MathF.Atan2(fwd.X, fwd.Z); + Assert.InRange(MathF.Abs(MatchRules.NormalizeAngle(rivalOnA.Yaw - expectedYaw)), 0f, 0.01f); + } + + private static void AssertValidPcmBounds(PcmClipData clip, string label) + { + Assert.True(clip.Samples.Length > 0, $"{label} empty"); + float peak = 0f; + double sumSq = 0.0; + for (int i = 0; i < clip.Samples.Length; i++) + { + float s = clip.Samples[i]; + Assert.True(float.IsFinite(s), $"{label} has non-finite sample at {i}"); + float a = MathF.Abs(s); + if (a > peak) peak = a; + sumSq += s * s; + } + double rms = Math.Sqrt(sumSq / clip.Samples.Length); + Assert.True(rms > 0.01, $"{label} is silent (RMS={rms:F5})"); + Assert.True(peak <= 0.98f, $"{label} clips (peak={peak:F4})"); + } +} diff --git a/tests/RustToDust.Tests/CameraJuiceTests.cs b/tests/RustToDust.Tests/CameraJuiceTests.cs new file mode 100644 index 0000000..aea6e9e --- /dev/null +++ b/tests/RustToDust.Tests/CameraJuiceTests.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using RustToDust.Client; +using RustToDust.Core; +using Xunit; + +namespace RustToDust.Tests; + +public sealed class CameraJuiceTests +{ + [Fact] + public void CameraJuiceState_ZeroIdleJitter_AndMonotonicDecayToExactZero() + { + var juice = new CameraJuiceState(); + Assert.True(juice.IsIdle); + + for (int i = 0; i < 60; i++) + { + juice.Update(1f / 60f, localSpeedMps: 5f, isVtol: false); + juice.ComputeOffsets(out Vector3 off, out float pitch, out float yaw, out float roll); + Assert.True(juice.IsIdle); + Assert.Equal(Vector3.Zero, off); + Assert.Equal(0f, pitch); + Assert.Equal(0f, yaw); + Assert.Equal(0f, roll); + Assert.Equal(0f, juice.FovOffsetDeg); + } + + // Fire local recoilless shot + var events = new List + { + new ShotFiredEvent + { + TracerId = 1, + IsSpectatorShooter = false, + ShooterId = 0, + WeaponClass = (byte)WeaponVisualClass.Explosive, + WeaponId = "recoilless" + } + }; + juice.ConsumeEvents(events, localContenderId: 0, Vector3.Zero); + Assert.False(juice.IsIdle); + Assert.True(juice.RecoilPitchRad > 0f); + Assert.True(juice.RecoilBackMeters > 0f); + Assert.True(juice.Trauma > 0f); + + juice.ComputeOffsets(out Vector3 kickOff, out float kickPitch, out _, out _); + Assert.True(kickOff.Z > 0f); + Assert.True(kickPitch > 0f); + + // Decays monotonically back to exact zero + float prevPitch = juice.RecoilPitchRad; + for (int i = 0; i < 120; i++) + { + juice.Update(1f / 60f, localSpeedMps: 0f, isVtol: false); + Assert.True(juice.RecoilPitchRad <= prevPitch); + prevPitch = juice.RecoilPitchRad; + } + + Assert.True(juice.IsIdle); + juice.ComputeOffsets(out Vector3 settledOff, out float settledPitch, out float settledYaw, out float settledRoll); + Assert.Equal(Vector3.Zero, settledOff); + Assert.Equal(0f, settledPitch); + Assert.Equal(0f, settledYaw); + Assert.Equal(0f, settledRoll); + } + + [Fact] + public void CameraJuiceState_IgnoresRemoteShots_ClampsTrauma_AndResetsCleanly() + { + var juice = new CameraJuiceState(); + + // Remote contender or spectator shot must NOT kick local camera + var remoteEvents = new List + { + new ShotFiredEvent + { + TracerId = 10, + IsSpectatorShooter = false, + ShooterId = 3, + WeaponClass = (byte)WeaponVisualClass.Explosive, + WeaponId = "recoilless" + }, + new ShotFiredEvent + { + TracerId = 11, + IsSpectatorShooter = true, + ShooterId = 0, + WeaponClass = (byte)WeaponVisualClass.Explosive, + WeaponId = "recoilless" + } + }; + juice.ConsumeEvents(remoteEvents, localContenderId: 0, new Vector3(100f, 0f, 100f)); + Assert.True(juice.IsIdle); + + // Clamp trauma to [0, 1] + juice.AddTrauma(5.0f); + Assert.Equal(1.0f, juice.Trauma); + + // Footstep bump triggers only for local contender + var steps = new List + { + new(true, 2, 0, "bastion", 4600f, 1.2f, Vector3.Zero), + new(true, 0, 0, "bastion", 4600f, 1.2f, Vector3.Zero) + }; + juice.ConsumeFootsteps(steps, localContenderId: 0); + Assert.True(juice.FootstepBumpY < 0f); + + // Reset zeroes everything immediately + juice.Reset(); + Assert.True(juice.IsIdle); + Assert.Equal(0f, juice.Trauma); + Assert.Equal(0f, juice.FootstepBumpY); + Assert.Equal(0f, juice.FovOffsetDeg); + } + + [Fact] + public void CameraJuiceState_DeathTrauma_RequiresVisibleAndWithin90m() + { + var juice = new CameraJuiceState(); + var localPos = Vector3.Zero; + + // 1. Out-of-PVS (not visible) contender death even nearby -> 0.0f trauma + var hiddenDeath = new ISimEvent[] + { + new ContenderEliminatedEvent { VictimId = 3, KillerId = 1, IsSpectatorKiller = false } + }; + juice.ConsumeEvents(hiddenDeath, localContenderId: 0, localPos, (_, _) => (false, new Vector3(15f, 0f, 0f))); + Assert.Equal(0.0f, juice.Trauma); + + // 2. Visible but distant (>= 90m) contender death -> 0.0f trauma + juice.ConsumeEvents(hiddenDeath, localContenderId: 0, localPos, (_, _) => (true, new Vector3(120f, 0f, 0f))); + Assert.Equal(0.0f, juice.Trauma); + + // 3. No resolver/session -> 0.0f trauma (never global) + juice.ConsumeEvents(hiddenDeath, localContenderId: 0, localPos); + Assert.Equal(0.0f, juice.Trauma); + + // 4. Nearby visible death (20m) -> positive scaled trauma: 0.14 * (1 - 20 / 90) + juice.ConsumeEvents(hiddenDeath, localContenderId: 0, localPos, (_, _) => (true, new Vector3(20f, 0f, 0f))); + float expected = 0.14f * (1f - 20f / 90f); + Assert.InRange(juice.Trauma, expected - 1e-4f, expected + 1e-4f); + } + + [Fact] + public void DropPodFov_WidensTo82DegAndEasesTo58DegOnTouchdown() + { + var juice = new CameraJuiceState(); + const float dt = 1f / 60f; + + // 1. Freefall at max cross-zone glide speed (124 m/s) -> widens to 82..84 deg smoothly + for (int i = 0; i < 120; i++) + { + juice.Update(dt, localSpeedMps: 124f, isVtol: false, isInDropPod: true, podPhase: OrbitalPodPhase.Freefall); + } + float freefallFov = CameraJuiceState.BaseFovDeg + juice.FovOffsetDeg; + Assert.InRange(freefallFov, 80.0f, 85.0f); + + // 2. RetroBurn -> tightens to ~76 deg + for (int i = 0; i < 90; i++) + { + juice.Update(dt, localSpeedMps: 15f, isVtol: false, isInDropPod: true, podPhase: OrbitalPodPhase.RetroBurn); + } + float retroFov = CameraJuiceState.BaseFovDeg + juice.FovOffsetDeg; + Assert.InRange(retroFov, 74.5f, 77.5f); + + // 3. Touchdown ground release -> eases monotonically back toward 58 deg within ~1.5s + float prevFov = retroFov; + for (int i = 0; i < 90; i++) + { + juice.Update(dt, localSpeedMps: 0f, isVtol: false, isInDropPod: false); + float curFov = CameraJuiceState.BaseFovDeg + juice.FovOffsetDeg; + Assert.True(curFov <= prevFov + 1e-4f, $"Expected monotonic FOV release, jumped {prevFov:F3} -> {curFov:F3}"); + Assert.True(prevFov - curFov < 2.0f, $"Expected smooth FOV release without discontinuity: delta={prevFov - curFov:F2}"); + prevFov = curFov; + } + Assert.InRange(prevFov, 57.9f, 59.0f); + } +} diff --git a/tests/RustToDust.Tests/CultNetMultiplayerTests.cs b/tests/RustToDust.Tests/CultNetMultiplayerTests.cs new file mode 100644 index 0000000..22052a9 --- /dev/null +++ b/tests/RustToDust.Tests/CultNetMultiplayerTests.cs @@ -0,0 +1,998 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Numerics; +using System.Threading; +using GameCult.Mesh; +using GameCult.Networking; +using RustToDust.Core; +using RustToDust.Net; +using RustToDust.Ymir; +using Xunit; +using Xunit.Abstractions; + +namespace RustToDust.Tests +{ + public sealed class CultNetMultiplayerTests + { + private readonly ITestOutputHelper _output; + + public CultNetMultiplayerTests(ITestOutputHelper output) + { + _output = output; + } + + [Fact] + public void SnapshotCodec_WorstCase12ContendersAndWalkersAndCombatSpecs_StrictlyFitsIn1152Bytes() + { + var state = new MatchState(seed: 42, ArenaMapKind.Desert); + var local = state.Contenders[0]; + local.Grid.SwapChassis(Catalog.Bastion); // large 8x8 dorsal mech grid + + var contenders = new List(12); + var walkers = new List(12); + var specs = new List(10); + + for (int i = 0; i < 12; i++) + { + contenders.Add(new NetContenderState + { + SlotId = (byte)i, + Alive = true, + IsHuman = true, + Fire = true, + Brake = false, + Snap = false, + Pos = new Vector3(i * 10f, 3f, -i * 5f), + Rot = Quaternion.Identity, + Vel = new Vector3(12f, 0f, 4f), + AimYaw = 0.5f, + AimPitchDeg = 10f, + Throttle = 1f, + Steer = -0.5f, + CoreHpRatio = 0.85f, + MaxThermalRatio = 0.45f + }); + + var ws = new WalkerVisualSnapshot { LegCount = 4 }; + for (int l = 0; l < 4; l++) + { + ws.LegAngles[l] = new WalkerLegAngles { HipPitch = 0.4f, HipRoll = 0.1f, KneeFlex = -0.8f, HockFlex = 0.3f, AnklePitch = 0.2f }; + ws.FootNormal[l] = Vector3.UnitY; + ws.LoadG[l] = 1.2f; + } + walkers.Add(new NetWalkerEntry { IsContender = true, EntityId = (byte)i, Snapshot = ws }); + } + + for (int i = 0; i < 10; i++) + { + specs.Add(new NetSpectatorState + { + Id = (byte)i, + Alive = true, + Stance = SpectatorStance.Provoked, + TargetContenderId = 0, + Pos = new Vector3(100f + i * 5f, 4f, -80f), + Rot = Quaternion.Identity, + Vel = new Vector3(2f, 0f, -3f) + }); + } + + byte[] p1 = SnapshotCodec.EncodeCorePvs( + 1, 42, 84, 1.4f, 10, 100, 450f, MatchPhase.Active, null, 2, 0xFFF, + local, new Vector3(0.1f, 0.2f, 0.05f), contenders, walkers, specs); + byte[] w1 = SnapshotCodec.WrapLatest(p1, 1, 1); + + byte[] p2 = SnapshotCodec.EncodeSpectatorOrbitHalf(1, 42, 0, Enumerable.Range(0, 28).Select(i => specs[i % specs.Count]).ToList()); + byte[] w2 = SnapshotCodec.WrapLatest(p2, 1, 2); + + var radarList = Enumerable.Range(0, 32).Select(i => new NetRadarContact { EntityId = (byte)i, Visible = true, LastSeenX = i * 5f, LastSeenZ = -i * 5f }).ToList(); + byte[] p3 = SnapshotCodec.EncodeRadarContacts(1, 42, radarList.Take(11).ToList(), radarList); + byte[] w3 = SnapshotCodec.WrapLatest(p3, 1, 3); + + byte[] pIn = SnapshotCodec.EncodeClientInput(new ClientInputPacket(1, 99, 1234, new PlayerInput(1f, -0.5f, 10f, 20f, true, true, false, 2f, 0.5f))); + byte[] wIn = SnapshotCodec.WrapLatest(pIn, 1, 4, SnapshotCodec.SchemaInputId); + + byte[] udp1 = EncodeRudpLatestDatagram(w1, 1); + byte[] udp2 = EncodeRudpLatestDatagram(w2, 2); + byte[] udp3 = EncodeRudpLatestDatagram(w3, 3); + byte[] udpIn = EncodeRudpLatestDatagram(wIn, 4); + + _output.WriteLine($"Max frame bytes: Packet1={w1.Length}B, Packet2={w2.Length}B, Packet3={w3.Length}B, Input={wIn.Length}B"); + _output.WriteLine($"Max UDP wire bytes: Packet1={udp1.Length}B, Packet2={udp2.Length}B, Packet3={udp3.Length}B, Input={udpIn.Length}B"); + + Assert.True(w1.Length <= SnapshotCodec.MaxLatestFrameBytes, $"Packet1 frame {w1.Length}B > {SnapshotCodec.MaxLatestFrameBytes}B"); + Assert.True(w2.Length <= SnapshotCodec.MaxLatestFrameBytes, $"Packet2 frame {w2.Length}B > {SnapshotCodec.MaxLatestFrameBytes}B"); + Assert.True(w3.Length <= SnapshotCodec.MaxLatestFrameBytes, $"Packet3 frame {w3.Length}B > {SnapshotCodec.MaxLatestFrameBytes}B"); + Assert.True(wIn.Length <= SnapshotCodec.MaxLatestFrameBytes, $"Input frame {wIn.Length}B > {SnapshotCodec.MaxLatestFrameBytes}B"); + + Assert.True(udp1.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Packet1 UDP {udp1.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); + Assert.True(udp2.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Packet2 UDP {udp2.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); + Assert.True(udp3.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Packet3 UDP {udp3.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); + Assert.True(udpIn.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Input UDP {udpIn.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); + + var decoded = SnapshotCodec.DecodeCorePvs(SnapshotCodec.Unwrap(w1).Payload.Span); + Assert.Equal(12, decoded.Contenders.Count); + Assert.Equal(42u, decoded.SnapshotSeq); + } + + [Fact] + public void RealUdpLoopback_TwoClientsSion_DriveFireDamageCargoAndSimEvents() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var clientA = new RemoteArenaSession(ep, "Alpha"); + using var clientB = new RemoteArenaSession(ep, "Bravo"); + + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + Assert.True(PumpUntil(host, new[] { clientA, clientB }, () => clientA.IsJoined && clientB.IsJoined, ref nowMs, 3000), + "Both UDP clients should join ServerMatchHost"); + + Assert.NotEqual(clientA.LocalContenderId, clientB.LocalContenderId); + int slotA = clientA.LocalContenderId; + int slotB = clientB.LocalContenderId; + + // Place A and B facing each other 28m apart in open Sion plaza + var anchor = host.Session.State.Contenders[slotA]; + host.Session.SetContenderPose(slotA, anchor.X, anchor.Z, 0f); + host.Session.SetContenderPose(slotB, anchor.X, anchor.Z + 28f, MathF.PI); + + // Give clientB a cargo module & equip it over reliable schema channel -> verify private cargo not leaked to A! + host.Session.State.Contenders[slotB].Grid.TryAddCargo(Catalog.Autocannon); + host.Session.State.Contenders[slotA].Grid.TryAddCargo(Catalog.CopperRad); + int cargoIdxB = host.Session.State.Contenders[slotB].Grid.Cargo.Count - 1; + Assert.True(clientB.RequestEquipCargo(cargoIdxB, "hp.weapon.roof")); + + float startAz = clientA.LocalContender.Z; + float bArmorBefore = host.Session.State.Contenders[slotB].Grid.TotalArmorRatio(); + + // Step 90 ticks: Client A drives forward + fires at Client B + for (int t = 0; t < 90; t++) + { + var posB = host.Session.State.Contenders[slotB]; + clientA.SubmitLocalInput(new PlayerInput(0.6f, 0f, posB.X, posB.Z, Fire: true, InteractPickup: false, Brake: false, AimWorldY: posB.Y), true); + clientB.SubmitLocalInput(new PlayerInput(0f, 0f, anchor.X, anchor.Z, Fire: false, InteractPickup: false, Brake: true), true); + + nowMs += 16; + host.StepOnce(nowMs); + clientA.BeginRenderFrame(1.0 / 60.0, 1f); + clientB.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + + Assert.True(clientA.LocalContender.Z > startAz + 1.5f, "Client A should have advanced under Option M + server auth"); + Assert.True(host.Session.State.Contenders[slotB].Grid.TotalArmorRatio() < bArmorBefore, "Client A's fire should damage Client B on server"); + Assert.True(clientB.LocalContender.Grid.TotalArmorRatio() < 1.0f, "Client B should receive HitImpactEvent armor damage"); + Assert.Equal(Catalog.Autocannon.Id, clientA.ViewState.Contenders[slotB].Grid.GetMountedOn("hp.weapon.roof")?.Spec.Id); + Assert.Empty(clientA.ViewState.Contenders[slotB].Grid.Cargo); // Private cargo NOT leaked! + Assert.True(clientA.ViewState.Tracers.Count > 0 || host.Session.State.Contenders[slotB].Grid.HitSequence > 0); + } + + [Fact] + public void AntiWallhack_PvsPayloadAudit_OccludedRivalAndExemplarOmittedUntilPvsEnter() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 12, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var clientA = new RemoteArenaSession(ep, "Alpha"); + using var clientB = new RemoteArenaSession(ep, "Bravo"); + + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + Assert.True(PumpUntil(host, new[] { clientA, clientB }, () => clientA.IsJoined && clientB.IsJoined, ref nowMs, 3000)); + + int slotA = clientA.LocalContenderId; + int slotB = clientB.LocalContenderId; + + // Place A and B on opposite sides of tall cover box (> 65m apart so outside proximity PVS envelope!) + var box = host.Session.State.ArenaCoverBoxes.First(b => b.HalfY >= 2.3f); + host.Session.SetContenderPose(slotA, box.X, box.Z - box.HalfZ - 40f, 0f); + host.Session.SetContenderPose(slotB, box.X, box.Z + box.HalfZ + 40f, 0f); + if (host.Session.State.ObserverStates.TryGetValue(slotA, out var obsA)) obsA.ContenderContacts.Remove(slotB); + if (host.Session.State.ObserverStates.TryGetValue(slotB, out var obsB)) obsB.ContenderContacts.Remove(slotA); + + // Step 10 ticks so server recomputes PVS & snapshots while B also tries moving behind cover + float preBClientX = clientA.ViewState.Contenders[slotB].X; + float preBClientZ = clientA.ViewState.Contenders[slotB].Z; + float preBServerZ = host.Session.State.Contenders[slotB].Z; + for (int t = 0; t < 10; t++) + { + clientB.SubmitLocalInput(new PlayerInput(1f, 0f, 0f, 0f, false, false, false), true); + nowMs += 16; + host.StepOnce(nowMs); + clientA.BeginRenderFrame(1.0 / 60.0, 1f); + clientB.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + + Assert.False(host.Session.IsEntityInPeerPvs(slotA, true, slotB), "Occluded rival > 65m must NOT be in Peer A PVS"); + Assert.False(clientA.IsContenderVisible(slotB), "Client A must mark occluded rival invisible"); + Assert.False(clientA.LocalContenderContacts.TryGetValue(slotB, out var memB) && MatchState.IsContactOnRadar(memB)); + Assert.True(MathF.Abs(host.Session.State.Contenders[slotB].Z - preBServerZ) > 0.25f, "Server B actually moved behind cover"); + Assert.Equal(preBClientX, clientA.ViewState.Contenders[slotB].X); + Assert.Equal(preBClientZ, clientA.ViewState.Contenders[slotB].Z); + + // Now move B into open plaza right in front of A AND swap B's chassis while occluded -> verify PvsEnter delivers chassis & pose! + host.Session.State.SpawnChassisDrop(box.X, box.Z + box.HalfZ + 40f, Catalog.Anvil); + Assert.True(host.Session.TrySwapNearbyChassis(slotB)); + host.Session.SetContenderPose(slotB, box.X + 18f, box.Z - box.HalfZ - 40f, 0f); + + for (int t = 0; t < 12; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + clientA.BeginRenderFrame(1.0 / 60.0, 1f); + clientB.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + + Assert.True(clientA.IsContenderVisible(slotB), "Rival entering open LOS must become PVS visible"); + Assert.Equal(Catalog.Anvil.Id, clientA.ViewState.Contenders[slotB].Grid.Spec.Id); + } + + [Fact] + public void OptionM_LocalPredictionMovesImmediatelyAtZeroMs_ReconcilesSmoothly_AndHardSnapsOver4m() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var serverEp = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var client = new RemoteArenaSession(serverEp, "Predictor"); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + Assert.True(PumpUntil(host, new[] { client }, () => client.IsJoined, ref nowMs, 3000)); + + int slot = client.LocalContenderId; + host.Session.SetContenderPose(slot, 0f, 0f, 0f); + for (int t = 0; t < 4; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + client.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + + float initialZ = client.GetInterpolatedContenderPose(slot, 1f).Pos.Z; + + // Drop ALL inbound snapshots temporarily while client drives 10 ticks -> Option M must predict movement immediately! + client.DebugInboundLatestDropFilter = _ => true; + for (int t = 0; t < 10; t++) + { + client.SubmitLocalInput(new PlayerInput(1f, 0f, 0f, 60f, false, false, false), true); + } + float predictedZ = client.GetInterpolatedContenderPose(slot, 1f).Pos.Z; + Assert.True(predictedZ > initialZ + 0.10f, $"Option M must move immediately at 0ms before snapshots arrive ({initialZ:F3} -> {predictedZ:F3})"); + Assert.True(client.UnackedInputCount >= 10); + + // Re-enable snapshots & let server process delayed packets -> verify reconciliation replays unacked & decays error smoothly + client.DebugInboundLatestDropFilter = null; + for (int t = 0; t < 12; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + client.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + + Assert.Equal(0, client.UnackedInputCount); + + // Force > 4.0m authoritative displacement (teleport) -> Option M MUST hard-snap residual error to zero! + host.Session.SetContenderPose(slot, 45f, 45f, 0f); + bool sawTeleportSnap = false; + float errAtSnap = float.MaxValue; + for (int t = 0; t < 10; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + client.BeginRenderFrame(1.0 / 60.0, 1f); + var p = client.GetInterpolatedContenderPose(slot, 1f).Pos; + if (Vector2.Distance(new Vector2(p.X, p.Z), new Vector2(45f, 45f)) < 2.0f) + { + sawTeleportSnap = true; + errAtSnap = client.CurrentPredictionError.Length(); + break; + } + Thread.Sleep(1); + } + + Assert.True(sawTeleportSnap, "Client should receive >4m teleport snapshot"); + Assert.True(errAtSnap < 0.001f, + $"Expected >4m teleport to hard-snap prediction error to zero, got {errAtSnap:F4}m"); + var snappedPos = client.GetInterpolatedContenderPose(slot, 1f).Pos; + Assert.InRange(Vector2.Distance(new Vector2(snappedPos.X, snappedPos.Z), new Vector2(45f, 45f)), 0f, 1.5f); + } + + [Fact] + public void OptionL1_DisconnectAndTimeoutHandBackToAi_AndReconnectTokenReclaimsExactSlot() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var serverEp = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + var clientA = new RemoteArenaSession(serverEp, "Nomad"); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000)); + + int originalSlot = clientA.LocalContenderId; + Guid token = clientA.ReconnectToken; + Assert.NotEqual(Guid.Empty, token); + Assert.True(host.Session.State.Contenders[originalSlot].IsHuman); + + // 1. Graceful disconnect -> IsHuman flips to false (AI takes over surviving chassis) + clientA.DisconnectGracefully("BRB"); + clientA.Dispose(); + + for (int t = 0; t < 35; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + Thread.Sleep(1); + } + + Assert.False(host.Session.State.Contenders[originalSlot].IsHuman, "Graceful disconnect must hand slot back to AI"); + Assert.Equal(0, host.ConnectedHumanCount); + + // 2. Reconnect presenting matching ReconnectToken -> reclaims exact same slot! + using var clientAReconnect = new RemoteArenaSession(serverEp, "Nomad", token); + Assert.True(PumpUntil(host, new[] { clientAReconnect }, () => clientAReconnect.IsJoined, ref nowMs, 3000)); + Assert.Equal(originalSlot, clientAReconnect.LocalContenderId); + Assert.True(host.Session.State.Contenders[originalSlot].IsHuman); + + // 3. Simulate > 5000ms silence (timeout) -> server releases slot back to AI cleanly! + nowMs += ServerMatchHost.IdleTimeoutMs + 250; + host.StepOnce(nowMs); + + Assert.False(host.Session.State.Contenders[originalSlot].IsHuman, "5s silence timeout must hand slot back to AI"); + Assert.Equal(0, host.ConnectedHumanCount); + } + + [Fact] + public void Cut5cFix1_Sion30mAcrossBuilding_OmitsOccludedRivalFromInitialStateCorePvsAndEvents() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + // Pick a solid Sion Old Town building ~30m wide and place contender 0 & 1 on opposite sides BEFORE client B joins! + var sion = host.Session.State.SionMap!; + var terrain = host.Session.State.Terrain; + float halfH = Catalog.Jackal.HalfHeight; + SionBuildingAabb? chosen = null; + float z1 = 0f, z2 = 0f; + for (int i = 0; i < sion.Buildings.Count; i++) + { + var b = sion.Buildings[i]; + if (b.Class != "Gebaeude Einzelhaus" || b.HalfX < 6f || b.HalfZ < 6f || (b.RoofY - b.GroundY) < 9f || + MathF.Abs(b.CenterX) > 600f || MathF.Abs(b.CenterZ) > 600f) + continue; + float candZ1 = b.CenterZ - b.HalfZ - 5f; + float candZ2 = b.CenterZ + b.HalfZ + 5f; + if (MathF.Abs(candZ2 - candZ1) > 48f) continue; + if (sion.IsInsideAnyBuildingXz(b.CenterX, candZ1, 3.5f) || sion.IsInsideAnyBuildingXz(b.CenterX, candZ2, 3.5f)) + continue; + float y1 = terrain.SampleHeight(b.CenterX, candZ1) + halfH + 0.15f; + float y2 = terrain.SampleHeight(b.CenterX, candZ2) + halfH + 0.15f; + if (!host.Session.HasLineOfSight(b.CenterX, MatchRules.GetObserverEyeY(y1, halfH), candZ1, + b.CenterX, MatchRules.GetTargetAimY(y2, halfH), candZ2)) + { + chosen = b; + z1 = candZ1; + z2 = candZ2; + break; + } + } + Assert.NotNull(chosen); + var building = chosen!.Value; + + using var clientA = new RemoteArenaSession(ep, "Alpha"); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000)); + int slotA = clientA.LocalContenderId; + + // Place A on side 1, and pick an AI/B slot on side 2 (~30m away across the building) BEFORE clientB joins + int slotB = (slotA + 1) % MatchState.ContenderCount; + host.Session.SetContenderPose(slotA, building.CenterX, z1, 0f); + host.Session.SetContenderPose(slotB, building.CenterX, z2, MathF.PI); + host.Session.State.SpawnChassisDrop(building.CenterX, z2 + 2f, Catalog.Anvil); + host.StepOnce(nowMs += 16); + + // Re-place B after step and join B while A & B are ~30m apart across the building + host.Session.SetContenderPose(slotA, building.CenterX, z1, 0f); + host.Session.SetContenderPose(slotB, building.CenterX, z2, MathF.PI); + host.StepOnce(nowMs += 16); + + Assert.False(host.Session.IsEntityInPeerPvs(slotA, true, slotB), + "Occluded rival 30m across Sion building must NOT be in Peer A PVS (no 65m blind bypass)"); + + using var clientB = new RemoteArenaSession(ep, "Bravo"); + Assert.True(PumpUntil(host, new[] { clientA, clientB }, () => clientB.IsJoined, ref nowMs, 3000)); + int realSlotB = clientB.LocalContenderId; + + // Verify InitialMatchStateDto omits occluded rival at ~30m across Sion building: + // Retire clientA, pin slotA at z1 and slotB at z2, then reconnect clientA with its token! + Guid tokenA = clientA.ReconnectToken; + clientA.DisconnectGracefully("RejoinTest"); + clientA.Dispose(); + for (int t = 0; t < 35; t++) + { + host.Session.SetContenderPose(slotA, building.CenterX, z1, 0f); + host.Session.SetContenderPose(realSlotB, building.CenterX, z2, MathF.PI); + nowMs += 16; + host.StepOnce(nowMs); + clientB.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + + using var clientARejoin = new RemoteArenaSession(ep, "Alpha", tokenA); + Assert.True(PumpUntil(host, new[] { clientARejoin, clientB }, () => clientARejoin.IsJoined, ref nowMs, 3000)); + Assert.Equal(slotA, clientARejoin.LocalContenderId); + Assert.False(clientARejoin.IsContenderVisible(realSlotB), "Occluded rival 30m across building must not be visible in InitialMatchStateDto"); + Assert.Equal(0f, clientARejoin.ViewState.Contenders[realSlotB].X); + Assert.Equal(0f, clientARejoin.ViewState.Contenders[realSlotB].Z); + + // Re-pin & test live events while occluded behind building + host.Session.SetContenderPose(slotA, building.CenterX, z1, 0f); + host.Session.SetContenderPose(realSlotB, building.CenterX, z2, MathF.PI); + if (host.Session.State.ObserverStates.TryGetValue(slotA, out var obsA)) obsA.ContenderContacts.Remove(realSlotB); + + int dropsBefore = clientARejoin.ViewState.GroundDrops.Count(d => !d.PickedUp && Vector2.Distance(new Vector2(d.X, d.Z), new Vector2(building.CenterX, z2)) < 12f); + host.Session.State.SpawnChassisDrop(building.CenterX, z2 + 3f, Catalog.Paladin); + int hitsBefore = clientARejoin.ViewState.HitEvents.Count; + int tracersBefore = clientARejoin.ViewState.Tracers.Count; + + for (int t = 0; t < 10; t++) + { + clientARejoin.SubmitLocalInput(new PlayerInput(0f, 0f, building.CenterX, z1 - 10f, false, false, false), true); + clientB.SubmitLocalInput(new PlayerInput(0f, 0f, building.CenterX + 3f, z2 + 6f, Fire: true, false, false, AimWorldY: terrain.SampleHeight(building.CenterX + 3f, z2 + 6f)), true); + nowMs += 16; + host.StepOnce(nowMs); + clientARejoin.BeginRenderFrame(1.0 / 60.0, 1f); + clientB.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + + Assert.False(host.Session.IsEntityInPeerPvs(slotA, true, realSlotB)); + Assert.False(clientARejoin.IsContenderVisible(realSlotB)); + int dropsAfter = clientARejoin.ViewState.GroundDrops.Count(d => !d.PickedUp && Vector2.Distance(new Vector2(d.X, d.Z), new Vector2(building.CenterX, z2)) < 12f); + Assert.Equal(dropsBefore, dropsAfter); + // Any HitImpactEvent or ShotFiredEvent from occluded B behind the building must NOT leak B's coordinates to A! + for (int i = tracersBefore; i < clientARejoin.ViewState.Tracers.Count; i++) + { + var tr = clientARejoin.ViewState.Tracers[i]; + Assert.True(Vector2.Distance(new Vector2(tr.StartX, tr.StartZ), new Vector2(building.CenterX, z2)) > 5f, + "Occluded ShotFiredEvent must not leak rival shooter coords"); + } + for (int i = hitsBefore; i < clientARejoin.ViewState.HitEvents.Count; i++) + { + var he = clientARejoin.ViewState.HitEvents[i]; + Assert.True(Vector2.Distance(new Vector2(he.SourceX, he.SourceZ), new Vector2(building.CenterX, z2)) > 5f, + "Occluded HitImpactEvent must scrub SourceX/Y/Z if shooter not in PVS"); + } + } + + [Fact] + public void Cut5cFix2_WalkerGaitClock_ChassisSwapSink_AndSpectatorWalkerSync() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var serverEp = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + // Real 120ms RTT UDP delay proxy (60ms uplink + 60ms downlink) + using var proxyToClient = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp) { Blocking = false }; + using var proxyToServer = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp) { Blocking = false }; + proxyToClient.Bind(new IPEndPoint(IPAddress.Loopback, 0)); + proxyToServer.Bind(new IPEndPoint(IPAddress.Loopback, 0)); + var proxyEp = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)proxyToClient.LocalEndPoint!).Port); + + var uplink = new Queue<(long DeliverMs, byte[] Data)>(); + var downlink = new Queue<(long DeliverMs, byte[] Data)>(); + EndPoint? clientRemoteEp = null; + void PumpProxy(long tMs, int oneWayMs) + { + var buf = new byte[4096]; + while (proxyToClient.Available > 0) + { + EndPoint from = new IPEndPoint(IPAddress.Any, 0); + int n = proxyToClient.ReceiveFrom(buf, ref from); + clientRemoteEp = from; + uplink.Enqueue((tMs + oneWayMs, buf.AsSpan(0, n).ToArray())); + } + while (proxyToServer.Available > 0) + { + EndPoint from = new IPEndPoint(IPAddress.Any, 0); + int n = proxyToServer.ReceiveFrom(buf, ref from); + downlink.Enqueue((tMs + oneWayMs, buf.AsSpan(0, n).ToArray())); + } + while (uplink.Count > 0 && uplink.Peek().DeliverMs <= tMs) + { + proxyToServer.SendTo(uplink.Dequeue().Data, serverEp); + } + while (downlink.Count > 0 && downlink.Peek().DeliverMs <= tMs && clientRemoteEp is not null) + { + proxyToClient.SendTo(downlink.Dequeue().Data, clientRemoteEp); + } + } + + using var client = new RemoteArenaSession(proxyEp, "Walker"); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var deadline = DateTimeOffset.UtcNow.AddMilliseconds(4000); + while (DateTimeOffset.UtcNow < deadline && !client.IsJoined) + { + nowMs += 16; + PumpProxy(nowMs, 60); + host.StepOnce(nowMs); + PumpProxy(nowMs, 60); + client.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.True(client.IsJoined); + int slot = client.LocalContenderId; + + // a) Swap local contender to Paladin (biped walker), walk 2.0s @ 120ms simulated RTT + host.Session.SetContenderPose(slot, 0f, 0f, 0f); + host.Session.State.SpawnChassisDrop(0f, 0f, Catalog.Paladin); + Assert.True(host.Session.TrySwapNearbyChassis(slot)); + for (int t = 0; t < 16; t++) + { + client.SubmitLocalInput(new PlayerInput(0f, 0f, 0f, 120f, false, false, false), true); + nowMs += 16; + PumpProxy(nowMs, 60); + host.StepOnce(nowMs); + PumpProxy(nowMs, 60); + client.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + + float clientStartTime = client.PredictedWalkerSimTime ?? 0f; + float serverStartTime = host.Session.GetWalkerSimTime(true, slot) ?? 0f; + int maxUnackedObserved = 0; + for (int t = 0; t < 120; t++) + { + client.SubmitLocalInput(new PlayerInput(0.8f, 0f, 0f, 120f, false, false, false), true); + maxUnackedObserved = Math.Max(maxUnackedObserved, client.UnackedInputCount); + nowMs += 16; + PumpProxy(nowMs, 60); + host.StepOnce(nowMs); + PumpProxy(nowMs, 60); + client.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + Assert.True(maxUnackedObserved >= 5, $"Expected >=5 unacked inputs under 120ms RTT, saw {maxUnackedObserved}"); + + float? serverWalkerTime = host.Session.GetWalkerSimTime(true, slot); + float? clientWalkerTime = client.PredictedWalkerSimTime; + Assert.NotNull(serverWalkerTime); + Assert.NotNull(clientWalkerTime); + float clientDelta = clientWalkerTime!.Value - clientStartTime; + float serverDelta = serverWalkerTime!.Value - serverStartTime; + Assert.True(MathF.Abs(clientDelta - serverDelta) <= 0.20f, + $"Walker SimTime must track 1x within +-0.20s (no 4.83x overdrive): client={clientDelta:F3}s server={serverDelta:F3}s"); + + // b) Mid-match Jackal -> Breaker chassis swap must produce 0.0m vertical underground _predErrorPos + host.Session.State.SpawnChassisDrop(host.Session.State.Contenders[slot].X, host.Session.State.Contenders[slot].Z, Catalog.Jackal); + Assert.True(host.Session.TrySwapNearbyChassis(slot)); + for (int t = 0; t < 16; t++) + { + nowMs += 16; + PumpProxy(nowMs, 60); + host.StepOnce(nowMs); + PumpProxy(nowMs, 60); + client.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + var cServer = host.Session.State.Contenders[slot]; + host.Session.State.SpawnChassisDrop(cServer.X, cServer.Z, Catalog.Breaker); + Assert.True(host.Session.TrySwapNearbyChassis(slot)); + for (int t = 0; t < 16; t++) + { + client.SubmitLocalInput(new PlayerInput(0f, 0f, cServer.X, cServer.Z + 120f, false, false, false), true); + nowMs += 16; + PumpProxy(nowMs, 60); + host.StepOnce(nowMs); + PumpProxy(nowMs, 60); + client.BeginRenderFrame(1.0 / 60.0, 1f); + var visPos = client.GetInterpolatedContenderPose(slot, 1f).Pos; + float gh = host.Session.State.Terrain.SampleHeight(visPos.X, visPos.Z); + Assert.True(visPos.Y >= gh + Catalog.Jackal.HalfHeight * 0.5f, + $"Jackal->Breaker swap must not sink underground: visY={visPos.Y:F3}m gh={gh:F3}m"); + Assert.True(MathF.Abs(client.CurrentPredictionError.Y) < 0.15f, + $"Jackal->Breaker swap must not accumulate vertical sink error: predErrorY={client.CurrentPredictionError.Y:F3}m"); + Thread.Sleep(1); + } + + // c) Combat spectator walker (Exemplar) has valid GeomScale > 0, IsDigitigrade, non-zero ComRot, and synced Exemplar HP/armor + var exemplar = host.Session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar && s.Alive); + exemplar.Stance = SpectatorStance.Provoked; + exemplar.TargetContenderId = slot; + host.Session.SetContenderPose(slot, exemplar.X, exemplar.Z - 24f, 0f); + for (int t = 0; t < 20; t++) + { + nowMs += 16; + PumpProxy(nowMs, 60); + host.StepOnce(nowMs); + PumpProxy(nowMs, 60); + client.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + Assert.True(client.TrySampleInterpolatedWalkerPose(false, exemplar.Id, 1f, out var exSnap), + "Combat Exemplar walker snapshot should be available"); + Assert.True(exSnap.GeomScale > 0.1f, $"Exemplar GeomScale must be > 0, got {exSnap.GeomScale}"); + Assert.True(exSnap.IsDigitigrade, "Exemplar walker must have IsDigitigrade=true"); + Assert.True(exSnap.ComRot.LengthSquared() > 0.5f, "Exemplar walker ComRot must be valid normalized quaternion"); + var clientExemplar = client.ViewState.Spectators.Spectators.First(s => s.Id == exemplar.Id); + Assert.Equal(SpectatorRing.ExemplarSpec.Id, clientExemplar.Grid.Spec.Id); + Assert.InRange(clientExemplar.Grid.CoreHp, exemplar.Grid.CoreHp - 1f, exemplar.Grid.CoreHp + 1f); + } + + [Fact] + public void Cut5cFix4_Packet2OverflowDeliversAll10CombatSpectators_AndMalformedPacketDoesNotThrow() + { + var state = new MatchState(seed: 42, ArenaMapKind.Desert); + var local = state.Contenders[0]; + local.Grid.SwapChassis(Catalog.Bastion); // large 8x8 local grid + + var contenders = new List(12); + var walkers = new List(12); + var combatSpecs = new List(10); + + for (int i = 0; i < 12; i++) + { + contenders.Add(new NetContenderState + { + SlotId = (byte)i, + Alive = true, + IsHuman = true, + Pos = new Vector3(i * 8f, 3f, 0f), + Rot = Quaternion.Identity, + CoreHpRatio = 1f + }); + var ws = new WalkerVisualSnapshot { LegCount = 4 }; + for (int l = 0; l < 4; l++) ws.FootNormal[l] = Vector3.UnitY; + walkers.Add(new NetWalkerEntry { IsContender = true, EntityId = (byte)i, Snapshot = ws }); + } + for (int i = 0; i < 10; i++) + { + combatSpecs.Add(new NetSpectatorState + { + Id = (byte)i, + Alive = true, + Stance = SpectatorStance.Provoked, + TargetContenderId = 0, + Pos = new Vector3(40f + i * 4f, 3f, -20f), + Rot = Quaternion.Identity + }); + } + + byte[] p1 = SnapshotCodec.EncodeCorePvs( + 1, 7, 14, 0.25f, 5, 100, 450f, MatchPhase.Active, null, 1, 0xFFF, + local, Vector3.Zero, contenders, walkers, combatSpecs, out int writtenInP1); + byte[] w1 = SnapshotCodec.WrapLatest(p1, 1, 1); + + var packet2List = new List(); + for (int i = writtenInP1; i < combatSpecs.Count; i++) packet2List.Add(combatSpecs[i]); + for (int i = 0; i < 20; i++) + { + packet2List.Add(new NetSpectatorState + { + Id = (byte)(20 + i), + Alive = true, + Stance = SpectatorStance.Neutral, + TargetContenderId = -1, + Pos = new Vector3(200f, 3f, 200f), + Rot = Quaternion.Identity + }); + } + byte[] p2 = SnapshotCodec.EncodeSpectatorOrbitHalf(1, 7, 0, packet2List); + byte[] w2 = SnapshotCodec.WrapLatest(p2, 1, 2); + + Assert.True(w1.Length <= SnapshotCodec.MaxLatestFrameBytes); + Assert.True(w2.Length <= SnapshotCodec.MaxLatestFrameBytes); + Assert.True(EncodeRudpLatestDatagram(w1, 1).Length <= SnapshotCodec.MaxLatestDatagramBytes); + Assert.True(EncodeRudpLatestDatagram(w2, 2).Length <= SnapshotCodec.MaxLatestDatagramBytes); + + var dec1 = SnapshotCodec.DecodeCorePvs(SnapshotCodec.Unwrap(w1).Payload.Span); + var dec2 = SnapshotCodec.DecodeSpectatorOrbitHalf(SnapshotCodec.Unwrap(w2).Payload.Span); + var deliveredCombatIds = dec1.CombatSpectators.Select(s => s.Id) + .Concat(dec2.Spectators.Where(s => s.Stance != SpectatorStance.Neutral).Select(s => s.Id)) + .OrderBy(id => id) + .ToList(); + Assert.Equal(Enumerable.Range(0, 10).Select(i => (byte)i).ToList(), deliveredCombatIds); + + // b) Malformed 120B packet with cellCount=200 must return false cleanly without throwing! + byte[] bad = new byte[120]; + bad[0] = (byte)LatestPacketKind.CorePvs; + bad[91] = 200; // cellCount = 200 > 64 and > remaining bytes + Assert.False(SnapshotCodec.TryDecodeCorePvs(bad, out _)); + bad[0] = (byte)LatestPacketKind.SpectatorOrbitHalf; + bad[10] = 250; + Assert.False(SnapshotCodec.TryDecodeSpectatorOrbitHalf(bad, out _)); + bad[0] = (byte)LatestPacketKind.RadarContacts; + bad[9] = 250; + Assert.False(SnapshotCodec.TryDecodeRadarContacts(bad, out _)); + } + + [Fact] + public void Cut5cFix5_TimedOutClientDisconnectsCleanly_AndDeadSlotReconnectIsRejected() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var client = new RemoteArenaSession(ep, "Ghost"); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + Assert.True(PumpUntil(host, new[] { client }, () => client.IsJoined, ref nowMs, 3000)); + int slot = client.LocalContenderId; + Guid token = client.ReconnectToken; + Assert.True(client.ConnectionStatus.Connected); + + // a) Simulate > 6000ms server silence -> client MUST transition to Disconnected (not stuck Connected)! + client.PumpNetwork(nowMs + 7000); + Assert.False(client.ConnectionStatus.Connected); + Assert.False(client.IsJoined); + Assert.Contains("DISCONNECTED", client.ConnectionStatus.StateLabel, StringComparison.OrdinalIgnoreCase); + + // Server also times out client & destroys that slot's chassis + nowMs += ServerMatchHost.IdleTimeoutMs + 500; + host.StepOnce(nowMs); + var deadContender = host.Session.State.Contenders[slot]; + deadContender.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, 0f, deadContender.Grid.HitSequence + 1); + Assert.False(deadContender.Alive); + + // b) Reconnecting with dead-slot ReconnectToken MUST be rejected cleanly instead of hijacking another AI slot! + using var deadReconnect = new RemoteArenaSession(ep, "Ghost", token); + Assert.False(PumpUntil(host, new[] { deadReconnect }, () => deadReconnect.IsJoined, ref nowMs, 800)); + Assert.NotNull(deadReconnect.ConnectionStatus.LastError); + Assert.Contains("destroyed", deadReconnect.ConnectionStatus.LastError!, StringComparison.OrdinalIgnoreCase); + Assert.Equal(0, host.ConnectedHumanCount); + } + + [Fact] + public void Cut5cFix6_Dense12QuadWalkersAndExemplar_OmitsSelfWalkerAndDeliversExemplar() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var client = new RemoteArenaSession(ep, "QuadLead"); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + Assert.True(PumpUntil(host, new[] { client }, () => client.IsJoined, ref nowMs, 3000)); + int slot = client.LocalContenderId; + + // Place all 12 contenders as Bastion quad walkers in a tight open cluster around the Exemplar + var exemplar = host.Session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar && s.Alive); + exemplar.Stance = SpectatorStance.Provoked; + exemplar.TargetContenderId = slot; + + for (int i = 0; i < MatchState.ContenderCount; i++) + { + host.Session.State.Contenders[i].Grid.SwapChassis(Catalog.Bastion); + float angle = i * (MathF.PI * 2f / MatchState.ContenderCount); + float dist = i == slot ? 12f : 28f + i * 2f; + host.Session.SetContenderPose(i, exemplar.X + MathF.Cos(angle) * dist, exemplar.Z + MathF.Sin(angle) * dist, angle + MathF.PI); + } + + DecodedCorePvsSnapshot? lastCore = null; + int maxUdpBytes = 0; + client.DebugInboundLatestDropFilter = payload => + { + if (SnapshotCodec.TryDecodeCorePvs(payload, out var core)) + { + lastCore = core; + byte[] frame = SnapshotCodec.WrapLatest(payload, 1, core.SnapshotSeq); + maxUdpBytes = Math.Max(maxUdpBytes, EncodeRudpLatestDatagram(frame, core.SnapshotSeq).Length); + } + return false; + }; + + for (int t = 0; t < 20; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + client.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + + byte exemplarIdx = (byte)host.Session.State.Spectators.Spectators.Select((s, idx) => (s, idx)).First(x => ReferenceEquals(x.s, exemplar)).idx; + Assert.NotNull(lastCore); + _output.WriteLine($"Cut5cFix6: maxUdpBytes={maxUdpBytes}B, walkers=[{string.Join(",", lastCore!.Walkers.Select(w => $"{(w.IsContender ? 'C' : 'S')}{w.EntityId}"))}]"); + Assert.True(maxUdpBytes > 0 && maxUdpBytes <= SnapshotCodec.MaxLatestDatagramBytes, + $"Packet 1 UDP datagram must be <= {SnapshotCodec.MaxLatestDatagramBytes}B, got {maxUdpBytes}B"); + Assert.DoesNotContain(lastCore.Walkers, w => w.IsContender && w.EntityId == slot); + Assert.Contains(lastCore.Walkers, w => !w.IsContender && w.EntityId == exemplarIdx); + Assert.True(client.TrySampleInterpolatedWalkerPose(false, exemplar.Id, 1f, out _), + "Client must receive Exemplar walker snapshot even under dense 12 quad-walker contention"); + } + + [Fact] + public void Cut13a_OutOfPvsHistoricalCratersSyncViaPersistentScars_AndLiveCratersEnterWithin576mBubble() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + const float histX = 700f; + const float histZ = 700f; + float baseHistH = host.Session.State.Terrain.SampleHeight(histX, histZ); + + // 1. Historical out-of-PVS crater stamped before Client A joins + ((IOrdnanceTargetSink)host.Session).StampTerrainImpact(histX, histZ, craterRadius: 6f, craterDepth: 2.0f, scorchRadius: 7f); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + host.StepOnce(nowMs += 16); + float scarredHistH = host.Session.State.Terrain.SampleHeight(histX, histZ); + Assert.True(scarredHistH < baseHistH - 1.2f); + + using var clientA = new RemoteArenaSession(ep, "Scout"); + Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000)); + + // Out-of-PVS historical crater must be present immediately via PersistentScars + Assert.Equal(scarredHistH, clientA.ViewState.Terrain.SampleHeight(histX, histZ), precision: 3); + Assert.InRange(clientA.PredTileSync.ResidentTileCount, 1, 9); + + // 2. Live crater stamped far outside 576m bubble (-700, 100 vs open-sky ~700, 100 = ~1400m apart) + int slotA = clientA.LocalContenderId; + var sion = host.Session.State.SionMap!; + float liveX = 700f, liveZ = 100f; + for (float x = 640f; x <= 760f; x += 8f) + { + if (!sion.IsInsideAnyBuildingXz(x, liveZ, padding: 10f)) + { + liveX = x; + break; + } + } + float baseLiveH = host.Session.State.Terrain.SampleHeight(liveX, liveZ); + + host.Session.SetContenderPose(slotA, -700f, liveZ, 0f); + host.StepOnce(nowMs += 16); + ((IOrdnanceTargetSink)host.Session).StampTerrainImpact(liveX, liveZ, craterRadius: 6f, craterDepth: 2.0f, scorchRadius: 7f); + for (int t = 0; t < 10; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + clientA.PumpNetwork(); + Thread.Sleep(1); + } + float hostLiveH = host.Session.State.Terrain.SampleHeight(liveX, liveZ); + Assert.True(hostLiveH < baseLiveH - 1.2f); + Assert.Equal(baseLiveH, clientA.ViewState.Terrain.SampleHeight(liveX, liveZ), precision: 3); + + // 3. Client A enters 576m local geometry bubble (liveX - 450m -> dist = 450m <= 576m) + host.Session.SetContenderPose(slotA, liveX - 450f, liveZ, 0f); + Assert.True(PumpUntil( + host, + new[] { clientA }, + () => MathF.Abs(clientA.ViewState.Terrain.SampleHeight(liveX, liveZ) - hostLiveH) < 0.05f, + ref nowMs, + 3000), + "Client must receive live TerrainStampEvent upon entering 576m bubble before reaching _predWorld 3x3 window"); + + // 4. Client A steps into (liveX, liveZ) tile -> _predWorld 3x3 window matches server Box3D crater depth 1:1 + host.Session.SetContenderPose(slotA, liveX - 20f, liveZ, 0f); + for (int t = 0; t < 10; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + clientA.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + Assert.InRange(clientA.PredTileSync.ResidentTileCount, 1, 9); + float rayStartY = sion.Metadata.MaxY + 25f; + float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f); + var hostHit = host.Session.CastWorldRayClosest(new Vector3(liveX, rayStartY, liveZ), new Vector3(0f, raySpanY, 0f)); + var predHit = clientA.CastWorldRayClosest(new Vector3(liveX, rayStartY, liveZ), new Vector3(0f, raySpanY, 0f)); + Assert.True(hostHit.Hit && predHit.Hit); + Assert.True(MathF.Abs(hostHit.Point.Y - predHit.Point.Y) < 0.05f, + $"Expected _predWorld crater impact Y ({predHit.Point.Y:F3}m) to match server ({hostHit.Point.Y:F3}m)"); + } + + [Fact] + public void Cut13a_OverlappingCraters_CoalesceIdenticallyAcrossLiveHostJoinerAndPostReset() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + const float cx = -120f; + const float cz = 180f; + + // Stamp 3 overlapping craters within < 0.75m (coalesce radius) + ((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx, cz, craterRadius: 4.0f, craterDepth: 1.1f, scorchRadius: 4.5f); + ((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx + 0.30f, cz - 0.20f, craterRadius: 5.8f, craterDepth: 2.2f, scorchRadius: 6.0f); + ((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx - 0.15f, cz + 0.25f, craterRadius: 3.0f, craterDepth: 0.7f, scorchRadius: 3.5f); + + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + host.StepOnce(nowMs += 16); + + float liveHostH = host.Session.State.Terrain.SampleHeight(cx, cz); + float liveHostEdgeH = host.Session.State.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f); + + using var clientA = new RemoteArenaSession(ep, "Joiner"); + Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000)); + + float clientJoinH = clientA.ViewState.Terrain.SampleHeight(cx, cz); + float clientJoinEdgeH = clientA.ViewState.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f); + Assert.True(MathF.Abs(liveHostH - clientJoinH) < 0.001f, + $"Expected liveHostH ({liveHostH:F4}) == clientJoinH ({clientJoinH:F4}) within 0.001m"); + Assert.True(MathF.Abs(liveHostEdgeH - clientJoinEdgeH) < 0.001f, + $"Expected liveHostEdgeH ({liveHostEdgeH:F4}) == clientJoinEdgeH ({clientJoinEdgeH:F4}) within 0.001m"); + + host.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false); + float postResetHostH = host.Session.State.Terrain.SampleHeight(cx, cz); + float postResetHostEdgeH = host.Session.State.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f); + Assert.True(MathF.Abs(liveHostH - postResetHostH) < 0.001f, + $"Expected liveHostH ({liveHostH:F4}) == postResetHostH ({postResetHostH:F4}) within 0.001m"); + Assert.True(MathF.Abs(liveHostEdgeH - postResetHostEdgeH) < 0.001f, + $"Expected liveHostEdgeH ({liveHostEdgeH:F4}) == postResetHostEdgeH ({postResetHostEdgeH:F4}) within 0.001m"); + } + + [Fact] + public void RemoteArenaSession_AppliesRemoteContenderCoreHpRatioOnPvsSnapshot() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var client = new RemoteArenaSession(ep, "HpProbe"); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + Assert.True(PumpUntil(host, new[] { client }, () => client.IsJoined, ref nowMs, 3000)); + int localSlot = client.LocalContenderId; + int rivalSlot = localSlot == 0 ? 1 : 0; + + var serverLocal = host.Session.State.Contenders[localSlot]; + var serverRival = host.Session.State.Contenders[rivalSlot]; + host.Session.SetContenderPose(localSlot, 0f, 0f, 0f); + host.Session.SetContenderPose(rivalSlot, 0f, 40f, MathF.PI); + + float targetHp = serverRival.Grid.MaxCoreHp * 0.42f; + serverRival.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, targetHp, serverRival.Grid.HitSequence + 1); + float expectedRatio = serverRival.Grid.CoreHp / serverRival.Grid.MaxCoreHp; + + bool synced = PumpUntil(host, new[] { client }, () => + { + if (!client.IsContenderVisible(rivalSlot)) return false; + var c = client.ViewState.Contenders[rivalSlot]; + float r = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 1f; + return MathF.Abs(r - expectedRatio) < 0.02f; + }, ref nowMs, 2500); + + var clientRival = client.ViewState.Contenders[rivalSlot]; + float actualRatio = clientRival.Grid.MaxCoreHp > 0f ? clientRival.Grid.CoreHp / clientRival.Grid.MaxCoreHp : 1f; + Assert.True(synced, $"Expected remote contender {rivalSlot} CoreHpRatio ~ {expectedRatio:F3}, got {actualRatio:F3}"); + + // Edge case: living rival at 0.30 HP rounds 8-bit CoreHpRatio to 0, yet must remain Alive on remote client + serverRival.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, 0.30f, serverRival.Grid.HitSequence + 1); + Assert.True(serverRival.Alive); + bool lowHpSynced = PumpUntil(host, new[] { client }, () => + { + var c = client.ViewState.Contenders[rivalSlot]; + return c.Alive && c.Grid.CoreHp > 0f && c.Grid.CoreHp <= 0.5f; + }, ref nowMs, 2500); + Assert.True(lowHpSynced && clientRival.Alive && !clientRival.Grid.IsDestroyed && clientRival.Grid.CoreHp > 0f, + $"Expected living 0.30 HP rival to stay Alive on remote client, got Alive={clientRival.Alive}, CoreHp={clientRival.Grid.CoreHp:F3}"); + } + + private static byte[] EncodeRudpLatestDatagram(byte[] frameBytes, uint sequence) => + CultNetRudpPacketCodec.Encode(new CultNetRudpPacket + { + PacketType = CultNetRudpPacketType.Data, + ConnectionId = 0x52544431, + Sequence = sequence, + ChannelId = SnapshotCodec.ChannelLatest, + Sequenced = true, + Payload = frameBytes + }); + + private static bool PumpUntil( + ServerMatchHost host, + RemoteArenaSession[] clients, + Func condition, + ref long nowMs, + int timeoutMs) + { + var deadline = DateTimeOffset.UtcNow.AddMilliseconds(timeoutMs); + while (DateTimeOffset.UtcNow < deadline) + { + nowMs += 16; + host.StepOnce(nowMs); + for (int i = 0; i < clients.Length; i++) + { + clients[i].PumpNetwork(); + } + if (condition()) return true; + Thread.Sleep(2); + } + return condition(); + } + } +} diff --git a/tests/RustToDust.Tests/DetectionLosTests.cs b/tests/RustToDust.Tests/DetectionLosTests.cs new file mode 100644 index 0000000..d56296e --- /dev/null +++ b/tests/RustToDust.Tests/DetectionLosTests.cs @@ -0,0 +1,613 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class DetectionLosTests + { + private static TerrainBrush FindTallMesa(TerrainField terrain) + { + for (int i = 0; i < terrain.Brushes.Count; i++) + { + var b = terrain.Brushes[i]; + if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f) + { + return b; + } + } + throw new InvalidOperationException("Expected at least one tall Mesa in generated terrain."); + } + + [Fact] + public void MesaBetweenSpectatorAndContender_BlocksLosAndPreventsFiringThroughTerrain() + { + using var session = new ArenaSession(seed: 42, slot0Human: true); + var mesa = FindTallMesa(session.State.Terrain); + var player = session.State.Contenders[0]; + var spec = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Patron); + + // Place player and spectator on opposite sides of the tall mesa + float playerX = mesa.X - mesa.RadiusX - 18f; + float specX = mesa.X + mesa.RadiusX + 18f; + session.SetContenderPose(player.Id, playerX, mesa.Z); + session.SetSpectatorPose(spec.Id, specX, mesa.Z); + + // Provoke this spectator onto the player so it actively hunts, while terrain blocks sightline + session.State.Spectators.OnSpectatorDamaged(spec, player.Id); + float initialCoreHp = player.Grid.CoreHp; + + for (int tick = 0; tick < 10; tick++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + + Assert.False(session.HasLineOfSight( + spec.X, MatchRules.GetObserverEyeY(spec.Y, spec.Grid.Spec.HalfHeight), spec.Z, + player.X, MatchRules.GetTargetAimY(player.Y, player.Grid.Spec.HalfHeight), player.Z)); + Assert.False(spec.HasTargetLos); + + MatchRules.ComputeSpectatorBehavior(spec, session.State, out _, out _, out _, out _, out bool shouldFire); + Assert.False(shouldFire, "Occluded spectator must NOT fire through a mesa"); + } + + Assert.Equal(initialCoreHp, player.Grid.CoreHp); + } + + [Fact] + public void CrestingRidge_RestoresLosAndAllowsSpectatorEngagement() + { + using var session = new ArenaSession(seed: 42, slot0Human: true); + var mesa = FindTallMesa(session.State.Terrain); + var player = session.State.Contenders[0]; + var spec = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Patron); + + // Start occluded across the mesa + session.SetContenderPose(player.Id, mesa.X - mesa.RadiusX - 18f, mesa.Z); + session.SetSpectatorPose(spec.Id, mesa.X + mesa.RadiusX + 18f, mesa.Z); + session.State.Spectators.OnSpectatorDamaged(spec, player.Id); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + Assert.False(spec.HasTargetLos); + + // Now player crests onto the high mesa plateau overlooking the spectator + session.SetContenderPose(player.Id, mesa.X + mesa.RadiusX * 0.25f, mesa.Z); + session.SetSpectatorPose(spec.Id, mesa.X + mesa.RadiusX + 18f, mesa.Z); + + bool sawTracer = false; + for (int tick = 0; tick < 30; tick++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + if (session.State.Tracers.Count > 0) + { + sawTracer = true; + } + } + + Assert.True(spec.HasTargetLos, "Cresting the mesa must restore spectator LOS"); + MatchRules.ComputeSpectatorBehavior(spec, session.State, out _, out _, out _, out _, out bool shouldFire); + Assert.True(shouldFire, "Spectator with restored LOS within range should be cleared to fire"); + Assert.True(sawTracer, "Expected spectator to fire weapons once LOS was restored"); + } + + [Fact] + public void LowSignatureExemplar_HiddenBehindRidge_IsInvisibleOnRadar_WhileInLosContactIsVisible() + { + using var session = new ArenaSession(seed: 42, slot0Human: true); + var mesa = FindTallMesa(session.State.Terrain); + var player = session.State.Contenders[0]; + var exemplar = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar); + var visibleRival = session.State.Contenders[1]; + + Assert.True(exemplar.RadarSignature <= 0.25f); + + // Reset memory so exemplar has never been seen yet, then hide it on the far side of the mesa + var obs0 = session.State.GetOrCreateObserverState(0); + obs0.SpectatorContacts[exemplar.Id] = new PlayerContactMemory(); + session.SetContenderPose(player.Id, mesa.X - mesa.RadiusX - 18f, mesa.Z); + session.SetSpectatorPose(exemplar.Id, mesa.X + mesa.RadiusX + 18f, mesa.Z); + + // Place rival contender nearby in clear open LOS on the player's side of the mesa + session.SetContenderPose(visibleRival.Id, mesa.X - mesa.RadiusX - 50f, mesa.Z + 12f); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + + var exMem = obs0.SpectatorContacts[exemplar.Id]; + Assert.False(exMem.VisibleToPlayer); + Assert.False(exMem.FaintHorizonPing); + Assert.False(MatchState.IsContactOnRadar(exMem), "Hidden low-signature Exemplar must vanish off player radar"); + + var rivalMem = obs0.ContenderContacts[visibleRival.Id]; + Assert.True(rivalMem.VisibleToPlayer, "In-LOS contact must be live-visible to player"); + Assert.True(MatchState.IsContactOnRadar(rivalMem)); + } + + [Fact] + public void StaticCoverWall_BlocksLineOfSight() + { + using var session = new ArenaSession(seed: 12, slot0Human: true); + var box = session.State.ArenaCoverBoxes[0]; + var player = session.State.Contenders[0]; + var rival = session.State.Contenders[1]; + + // Ensure rival is a low-profile ground vehicle shorter than the 4m ruin cover wall + if (rival.Grid.Spec.IsVtol || rival.Grid.Spec.HalfHeight * 2f >= box.HalfY * 2f) + { + session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 4f); + session.State.SpawnChassisDrop(box.X, box.Z + box.HalfZ + 4f, Catalog.Jackal); + Assert.True(session.State.TrySwapNearbyChassis(rival.Id)); + } + + session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 4f); + session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 4f); + + bool los = session.HasLineOfSight( + player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z, + rival.X, MatchRules.GetTargetAimY(rival.Y, rival.Grid.Spec.HalfHeight), rival.Z); + + Assert.False(los, "Static cover ruin wall between two vehicles must block HasLineOfSight"); + } + + [Fact] + public void NeutralTierPositioning_PatronsClaimHigherGroundThanTouristsAndExemplars_AndHoldSpots() + { + var state = new MatchState(seed: 42); + var ring = state.Spectators; + + var touristHeights = new List(); + var patronHeights = new List(); + var exemplarHeights = new List(); + var initialGoals = new Dictionary(); + + for (int i = 0; i < ring.Spectators.Count; i++) + { + var s = ring.Spectators[i]; + var (gx, gz) = ring.GetNeutralGoal(s, state.Terrain, state.ArenaCoverBoxes); + initialGoals[s.Id] = (gx, gz); + float h = state.Terrain.SampleHeight(gx, gz); + + switch (s.Tier) + { + case SpectatorTier.Tourist: touristHeights.Add(h); break; + case SpectatorTier.Patron: patronHeights.Add(h); break; + case SpectatorTier.Exemplar: exemplarHeights.Add(h); break; + } + } + + float avgPatronH = patronHeights.Average(); + float avgTouristH = touristHeights.Average(); + float avgExemplarH = exemplarHeights.Average(); + + Assert.True(avgPatronH > avgTouristH + 1.0f, + $"Expected Patrons ({avgPatronH:F2}m) to claim higher ground than Tourists ({avgTouristH:F2}m)"); + Assert.True(avgPatronH > avgExemplarH + 1.0f, + $"Expected Patrons ({avgPatronH:F2}m) to claim higher ground than Exemplars ({avgExemplarH:F2}m)"); + + // Advance perimeter orbits while SafeRadius is within grace period: Tourists orbit, Patrons & Exemplars hold! + ring.AdvancePerimeterOrbits(15f); + + for (int i = 0; i < ring.Spectators.Count; i++) + { + var s = ring.Spectators[i]; + var (gx, gz) = ring.GetNeutralGoal(s, state.Terrain, state.ArenaCoverBoxes); + var prev = initialGoals[s.Id]; + float moved = MathF.Sqrt((gx - prev.X) * (gx - prev.X) + (gz - prev.Z) * (gz - prev.Z)); + + if (s.Tier == SpectatorTier.Tourist) + { + Assert.True(moved > 10f, "Expected Neutral Tourists to continue orbiting perimeter"); + } + else + { + Assert.True(moved < 0.01f, $"Expected Neutral {s.Tier} to hold chosen vantage/ambush spot, moved {moved:F2}m"); + } + } + } + + [Fact] + public void OccludedSpectators_DoNotLeakLiveTargetAfterMemoryExpires_FiveSeconds() + { + using var session = new ArenaSession(seed: 42, slot0Human: true); + // Shrink safe circle so the tall mesa perimeter is outside SafeRadius + session.State.Time = 360f; + session.State.Spectators.UpdateSafeRadius(session.State.Time); + + TerrainBrush mesa = default; + float bestMinRadius = -1f; + for (int i = 0; i < session.State.Terrain.Brushes.Count; i++) + { + var b = session.State.Terrain.Brushes[i]; + if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f) + { + float minR = MathF.Min(b.RadiusX, b.RadiusZ); + if (minR > bestMinRadius) + { + bestMinRadius = minR; + mesa = b; + } + } + } + Assert.True(bestMinRadius > 0f, "Expected at least one tall Mesa in generated terrain."); + + var player = session.State.Contenders[0]; + var tourists = session.State.Spectators.Spectators.Where(s => s.Tier == SpectatorTier.Tourist).ToList(); + var provokedSpec = tourists[0]; + var clearedSpec = tourists[1]; + + // Place player on the side of the mesa further from center (strictly outside SafeRadius) + float xNeg = mesa.X - mesa.RadiusX - 18f; + float xPos = mesa.X + mesa.RadiusX + 18f; + bool negIsFurther = (xNeg * xNeg + mesa.Z * mesa.Z) >= (xPos * xPos + mesa.Z * mesa.Z); + float occludedX = negIsFurther ? xNeg : xPos; + float specSideX = negIsFurther ? (mesa.X + mesa.RadiusX + 45f) : (mesa.X - mesa.RadiusX - 45f); + + // Keep AI contenders safely inside the safe circle and other spectators behind the mesa shadow so they don't peek around the flank + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(session.State.Contenders[i].Id, (i - 6) * 12f, 0f); + } + for (int i = 0; i < session.State.Spectators.Spectators.Count; i++) + { + var other = session.State.Spectators.Spectators[i]; + if (other.Id != provokedSpec.Id && other.Id != clearedSpec.Id) + { + // Space bystanders in a non-overlapping grid at the far corner so Box3D never stacks them into a tower peeking over the mesa + float signX = mesa.X >= 0f ? -1f : 1f; + float signZ = mesa.Z >= 0f ? -1f : 1f; + float farX = signX * (730f - (i % 8) * 16f); + float farZ = signZ * (730f - (i / 8) * 16f); + session.SetSpectatorPose(other.Id, farX, farZ); + } + } + + // Briefly establish visual contact for provokedSpec at initial spot, then move player behind the mesa + session.SetContenderPose(player.Id, specSideX - (negIsFurther ? 12f : -12f), mesa.Z); + session.SetSpectatorPose(provokedSpec.Id, specSideX, mesa.Z); + session.State.Spectators.OnSpectatorDamaged(provokedSpec, player.Id); + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + Assert.True(provokedSpec.HasTargetLos, "Expected initial LOS before player drops behind cover"); + + float provokedKnownX = provokedSpec.LastKnownTargetX; + float provokedKnownZ = provokedSpec.LastKnownTargetZ; + + // Now hide player behind the mesa and place clearedSpec on the opposite side closest to the breach + session.SetContenderPose(player.Id, occludedX, mesa.Z - 14f); + session.SetSpectatorPose(provokedSpec.Id, specSideX, mesa.Z - 4f); + session.SetSpectatorPose(clearedSpec.Id, specSideX, mesa.Z + 4f); + + // Verify clearedSpec gets Pass-2 Cleared assignment without LOS + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + Assert.False(provokedSpec.HasTargetLos); + Assert.Equal(SpectatorStance.Cleared, clearedSpec.Stance); + Assert.False(clearedSpec.HasTargetLos); + + float clearedInitialKnownX = clearedSpec.LastKnownTargetX; + float clearedInitialKnownZ = clearedSpec.LastKnownTargetZ; + + // Run 300 ticks (5.0s > 4.0s TargetMemoryDuration) while player moves laterally behind cover + for (int tick = 0; tick < 300; tick++) + { + float latZ = mesa.Z - 14f + (tick / 299f) * 28f; + if (tick % 10 == 0) + { + session.SetContenderPose(player.Id, occludedX, latZ); + } + + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + + Assert.False(provokedSpec.HasTargetLos, $"Provoked spectator regained unexpected LOS at tick {tick}"); + Assert.False(clearedSpec.HasTargetLos, $"Cleared spectator regained unexpected LOS at tick {tick}"); + + if (tick == 270) // 4.5s > 4.0s memory window + { + Assert.True(provokedSpec.TimeSinceLastSeen >= 4.5f, + $"Provoked TimeSinceLastSeen reset unexpectedly: {provokedSpec.TimeSinceLastSeen:F2}s"); + Assert.True(clearedSpec.TimeSinceLastSeen >= 4.5f, + $"Cleared TimeSinceLastSeen reset unexpectedly: {clearedSpec.TimeSinceLastSeen:F2}s"); + } + } + + // Neither spectator's LastKnownTarget or aim vector may track the player's new occluded position + float provokedDistToPlayer = MathF.Sqrt( + (provokedSpec.LastKnownTargetX - player.X) * (provokedSpec.LastKnownTargetX - player.X) + + (provokedSpec.LastKnownTargetZ - player.Z) * (provokedSpec.LastKnownTargetZ - player.Z)); + Assert.Equal(provokedKnownX, provokedSpec.LastKnownTargetX, precision: 3); + Assert.Equal(provokedKnownZ, provokedSpec.LastKnownTargetZ, precision: 3); + Assert.True(provokedDistToPlayer > 25f, + $"Provoked LastKnownTarget leaked live player position (dist={provokedDistToPlayer:F2}m)"); + + float clearedDistToPlayer = MathF.Sqrt( + (clearedSpec.LastKnownTargetX - player.X) * (clearedSpec.LastKnownTargetX - player.X) + + (clearedSpec.LastKnownTargetZ - player.Z) * (clearedSpec.LastKnownTargetZ - player.Z)); + Assert.Equal(clearedInitialKnownX, clearedSpec.LastKnownTargetX, precision: 3); + Assert.Equal(clearedInitialKnownZ, clearedSpec.LastKnownTargetZ, precision: 3); + Assert.True(clearedDistToPlayer > 20f, + $"Cleared LastKnownTarget leaked live player position (dist={clearedDistToPlayer:F2}m)"); + + MatchRules.ComputeSpectatorBehavior(provokedSpec, session.State, out _, out _, out float pAimX, out float pAimZ, out bool pFire); + Assert.False(pFire); + Assert.Equal(provokedKnownX, pAimX, precision: 3); + Assert.Equal(provokedKnownZ, pAimZ, precision: 3); + + MatchRules.ComputeSpectatorBehavior(clearedSpec, session.State, out _, out _, out float cAimX, out float cAimZ, out bool cFire); + Assert.False(cFire); + Assert.Equal(clearedInitialKnownX, cAimX, precision: 3); + Assert.Equal(clearedInitialKnownZ, cAimZ, precision: 3); + } + + [Fact] + public void Probe2_OccludedLateralArc_FullRingDoesNotLeakOrTrackPlayerPosition() + { + var ring = new SpectatorRing(seed: 42); + Assert.Equal(56, ring.Spectators.Count); + const float dt = 1f / 60f; + + // Phase 1 (10 ticks): Player pops out of safe circle briefly at 0 degrees with LOS to nearby 0-deg watchers. + float startR = ring.SafeRadius + 15f; + for (int tick = 0; tick < 10; tick++) + { + var contact = new RingContact(0, startR, 0f, true); + ring.UpdateClearance(new[] { contact }, dt, (spec, _) => + { + float specAng = MathF.Atan2(spec.Z, spec.X); + return MathF.Abs(specAng) < 0.45f; + }); + } + + int initialCleared = ring.CountClearedFor(0); + Assert.True(initialCleared >= 1, "Expected at least one Cleared spectator at 0 degrees during initial pop-out"); + Assert.Contains(ring.Spectators, s => s.Stance == SpectatorStance.Cleared && s.HasTargetLos); + + // Phase 2 (600 ticks = 10s): 100% occlusion while player moves laterally 0 -> 80 deg and steps further out. + float playerX = startR; + float playerZ = 0f; + float maxArcRad = 80f * (MathF.PI / 180f); + + for (int tick = 0; tick < 600; tick++) + { + float t = tick / 599f; + float angle = t * maxArcRad; + float r = ring.SafeRadius + 15f + t * 70f; + playerX = MathF.Cos(angle) * r; + playerZ = MathF.Sin(angle) * r; + + var contact = new RingContact(0, playerX, playerZ, true); + ring.UpdateClearance(new[] { contact }, dt, static (_, _) => false); + + foreach (var s in ring.Spectators) + { + Assert.False(s.HasTargetLos, $"No spectator may have LOS during occluded arc (tick {tick}, spec {s.Id})"); + if (s.Stance == SpectatorStance.Cleared) + { + float targetAngle = MathF.Atan2(s.LastKnownTargetZ, s.LastKnownTargetX); + Assert.True(MathF.Abs(targetAngle) < 0.35f, + $"Cleared spectator {s.Id} leaked lateral angle {targetAngle * 180f / MathF.PI:F1} deg at tick {tick}"); + } + } + } + + // At end of 80-deg hidden move, no spectator has LastKnownTarget near the player's hidden position, + // and spectators stationed along 35..90 degrees remain Neutral. + foreach (var s in ring.Spectators) + { + if (s.Stance == SpectatorStance.Cleared) + { + float dx = s.LastKnownTargetX - playerX; + float dz = s.LastKnownTargetZ - playerZ; + float distToHiddenPlayer = MathF.Sqrt(dx * dx + dz * dz); + Assert.True(distToHiddenPlayer > 400f, + $"Cleared spectator {s.Id} LastKnownTarget ({s.LastKnownTargetX:F1}, {s.LastKnownTargetZ:F1}) too close to hidden player ({distToHiddenPlayer:F1}m)"); + } + + float specAngleDeg = MathF.Atan2(s.Z, s.X) * (180f / MathF.PI); + if (specAngleDeg >= 35f && specAngleDeg <= 95f) + { + Assert.Equal(SpectatorStance.Neutral, s.Stance); + } + } + } + + [Fact] + public void OnSpectatorDamaged_WithoutLos_SeedsIncomingDirectionInsteadOfStaleTarget() + { + var ring = new SpectatorRing(seed: 77); + var spec = ring.Spectators[0]; + spec.LastKnownTargetX = 0f; + spec.LastKnownTargetZ = 0f; + + bool provoked = ring.OnSpectatorDamaged(spec, attackerContenderId: 0, incomingDirX: 0f, incomingDirZ: 1f); + Assert.True(provoked); + Assert.Equal(SpectatorStance.Provoked, spec.Stance); + Assert.False(spec.HasTargetLos); + Assert.True(spec.LastKnownTargetZ > spec.Z + 10f, + $"Expected LastKnownTarget to point along incoming +Z direction, got Z={spec.LastKnownTargetZ:F1} vs spec.Z={spec.Z:F1}"); + } + + [Fact] + public void AiContender_ImmediatelyDropsTrackingAndFiring_OnExactTickLosBreaks() + { + using var session = new ArenaSession(seed: 12, slot0Human: true); + var box = session.State.ArenaCoverBoxes[0]; + var player = session.State.Contenders[0]; + var ai = session.State.Contenders[1]; + + // Move other rivals far away so only ai <-> player interaction is isolated + for (int i = 2; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(session.State.Contenders[i].Id, -680f + i * 8f, -680f); + } + + // Ensure both player and AI are low-profile ground vehicles shorter than the cover wall + if (player.Grid.Spec.IsVtol || player.Grid.Spec.HalfHeight * 2f >= box.HalfY * 2f) + { + session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 8f); + session.State.SpawnChassisDrop(box.X, box.Z - box.HalfZ - 8f, Catalog.Jackal); + Assert.True(session.State.TrySwapNearbyChassis(player.Id)); + } + if (ai.Grid.Spec.IsVtol || ai.Grid.Spec.HalfHeight * 2f >= box.HalfY * 2f) + { + session.SetContenderPose(ai.Id, box.X + 8f, box.Z - box.HalfZ - 8f); + session.State.SpawnChassisDrop(box.X + 8f, box.Z - box.HalfZ - 8f, Catalog.Jackal); + Assert.True(session.State.TrySwapNearbyChassis(ai.Id)); + } + + // Test breaking LOS across multiple step-tick phases (would catch any % 3 stagger!) + for (int phase = 0; phase < 3; phase++) + { + // Place both on the same open side of the cover box within firing range (< 165m), AI facing player + float openAiX = box.X; + float openAiZ = box.Z - box.HalfZ - 14f; + float openPlayerX = box.X + 18f; + float openPlayerZ = box.Z - box.HalfZ - 14f; + float facePlayerYaw = MathF.Atan2(openPlayerX - openAiX, openPlayerZ - openAiZ); + session.SetContenderPose(ai.Id, openAiX, openAiZ, yaw: facePlayerYaw); + session.SetContenderPose(player.Id, openPlayerX, openPlayerZ, yaw: 0f); + + // Advance `phase` ticks in open LOS; open-LOS acquisition must be immediate on tick 0! + for (int t = 0; t <= phase; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + Assert.Equal(player.Id, ai.AiTargetContenderId); + Assert.True(ai.FireCmd, $"Expected AI to acquire open-LOS target and fire immediately (phase={phase}, t={t})"); + } + + // Now break LOS behind the static cover wall while staying within weapon range + session.SetContenderPose(ai.Id, box.X, box.Z - box.HalfZ - 8f, yaw: 0f); + session.SetContenderPose(player.Id, box.X, box.Z + box.HalfZ + 8f, yaw: 0f); + session.State.Tracers.Clear(); + + for (int occTick = 0; occTick < 6; occTick++) + { + if (occTick > 0) + { + // Move laterally behind cover to verify AI never steers/aims toward hidden coords + session.SetContenderPose(player.Id, box.X + (occTick % 2 == 0 ? 1.5f : -1.5f), box.Z + box.HalfZ + 8f, yaw: 0f); + } + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + + Assert.Null(ai.AiTargetContenderId); + Assert.False(ai.FireCmd, $"AI leaked FireCmd on occluded tick {occTick} (phase={phase})"); + float aimToHidden = MathF.Sqrt((ai.AimX - player.X) * (ai.AimX - player.X) + (ai.AimZ - player.Z) * (ai.AimZ - player.Z)); + Assert.True(aimToHidden > 5f, $"AI aim leaked hidden player coords on occluded tick {occTick} (dist={aimToHidden:F2}m)"); + } + } + } + + [Fact] + public void PlayerDetectedByCount_StaysExactZero_UnderAsymmetricCover_NoFlicker() + { + using var session = new ArenaSession(seed: 12, slot0Human: true); + var box = session.State.ArenaCoverBoxes.First(b => b.HalfY >= 2.8f); + var player = session.State.Contenders[0]; + var rival = session.State.Contenders[1]; + + // Move all other rivals and spectators far away (> 500m) so only rival <-> player is tested + for (int i = 2; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(session.State.Contenders[i].Id, -680f + i * 8f, -680f); + } + for (int i = 0; i < session.State.Spectators.Spectators.Count; i++) + { + var s = session.State.Spectators.Spectators[i]; + session.SetSpectatorPose(s.Id, (box.X >= 0f ? -1f : 1f) * 680f, (box.Z >= 0f ? -1f : 1f) * 680f); + } + + // Medium-tall player (Breaker) right next to the 5.6m bunker sees over it onto a low rival (Jackal) 40m on the far side, + // while the low rival's eye cannot see the Breaker's lower target center behind the bunker. + session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 4f); + session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Breaker); + Assert.True(session.State.TrySwapNearbyChassis(player.Id)); + + session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 40f); + session.State.SpawnChassisDrop(rival.X, rival.Z, Catalog.Jackal); + Assert.True(session.State.TrySwapNearbyChassis(rival.Id)); + + // Confirm asymmetric LOS precondition + Assert.True(session.HasLineOfSight( + player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z, + rival.X, MatchRules.GetTargetAimY(rival.Y, rival.Grid.Spec.HalfHeight), rival.Z)); + Assert.False(session.HasLineOfSight( + rival.X, MatchRules.GetObserverEyeY(rival.Y, rival.Grid.Spec.HalfHeight), rival.Z, + player.X, MatchRules.GetTargetAimY(player.Y, player.Grid.Spec.HalfHeight), player.Z)); + + for (int tick = 0; tick < 18; tick++) + { + // Re-pin poses each tick so drift never alters cover geometry + session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 4f); + session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 40f); + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + + var obs0 = session.State.GetOrCreateObserverState(0); + Assert.True(obs0.ContenderContacts[rival.Id].VisibleToPlayer); + Assert.Equal(0, obs0.DetectedByCount); + } + } + + [Fact] + public void SpectatorRing_ClearsNearestOpenLosNeutralWatcher_OnFirstTickOutsideSafeRadius() + { + // Test every tick phase 0..5 so % 6 staggering cannot hide + for (int tickIndex = 0; tickIndex < 6; tickIndex++) + { + var ring = new SpectatorRing(seed: 42); + // Pick a spectator whose (Id + tickIndex) % 6 != 0 so % 6 staggering would have skipped it + var targetNearest = ring.Spectators.First(s => (s.Id + tickIndex) % 6 != 0); + + // Place contender just outside SafeRadius directly beside targetNearest (within 12m outside => allowedCleared = 1) + float len = MathF.Sqrt(targetNearest.X * targetNearest.X + targetNearest.Z * targetNearest.Z); + float nx = targetNearest.X / len; + float nz = targetNearest.Z / len; + float outR = ring.SafeRadius + 4f; + float cx = nx * outR; + float cz = nz * outR; + + ring.UpdateClearance( + new[] { new RingContact(0, cx, cz, true) }, + 1f / 60f, + static (_, _) => true, + tickIndex: tickIndex); + + Assert.Equal(1, ring.CountClearedFor(0)); + Assert.Equal(SpectatorStance.Cleared, targetNearest.Stance); + Assert.Equal(0, targetNearest.TargetContenderId); + } + } + + [Fact] + public void DeadObserver_ClearsSpectatorContactsVisibleToPlayer() + { + using var session = new ArenaSession(seed: 12, slot0Human: true); + var player = session.State.Contenders[0]; + var spec = session.State.Spectators.Spectators.First(s => s.Alive); + + session.SetContenderPose(player.Id, 0f, 0f); + session.SetSpectatorPose(spec.Id, 0f, 35f); + session.State.Spectators.OnSpectatorDamaged(spec, player.Id); + + session.Step(); + var obs0 = session.State.GetOrCreateObserverState(0); + Assert.True(obs0.SpectatorContacts.TryGetValue(spec.Id, out var memBefore) && memBefore.VisibleToPlayer, + "Expected living observer in open LOS to mark provoked spectator VisibleToPlayer=true"); + + // Kill observer and step once; stale SpectatorContacts must clear VisibleToPlayer + player.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, 0f, player.Grid.HitSequence + 1); + Assert.False(player.Alive); + + session.Step(); + Assert.False(obs0.SpectatorContacts[spec.Id].VisibleToPlayer, + "Expected dead observer to clear SpectatorContacts.VisibleToPlayer"); + } + } +} diff --git a/tests/RustToDust.Tests/GraphicsSettingsTests.cs b/tests/RustToDust.Tests/GraphicsSettingsTests.cs new file mode 100644 index 0000000..e798424 --- /dev/null +++ b/tests/RustToDust.Tests/GraphicsSettingsTests.cs @@ -0,0 +1,158 @@ +using System; +using System.IO; +using RustToDust.Client; +using Xunit; + +namespace RustToDust.Tests; + +public sealed class GraphicsSettingsTests +{ + [Fact] + public void Defaults_MatchExpectedBaseline() + { + var settings = new GraphicsSettings(); + Assert.Equal(VfxResolutionScale.Half, settings.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, settings.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, settings.SdfgiQuality); + Assert.True(settings.BorderlessFullscreen); + + Assert.Equal(0.50f, GraphicsSettings.GetResolutionScaleFactor(settings.VfxResolution)); + Assert.Equal((10, 15), GraphicsSettings.GetVolumetricStepBudget(settings.VolumetricSamples)); + var sdfgi = GraphicsSettings.GetSdfgiConfig(settings.SdfgiQuality); + Assert.True(sdfgi.Enabled); + Assert.Equal(0.8f, sdfgi.MinCellSize); + Assert.Equal(3, sdfgi.Cascades); + Assert.True(sdfgi.HalfResolution); + Assert.Equal(4, sdfgi.RayCount); + } + + [Fact] + public void MissingOrCorruptJson_FallsBackToSafeDefaults() + { + string tempDir = Path.Combine(Path.GetTempPath(), "rtd-gfx-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + try + { + string missingPath = Path.Combine(tempDir, "missing.json"); + var missingLoaded = GraphicsSettings.Load(missingPath); + Assert.Equal(VfxResolutionScale.Half, missingLoaded.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, missingLoaded.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, missingLoaded.SdfgiQuality); + Assert.True(missingLoaded.BorderlessFullscreen); + + string corruptPath = Path.Combine(tempDir, "corrupt.json"); + File.WriteAllText(corruptPath, "{ this is not valid json !!!"); + var corruptLoaded = GraphicsSettings.Load(corruptPath); + Assert.Equal(VfxResolutionScale.Half, corruptLoaded.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, corruptLoaded.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, corruptLoaded.SdfgiQuality); + Assert.True(corruptLoaded.BorderlessFullscreen); + + // ResetToDefaults(persist: true) must unconditionally rewrite a corrupt file even when memory equals defaults + corruptLoaded.ResetToDefaults(persist: true); + string repairedJson = File.ReadAllText(corruptPath); + Assert.DoesNotContain("not valid json", repairedJson, StringComparison.Ordinal); + var repaired = new GraphicsSettings(); + Assert.True(repaired.LoadFromJson(repairedJson)); + Assert.Equal(VfxResolutionScale.Half, repaired.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, repaired.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, repaired.SdfgiQuality); + Assert.True(repaired.BorderlessFullscreen); + + var outOfRange = new GraphicsSettings(); + Assert.True(outOfRange.LoadFromJson("""{"vfxResolutionScale":99,"volumetricSamples":42,"sdfgiQuality":77,"borderlessFullscreen":false}""")); + Assert.Equal(VfxResolutionScale.Half, outOfRange.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, outOfRange.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, outOfRange.SdfgiQuality); + Assert.False(outOfRange.BorderlessFullscreen); + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, recursive: true); + } + } + } + + [Fact] + public void SaveAndReload_RoundtripsAllFieldsAndFiresChanged() + { + string tempDir = Path.Combine(Path.GetTempPath(), "rtd-gfx-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + try + { + string path = Path.Combine(tempDir, "graphics_settings.json"); + var settings = GraphicsSettings.Load(path); + int changeEvents = 0; + settings.Changed += _ => changeEvents++; + + settings.Apply( + VfxResolutionScale.Full, + VolumetricSamples.Ultra, + SdfgiQuality.High, + borderlessFullscreen: false, + persist: true); + Assert.Equal(1, changeEvents); + Assert.True(File.Exists(path)); + + // No-op apply must not fire duplicate Changed events + settings.Apply( + VfxResolutionScale.Full, + VolumetricSamples.Ultra, + SdfgiQuality.High, + borderlessFullscreen: false, + persist: true); + Assert.Equal(1, changeEvents); + + var reloaded = GraphicsSettings.Load(path); + Assert.Equal(VfxResolutionScale.Full, reloaded.VfxResolution); + Assert.Equal(VolumetricSamples.Ultra, reloaded.VolumetricSamples); + Assert.Equal(SdfgiQuality.High, reloaded.SdfgiQuality); + Assert.False(reloaded.BorderlessFullscreen); + + reloaded.ResetToDefaults(persist: true); + var afterReset = GraphicsSettings.Load(path); + Assert.Equal(VfxResolutionScale.Half, afterReset.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, afterReset.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, afterReset.SdfgiQuality); + Assert.True(afterReset.BorderlessFullscreen); + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, recursive: true); + } + } + } + + [Fact] + public void PresetMappings_MatchSpecification() + { + Assert.Equal(0.50f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.Half)); + Assert.Equal(0.75f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.ThreeQuarter)); + Assert.Equal(1.00f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.Full)); + + Assert.Equal((8, 12), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Low)); + Assert.Equal((10, 15), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Medium)); + Assert.Equal((16, 24), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.High)); + Assert.Equal((24, 36), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Ultra)); + + Assert.False(GraphicsSettings.GetSdfgiConfig(SdfgiQuality.Off).Enabled); + + var balanced = GraphicsSettings.GetSdfgiConfig(SdfgiQuality.Balanced); + Assert.True(balanced.Enabled); + Assert.Equal(0.8f, balanced.MinCellSize); + Assert.Equal(3, balanced.Cascades); + Assert.True(balanced.HalfResolution); + Assert.Equal(4, balanced.RayCount); + + var high = GraphicsSettings.GetSdfgiConfig(SdfgiQuality.High); + Assert.True(high.Enabled); + Assert.Equal(0.4f, high.MinCellSize); + Assert.Equal(4, high.Cascades); + Assert.False(high.HalfResolution); + Assert.Equal(8, high.RayCount); + } +} diff --git a/tests/RustToDust.Tests/GridHeatTests.cs b/tests/RustToDust.Tests/GridHeatTests.cs new file mode 100644 index 0000000..cba59dc --- /dev/null +++ b/tests/RustToDust.Tests/GridHeatTests.cs @@ -0,0 +1,130 @@ +using System.Collections.Generic; +using RustToDust.Core; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class GridHeatTests + { + [Fact] + public void Conduction_SpreadsHeatFromHotHardpointToNeighbors() + { + var grid = Catalog.CreateStarterBuggy(); + // hp.weapon.roof is at (1, 0) 1x2. Neighbors (0, 0) and (1, 2) start at ambient 20f. + grid.InjectHardpointHeat("hp.weapon.roof", 600f); + float hotBefore = grid.Temperature[1, 0]; + Assert.True(hotBefore > ChassisGrid.AmbientTemp + 20f); + Assert.Equal(ChassisGrid.AmbientTemp, grid.Temperature[0, 0]); + Assert.Equal(ChassisGrid.AmbientTemp, grid.Temperature[1, 2]); + + for (int i = 0; i < 30; i++) + { + grid.StepHeat(1f / 60f); + } + + Assert.True(grid.Temperature[0, 0] > ChassisGrid.AmbientTemp + 1f); + Assert.True(grid.Temperature[1, 2] > ChassisGrid.AmbientTemp + 1f); + Assert.True(grid.Temperature[1, 0] < hotBefore); + } + + [Fact] + public void Radiation_CoolsBorderCellsWhileInteriorCellsDoNotRadiateDirectly() + { + var grid = new ChassisGrid(Catalog.Tank); // 4x5 full grid: interior cells exist at (1..2, 1..3) + for (int y = 0; y < grid.Spec.Height; y++) + { + for (int x = 0; x < grid.Spec.Width; x++) + { + grid.Temperature[x, y] = 120f; + } + } + + // Single 60Hz substep: neighbors are all 120f so net conduction is 0. + // Only BorderCells lose heat to radiation; interior cell (1, 2) must stay at 120f. + grid.StepHeat(1f / 60f); + + Assert.True(grid.BorderCells[0, 0]); + Assert.False(grid.BorderCells[1, 2]); + Assert.True(grid.Temperature[0, 0] < 120f); + Assert.Equal(120f, grid.Temperature[1, 2], precision: 5); + } + + [Fact] + public void ModulePerformance_MatchesTrapezoidalPlateauCurve() + { + var mod = Catalog.Mg762; // Min=0, Optimal=65, Plateau=70 => [30, 100], Max=155 + + Assert.Equal(0f, mod.Performance(-5f)); + Assert.Equal(0f, mod.Performance(0f)); + Assert.Equal(0.5f, mod.Performance(15f), precision: 4); + Assert.Equal(1f, mod.Performance(30f), precision: 4); + Assert.Equal(1f, mod.Performance(65f), precision: 4); + Assert.Equal(1f, mod.Performance(100f), precision: 4); + Assert.Equal(0.5f, mod.Performance(127.5f), precision: 4); + Assert.Equal(0f, mod.Performance(155f)); + Assert.Equal(0f, mod.Performance(210f)); + } + + [Fact] + public void DorsalHit_FrontStrikesFrontRowAndRearStrikesRearRow() + { + var grid = new ChassisGrid(Catalog.Tank); + + var frontHit = grid.ApplyHit(localRight: 0f, localForward: 1f, localHeightNorm: 0.5f, damage: 15f, heatTransfer: 0f); + var rearHit = grid.ApplyHit(localRight: 0f, localForward: -1f, localHeightNorm: 0.5f, damage: 15f, heatTransfer: 0f); + var leftHit = grid.ApplyHit(localRight: -1f, localForward: 0f, localHeightNorm: 0.5f, damage: 15f, heatTransfer: 0f); + var rightHit = grid.ApplyHit(localRight: 1f, localForward: 0f, localHeightNorm: 0.5f, damage: 15f, heatTransfer: 0f); + + Assert.Equal(0, frontHit.CellY); + Assert.Equal(grid.Spec.Height - 1, rearHit.CellY); + Assert.Equal(0, leftHit.CellX); + Assert.Equal(grid.Spec.Width - 1, rightHit.CellX); + } + + [Fact] + public void CoronalHit_HighVsLowElevationStrikesUpperVsLowerBipedCells() + { + var grid = new ChassisGrid(Catalog.Raptor); + float initialLegs = grid.LegIntegrity; + Assert.Equal(1f, initialLegs); + + var highHit = grid.ApplyHit(localRight: 0f, localForward: 1f, localHeightNorm: 0.95f, damage: 20f, heatTransfer: 0f); + var lowHit = grid.ApplyHit(localRight: -0.4f, localForward: 1f, localHeightNorm: 0.05f, damage: 35f, heatTransfer: 0f); + + Assert.True(highHit.CellY <= 1); + Assert.True(lowHit.CellY >= grid.Spec.Height - 2); + Assert.True(grid.LegIntegrity < initialLegs); + } + + [Fact] + public void LooseFitAndSwapChassis_PreservesCompatibleGearAndStowsOverflow() + { + // Ironclad has 2x2 main turret hardpoint: smaller 1x1 weapon fits loosely; 2x2 weapon must NOT fit 1x2 Jackal roof. + var tankGrid = new ChassisGrid(Catalog.Ironclad); + Assert.True(tankGrid.TryMount(Catalog.Recoilless, "hp.weapon.main")); // 2x2 into 2x2 + Assert.True(tankGrid.TryMount(Catalog.Mg762, "hp.weapon.coax")); // 1x1 into 1x1 + Assert.True(tankGrid.TryMount(Catalog.TurboCore, "hp.engine.rear")); // 1x2 into 2x2 + Assert.True(tankGrid.TryMount(Catalog.GoldRadiator, "hp.radiator.l")); // 1x1 into 1x2 + Assert.True(tankGrid.TryMount(Catalog.WeldedPlate, "hp.armor.front")); // 1x1 into 4x1 + Assert.True(tankGrid.TryMount(Catalog.GildedPlate, "hp.armor.skirts")); // 1x1 into 1x2 + + // Fill cargo so swapping down to Jackal (capacity 4) overflows 2 items to ground! + Assert.True(tankGrid.TryAddCargo(Catalog.Flak)); + Assert.True(tankGrid.TryAddCargo(Catalog.CopperRad)); + Assert.True(tankGrid.TryAddCargo(Catalog.DieselCore)); + + List dropped = tankGrid.SwapChassis(Catalog.Jackal); + + // Jackal has 1x2 Weapon (mg_762 fits, recoilless 2x2 does not!), 1x2 Engine (turbo_core fits), 1x1 Radiator (gold_radiator fits), 0 Armor hardpoints. + Assert.Equal("jackal", tankGrid.Spec.Id); + Assert.Contains(tankGrid.Mounted, m => m.Spec.Id == "mg_762"); + Assert.Contains(tankGrid.Mounted, m => m.Spec.Id == "turbo_core"); + Assert.Contains(tankGrid.Mounted, m => m.Spec.Id == "gold_radiator"); + Assert.DoesNotContain(tankGrid.Mounted, m => m.Spec.Id == "recoilless"); + + // 6 mounted on Ironclad: 3 transferred, 3 leftover + 3 cargo = 6 items -> 4 in Jackal Cargo, 2 dropped! + Assert.Equal(Catalog.Jackal.CargoCapacity, tankGrid.Cargo.Count); + Assert.Equal(2, dropped.Count); + } + } +} diff --git a/tests/RustToDust.Tests/HbGpuNativeTests.cs b/tests/RustToDust.Tests/HbGpuNativeTests.cs new file mode 100644 index 0000000..72d2e8a --- /dev/null +++ b/tests/RustToDust.Tests/HbGpuNativeTests.cs @@ -0,0 +1,271 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using RustToDust.HbGpu; +using Xunit; + +namespace RustToDust.Tests; + +public sealed class HbGpuNativeTests +{ + private static string RepoRoot + { + get + { + string? dir = AppContext.BaseDirectory; + while (dir is not null) + { + if (File.Exists(Path.Combine(dir, "RustToDust.slnx"))) + { + return dir; + } + dir = Directory.GetParent(dir)?.FullName; + } + throw new DirectoryNotFoundException("Could not locate RustToDust.slnx from test output directory."); + } + } + + [Fact] + public void NativeDllExistsAndMeetsSizeBudget() + { + if (OperatingSystem.IsWindows()) + { + string dllPath = Path.Combine(AppContext.BaseDirectory, "rtd_hbgpu.dll"); + Assert.True(File.Exists(dllPath), $"Expected rtd_hbgpu.dll at '{dllPath}'."); + long size = new FileInfo(dllPath).Length; + Assert.InRange(size, 100_000, 2_621_440); // < 2.5 MiB + } + + string ver = HbGpuNative.GetVersionString(); + Assert.Equal("15.2.0", ver); + + string vertShared = HbGpuNative.GetShaderSource(HbGpuShaderStage.Vertex, HbGpuShaderKind.Shared); + string fragShared = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Shared); + string fragDraw = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Draw); + Assert.Contains("hb_gpu_dilate", vertShared); + Assert.Contains("uniform isamplerBuffer hb_gpu_atlas;", fragShared); + Assert.Contains("hb_gpu_draw", fragDraw); + } + + [Fact] + public void KryptonFontAndLicensesAreCompliant() + { + string root = RepoRoot; + string fontPath = Path.Combine(root, "assets", "fonts", "Krypton.ttf"); + string oflPath = Path.Combine(root, "assets", "fonts", "OFL-1.1.txt"); + string hbCopyPath = Path.Combine(root, "assets", "fonts", "HARFBUZZ-COPYING.txt"); + string noticesPath = Path.Combine(root, "THIRD_PARTY_NOTICES.txt"); + + Assert.True(File.Exists(fontPath)); + Assert.True(File.Exists(oflPath)); + Assert.True(File.Exists(hbCopyPath)); + Assert.True(File.Exists(noticesPath)); + + byte[] fontBytes = File.ReadAllBytes(fontPath); + Assert.Equal(1_363_340, fontBytes.Length); + string sha = Convert.ToHexString(SHA256.HashData(fontBytes)).ToLowerInvariant(); + Assert.Equal("6462cae55b336ae6ffb7c8f1932177960510a4207e65803f527b276d42c8a240", sha); + + string oflText = File.ReadAllText(oflPath); + Assert.Contains("Copyright (c) 2023, GitHub", oflText); + Assert.Contains("Krypton", oflText); + } + + [Fact] + public void QuadInstanceStructIs80Bytes() + { + Assert.Equal(80, Unsafe.SizeOf()); + Assert.Equal(80, Marshal.SizeOf()); + } + + [Fact] + public void ShapingAndGlyphEncodingWorkAcrossKryptonAxes() + { + string fontPath = Path.Combine(RepoRoot, "assets", "fonts", "Krypton.ttf"); + using var fonts = new HbGpuFontCache(); + fonts.RegisterFontFromFile(0, fontPath); + + RtdHbFontMetrics metrics = fonts.GetMetrics(0); + Assert.Equal(2000, metrics.Upem); + + var atlas = new HbGpuAtlasAllocator(); + var blobs = new HbGpuBlobCache(atlas); + var writer = new HbGpuCommandWriter(); + + writer.BeginFrame(); + float wReg = writer.DrawTextUtf16("RAPTOR -> 142.8m", 10f, 40f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 200f); + float wBold = writer.DrawTextUtf16("CHASSIS", 10f, 80f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 700f); + float wSlnt = writer.DrawTextUtf16("SLANT", 10f, 120f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 400f, slnt: -9f); + + Assert.True(wReg > 50f); + Assert.True(wBold > 20f); + Assert.True(wSlnt > 20f); + Assert.True(writer.QuadCount >= 18); // spaces omit quads, visible glyphs emit quads + Assert.True(blobs.CachedGlyphCount >= 15); + Assert.True(atlas.PersistentCursor > 0); + Assert.True(atlas.PendingChunkCount > 0); + + // Space glyph encodes cleanly as empty + CachedBlob spaceBlob = blobs.GetOrEncodeGlyph(fonts, 0, 1 /* glyph or verify space */, 200, 1000, 0); + Assert.True(spaceBlob.TexelCount >= 0); + + // Hot steady-state loop allocates zero managed bytes once glyphs/styles are cached + writer.BeginFrame(); + atlas.ClearPending(); + ReadOnlySpan hotText = "RAPTOR -> 142.8m"; + long before = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < 64; i++) + { + writer.BeginFrame(); + writer.DrawTextUtf16(hotText, 10f, 40f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 200f); + } + long after = GC.GetAllocatedBytesForCurrentThread(); + Assert.Equal(0, after - before); + } + + [Fact] + public void VectorPathsAndAtlasBudgetResetWork() + { + var atlas = new HbGpuAtlasAllocator(); + var blobs = new HbGpuBlobCache(atlas); + + CachedBlob rect = HbGpuVectorShapes.GetUnitFilledRect(blobs); + CachedBlob circle = HbGpuVectorShapes.GetUnitFilledCircle(blobs); + CachedBlob ring = HbGpuVectorShapes.GetUnitRingStroke(blobs, 24); + CachedBlob bracket = HbGpuVectorShapes.GetTargetBracketCorner(blobs, 120); + CachedBlob arrow = HbGpuVectorShapes.GetDirectionalArrow(blobs); + CachedBlob chevron = HbGpuVectorShapes.GetChevronTriangle(blobs); + CachedBlob diamond = HbGpuVectorShapes.GetDiamondBlip(blobs); + CachedBlob arc = HbGpuVectorShapes.EncodeArcStrokeDynamic(blobs, -2.356f, 0.785f); + + Assert.True(rect.IsValid && rect.TexelCount > 2); + Assert.True(circle.IsValid && circle.TexelCount > 2); + Assert.True(ring.IsValid && ring.TexelCount > 4); + Assert.True(bracket.IsValid && bracket.TexelCount > 2); + Assert.True(arrow.IsValid && arrow.TexelCount > 2); + Assert.True(chevron.IsValid && chevron.TexelCount > 2); + Assert.True(diamond.IsValid && diamond.TexelCount > 2); + Assert.True(arc.IsValid && arc.TexelCount > 4); + Assert.True(arc.AtlasOffset >= HbGpuAtlasAllocator.DynamicBase); + + // Also test tapered line verb directly + Span lineVerb = stackalloc byte[] { (byte)HbGpuPathVerb.Line }; + Span lineArgs = stackalloc float[] { -400f, 0f, 20f, 400f, 0f, 60f, 1f }; + CachedBlob lineBlob = blobs.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.Custom, 1, 0), 1000u, lineVerb, lineArgs); + Assert.True(lineBlob.IsValid); + + // Drain uploads with zero allocations + byte[] staging = new byte[HbGpuBlobCache.ScratchShortsCapacity * sizeof(short)]; + int drainedBytes = 0; + Action cb = (_, len) => drainedBytes += (int)len; + int chunks = atlas.DrainChunks(staging, cb); + Assert.True(chunks >= 9); + Assert.True(drainedBytes > 0); + Assert.Equal(0, atlas.PendingChunkCount); + + // Verify static arc caching (0 pending chunks and 0 B GC allocs on repeat lookup) + var staticArcKey = new VectorBlobKey(VectorShapeKind.ThermalHeatArc, 45, 1); + CachedBlob staticArc = HbGpuVectorShapes.GetStaticArcStroke(blobs, staticArcKey, -2.356f, 0.785f, 500f, 30f); + Assert.True(staticArc.IsValid); + Assert.True(staticArc.AtlasOffset < HbGpuAtlasAllocator.DynamicBase); + atlas.ClearPending(); + + // Warm up cache-hit path once before measuring GC allocations + CachedBlob warmHit = HbGpuVectorShapes.GetStaticArcStroke(blobs, staticArcKey, -2.356f, 0.785f, 500f, 30f); + Assert.Equal(staticArc.AtlasOffset, warmHit.AtlasOffset); + + uint expectedOffset = staticArc.AtlasOffset; + bool allMatched = true; + long arcGcBefore = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < 64; i++) + { + CachedBlob hit = HbGpuVectorShapes.GetStaticArcStroke(blobs, staticArcKey, -2.356f, 0.785f, 500f, 30f); + if (hit.AtlasOffset != expectedOffset) allMatched = false; + } + long arcGcAfter = GC.GetAllocatedBytesForCurrentThread(); + Assert.True(allMatched); + Assert.Equal(0, arcGcAfter - arcGcBefore); + Assert.Equal(0, atlas.PendingChunkCount); + + // Verify dynamic ring wrap-around + for (int i = 0; i < 600; i++) + { + CachedBlob dyn = HbGpuVectorShapes.EncodeArcStrokeDynamic(blobs, -1.5f, 1.5f); + Assert.True(dyn.AtlasOffset >= HbGpuAtlasAllocator.DynamicBase); + Assert.True(dyn.AtlasOffset + dyn.TexelCount <= HbGpuAtlasAllocator.TotalTexels); + atlas.ClearPending(); + } + } + + [Fact] + public void PersistentAtlasOverflowDoesNotResetMidFrame() + { + var atlas = new HbGpuAtlasAllocator(); + var blobs = new HbGpuBlobCache(atlas); + + // Fill persistent zone right up near PersistentCapacity without crossing it + short[] chunk = new short[4096 * 4]; // 4096 texels + chunk[0] = 1; + while (atlas.PersistentCursor + 4096 <= HbGpuAtlasAllocator.PersistentCapacity) + { + atlas.AllocatePersistent(chunk); + atlas.ClearPending(); + } + + uint epochBefore = atlas.Epoch; + uint cursorBefore = atlas.PersistentCursor; + Assert.True(cursorBefore > HbGpuAtlasAllocator.PersistentResetWatermark); + + // Encode a static vector that exceeds remaining PersistentCapacity: must NOT reset mid-frame! + Span bigVerbs = stackalloc byte[64]; + Span bigArgs = stackalloc float[128]; + int v = 0, a = 0; + bigVerbs[v++] = (byte)HbGpuPathVerb.Move; + bigArgs[a++] = 0f; + bigArgs[a++] = 0f; + for (int i = 1; i <= 30; i++) + { + float ang = i * 0.2f; + bigVerbs[v++] = (byte)HbGpuPathVerb.LineTo; + bigArgs[a++] = MathF.Cos(ang) * 400f; + bigArgs[a++] = MathF.Sin(ang) * 400f; + } + bigVerbs[v++] = (byte)HbGpuPathVerb.Close; + + // First force a large remaining fill so the encoded vector overflows remaining space + uint rem = HbGpuAtlasAllocator.PersistentCapacity - atlas.PersistentCursor; + if (rem > 2) + { + atlas.AllocatePersistent(new short[(rem - 1) * 4]); + atlas.ClearPending(); + } + cursorBefore = atlas.PersistentCursor; + + CachedBlob overflowed = blobs.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.Custom, 999, 1), + 1000u, + bigVerbs[..v], + bigArgs[..a]); + + Assert.False(overflowed.IsValid); + Assert.Equal(epochBefore, atlas.Epoch); + Assert.Equal(cursorBefore, atlas.PersistentCursor); + Assert.True(blobs.IsPersistentOverflowPending); + + // Next BeginFrame resets cleanly and allows encoding + Assert.True(blobs.EnsureBudgetOrReset()); + Assert.Equal(epochBefore + 1, atlas.Epoch); + Assert.Equal(0u, atlas.PersistentCursor); + Assert.False(blobs.IsPersistentOverflowPending); + + CachedBlob recovered = blobs.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.Custom, 999, 1), + 1000u, + bigVerbs[..v], + bigArgs[..a]); + Assert.True(recovered.IsValid); + } +} diff --git a/tests/RustToDust.Tests/HybridBWalkerTests.cs b/tests/RustToDust.Tests/HybridBWalkerTests.cs new file mode 100644 index 0000000..9099c55 --- /dev/null +++ b/tests/RustToDust.Tests/HybridBWalkerTests.cs @@ -0,0 +1,1437 @@ +using System; +using System.Diagnostics; +using System.Numerics; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; +using Xunit.Abstractions; +using Ymir.Box3D; + +namespace RustToDust.Tests +{ + public sealed class HybridBWalkerTests + { + private readonly ITestOutputHelper _output; + + public HybridBWalkerTests(ITestOutputHelper output) + { + _output = output; + } + + private static ChassisSpec MakeExemplarSpec() => + Catalog.Raptor with + { + Id = "exemplar_frame", + Name = "Exemplar Frame", + BaseCellArmor = 22f, + MassKg = 1150f, + BaseThrust = 26000f, + BaseTurnRate = 6.2f, + MaxSpeed = 40f, + HalfWidth = 0.8f, + HalfHeight = 1.55f, + HalfLength = 0.8f + }; + + [Fact] + public void HybridB_All7Mechs_WalkTurnSlopes_SmoothLiftoff_ZeroTeleports() + { + var specs = new[] + { + Catalog.Breaker, + Catalog.Paladin, + Catalog.Raptor, + Catalog.Spectre, + Catalog.Kestrel, + Catalog.Manticore, + Catalog.Bastion, + MakeExemplarSpec() + }; + + // 1. Walk, turn, and climb slopes across all 7 mechs + exemplar_frame + foreach (var spec in specs) + { + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: true); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 500f + i * 16f, 500f); + } + + // Phase A: start on flat/gentle ground near origin (60 ticks) to verify honest walk slip < 8cm + session.SetContenderPose(0, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, spec); + Assert.True(session.TrySwapNearbyChassis(0), $"Failed swap to {spec.Id}"); + var player = session.State.Contenders[0]; + Assert.Equal(spec.Id, player.Grid.Spec.Id); + + var ws = session.GetWalkerState(true, player.Id); + Assert.NotNull(ws); + int nLegs = ws!.Geom.LegCount; + float geomScale = ws.GeomScale; + + for (int t = 0; t < 60; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 0.45f, + Steer: 0f, + AimWorldX: player.X, + AimWorldZ: player.Z + 60f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + } + Assert.True(ws.MaxFootSlipM < 0.08f, + $"{spec.Id}: normal walk foot slip {ws.MaxFootSlipM:F4}m >= 0.08m (maxSpd={spec.MaxSpeed:F1})"); + + // Phase B: move to dune slope approach, turn & climb (180 ticks) checking liftoff teleport, C1 touchdown, omega continuity + float duneApproachX = 0f; + float duneApproachZ = 0f; + float bestScore = -1f; + foreach (var b in session.State.Terrain.Brushes) + { + if (b.Kind == TerrainBrushKind.DuneRidge && b.HeightDelta > 4f) + { + float d = MathF.Sqrt(b.X * b.X + b.Z * b.Z); + if (d > 40f && d < 280f && b.HeightDelta > bestScore) + { + bestScore = b.HeightDelta; + float dirX = -b.X / d; + float dirZ = -b.Z / d; + duneApproachX = b.X + dirX * MathF.Min(36f, b.RadiusX * 0.85f); + duneApproachZ = b.Z + dirZ * MathF.Min(36f, b.RadiusZ * 0.85f); + } + } + } + session.SetContenderPose(0, duneApproachX, duneApproachZ, MathF.Atan2(-duneApproachX, -duneApproachZ) + MathF.PI); + ws = session.GetWalkerState(true, player.Id)!; + + var prevFoot = new Vector3[nLegs]; + var prevPlanted = new bool[nLegs]; + var prevOmegaHip = new float[nLegs]; + for (int i = 0; i < nLegs; i++) + { + prevFoot[i] = ws.FootSole[i]; + prevPlanted[i] = ws.Planted[i]; + prevOmegaHip[i] = ws.Actuators[i].Omega.HipPitch; + } + + float maxDeltaFootPerTick = 0f; + float maxLiftoffDelta = 0f; + float maxOmegaJumpAtSwap = 0f; + float maxTouchdownGroundErr = 0f; + float minUpDot = 1f; + int swapCount = 0; + for (int t = 0; t < 180; t++) + { + float steer = MathF.Sin(t * 0.06f) * 0.65f; + session.SetHumanInput(0, new PlayerInput( + Throttle: 0.85f, + Steer: steer, + AimWorldX: player.X + 40f * MathF.Sin(player.Yaw), + AimWorldZ: player.Z + 40f * MathF.Cos(player.Yaw), + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + Assert.True(float.IsFinite(player.X) && float.IsFinite(player.Y) && float.IsFinite(player.Z), + $"{spec.Id}: non-finite pose at tick {t}"); + + var q = new Quaternion(player.CurrRotX, player.CurrRotY, player.CurrRotZ, player.CurrRotW); + var up = Vector3.Transform(Vector3.UnitY, q); + minUpDot = MathF.Min(minUpDot, up.Y); + + for (int i = 0; i < nLegs; i++) + { + Vector3 curFoot = ws.FootSole[i]; + float delta = (curFoot - prevFoot[i]).Length(); + if (delta > maxDeltaFootPerTick) + { + maxDeltaFootPerTick = delta; + } + + bool curPlanted = ws.Planted[i]; + if (prevPlanted[i] && !curPlanted && !ws.IsAirborne) + { + if (delta > maxLiftoffDelta) + { + maxLiftoffDelta = delta; + } + } + if (!prevPlanted[i] && curPlanted) + { + swapCount++; + float groundY = session.State.Terrain.SampleHeight(curFoot.X, curFoot.Z); + float gErr = MathF.Abs(curFoot.Y - groundY); + if (gErr > maxTouchdownGroundErr) + { + maxTouchdownGroundErr = gErr; + } + + float omegaDelta = MathF.Abs(ws.Actuators[i].Omega.HipPitch - prevOmegaHip[i]); + if (omegaDelta > maxOmegaJumpAtSwap) + { + maxOmegaJumpAtSwap = omegaDelta; + } + } + + prevFoot[i] = curFoot; + prevPlanted[i] = curPlanted; + prevOmegaHip[i] = ws.Actuators[i].Omega.HipPitch; + } + } + + float maxFootGroundSpeed = spec.MaxSpeed + MathF.Max(spec.HalfWidth, spec.HalfLength) * spec.BaseTurnRate * 0.5f; + float maxAllowedTickDelta = MathF.Max(0.55f, maxFootGroundSpeed * ArenaSession.FixedDt * 3.5f); + _output.WriteLine( + $"{spec.Id,-15} minUp={minUpDot:F3} slip={ws.MaxFootSlipM:F4}m maxFootDelta/tick={maxDeltaFootPerTick:F4}m " + + $"liftoffDelta={maxLiftoffDelta:F4}m tdGroundErr={maxTouchdownGroundErr:F5}m swapOmegaJump={maxOmegaJumpAtSwap:F3} swaps={swapCount}"); + + Assert.True(minUpDot >= 0.90f, $"{spec.Id}: unstable tilt minUpDot={minUpDot:F3}"); + Assert.True(swapCount >= 4, $"{spec.Id}: expected >= 4 gait transitions, got {swapCount}"); + Assert.True(maxLiftoffDelta <= 0.35f * MathF.Max(1f, geomScale), + $"{spec.Id}: Bug 1 liftoff teleport detected: liftoffDelta={maxLiftoffDelta:F4}m"); + Assert.True(maxDeltaFootPerTick <= maxAllowedTickDelta, + $"{spec.Id}: 1-tick foot teleport detected: maxDelta={maxDeltaFootPerTick:F4}m > {maxAllowedTickDelta:F4}m"); + Assert.True(maxTouchdownGroundErr <= 0.06f * MathF.Max(1f, geomScale), + $"{spec.Id}: non-C1 liftoff/touchdown height gap {maxTouchdownGroundErr:F4}m"); + Assert.True(maxOmegaJumpAtSwap < 12.0f, + $"{spec.Id}: discontinuous joint omega jump across swap: {maxOmegaJumpAtSwap:F3} rad/s"); + } + + // 2. Benchmark 12 simultaneous mechs CPU < 1.5 ms/tick + { + using var benchSession = new ArenaSession(seed: 99, mapKind: ArenaMapKind.Desert, slot0Human: true); + for (int i = 0; i < benchSession.State.Contenders.Count; i++) + { + var spec = specs[i % 7]; + float x = (i - 5.5f) * 28f; + float z = -80f + (i % 3) * 35f; + benchSession.SetContenderPose(i, x, z, 0f); + if (benchSession.State.Contenders[i].Grid.Spec.Id != spec.Id) + { + benchSession.State.Contenders[i].Grid.SwapChassis(spec); + benchSession.SetContenderPose(i, x, z, 0f); + } + } + + var walkers = new (ContenderState C, WalkerState Ws, int Lane)[12]; + for (int i = 0; i < 12; i++) + { + var c = benchSession.State.Contenders[i]; + c.ThrottleCmd = 0.8f; + c.SteerCmd = (i % 2 == 0 ? 0.2f : -0.2f); + walkers[i] = (c, benchSession.GetWalkerState(true, c.Id)!, benchSession.GetContenderBody(c.Id)!.Value.Lane); + } + + // Warmup JIT + for (int w = 0; w < 20; w++) + { + benchSession.SetHumanInput(0, new PlayerInput(0.8f, 0.2f, 0f, 100f, false, false, false)); + benchSession.Step(); + } + + var view = benchSession.World.View; + const int benchTicks = 300; + long t0 = Stopwatch.GetTimestamp(); + for (int t = 0; t < benchTicks; t++) + { + for (int i = 0; i < 12; i++) + { + var (c, ws, lane) = walkers[i]; + var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); + var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); + var fwd = Vector3.Transform(Vector3.UnitZ, q); + fwd.Y = 0f; + fwd = fwd.LengthSquared() < 1e-4f ? Vector3.UnitZ : Vector3.Normalize(fwd); + WalkerLocomotion.StepWalker( + ws, c.Grid, benchSession.State.Terrain, view, lane, view.Mass[lane], + pos, q, vel, angVel, fwd * (c.ThrottleCmd * c.Grid.Spec.MaxSpeed), 0.3f, false, ArenaSession.FixedDt); + } + } + long t1 = Stopwatch.GetTimestamp(); + double msPerTick = (t1 - t0) * 1000.0 / Stopwatch.Frequency / benchTicks; + _output.WriteLine($"12-mech simultaneous WalkerLocomotion CPU: {msPerTick:F4} ms/tick"); + Assert.True(msPerTick < 1.5, $"12 simultaneous mechs CPU {msPerTick:F4} ms/tick exceeded 1.5 ms/tick budget"); + } + } + + [Fact] + public void HybridB_CrippledLeg_ReducesGrfAndTorque_InducesLimp() + { + Span legIntegrities = stackalloc float[4]; + foreach (var spec in new[] { Catalog.Breaker, Catalog.Bastion }) + { + using var session = new ArenaSession(seed: 17, mapKind: ArenaMapKind.Desert, slot0Human: true); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 450f + i * 16f, 450f); + } + session.SetContenderPose(0, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, spec); + Assert.True(session.TrySwapNearbyChassis(0)); + + var player = session.State.Contenders[0]; + var grid = player.Grid; + + // Strip all left-leg cells (Breaker Coronal L: y>=H-2, x 0.002f, + $"{spec.Id}: expected crippled leg asymmetry to induce measurable limp roll"); + } + } + + [Fact] + public void HybridB_AirborneMech_ZeroGrfForce() + { + foreach (var spec in new[] { Catalog.Breaker, Catalog.Manticore }) + { + using var session = new ArenaSession(seed: 7, mapKind: ArenaMapKind.Desert, slot0Human: true); + session.SetContenderPose(0, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, spec); + Assert.True(session.TrySwapNearbyChassis(0)); + + var player = session.State.Contenders[0]; + var body = session.GetContenderBody(player.Id)!.Value; + var view = session.World.View; + int lane = body.Lane; + + // 1. Direct StepWalker check with COM lifted 18m above terrain + float groundY = session.State.Terrain.SampleHeight(0f, 0f); + Vector3 liftedPos = new(view.PositionX[lane], groundY + spec.HalfHeight + 18f, view.PositionZ[lane]); + + var ws = session.GetWalkerState(true, player.Id)!; + WalkerLocomotion.StepWalker( + ws, + player.Grid, + session.State.Terrain, + view, + lane, + view.Mass[lane], + liftedPos, + new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]), + Vector3.Zero, + Vector3.Zero, + new Vector3(0f, 0f, 10f), + 0f, + false, + ArenaSession.FixedDt); + + Assert.True(ws.IsAirborne, $"{spec.Id}: expected IsAirborne == true when lifted 18m above terrain"); + Assert.Equal(Vector3.Zero, ws.LastTotalForce); + Assert.Equal(Vector3.Zero, ws.LastTotalTorque); + Assert.Equal(0f, view.ForceX[lane]); + Assert.Equal(0f, view.ForceY[lane]); + Assert.Equal(0f, view.ForceZ[lane]); + Assert.Equal(0f, view.TorqueX[lane]); + Assert.Equal(0f, view.TorqueY[lane]); + Assert.Equal(0f, view.TorqueZ[lane]); + + // 2. End-to-end ArenaSession launch into air: confirm zero GRF while airborne in real Step() + session.World.ApplyImpulse( + lane, + (0f, view.Mass[lane] * 28f, 0f), + (view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane])); + bool sawAirborneTick = false; + for (int t = 0; t < 20; t++) + { + session.SetHumanInput(0, new PlayerInput(1f, 0f, 0f, 50f, false, false, false)); + session.Step(); + if (ws.IsAirborne) + { + sawAirborneTick = true; + Assert.Equal(Vector3.Zero, ws.LastTotalForce); + Assert.Equal(Vector3.Zero, ws.LastTotalTorque); + } + } + Assert.True(sawAirborneTick, $"{spec.Id}: expected vertical launch to trigger airborne zero-GRF ticks"); + } + } + + [Fact] + public void HybridB_All7Mechs_ObeyDirectionalInputAtMultipleYaws_NoGooseStepNoDrift() + { + var specs = new[] + { + Catalog.Breaker, + Catalog.Paladin, + Catalog.Raptor, + Catalog.Spectre, + Catalog.Kestrel, + Catalog.Manticore, + Catalog.Bastion + }; + float[] yawsDeg = { 0f, 45f, 90f, 135f }; + + foreach (var spec in specs) + { + foreach (float yawDeg in yawsDeg) + { + float yawRad = yawDeg * MathF.PI / 180f; + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: true); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 500f + i * 16f, 500f); + } + + session.SetContenderPose(0, 0f, 0f, yawRad); + session.State.SpawnChassisDrop(0f, 0f, spec); + Assert.True(session.TrySwapNearbyChassis(0), $"Failed swap to {spec.Id}"); + session.SetContenderPose(0, 0f, 0f, yawRad); + var player = session.State.Contenders[0]; + + // Lettle -> Wait 5 idle ticks to verify zero rest creep from dead stop + for (int t = 0; t < 5; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false)); + session.Step(); + } + + Vector2 cmdFwd = new(MathF.Sin(yawRad), MathF.Cos(yawRad)); + Vector2 cmdRight = new(-cmdFwd.Y, cmdFwd.X); + + // 1. Hold W (Throttle = +1) for 2.0s (120 ticks) from rest + Vector2 wStart = new(player.X, player.Z); + for (int t = 0; t < 120; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: player.X + cmdFwd.X * 50f, + AimWorldZ: player.Z + cmdFwd.Y * 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + } + float endWSpeed = player.Speed; + Vector2 wDelta = new Vector2(player.X, player.Z) - wStart; + float fwdDisp = Vector2.Dot(wDelta, cmdFwd); + float latDrift = MathF.Abs(Vector2.Dot(wDelta, cmdRight)); + Assert.True(fwdDisp >= 6.0f, + $"{spec.Id} @ {yawDeg}deg W 2.0s: fwdDisp={fwdDisp:F2}m < 6.0m (lat={latDrift:F2}m)"); + Assert.True(latDrift < 2.0f, + $"{spec.Id} @ {yawDeg}deg W 2.0s: latDrift={latDrift:F2}m >= 2.0m (fwd={fwdDisp:F2}m)"); + + // 2. Release W (Throttle = 0) for 3.0s (180 ticks): stop < 0.30 m/s within physical Coulomb limit, final 1.0s (60 ticks) drift < 0.15m + float speedAt1_2s = 0f; + float speedAt2_0s = 0f; + float timeToStop = -1f; + Vector2 finalWindowStart = Vector2.Zero; + for (int t = 0; t < 180; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: player.X + cmdFwd.X * 50f, + AimWorldZ: player.Z + cmdFwd.Y * 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + if (timeToStop < 0f && player.Speed < 0.30f) + { + timeToStop = (t + 1) * ArenaSession.FixedDt; + } + if (t == 71) speedAt1_2s = player.Speed; + if (t == 119) + { + speedAt2_0s = player.Speed; + finalWindowStart = new Vector2(player.X, player.Z); + } + } + float finalDrift = (new Vector2(player.X, player.Z) - finalWindowStart).Length(); + float maxPhysStopSec = MathF.Max(1.2f, endWSpeed / 16.0f + 0.35f); + if (yawDeg == 0f) + { + _output.WriteLine( + $"{spec.Id,-10} maxSpd={spec.MaxSpeed:F1} endWSpd={endWSpeed:F2} " + + $"tStop={timeToStop:F2}s (limit={maxPhysStopSec:F2}s) spd@1.2s={speedAt1_2s:F3} spd@2.0s={speedAt2_0s:F3} finalDrift={finalDrift:F4}m"); + } + Assert.True(timeToStop > 0f && timeToStop <= maxPhysStopSec, + $"{spec.Id} @ {yawDeg}deg release W: tStop={timeToStop:F2}s > {maxPhysStopSec:F2}s (endWSpd={endWSpeed:F2}, @2.0s={speedAt2_0s:F3})"); + Assert.True(finalDrift < 0.15f, + $"{spec.Id} @ {yawDeg}deg release W: final 1.0s drift={finalDrift:F4}m >= 0.15m"); + + // 3. Hold S (Throttle = -1) for 1.5s (90 ticks) + Vector2 sStart = new(player.X, player.Z); + Vector2 revDir = new(MathF.Sin(player.Yaw), MathF.Cos(player.Yaw)); + for (int t = 0; t < 90; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: -1f, + Steer: 0f, + AimWorldX: player.X + revDir.X * 50f, + AimWorldZ: player.Z + revDir.Y * 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + } + float revDisp = Vector2.Dot(new Vector2(player.X, player.Z) - sStart, -revDir); + Assert.True(revDisp >= 3.0f, + $"{spec.Id} @ {yawDeg}deg S 1.5s: revDisp={revDisp:F2}m < 3.0m"); + + // Settle until stopped before turning test + for (int t = 0; t < 180 && (t < 20 || player.Speed > 0.05f); t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false)); + session.Step(); + } + + // 4. Hold D (Steer = +1, Throttle = 0) for 1.5s (90 ticks) + Vector2 dStart = new(player.X, player.Z); + float prevYaw = player.Yaw; + float accumYaw = 0f; + for (int t = 0; t < 90; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 0f, + Steer: 1f, + AimWorldX: player.X, + AimWorldZ: player.Z + 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + accumYaw += MatchRules.NormalizeAngle(player.Yaw - prevYaw); + prevYaw = player.Yaw; + } + float dTrans = (new Vector2(player.X, player.Z) - dStart).Length(); + // Steer = +1 turns right -> negative yaw change (-accumYaw >= 0.5 rad) + Assert.True(-accumYaw >= 0.5f, + $"{spec.Id} @ {yawDeg}deg D 1.5s: yawChange={accumYaw:F3} rad (expected <= -0.50 rad)"); + Assert.True(dTrans < 1.0f, + $"{spec.Id} @ {yawDeg}deg D 1.5s: spurious translation={dTrans:F3}m >= 1.0m"); + + if (yawDeg == 0f || yawDeg == 135f) + { + _output.WriteLine( + $"{spec.Id,-10} yaw={yawDeg,3:F0}deg: fwd={fwdDisp:F2}m lat={latDrift:F2}m " + + $"stopSpd={speedAt1_2s:F3}m/s drift={finalDrift:F4}m rev={revDisp:F2}m turn={-accumYaw:F2}rad dTrans={dTrans:F3}m"); + } + } + } + } + + [Fact] + public void HybridB_BreakerAndBastion_SionSlopeControl_ObeysInput() + { + foreach (var spec in new[] { Catalog.Breaker, Catalog.Bastion }) + { + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 900f + i * 16f, 900f); + } + + var sion = session.State.SionMap!; + // Find a clear sloped hillside on Sion (slope ~7-18 deg, free of buildings and low wall meshes along a +/-7m corridor) + float slopeX = session.State.Contenders[0].X; + float slopeZ = session.State.Contenders[0].Z; + float slopeYaw = 0f; + bool foundSlope = false; + for (float r = 40f; r <= 560f && !foundSlope; r += 20f) + { + for (int a = 0; a < 36 && !foundSlope; a++) + { + float ang = a * (MathF.Tau / 36f); + float x = MathF.Cos(ang) * r; + float z = MathF.Sin(ang) * r; + if (sion.IsInsideAnyBuildingXz(x, z, 14f)) continue; + var (nx, ny, nz) = session.State.Terrain.SampleNormal(x, z); + if (ny <= 0.992f && ny >= 0.950f) + { + float yaw = MathF.Atan2(-nx, -nz); // uphill heading + float fx = MathF.Sin(yaw); + float fz = MathF.Cos(yaw); + float rx = -fz; + float rz = fx; + bool clear = true; + foreach (float lat in new[] { -7f, 0f, 7f }) + { + float sx = x + rx * lat; + float sz = z + rz * lat; + for (float d = 0f; d < 28f; d += 4f) + { + float ax = sx + fx * d; + float az = sz + fz * d; + float bx = sx + fx * (d + 4f); + float bz = sz + fz * (d + 4f); + if (sion.IsInsideAnyBuildingXz(ax, az, 4f) || + session.State.Terrain.SampleNormal(ax, az).Ny < 0.90f) + { + clear = false; + break; + } + float gyA = session.State.Terrain.SampleHeight(ax, az); + float gyB = session.State.Terrain.SampleHeight(bx, bz); + if (!session.HasLineOfSight(ax, gyA + 2.5f, az, bx, gyB + 2.5f, bz)) + { + clear = false; + break; + } + } + if (!clear) break; + } + if (clear) + { + slopeX = x; + slopeZ = z; + slopeYaw = yaw; + foundSlope = true; + } + } + } + } + Assert.True(foundSlope, $"{spec.Id}: failed to locate clear Sion slope test site"); + + session.SetContenderPose(0, slopeX, slopeZ, slopeYaw); + session.State.SpawnChassisDrop(slopeX, slopeZ, spec); + Assert.True(session.TrySwapNearbyChassis(0), $"Failed swap to {spec.Id} on Sion"); + session.SetContenderPose(0, slopeX, slopeZ, slopeYaw); + var player = session.State.Contenders[0]; + + // 1. Drive forward up/along slope (2.0s) + Vector2 startPos = new(player.X, player.Z); + Vector2 fwdDir = new(MathF.Sin(slopeYaw), MathF.Cos(slopeYaw)); + var ws = session.GetWalkerState(true, player.Id)!; + float gStart = session.State.Terrain.SampleHeight(player.X, player.Z); + float startY = player.Y; + for (int t = 0; t < 120; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: player.X + fwdDir.X * 50f, + AimWorldZ: player.Z + fwdDir.Y * 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + } + float gEnd = session.State.Terrain.SampleHeight(player.X, player.Z); + float fwdDisp = Vector2.Dot(new Vector2(player.X, player.Z) - startPos, fwdDir); + int pLane = session.GetContenderBody(player.Id)!.Value.Lane; + string touchesStr = ""; + foreach (var tc in session.World.Facts.Touching) + { + if (tc.LaneA == pLane || tc.LaneB == pLane) + { + ulong other = tc.LaneA == pLane ? tc.StableIdB : tc.StableIdA; + touchesStr += $"{other},"; + } + } + _output.WriteLine( + $"{spec.Id} Sion slope ({slopeX:F1},{slopeZ:F1}) gStart={gStart:F2} startY={startY:F2} (H={spec.HalfHeight:F2}) -> " + + $"({player.X:F1},{player.Y:F2},{player.Z:F1}) gEnd={gEnd:F2} pYaw={player.Yaw:F2} fwdDisp={fwdDisp:F2}m air={ws.IsAirborne} force={ws.LastTotalForce} touching=[{touchesStr}]"); + Assert.True(fwdDisp >= 5.0f, $"{spec.Id} Sion slope W 2.0s: fwdDisp={fwdDisp:F2}m < 5.0m"); + + // 2. Turn cleanly on Sion slope (D for 1.5s) + float prevYaw = player.Yaw; + float accumYaw = 0f; + for (int t = 0; t < 90; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 1f, player.X, player.Z + 50f, false, false, false)); + session.Step(); + accumYaw += MatchRules.NormalizeAngle(player.Yaw - prevYaw); + prevYaw = player.Yaw; + } + Assert.True(-accumYaw >= 0.35f, $"{spec.Id} Sion slope D 1.5s: yawChange={accumYaw:F3} rad"); + + // 3. Release controls on slope (3.0s): must stop cleanly and NOT slide away + float speedAt1_2s = 0f; + float timeToStop = -1f; + Vector2 finalWinStart = Vector2.Zero; + for (int t = 0; t < 180; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false)); + session.Step(); + if (timeToStop < 0f && player.Speed < 0.35f) timeToStop = (t + 1) * ArenaSession.FixedDt; + if (t == 71) speedAt1_2s = player.Speed; + if (t == 119) finalWinStart = new Vector2(player.X, player.Z); + } + float finalSlide = (new Vector2(player.X, player.Z) - finalWinStart).Length(); + _output.WriteLine( + $"{spec.Id,-10} Sion slope ({slopeX:F1},{slopeZ:F1}): fwd={fwdDisp:F2}m turn={-accumYaw:F2}rad " + + $"tStop={timeToStop:F2}s spd@1.2s={speedAt1_2s:F3}m/s slopeSlide={finalSlide:F4}m"); + Assert.True(timeToStop > 0f && timeToStop <= 2.0f, $"{spec.Id} Sion slope release: tStop={timeToStop:F2}s > 2.0s (spd@1.2s={speedAt1_2s:F3}m/s)"); + Assert.True(finalSlide < 0.18f, $"{spec.Id} Sion slope release: 1.0s slide={finalSlide:F4}m >= 0.18m"); + } + } + + [Fact] + public void HybridB_Bastion_SteepSionHills_15To22Deg_ClimbsWithoutBeaching() + { + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 900f + i * 16f, 900f); + } + + var sion = session.State.SionMap!; + var sites = new System.Collections.Generic.List<(float X, float Z, float Yaw, float Ny)>(); + for (float r = 60f; r <= 720f && sites.Count < 3; r += 25f) + { + for (int a = 0; a < 48 && sites.Count < 3; a++) + { + float ang = a * (MathF.Tau / 48f); + float x = MathF.Cos(ang) * r; + float z = MathF.Sin(ang) * r; + if (sion.IsInsideAnyBuildingXz(x, z, 14f)) continue; + var (nx, ny, nz) = session.State.Terrain.SampleNormal(x, z); + if (ny < 0.925f || ny > 0.966f) continue; + + float yaw = MathF.Atan2(-nx, -nz); + float fx = MathF.Sin(yaw); + float fz = MathF.Cos(yaw); + float rx = -fz; + float rz = fx; + bool clear = true; + foreach (float lat in new[] { -7.5f, 0f, 7.5f }) + { + float sx = x + rx * lat; + float sz = z + rz * lat; + for (float d = 0f; d < 28f; d += 4f) + { + float ax = sx + fx * d; + float az = sz + fz * d; + float bx = sx + fx * (d + 4f); + float bz = sz + fz * (d + 4f); + if (sion.IsInsideAnyBuildingXz(ax, az, 4f) || + session.State.Terrain.SampleNormal(ax, az).Ny < 0.88f) + { + clear = false; + break; + } + float gyA = session.State.Terrain.SampleHeight(ax, az); + float gyB = session.State.Terrain.SampleHeight(bx, bz); + if (!session.HasLineOfSight(ax, gyA + 2.5f, az, bx, gyB + 2.5f, bz)) + { + clear = false; + break; + } + } + if (!clear) break; + } + if (clear && sites.TrueForAll(s => (s.X - x) * (s.X - x) + (s.Z - z) * (s.Z - z) > 60f * 60f)) + { + sites.Add((x, z, yaw, ny)); + } + } + } + Assert.NotEmpty(sites); + + session.SetContenderPose(0, sites[0].X, sites[0].Z, sites[0].Yaw); + session.State.SpawnChassisDrop(sites[0].X, sites[0].Z, Catalog.Bastion); + Assert.True(session.TrySwapNearbyChassis(0), "Failed swap to Bastion on Sion"); + var player = session.State.Contenders[0]; + + foreach (var site in sites) + { + session.SetContenderPose(0, site.X, site.Z, site.Yaw); + Vector2 startPos = new(player.X, player.Z); + Vector2 fwdDir = new(MathF.Sin(site.Yaw), MathF.Cos(site.Yaw)); + float gStart = session.State.Terrain.SampleHeight(player.X, player.Z); + + for (int t = 0; t < 120; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: player.X + fwdDir.X * 50f, + AimWorldZ: player.Z + fwdDir.Y * 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + } + + float disp2s = Vector2.Dot(new Vector2(player.X, player.Z) - startPos, fwdDir); + float endSpd = player.Speed; + float gEnd = session.State.Terrain.SampleHeight(player.X, player.Z); + var ws = session.GetWalkerState(true, player.Id)!; + _output.WriteLine( + $"Bastion Sion 15-22deg site ({site.X:F1},{site.Z:F1}) ny={site.Ny:F3}: " + + $"disp2s={disp2s:F2}m endSpd={endSpd:F2}m/s climb={(gEnd - gStart):F2}m force={ws.LastTotalForce}"); + + Assert.True(disp2s >= 10.0f, $"Bastion beached on Sion hill ny={site.Ny:F3}: disp2s={disp2s:F2}m < 10.0m"); + Assert.True(endSpd >= 6.0f, $"Bastion stalled on Sion hill ny={site.Ny:F3}: endSpd={endSpd:F2}m/s < 6.0m/s"); + } + } + + [Fact] + public void Kestrel_5x5Coronal_ArmAndEngineDamage_DoesNotCrippleLegs() + { + var grid = new ChassisGrid(Catalog.Kestrel); + Span legs = stackalloc float[4]; + + // Destroy right weapon arm (4,2),(4,3) and engine core (2,2),(2,3) + grid.Armor[4, 2] = 0f; + grid.Armor[4, 3] = 0f; + grid.Armor[2, 2] = 0f; + grid.Armor[2, 3] = 0f; + + grid.GetLegIntegrities(legs); + Assert.Equal(1.0f, legs[0], precision: 3); + Assert.Equal(1.0f, legs[1], precision: 3); + Assert.Equal(1.0f, grid.LegIntegrity, precision: 3); + + // Destroy left leg (1,4) -> only legs[0] drops + grid.Armor[1, 4] = 0f; + grid.GetLegIntegrities(legs); + Assert.True(legs[0] < 1.0f, $"Expected left leg integrity < 1.0 after (1,4) destroyed, got {legs[0]:F3}"); + Assert.Equal(1.0f, legs[1], precision: 3); + Assert.True(grid.LegIntegrity < 1.0f); + + // Destroy right leg (3,4) -> legs[1] also drops + grid.Armor[3, 4] = 0f; + grid.GetLegIntegrities(legs); + Assert.True(legs[1] < 1.0f, $"Expected right leg integrity < 1.0 after (3,4) destroyed, got {legs[1]:F3}"); + } + + [Fact] + public void DorsalWalkers_AimedShotsWithSpreadAt80m_DoNotSailOverTop() + { + foreach (var spec in new[] { Catalog.Bastion, Catalog.Manticore }) + { + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: true); + for (int i = 2; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 900f + i * 16f, 900f); + } + + // Target contender 1 on flat ground facing perpendicular so silhouette is clean + session.SetContenderPose(1, 0f, 80f, MathF.PI * 0.5f); + session.State.Contenders[1].Grid.SwapChassis(spec); + session.SetContenderPose(1, 0f, 80f, MathF.PI * 0.5f); + + // Shooter contender 0 at 80m away + session.SetContenderPose(0, 0f, 0f, 0f); + for (int t = 0; t < 45; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 80f, false, false, false)); + session.Step(); + } + + var target = session.State.Contenders[1]; + var shooter = session.State.Contenders[0]; + ulong targetStableId = ArenaSession.ContenderStableIdBase + (ulong)target.Id; + + float aimY = MatchRules.GetTargetAimY(target.Y, target.Grid.Spec.HalfHeight); + Vector3 muzzle = new(shooter.X, shooter.Y + shooter.Grid.Spec.HalfHeight * 0.25f, shooter.Z + shooter.Grid.Spec.HalfLength + 0.35f); + Vector3 baseDir = Vector3.Normalize(new Vector3(target.X - muzzle.X, aimY - muzzle.Y, target.Z - muzzle.Z)); + + var rng = new Random(12345); + const int shotCount = 250; + const float totalSpread = 0.015f; + int overTopMisses = 0; + int hits = 0; + + for (int s = 0; s < shotCount; s++) + { + float yawJitter = ((float)rng.NextDouble() * 2f - 1f) * totalSpread; + float pitchJitter = ((float)rng.NextDouble() * 2f - 1f) * (totalSpread * 0.35f); + var yawQ = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawJitter); + var rotated = Vector3.Transform(baseDir, yawQ); + var right = Vector3.Cross(rotated, Vector3.UnitY); + if (right.LengthSquared() > 1e-4f) + { + rotated = Vector3.Transform(rotated, Quaternion.CreateFromAxisAngle(Vector3.Normalize(right), pitchJitter)); + } + var dir = Vector3.Normalize(rotated); + + var hit = session.World.CastRayClosest((muzzle.X, muzzle.Y, muzzle.Z), (dir.X * 160f, dir.Y * 160f, dir.Z * 160f)); + if (hit.Hit && hit.StableId == targetStableId) + { + hits++; + } + else + { + float tPlane = (target.Z - muzzle.Z) / MathF.Max(1e-4f, dir.Z); + float yAtTarget = muzzle.Y + dir.Y * tPlane; + if (yAtTarget > target.Y) + { + overTopMisses++; + } + } + } + + float overTopRate = (float)overTopMisses / shotCount; + _output.WriteLine($"{spec.Id}: 80m hits={hits}/{shotCount}, overTopMisses={overTopMisses} ({overTopRate * 100f:F2}%)"); + Assert.True(overTopRate < 0.02f, $"{spec.Id}: over-top miss rate {overTopRate * 100f:F2}% >= 2%"); + } + } + + [Fact] + public void HybridB_BastionAndManticore_ExactSionSteepHills_ClimbWithoutBeaching() + { + var failingSites = new (string Name, float X, float Z)[] + { + ("Site#9", 459.6f, -385.7f), + ("Site#12", 413.0f, 589.8f), + ("Site#7", 0.0f, -580.0f), + ("Site#2", 360.4f, -252.4f), + }; + + foreach (var spec in new[] { Catalog.Bastion, Catalog.Manticore }) + { + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 900f + i * 16f, 900f); + } + + session.SetContenderPose(0, failingSites[0].X, failingSites[0].Z, 0f); + session.State.SpawnChassisDrop(failingSites[0].X, failingSites[0].Z, spec); + Assert.True(session.TrySwapNearbyChassis(0), $"Failed swap to {spec.Id}"); + var player = session.State.Contenders[0]; + + foreach (var site in failingSites) + { + var (nx, ny, nz) = session.State.Terrain.SampleNormal(site.X, site.Z); + float uphillYaw = MathF.Atan2(-nx, -nz); + session.SetContenderPose(0, site.X, site.Z, uphillYaw); + + Vector2 startPos = new(player.X, player.Z); + Vector2 fwdDir = new(MathF.Sin(uphillYaw), MathF.Cos(uphillYaw)); + float gStart = session.State.Terrain.SampleHeight(player.X, player.Z); + + for (int t = 0; t < 120; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: player.X + fwdDir.X * 50f, + AimWorldZ: player.Z + fwdDir.Y * 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + } + + float disp2s = Vector2.Dot(new Vector2(player.X, player.Z) - startPos, fwdDir); + float endSpd = player.Speed; + float gEnd = session.State.Terrain.SampleHeight(player.X, player.Z); + _output.WriteLine( + $"{spec.Id} {site.Name} ({site.X:F1},{site.Z:F1}) ny={ny:F3}: disp2s={disp2s:F2}m endSpd={endSpd:F2}m/s climb={(gEnd - gStart):F2}m"); + + Assert.True(disp2s >= 8.0f, $"{spec.Id} beached at {site.Name} ({site.X:F1},{site.Z:F1}) ny={ny:F3}: disp2s={disp2s:F2}m < 8.0m"); + Assert.True(endSpd >= 4.0f, $"{spec.Id} stalled at {site.Name} ({site.X:F1},{site.Z:F1}) ny={ny:F3}: endSpd={endSpd:F2}m/s < 4.0m/s"); + } + } + } + + [Fact] + public void HybridB_Bastion_StationaryFacingHill_DoesNotHyperExtendLegs() + { + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 900f + i * 16f, 900f); + } + + const float siteX = 0f; + const float siteZ = -180f; + var (nx, _, nz) = session.State.Terrain.SampleNormal(siteX, siteZ); + float uphillYaw = (nx * nx + nz * nz) > 1e-5f ? MathF.Atan2(-nx, -nz) : 0f; + + session.SetContenderPose(0, siteX, siteZ, uphillYaw); + session.State.SpawnChassisDrop(siteX, siteZ, Catalog.Bastion); + Assert.True(session.TrySwapNearbyChassis(0), "Failed swap to Bastion at Site#0"); + session.SetContenderPose(0, siteX, siteZ, uphillYaw); + + var player = session.State.Contenders[0]; + var ws = session.GetWalkerState(true, player.Id)!; + float modelRide = WalkerLocomotion.GetRideHeight(Catalog.Bastion); + float maxRelCom = 0f; + float maxReachOverflow = 0f; + + for (int t = 0; t < 120; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: player.X + MathF.Sin(uphillYaw) * 50f, + AimWorldZ: player.Z + MathF.Cos(uphillYaw) * 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + float groundY = session.State.Terrain.SampleHeight(player.X, player.Z); + float relCom = player.Y - groundY; + if (relCom > maxRelCom) + { + maxRelCom = relCom; + } + + Vector3 comPos = new(player.X, player.Y, player.Z); + Quaternion qBody = new(player.CurrRotX, player.CurrRotY, player.CurrRotZ, player.CurrRotW); + for (int leg = 0; leg < ws.Geom.LegCount; leg++) + { + Vector3 hipW = comPos + Vector3.Transform(ws.Geom.Legs[leg].HipInCom * ws.GeomScale, qBody); + Vector3 ankleW = ws.FootSole[leg] + ws.FootNormal[leg] * (ws.Geom.Legs[leg].AnkleH * ws.GeomScale); + float dist = Vector3.Distance(hipW, ankleW); + float maxReach = ws.Geom.Legs[leg].MaxLegReach * ws.GeomScale; + float overflow = dist - maxReach; + if (overflow > maxReachOverflow) + { + maxReachOverflow = overflow; + } + } + } + + _output.WriteLine($"Bastion idle Site#0: maxRelCom={maxRelCom:F3}m (ride={modelRide:F3}m) maxReachOverflow={maxReachOverflow:F4}m"); + Assert.True(maxRelCom <= modelRide + 0.25f, $"Bastion idle COM floated too high: {maxRelCom:F3}m > {modelRide + 0.25f:F3}m"); + Assert.True(maxReachOverflow <= 0.05f, $"Bastion idle leg hyper-extended past MaxLegReach by {maxReachOverflow:F4}m > 0.05m"); + } + + private static (TerrainField Terrain, float[] Heights, int GridRes, float CellSize, float MinY, float MaxY) MakeSyntheticSlope(float slopeDeg) + { + const float sizeMeters = 400f; + const int gridRes = 201; + const float cellSize = sizeMeters / (gridRes - 1); + float half = sizeMeters * 0.5f; + float tan = MathF.Tan(slopeDeg * MathF.PI / 180f); + var heights = new float[gridRes * gridRes]; + for (int iz = 0; iz < gridRes; iz++) + { + float z = -half + iz * cellSize; + float h = (z + half) * tan; + int row = iz * gridRes; + for (int ix = 0; ix < gridRes; ix++) + { + heights[row + ix] = h; + } + } + float minY = -10f; + float maxY = sizeMeters * tan + 10f; + var terrain = TerrainField.LoadHeightmap(sizeMeters, gridRes, heights, minY, maxY, seed: 1UL); + return (terrain, heights, gridRes, cellSize, minY, maxY); + } + + private static (Box3DSoaWorld World, Box3DSoaBodyHandle Body, WalkerState Walker, ChassisGrid Grid) SpawnWalkerOnSyntheticTerrain( + ChassisSpec spec, + in (TerrainField Terrain, float[] Heights, int GridRes, float CellSize, float MinY, float MaxY) syn, + float startX, + float startZ) + { + var world = new Box3DSoaWorld(capacity: 8, gravityX: 0f, gravityY: -20f, gravityZ: 0f); + float half = syn.Terrain.MapHalfExtent; + world.AddStaticHeightField( + 1UL, + (-half, 0f, -half), + syn.Heights, + syn.GridRes, + syn.GridRes, + (syn.CellSize, 1.0f, syn.CellSize), + syn.MinY, + syn.MaxY, + friction: 0.15f, + restitution: 0.0f); + + float physHalfH = ArenaSession.GetPhysicsHalfHeight(spec); + float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength; + float density = spec.MassKg / MathF.Max(0.1f, volume); + Quaternion q0 = Quaternion.Identity; + if (spec.Plane == GridPlane.Dorsal) + { + var (nx, ny, nz) = syn.Terrain.SampleNormal(startX, startZ); + Vector3 desUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, new Vector3(nx, ny, nz), 0.90f)); + Vector3 axis = Vector3.Cross(Vector3.UnitY, desUp); + if (axis.LengthSquared() > 1e-8f) + { + float ang = MathF.Min(0.295f, MathF.Acos(Math.Clamp(desUp.Y, -1f, 1f))); + q0 = Quaternion.Normalize(Quaternion.CreateFromAxisAngle(Vector3.Normalize(axis), ang)); + } + } + float spawnY = syn.Terrain.SampleHeight(startX, startZ) + WalkerLocomotion.GetRideHeight(spec); + var body = world.AddBox( + 1000UL, + (startX, spawnY, startZ), + (spec.HalfWidth, physHalfH, spec.HalfLength), + density, + (q0.X, q0.Y, q0.Z, q0.W), + friction: 0.2f, + restitution: 0.1f); + + var grid = new ChassisGrid(spec); + var ws = new WalkerState(spec); + ws.InitializePose(new Vector3(startX, spawnY, startZ), q0, world.View.Mass[body.Lane], syn.Terrain); + return (world, body, ws, grid); + } + + [Fact] + public void HybridB_All7Mechs_BoldWeightedStrides_NoTinyBabySteps() + { + var specs = new[] + { + Catalog.Breaker, + Catalog.Paladin, + Catalog.Raptor, + Catalog.Spectre, + Catalog.Kestrel, + Catalog.Manticore, + Catalog.Bastion + }; + var flat = MakeSyntheticSlope(0f); + + foreach (var spec in specs) + { + var (world, body, ws, grid) = SpawnWalkerOnSyntheticTerrain(spec, flat, 0f, -140f); + using (world) + { + int lane = body.Lane; + var view = world.View; + int nLegs = ws.Geom.LegCount; + var prevPlanted = new bool[nLegs]; + var lastPlantTime = new float[nLegs]; + for (int i = 0; i < nLegs; i++) + { + prevPlanted[i] = ws.Planted[i]; + lastPlantTime[i] = -1f; + } + + var minHipPitch = new float[nLegs]; + var maxHipPitch = new float[nLegs]; + Array.Fill(minHipPitch, float.PositiveInfinity); + Array.Fill(maxHipPitch, float.NegativeInfinity); + + double stepDurSum = 0.0; + int stepDurCount = 0; + double footSepSum = 0.0; + double swingTravelSum = 0.0; + int strideCount = 0; + + for (int t = 0; t < 180; t++) + { + var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); + var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); + + WalkerLocomotion.StepWalker( + ws, grid, flat.Terrain, view, lane, view.Mass[lane], + pos, q, vel, angVel, + new Vector3(0f, 0f, grid.Spec.MaxSpeed), 0f, false, ArenaSession.FixedDt); + world.Step(ArenaSession.FixedDt, ArenaSession.SubStepCount); + + if (t >= 60) + { + for (int i = 0; i < nLegs; i++) + { + float hp = ws.Actuators[i].Theta.HipPitch; + if (hp < minHipPitch[i]) minHipPitch[i] = hp; + if (hp > maxHipPitch[i]) maxHipPitch[i] = hp; + + bool curPlanted = ws.Planted[i]; + if (!prevPlanted[i] && curPlanted) + { + if (lastPlantTime[i] >= 0f) + { + float cycleSec = ws.SimTime - lastPlantTime[i]; + stepDurSum += cycleSec * 0.5f; + stepDurCount++; + } + lastPlantTime[i] = ws.SimTime; + + int partner = i ^ 1; + float foreAftSep = MathF.Abs(ws.FootSole[i].Z - ws.FootSole[partner].Z); + float swingTravel = Vector2.Distance( + new Vector2(ws.SwingTargetSole[i].X, ws.SwingTargetSole[i].Z), + new Vector2(ws.SwingStartSole[i].X, ws.SwingStartSole[i].Z)); + footSepSum += foreAftSep; + swingTravelSum += swingTravel; + strideCount++; + } + prevPlanted[i] = curPlanted; + } + } + else + { + for (int i = 0; i < nLegs; i++) + { + prevPlanted[i] = ws.Planted[i]; + } + } + } + + Assert.True(stepDurCount >= 2, $"{spec.Id}: expected >= 2 measured step intervals, got {stepDurCount}"); + Assert.True(strideCount >= 2, $"{spec.Id}: expected >= 2 measured strides, got {strideCount}"); + float avgStepDur = (float)(stepDurSum / stepDurCount); + float avgFootSep = (float)(footSepSum / strideCount); + float avgSwingTravel = (float)(swingTravelSum / strideCount); + float maxHipSwingRad = 0f; + for (int i = 0; i < nLegs; i++) + { + maxHipSwingRad = MathF.Max(maxHipSwingRad, maxHipPitch[i] - minHipPitch[i]); + } + + bool isCompact = spec.Id == "breaker" || spec.Id == "manticore"; + float minFootSep = isCompact ? 1.25f : 1.80f; + + _output.WriteLine( + $"{spec.Id,-10} stepDur={avgStepDur:F3}s ({1f / avgStepDur:F2} Hz) footToFoot={avgFootSep:F2}m " + + $"swingTravel={avgSwingTravel:F2}m hipPitchP2P={maxHipSwingRad:F3}rad ({maxHipSwingRad * 180f / MathF.PI:F1}deg)"); + + Assert.True(avgStepDur >= 0.21f, + $"{spec.Id}: tiny baby-step cadence {avgStepDur:F3}s < 0.21s"); + Assert.True(avgFootSep >= minFootSep, + $"{spec.Id}: foot-to-foot stride {avgFootSep:F2}m < {minFootSep:F2}m"); + Assert.True(maxHipSwingRad >= 0.45f, + $"{spec.Id}: insufficient hip-pitch actuator swing {maxHipSwingRad:F3} rad < 0.45 rad"); + } + } + } + + [Fact] + public void HybridB_All7Mechs_ClimbSmallAndMediumSlopes_6To22Deg_NeverDefeated() + { + var specs = new[] + { + Catalog.Breaker, + Catalog.Paladin, + Catalog.Raptor, + Catalog.Spectre, + Catalog.Kestrel, + Catalog.Manticore, + Catalog.Bastion + }; + float[] slopesDeg = { 6f, 12f, 18f, 22f }; + var flat = MakeSyntheticSlope(0f); + var slopeTerrains = new (float Deg, (TerrainField Terrain, float[] Heights, int GridRes, float CellSize, float MinY, float MaxY) Syn)[slopesDeg.Length]; + for (int s = 0; s < slopesDeg.Length; s++) + { + slopeTerrains[s] = (slopesDeg[s], MakeSyntheticSlope(slopesDeg[s])); + } + + foreach (var spec in specs) + { + float flatSpeed; + { + var (world, body, ws, grid) = SpawnWalkerOnSyntheticTerrain(spec, flat, 0f, -140f); + using (world) + { + int lane = body.Lane; + var view = world.View; + for (int t = 0; t < 150; t++) + { + var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); + var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); + WalkerLocomotion.StepWalker( + ws, grid, flat.Terrain, view, lane, view.Mass[lane], + pos, q, vel, angVel, + new Vector3(0f, 0f, grid.Spec.MaxSpeed), 0f, false, ArenaSession.FixedDt); + world.Step(ArenaSession.FixedDt, ArenaSession.SubStepCount); + } + flatSpeed = MathF.Sqrt(view.VelocityX[lane] * view.VelocityX[lane] + view.VelocityZ[lane] * view.VelocityZ[lane]); + } + } + + var summary = $"{spec.Id,-10} flat={flatSpeed:F2}m/s"; + foreach (var (deg, syn) in slopeTerrains) + { + var (world, body, ws, grid) = SpawnWalkerOnSyntheticTerrain(spec, syn, 0f, -140f); + using (world) + { + int lane = body.Lane; + var view = world.View; + float gStart = syn.Terrain.SampleHeight(0f, -140f); + float minSpeedAfterAccel = float.PositiveInfinity; + + for (int t = 0; t < 150; t++) + { + var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); + var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); + WalkerLocomotion.StepWalker( + ws, grid, syn.Terrain, view, lane, view.Mass[lane], + pos, q, vel, angVel, + new Vector3(0f, 0f, grid.Spec.MaxSpeed), 0f, false, ArenaSession.FixedDt); + world.Step(ArenaSession.FixedDt, ArenaSession.SubStepCount); + + if (t >= 30) + { + float fwdSpd = view.VelocityZ[lane]; + if (fwdSpd < minSpeedAfterAccel) minSpeedAfterAccel = fwdSpd; + } + } + + float endZ = view.PositionZ[lane]; + float endHorizSpeed = MathF.Sqrt(view.VelocityX[lane] * view.VelocityX[lane] + view.VelocityZ[lane] * view.VelocityZ[lane]); + float gEnd = syn.Terrain.SampleHeight(view.PositionX[lane], endZ); + float climbM = gEnd - gStart; + float dispM = endZ - (-140f); + float ratio = endHorizSpeed / MathF.Max(1f, flatSpeed); + float reqRatio = deg <= 12f ? 0.60f : 0.45f; + + summary += $" | {deg:F0}deg:{endHorizSpeed:F1}m/s({ratio * 100f:F0}%,+{climbM:F1}m,min={minSpeedAfterAccel:F1})"; + + Assert.True(dispM > 12f && climbM > 1.2f, + $"{spec.Id} @ {deg}deg: failed climb (disp={dispM:F2}m, climb={climbM:F2}m)"); + Assert.True(minSpeedAfterAccel > 4.0f, + $"{spec.Id} @ {deg}deg: stalled or kicked back (minFwdSpd={minSpeedAfterAccel:F2}m/s)"); + Assert.True(ratio >= reqRatio, + $"{spec.Id} @ {deg}deg: speed {endHorizSpeed:F2}m/s ({ratio * 100f:F1}% of flat {flatSpeed:F2}) < {reqRatio * 100f:F0}%"); + } + } + _output.WriteLine(summary); + } + } + + [Fact] + public void HybridB_All7Mechs_YawRelease_StopsCrisplyWithMinimalCoast() + { + var specs = new[] + { + Catalog.Breaker, + Catalog.Paladin, + Catalog.Raptor, + Catalog.Spectre, + Catalog.Kestrel, + Catalog.Manticore, + Catalog.Bastion + }; + + foreach (var spec in specs) + { + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: true); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 500f + i * 16f, 500f); + } + + session.SetContenderPose(0, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, spec); + Assert.True(session.TrySwapNearbyChassis(0), $"Failed swap to {spec.Id}"); + session.SetContenderPose(0, 0f, 0f, 0f); + var player = session.State.Contenders[0]; + int lane = session.GetContenderBody(player.Id)!.Value.Lane; + + // Spin 1.0s at full steer + for (int t = 0; t < 60; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 0f, + Steer: 1.0f, + AimWorldX: 0f, + AimWorldZ: 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + } + + float yawAtRelease = player.Yaw; + float spinAngVelY = session.World.View.AngularVelocityY[lane]; + float maxOvershootRad = 0f; + float angVelAt020s = 0f; + + // Release for 0.5s (30 ticks) + for (int t = 0; t < 30; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: 0f, + AimWorldZ: 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + float overshoot = MathF.Abs(MatchRules.NormalizeAngle(player.Yaw - yawAtRelease)); + if (overshoot > maxOvershootRad) + { + maxOvershootRad = overshoot; + } + if (t == 11) + { + angVelAt020s = session.World.View.AngularVelocityY[lane]; + } + } + + _output.WriteLine( + $"{spec.Id,-10} spinOmegaY={spinAngVelY:F2}rad/s overshoot={maxOvershootRad:F4}rad ({maxOvershootRad * 180f / MathF.PI:F2}deg) " + + $"omegaY@0.20s={angVelAt020s:F4}rad/s"); + + Assert.True(MathF.Abs(spinAngVelY) > 1.0f, + $"{spec.Id}: failed to spin up before release (omegaY={spinAngVelY:F2})"); + Assert.True(maxOvershootRad <= 0.08f, + $"{spec.Id}: yaw coast overshoot {maxOvershootRad:F4} rad ({maxOvershootRad * 180f / MathF.PI:F2} deg) > 0.08 rad"); + Assert.True(MathF.Abs(angVelAt020s) <= 0.05f, + $"{spec.Id}: residual yaw angVel@0.20s={angVelAt020s:F4} rad/s > 0.05 rad/s"); + } + } + } +} diff --git a/tests/RustToDust.Tests/LobbyAndDirectoryTests.cs b/tests/RustToDust.Tests/LobbyAndDirectoryTests.cs new file mode 100644 index 0000000..85693eb --- /dev/null +++ b/tests/RustToDust.Tests/LobbyAndDirectoryTests.cs @@ -0,0 +1,836 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Net.Sockets; +using System.Numerics; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using GameCult.Networking; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using RustToDust.Core; +using RustToDust.DirectoryService; +using RustToDust.Net; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class LobbyAndDirectoryTests + { + private static async Task<(WebApplication App, string BaseUrl)> StartDirectoryServerAsync(DirectoryRegistryOptions? options = null) + { + var opts = options ?? new DirectoryRegistryOptions(); + var app = DirectoryApp.Build(Array.Empty(), opts); + app.Urls.Clear(); + app.Urls.Add("http://127.0.0.1:0"); + await app.StartAsync(); + string baseUrl = app.Urls.First(); + return (app, baseUrl); + } + + private static void PumpHostAndClients(ServerMatchHost host, params RemoteArenaSession[] clients) + { + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + host.StepOnce(nowMs); + for (int i = 0; i < clients.Length; i++) + { + clients[i].PumpNetwork(nowMs); + } + } + + private static void PumpListenHostAndClient(ListenHostArenaSession listenHost, RemoteArenaSession client, int ticks = 1) + { + for (int i = 0; i < ticks; i++) + { + listenHost.SubmitLocalInput(default, isPhysicsTick: true); + client.PumpNetwork(); + Thread.Sleep(2); + } + } + + [Fact] + public async Task Directory_Heartbeat_LeaseTokenSecrecy_AuthRejection_LoopbackSpoof_And_TtlExpiry() + { + var now = DateTimeOffset.UtcNow; + var opts = new DirectoryRegistryOptions + { + EntryTtl = TimeSpan.FromMilliseconds(350), + ReaperInterval = TimeSpan.FromMilliseconds(60), + UtcNow = () => now + }; + + var (app, baseUrl) = await StartDirectoryServerAsync(opts); + try + { + using var http = new HttpClient { BaseAddress = new Uri(baseUrl) }; + + // 1. Register with empty publicHost behind simulated nginx X-Real-IP -> auto-resolves to caller IP + using var regReq = new HttpRequestMessage(HttpMethod.Post, "/api/v1/servers/heartbeat") + { + Content = JsonContent.Create(new DirectoryHeartbeatRequest + { + Name = "Yggdrasil Ring", + PublicHost = "", + UdpPort = 3076, + Map = "sion", + Seed = 77, + Humans = 2, + MaxHumans = 12, + Phase = "Lobby", + Wave = 0 + }) + }; + regReq.Headers.TryAddWithoutValidation("X-Real-IP", "203.0.113.42"); + using var regResp = await http.SendAsync(regReq); + Assert.Equal(HttpStatusCode.OK, regResp.StatusCode); + + var ack = await regResp.Content.ReadFromJsonAsync(); + Assert.NotNull(ack); + Assert.NotEqual(Guid.Empty, ack!.ServerId); + Assert.False(string.IsNullOrWhiteSpace(ack.LeaseToken)); + Assert.True(ack.TtlSeconds >= 1); + + // 2. GET /api/v1/servers returns resolved publicHost and NEVER exposes leaseToken + string rawListJson = await http.GetStringAsync("/api/v1/servers"); + Assert.DoesNotContain(ack.LeaseToken, rawListJson, StringComparison.Ordinal); + + var list = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http); + Assert.Single(list); + Assert.Equal(ack.ServerId, list[0].ServerId); + Assert.Equal("203.0.113.42", list[0].PublicHost); + Assert.Equal("sion", list[0].Map); + Assert.Equal("Lobby", list[0].Phase); + + // 3. Non-loopback X-Real-IP attempting to spoof loopback publicHost is rejected (400) + foreach (string spoofHost in new[] { "127.0.0.1", "localhost", "::1" }) + { + using var spoofReq = new HttpRequestMessage(HttpMethod.Post, "/api/v1/servers/heartbeat") + { + Content = JsonContent.Create(new DirectoryHeartbeatRequest + { + Name = "Spoofed", + PublicHost = spoofHost, + UdpPort = 3076 + }) + }; + spoofReq.Headers.TryAddWithoutValidation("X-Real-IP", "203.0.113.42"); + using var spoofResp = await http.SendAsync(spoofReq); + Assert.Equal(HttpStatusCode.BadRequest, spoofResp.StatusCode); + } + + // 4. Wrong leaseToken on refresh -> 403, entry stays intact + using var badRefresh = await http.PostAsJsonAsync("/api/v1/servers/heartbeat", new DirectoryHeartbeatRequest + { + ServerId = ack.ServerId, + LeaseToken = "wrong-token-value", + Name = "Hijacked", + PublicHost = "203.0.113.42", + UdpPort = 3076 + }); + Assert.Equal(HttpStatusCode.Forbidden, badRefresh.StatusCode); + + // 5. Wrong leaseToken on DELETE -> 403, entry stays intact + using var badDeleteReq = new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/servers/{ack.ServerId}"); + badDeleteReq.Headers.TryAddWithoutValidation("X-Lease-Token", "wrong-token-value"); + using var badDeleteResp = await http.SendAsync(badDeleteReq); + Assert.Equal(HttpStatusCode.Forbidden, badDeleteResp.StatusCode); + + var stillPresent = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http); + Assert.Single(stillPresent); + Assert.Equal("Yggdrasil Ring", stillPresent[0].Name); + + // 6. Valid leaseToken refresh succeeds and keeps entry alive + using var goodRefresh = await http.PostAsJsonAsync("/api/v1/servers/heartbeat", new DirectoryHeartbeatRequest + { + ServerId = ack.ServerId, + LeaseToken = ack.LeaseToken, + Name = "Yggdrasil Ring Updated", + PublicHost = "203.0.113.42", + UdpPort = 3076, + Humans = 5, + Phase = "Active", + Wave = 1 + }); + Assert.Equal(HttpStatusCode.OK, goodRefresh.StatusCode); + + // 7. Advance clock past TTL -> entry expires cleanly and disappears + now = now + TimeSpan.FromMilliseconds(500); + await Task.Delay(150); + var afterExpiry = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http); + Assert.Empty(afterExpiry); + } + finally + { + await app.StopAsync(); + await app.DisposeAsync(); + } + } + + [Fact] + public async Task DirectoryReporter_Registers_Updates_And_DeregistersOnDispose() + { + var (app, baseUrl) = await StartDirectoryServerAsync(); + try + { + int humans = 1; + string phase = "Lobby"; + + var reporter = new DirectoryReporter( + baseUrl, + () => new DirectoryHeartbeatSnapshot( + "Reporter Test Ring", + "127.0.0.1", + 3079, + "desert", + 42, + humans, + 12, + phase, + 0), + heartbeatInterval: TimeSpan.FromSeconds(30)); + + try + { + var deadline = DateTime.UtcNow.AddSeconds(15); + IReadOnlyList servers = Array.Empty(); + while (DateTime.UtcNow < deadline) + { + servers = await DirectoryBrowserClient.FetchServersAsync(baseUrl); + if (servers.Count > 0) break; + await Task.Delay(25); + } + + Assert.Single(servers); + Assert.Equal("Reporter Test Ring", servers[0].Name); + Assert.Equal(1, servers[0].Humans); + + humans = 4; + phase = "Active"; + reporter.NotifyChanged(); + + deadline = DateTime.UtcNow.AddSeconds(15); + while (DateTime.UtcNow < deadline) + { + servers = await DirectoryBrowserClient.FetchServersAsync(baseUrl); + if (servers.Count == 1 && servers[0].Humans == 4 && servers[0].Phase == "Active") break; + await Task.Delay(25); + } + Assert.Equal(4, servers[0].Humans); + Assert.Equal("Active", servers[0].Phase); + } + finally + { + await reporter.DisposeAsync(); + } + + var afterDispose = await DirectoryBrowserClient.FetchServersAsync(baseUrl); + Assert.Empty(afterDispose); + } + finally + { + await app.StopAsync(); + await app.DisposeAsync(); + } + } + + [Fact] + public async Task StatelessUdpPing_CoexistsWithActiveRemoteSession_AndHandlesMalformedPingsSafely() + { + using var host = new ServerMatchHost( + IPAddress.Loopback, + 0, + seed: 77, + mapKind: ArenaMapKind.Desert, + serverName: "Ping Coexistence Arena", + startInLobby: false); + using var client = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "ProbePilot"); + + var joinDeadline = DateTime.UtcNow.AddSeconds(3); + while (!client.IsJoined && DateTime.UtcNow < joinDeadline) + { + PumpHostAndClients(host, client); + await Task.Delay(5); + } + Assert.True(client.IsJoined); + + // Drive and fire concurrently on the active RUDP session while probing RTDP pings + for (int i = 0; i < 15; i++) + { + client.SubmitLocalInput(new PlayerInput(1f, 0.25f, 30f, 40f, Fire: true, InteractPickup: false, Brake: false), isPhysicsTick: true); + PumpHostAndClients(host, client); + } + + var target = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + var pingTask = Task.Run(async () => + { + var results = new List(4); + for (int i = 0; i < 4; i++) + { + results.Add(await ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2))); + } + return results; + }); + + while (!pingTask.IsCompleted) + { + client.SubmitLocalInput(new PlayerInput(0.8f, -0.1f, 25f, 35f, Fire: true, InteractPickup: false, Brake: false), isPhysicsTick: true); + PumpHostAndClients(host, client); + await Task.Delay(3); + } + + var pingResults = await pingTask; + Assert.Equal(4, pingResults.Count); + foreach (var r in pingResults) + { + Assert.True(r.Success, "Expected stateless RTDP ping to succeed alongside active RUDP session"); + Assert.True(r.Summary.HasValue); + Assert.Equal("Ping Coexistence Arena", r.Summary!.Value.ServerName); + Assert.Equal(1, r.Summary.Value.Humans); + Assert.Equal(12, r.Summary.Value.MaxHumans); + Assert.Equal(MatchPhase.Active, r.Summary.Value.Phase); + Assert.Equal(ArenaMapKind.Desert, r.Summary.Value.MapKind); + Assert.Equal(77, r.Summary.Value.Seed); + Assert.True(r.Summary.Value.AcceptingJoin); + Assert.True(SnapshotCodec.EncodePong(r.Summary.Value).Length < 110); + } + + Assert.Equal(0, host.TransportPacketsDropped); + Assert.True(client.ConnectionStatus.Connected); + + // Send truncated "RTDP" packet (< 16B) and bogus magic packet; host must not crash or drop RUDP peer + using (var rawSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) + { + byte[] truncatedPing = Encoding.ASCII.GetBytes("RTDP\x01\x01short"); // 11 bytes + rawSock.SendTo(truncatedPing, target); + for (int i = 0; i < 4; i++) + { + PumpHostAndClients(host, client); + await Task.Delay(2); + } + Assert.Equal(0, host.TransportPacketsDropped); + + byte[] bogusMagic = Encoding.ASCII.GetBytes("JUNK_NOT_RTDP_OR_CNR0_PAYLOAD_DATA"); + rawSock.SendTo(bogusMagic, target); + for (int i = 0; i < 4; i++) + { + PumpHostAndClients(host, client); + await Task.Delay(2); + } + } + + Assert.True(client.IsJoined); + Assert.True(client.ConnectionStatus.Connected); + + // Valid ping still succeeds after malformed datagrams + var finalPingTask = ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2)); + while (!finalPingTask.IsCompleted) + { + PumpHostAndClients(host, client); + await Task.Delay(2); + } + var finalPing = await finalPingTask; + Assert.True(finalPing.Success); + } + + [Fact] + public void Lobby_NonHostConfigAndStartRejected_AndLocalOutcomeIsActive() + { + using var listenHost = new ListenHostArenaSession( + IPAddress.Loopback, + 0, + seed: 42, + mapKind: ArenaMapKind.Desert, + startInLobby: true, + serverName: "Host Authority Lobby"); + using var client = new RemoteArenaSession( + new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort), + "Guest"); + + var joinDeadline = DateTime.UtcNow.AddSeconds(3); + while (!client.IsJoined && DateTime.UtcNow < joinDeadline) + { + PumpListenHostAndClient(listenHost, client); + } + Assert.True(client.IsJoined); + + Assert.Equal(MatchPhase.Lobby, listenHost.ViewState.Phase); + Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase); + Assert.Equal(ClientMatchOutcome.Active, listenHost.LocalOutcome); + Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome); + + // Guest attempts unauthorized config change and launch + Assert.True(client.RequestLobbyConfig(999, ArenaMapKind.Sion)); + Assert.True(client.RequestLobbyStart()); + PumpListenHostAndClient(listenHost, client, ticks: 15); + + Assert.Equal(MatchPhase.Lobby, listenHost.ViewState.Phase); + Assert.Equal(ArenaMapKind.Desert, listenHost.ViewState.MapKind); + Assert.Equal(42, listenHost.ViewState.Seed); + Assert.Null(listenHost.LobbyState?.CountdownSeconds); + Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase); + Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome); + } + + [Fact] + public void Lobby_CountdownStartsWhenAllReady_CancelsOnUnready_AndResetsOnMapSwitch() + { + using var host = new ServerMatchHost( + IPAddress.Loopback, + 0, + seed: 42, + mapKind: ArenaMapKind.Desert, + allowClientReset: true, + startInLobby: true, + minHumansToStart: 2); + using var peerA = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Alpha"); + using var peerB = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Bravo"); + + var deadline = DateTime.UtcNow.AddSeconds(3); + while ((!peerA.IsJoined || !peerB.IsJoined) && DateTime.UtcNow < deadline) + { + PumpHostAndClients(host, peerA, peerB); + Thread.Sleep(3); + } + Assert.True(peerA.IsJoined); + Assert.True(peerB.IsJoined); + + // Peer A readies up; Peer B not ready -> no countdown yet + Assert.True(peerA.SetLobbyReady(true)); + for (int i = 0; i < 10; i++) + { + PumpHostAndClients(host, peerA, peerB); + Thread.Sleep(2); + } + Assert.Null(host.Lobby?.CountdownSeconds); + + // Peer B readies up -> countdown starts + Assert.True(peerB.SetLobbyReady(true)); + for (int i = 0; i < 15; i++) + { + PumpHostAndClients(host, peerA, peerB); + Thread.Sleep(2); + } + Assert.NotNull(host.Lobby?.CountdownSeconds); + Assert.True(host.Lobby!.CountdownSeconds!.Value > 0f && host.Lobby.CountdownSeconds.Value < 5.0f); + Assert.NotNull(peerA.LobbyState?.CountdownSeconds); + + // Peer B un-readies -> countdown cancels and Wave 0 does NOT launch + Assert.True(peerB.SetLobbyReady(false)); + for (int i = 0; i < 15; i++) + { + PumpHostAndClients(host, peerA, peerB); + Thread.Sleep(2); + } + Assert.Null(host.Lobby?.CountdownSeconds); + Assert.Null(peerA.LobbyState?.CountdownSeconds); + Assert.Equal(MatchPhase.Lobby, host.Session.State.Phase); + Assert.Empty(host.Session.State.OrbitalDrop.ActivePods); + + // Authorized config switch in Lobby resets ready flags and syncs all peers + Assert.True(peerA.SetLobbyReady(true)); + for (int i = 0; i < 6; i++) + { + PumpHostAndClients(host, peerA, peerB); + Thread.Sleep(2); + } + + Assert.True(host.ConfigureLobby(peerA.LocalContenderId, 99, ArenaMapKind.Sion)); + for (int i = 0; i < 15; i++) + { + PumpHostAndClients(host, peerA, peerB); + Thread.Sleep(2); + } + + Assert.Equal(MatchPhase.Lobby, host.Session.State.Phase); + Assert.Equal(ArenaMapKind.Sion, host.Session.State.MapKind); + Assert.Equal(99, host.Session.State.Seed); + Assert.Equal(ArenaMapKind.Sion, peerA.ViewState.MapKind); + Assert.Equal(99, peerA.ViewState.Seed); + Assert.Equal(ArenaMapKind.Sion, peerB.ViewState.MapKind); + Assert.Equal(99, peerB.ViewState.Seed); + Assert.All(host.Lobby!.Slots.Where(s => s.IsHuman), s => Assert.False(s.IsReady)); + Assert.Equal(ClientMatchOutcome.Active, peerA.LocalOutcome); + Assert.Equal(ClientMatchOutcome.Active, peerB.LocalOutcome); + } + + [Fact] + public void Lobby_IdleClientKeptAlivePastIdleTimeout_WithActiveOutcome() + { + using var host = new ServerMatchHost( + IPAddress.Loopback, + 0, + seed: 42, + mapKind: ArenaMapKind.Desert, + startInLobby: true); + using var client = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "IdlePilot"); + + long simNowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + for (int i = 0; i < 100 && !client.IsJoined; i++) + { + simNowMs += 20; + host.StepOnce(simNowMs); + client.PumpNetwork(simNowMs); + Thread.Sleep(2); + } + Assert.True(client.IsJoined); + + // Advance 8.5 seconds (> IdleTimeoutMs 5000ms and > ClientDisconnectTimeoutMs 6000ms) with ZERO SubmitLocalInput + for (int step = 0; step < 170; step++) + { + simNowMs += 50; + host.StepOnce(simNowMs); + client.PumpNetwork(simNowMs); + } + + Assert.True(client.IsJoined); + Assert.True(client.ConnectionStatus.Connected); + Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome); + Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase); + Assert.Equal(1, host.ConnectedHumanCount); + } + + [Fact] + public void Lobby_SynchronizedLaunch_TransitionsToActiveAndDropsWave0AcrossHostAndRemote() + { + using var listenHost = new ListenHostArenaSession( + IPAddress.Loopback, + 0, + seed: 42, + mapKind: ArenaMapKind.Desert, + startInLobby: true, + minHumansToStart: 2); + using var remote = new RemoteArenaSession( + new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort), + "DropMate"); + + var deadline = DateTime.UtcNow.AddSeconds(3); + while (!remote.IsJoined && DateTime.UtcNow < deadline) + { + PumpListenHostAndClient(listenHost, remote); + } + Assert.True(remote.IsJoined); + + Assert.True(listenHost.SetLobbyReady(true)); + Assert.True(remote.SetLobbyReady(true)); + + // Step 320 ticks (~5.33s at 60Hz) so the 5.0s countdown completes cleanly + for (int tick = 0; tick < 330; tick++) + { + listenHost.SubmitLocalInput(default, isPhysicsTick: true); + remote.PumpNetwork(); + if (listenHost.ViewState.Phase == MatchPhase.Active && + remote.ViewState.Phase == MatchPhase.Active && + remote.ActivePods.Count > 0) + { + break; + } + Thread.Sleep(1); + } + + // Pump a few extra frames to ensure all Wave 0 reliable events arrive on remote + PumpListenHostAndClient(listenHost, remote, ticks: 10); + + Assert.Equal(MatchPhase.Active, listenHost.ViewState.Phase); + Assert.Equal(MatchPhase.Active, remote.ViewState.Phase); + Assert.Equal(ClientMatchOutcome.Active, listenHost.LocalOutcome); + Assert.Equal(ClientMatchOutcome.Active, remote.LocalOutcome); + + Assert.True(listenHost.ActivePods.Count >= MatchState.ContenderCount); + Assert.Equal(ContenderLifecycle.Deploying, listenHost.LocalContender.Lifecycle); + Assert.Equal(ContenderLifecycle.Deploying, remote.LocalContender.Lifecycle); + Assert.Contains(remote.ActivePods, p => p.PodKind == OrbitalPodKind.Contender && p.ContenderId == remote.LocalContenderId); + + var remoteEvents = new List(); + remote.DrainSimEvents(remoteEvents); + Assert.Contains(remoteEvents, e => e is MatchStartedEvent); + } + + [Fact] + public void CorePvs_RoundTripsMatchPhaseLobby_Within1152Bytes() + { + var state = new MatchState(seed: 42, ArenaMapKind.Desert, startInLobby: true); + var local = state.Contenders[0]; + local.Grid.SwapChassis(Catalog.Bastion); + + var contenders = new List(12); + var walkers = new List(12); + var specs = new List(10); + + for (int i = 0; i < 12; i++) + { + contenders.Add(new NetContenderState + { + SlotId = (byte)i, + Alive = true, + IsHuman = i < 2, + Lifecycle = ContenderLifecycle.Deploying, + Pos = new Vector3(i * 10f, 3f, -i * 5f), + Rot = Quaternion.Identity, + Vel = Vector3.Zero, + CoreHpRatio = 1f + }); + var ws = new WalkerVisualSnapshot { LegCount = 4 }; + walkers.Add(new NetWalkerEntry { IsContender = true, EntityId = (byte)i, Snapshot = ws }); + } + + byte[] payload = SnapshotCodec.EncodeCorePvs( + 1, 5, 10, 0f, 0, 0, 772f, MatchPhase.Lobby, null, 0, 0xFFF, + local, Vector3.Zero, contenders, walkers, specs); + byte[] wireFrame = SnapshotCodec.WrapLatest(payload, 1, 5); + byte[] rudpDatagram = CultNetRudpPacketCodec.Encode(new CultNetRudpPacket + { + ConnectionId = 0x52544431, + PacketType = CultNetRudpPacketType.Data, + ChannelId = SnapshotCodec.ChannelLatest, + Sequence = 5, + Sequenced = true, + Payload = wireFrame + }); + + Assert.True(rudpDatagram.Length <= SnapshotCodec.MaxLatestDatagramBytes, + $"Lobby CorePvs UDP datagram {rudpDatagram.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); + + Assert.True(SnapshotCodec.TryDecodeCorePvs(payload, out var decoded)); + Assert.Equal(MatchPhase.Lobby, decoded.Phase); + Assert.Null(decoded.WinnerContenderId); + + // Also verify Completed + WinnerContenderId still round-trips via bit 2 (0x04) + byte[] completedPayload = SnapshotCodec.EncodeCorePvs( + 1, 6, 12, 100f, 0, 0, 120f, MatchPhase.Completed, 3, 0, 0xFFF, + local, Vector3.Zero, contenders, walkers, specs); + Assert.True(SnapshotCodec.TryDecodeCorePvs(completedPayload, out var decodedCompleted)); + Assert.Equal(MatchPhase.Completed, decodedCompleted.Phase); + Assert.Equal(3, decodedCompleted.WinnerContenderId); + } + + [Fact] + public async Task StatelessUdpPing_HandlesMultiByteUtf8ServerName_WithoutOverflow() + { + string multiByteName = new string('\u2022', 24); + using var host = new ServerMatchHost( + IPAddress.Loopback, + 0, + seed: 77, + mapKind: ArenaMapKind.Desert, + serverName: multiByteName, + startInLobby: true); + + var target = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + var pingTask = ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2)); + while (!pingTask.IsCompleted) + { + host.PollStatelessPings(); + await Task.Delay(5); + } + + var res = await pingTask; + Assert.True(res.Success); + Assert.NotNull(res.Summary); + Assert.Equal(new string('\u2022', 16), res.Summary!.Value.ServerName); + } + + [Fact] + public void LobbySquadSwap_ReliableRoundTrip() + { + using var listenHost = new ListenHostArenaSession( + IPAddress.Loopback, + 0, + seed: 42, + mapKind: ArenaMapKind.Desert, + startInLobby: true, + minHumansToStart: 2, + squadSize: 3); + using var remote = new RemoteArenaSession( + new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort), + "WingBuddy"); + + var deadline = DateTime.UtcNow.AddSeconds(3); + while (!remote.IsJoined && DateTime.UtcNow < deadline) + { + PumpListenHostAndClient(listenHost, remote); + } + Assert.True(remote.IsJoined); + int remoteId = remote.LocalContenderId; + + Assert.Equal((byte)3, listenHost.LobbyState?.SquadSize); + Assert.Equal((byte)3, remote.LobbyState?.SquadSize); + Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId); + + // 1. Remote client swaps to Squad 2 -> swaps cleanly with an AI in Squad 2 + Assert.True(remote.RequestLobbySquad(2)); + PumpListenHostAndClient(listenHost, remote, ticks: 15); + Assert.Equal((byte)2, listenHost.LobbyState!.Slots[remoteId].SquadId); + Assert.Equal((byte)2, remote.LobbyState!.Slots[remoteId].SquadId); + + // 2. Host switches SquadMode to Duos (2) -> slots regroup cleanly to 2-player squads + Assert.True(listenHost.RequestLobbyConfig(77, ArenaMapKind.Desert, 2)); + PumpListenHostAndClient(listenHost, remote, ticks: 15); + Assert.Equal((byte)2, listenHost.LobbyState!.SquadSize); + Assert.Equal((byte)2, remote.LobbyState!.SquadSize); + Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId); + + // 3. Remote swaps to Squad 3, then back to Squad 0 (Host's Duo), both ready up & launch! + Assert.True(remote.RequestLobbySquad(3)); + PumpListenHostAndClient(listenHost, remote, ticks: 15); + Assert.Equal((byte)3, remote.LobbyState!.Slots[remoteId].SquadId); + + Assert.True(remote.RequestLobbySquad(0)); + PumpListenHostAndClient(listenHost, remote, ticks: 15); + Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId); + + Assert.True(listenHost.SetLobbyReady(true)); + Assert.True(remote.SetLobbyReady(true)); + for (int tick = 0; tick < 340; tick++) + { + listenHost.SubmitLocalInput(default, isPhysicsTick: true); + remote.PumpNetwork(); + if (listenHost.ViewState.Phase == MatchPhase.Active && + remote.ViewState.Phase == MatchPhase.Active && + remote.ActivePods.Count > 0) + { + break; + } + Thread.Sleep(1); + } + PumpListenHostAndClient(listenHost, remote, ticks: 10); + + Assert.Equal(MatchPhase.Active, listenHost.ViewState.Phase); + Assert.Equal(MatchPhase.Active, remote.ViewState.Phase); + Assert.Equal((byte)2, listenHost.ViewState.SquadSize); + Assert.Equal((byte)2, remote.ViewState.SquadSize); + Assert.Equal(0, listenHost.ViewState.Contenders[remoteId].SquadId); + Assert.Equal(0, remote.ViewState.Contenders[remoteId].SquadId); + Assert.True(listenHost.ViewState.AreAllies(0, remoteId)); + Assert.True(remote.ViewState.AreAllies(0, remoteId)); + } + + [Fact] + public void LobbySquadSwap_MidMatchReconnectAndLateJoin_PreservesAll12SquadIdsOutsidePvs() + { + using var host = new ServerMatchHost( + IPAddress.Loopback, + 0, + seed: 42, + mapKind: ArenaMapKind.Desert, + startInLobby: true, + minHumansToStart: 1, + squadSize: 3); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var clientA = new RemoteArenaSession(ep, "LeaderSwap"); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var deadline = DateTime.UtcNow.AddSeconds(3); + while (!clientA.IsJoined && DateTime.UtcNow < deadline) + { + nowMs += 16; + host.StepOnce(nowMs); + clientA.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.True(clientA.IsJoined); + int slotA = clientA.LocalContenderId; + Assert.Equal(0, slotA); + + // Polish check: out-of-range TargetSquadId >= maxSquads (4 for SquadSize=3) must be rejected, not clamped + Assert.False(host.MovePeerToSquad(slotA, 4)); + Assert.Equal((byte)0, host.Session.State.Contenders[slotA].SquadId); + + // Swap Slot 0 (0 -> 2) and Slot 6 (2 -> 0) in Lobby (SquadSize = 3) + Assert.True(clientA.RequestLobbySquad(2)); + for (int t = 0; t < 20; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + clientA.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.Equal((byte)2, host.Session.State.Contenders[0].SquadId); + Assert.Equal((byte)0, host.Session.State.Contenders[6].SquadId); + + // Launch to MatchPhase.Active + Assert.True(host.SetLobbyReady(slotA, true)); + for (int tick = 0; tick < 340; tick++) + { + nowMs += 16; + host.StepOnce(nowMs); + clientA.PumpNetwork(nowMs); + if (host.Session.State.Phase == MatchPhase.Active && clientA.ViewState.Phase == MatchPhase.Active) + { + break; + } + Thread.Sleep(1); + } + Assert.Equal(MatchPhase.Active, host.Session.State.Phase); + + // Position contenders far apart across Desert so non-allies (including Slot 6) are outside PVS + host.Session.SetContenderPose(0, -320f, -320f, 0f); + for (int i = 1; i < MatchState.ContenderCount; i++) + { + if (host.Session.State.AreAllies(0, i)) + { + host.Session.SetContenderPose(i, -310f + i * 3f, -320f, 0f); + } + else + { + host.Session.SetContenderPose(i, 320f, 320f - i * 8f, MathF.PI); + } + } + nowMs += 16; + host.StepOnce(nowMs); + Assert.False(host.Session.IsEntityInPeerPvs(0, true, 6)); + + // 1. Reconnect clientA mid-match and assert ALL 12 SquadIds and AreAllies match server 12/12 + Guid tokenA = clientA.ReconnectToken; + clientA.DisconnectGracefully("ReconnectSquadTest"); + clientA.Dispose(); + for (int t = 0; t < 20; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + Thread.Sleep(1); + } + + using var clientARejoin = new RemoteArenaSession(ep, "LeaderSwap", tokenA); + deadline = DateTime.UtcNow.AddSeconds(3); + while (!clientARejoin.IsJoined && DateTime.UtcNow < deadline) + { + nowMs += 16; + host.StepOnce(nowMs); + clientARejoin.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.True(clientARejoin.IsJoined); + Assert.Equal(0, clientARejoin.LocalContenderId); + + // 2. Late-join a fresh clientB mid-match while non-allies are outside PVS + using var clientB = new RemoteArenaSession(ep, "LateJoiner"); + deadline = DateTime.UtcNow.AddSeconds(3); + while (!clientB.IsJoined && DateTime.UtcNow < deadline) + { + nowMs += 16; + host.StepOnce(nowMs); + clientARejoin.PumpNetwork(nowMs); + clientB.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.True(clientB.IsJoined); + + var serverState = host.Session.State; + for (int i = 0; i < MatchState.ContenderCount; i++) + { + Assert.Equal(serverState.Contenders[i].SquadId, clientARejoin.ViewState.Contenders[i].SquadId); + Assert.Equal(serverState.Contenders[i].SquadId, clientB.ViewState.Contenders[i].SquadId); + for (int j = 0; j < MatchState.ContenderCount; j++) + { + Assert.Equal(serverState.AreAllies(i, j), clientARejoin.ViewState.AreAllies(i, j)); + Assert.Equal(serverState.AreAllies(i, j), clientB.ViewState.AreAllies(i, j)); + } + } + } + } +} diff --git a/tests/RustToDust.Tests/MultiplayerSimulationTests.cs b/tests/RustToDust.Tests/MultiplayerSimulationTests.cs new file mode 100644 index 0000000..a2da7fc --- /dev/null +++ b/tests/RustToDust.Tests/MultiplayerSimulationTests.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class MultiplayerSimulationTests + { + [Fact] + public void TwoHumanSlots_DriveFireSwapAndMatchPhaseStaysActiveUntilSoleSurvivor() + { + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: false); + session.SetHumanSlot(0, true, "Alpha"); + session.SetHumanSlot(5, true, "Bravo"); + + Assert.True(session.State.Contenders[0].IsHuman); + Assert.True(session.State.Contenders[5].IsHuman); + Assert.False(session.State.Contenders[1].IsHuman); + + var h0 = session.State.Contenders[0]; + var h5 = session.State.Contenders[5]; + session.SetContenderPose(0, -30f, 0f, 0f); + session.SetContenderPose(5, 30f, 0f, 0f); + + // Place Rival 2 in open LOS for h0, and behind tall mesa or far away from h5 + session.SetContenderPose(2, -30f, 55f, MathF.PI); + + float h0StartZ = h0.Z; + float h5StartZ = h5.Z; + + var events = new List(); + for (int t = 0; t < 45; t++) + { + session.SetHumanInput(0, new PlayerInput(1f, 0f, -30f, 55f, Fire: true, InteractPickup: false, Brake: false)); + session.SetHumanInput(5, new PlayerInput(-1f, 0.3f, 30f, -50f, Fire: false, InteractPickup: false, Brake: false)); + session.Step(); + session.DrainStepEvents(events); + } + + Assert.True(h0.Z > h0StartZ + 3f, $"Human 0 should drive forward independently, deltaZ={h0.Z - h0StartZ:F2}"); + Assert.True(h5.Z < h5StartZ - 2f, $"Human 5 should reverse independently, deltaZ={h5.Z - h5StartZ:F2}"); + Assert.Contains(events, e => e is ShotFiredEvent sf && !sf.IsSpectatorShooter && sf.ShooterId == 0); + Assert.Contains(events, e => e is HitImpactEvent hi && hi.IsContenderShooter && hi.ShooterId == 0 && hi.ArmorDamage > 0f); + + // Kill slot 0 -> match MUST stay Active while multiple contenders remain! + h0.Grid.ApplyHit(0f, 0f, 0.5f, 50000f, 0f); + Assert.False(h0.Alive); + MatchRules.UpdateMatchOutcome(session.State); + Assert.Equal(MatchPhase.Active, session.State.Phase); + + // Kill all contenders except slot 5 -> MatchPhase becomes Completed and WinnerContenderId == 5! + for (int i = 0; i < session.State.Contenders.Count; i++) + { + if (i != 5 && session.State.Contenders[i].Alive) + { + session.State.Contenders[i].Grid.ApplyHit(0f, 0f, 0.5f, 50000f, 0f); + } + } + MatchRules.UpdateMatchOutcome(session.State); + Assert.Equal(MatchPhase.Completed, session.State.Phase); + Assert.Equal(5, session.State.WinnerContenderId); + } + + [Fact] + public void PerObserverDetectionIsolation_Human0SeesRivalWhileOccludedHuman5DoesNot() + { + using var session = new ArenaSession(seed: 12, mapKind: ArenaMapKind.Desert, slot0Human: false, skipInitialDrop: true); + session.SetHumanSlot(0, true, "Alpha"); + session.SetHumanSlot(5, true, "Bravo"); + + var box = session.State.ArenaCoverBoxes[0]; + var h0 = session.State.Contenders[0]; + var h5 = session.State.Contenders[5]; + var rival = session.State.Contenders[2]; + + // Move others far away + for (int i = 0; i < session.State.Contenders.Count; i++) + { + if (i != 0 && i != 5 && i != 2) + { + session.SetContenderPose(i, -650f + i * 12f, -650f); + } + } + + // Place h0 and rival on same open side of cover wall; place h5 behind cover wall + session.SetContenderPose(h0.Id, box.X - 10f, box.Z - box.HalfZ - 12f, 0f); + session.SetContenderPose(rival.Id, box.X + 4f, box.Z - box.HalfZ - 12f, 0f); + session.SetContenderPose(h5.Id, box.X + 4f, box.Z + box.HalfZ + 8f, 0f); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, rival.X, rival.Z, false, false, true)); + session.SetHumanInput(5, new PlayerInput(0f, 0f, h5.X, h5.Z, false, false, true)); + session.Step(); + + var obs0 = session.State.ObserverStates[0]; + var obs5 = session.State.ObserverStates[5]; + + Assert.True(obs0.ContenderContacts[rival.Id].VisibleToPlayer); + Assert.False(obs5.ContenderContacts[rival.Id].VisibleToPlayer); + Assert.False(MatchState.IsContactOnRadar(obs5.ContenderContacts[rival.Id])); + Assert.Equal(0, obs5.DetectedByCount); + } + + [Fact] + public void LocalArenaSession_ImplementsUnifiedClientBoundary() + { + using var local = new LocalArenaSession(seed: 42, ArenaMapKind.Desert, "TestSolo"); + Assert.Equal(0, local.LocalContenderId); + Assert.Equal("TestSolo", local.LocalContender.Name); + Assert.Equal(ClientMatchOutcome.Active, local.LocalOutcome); + Assert.Equal(NetworkMode.Solo, local.ConnectionStatus.Mode); + + float startZ = local.LocalContender.Z; + for (int t = 0; t < 30; t++) + { + local.SubmitLocalInput(new PlayerInput(1f, 0f, local.LocalContender.X, local.LocalContender.Z + 50f, false, false, false), isPhysicsTick: true); + } + + var (pos, _, _) = local.GetInterpolatedContenderPose(0, 1f); + Assert.NotEqual(startZ, pos.Z); + } + } +} diff --git a/tests/RustToDust.Tests/OrbitalDropTests.cs b/tests/RustToDust.Tests/OrbitalDropTests.cs new file mode 100644 index 0000000..e61278e --- /dev/null +++ b/tests/RustToDust.Tests/OrbitalDropTests.cs @@ -0,0 +1,1633 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Numerics; +using System.Threading; +using GameCult.Networking; +using RustToDust.Core; +using RustToDust.Net; +using RustToDust.Ymir; +using Xunit; +using Xunit.Abstractions; + +namespace RustToDust.Tests +{ + public sealed class OrbitalDropTests + { + private readonly ITestOutputHelper _output; + + public OrbitalDropTests(ITestOutputHelper output) + { + _output = output; + } + + [Fact] + public void HoverSlam_FlatDesertAnd30DegSionSlope_TouchdownUnder3MsAndZeroPenetration() + { + // 1. Flat Desert trajectory & cross-range steering + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true); + var player = session.State.Contenders[0]; + float startX = player.X; + float startZ = player.Z; + // Steer straight across the arena center so boundary clamp does not reverse heading + float dirLen = MathF.Max(1f, MathF.Sqrt(startX * startX + startZ * startZ)); + float dirX = -startX / dirLen; + float dirZ = -startZ / dirLen; + + int maxTicks = 1200; + float impactSpeed = -1f; + float touchTime = -1f; + float snapDiffAtTouchdown = float.NaN; + session.State.ContenderPodTouchedDown += c => + { + if (c.Id == 0) + { + snapDiffAtTouchdown = MathF.Abs(c.PrevY - c.Y); + } + }; + for (int t = 0; t < maxTicks; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 1.0f, + Steer: 0f, + AimWorldX: player.X + dirX * 100f, + AimWorldZ: player.Z + dirZ * 100f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + if (player.IsGroundedActive) + { + touchTime = session.State.Time; + var tdEvent = session.State.PodEvents.LastOrDefault(e => + e.Kind == DropPodEventKind.PodTouchdownBlowPetals && e.ContenderId == 0); + impactSpeed = MathF.Abs(tdEvent.VelY); + break; + } + } + + Assert.True(player.IsGroundedActive, "Player pod failed to touch down within 20s on Desert"); + Assert.InRange(impactSpeed, 0.5f, 2.49f); + Assert.InRange(touchTime, 12.5f, 18.0f); + + float glideDist = MathF.Sqrt((player.X - startX) * (player.X - startX) + (player.Z - startZ) * (player.Z - startZ)); + Assert.True(glideDist >= 800f, $"Expected cross-arena Desert glide >= 800m, got {glideDist:F1}m"); + + // Verify PrevY == Y right at touchdown SnapPreviousPose() and continuous post-Step settlement (< 0.06m, zero sky pop) + Assert.True(snapDiffAtTouchdown < 1e-4f, + $"Expected SnapPreviousPose clean right at touchdown: diff={snapDiffAtTouchdown:F6}"); + Assert.True(MathF.Abs(player.PrevY - player.Y) < 0.06f, + $"Expected smooth 1-tick settlement post-touchdown: PrevY={player.PrevY:F5}, Y={player.Y:F5}"); + AssertZeroChassisPenetration(session.State, player); + _output.WriteLine($"Desert flat glide: touchTime={touchTime:F2}s, impactSpeed={impactSpeed:F2} m/s, glide={glideDist:F1}m"); + } + + // 2. ~30 deg Sion mountain slope (uphill + downhill) + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + + // Find a steep Sion mountain slope spot (~25-33 deg, Ny in [0.83, 0.90]) outside buildings + float slopeX = 0f; + float slopeZ = 0f; + float bestDiff = float.PositiveInfinity; + float targetNy = MathF.Cos(30f * MathF.PI / 180f); // ~0.866 + for (float z = -1200f; z <= 1200f; z += 24f) + { + for (float x = -1200f; x <= 1200f; x += 24f) + { + if (sion.IsInsideAnyBuildingXz(x, z, 14f)) continue; + var (_, ny, _) = session.State.Terrain.SampleNormal(x, z); + if (ny >= 0.80f && ny <= 0.91f) + { + float diff = MathF.Abs(ny - targetNy); + if (diff < bestDiff) + { + bestDiff = diff; + slopeX = x; + slopeZ = z; + } + } + } + } + Assert.True(bestDiff < 0.08f, "Expected to find a ~30 deg Sion slope test site"); + + var (snx, sny, snz) = session.State.Terrain.SampleNormal(slopeX, slopeZ); + float slopeDeg = MathF.Acos(Math.Clamp(sny, -1f, 1f)) * (180f / MathF.PI); + + // Test launching pod directly above slope with uphill lateral input + var c = session.State.Contenders[1]; + float uphillYaw = MathF.Atan2(-snx, -snz); + var pod = session.State.OrbitalDrop.LaunchContenderPod( + c, waveIndex: 0, slopeX, slopeZ, uphillYaw, session.QueryDropSurface, isRespawn: false); + pod.AllowFlatRoofLanding = false; + + float snapDiffAtTouchdown = float.NaN; + session.State.ContenderPodTouchedDown += tc => + { + if (tc.Id == c.Id) snapDiffAtTouchdown = MathF.Abs(tc.PrevY - tc.Y); + }; + + float impactSpeed = -1f; + for (int t = 0; t < 2000; t++) + { + pod.LookForwardX = -snx; + pod.LookForwardZ = -snz; + pod.SteerForwardCmd = 0.8f; + session.Step(); + if (c.IsGroundedActive) + { + var td = session.State.PodEvents.Last(e => + e.Kind == DropPodEventKind.PodTouchdownBlowPetals && e.PodId == pod.PodId); + impactSpeed = MathF.Abs(td.VelY); + break; + } + } + + Assert.True(c.IsGroundedActive, $"Pod failed to land on {slopeDeg:F1} deg Sion slope"); + Assert.InRange(impactSpeed, 0.5f, 2.49f); + Assert.True(snapDiffAtTouchdown < 1e-4f); + Assert.True(MathF.Abs(c.PrevY - c.Y) < 0.06f); + AssertZeroChassisPenetration(session.State, c); + _output.WriteLine($"Sion {slopeDeg:F1} deg slope: impactSpeed={impactSpeed:F2} m/s, terrainY={session.State.Terrain.SampleHeight(c.X, c.Z):F2}, chassisY={c.Y:F2}"); + } + } + + [Fact] + public void Wave0_GearPodsTouchDownAheadOfContenders_Around3Point3Seconds() + { + foreach (var map in new[] { ArenaMapKind.Desert, ArenaMapKind.Sion }) + { + using var session = new ArenaSession(seed: 42, map, slot0Human: true); + Assert.True(session.State.OrbitalDrop.ActivePods.Count >= 52, + $"Expected 12 contender + 40 gear pods at t=0, got {session.State.OrbitalDrop.ActivePods.Count}"); + Assert.Empty(session.State.GroundDrops); + + float maxGearTouchTime = 0f; + float minContenderTouchTime = float.PositiveInfinity; + + for (int t = 0; t < 2000; t++) + { + session.Step(); + if (session.State.OrbitalDrop.ActivePods.Count == 0) + { + break; + } + } + + Assert.Empty(session.State.OrbitalDrop.ActivePods); + Assert.True(session.State.GroundDrops.Count >= 40, + $"Expected >= 40 GroundDrops after Wave 0, got {session.State.GroundDrops.Count}"); + Assert.Equal(40, session.State.PodEvents.Count(e => + e.Kind == DropPodEventKind.PodTouchdownBlowPetals && e.PodKind != OrbitalPodKind.Contender)); + + foreach (var ev in session.State.PodEvents) + { + if (ev.Kind != DropPodEventKind.PodTouchdownBlowPetals) continue; + // Use Wave 0 launch time (0s) and PodEvents order/timestamps via simulation + } + + // Re-measure exact per-pod FlightTime on a MatchState sweep + var state = new MatchState(seed: 42, map); + var gearTouchTimes = new List(); + var contenderTouchTimes = new List(); + for (int t = 0; t < 2000; t++) + { + state.Time += ArenaSession.FixedDt; + state.OrbitalDrop.Step(ArenaSession.FixedDt, state.DefaultDropSurfaceQuery, (pod, _) => + { + if (pod.PodKind == OrbitalPodKind.Contender) contenderTouchTimes.Add(pod.FlightTime); + else gearTouchTimes.Add(pod.FlightTime); + }); + } + + maxGearTouchTime = gearTouchTimes.Max(); + minContenderTouchTime = contenderTouchTimes.Min(); + float lead = minContenderTouchTime - maxGearTouchTime; + _output.WriteLine($"{map}: maxGearTouch={maxGearTouchTime:F2}s, minContenderTouch={minContenderTouchTime:F2}s, lead={lead:F2}s"); + + Assert.Equal(40, gearTouchTimes.Count); + Assert.Equal(12, contenderTouchTimes.Count); + Assert.InRange(lead, 2.5f, 4.2f); + } + } + + [Fact] + public void Sion64TargetSweep_ZeroBuildingInteriorLandings_AndZeroHoverStalls() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + + // Pick 64 targets deliberately across Old Town dense buildings (center & towers) + valley + var rng = new Random(101); + int tested = 0; + int buildingOverTargets = 0; + float worstTouchTime = 0f; + float worstImpactSpeed = 0f; + + for (int i = 0; i < 64; i++) + { + float tx; + float tz; + if (i < 32) + { + // Aim directly onto real Sion building rooftops in Old Town & towers to stress deflection! + var b = sion.Buildings[(i * 71) % sion.Buildings.Count]; + tx = Math.Clamp(b.CenterX, -1350f, 1350f); + tz = Math.Clamp(b.CenterZ, -1350f, 1350f); + buildingOverTargets++; + } + else + { + tx = (float)(rng.NextDouble() * 1800.0 - 900.0); + tz = (float)(rng.NextDouble() * 1800.0 - 900.0); + } + + var pod = session.State.OrbitalDrop.LaunchGearPod(0, tx, tz, null, Catalog.Autocannon, session.QueryDropSurface); + bool landed = false; + for (int t = 0; t < 1800; t++) + { + bool touched = OrbitalDropKinematics.StepPod( + pod, + ArenaSession.FixedDt, + session.State.Terrain, + session.QueryDropSurface, + session.State.FindClearDropPoint, + out _, + out var touchSample); + if (touched) + { + landed = true; + worstTouchTime = MathF.Max(worstTouchTime, pod.FlightTime); + worstImpactSpeed = MathF.Max(worstImpactSpeed, pod.TouchdownSpeed); + var skyCheck = session.QueryDropSurface(pod.X, pod.Z, 0f, 500f); + Assert.False(skyCheck.IsBuildingRoof, + $"Target #{i} ({tx:F1},{tz:F1}) landed inside solid Sion building at ({pod.X:F1},{pod.Z:F1})!"); + Assert.False(touchSample.IsInsideSolidBuilding, + $"Target #{i} ({tx:F1},{tz:F1}) landed with IsInsideSolidBuilding=true at ({pod.X:F1},{pod.Z:F1})!"); + Assert.False(touchSample.IsBuildingRoof); + Assert.InRange(pod.TouchdownSpeed, 0.5f, 2.5f); + break; + } + } + Assert.True(landed, $"Target #{i} ({tx:F1},{tz:F1}) hover-stalled!"); + Assert.True(pod.FlightTime <= 28.0f, $"Target #{i} took too long: {pod.FlightTime:F2}s"); + tested++; + } + + _output.WriteLine($"Sion 64-target sweep ({buildingOverTargets} directly over buildings): {tested}/64 clear street landings, maxFlight={worstTouchTime:F2}s, maxImpact={worstImpactSpeed:F2} m/s"); + } + + [Fact] + public void SionHumanPod_FlatRoofValidLanding_AndSkyscraperLateralWallGuard() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + + // 1. Find a tall wide flat-roofed Sion building (HalfX >= 7m, HalfZ >= 7m, height >= 10m) + SionBuildingAabb? flatRoofBldg = null; + for (int i = 0; i < sion.Buildings.Count; i++) + { + var b = sion.Buildings[i]; + if (b.Class == "Gebaeude Einzelhaus" && + b.HalfX >= 7f && b.HalfZ >= 7f && + (b.RoofY - b.GroundY) >= 10f && + MathF.Abs(b.CenterX) < 800f && MathF.Abs(b.CenterZ) < 800f) + { + var sample = session.QueryDropSurface(b.CenterX, b.CenterZ, 1.65f, b.RoofY + 20f); + if (sample.IsBuildingRoof && sample.IsFlatRoofValid) + { + flatRoofBldg = b; + break; + } + } + } + Assert.NotNull(flatRoofBldg); + var fr = flatRoofBldg!.Value; + + // Land human player pod on that flat roof and verify driving on roof works! + var player = session.State.Contenders[0]; + var roofPod = session.State.OrbitalDrop.LaunchContenderPod( + player, 0, fr.CenterX, fr.CenterZ, 0f, session.QueryDropSurface, isRespawn: false); + roofPod.AllowFlatRoofLanding = true; + + for (int t = 0; t < 2000 && !player.IsGroundedActive; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 20f, false, false, false)); + session.Step(); + } + + Assert.True(player.IsGroundedActive); + Assert.True(player.TouchdownOnRoof); + float terrainUnder = session.State.Terrain.SampleHeight(player.X, player.Z); + Assert.True(player.Y > terrainUnder + 6f, $"Expected player seated on roof above terrain ({player.Y:F2} > {terrainUnder + 6f:F2})"); + + // Drive forward slightly on roof -> stays supported on roof (doesn't fall through roof) + float yStartOnRoof = player.Y; + for (int t = 0; t < 20; t++) + { + session.SetHumanInput(0, new PlayerInput(0.4f, 0f, player.X, player.Z + 20f, false, false, false)); + session.Step(); + } + Assert.True(player.Y >= yStartOnRoof - 0.6f, $"Player sank through flat Sion roof: {yStartOnRoof:F2} -> {player.Y:F2}"); + + // 2. Lateral Building Wall Guard: steer straight into a tall Sion building face at mid-height + SionBuildingAabb? tallBldg = null; + for (int i = 0; i < sion.Buildings.Count; i++) + { + var b = sion.Buildings[i]; + if ((b.RoofY - b.GroundY) >= 22f && MathF.Abs(b.CenterX) < 900f && MathF.Abs(b.CenterZ) < 900f) + { + if (!sion.IsInsideAnyBuildingXz(b.CenterX, b.CenterZ - b.HalfZ - 12f, 3f)) + { + tallBldg = b; + break; + } + } + } + Assert.NotNull(tallBldg); + var tb = tallBldg!.Value; + + var c2 = session.State.Contenders[2]; + c2.IsHuman = true; + float wallStartX = tb.CenterX; + float wallStartZ = tb.CenterZ - tb.HalfZ - 10f; + var wallPod = session.State.OrbitalDrop.LaunchContenderPod( + c2, 0, wallStartX, wallStartZ, 0f, session.QueryDropSurface, isRespawn: false); + // Position pod below roof height (~mid-wall) with high speed straight into the building wall + wallPod.Y = tb.GroundY + (tb.RoofY - tb.GroundY) * 0.5f + 45f; + wallPod.VelY = -30f; + + for (int t = 0; t < 360 && !c2.IsGroundedActive; t++) + { + session.SetHumanInput(c2.Id, new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: tb.CenterX, + AimWorldZ: tb.CenterZ + 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + if (wallPod.Phase != OrbitalPodPhase.Popped && wallPod.Y < tb.RoofY - 1.0f) + { + Assert.False(sion.IsInsideAnyBuildingXz(wallPod.X, wallPod.Z, 0f), + $"Pod clipped laterally inside tall building {tb.Id} at y={wallPod.Y:F1}m (roof={tb.RoofY:F1}m)"); + } + } + + Assert.True(c2.IsGroundedActive, "Pod stalled against building wall"); + Assert.False(sion.IsInsideAnyBuildingXz(c2.X, c2.Z, 0f), "Pod ended inside tall building interior!"); + _output.WriteLine($"Wall guard verified against {tb.Id} (height={tb.RoofY - tb.GroundY:F1}m): landed outside at ({c2.X:F1}, {c2.Z:F1})"); + } + + [Fact] + public void Wave1To3Respawns_AndFinalRingCutoff_CompletesMatchCleanly() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true); + var state = session.State; + var player = state.Contenders[0]; + + // Step until Wave 0 contenders touch down (~15s on Desert) + for (int t = 0; t < 1200 && !state.Contenders.All(c => c.IsGroundedActive); t++) + { + session.Step(); + } + Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive)); + + // 1. Kill 11 AIs at t = 20s -> must enter WaitingForRespawnWave and match stays Active! + while (state.Time < 20f) + { + session.Step(); + } + for (int i = 1; i < state.Contenders.Count; i++) + { + session.ForceEliminateContender(i); + } + MatchRules.UpdateMatchOutcome(state); + Assert.Equal(MatchPhase.Active, state.Phase); + for (int i = 1; i < state.Contenders.Count; i++) + { + Assert.Equal(ContenderLifecycle.WaitingForRespawnWave, state.Contenders[i].Lifecycle); + Assert.True(state.Contenders[i].WaitingForRespawn); + } + + // 2. Step past Wave 1 (t = 85s) + drop time -> all 11 AIs re-drop in stock Jackals with RespawnsRemaining == 0! + while (state.Time < 85.5f) + { + session.Step(); + } + Assert.Equal(1, state.OrbitalDrop.CurrentWaveIndex); + for (int i = 1; i < state.Contenders.Count; i++) + { + Assert.Equal(ContenderLifecycle.Deploying, state.Contenders[i].Lifecycle); + Assert.Equal(0, state.Contenders[i].RespawnsRemaining); + Assert.Equal(Catalog.Jackal.Id, state.Contenders[i].Grid.Spec.Id); + } + for (int t = 0; t < 1200; t++) + { + session.Step(); + if (state.Contenders.All(c => c.IsGroundedActive)) break; + } + Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive)); + + // 3. Kill Player before Wave 2 (t = 130s) -> match MUST stay Active (Player.WaitingForRespawn == true) + while (state.Time < 130f) + { + session.Step(); + } + session.ForceEliminateContender(0); + MatchRules.UpdateMatchOutcome(state); + + Assert.Equal(MatchPhase.Active, state.Phase); + Assert.True(player.WaitingForRespawn); + + // Step past Wave 2 (t = 165s) -> Player re-drops in stock Jackal (RespawnsRemaining == 0), RespawnCutoffReached == true! + while (state.Time < 165.5f) + { + session.Step(); + } + Assert.Equal(2, state.OrbitalDrop.CurrentWaveIndex); + Assert.True(state.OrbitalDrop.RespawnCutoffReached); + Assert.Equal(ContenderLifecycle.Deploying, player.Lifecycle); + Assert.Equal(0, player.RespawnsRemaining); + + // 4. Kill an AI at t = 168.1s (after Wave 2 cutoff) -> immediately Eliminated (never WaitingForRespawnWave)! + while (state.Time < 168.1f) + { + session.Step(); + } + var aiLate = state.Contenders[1]; + session.ForceEliminateContender(1); + Assert.Equal(ContenderLifecycle.Eliminated, aiLate.Lifecycle); + + // Kill all remaining rivals after cutoff -> MatchPhase becomes Completed, WinnerContenderId == 0! + for (int i = 2; i < state.Contenders.Count; i++) + { + session.ForceEliminateContender(i); + } + MatchRules.UpdateMatchOutcome(state); + Assert.Equal(MatchPhase.Completed, state.Phase); + Assert.Equal(0, state.WinnerContenderId); + + // 5. Verify SetContenderPose mid-drop cleanly cancels active pod + using var midDropSession = new ArenaSession(seed: 77, ArenaMapKind.Desert, slot0Human: true); + Assert.True(midDropSession.State.Contenders[0].IsInDropPod); + midDropSession.SetContenderPose(0, 15f, -20f, 0.5f); + Assert.True(midDropSession.State.Contenders[0].IsGroundedActive); + Assert.Null(midDropSession.State.Contenders[0].ActivePodId); + Assert.DoesNotContain(midDropSession.State.OrbitalDrop.ActivePods, + p => p.PodKind == OrbitalPodKind.Contender && p.ContenderId == 0); + } + + [Fact] + public void NetworkSync_Wave0OrbitalPods_ReplicateUnder1152ByteUdpCap() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var client = new RemoteArenaSession(ep, "DropPilot"); + IClientArenaSession clientIface = client; + + int maxUdpBytes = 0; + int latestPacketsSeen = 0; + client.DebugInboundLatestDropFilter = payload => + { + byte[] frame = SnapshotCodec.WrapLatest(payload, host.MatchGeneration, (uint)(latestPacketsSeen + 1)); + byte[] udp = CultNetRudpPacketCodec.Encode(new CultNetRudpPacket + { + PacketType = CultNetRudpPacketType.Data, + ConnectionId = 0x52544431, + Sequence = (uint)(latestPacketsSeen + 1), + ChannelId = SnapshotCodec.ChannelLatest, + Sequenced = true, + Payload = frame + }); + maxUdpBytes = Math.Max(maxUdpBytes, udp.Length); + latestPacketsSeen++; + return false; + }; + + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var deadline = DateTimeOffset.UtcNow.AddSeconds(3); + while (DateTimeOffset.UtcNow < deadline && !client.IsJoined) + { + nowMs += 16; + host.StepOnce(nowMs); + client.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.True(client.IsJoined); + Assert.True(clientIface.LocalContender.IsInDropPod); + Assert.True(clientIface.ActivePods.Count >= 12, + $"Expected active Wave 0 pods on RemoteArenaSession join, got {clientIface.ActivePods.Count}"); + + // Step through full Wave 0 orbital drop (~15.1s = 905 ticks) with steering input + var simEvents = new List(); + for (int t = 0; t < 1100; t++) + { + nowMs += 16; + clientIface.SubmitLocalInput(new PlayerInput( + Throttle: 0.7f, + Steer: 0f, + AimWorldX: clientIface.LocalContender.X, + AimWorldZ: clientIface.LocalContender.Z + 50f, + Fire: false, + InteractPickup: false, + Brake: false), isPhysicsTick: true); + host.StepOnce(nowMs); + client.PumpNetwork(nowMs); + clientIface.DrainSimEvents(simEvents); + if (clientIface.LocalContender.IsGroundedActive && + host.Session.State.Contenders[clientIface.LocalContenderId].IsGroundedActive) + { + break; + } + } + + Assert.True(latestPacketsSeen > 10); + Assert.True(maxUdpBytes > 0 && maxUdpBytes <= SnapshotCodec.MaxLatestDatagramBytes, + $"UDP latest datagram exceeded {SnapshotCodec.MaxLatestDatagramBytes}B cap: max={maxUdpBytes}B"); + Assert.True(clientIface.LocalContender.IsGroundedActive, + $"Expected RemoteArenaSession LocalContender grounded after drop, lifecycle={clientIface.LocalContender.Lifecycle}"); + Assert.Contains(simEvents, e => e is DropPodEvent dpe && dpe.Kind == (byte)DropPodEventKind.PodTouchdownBlowPetals && dpe.ContenderId == clientIface.LocalContenderId); + + _output.WriteLine($"Network orbital drop: maxUdpBytes={maxUdpBytes}B (cap {SnapshotCodec.MaxLatestDatagramBytes}B), packets={latestPacketsSeen}, podEvents={simEvents.OfType().Count()}"); + } + + [Fact] + public void RemoteArenaSession_Wave0Pods_AdvanceSmoothlyAndZeroGhostPodsAfterTouchdown() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var client = new RemoteArenaSession(ep, "SionDropPilot"); + IClientArenaSession clientIface = client; + + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var deadline = DateTimeOffset.UtcNow.AddSeconds(4); + while (DateTimeOffset.UtcNow < deadline && !client.IsJoined) + { + nowMs += 16; + host.StepOnce(nowMs); + client.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.True(client.IsJoined); + Assert.True(clientIface.LocalContender.IsInDropPod); + + var initialLocalPod = clientIface.ActivePods.FirstOrDefault( + p => p.PodKind == OrbitalPodKind.Contender && p.ContenderId == clientIface.LocalContenderId); + var initialGearPod = clientIface.ActivePods.FirstOrDefault(p => p.PodKind != OrbitalPodKind.Contender); + Assert.NotNull(initialLocalPod); + Assert.NotNull(initialGearPod); + + float localY0 = initialLocalPod!.Y; + float localAgl0 = initialLocalPod.LastAgl; + int trackedGearId = initialGearPod!.PodId; + float gearY0 = initialGearPod.Y; + float gearAgl0 = initialGearPod.LastAgl; + Assert.True(localAgl0 > 50f, $"Expected initialized local LastAgl > 50m, got {localAgl0:F2}"); + Assert.True(gearAgl0 > 50f, $"Expected initialized gear LastAgl > 50m, got {gearAgl0:F2}"); + + // Step 60 ticks (1.0s) and verify BOTH local pod and replicated gear pods descend smoothly and update LastAgl + for (int t = 0; t < 60; t++) + { + nowMs += 16; + clientIface.SubmitLocalInput(new PlayerInput( + Throttle: 0.4f, + Steer: 0f, + AimWorldX: clientIface.LocalContender.X, + AimWorldZ: clientIface.LocalContender.Z + 50f, + Fire: false, + InteractPickup: false, + Brake: false), isPhysicsTick: true); + host.StepOnce(nowMs); + client.PumpNetwork(nowMs); + clientIface.BeginRenderFrame(ArenaSession.FixedDt, 1.0f); + } + + var midLocalPod = clientIface.ActivePods.FirstOrDefault( + p => p.PodKind == OrbitalPodKind.Contender && p.ContenderId == clientIface.LocalContenderId); + var midGearPod = clientIface.ActivePods.FirstOrDefault(p => p.PodId == trackedGearId); + Assert.NotNull(midLocalPod); + Assert.NotNull(midGearPod); + Assert.True(midLocalPod!.Y < localY0 - 15f, $"Local pod froze on client: {localY0:F2} -> {midLocalPod.Y:F2}"); + Assert.True(midLocalPod.LastAgl < localAgl0 - 15f && midLocalPod.LastAgl > 0f, + $"Local pod LastAgl failed to update: {localAgl0:F2} -> {midLocalPod.LastAgl:F2}"); + Assert.True(midGearPod!.Y < gearY0 - 20f, $"Gear pod froze on client: {gearY0:F2} -> {midGearPod.Y:F2}"); + Assert.True(midGearPod.LastAgl < gearAgl0 - 20f && midGearPod.LastAgl > 0f, + $"Gear pod LastAgl failed to update: {gearAgl0:F2} -> {midGearPod.LastAgl:F2}"); + + // Step through remainder of Wave 0 + 30 settle ticks so all pods touch down across Sion PVS (~27.6s = 1658 ticks) + var simEvents = new List(); + for (int t = 0; t < 1900; t++) + { + nowMs += 16; + clientIface.SubmitLocalInput(new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: clientIface.LocalContender.X, + AimWorldZ: clientIface.LocalContender.Z + 50f, + Fire: false, + InteractPickup: false, + Brake: false), isPhysicsTick: true); + host.StepOnce(nowMs); + client.PumpNetwork(nowMs); + clientIface.BeginRenderFrame(ArenaSession.FixedDt, 1.0f); + clientIface.DrainSimEvents(simEvents); + } + + Assert.True(clientIface.LocalContender.IsGroundedActive, + $"Expected LocalContender grounded after Wave 0, lifecycle={clientIface.LocalContender.Lifecycle}"); + Assert.Empty(host.Session.State.OrbitalDrop.ActivePods); + Assert.Empty(clientIface.ActivePods); + _output.WriteLine($"Sion net Wave 0: local {localY0:F1}->{midLocalPod.Y:F1}, gear {gearY0:F1}->{midGearPod.Y:F1}, final ActivePods={clientIface.ActivePods.Count}"); + } + + [Fact] + public void RemoteArenaSession_Wave1Respawn_ReplicatesResetJackalChassisToLocalClient() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var client = new RemoteArenaSession(ep, "RespawnPilot"); + IClientArenaSession clientIface = client; + + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var deadline = DateTimeOffset.UtcNow.AddSeconds(4); + while (DateTimeOffset.UtcNow < deadline && !client.IsJoined) + { + nowMs += 16; + host.StepOnce(nowMs); + client.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.True(client.IsJoined); + int localId = clientIface.LocalContenderId; + + void PumpStep(int ticks) + { + var evs = new List(); + for (int t = 0; t < ticks; t++) + { + nowMs += 16; + clientIface.SubmitLocalInput(new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: clientIface.LocalContender.X, + AimWorldZ: clientIface.LocalContender.Z + 50f, + Fire: false, + InteractPickup: false, + Brake: false), isPhysicsTick: true); + host.StepOnce(nowMs); + client.PumpNetwork(nowMs); + clientIface.BeginRenderFrame(ArenaSession.FixedDt, 1.0f); + clientIface.DrainSimEvents(evs); + } + } + + // 1. Land Wave 0 + for (int i = 0; i < 1100 && !clientIface.LocalContender.IsGroundedActive; i++) + { + PumpStep(1); + } + Assert.True(clientIface.LocalContender.IsGroundedActive); + + // 2. Swap local player to Paladin on server and replicate to client + var serverLocal = host.Session.State.Contenders[localId]; + host.Session.State.SpawnChassisDrop(serverLocal.X, serverLocal.Z, Catalog.Paladin); + Assert.True(host.Session.TrySwapNearbyChassis(localId)); + PumpStep(12); + Assert.Equal(Catalog.Paladin.Id, clientIface.LocalContender.Grid.Spec.Id); + + // 3. Eliminate local player -> WaitingForRespawnWave + host.Session.ForceEliminateContender(localId); + PumpStep(12); + Assert.Equal(ContenderLifecycle.WaitingForRespawnWave, clientIface.LocalContender.Lifecycle); + + // 4. Advance past Wave 1 (85.0s) -> server resets local player to Jackal (256/256) and launches Wave 1 pod + host.Session.State.Time = 84.85f; + PumpStep(30); + + Assert.Equal(ContenderLifecycle.Deploying, clientIface.LocalContender.Lifecycle); + Assert.Equal(Catalog.Jackal.Id, clientIface.LocalContender.Grid.Spec.Id); + Assert.Equal(256f, clientIface.LocalContender.Grid.MaxCoreHp); + Assert.Equal(256f, clientIface.LocalContender.Grid.CoreHp); + _output.WriteLine($"Wave 1 respawn replicated: chassis={clientIface.LocalContender.Grid.Spec.Id}, core={clientIface.LocalContender.Grid.CoreHp}/{clientIface.LocalContender.Grid.MaxCoreHp}"); + } + + [Fact] + public void SionQueryDropSurface_1mOutsideBuildingWall_DoesNotReturnPhantomRoofAbovePod() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + + var alleySpots = new List<(SionBuildingAabb Bldg, float X, float Z)>(); + for (int i = 0; i < sion.Buildings.Count && alleySpots.Count < 10; i++) + { + var b = sion.Buildings[i]; + if ((b.RoofY - b.GroundY) < 8f || MathF.Abs(b.CenterX) > 1000f || MathF.Abs(b.CenterZ) > 1000f) + { + continue; + } + float px = b.CenterX; + float pz = b.CenterZ - b.HalfZ - 1.0f; + if (!sion.IsInsideAnyBuildingXz(px, pz, 0f)) + { + alleySpots.Add((b, px, pz)); + } + } + Assert.Equal(10, alleySpots.Count); + + for (int i = 0; i < alleySpots.Count; i++) + { + var (b, px, pz) = alleySpots[i]; + float terrainY = session.State.Terrain.SampleHeight(px, pz); + float midWallY = terrainY + (b.RoofY - terrainY) * 0.5f; + + var simSample = session.QueryDropSurface(px, pz, OrbitalPodPreset.Contender.PodFootRadius, midWallY + 1.0f); + var coreSample = session.State.DefaultDropSurfaceQuery(px, pz, OrbitalPodPreset.Contender.PodFootRadius, midWallY + 1.0f); + + Assert.False(simSample.IsBuildingRoof, $"Point {i} 1.0m outside {b.Id} returned IsBuildingRoof=true!"); + Assert.True(simSample.SurfaceY <= midWallY, + $"Point {i} 1.0m outside {b.Id}: QueryDropSurface returned phantom SurfaceY={simSample.SurfaceY:F2} > midWallY={midWallY:F2} (roof={b.RoofY:F2})"); + Assert.False(coreSample.IsBuildingRoof); + Assert.True(coreSample.SurfaceY <= midWallY, + $"Point {i} 1.0m outside {b.Id}: DefaultDropSurfaceQuery returned phantom SurfaceY={coreSample.SurfaceY:F2} > midWallY={midWallY:F2}"); + + // Verify a descending pod 1.0m outside the wall does NOT mid-air instant-pop at 33.67 m/s + var pod = new OrbitalPod + { + PodId = 9000 + i, + PodKind = OrbitalPodKind.Contender, + Phase = OrbitalPodPhase.Freefall, + X = px, + Y = midWallY + 18f, + Z = pz, + VelY = -33.67f, + AllowFlatRoofLanding = true + }; + bool touched = false; + for (int t = 0; t < 360; t++) + { + if (OrbitalDropKinematics.StepPod( + pod, + ArenaSession.FixedDt, + session.State.Terrain, + session.QueryDropSurface, + session.State.FindClearDropPoint, + out _, + out _)) + { + touched = true; + break; + } + } + Assert.True(touched, $"Pod {i} outside {b.Id} failed to land"); + float finalTerrain = session.State.Terrain.SampleHeight(pod.X, pod.Z); + Assert.True(pod.Y <= finalTerrain + 0.5f, + $"Pod {i} outside {b.Id} popped in mid-air at Y={pod.Y:F2} vs terrain={finalTerrain:F2}"); + Assert.InRange(pod.TouchdownSpeed, 0.5f, 2.99f); + } + } + + [Fact] + public void SionRoofEdgeAndSteppedRoof_HorizontalSteering_AlwaysLandsUnder3MsWithoutWarp() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + + // 1. Test horizontal entry onto flat Sion roofs (including sion_0146, sion_0665) at 1..3m above roof edge during RetroBurn + var targetRoofs = new List(); + foreach (var targetId in new[] { "sion_0146", "sion_0665" }) + { + var found = sion.Buildings.FirstOrDefault(b => b.Id == targetId); + Assert.Equal(targetId, found.Id); + targetRoofs.Add(found); + } + + foreach (var b in targetRoofs) + { + // Find a clear approach side 1.0m outside the building AABB and sample actual roof height inside the edge + float probeInX = b.CenterX; + float probeInZ = b.CenterZ - b.HalfZ + 4.0f; + var roofSample = session.QueryDropSurface(probeInX, probeInZ, 1.65f, b.RoofY + 20f); + float edgeRoofY = roofSample.IsBuildingRoof ? roofSample.SurfaceY : b.RoofY; + + float startX = b.CenterX; + float startZ = b.CenterZ - b.HalfZ - 0.8f; + if (sion.IsInsideAnyBuildingXz(startX, startZ, 0f)) continue; + + foreach (float hAboveEdge in new[] { 1.0f, 2.0f, 3.0f }) + { + foreach (float vyDown in new[] { 12f, 22f, 35f }) + { + var pod = new OrbitalPod + { + PodId = 9100, + PodKind = OrbitalPodKind.Contender, + Phase = OrbitalPodPhase.RetroBurn, + AllowFlatRoofLanding = true, + X = startX, + Y = edgeRoofY + hAboveEdge, + Z = startZ, + VelX = 0f, + VelY = -vyDown, + VelZ = 18f + }; + + bool landed = false; + float maxStepDeltaY = 0f; + for (int t = 0; t < 360; t++) + { + float prevY = pod.Y; + bool touched = OrbitalDropKinematics.StepPod( + pod, + ArenaSession.FixedDt, + session.State.Terrain, + session.QueryDropSurface, + session.State.FindClearDropPoint, + out _, + out _); + maxStepDeltaY = MathF.Max(maxStepDeltaY, MathF.Abs(pod.Y - prevY)); + if (touched) + { + landed = true; + break; + } + } + + Assert.True(landed, $"Pod near {b.Id} (h={hAboveEdge}m, vy={vyDown}) failed to land"); + Assert.InRange(pod.TouchdownSpeed, 0.5f, 2.99f); + Assert.True(maxStepDeltaY <= 2.0f, + $"Pod near {b.Id} (h={hAboveEdge}m, vy={vyDown}) warped vertically by {maxStepDeltaY:F2}m"); + } + } + } + + // 2. Test AllowFlatRoofLanding = false near stepped Old Town roofs -> never warps > 2m and always < 3.0 m/s + int steppedTested = 0; + for (int i = 0; i < sion.Buildings.Count && steppedTested < 12; i++) + { + var b = sion.Buildings[(i * 53) % sion.Buildings.Count]; + if ((b.RoofY - b.GroundY) < 10f || MathF.Abs(b.CenterX) > 900f || MathF.Abs(b.CenterZ) > 900f) + { + continue; + } + float startX = b.CenterX; + float startZ = b.CenterZ - b.HalfZ - 1.2f; + if (sion.IsInsideAnyBuildingXz(startX, startZ, 0f)) continue; + + foreach (float startOffset in new[] { 2.0f, 18.0f, 55.0f }) + { + var pod = new OrbitalPod + { + PodId = 9200 + steppedTested, + PodKind = OrbitalPodKind.Contender, + Phase = startOffset < 10f ? OrbitalPodPhase.RetroBurn : OrbitalPodPhase.Freefall, + AllowFlatRoofLanding = false, + X = startX, + Y = b.RoofY + startOffset, + Z = startZ, + VelX = 0f, + VelY = -28f, + VelZ = 16f, + LookForwardX = 0f, + LookForwardZ = 1f, + SteerForwardCmd = 1f + }; + + bool landed = false; + float maxStepDeltaY = 0f; + for (int t = 0; t < 480; t++) + { + float prevY = pod.Y; + bool touched = OrbitalDropKinematics.StepPod( + pod, + ArenaSession.FixedDt, + session.State.Terrain, + session.QueryDropSurface, + session.State.FindClearDropPoint, + out _, + out var touchSample); + maxStepDeltaY = MathF.Max(maxStepDeltaY, MathF.Abs(pod.Y - prevY)); + if (touched) + { + landed = true; + Assert.False(touchSample.IsBuildingRoof, $"AllowFlatRoofLanding=false pod landed on roof of {b.Id}"); + Assert.False(sion.IsInsideAnyBuildingXz(pod.X, pod.Z, 0f), $"Pod landed inside {b.Id}"); + break; + } + } + + Assert.True(landed, $"AllowFlatRoofLanding=false pod near {b.Id} failed to land"); + Assert.InRange(pod.TouchdownSpeed, 0.5f, 2.99f); + Assert.True(maxStepDeltaY <= 2.0f, + $"AllowFlatRoofLanding=false pod near {b.Id} (offset={startOffset}m) warped by {maxStepDeltaY:F2}m"); + } + steppedTested++; + } + Assert.Equal(12, steppedTested); + } + + [Fact] + public void Sion410mDrop_SteeringIntoTallWallAndSteepTerrain_NeverBreachesWallOrIgnitesStratosphericRetro() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + var tall = sion.Buildings.First(b => b.Id == "sion_1365"); + Assert.True((tall.RoofY - tall.GroundY) > 60f, $"Expected sion_1365 H>60m, got {tall.RoofY - tall.GroundY:F1}m"); + + // 1. 410m AGL human drop outside sion_1365 steering straight toward sion_1365 center, plus low wall-approach & roof-edge sweeps + var approachStarts = new (float X, float Z, float StartAgl, float Vy0)[] + { + (tall.CenterX, tall.CenterZ - tall.HalfZ - 18f, 410f, OrbitalPodPreset.Contender.InitialVelY), + (tall.CenterX - tall.HalfX - 18f, tall.CenterZ, 410f, OrbitalPodPreset.Contender.InitialVelY), + (tall.CenterX, tall.CenterZ + tall.HalfZ + 4.5f, 35f, -35f), + (tall.CenterX + tall.HalfX + 1.2f, tall.CenterZ, tall.RoofY - session.State.Terrain.SampleHeight(tall.CenterX + tall.HalfX + 1.2f, tall.CenterZ) + 2.0f, -22f), + }; + + for (int c = 0; c < approachStarts.Length; c++) + { + var (sx, sz, agl0, vy0) = approachStarts[c]; + float terrain0 = session.State.Terrain.SampleHeight(sx, sz); + float dx = tall.CenterX - sx; + float dz = tall.CenterZ - sz; + float len = MathF.Sqrt(dx * dx + dz * dz); + float dirX = dx / len; + float dirZ = dz / len; + + var pod = new OrbitalPod + { + PodId = 9500 + c, + PodKind = OrbitalPodKind.Contender, + Phase = OrbitalPodPhase.Freefall, + AllowFlatRoofLanding = true, + X = sx, + Y = terrain0 + agl0, + Z = sz, + VelY = vy0, + LookForwardX = dirX, + LookForwardZ = dirZ, + SteerForwardCmd = 1f, + Yaw = MathF.Atan2(dirX, dirZ) + }; + + bool landed = false; + float maxStepDeltaY = 0f; + for (int t = 0; t < 720; t++) + { + float prevY = pod.Y; + bool touched = OrbitalDropKinematics.StepPod( + pod, + ArenaSession.FixedDt, + session.State.Terrain, + session.QueryDropSurface, + session.State.FindClearDropPoint, + out bool retroStarted, + out _); + maxStepDeltaY = MathF.Max(maxStepDeltaY, MathF.Abs(pod.Y - prevY)); + + if (retroStarted) + { + float surfY = session.QueryDropSurface(pod.X, pod.Z, OrbitalPodPreset.Contender.PodFootRadius, pod.Y + 1.0f).SurfaceY; + float startAgl = pod.Y - MathF.Max(session.State.Terrain.SampleHeight(pod.X, pod.Z), surfY); + Assert.True(startAgl <= 160f, $"Case {c}: RetroBurn ignited in stratosphere at {startAgl:F1}m AGL"); + } + + if (sion.TryGetBuildingAt(pod.X, pod.Z, 0f, out var bInside)) + { + Assert.True(pod.Y >= bInside.RoofY - 0.1f, + $"Case {c} tick {t}: pod breached wall of {bInside.Id} at Y={pod.Y:F2} < RoofY={bInside.RoofY:F2}"); + } + + if (touched) + { + landed = true; + break; + } + } + + Assert.True(landed, $"Case {c} pod near sion_1365 failed to land"); + Assert.True(pod.FlightTime <= 10.5f, $"Case {c} exceeded 10.5s flight time: {pod.FlightTime:F2}s"); + Assert.True(maxStepDeltaY <= 2.0f, $"Case {c} had vertical teleport step {maxStepDeltaY:F2}m"); + Assert.InRange(pod.TouchdownSpeed, 0.5f, 2.99f); + } + + // 2. Full Sion Wave 0 drop steering human toward sion_1365 + steep Sion terrain checks across all 12 contenders + var maxBurnStartAgl = new Dictionary(); + for (int t = 0; t < 2200; t++) + { + var p0 = session.State.Contenders[0]; + session.SetHumanInput(0, new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: tall.CenterX, + AimWorldZ: tall.CenterZ, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + foreach (var pod in session.State.OrbitalDrop.ActivePods) + { + if (sion.TryGetBuildingAt(pod.X, pod.Z, 0f, out var bHit)) + { + Assert.True(pod.Y >= bHit.RoofY - 0.1f, + $"Wave 0 pod {pod.PodId} breached {bHit.Id} wall at Y={pod.Y:F2} < RoofY={bHit.RoofY:F2}"); + } + if (pod.Phase == OrbitalPodPhase.RetroBurn && !maxBurnStartAgl.ContainsKey(pod.PodId)) + { + maxBurnStartAgl[pod.PodId] = pod.LastAgl; + Assert.True(pod.LastAgl <= 160f, $"Wave 0 pod {pod.PodId} ignited RetroBurn at {pod.LastAgl:F1}m AGL"); + } + Assert.True(pod.FlightTime <= 34.0f, $"Wave 0 pod {pod.PodId} exceeded 34.0s flight time: {pod.FlightTime:F2}s"); + } + + if (session.State.OrbitalDrop.ActivePods.Count == 0 && p0.IsGroundedActive) + { + break; + } + } + + Assert.Empty(session.State.OrbitalDrop.ActivePods); + Assert.True(session.State.Contenders[0].IsGroundedActive); + } + + [Fact] + public void RemoteArenaSession_RivalEntersPvsMidDrop_BecomesVisibleWithActivePod() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var client = new RemoteArenaSession(ep, "PvsObserver"); + IClientArenaSession clientIface = client; + + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var deadline = DateTimeOffset.UtcNow.AddSeconds(4); + while (DateTimeOffset.UtcNow < deadline && !client.IsJoined) + { + nowMs += 16; + host.StepOnce(nowMs); + client.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.True(client.IsJoined); + int localId = clientIface.LocalContenderId; + int rivalId = localId == 0 ? 1 : 0; + + void PumpStep(int ticks) + { + var evs = new List(); + for (int t = 0; t < ticks; t++) + { + nowMs += 16; + clientIface.SubmitLocalInput(new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: clientIface.LocalContender.X, + AimWorldZ: clientIface.LocalContender.Z + 50f, + Fire: false, + InteractPickup: false, + Brake: false), isPhysicsTick: true); + host.StepOnce(nowMs); + client.PumpNetwork(nowMs); + clientIface.BeginRenderFrame(ArenaSession.FixedDt, 1.0f); + clientIface.DrainSimEvents(evs); + } + } + + // Land Wave 0 immediately and place observer far away from rival's Wave 1 drop + host.Session.State.OrbitalDrop.DeployAllPodsImmediately(host.Session.QueryDropSurface); + PumpStep(5); + Assert.True(clientIface.LocalContender.IsGroundedActive); + + // Eliminate rival -> WaitingForRespawnWave, then move observer far away (-900, -900) + host.Session.ForceEliminateContender(rivalId); + host.Session.SetContenderPose(localId, -900f, -900f, 0f); + PumpStep(5); + + // Trigger Wave 1 (85.0s) so rival launches its drop pod out of observer PVS + host.Session.State.Time = 84.9f; + for (int i = 0; i < 20 && host.Session.State.Contenders[rivalId].Lifecycle != ContenderLifecycle.Deploying; i++) + { + PumpStep(1); + } + Assert.Equal(ContenderLifecycle.Deploying, host.Session.State.Contenders[rivalId].Lifecycle); + PumpStep(5); + + var rivalPod = host.Session.State.OrbitalDrop.ActivePods.FirstOrDefault( + p => p.PodKind == OrbitalPodKind.Contender && p.ContenderId == rivalId); + Assert.NotNull(rivalPod); + Assert.False(host.Session.IsEntityInPeerPvs(localId, true, rivalId), "Rival should start out of observer PVS"); + Assert.False(clientIface.IsContenderVisible(rivalId), "Rival should not be visible on client before entering PVS"); + + // Move observer within 20m of rival's pod mid-drop, then step 15 ticks + host.Session.SetContenderPose(localId, rivalPod!.X + 18f, rivalPod.Z, 0f); + PumpStep(15); + + Assert.True(clientIface.IsContenderVisible(rivalId), "Rival should become visible on client after entering PVS mid-drop"); + Assert.Contains(clientIface.ActivePods, + p => p.PodKind == OrbitalPodKind.Contender && p.ContenderId == rivalId); + } + + [Fact] + public void Sion0005_LShapedCornerAndWallSteering_ZeroWallBreachesAndZeroTouchdownWarps() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + var b = sion.Buildings.First(x => x.Id == "sion_0005"); + + // Find an open-sky AABB corner inside sion_0005 (IsInsideAnyBuildingXz == true, no solid roof overhead) + // and a solid-roof interior target inside sion_0005 to steer toward. + float? openCornerX = null, openCornerZ = null; + float? solidTargetX = null, solidTargetZ = null; + float solidTargetRoofY = b.RoofY; + for (float z = b.CenterZ - b.HalfZ + 1.5f; z <= b.CenterZ + b.HalfZ - 1.5f; z += 2.0f) + { + for (float x = b.CenterX - b.HalfX + 1.5f; x <= b.CenterX + b.HalfX - 1.5f; x += 2.0f) + { + var sky = session.QueryDropSurface(x, z, 0f, b.RoofY + 50f); + if (!sky.IsBuildingRoof) + { + openCornerX ??= x; + openCornerZ ??= z; + } + else if (solidTargetX is null && sky.SurfaceY > session.State.Terrain.SampleHeight(x, z) + 2f) + { + solidTargetX = x; + solidTargetZ = z; + solidTargetRoofY = sky.SurfaceY; + } + } + } + + Assert.True(solidTargetX.HasValue, "Expected solid roof interior point on sion_0005"); + float tx = solidTargetX!.Value; + float tz = solidTargetZ!.Value; + + var startPoints = new List<(string Label, float X, float Z)>(); + if (openCornerX.HasValue) + { + startPoints.Add(("L-corner", openCornerX.Value, openCornerZ!.Value)); + } + foreach (float offset in new[] { 1.2f, 5.0f, 18.0f, 35.0f }) + { + startPoints.Add(($"+{offset:F1}m_W", b.CenterX - b.HalfX - offset, tx != b.CenterX ? tz : b.CenterZ)); + startPoints.Add(($"+{offset:F1}m_S", tx, b.CenterZ - b.HalfZ - offset)); + } + + int totalCases = 0; + int wallBreachFrames = 0; + int touchdownWarps = 0; + float maxHorizStep = 0f; + float maxTouchdownStep = 0f; + float maxTouchSpeed = 0f; + + foreach (bool allowFlat in new[] { false, true }) + { + foreach (float startAgl in new[] { 1620f, 80f }) + { + foreach (var (label, sx, sz) in startPoints) + { + float terrain0 = session.State.Terrain.SampleHeight(sx, sz); + float dx = tx - sx; + float dz = tz - sz; + float len = MathF.Max(0.001f, MathF.Sqrt(dx * dx + dz * dz)); + float dirX = dx / len; + float dirZ = dz / len; + + var pod = new OrbitalPod + { + PodId = 9800 + totalCases, + PodKind = OrbitalPodKind.Contender, + Phase = OrbitalPodPhase.Freefall, + AllowFlatRoofLanding = allowFlat, + X = sx, + Y = terrain0 + startAgl, + Z = sz, + VelY = startAgl > 200f ? OrbitalPodPreset.GetContender(ArenaMapKind.Sion).InitialVelY : -28f, + LookForwardX = dirX, + LookForwardZ = dirZ, + SteerForwardCmd = 1f, + Yaw = MathF.Atan2(dirX, dirZ) + }; + + bool landed = false; + for (int t = 0; t < 2200; t++) + { + float prevX = pod.X; + float prevY = pod.Y; + float prevZ = pod.Z; + + bool touched = OrbitalDropKinematics.StepPod( + pod, + ArenaSession.FixedDt, + session.State.Terrain, + session.QueryDropSurface, + session.State.FindClearDropPoint, + out _, + out _); + + float horizStep = MathF.Sqrt((pod.X - prevX) * (pod.X - prevX) + (pod.Z - prevZ) * (pod.Z - prevZ)); + maxHorizStep = MathF.Max(maxHorizStep, horizStep); + + var skyProbe = session.QueryDropSurface(pod.X, pod.Z, 0f, solidTargetRoofY + 60f); + if (skyProbe.IsBuildingRoof && pod.Y < skyProbe.SurfaceY - 0.1f) + { + wallBreachFrames++; + } + + if (touched) + { + float tdStep3D = MathF.Sqrt( + (pod.X - prevX) * (pod.X - prevX) + + (pod.Y - prevY) * (pod.Y - prevY) + + (pod.Z - prevZ) * (pod.Z - prevZ)); + maxTouchdownStep = MathF.Max(maxTouchdownStep, tdStep3D); + if (tdStep3D > 1.0f || horizStep > 2.25f) + { + touchdownWarps++; + } + maxTouchSpeed = MathF.Max(maxTouchSpeed, pod.TouchdownSpeed); + landed = true; + break; + } + } + + Assert.True(landed, $"sion_0005 case {label} (agl={startAgl}, flat={allowFlat}) failed to land"); + totalCases++; + } + } + } + + _output.WriteLine( + $"sion_0005 sweep: cases={totalCases}, hasLCorner={openCornerX.HasValue}, " + + $"wallBreachFrames={wallBreachFrames}, touchdownWarps={touchdownWarps}, " + + $"maxHorizStep={maxHorizStep:F3}m, maxTouchdownStep={maxTouchdownStep:F3}m, maxTouchSpeed={maxTouchSpeed:F2} m/s"); + + Assert.Equal(0, wallBreachFrames); + Assert.Equal(0, touchdownWarps); + Assert.True(maxHorizStep <= 2.25f, $"Horizontal warp {maxHorizStep:F3}m > 2.25m/tick"); + Assert.True(maxTouchSpeed < 2.5f, $"Touchdown speed {maxTouchSpeed:F2} m/s >= 2.5 m/s"); + } + + [Fact] + public void HoverSlam_CrossZoneDrop_SionAndDesert() + { + // Large synthetic flat terrain to measure unobstructed max-burn cross-zone horizontal glide + var largeHeights = new float[17 * 17]; + var largeFlat = TerrainField.LoadHeightmap(sizeMeters: 10000f, gridRes: 17, largeHeights, minY: 0f, maxY: 0f, seed: 1); + DropSurfaceSample FlatQuery(float x, float z, float footR, float refMaxY) => + new(0f, Vector3.UnitY, false, false, false, false); + (float X, float Z) FlatClear(float x, float z, float pad) => (x, z); + + foreach (var (map, minGlideM) in new[] { (ArenaMapKind.Sion, 3000f), (ArenaMapKind.Desert, 1400f) }) + { + var preset = OrbitalPodPreset.GetContender(map); + var pod = new OrbitalPod + { + PodId = 100 + (int)map, + PodKind = OrbitalPodKind.Contender, + Phase = OrbitalPodPhase.Freefall, + X = 0f, + Y = preset.StartAltAgl, + Z = 0f, + VelY = preset.InitialVelY, + LookForwardX = 0f, + LookForwardZ = 1f, + SteerForwardCmd = 1.0f, + Yaw = 0f + }; + + float burnStartAgl = -1f; + bool touched = false; + for (int t = 0; t < 2400; t++) + { + if (OrbitalDropKinematics.StepPod(pod, ArenaSession.FixedDt, largeFlat, FlatQuery, FlatClear, out bool retroStarted, out _)) + { + touched = true; + break; + } + if (retroStarted) + { + burnStartAgl = pod.Y; + } + } + + Assert.True(touched, $"{map} cross-zone pod failed to touch down"); + Assert.True(pod.Z >= minGlideM, $"{map} max-burn horizontal glide {pod.Z:F1}m < {minGlideM:F1}m"); + Assert.True(pod.TouchdownSpeed < 2.5f, $"{map} flat touchdown speed {pod.TouchdownSpeed:F2} >= 2.5 m/s"); + Assert.InRange(burnStartAgl, 8f, 160f); + Assert.Equal(0f, pod.Y, precision: 3); + _output.WriteLine($"{map} flat cross-zone: glide={pod.Z:F1}m, flight={pod.FlightTime:F2}s, retroAgl={burnStartAgl:F2}m, tdVel={pod.TouchdownSpeed:F2} m/s"); + } + + // +-30 deg slope hover-slam verification + float slopeTan = MathF.Tan(30f * MathF.PI / 180f); // ~0.57735 + foreach (float sign in new[] { 1f, -1f }) + { + const int res = 129; + const float size = 8000f; + var slopeHeights = new float[res * res]; + for (int gz = 0; gz < res; gz++) + { + float wz = -size * 0.5f + (gz / (float)(res - 1)) * size; + float h = sign > 0f ? MathF.Max(0f, wz * slopeTan) : MathF.Max(0f, (1000f - wz) * slopeTan); + for (int gx = 0; gx < res; gx++) + { + slopeHeights[gz * res + gx] = h; + } + } + var slopeTerrain = TerrainField.LoadHeightmap(size, res, slopeHeights, 0f, 3000f, 2UL); + DropSurfaceSample SlopeQuery(float x, float z, float footR, float refMaxY) + { + float sy = slopeTerrain.SampleHeight(x, z); + var (nx, ny, nz) = slopeTerrain.SampleNormal(x, z); + return new DropSurfaceSample(sy, Vector3.Normalize(new Vector3(nx, ny, nz)), false, false, false, false); + } + + var sionPreset = OrbitalPodPreset.GetContender(ArenaMapKind.Sion); + float startZ = -400f; + float startSurf = slopeTerrain.SampleHeight(0f, startZ); + var pod = new OrbitalPod + { + PodId = 300 + (sign > 0 ? 1 : 2), + PodKind = OrbitalPodKind.Contender, + Phase = OrbitalPodPhase.Freefall, + X = 0f, + Y = startSurf + sionPreset.StartAltAgl, + Z = startZ, + VelY = sionPreset.InitialVelY, + LookForwardX = 0f, + LookForwardZ = 1f, + SteerForwardCmd = 1.0f, + Yaw = 0f + }; + + float burnStartAgl = -1f; + bool touched = false; + for (int t = 0; t < 3000; t++) + { + if (OrbitalDropKinematics.StepPod(pod, ArenaSession.FixedDt, slopeTerrain, SlopeQuery, FlatClear, out bool retroStarted, out _)) + { + touched = true; + break; + } + if (retroStarted) + { + burnStartAgl = pod.Y - slopeTerrain.SampleHeight(pod.X, pod.Z); + } + } + + Assert.True(touched, $"Slope sign={sign} pod failed to touch down"); + Assert.True(pod.TouchdownSpeed < 2.5f, $"Slope sign={sign} touchdown speed {pod.TouchdownSpeed:F2} >= 2.5 m/s"); + Assert.InRange(burnStartAgl, 5f, 160f); + float endTerrain = slopeTerrain.SampleHeight(pod.X, pod.Z); + Assert.True(MathF.Abs(pod.Y - endTerrain) < 0.001f, $"Slope sign={sign} penetration/hover error {pod.Y - endTerrain:F5}m"); + _output.WriteLine($"Slope sign={sign:+#;-#}: flight={pod.FlightTime:F2}s, retroAgl={burnStartAgl:F2}m, tdVel={pod.TouchdownSpeed:F2} m/s"); + } + } + + [Fact] + public void SquadFormation_TrioDrop_ZeroPodOverlapAndFormationVisible() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, squadSize: 3); + var state = session.State; + Assert.Equal(3, state.SquadSize); + + // Verify 4 squads of 3; inter-squad anchors >= 220m apart, intra-squad pods >= 14m apart at launch + var squadGroups = state.Contenders.GroupBy(c => c.SquadId).ToList(); + Assert.Equal(4, squadGroups.Count); + foreach (var grp in squadGroups) + { + var members = grp.ToList(); + Assert.Equal(3, members.Count); + for (int a = 0; a < members.Count; a++) + { + for (int b = a + 1; b < members.Count; b++) + { + float d = MathF.Sqrt( + (members[a].X - members[b].X) * (members[a].X - members[b].X) + + (members[a].Z - members[b].Z) * (members[a].Z - members[b].Z)); + Assert.True(d >= 14f, $"Same-squad launch separation too small: {d:F2}m"); + } + } + } + + // Different squad leaders >= 200m apart (anchors >= 220m, leaders +8m fwd) + for (int i = 0; i < squadGroups.Count; i++) + { + var li = state.GetSquadLeader(squadGroups[i].Key)!; + for (int j = i + 1; j < squadGroups.Count; j++) + { + var lj = state.GetSquadLeader(squadGroups[j].Key)!; + float d = MathF.Sqrt((li.X - lj.X) * (li.X - lj.X) + (li.Z - lj.Z) * (li.Z - lj.Z)); + Assert.True(d >= 195f, $"Inter-squad separation too small: {d:F1}m"); + } + } + + // Allied persistent PVS + zero false DetectedBy from allies + Assert.True(session.IsEntityInPeerPvs(0, true, 1)); + Assert.True(session.IsEntityInPeerPvs(0, true, 2)); + Assert.Equal(0, state.ObserverStates[0].DetectedByCount); + + // Step Wave 0 drop while player glides gently forward; track formation and touchdown separation + for (int t = 0; t < 2200; t++) + { + var p0 = state.Contenders[0]; + session.SetHumanInput(0, new PlayerInput( + Throttle: 0.45f, + Steer: 0f, + AimWorldX: p0.X + MathF.Sin(p0.Yaw) * 100f, + AimWorldZ: p0.Z + MathF.Cos(p0.Yaw) * 100f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + if (state.Contenders.All(c => c.IsGroundedActive)) + { + break; + } + } + + Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive)); + + // Wingmen (1, 2) landed >= 12m apart from player (0) and each other, with 0 penetration + for (int a = 0; a < 3; a++) + { + AssertZeroChassisPenetration(state, state.Contenders[a]); + for (int b = a + 1; b < 3; b++) + { + float d = MathF.Sqrt( + (state.Contenders[a].X - state.Contenders[b].X) * (state.Contenders[a].X - state.Contenders[b].X) + + (state.Contenders[a].Z - state.Contenders[b].Z) * (state.Contenders[a].Z - state.Contenders[b].Z)); + Assert.True(d >= 11.5f, $"Squadmates {a} & {b} landed too close: {d:F2}m"); + } + } + + // Verify AI allies do not target allies and friendly fire does 0 damage + var ally1 = state.Contenders[1]; + float allyHpBefore = ally1.Grid.CoreHp; + session.SetContenderPose(0, 0f, 0f, 0f); + session.SetContenderPose(1, 0f, 20f, MathF.PI); + for (int t = 0; t < 30; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, ally1.X, ally1.Z, Fire: true, InteractPickup: false, Brake: true)); + session.Step(); + Assert.False(ally1.AiTargetContenderId.HasValue && state.AreAllies(1, ally1.AiTargetContenderId.Value), + "AI wingman targeted an allied squadmate!"); + } + Assert.Equal(allyHpBefore, ally1.Grid.CoreHp); + + // Advance past Wave 2 cutoff and eliminate all 9 non-Squad-0 contenders -> Squad 0 wins! + state.Time = 250f; + session.Step(); + Assert.True(state.OrbitalDrop.RespawnCutoffReached); + for (int i = 3; i < state.Contenders.Count; i++) + { + session.ForceEliminateContender(i); + } + MatchRules.UpdateMatchOutcome(state); + Assert.Equal(MatchPhase.Completed, state.Phase); + Assert.Equal(0, state.WinnerContenderId); + } + + [Fact] + public void CorePvs_MaxDatagramCap_StrictlyUnder1152B() + { + var state = new MatchState(seed: 42, ArenaMapKind.Desert, skipInitialDrop: true, squadSize: 3); + var local = state.Contenders[0]; + local.Grid.SwapChassis(Catalog.Bastion); + + var contenders = new List(12); + var walkers = new List(12); + var specs = new List(10); + + for (int i = 0; i < 12; i++) + { + contenders.Add(new NetContenderState + { + SlotId = (byte)i, + Alive = true, + IsHuman = i < 3, + Lifecycle = ContenderLifecycle.Active, + Pos = new Vector3(i * 12f, 3f, -i * 6f), + Rot = Quaternion.Identity, + Vel = Vector3.Zero, + CoreHpRatio = 1f + }); + walkers.Add(new NetWalkerEntry + { + IsContender = true, + EntityId = (byte)i, + Snapshot = new WalkerVisualSnapshot { LegCount = 4 } + }); + } + + byte[] payload = SnapshotCodec.EncodeCorePvs( + 1, 10, 20, 12.5f, 0, 0, 772f, MatchPhase.Active, null, 0, 0xFFF, + local, Vector3.Zero, contenders, walkers, specs); + byte[] wire = SnapshotCodec.WrapLatest(payload, 1, 10); + Assert.True(wire.Length <= SnapshotCodec.MaxLatestDatagramBytes, + $"CorePvs wire frame {wire.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); + } + + [Fact] + public void SquadTrioDrop_AllSeedsAndMaps_AllLandedSquadmatesSeparatedAtLeast12Meters() + { + int[] seeds = { 1, 7, 42, 1337 }; + ArenaMapKind[] maps = { ArenaMapKind.Sion, ArenaMapKind.Desert }; + + foreach (var mapKind in maps) + { + foreach (int seed in seeds) + { + using var session = new ArenaSession(seed: seed, mapKind: mapKind, slot0Human: false, squadSize: 3); + var state = session.State; + + var tdPos = new (float X, float Z, int Tick)[MatchState.ContenderCount]; + var landed = new bool[MatchState.ContenderCount]; + for (int t = 0; t < 2400; t++) + { + session.Step(); + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (!landed[i] && c.IsGroundedActive) + { + landed[i] = true; + tdPos[i] = (c.X, c.Z, t); + } + } + if (state.Contenders.All(c => c.IsGroundedActive)) + { + break; + } + } + + Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive, + $"Map={mapKind} Seed={seed} contender {c.Id} failed to land")); + + foreach (var grp in state.Contenders.GroupBy(c => c.SquadId)) + { + var members = grp.ToList(); + for (int a = 0; a < members.Count; a++) + { + for (int b = a + 1; b < members.Count; b++) + { + var ma = members[a]; + var mb = members[b]; + float tdDx = tdPos[ma.Id].X - tdPos[mb.Id].X; + float tdDz = tdPos[ma.Id].Z - tdPos[mb.Id].Z; + float tdDist = MathF.Sqrt(tdDx * tdDx + tdDz * tdDz); + float dx = ma.X - mb.X; + float dz = ma.Z - mb.Z; + float d = MathF.Sqrt(dx * dx + dz * dz); + Assert.True(tdDist >= 12.0f, + $"Map={mapKind} Seed={seed} Squad={grp.Key} pair ({ma.Id}@t{tdPos[ma.Id].Tick},{mb.Id}@t{tdPos[mb.Id].Tick}) touchdown too close: td={tdDist:F2}m (now={d:F2}m)"); + Assert.True(d >= 12.0f, + $"Map={mapKind} Seed={seed} Squad={grp.Key} pair ({ma.Id}@t{tdPos[ma.Id].Tick},{mb.Id}@t{tdPos[mb.Id].Tick}) landed too close: now={d:F2}m (td={tdDist:F2}m)"); + } + } + } + } + } + } + + private static void AssertZeroChassisPenetration(MatchState state, ContenderState c) + { + var spec = c.Grid.Spec; + float physHalfH = ArenaSession.GetPhysicsHalfHeight(spec); + Quaternion q = Quaternion.Normalize(new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW)); + Vector3 center = new(c.X, c.Y, c.Z); + + float groundCenter = state.Terrain.SampleHeight(c.X, c.Z); + float centerClearance = (c.Y - physHalfH) - groundCenter; + Assert.True(centerClearance >= 0f, + $"Chassis center penetrated terrain: bottom={c.Y - physHalfH:F4} < ground={groundCenter:F4} (clearance={centerClearance:F4}m)"); + + Span localCorners = stackalloc Vector3[4] + { + new Vector3(-spec.HalfWidth, -physHalfH, -spec.HalfLength), + new Vector3( spec.HalfWidth, -physHalfH, -spec.HalfLength), + new Vector3(-spec.HalfWidth, -physHalfH, spec.HalfLength), + new Vector3( spec.HalfWidth, -physHalfH, spec.HalfLength) + }; + for (int k = 0; k < 4; k++) + { + Vector3 wp = center + Vector3.Transform(localCorners[k], q); + float gh = state.Terrain.SampleHeight(wp.X, wp.Z); + float clearance = wp.Y - gh; + Assert.True(clearance >= 0f, + $"Chassis corner {k} penetrated terrain: cornerY={wp.Y:F4} < ground={gh:F4} (clearance={clearance:F4}m)"); + } + } + } +} diff --git a/tests/RustToDust.Tests/OrdnanceAndProceduralWeaponTests.cs b/tests/RustToDust.Tests/OrdnanceAndProceduralWeaponTests.cs new file mode 100644 index 0000000..81bbf59 --- /dev/null +++ b/tests/RustToDust.Tests/OrdnanceAndProceduralWeaponTests.cs @@ -0,0 +1,1111 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Numerics; +using MessagePack; +using RustToDust.Core; +using RustToDust.Net; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class OrdnanceAndProceduralWeaponTests + { + private static void IsolateContenders(ArenaSession session, params int[] keepIds) + { + var keep = keepIds.ToHashSet(); + for (int i = 0; i < session.State.Contenders.Count; i++) + { + var c = session.State.Contenders[i]; + if (!keep.Contains(c.Id)) + { + session.SetContenderPose(c.Id, -280f + i * 10f, -280f); + } + } + for (int i = 0; i < session.State.Spectators.Spectators.Count; i++) + { + var s = session.State.Spectators.Spectators[i]; + session.SetSpectatorPose(s.Id, 280f, -280f + i * 4f); + } + } + + [Fact] + public void ProceduralWeapons_DeterministicGeneration_And12ByteKeyRoundTrip() + { + var rng = new Random(1337); + for (int i = 0; i < 200; i++) + { + byte mfg = (byte)(i % 5); + byte arch = (byte)(mfg * 4 + (i % 4)); + byte tier = (byte)(i % 4); + byte flags = (byte)(i % 2); + ulong seed = ((ulong)(uint)rng.Next() << 32) | (uint)rng.Next(); + + var key = new ProceduralWeaponKey(seed, mfg, arch, tier, flags); + var specA = ProceduralWeaponGenerator.Generate(key); + var specB = ProceduralWeaponGenerator.Generate(key); + + Assert.Equal(specA.DisplayName, specB.DisplayName); + Assert.Equal(specA.SummaryLine1, specB.SummaryLine1); + Assert.Equal(specA.SummaryLine2, specB.SummaryLine2); + Assert.Equal(specA.Assembly, specB.Assembly); + Assert.Equal(specA.PowerScore, specB.PowerScore); + Assert.Equal(specA.Module.WeaponDamage, specB.Module.WeaponDamage); + Assert.Equal(specA.FlattenedNodes.Length, specB.FlattenedNodes.Length); + for (int n = 0; n < specA.FlattenedNodes.Length; n++) + { + Assert.Equal(specA.FlattenedNodes[n].DefIndex, specB.FlattenedNodes[n].DefIndex); + Assert.Equal(specA.FlattenedNodes[n].Depth, specB.FlattenedNodes[n].Depth); + Assert.Equal(specA.FlattenedNodes[n].Motion, specB.FlattenedNodes[n].Motion); + } + + string encodedId = specA.Module.Id; + Assert.True(ProceduralWeaponGenerator.TryParseId(encodedId, out var parsedKey)); + Assert.Equal(key, parsedKey); + + var specC = ProceduralWeaponGenerator.Generate(parsedKey); + Assert.Equal(specA.Module.Id, specC.Module.Id); + Assert.Equal(specA.PowerScore, specC.PowerScore); + Assert.True(Catalog.TryGetModule(encodedId, out var resolvedMod)); + Assert.Equal(specA.Module.Id, resolvedMod.Id); + Assert.Equal(1, specA.Module.Width); + Assert.InRange(specA.Module.Height, 1, 2); + } + } + + [Fact] + public void All5Manufacturers_All20Archetypes_GenerateValidTreesAndTwoLineTooltips() + { + for (int m = 0; m < 5; m++) + { + for (int a = 0; a < 4; a++) + { + var arch = (WeaponArchetypeKind)(m * 4 + a); + var key = new ProceduralWeaponKey(0xCAFE0001UL + (ulong)(m * 4 + a), (byte)m, (byte)arch, Tier: 2, Flags: 0); + var spec = ProceduralWeaponGenerator.Generate(key); + + Assert.Equal((ManufacturerId)m, spec.Manufacturer); + Assert.Equal(arch, spec.Archetype); + Assert.False(string.IsNullOrWhiteSpace(spec.DisplayName)); + Assert.False(string.IsNullOrWhiteSpace(spec.SummaryLine1)); + Assert.False(string.IsNullOrWhiteSpace(spec.SummaryLine2)); + Assert.True(float.IsFinite(spec.PowerScore) && spec.PowerScore > 0f); + Assert.True(float.IsFinite(spec.Module.WeaponDamage) && spec.Module.WeaponDamage > 0f); + Assert.True(float.IsFinite(spec.Module.FireCooldown) && spec.Module.FireCooldown > 0f); + Assert.True(float.IsFinite(spec.Module.HeatOutput) && spec.Module.HeatOutput > 0f); + Assert.NotEmpty(spec.FlattenedNodes); + Assert.All(spec.FlattenedNodes, n => Assert.InRange(n.Depth, (byte)0, (byte)(OrdnanceNodeDef.MaxAllowedDepth - 1))); + Assert.InRange(spec.Assembly.ReceiverIdx, (byte)0, (byte)3); + Assert.InRange(spec.Assembly.BarrelIdx, (byte)0, (byte)3); + Assert.InRange(spec.Assembly.FeedIdx, (byte)0, (byte)3); + Assert.InRange(spec.Assembly.MuzzleIdx, (byte)0, (byte)3); + } + } + } + + [Fact] + public void DreamWeapon1_SabotRocketSled_TransitionsStageAt018s_AndHitsPointBlankWithoutTunneling() + { + // 1. Distant target (120m): Stage 0 Ballistic transitions at t=0.18s into Stage 1 RocketBoosted, accelerates >250m/s, impacts Anvil + crater + using (var session = new ArenaSession(seed: 101, slot0Human: true, skipInitialDrop: true)) + { + var shooter = session.State.Contenders[0]; + var target = session.State.Contenders[1]; + IsolateContenders(session, shooter.Id, target.Id); + + session.SetContenderPose(shooter.Id, 0f, 0f, 0f); + session.SetContenderPose(target.Id, 0f, 120f, MathF.PI); + session.State.SpawnChassisDrop(0f, 120f, Catalog.Anvil); + Assert.True(session.State.TrySwapNearbyChassis(target.Id)); + session.SetContenderPose(target.Id, 0f, 120f, MathF.PI); + target.AiScavengeCooldown = 999f; + + session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil); + Assert.True(session.TrySwapNearbyChassis(shooter.Id)); + var sabotSled = ProceduralWeaponGenerator.CreateDreamSabotSled(); + Assert.True(shooter.Grid.TryMount(sabotSled.Module, "hp.weapon.siege_l")); + + // Settle one tick, then fire once + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 120f, Fire: false, InteractPickup: false, Brake: true)); + session.Step(); + + float targetHpBefore = target.Grid.TotalArmorRatio() + target.Grid.CoreHp; + var events = new List(); + session.DrainStepEvents(events); // flush setup + + bool sawSpawned = false; + bool sawStageTransition = false; + float transitionMaxSpeed = 0f; + bool sawDetonated = false; + + for (int tick = 0; tick < 90; tick++) + { + session.SetHumanInput(0, new PlayerInput( + 0f, 0f, + target.X, target.Z, + Fire: tick == 0, + InteractPickup: false, + Brake: true, + AimWorldY: MatchRules.GetTargetAimY(target.Y, target.Grid.Spec.HalfHeight))); + session.Step(); + + foreach (ref readonly var inst in session.Ordnance.PoolSpan) + { + if (inst.Active && inst.Depth == 1) + { + transitionMaxSpeed = MathF.Max(transitionMaxSpeed, inst.Vel.Length()); + } + } + + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is OrdnanceNodeEvent one) + { + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.Spawned) sawSpawned = true; + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.StageTransition) sawStageTransition = true; + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.Detonated) sawDetonated = true; + } + } + } + + float targetHpAfter = target.Grid.TotalArmorRatio() + target.Grid.CoreHp; + Assert.True(sawSpawned, "Expected Stage 0 Sabot-Sled Spawned event"); + Assert.True(sawStageTransition, "Expected Stage 0 -> Stage 1 StageTransition event at t=0.18s"); + Assert.True(transitionMaxSpeed > 250f, $"Expected Stage 1 RocketBoosted to accelerate >250 m/s, got {transitionMaxSpeed:F1}"); + Assert.True(sawDetonated, "Expected Sabot-Sled warhead detonation"); + Assert.True(targetHpAfter < targetHpBefore, "Expected distant Anvil to take Sabot-Sled damage"); + } + + // 2. Point-blank target (25m): Stage 0 impacts directly before 0.18s without StageTransition or tunneling + using (var session = new ArenaSession(seed: 102, slot0Human: true, skipInitialDrop: true)) + { + var shooter = session.State.Contenders[0]; + var target = session.State.Contenders[1]; + IsolateContenders(session, shooter.Id, target.Id); + + session.SetContenderPose(shooter.Id, 0f, 0f, 0f); + session.SetContenderPose(target.Id, 0f, 25f, MathF.PI); + session.State.SpawnChassisDrop(0f, 25f, Catalog.Anvil); + Assert.True(session.State.TrySwapNearbyChassis(target.Id)); + session.SetContenderPose(target.Id, 0f, 25f, MathF.PI); + + session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil); + Assert.True(session.TrySwapNearbyChassis(shooter.Id)); + var sabotSled = ProceduralWeaponGenerator.CreateDreamSabotSled(); + Assert.True(shooter.Grid.TryMount(sabotSled.Module, "hp.weapon.siege_l")); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 25f, Fire: false, InteractPickup: false, Brake: true)); + session.Step(); + var events = new List(); + session.DrainStepEvents(events); + + float hpBefore = target.Grid.TotalArmorRatio() + target.Grid.CoreHp; + bool sawStageTransition = false; + bool sawDetonated = false; + + for (int tick = 0; tick < 20; tick++) + { + session.SetHumanInput(0, new PlayerInput( + 0f, 0f, + target.X, target.Z, + Fire: tick == 0, + InteractPickup: false, + Brake: true, + AimWorldY: MatchRules.GetTargetAimY(target.Y, target.Grid.Spec.HalfHeight))); + session.Step(); + + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is OrdnanceNodeEvent one) + { + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.StageTransition) sawStageTransition = true; + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.Detonated) sawDetonated = true; + } + } + } + + Assert.False(sawStageTransition, "Point-blank 25m shot should impact in Stage 0 before 0.18s transition"); + Assert.True(sawDetonated, "Expected Stage 0 sabot impact detonation at 25m"); + Assert.True(target.Grid.TotalArmorRatio() + target.Grid.CoreHp < hpBefore); + } + } + + [Fact] + public void DreamWeapon2_LoiteringLaserDrone_OrbitsFiresDownwardLasers_IgnoresNeutralSpectators_AndDiveBombs() + { + using var session = new ArenaSession(seed: 202, slot0Human: true, skipInitialDrop: true); + var shooter = session.State.Contenders[0]; + var enemy = session.State.Contenders[1]; + var neutralSpec = session.State.Spectators.Spectators[0]; + IsolateContenders(session, shooter.Id, enemy.Id); + + session.SetContenderPose(shooter.Id, 0f, 0f, 0f); + session.SetContenderPose(enemy.Id, 0f, 55f, MathF.PI); + session.State.SpawnChassisDrop(0f, 55f, Catalog.Anvil); + Assert.True(session.State.TrySwapNearbyChassis(enemy.Id)); + session.SetContenderPose(enemy.Id, 0f, 55f, MathF.PI); + + // Place a Neutral Spectator inside drone's 110m downward scan radius, well clear of 6m dive-bomb splash around enemy + session.SetSpectatorPose(neutralSpec.Id, 38f, 35f, 0f); + Assert.Equal(SpectatorStance.Neutral, neutralSpec.Stance); + float specHpBefore = neutralSpec.Grid.TotalArmorRatio() + neutralSpec.Grid.CoreHp; + + var droneLauncher = ProceduralWeaponGenerator.CreateDreamLoiteringDrone(); + Assert.True(shooter.Grid.TryMount(droneLauncher.Module, "hp.weapon.roof")); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 55f, Fire: false, InteractPickup: false, Brake: true)); + session.Step(); + var events = new List(); + session.DrainStepEvents(events); + + float enemyHpBefore = enemy.Grid.TotalArmorRatio() + enemy.Grid.CoreHp; + int stageTransitions = 0; + int downwardDroneLasers = 0; + bool sawDiveBombDetonation = false; + + for (int tick = 0; tick < 540; tick++) + { + session.SetHumanInput(0, new PlayerInput( + 0f, 0f, + enemy.X, enemy.Z, + Fire: tick == 0, + InteractPickup: false, + Brake: true, + AimWorldY: enemy.Y + 2f)); + session.Step(); + + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is OrdnanceNodeEvent one) + { + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.StageTransition) + { + stageTransitions++; + } + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.Detonated) + { + sawDiveBombDetonation = true; + } + } + else if (ev is ShotFiredEvent shot && + shot.StartY > 12f && + shot.EndY < shot.StartY - 8f && + (WeaponVisualClass)shot.WeaponClass == WeaponVisualClass.ThermalBeam) + { + downwardDroneLasers++; + } + } + } + + Assert.True(stageTransitions >= 2, $"Expected >=2 stage transitions (climb->loiter->divebomb), got {stageTransitions}"); + Assert.True(downwardDroneLasers >= 6, $"Expected >=6 downward laser beams from loitering drone, got {downwardDroneLasers}"); + Assert.True(sawDiveBombDetonation, "Expected terminal HomingMissile dive-bomb detonation"); + Assert.True(enemy.Grid.TotalArmorRatio() + enemy.Grid.CoreHp < enemyHpBefore, "Expected enemy Anvil to take laser + dive-bomb damage"); + Assert.Equal(SpectatorStance.Neutral, neutralSpec.Stance); + Assert.Equal(specHpBefore, neutralSpec.Grid.TotalArmorRatio() + neutralSpec.Grid.CoreHp); + } + + [Fact] + public void DreamWeapon3_MirvMineBlanket_SplitsIntoArmedMines_IgnoresOwner_DetonatesOnEnemy() + { + using var session = new ArenaSession(seed: 303, slot0Human: true, skipInitialDrop: true); + var shooter = session.State.Contenders[0]; + var enemy = session.State.Contenders[1]; + IsolateContenders(session, shooter.Id, enemy.Id); + + session.SetContenderPose(shooter.Id, 0f, 0f, 0f); + session.SetContenderPose(enemy.Id, 0f, 400f, MathF.PI); // keep enemy clear during deployment + + session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil); + Assert.True(session.TrySwapNearbyChassis(shooter.Id)); + var mirvWeapon = ProceduralWeaponGenerator.CreateDreamMirvMineBlanket(); + Assert.True(shooter.Grid.TryMount(mirvWeapon.Module, "hp.weapon.siege_l")); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 120f, Fire: false, InteractPickup: false, Brake: true)); + session.Step(); + var events = new List(); + session.DrainStepEvents(events); + + bool sawSplit = false; + int minesDeployed = 0; + + // Fire once toward (0, 120) and let carrier reach apex -> split -> land as armed mines + for (int tick = 0; tick < 240; tick++) + { + session.SetHumanInput(0, new PlayerInput( + 0f, 0f, + 0f, 120f, + Fire: tick == 0, + InteractPickup: false, + Brake: true)); + session.Step(); + + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is OrdnanceNodeEvent one) + { + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.Split) sawSplit = true; + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.StageTransition && + (OrdnanceVisualShape)one.VisualShape == OrdnanceVisualShape.Mine) + { + minesDeployed++; + } + } + } + } + + Assert.True(sawSplit, "Expected MIRV carrier to Split at apex"); + Assert.True(minesDeployed >= 8, $"Expected >=8 deployed StationaryMines, got {minesDeployed}"); + + // Pick a live armed mine position + Vector3 minePos = Vector3.Zero; + int activeMinesBeforeOwner = 0; + foreach (ref readonly var inst in session.Ordnance.PoolSpan) + { + if (inst.Active && inst.Def.Motion == OrdnanceMotion.StationaryMine) + { + activeMinesBeforeOwner++; + minePos = inst.Pos; + } + } + Assert.True(activeMinesBeforeOwner >= 8); + + // Shooter drives directly over own minefield -> ProximityIgnoreOwner must prevent detonation! + float shooterHpBefore = shooter.Grid.TotalArmorRatio() + shooter.Grid.CoreHp; + session.SetContenderPose(shooter.Id, minePos.X, minePos.Z, 0f); + for (int t = 0; t < 15; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, minePos.X, minePos.Z + 10f, Fire: false, InteractPickup: false, Brake: true)); + session.Step(); + } + Assert.Equal(shooterHpBefore, shooter.Grid.TotalArmorRatio() + shooter.Grid.CoreHp); + + // Move shooter away, then place enemy contender right onto the mine -> must detonate and damage enemy! + session.SetContenderPose(shooter.Id, -100f, -100f, 0f); + float enemyHpBefore = enemy.Grid.TotalArmorRatio() + enemy.Grid.CoreHp; + session.SetContenderPose(enemy.Id, minePos.X, minePos.Z, 0f); + events.Clear(); + session.DrainStepEvents(events); + + bool mineDetonated = false; + for (int t = 0; t < 10; t++) + { + session.Step(); + events.Clear(); + session.DrainStepEvents(events); + if (events.OfType().Any(e => (OrdnanceEventKind)e.Kind == OrdnanceEventKind.Detonated)) + { + mineDetonated = true; + } + } + + Assert.True(mineDetonated, "Expected armed mine to detonate when enemy entered 6.5m proximity"); + Assert.True(enemy.Grid.TotalArmorRatio() + enemy.Grid.CoreHp < enemyHpBefore); + } + + [Fact] + public void SafetyCaps_12MirvSpamEnforces256PoolCapAndDepthUnder4_AndRejectsDepth5OrCycles() + { + // 1. Reject depth-5 chain (depth 4 node violates MaxAllowedDepth=4) + var d4 = new OrdnanceNodeDef { Motion = OrdnanceMotion.HitscanBeam }; + var d3 = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = d4 } } + }; + var d2 = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = d3 } } + }; + var d1 = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = d2 } } + }; + var d0 = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = d1 } } + }; + Assert.Throws(() => OrdnanceGraphValidator.ValidateAndFlatten(d0)); + + // 2. Reject cyclic graph + var cycleA = new OrdnanceNodeDef { Motion = OrdnanceMotion.Ballistic }; + var cycleB = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = cycleA } } + }; + var cycleRoot = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = cycleB } + } + }; + // Hook cycleA -> cycleRoot via reflection-free self-loop using array mutation + var aRules = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = cycleRoot } }; + var cycleSelf = new OrdnanceNodeDef { Motion = OrdnanceMotion.Ballistic, Triggers = aRules }; + aRules[0] = new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = cycleSelf }; + Assert.Throws(() => OrdnanceGraphValidator.ValidateAndFlatten(cycleSelf)); + + // 3. 12 contenders firing MIRVs simultaneously for 600 ticks strictly obey ActiveCount <= 256 & MaxObservedDepth < 4 + using var session = new ArenaSession(seed: 404, slot0Human: false, skipInitialDrop: true); + var mirv = ProceduralWeaponGenerator.CreateDreamMirvMineBlanket(); + for (int i = 0; i < session.State.Contenders.Count; i++) + { + var c = session.State.Contenders[i]; + float ang = (i / 12f) * MathF.Tau; + session.SetContenderPose(c.Id, MathF.Cos(ang) * 140f, MathF.Sin(ang) * 140f, ang + MathF.PI); + session.State.SpawnChassisDrop(c.X, c.Z, Catalog.Anvil); + session.State.TrySwapNearbyChassis(c.Id); + session.SetContenderPose(c.Id, MathF.Cos(ang) * 140f, MathF.Sin(ang) * 140f, ang + MathF.PI); + c.Grid.TryMount(mirv.Module, "hp.weapon.siege_l"); + c.Grid.TryMount(mirv.Module, "hp.weapon.siege_r"); + } + + int maxObservedActive = 0; + for (int tick = 0; tick < 600; tick++) + { + for (int i = 0; i < session.State.Contenders.Count; i++) + { + var c = session.State.Contenders[i]; + if (c.IsGroundedActive) + { + c.AimX = 0f; + c.AimY = 4f; + c.AimZ = 0f; + c.FireCmd = true; + } + } + session.Step(); + maxObservedActive = Math.Max(maxObservedActive, session.Ordnance.ActiveCount); + Assert.InRange(session.Ordnance.ActiveCount, 0, OrdnanceRuntime.PoolCapacity); + Assert.True(session.Ordnance.MaxObservedDepth < OrdnanceNodeDef.MaxAllowedDepth); + } + + Assert.True(maxObservedActive > 64, $"Expected heavy concurrent MIRV saturation, peaked at {maxObservedActive}"); + } + + [Fact] + public void ZeroTunneling_400MetersPerSecondSabot_Hits1Point5MeterWallWithoutPassingThroughTargetBehind() + { + using var session = new ArenaSession(seed: 505, slot0Human: true, skipInitialDrop: true); + var shooter = session.State.Contenders[0]; + var targetBehindWall = session.State.Contenders[1]; + IsolateContenders(session, shooter.Id, targetBehindWall.Id); + + // Add a thin 1.5m-thick static wall directly in world between shooter (0, 0) and target (0, 50) + session.World.AddStaticBox( + 90UL, + (0f, 3.0f, 25f), + (12f, 6.0f, 0.75f), // 1.5m thick in Z! + friction: 0.4f, + restitution: 0.05f); + + session.SetContenderPose(shooter.Id, 0f, 0f, 0f); + session.SetContenderPose(targetBehindWall.Id, 0f, 50f, MathF.PI); + session.State.SpawnChassisDrop(0f, 50f, Catalog.Anvil); + Assert.True(session.State.TrySwapNearbyChassis(targetBehindWall.Id)); + session.SetContenderPose(targetBehindWall.Id, 0f, 50f, MathF.PI); + + session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil); + Assert.True(session.TrySwapNearbyChassis(shooter.Id)); + var gaussRail = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.HypervelocityGaussRail); + Assert.True(shooter.Grid.TryMount(gaussRail.Module, "hp.weapon.siege_l")); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 50f, Fire: false, InteractPickup: false, Brake: true)); + session.Step(); + var events = new List(); + session.DrainStepEvents(events); + + float behindHpBefore = targetBehindWall.Grid.TotalArmorRatio() + targetBehindWall.Grid.CoreHp; + bool wallHitRecorded = false; + + for (int t = 0; t < 30; t++) + { + session.SetHumanInput(0, new PlayerInput( + 0f, 0f, + 0f, 50f, + Fire: t == 0, + InteractPickup: false, + Brake: true, + AimWorldY: shooter.Y)); + session.Step(); + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is HitImpactEvent hit && hit.TargetKind == (byte)HitTargetKind.StaticCover && hit.TargetId == 90) + { + wallHitRecorded = true; + Assert.InRange(hit.HitZ, 24.0f, 26.0f); + } + } + } + + Assert.True(wallHitRecorded, "Expected 420m/s Gauss sabot to strike 1.5m-thick wall without tunneling"); + Assert.Equal(behindHpBefore, targetBehindWall.Grid.TotalArmorRatio() + targetBehindWall.Grid.CoreHp); + } + + [Fact] + public void AiPowerScore_EquipsMirvOverStarterMg762_AndNetUnion13ReplicatesUnder1152UdpCap() + { + // 1. AI PowerScore prefers MIRV Mine-Blanket over Mg762 + var state = new MatchState(seed: 606, skipInitialDrop: true); + var ai = state.Contenders[1]; + state.SpawnChassisDrop(ai.X, ai.Z, Catalog.Anvil); + Assert.True(state.TrySwapNearbyChassis(ai.Id)); + Assert.True(ai.Grid.TryMount(Catalog.Mg762, "hp.weapon.siege_l")); + Assert.True(ai.Grid.TryMount(Catalog.Mg762, "hp.weapon.siege_r")); + Assert.True(ai.Grid.TryMount(Catalog.Mg762, "hp.weapon.sponson_l")); + Assert.True(ai.Grid.TryMount(Catalog.Mg762, "hp.weapon.sponson_r")); + + var mirv = ProceduralWeaponGenerator.CreateDreamMirvMineBlanket(); + ai.Grid.Cargo.Add(mirv.Module); + + MatchRules.UpdateAiContenders(state, 1f / 60f, (_, _, _, _, _, _) => true); + Assert.Contains(ai.Grid.Mounted, m => m.Spec.Id == mirv.Module.Id); + + // 2. [Union(13)] OrdnanceNodeEvent MessagePack round-trip & ServerMatchHost -> RemoteArenaSession PVS replication + var ordEv = new OrdnanceNodeEvent + { + OrdnanceId = 42, + ParentOrdnanceId = 7, + Kind = (byte)OrdnanceEventKind.StageTransition, + IsSpectatorShooter = false, + ShooterId = 0, + WeaponKey = mirv.Key, + NodeDefIndex = 1, + PosX = 10f, + PosY = 25f, + PosZ = 40f, + VelX = 0f, + VelY = 12f, + VelZ = 180f, + TargetEntityId = 1, + TargetIsSpectator = false, + SimTime = 4.25f, + VisualShape = (byte)OrdnanceVisualShape.Rocket, + ColorRgba = 0xF2C422FFu + }; + byte[] encoded = MessagePackSerializer.Serialize(ordEv); + var decoded = Assert.IsType(MessagePackSerializer.Deserialize(encoded)); + Assert.Equal(ordEv.OrdnanceId, decoded.OrdnanceId); + Assert.Equal(ordEv.WeaponKey, decoded.WeaponKey); + Assert.Equal(ordEv.ColorRgba, decoded.ColorRgba); + + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 707, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var serverEp = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + using var client = new RemoteArenaSession(serverEp, "Client01"); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var deadline = DateTimeOffset.UtcNow.AddSeconds(3); + while (DateTimeOffset.UtcNow < deadline && !client.IsJoined) + { + nowMs += 16; + host.StepOnce(nowMs); + client.PumpNetwork(); + System.Threading.Thread.Sleep(2); + } + Assert.True(client.IsJoined); + + int cSlot = client.LocalContenderId; + int shooterSlot = (cSlot + 1) % MatchState.ContenderCount; + host.Session.SetContenderPose(shooterSlot, 0f, 0f, 0f); + host.Session.SetContenderPose(cSlot, 0f, 20f, 0f); + host.Session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil); + Assert.True(host.Session.TrySwapNearbyChassis(shooterSlot)); + host.Session.State.Contenders[shooterSlot].Grid.TryMount(mirv.Module, "hp.weapon.siege_l"); + host.Session.SetContenderPose(shooterSlot, 0f, 0f, 0f); + host.Session.SetContenderPose(cSlot, 0f, 20f, 0f); + + var clientEvents = new List(); + bool clientReceivedOrdnanceEvent = false; + for (int t = 0; t < 60; t++) + { + nowMs += 16; + var shooter = host.Session.State.Contenders[shooterSlot]; + shooter.AimX = 0f; + shooter.AimY = shooter.Y; + shooter.AimZ = 120f; + shooter.FireCmd = (t == 0); + host.StepOnce(nowMs); + client.PumpNetwork(); + client.BeginRenderFrame(1f / 60f, 1f); + clientEvents.Clear(); + client.DrainSimEvents(clientEvents); + if (clientEvents.OfType().Any()) + { + clientReceivedOrdnanceEvent = true; + break; + } + System.Threading.Thread.Sleep(2); + } + + Assert.True(clientReceivedOrdnanceEvent, "Expected remote client in PVS to receive [Union(13)] OrdnanceNodeEvent"); + } + + [Fact] + public void PiercingHitscanBeam_BlockedByDesertTerrainRidge_ZeroOccludedDamage() + { + var piercingArchs = new[] + { + WeaponArchetypeKind.RefractingPrismLance, + WeaponArchetypeKind.RailPlasmaBeam + }; + + foreach (var arch in piercingArchs) + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true, skipInitialDrop: true); + IsolateContenders(session, 0, 1); + + TerrainBrush tallMesa = default; + bool foundMesa = false; + for (int i = 0; i < session.State.Terrain.Brushes.Count; i++) + { + var b = session.State.Terrain.Brushes[i]; + if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f) + { + tallMesa = b; + foundMesa = true; + break; + } + } + Assert.True(foundMesa, "Expected tall >= 22m Mesa in Desert terrain"); + + float shooterX = tallMesa.X - tallMesa.RadiusX - 16f; + float targetX = tallMesa.X + tallMesa.RadiusX + 16f; + session.SetContenderPose(0, shooterX, tallMesa.Z, yaw: MathF.PI * 0.5f); + session.SetContenderPose(1, targetX, tallMesa.Z, yaw: -MathF.PI * 0.5f); + + session.State.SpawnChassisDrop(shooterX, tallMesa.Z, Catalog.Anvil); + Assert.True(session.TrySwapNearbyChassis(0)); + session.SetContenderPose(0, shooterX, tallMesa.Z, yaw: MathF.PI * 0.5f); + + var spec = ProceduralWeaponGenerator.CreateDreamWeapon(arch, seed: 0xBEEF01UL, tier: 3); + Assert.True(spec.RootNode.Motion == OrdnanceMotion.HitscanBeam); + Assert.True(spec.RootNode.MaxPenetrations >= 1, $"Expected piercing beam on {arch}"); + + var shooter = session.State.Contenders[0]; + var target = session.State.Contenders[1]; + shooter.Grid.Mounted.RemoveAll(m => m.Spec.Kind == HardpointKind.Weapon); + Assert.True(shooter.Grid.TryMount(spec.Module, "hp.weapon.siege_l")); + + // Force beam range to reach past targetX if unoccluded + float distToTarget = MathF.Abs(targetX - shooterX); + Assert.True(spec.RootNode.Range > distToTarget, + $"Expected beam range {spec.RootNode.Range} > target distance {distToTarget}"); + + float targetCoreBefore = target.Grid.CoreHp; + float targetArmorBefore = target.Grid.TotalArmorRatio(); + + var stepEvents = new List(); + session.DrainStepEvents(stepEvents); + stepEvents.Clear(); + + // Aim directly at target's center on the far side of the mountain ridge + for (int t = 0; t < 4; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: target.X, + AimWorldZ: target.Z, + Fire: t == 0, + InteractPickup: false, + Brake: true)); + session.Step(); + } + + session.DrainStepEvents(stepEvents); + var shots = stepEvents.OfType() + .Where(s => !s.IsSpectatorShooter && s.ShooterId == 0) + .ToList(); + Assert.NotEmpty(shots); + + // Beam must terminate on the near face of the mesa, strictly before targetX + foreach (var shot in shots) + { + Assert.True(shot.EndX < targetX - 5f, + $"Expected {arch} beam to terminate on Desert ridge before targetX={targetX:F1}, got EndX={shot.EndX:F1}"); + } + + // Occluded target must take ZERO armor & core damage + Assert.Equal(targetCoreBefore, target.Grid.CoreHp); + Assert.Equal(targetArmorBefore, target.Grid.TotalArmorRatio()); + } + } + + [Fact] + public void Validator_RejectsWhileAliveHitscanSplitFanOutBypass_AndNegativeScalars() + { + // WhileAlive pulsing a HitscanBeam whose Impact triggers Split(12) -> 9 * 12 = 108 > MaxShotSubSpawnBudget (16) + var bomblet = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = 24f, + DirectDamage = 15f, + MaxLifetime = 3f + }; + var pulsedBeamWithSplit = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + Range = 110f, + DirectDamage = 12f, + Triggers = new[] + { + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.Impact, + Action = OrdnanceTriggerAction.Split, + ChildNode = bomblet, + SplitCount = 12, + SplitConeDeg = 45f + } + } + }; + var droneFanOutBypass = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.LoiterOrbit, + LoiterAltitudeAgl = 35f, + LoiterOrbitRadius = 15f, + WhileAlive = new OrdnanceWhileAliveDef + { + Interval = 0.45f, + MaxPulses = 9, + TriggerScanRadius = 95f, + ChildNode = pulsedBeamWithSplit + } + }; + Assert.Throws(() => OrdnanceGraphValidator.ValidateAndFlatten(droneFanOutBypass)); + + // Negative Trigger Threshold + Assert.Throws(() => OrdnanceGraphValidator.ValidateAndFlatten(new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = -0.5f, Action = OrdnanceTriggerAction.Detonate } } + })); + + // Negative Trigger MinAge + Assert.Throws(() => OrdnanceGraphValidator.ValidateAndFlatten(new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Apex, MinAge = -0.1f, Action = OrdnanceTriggerAction.Detonate } } + })); + + // Negative LoiterAltitudeAgl + Assert.Throws(() => OrdnanceGraphValidator.ValidateAndFlatten(new OrdnanceNodeDef + { + Motion = OrdnanceMotion.LoiterOrbit, + LoiterAltitudeAgl = -5f + })); + + // Negative WhileAlive RadialDamage + Assert.Throws(() => OrdnanceGraphValidator.ValidateAndFlatten(new OrdnanceNodeDef + { + Motion = OrdnanceMotion.StationaryMine, + WhileAlive = new OrdnanceWhileAliveDef { Interval = 0.5f, RadialDamage = -10f, RadialRadius = 4f } + })); + } + + [Fact] + public void PvsTerminalOrdnanceEvent_OutsidePvs_ScrubsFinalCoordinates() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var serverEp = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + using var client = new RemoteArenaSession(serverEp, "PvsObserver"); + + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var deadline = DateTimeOffset.UtcNow.AddSeconds(3); + while (DateTimeOffset.UtcNow < deadline && !client.IsJoined) + { + nowMs += 16; + host.StepOnce(nowMs); + client.PumpNetwork(); + System.Threading.Thread.Sleep(2); + } + Assert.True(client.IsJoined); + + TerrainBrush tallMesa = default; + bool foundMesa = false; + for (int i = 0; i < host.Session.State.Terrain.Brushes.Count; i++) + { + var b = host.Session.State.Terrain.Brushes[i]; + if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f) + { + tallMesa = b; + foundMesa = true; + break; + } + } + Assert.True(foundMesa); + + int obsSlot = client.LocalContenderId; + int shooterSlot = (obsSlot + 1) % MatchState.ContenderCount; + + // Place observer and shooter together on the near side of the tall mesa with clear LOS + float nearX = tallMesa.X - tallMesa.RadiusX - 30f; + float farX = tallMesa.X + tallMesa.RadiusX + 35f; + host.Session.SetContenderPose(obsSlot, nearX - 10f, tallMesa.Z, yaw: MathF.PI * 0.5f); + host.Session.SetContenderPose(shooterSlot, nearX, tallMesa.Z, yaw: MathF.PI * 0.5f); + host.Session.State.SpawnChassisDrop(nearX, tallMesa.Z, Catalog.Anvil); + Assert.True(host.Session.TrySwapNearbyChassis(shooterSlot)); + host.Session.SetContenderPose(shooterSlot, nearX, tallMesa.Z, yaw: MathF.PI * 0.5f); + host.Session.SetHumanSlot(shooterSlot, true, "Shooter"); + + var rocketSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.DumbRocketPod, seed: 0x5511UL, tier: 1); + var shooter = host.Session.State.Contenders[shooterSlot]; + shooter.Grid.Mounted.RemoveAll(m => m.Spec.Kind == HardpointKind.Weapon); + Assert.True(shooter.Grid.TryMount(rocketSpec.Module, "hp.weapon.siege_l")); + + var clientEvents = new List(); + var receivedSpawnedIds = new HashSet(); + OrdnanceNodeEvent? scrubbedTerminal = null; + bool movedObserverBehindMesa = false; + + for (int t = 0; t < 240 && scrubbedTerminal is null; t++) + { + nowMs += 17; + host.Session.SetHumanInput(shooterSlot, new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: nearX - 80f, // fire away from the mesa so projectile stays on near side while observer moves behind mesa + AimWorldZ: tallMesa.Z + 18f, + Fire: receivedSpawnedIds.Count == 0, + InteractPickup: false, + Brake: true)); + + if (receivedSpawnedIds.Count > 0 && !movedObserverBehindMesa) + { + // Move observer behind the >=22m tall mesa so both shooter & rocket exit observer PVS before detonation + host.Session.SetContenderPose(obsSlot, farX, tallMesa.Z, yaw: MathF.PI * 0.5f); + movedObserverBehindMesa = true; + } + + host.StepOnce(nowMs); + client.PumpNetwork(); + client.BeginRenderFrame(1f / 60f, 1f); + clientEvents.Clear(); + client.DrainSimEvents(clientEvents); + + foreach (var ev in clientEvents.OfType()) + { + if (ev.Kind == (byte)OrdnanceEventKind.Spawned) + { + receivedSpawnedIds.Add(ev.OrdnanceId); + } + else if (ev.Kind is 3 or 4 or 5 && receivedSpawnedIds.Contains(ev.OrdnanceId)) + { + // If terminal happened outside observer PVS, it must arrive scrubbed as Expired at (0,0,0) + if (ev.Kind == (byte)OrdnanceEventKind.Expired && ev.PosX == 0f && ev.PosY == 0f && ev.PosZ == 0f) + { + scrubbedTerminal = ev; + break; + } + } + } + System.Threading.Thread.Sleep(2); + } + + Assert.NotEmpty(receivedSpawnedIds); + Assert.NotNull(scrubbedTerminal); + Assert.Equal((byte)OrdnanceEventKind.Expired, scrubbedTerminal!.Kind); + Assert.Equal(0f, scrubbedTerminal.PosX); + Assert.Equal(0f, scrubbedTerminal.PosY); + Assert.Equal(0f, scrubbedTerminal.PosZ); + Assert.Equal(-1, scrubbedTerminal.TargetEntityId); + } + + [Fact] + public void Validator_CombinesWhileAliveAndTriggerBudgetsAdditively() + { + var mine = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.StationaryMine, + MaxLifetime = 6f, + DirectDamage = 10f + }; + var pulseBeam = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + Range = 80f, + DirectDamage = 5f, + Triggers = new[] + { + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.Impact, + Action = OrdnanceTriggerAction.Split, + SplitCount = 1, + ChildNode = mine + } + } + }; + var combined = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.LoiterOrbit, + MaxLifetime = 5f, + WhileAlive = new OrdnanceWhileAliveDef + { + Interval = 0.25f, + MaxPulses = 10, + ChildNode = pulseBeam + }, + Triggers = new[] + { + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.Timeout, + Threshold = 5f, + Action = OrdnanceTriggerAction.Split, + SplitCount = 10, + ChildNode = mine + } + } + }; + + var ex = Assert.Throws(() => OrdnanceGraphValidator.ValidateAndFlatten(combined)); + Assert.Contains("sub-spawn budget", ex.Message, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void AlliedPdAndHitscan_DoNotInterceptSquadmateOrdnance() + { + using var session = new ArenaSession(seed: 101, slot0Human: true, skipInitialDrop: true, squadSize: 3); + var ally0 = session.State.Contenders[0]; + var ally1 = session.State.Contenders[1]; + var enemy = session.State.Contenders[3]; + Assert.True(session.State.AreAllies(ally0.Id, ally1.Id)); + Assert.False(session.State.AreAllies(ally0.Id, enemy.Id)); + IsolateContenders(session, ally0.Id, ally1.Id, enemy.Id); + + // Place Ally 0 and Ally 1 nearby facing Enemy so Ally 1's PD + RailPlasmaBeam shoot across Ally 0's ordnance + session.SetContenderPose(ally0.Id, 0f, 0f, 0f); + session.SetContenderPose(ally1.Id, 16f, 16f, -0.5f); + session.SetContenderPose(enemy.Id, 0f, 80f, MathF.PI); + + foreach (var c in new[] { ally0, ally1, enemy }) + { + session.State.SpawnChassisDrop(c.X, c.Z, Catalog.Anvil); + Assert.True(session.State.TrySwapNearbyChassis(c.Id)); + c.Grid.Mounted.RemoveAll(m => m.Spec.Kind == HardpointKind.Weapon); + } + session.SetContenderPose(ally0.Id, 0f, 0f, 0f); + session.SetContenderPose(ally1.Id, 16f, 16f, -0.5f); + session.SetContenderPose(enemy.Id, 0f, 80f, MathF.PI); + + var droneSpec = ProceduralWeaponGenerator.CreateDreamLoiteringDrone(); + var swarmSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.HomingSwarmPod); + var railSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.RailPlasmaBeam); + Assert.True(ally0.Grid.TryMount(droneSpec.Module, "hp.weapon.siege_l")); + Assert.True(ally0.Grid.TryMount(swarmSpec.Module, "hp.weapon.siege_r")); + Assert.True(ally1.Grid.TryMount(Catalog.ImperialAegisPd, "hp.weapon.sponson_l")); + Assert.True(ally1.Grid.TryMount(railSpec.Module, "hp.weapon.siege_l")); + Assert.True(ally1.Grid.TryMount(Catalog.GoldRadiator, "hp.radiator.l")); + Assert.True(ally1.Grid.TryMount(Catalog.GoldRadiator, "hp.radiator.r")); + + session.SetHumanSlot(ally1.Id, true, "Ally1"); + session.SetHumanInput(ally0.Id, new PlayerInput(0f, 0f, enemy.X, enemy.Z, Fire: false, InteractPickup: false, Brake: true, AimWorldY: enemy.Y + 2f)); + session.SetHumanInput(ally1.Id, new PlayerInput(0f, 0f, 0f, 25f, Fire: false, InteractPickup: false, Brake: true, AimWorldY: 12f)); + session.Step(); + + var events = new List(); + session.DrainStepEvents(events); + + int allyOrdnanceSpawned = 0; + int allyOrdnanceIntercepted = 0; + int railShotsWhileAllyOrdnanceAirborne = 0; + + for (int tick = 0; tick < 360; tick++) + { + Vector3? allyAirbornePos = null; + var pool = session.Ordnance.PoolSpan; + for (int i = 0; i < pool.Length; i++) + { + ref readonly var inst = ref pool[i]; + if (!inst.Active || inst.IsSpectatorShooter || inst.ShooterContenderId != ally0.Id) + { + continue; + } + if (inst.Def.InterceptHp > 0f && + inst.Def.Motion is OrdnanceMotion.LoiterOrbit or OrdnanceMotion.HomingMissile) + { + allyAirbornePos = inst.Pos; + break; + } + } + + // Keep Ally 1 cool enough to continuously fire PD + RailPlasmaBeam directly at Ally 0's airborne ordnance + foreach (var mod in ally1.Grid.Mounted) + { + mod.CurrentTemp = mod.Spec.OptimalTemp; + } + + session.SetHumanInput(ally0.Id, new PlayerInput( + 0f, 0f, + enemy.X, enemy.Z, + Fire: tick < 5, + InteractPickup: false, + Brake: true, + AimWorldY: enemy.Y + 2f)); + + if (allyAirbornePos.HasValue) + { + var p = allyAirbornePos.Value; + session.SetHumanInput(ally1.Id, new PlayerInput( + 0f, 0f, + p.X, p.Z, + Fire: true, + InteractPickup: false, + Brake: true, + AimWorldY: p.Y)); + railShotsWhileAllyOrdnanceAirborne++; + } + else + { + session.SetHumanInput(ally1.Id, new PlayerInput( + 0f, 0f, + enemy.X, enemy.Z, + Fire: false, + InteractPickup: false, + Brake: true, + AimWorldY: enemy.Y + 2f)); + } + + session.Step(); + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is OrdnanceNodeEvent one && !one.IsSpectatorShooter && one.ShooterId == ally0.Id) + { + if (one.Kind == (byte)OrdnanceEventKind.Spawned) + { + allyOrdnanceSpawned++; + } + else if (one.Kind == (byte)OrdnanceEventKind.Intercepted) + { + allyOrdnanceIntercepted++; + } + } + } + } + + Assert.True(allyOrdnanceSpawned >= 2, $"Expected Ally 0 to spawn drone + swarm ordnance, got {allyOrdnanceSpawned}"); + Assert.True(railShotsWhileAllyOrdnanceAirborne >= 10, $"Expected Ally 1 to aim RailPlasmaBeam + PD at airborne ally ordnance, got {railShotsWhileAllyOrdnanceAirborne}"); + Assert.Equal(0, allyOrdnanceIntercepted); + } + } +} diff --git a/tests/RustToDust.Tests/PlaytestFixesTests.cs b/tests/RustToDust.Tests/PlaytestFixesTests.cs new file mode 100644 index 0000000..0637618 --- /dev/null +++ b/tests/RustToDust.Tests/PlaytestFixesTests.cs @@ -0,0 +1,536 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class PlaytestFixesTests + { + private static void IsolateContenders(ArenaSession session, params int[] keepIds) + { + var keep = keepIds.ToHashSet(); + for (int i = 0; i < session.State.Contenders.Count; i++) + { + var c = session.State.Contenders[i]; + if (!keep.Contains(c.Id)) + { + session.SetContenderPose(c.Id, -680f + i * 10f, -680f); + } + } + for (int i = 0; i < session.State.Spectators.Spectators.Count; i++) + { + var s = session.State.Spectators.Spectators[i]; + session.SetSpectatorPose(s.Id, 680f, -680f + i * 4f); + } + } + + [Fact] + public void EqualStart_DesertAndSion_AllContendersStartJackal_MinSpacing220m_NoTick0Ambush() + { + int[] seeds = { 12, 42, 77 }; + ArenaMapKind[] maps = { ArenaMapKind.Desert, ArenaMapKind.Sion }; + + foreach (var map in maps) + { + foreach (int seed in seeds) + { + using var session = new ArenaSession(seed, map); + var state = session.State; + Assert.Equal(MatchState.ContenderCount, state.Contenders.Count); + + // 1. Every contender (player + 11 AI) starts in stock Jackal with starter loadout + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + Assert.Equal(Catalog.Jackal.Id, c.Grid.Spec.Id); + Assert.NotNull(c.Grid.GetMountedOn("hp.weapon.roof")); + Assert.NotNull(c.Grid.GetMountedOn("hp.engine.rear")); + Assert.NotNull(c.Grid.GetMountedOn("hp.radiator.rear")); + } + + // 2. Pairwise minimum separation >= 220m across all 12 contenders + for (int i = 0; i < state.Contenders.Count; i++) + { + for (int j = i + 1; j < state.Contenders.Count; j++) + { + var a = state.Contenders[i]; + var b = state.Contenders[j]; + float dx = a.X - b.X; + float dz = a.Z - b.Z; + float dist = MathF.Sqrt(dx * dx + dz * dz); + Assert.True(dist >= 220f, + $"Map={map}, Seed={seed}: Contenders {a.Id} and {b.Id} spawned too close ({dist:F1}m < 220m)"); + } + } + + // 3. Step Wave 0 gear drop duration so Wave 0 gear pods touch down into GroundDrops; all 14 non-Jackal chassis exist + int gearDropTicks = map == ArenaMapKind.Sion ? 1600 : 900; + for (int t = 0; t < gearDropTicks; t++) + { + session.Step(); + } + var droppedChassisIds = state.GroundDrops + .Where(d => d.Chassis is not null) + .Select(d => d.Chassis!.Id) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + foreach (var spec in Catalog.AllChassis) + { + if (!string.Equals(spec.Id, Catalog.Jackal.Id, StringComparison.OrdinalIgnoreCase)) + { + Assert.Contains(spec.Id, droppedChassisIds); + } + } + + if (map == ArenaMapKind.Sion) + { + int nearRingDrops = state.GroundDrops.Count(d => + { + float r = MathF.Sqrt(d.X * d.X + d.Z * d.Z); + return r >= 110f && r <= 190f; + }); + Assert.True(nearRingDrops >= 3, + $"Sion Seed={seed}: Expected >= 3 reachable drops within 110-190m ring sector, got {nearRingDrops}"); + } + + // 4. Zero tick-0 spawn ambush (instant ground start check) + using var instantSession = new ArenaSession(seed, map, skipInitialDrop: true); + var instantState = instantSession.State; + var player = instantState.Contenders[0]; + float initialHp = player.Grid.CoreHp; + instantSession.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 10f, false, false, true)); + instantSession.Step(); + + for (int i = 1; i < instantState.Contenders.Count; i++) + { + var ai = instantState.Contenders[i]; + Assert.False(ai.FireCmd, $"Map={map}, Seed={seed}: AI {ai.Id} fired on tick 0!"); + } + Assert.Equal(initialHp, player.Grid.CoreHp); + } + } + } + + [Fact] + public void AiScavenge_JackalMovesTowardAndSwapsIntoHornetAndMechDrops() + { + // Part A: AI Jackal (950 kg) must pick up Hornet (820 kg) via GetChassisUpgradeScore (> 0) + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true); + IsolateContenders(session, 0, 1); + var player = session.State.Contenders[0]; + var ai = session.State.Contenders[1]; + + // Clear unrelated drops so Hornet is the clean target + foreach (var d in session.State.GroundDrops) + { + d.PickedUp = true; + } + + session.SetContenderPose(player.Id, -450f, -450f, yaw: 0f); + session.SetContenderPose(ai.Id, 0f, 0f, yaw: 0f); + ai.AiScavengeCooldown = 0f; + + session.State.SpawnChassisDrop(0f, 45f, Catalog.Hornet); + Assert.True(Catalog.GetChassisUpgradeScore(Catalog.Hornet) > Catalog.GetChassisUpgradeScore(Catalog.Jackal)); + + for (int tick = 0; tick < 240 && ai.Grid.Spec.Id == Catalog.Jackal.Id; tick++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + } + + Assert.Equal(Catalog.Hornet.Id, ai.Grid.Spec.Id); + } + + // Part B: AI Jackal picks up heavy mech drop (Breaker) + { + using var session = new ArenaSession(seed: 77, ArenaMapKind.Desert, slot0Human: true); + IsolateContenders(session, 0, 1); + var player = session.State.Contenders[0]; + var ai = session.State.Contenders[1]; + + foreach (var d in session.State.GroundDrops) + { + d.PickedUp = true; + } + + session.SetContenderPose(player.Id, -450f, -450f, yaw: 0f); + session.SetContenderPose(ai.Id, 0f, 0f, yaw: 0f); + ai.AiScavengeCooldown = 0f; + + session.State.SpawnChassisDrop(0f, 48f, Catalog.Breaker); + for (int tick = 0; tick < 240 && ai.Grid.Spec.Id == Catalog.Jackal.Id; tick++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + } + + Assert.Equal(Catalog.Breaker.Id, ai.Grid.Spec.Id); + } + } + + [Fact] + public void NaturalizedBotAim_OffAxisSlewAndJinkOvershoot_ZeroOccludedLeak() + { + // 1. 90-degree off-axis slew delay + using (var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true)) + { + IsolateContenders(session, 0, 1); + var player = session.State.Contenders[0]; + var ai = session.State.Contenders[1]; + + // Place AI facing +Z (yaw = 0) and player 60m due +X (90 degrees off-axis) in open LOS + session.SetContenderPose(ai.Id, 0f, 0f, yaw: 0f); + session.SetContenderPose(player.Id, 60f, 0f, yaw: 0f); + ai.AiScavengeCooldown = 999f; + + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + Assert.Equal(player.Id, ai.AiTargetContenderId); + Assert.False(ai.FireCmd, "90-degree off-axis AI must not snap-fire on tick 0 before slewing into cone"); + + bool eventuallyFired = false; + for (int t = 0; t < 75; t++) + { + session.SetContenderPose(player.Id, 60f, 0f, yaw: 0f); + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + if (ai.FireCmd) + { + eventuallyFired = true; + break; + } + } + Assert.True(eventuallyFired, "AI must acquire and fire after slewing onto 90-degree off-axis target"); + } + + // 2. Lateral jink overshoot > 2.5m at 70m + dynamic spread scaling with crossing angular rate + { + const float dt = 1f / 60f; + var shooterGrid = Catalog.CreateStarterBuggy(); + var targetGrid = Catalog.CreateStarterBuggy(); + var target = new ContenderState(9, "Jinker", false, targetGrid, 0f, 70f, 0f); + target.Y = 1.5f; + + var tracker = new PhysicalAimTracker(); + tracker.Reset(0f); + var eyePos = new Vector3(0f, 2.0f, 0f); + + // Stationary spread baseline + AimTrackerHelper.StepTrackedAim( + ref tracker, shooterGrid, eyePos, 0f, 0f, 0f, target, dt, + out _, out _, out _, out _); + float stationarySpread = tracker.DynamicSpreadRad; + + // Steady lateral run at +30 m/s along +X for 1.2s (72 ticks) + float vx = 30f; + for (int t = 0; t < 72; t++) + { + target.X += vx * dt; + target.VelX = vx; + target.VelZ = 0f; + AimTrackerHelper.StepTrackedAim( + ref tracker, shooterGrid, eyePos, 0f, 0f, 0f, target, dt, + out _, out _, out _, out _); + } + + float crossingSpread = tracker.DynamicSpreadRad; + Assert.True(crossingSpread > stationarySpread + 0.04f, + $"Expected crossing angular rate to inflate DynamicSpreadRad (stat={stationarySpread:F4}, cross={crossingSpread:F4})"); + + // Sudden lateral jink: reverse to -30 m/s for 0.18s (11 ticks) + vx = -30f; + float maxOvershootX = 0f; + for (int t = 0; t < 11; t++) + { + target.X += vx * dt; + target.VelX = vx; + AimTrackerHelper.StepTrackedAim( + ref tracker, shooterGrid, eyePos, 0f, 0f, 0f, target, dt, + out float aimX, out _, out float aimZ, out _); + float err = MathF.Sqrt((aimX - target.X) * (aimX - target.X) + (aimZ - target.Z) * (aimZ - target.Z)); + maxOvershootX = MathF.Max(maxOvershootX, err); + } + + Assert.True(maxOvershootX > 2.5f, + $"Expected lateral jink overshoot > 2.5m at ~70m, got {maxOvershootX:F2}m"); + } + + // 3. Zero occluded fire / target leak when LOS breaks behind cover + using (var session = new ArenaSession(seed: 12, ArenaMapKind.Desert, slot0Human: true)) + { + IsolateContenders(session, 0, 1); + var box = session.State.ArenaCoverBoxes[0]; + var player = session.State.Contenders[0]; + var ai = session.State.Contenders[1]; + + float aiX = box.X; + float aiZ = box.Z - box.HalfZ - 14f; + float px = box.X + 12f; + float pz = box.Z - box.HalfZ - 14f; + session.SetContenderPose(ai.Id, aiX, aiZ, MathF.Atan2(px - aiX, pz - aiZ)); + session.SetContenderPose(player.Id, px, pz, 0f); + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + Assert.Equal(player.Id, ai.AiTargetContenderId); + Assert.True(ai.AimTracker.HasTarget); + + // Break LOS behind cover box and shift player laterally + session.SetContenderPose(ai.Id, box.X, box.Z - box.HalfZ - 8f, 0f); + session.SetContenderPose(player.Id, box.X, box.Z + box.HalfZ + 8f, 0f); + for (int t = 0; t < 10; t++) + { + session.SetContenderPose(player.Id, box.X + (t % 2 == 0 ? 2f : -2f), box.Z + box.HalfZ + 8f, 0f); + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + + Assert.Null(ai.AiTargetContenderId); + Assert.False(ai.FireCmd); + Assert.False(ai.AimTracker.HasTarget); + float distToHidden = MathF.Sqrt((ai.AimX - player.X) * (ai.AimX - player.X) + (ai.AimZ - player.Z) * (ai.AimZ - player.Z)); + Assert.True(distToHidden > 5f, $"Occluded AI aim leaked hidden target coords (dist={distToHidden:F2}m)"); + } + } + } + + [Fact] + public void RenderInterpolation_CameraAnchorAndContenderPose_ZeroHorizPhaseMismatchAcrossAlpha() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true, skipInitialDrop: true); + IsolateContenders(session, 0); + var player = session.State.Contenders[0]; + + // Accelerate player forward for 30 ticks so Prev != Curr with genuine horizontal displacement & rotation + for (int t = 0; t < 30; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 1f, + Steer: 0.35f, + AimWorldX: player.X + MathF.Sin(player.Yaw) * 40f, + AimWorldZ: player.Z + MathF.Cos(player.Yaw) * 40f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + } + + float stepHoriz = MathF.Sqrt( + (player.X - player.PrevX) * (player.X - player.PrevX) + + (player.Z - player.PrevZ) * (player.Z - player.PrevZ)); + Assert.True(stepHoriz > 0.05f, $"Expected non-trivial single-tick displacement, got {stepHoriz:F4}m"); + + float[] alphas = { 0f, 0.25f, 0.5f, 0.75f, 1.0f }; + foreach (float alpha in alphas) + { + var (contenderPos, contenderRot, _) = session.GetInterpolatedContenderPose(player.Id, alpha); + + // Camera anchor pivot uses (contenderPos.X, _smoothedShoulderY, contenderPos.Z) with ZERO horizontal chase lag + float expectedX = player.PrevX + (player.X - player.PrevX) * alpha; + float expectedZ = player.PrevZ + (player.Z - player.PrevZ) * alpha; + float camPivotX = contenderPos.X; + float camPivotZ = contenderPos.Z; + + float mismatch = MathF.Sqrt( + (camPivotX - expectedX) * (camPivotX - expectedX) + + (camPivotZ - expectedZ) * (camPivotZ - expectedZ)); + Assert.True(mismatch < 1e-4f, + $"Alpha={alpha:F2}: Horizontal phase mismatch {mismatch:E3}m >= 1e-4m"); + Assert.InRange(contenderRot.Length(), 0.999f, 1.001f); + } + + // SnapPreviousPose collapses alpha=0 and alpha=1 + player.SnapPreviousPose(); + var (p0, _, _) = session.GetInterpolatedContenderPose(player.Id, 0f); + var (p1, _, _) = session.GetInterpolatedContenderPose(player.Id, 1f); + Assert.True(Vector3.Distance(p0, p1) < 1e-5f); + } + + [Fact] + public void PointBlankConvergence_LargeChassis_NeverFiresBackward() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true); + IsolateContenders(session, 0, 1); + var player = session.State.Contenders[0]; + var target = session.State.Contenders[1]; + + // Swap player to Bastion (largest heavy chassis) and target to Raptor (tall mech, small 0.8m footprint) + session.SetContenderPose(player.Id, 0f, 0f, yaw: 0f); + session.State.SpawnChassisDrop(0f, 0f, Catalog.Bastion); + Assert.True(session.TrySwapNearbyChassis(0)); + Assert.Equal(Catalog.Bastion.Id, player.Grid.Spec.Id); + + session.SetContenderPose(target.Id, 0f, 4.5f, yaw: MathF.PI); + session.State.SpawnChassisDrop(0f, 4.5f, Catalog.Raptor); + Assert.True(session.State.TrySwapNearbyChassis(target.Id)); + Assert.Equal(Catalog.Raptor.Id, target.Grid.Spec.Id); + target.AiScavengeCooldown = 999f; + + // Step 1 tick to seat bodies, re-pin poses, then fire point-blank 4.5m in front (+Z) + float aimY = player.Y + player.Grid.Spec.HalfHeight * 0.25f; + session.SetHumanInput(0, new PlayerInput(0f, 0f, target.X, target.Z, false, false, true, AimWorldY: aimY)); + session.Step(); + session.SetContenderPose(player.Id, 0f, 0f, yaw: 0f); + session.SetContenderPose(target.Id, 0f, 4.5f, yaw: MathF.PI); + session.State.Tracers.Clear(); + + aimY = player.Y + player.Grid.Spec.HalfHeight * 0.25f; + float targetArmorBefore = target.Grid.TotalArmorRatio(); + session.SetHumanInput(0, new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: target.X, + AimWorldZ: target.Z, + Fire: true, + InteractPickup: false, + Brake: true, + AimWorldY: aimY)); + session.Step(); + + float bastionMuzzleY = player.Y + player.Grid.Spec.HalfHeight * 0.25f; + var playerTracers1 = session.State.Tracers + .Where(t => MathF.Abs(t.StartX - player.X) < 1f && MathF.Abs(t.StartY - bastionMuzzleY) < 0.25f) + .ToList(); + Assert.NotEmpty(playerTracers1); + foreach (var tracer in playerTracers1) + { + float dz = tracer.EndZ - tracer.StartZ; + Assert.True(dz > 0f, + $"Point-blank Bastion shot fired backward! startZ={tracer.StartZ:F2}, endZ={tracer.EndZ:F2}"); + Assert.True(tracer.StartZ < target.Z, + $"Muzzle overshot target Z! startZ={tracer.StartZ:F2}, targetZ={target.Z:F2}"); + } + + // Place target just outside Bastion's front nose (non-overlapping) to confirm forward ray hits target cleanly + float clearFrontZ = player.Grid.Spec.HalfLength + target.Grid.Spec.HalfLength + 0.5f; + session.SetContenderPose(player.Id, 0f, 0f, yaw: 0f); + session.SetContenderPose(target.Id, 0f, clearFrontZ, yaw: MathF.PI); + session.State.Tracers.Clear(); + foreach (var m in player.Grid.Mounted) + { + m.Cooldown = 0f; + } + session.SetHumanInput(0, new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: target.X, + AimWorldZ: target.Z, + Fire: true, + InteractPickup: false, + Brake: true, + AimWorldY: aimY)); + session.Step(); + + bastionMuzzleY = player.Y + player.Grid.Spec.HalfHeight * 0.25f; + var playerTracersFront = session.State.Tracers + .Where(t => MathF.Abs(t.StartX - player.X) < 1f && MathF.Abs(t.StartY - bastionMuzzleY) < 0.25f) + .ToList(); + Assert.NotEmpty(playerTracersFront); + foreach (var tracer in playerTracersFront) + { + Assert.True(tracer.EndZ > tracer.StartZ, + $"Close front Bastion shot fired backward! startZ={tracer.StartZ:F2}, endZ={tracer.EndZ:F2}"); + Assert.True(tracer.StartZ < target.Z, + $"Close front muzzle overshot target Z! startZ={tracer.StartZ:F2}, targetZ={target.Z:F2}"); + } + Assert.True(target.Grid.TotalArmorRatio() < targetArmorBefore, + "Expected close front Bastion fire to hit Raptor"); + + // Also verify even tighter point-blank (2.2m, strictly inside Bastion HalfLength) still fires strictly forward + session.SetContenderPose(player.Id, 0f, 0f, yaw: 0f); + session.SetContenderPose(target.Id, 0f, 2.2f, yaw: MathF.PI); + session.State.Tracers.Clear(); + foreach (var m in player.Grid.Mounted) + { + m.Cooldown = 0f; + } + session.SetHumanInput(0, new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: target.X, + AimWorldZ: target.Z, + Fire: true, + InteractPickup: false, + Brake: true, + AimWorldY: aimY)); + session.Step(); + + bastionMuzzleY = player.Y + player.Grid.Spec.HalfHeight * 0.25f; + var playerTracers2 = session.State.Tracers + .Where(t => MathF.Abs(t.StartX - player.X) < 1f && MathF.Abs(t.StartY - bastionMuzzleY) < 0.25f) + .ToList(); + Assert.NotEmpty(playerTracers2); + foreach (var tracer in playerTracers2) + { + Assert.True(tracer.EndZ > tracer.StartZ, + $"Ultra-close 2.2m Bastion shot fired backward! startZ={tracer.StartZ:F2}, endZ={tracer.EndZ:F2}"); + Assert.True(tracer.StartZ < target.Z, + $"Ultra-close 2.2m muzzle overshot target Z! startZ={tracer.StartZ:F2}, targetZ={target.Z:F2}"); + } + } + + [Fact] + public void EqualStart_50Seeds_DesertAndSion_AllPairsAtLeast220m() + { + foreach (var map in new[] { ArenaMapKind.Desert, ArenaMapKind.Sion }) + { + for (int seed = 1; seed <= 50; seed++) + { + var state = new MatchState(seed, map); + Assert.Equal(MatchState.ContenderCount, state.Contenders.Count); + + float minDist = float.PositiveInfinity; + int minA = -1, minB = -1; + for (int i = 0; i < state.Contenders.Count; i++) + { + for (int j = i + 1; j < state.Contenders.Count; j++) + { + float dx = state.Contenders[i].X - state.Contenders[j].X; + float dz = state.Contenders[i].Z - state.Contenders[j].Z; + float d = MathF.Sqrt(dx * dx + dz * dz); + if (d < minDist) + { + minDist = d; + minA = i; + minB = j; + } + } + } + + Assert.True(minDist >= 220.0f, + $"Map={map}, Seed={seed}: Contenders {minA} and {minB} pairwise separation {minDist:F2}m < 220.0m"); + } + } + } + + [Fact] + public void AiScavenge_PrefersBetterUpgradeInPickupRange_OverCloserInferiorWreck() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true); + IsolateContenders(session, 0, 1); + var player = session.State.Contenders[0]; + var ai = session.State.Contenders[1]; + + foreach (var d in session.State.GroundDrops) + { + d.PickedUp = true; + } + + session.SetContenderPose(player.Id, -450f, -450f, yaw: 0f); + session.SetContenderPose(ai.Id, 0f, 0f, yaw: 0f); + ai.AiScavengeCooldown = 0f; + + // Closer abandoned Jackal wreck at 1.5m vs superior Hornet at 5.5m (both within PickupRadius = 7.0m) + session.State.SpawnChassisDrop(0f, 1.5f, Catalog.Jackal); + session.State.SpawnChassisDrop(0f, 5.5f, Catalog.Hornet); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + + Assert.Equal(Catalog.Hornet.Id, ai.Grid.Spec.Id); + } + } +} diff --git a/tests/RustToDust.Tests/RustToDust.Tests.csproj b/tests/RustToDust.Tests/RustToDust.Tests.csproj new file mode 100644 index 0000000..e833c3a --- /dev/null +++ b/tests/RustToDust.Tests/RustToDust.Tests.csproj @@ -0,0 +1,33 @@ + + + + net10.0 + enable + disable + false + Release + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/RustToDust.Tests/SionDetectionLosTests.cs b/tests/RustToDust.Tests/SionDetectionLosTests.cs new file mode 100644 index 0000000..30ee3f6 --- /dev/null +++ b/tests/RustToDust.Tests/SionDetectionLosTests.cs @@ -0,0 +1,428 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class SionDetectionLosTests + { + private static (float X, float Z) FindClearBuildingAdjacentSpot(SionMapData sion, float targetX, float targetZ, float pad = 3.5f) + { + for (int r = 0; r <= 180; r += 6) + { + for (int a = 0; a < 12; a++) + { + float ang = a * (MathF.PI / 6f); + float x = Math.Clamp(targetX + MathF.Cos(ang) * r, -1450f, 1450f); + float z = Math.Clamp(targetZ + MathF.Sin(ang) * r, -1450f, 1450f); + if (!sion.IsInsideAnyBuildingXz(x, z, pad)) + { + return (x, z); + } + if (r == 0) break; + } + } + throw new InvalidOperationException($"No clear Sion spot near ({targetX}, {targetZ})"); + } + + private static (float X, float Z) FindOpenLosSpotFromPlayer( + ArenaSession session, + ContenderState player, + float minDist, + float maxDist, + float targetHalfHeight, + float baseAngleRad, + List<(float X, float Z)>? usedSpots = null) + { + var sion = session.State.SionMap!; + var terrain = session.State.Terrain; + float pEyeY = MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight); + + for (int aStep = 0; aStep < 36; aStep++) + { + float ang = baseAngleRad + aStep * (MathF.Tau / 36f); + for (float r = minDist; r <= maxDist; r += 40f) + { + float x = player.X + MathF.Cos(ang) * r; + float z = player.Z + MathF.Sin(ang) * r; + if (MathF.Abs(x) > 1420f || MathF.Abs(z) > 1420f) + { + continue; + } + if (sion.IsInsideAnyBuildingXz(x, z, 3.5f)) + { + continue; + } + if (usedSpots is not null && usedSpots.Any(u => (u.X - x) * (u.X - x) + (u.Z - z) * (u.Z - z) < 25f * 25f)) + { + continue; + } + + float targetY = terrain.SampleHeight(x, z) + targetHalfHeight + 0.15f; + if (session.HasLineOfSight(player.X, pEyeY, player.Z, x, MatchRules.GetTargetAimY(targetY, targetHalfHeight), z)) + { + return (x, z); + } + } + } + + throw new InvalidOperationException($"No open-LOS Sion spot found in [{minDist}, {maxDist}]m from ({player.X:F1}, {player.Z:F1})"); + } + + private static (SionBuildingAabb Building, float Z1, float Z2) FindOccludingOldTownBuilding(ArenaSession session, float halfHeight) + { + var sion = session.State.SionMap!; + var terrain = session.State.Terrain; + for (int i = 0; i < sion.Buildings.Count; i++) + { + var b = sion.Buildings[i]; + if (b.Class != "Gebaeude Einzelhaus" || + b.HalfX < 6f || b.HalfZ < 6f || + (b.RoofY - b.GroundY) < 9f || + MathF.Abs(b.CenterX) > 600f || MathF.Abs(b.CenterZ) > 600f) + { + continue; + } + + float z1 = b.CenterZ - b.HalfZ - 5f; + float z2 = b.CenterZ + b.HalfZ + 5f; + if (sion.IsInsideAnyBuildingXz(b.CenterX, z1, 3.5f) || + sion.IsInsideAnyBuildingXz(b.CenterX, z2, 3.5f)) + { + continue; + } + + float y1 = terrain.SampleHeight(b.CenterX, z1) + halfHeight + 0.15f; + float y2 = terrain.SampleHeight(b.CenterX, z2) + halfHeight + 0.15f; + if (!session.HasLineOfSight( + b.CenterX, MatchRules.GetObserverEyeY(y1, halfHeight), z1, + b.CenterX, MatchRules.GetTargetAimY(y2, halfHeight), z2)) + { + return (b, z1, z2); + } + } + + throw new InvalidOperationException("Expected at least one occluding Sion Old Town building."); + } + + private static void SwapToChassis(ArenaSession session, ContenderState c, ChassisSpec chassis, float x, float z) + { + session.SetContenderPose(c.Id, x, z); + if (!string.Equals(c.Grid.Spec.Id, chassis.Id, StringComparison.OrdinalIgnoreCase)) + { + session.State.SpawnChassisDrop(x, z, chassis); + Assert.True(session.State.TrySwapNearbyChassis(c.Id)); + } + } + + [Fact] + public void Sion_Contenders_ZeroOccludedRadarLeaks_UnderAndOver350m_EveryTick() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + var player = session.State.Contenders[0]; + var nearRival = session.State.Contenders[1]; + var farRival = session.State.Contenders[2]; + + // Move unrelated contenders out of the test corridor + for (int i = 3; i < session.State.Contenders.Count; i++) + { + var (ox, oz) = FindClearBuildingAdjacentSpot(sion, -1350f + i * 20f, -1350f); + session.SetContenderPose(session.State.Contenders[i].Id, ox, oz); + } + + // 1. < 350m occluded across a real Old Town building + var (bldg, z1, z2) = FindOccludingOldTownBuilding(session, Catalog.Jackal.HalfHeight); + SwapToChassis(session, player, Catalog.Jackal, bldg.CenterX, z1); + SwapToChassis(session, nearRival, Catalog.Jackal, bldg.CenterX, z2); + float nearDist = MathF.Abs(z2 - z1); + Assert.True(nearDist < 350f, $"Expected <350m building test distance, got {nearDist:F1}m"); + + // Place farRival far away temporarily while testing nearRival + var (tempFarX, tempFarZ) = FindClearBuildingAdjacentSpot(sion, -1300f, 1300f); + SwapToChassis(session, farRival, Catalog.Jackal, tempFarX, tempFarZ); + + var obs0 = session.State.GetOrCreateObserverState(0); + obs0.ContenderContacts[nearRival.Id] = new PlayerContactMemory(); + for (int tick = 0; tick < 8; tick++) + { + session.SetContenderPose(player.Id, bldg.CenterX, z1); + session.SetContenderPose(nearRival.Id, bldg.CenterX, z2); + Assert.False(session.HasLineOfSight( + player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z, + nearRival.X, MatchRules.GetTargetAimY(nearRival.Y, nearRival.Grid.Spec.HalfHeight), nearRival.Z)); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + + var mem = obs0.ContenderContacts[nearRival.Id]; + Assert.False(mem.VisibleToPlayer, $"Occluded <350m Sion contender leaked VisibleToPlayer on tick {tick}"); + Assert.False(mem.HasEverBeenSeen, $"Occluded <350m Sion contender leaked HasEverBeenSeen on tick {tick}"); + Assert.False(MatchState.IsContactOnRadar(mem), $"Occluded <350m Sion contender leaked onto radar on tick {tick}"); + } + + // 2. > 350m occluded across Valere hill (113, -360) vs (113, 80) => ~440m + var (southX, southZ) = FindClearBuildingAdjacentSpot(sion, 113f, 80f); + var (northX, northZ) = FindClearBuildingAdjacentSpot(sion, 113f, -360f); + float farDist = MathF.Sqrt((southX - northX) * (southX - northX) + (southZ - northZ) * (southZ - northZ)); + Assert.True(farDist > 350f, $"Expected >350m Valere hill test distance, got {farDist:F1}m"); + + session.SetContenderPose(player.Id, northX, northZ); + session.SetContenderPose(farRival.Id, southX, southZ); + obs0.ContenderContacts[farRival.Id] = new PlayerContactMemory(); + + for (int tick = 0; tick < 8; tick++) + { + session.SetContenderPose(player.Id, northX, northZ); + session.SetContenderPose(farRival.Id, southX, southZ); + Assert.False(session.HasLineOfSight( + player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z, + farRival.X, MatchRules.GetTargetAimY(farRival.Y, farRival.Grid.Spec.HalfHeight), farRival.Z)); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + + var mem = obs0.ContenderContacts[farRival.Id]; + Assert.False(mem.VisibleToPlayer, $"Occluded >350m Sion contender leaked VisibleToPlayer on tick {tick}"); + Assert.False(mem.HasEverBeenSeen, $"Occluded >350m Sion contender leaked HasEverBeenSeen on tick {tick}"); + Assert.False(MatchState.IsContactOnRadar(mem), $"Occluded >350m Sion contender leaked onto radar on tick {tick}"); + } + } + + [Fact] + public void Sion_Contenders_Over350m_OpenLosDetectedImmediatelyOnEveryTickPhase() + { + // Verify >350m contenders with open LOS are never delayed by mod-4 staggering across contenders 1..4 on tick 0. + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + var player = session.State.Contenders[0]; + + var (px, pz) = FindClearBuildingAdjacentSpot(sion, 113f, -211f); + SwapToChassis(session, player, Catalog.Condor, px, pz); + player.TargetHoverAltAgl = Catalog.Condor.HoverMaxAltitudeM; + session.SetContenderPose(player.Id, px, pz); + + var tested = new List(); + var used = new List<(float X, float Z)>(); + for (int i = 1; i <= 4; i++) + { + var c = session.State.Contenders[i]; + SwapToChassis(session, c, Catalog.Jackal, px, pz); + var (cx, cz) = FindOpenLosSpotFromPlayer( + session, + player, + minDist: 380f, + maxDist: 900f, + targetHalfHeight: c.Grid.Spec.HalfHeight, + baseAngleRad: i * 0.45f, + usedSpots: used); + used.Add((cx, cz)); + session.SetContenderPose(c.Id, cx, cz); + + float dist = MathF.Sqrt((cx - px) * (cx - px) + (cz - pz) * (cz - pz)); + Assert.True(dist > 350f, $"Expected >350m distance for contender {c.Id}, got {dist:F1}m"); + Assert.True(session.HasLineOfSight( + player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z, + c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z), + $"Expected clear elevated LOS to contender {c.Id}"); + + var obs0 = session.State.GetOrCreateObserverState(0); + obs0.ContenderContacts[c.Id] = new PlayerContactMemory(); + tested.Add(c); + } + + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + + var obs0After = session.State.GetOrCreateObserverState(0); + foreach (var c in tested) + { + var mem = obs0After.ContenderContacts[c.Id]; + Assert.True(mem.VisibleToPlayer, $"Contender {c.Id} >350m with open LOS missed tick-0 detection (staggering leak)"); + Assert.True(MatchState.IsContactOnRadar(mem)); + } + } + + [Fact] + public void Sion_Spectators_ZeroOccludedLeaks_ZeroTick0Blindspots_AndNo950mHardCull() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + var player = session.State.Contenders[0]; + + // Part 1: Occluded low-signature Exemplar across Valere hill (>450m) never leaks on any tick (0..9) + var exemplar = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar); + var (northX, northZ) = FindClearBuildingAdjacentSpot(sion, 113f, -380f); + var (southX, southZ) = FindClearBuildingAdjacentSpot(sion, 113f, 110f); + float occDist = MathF.Sqrt((northX - southX) * (northX - southX) + (northZ - southZ) * (northZ - southZ)); + Assert.True(occDist > 450f, $"Expected >450m Valere occlusion test distance, got {occDist:F1}m"); + + SwapToChassis(session, player, Catalog.Jackal, northX, northZ); + session.SetSpectatorPose(exemplar.Id, southX, southZ); + var obs0 = session.State.GetOrCreateObserverState(0); + obs0.SpectatorContacts[exemplar.Id] = new PlayerContactMemory(); + + for (int tick = 0; tick < 10; tick++) + { + session.SetContenderPose(player.Id, northX, northZ); + session.SetSpectatorPose(exemplar.Id, southX, southZ); + Assert.False(session.HasLineOfSight( + player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z, + exemplar.X, MatchRules.GetTargetAimY(exemplar.Y, exemplar.Grid.Spec.HalfHeight), exemplar.Z)); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + + var mem = obs0.SpectatorContacts[exemplar.Id]; + Assert.False(mem.VisibleToPlayer, $"Occluded Sion Exemplar leaked VisibleToPlayer on tick {tick}"); + Assert.False(mem.FaintHorizonPing, $"Occluded Sion Exemplar leaked FaintHorizonPing on tick {tick}"); + Assert.False(MatchState.IsContactOnRadar(mem), $"Occluded Sion Exemplar leaked onto radar on tick {tick}"); + } + + // Part 2: Zero tick-0 open-LOS blindspots across 8 consecutive spectator indices AND no >950m hard cull + var (px, pz) = FindClearBuildingAdjacentSpot(sion, 113f, -211f); + SwapToChassis(session, player, Catalog.Condor, px, pz); + player.TargetHoverAltAgl = Catalog.Condor.HoverMaxAltitudeM; + session.SetContenderPose(player.Id, px, pz); + + var openSpecs = new List(); + var usedSpecSpots = new List<(float X, float Z)>(); + for (int i = 0; i < 8; i++) + { + var s = session.State.Spectators.Spectators[i]; + // Place indices 0..3 within <450m and indices 4..7 >950m away, all with open elevated LOS + float minD = i < 4 ? 220f : 980f; + float maxD = i < 4 ? 440f : 1380f; + var (sx, sz) = FindOpenLosSpotFromPlayer( + session, + player, + minDist: minD, + maxDist: maxD, + targetHalfHeight: s.Grid.Spec.HalfHeight, + baseAngleRad: i * 0.35f, + usedSpots: usedSpecSpots); + usedSpecSpots.Add((sx, sz)); + session.SetSpectatorPose(s.Id, sx, sz); + + float actualDist = MathF.Sqrt((sx - px) * (sx - px) + (sz - pz) * (sz - pz)); + if (i >= 4) + { + Assert.True(actualDist > 950f, $"Expected >950m spectator test distance, got {actualDist:F1}m"); + } + Assert.True(session.HasLineOfSight( + player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z, + s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z), + $"Expected open elevated LOS to spectator {s.Id} at dist={actualDist:F1}m"); + + obs0.SpectatorContacts[s.Id] = new PlayerContactMemory(); + openSpecs.Add(s); + } + + // Step ONE tick: all 8 spectators (covering all %4 and %8 phases and >950m) must be visible immediately. + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + + foreach (var s in openSpecs) + { + var mem = obs0.SpectatorContacts[s.Id]; + float d = MathF.Sqrt((s.X - player.X) * (s.X - player.X) + (s.Z - player.Z) * (s.Z - player.Z)); + Assert.True(mem.VisibleToPlayer, + $"Open-LOS Sion spectator {s.Id} at {d:F1}m missed tick-0 detection (blindspot or >950m hard cull)"); + Assert.True(MatchState.IsContactOnRadar(mem)); + } + } + + [Fact] + public void Sion_AiContender_NoOddTickTargetDropOrTunnelVision() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + var player = session.State.Contenders[0]; + var ai = session.State.Contenders[1]; + var closerRival = session.State.Contenders[2]; + + // Isolate player, ai, and closerRival + for (int i = 3; i < session.State.Contenders.Count; i++) + { + var (ox, oz) = FindClearBuildingAdjacentSpot(sion, -1350f + i * 20f, -1350f); + session.SetContenderPose(session.State.Contenders[i].Id, ox, oz); + } + + // 1. Immediate target switch on BOTH even and odd ticks when a closer threat enters open LOS (no tunnel vision) + var (aiX, aiZ) = FindClearBuildingAdjacentSpot(sion, -60f, 360f); + var (farX, farZ) = FindClearBuildingAdjacentSpot(sion, -60f, 250f); + var (nearX, nearZ) = FindClearBuildingAdjacentSpot(sion, -45f, 330f); + + SwapToChassis(session, ai, Catalog.Jackal, aiX, aiZ); + SwapToChassis(session, player, Catalog.Jackal, farX, farZ); + var (parkX, parkZ) = FindClearBuildingAdjacentSpot(sion, -1200f, -1200f); + SwapToChassis(session, closerRival, Catalog.Jackal, parkX, parkZ); + + Assert.True(session.HasLineOfSight( + ai.X, MatchRules.GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight), ai.Z, + player.X, MatchRules.GetTargetAimY(player.Y, player.Grid.Spec.HalfHeight), player.Z)); + + // Advance 1 tick so ai locks onto player on tick 1 + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + Assert.Equal(player.Id, ai.AiTargetContenderId); + + // On the next tick (even/odd opposite phase), bring closerRival into open LOS closer than player + session.SetContenderPose(ai.Id, aiX, aiZ); + session.SetContenderPose(player.Id, farX, farZ); + session.SetContenderPose(closerRival.Id, nearX, nearZ); + Assert.True(session.HasLineOfSight( + ai.X, MatchRules.GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight), ai.Z, + closerRival.X, MatchRules.GetTargetAimY(closerRival.Y, closerRival.Grid.Spec.HalfHeight), closerRival.Z)); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + Assert.Equal(closerRival.Id, ai.AiTargetContenderId); + + // 2. Immediate target drop and FireCmd=false across consecutive ticks when LOS breaks behind a Sion building + var (bldg, z1, z2) = FindOccludingOldTownBuilding(session, Catalog.Jackal.HalfHeight); + session.SetContenderPose(closerRival.Id, parkX, parkZ); + + for (int phase = 0; phase < 3; phase++) + { + session.SetContenderPose(ai.Id, bldg.CenterX, z1, yaw: 0f); + session.SetContenderPose(player.Id, bldg.CenterX + 12f, z1, yaw: 0f); + // Ensure open LOS on same side of building + if (!session.HasLineOfSight( + ai.X, MatchRules.GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight), ai.Z, + player.X, MatchRules.GetTargetAimY(player.Y, player.Grid.Spec.HalfHeight), player.Z)) + { + var (openPx, openPz) = FindClearBuildingAdjacentSpot(sion, bldg.CenterX + 10f, z1); + session.SetContenderPose(player.Id, openPx, openPz, yaw: 0f); + } + float facePlayerYaw = MathF.Atan2(player.X - ai.X, player.Z - ai.Z); + session.SetContenderPose(ai.Id, bldg.CenterX, z1, yaw: facePlayerYaw); + + for (int t = 0; t <= phase; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + Assert.Equal(player.Id, ai.AiTargetContenderId); + Assert.True(ai.FireCmd, $"Expected AI to acquire and fire immediately on Sion (phase={phase}, t={t})"); + } + + // Break LOS across the Sion building + session.SetContenderPose(ai.Id, bldg.CenterX, z1, yaw: 0f); + session.SetContenderPose(player.Id, bldg.CenterX, z2, yaw: 0f); + for (int occTick = 0; occTick < 6; occTick++) + { + session.SetContenderPose(ai.Id, bldg.CenterX, z1, yaw: 0f); + session.SetContenderPose(player.Id, bldg.CenterX, z2, yaw: 0f); + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + session.Step(); + + Assert.Null(ai.AiTargetContenderId); + Assert.False(ai.FireCmd, $"AI leaked FireCmd through Sion building on occluded tick {occTick} (phase={phase})"); + } + } + } + } +} diff --git a/tests/RustToDust.Tests/SionMapTests.cs b/tests/RustToDust.Tests/SionMapTests.cs new file mode 100644 index 0000000..0395045 --- /dev/null +++ b/tests/RustToDust.Tests/SionMapTests.cs @@ -0,0 +1,803 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Numerics; +using RustToDust.Core; +using RustToDust.Net; +using RustToDust.Ymir; +using Xunit; +using Ymir.Box3D; + +namespace RustToDust.Tests +{ + public sealed class SionMapTests + { + [Fact] + public void SionMapLoader_LoadsMetadataHeightmapBuildingsAndRcolMeshesWithExactParity() + { + var sion = SionMapLoader.Load(); + var meta = sion.Metadata; + + Assert.Equal(3072f, meta.SizeMeters); + Assert.Equal(16, meta.TileGrid); + Assert.Equal(192f, meta.TileSizeMeters); + Assert.Equal(6145, meta.GridRes); + Assert.Equal(0.5f, meta.CellSizeMeters); + Assert.Equal("heightmap_05m.u16z", meta.HeightmapFile); + Assert.False(string.IsNullOrWhiteSpace(meta.DemAssetHash)); + Assert.Contains("swisstopo", meta.Attribution, StringComparison.OrdinalIgnoreCase); + + Assert.Equal(6145 * 6145, sion.BaseDem.Length); + Assert.Equal(2319, sion.Buildings.Count); + Assert.Equal(36, sion.CollisionMeshes.Count); + + var terrain = TerrainField.LoadSharedHeightmap( + meta.SizeMeters, meta.GridRes, meta.TileGrid, + sion.BaseDem, sion.BaseDemMinY, sion.BaseDemScale, + meta.MinY, meta.MaxY); + + // Verify Basilique de Valere and valley buildings align cleanly with heightmap_05m.u16z (0.00m coordinate drift) + bool foundValere = false; + int flatAlignChecked = 0; + int closeAlignCount = 0; + for (int i = 0; i < sion.Buildings.Count; i++) + { + var b = sion.Buildings[i]; + if (b.Name.Contains("Val", StringComparison.OrdinalIgnoreCase)) + { + foundValere = true; + float hValere = terrain.SampleHeight(b.CenterX, b.CenterZ); + Assert.InRange(hValere, 90f, 150f); + } + + if (b.Class == "Gebaeude Einzelhaus" && + b.HalfX < 10f && b.HalfZ < 10f && + terrain.SampleNormal(b.CenterX, b.CenterZ).Ny > 0.98f) + { + float hTerrain = terrain.SampleHeight(b.CenterX, b.CenterZ); + // Buildings include a ~4m foundation skirt below ground level; sloped/stepped lots can vary slightly around center. + Assert.InRange(hTerrain, b.GroundY - 5.0f, b.RoofY + 2.0f); + if (MathF.Abs(hTerrain - (b.GroundY + 3.5f)) <= 2.5f) + { + closeAlignCount++; + } + flatAlignChecked++; + } + } + + Assert.True(foundValere, "Expected Basilique de Valere in Sion buildings_manifest.json"); + Assert.True(flatAlignChecked > 200, $"Expected > 200 flat-ground buildings matching DEM, got {flatAlignChecked}"); + Assert.True(closeAlignCount > flatAlignChecked * 0.90f, + $"Expected >90% of flat-lot buildings to sit within 2.5m of skirted DEM ({closeAlignCount}/{flatAlignChecked})"); + + // Verify RCOL collision mesh bounds match metadata tile bounds + for (int i = 0; i < sion.CollisionMeshes.Count; i++) + { + var cm = sion.CollisionMeshes[i]; + var tm = meta.Tiles[i]; + Assert.Equal(tm.Tx, cm.Tx); + Assert.Equal(tm.Tz, cm.Tz); + Assert.True(cm.Vertices.Length >= 3); + Assert.True(cm.Indices.Length >= 3 && cm.Indices.Length % 3 == 0); + Assert.True(Vector3.Distance(tm.BoundsMin, cm.BoundsMin) < 0.05f); + Assert.True(Vector3.Distance(tm.BoundsMax, cm.BoundsMax) < 0.05f); + } + } + + [Fact] + public void SionTerrainField_SupportsBilinearSamplingNormalsRaycastAndCraters() + { + var sion = SionMapLoader.Load(); + var meta = sion.Metadata; + var terrain = TerrainField.LoadSharedHeightmap( + meta.SizeMeters, meta.GridRes, meta.TileGrid, + sion.BaseDem, sion.BaseDemMinY, sion.BaseDemScale, + meta.MinY, meta.MaxY); + + Assert.True(terrain.IsHeightmapMode); + Assert.Equal(3072f, terrain.MapSize); + Assert.Equal(1536f, terrain.MapHalfExtent); + Assert.Equal(16, terrain.TileGridCount); + + // Grid vertex exactness at (-1536, -1536) and (0, 0) + Assert.Equal(sion.SampleBaseDemAtIndex(0), terrain.SampleHeight(-1536f, -1536f), precision: 4); + Assert.Equal(sion.SampleBaseDemAtIndex(3072 * 6145 + 3072), terrain.SampleHeight(0f, 0f), precision: 4); + + // Plaza spawn area is flat; Valere hill rises > 100m + var (_, plazaNy, _) = terrain.SampleNormal(-60f, 360f); + Assert.True(plazaNy >= 0.95f, $"Expected flat plaza normal.Y >= 0.95, got {plazaNy:F3}"); + float valerePeakH = terrain.SampleHeight(113f, -211f); + Assert.True(valerePeakH > 100f, $"Expected Valere hill height > 100m, got {valerePeakH:F2}m"); + + // Raycast hits Valere hill at low elevation and clears above peak + bool blocked = terrain.Raycast(113f, 35f, -350f, 0f, 0f, 1f, 280f, out _, out float hitY, out float hitZ, out _); + Assert.True(blocked, "Expected terrain raycast through Valere ridge to hit"); + Assert.InRange(hitZ, -350f, -70f); + Assert.True(hitY >= 34f); + + bool clear = terrain.Raycast(113f, meta.MaxY + 10f, -350f, 0f, 0f, 1f, 280f, out _, out _, out _, out _); + Assert.False(clear, "Expected high raycast above Valere peak to clear"); + + // Dynamic crater lowers height on top of DEM + float before = terrain.SampleHeight(-60f, 360f); + terrain.StampCrater(-60f, 360f, radius: 5f, depth: 1.5f); + float after = terrain.SampleHeight(-60f, 360f); + Assert.True(after < before - 1.0f, $"Expected crater to depress Sion DEM (before={before:F2}, after={after:F2})"); + } + + [Fact] + public void ArenaSession_SionLoadsHeightfieldAndMeshesSpawnsClearBlocksLosAndStepsCleanly() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true); + var state = session.State; + var sion = state.SionMap!; + + Assert.Equal(ArenaMapKind.Sion, state.MapKind); + Assert.Empty(state.ArenaCoverBoxes); + Assert.Equal(MatchState.SionInitialSafeRadius, state.Spectators.SafeRadius); + + // Verify lazy tiled StaticHeightField (192m tiles) + StaticMesh (36) exist in Ymir + int hfCount = 0; + int meshCount = 0; + var view = session.World.View; + for (int lane = 0; lane < view.Count; lane++) + { + var kind = (Box3DSoaKind)view.Kind[lane]; + if (kind == Box3DSoaKind.StaticHeightField) hfCount++; + else if (kind == Box3DSoaKind.StaticMesh) meshCount++; + } + Assert.InRange(hfCount, 1, 45); + Assert.Equal(hfCount, session.TileSync.ResidentTileCount); + Assert.Equal(36, meshCount); + + // Verify zero contenders, spectators, or drops spawned inside any building + foreach (var c in state.Contenders) + { + float pad = MathF.Max(c.Grid.Spec.HalfWidth, c.Grid.Spec.HalfLength) + 1.5f; + Assert.False(sion.IsInsideAnyBuildingXz(c.X, c.Z, pad), + $"Contender {c.Id} ({c.Grid.Spec.Id}) spawned inside building at ({c.X:F2}, {c.Z:F2})"); + } + foreach (var s in state.Spectators.Spectators) + { + Assert.False(sion.IsInsideAnyBuildingXz(s.X, s.Z, 1.5f), + $"Spectator {s.Id} spawned inside building at ({s.X:F2}, {s.Z:F2})"); + } + foreach (var d in state.GroundDrops) + { + Assert.False(sion.IsInsideAnyBuildingXz(d.X, d.Z, 1.5f), + $"GroundDrop {d.Id} spawned inside building at ({d.X:F2}, {d.Z:F2})"); + } + + // LOS blocked by Valere hill + Assert.False(session.HasLineOfSight(113f, 35f, -350f, 113f, 35f, -70f), + "Expected HasLineOfSight to be blocked by Valere hill"); + + // LOS blocked by a real Old Town solid building mesh (and clear over its roof) + SionBuildingAabb? testBldg = null; + for (int i = 0; i < sion.Buildings.Count; i++) + { + var b = sion.Buildings[i]; + if (b.Class == "Gebaeude Einzelhaus" && + b.HalfX >= 5f && b.HalfZ >= 5f && + (b.RoofY - b.GroundY) >= 8f && + MathF.Abs(b.CenterX) < 500f && MathF.Abs(b.CenterZ) < 500f) + { + testBldg = b; + break; + } + } + Assert.NotNull(testBldg); + var tb = testBldg!.Value; + float midY = tb.GroundY + (tb.RoofY - tb.GroundY) * 0.45f; + float zA = tb.CenterZ - tb.HalfZ - 4f; + float zB = tb.CenterZ + tb.HalfZ + 4f; + Assert.False(session.HasLineOfSight(tb.CenterX, midY, zA, tb.CenterX, midY, zB), + $"Expected HasLineOfSight to be blocked by Sion building {tb.Id} at ({tb.CenterX:F1}, {midY:F1}, {tb.CenterZ:F1})"); + Assert.True(session.HasLineOfSight(tb.CenterX, tb.RoofY + 6f, zA, tb.CenterX, tb.RoofY + 6f, zB), + $"Expected HasLineOfSight above Sion building {tb.Id} roof ({tb.RoofY:F1}m) to be clear"); + + // Step 180 ticks (3 seconds) driving & firing: zero NaNs, zero underground falls, player moves cleanly + var player = state.Contenders[0]; + float pStartX = player.X; + float pStartZ = player.Z; + for (int tick = 0; tick < 180; tick++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 1f, + Steer: MathF.Sin(tick * 0.04f) * 0.25f, + AimWorldX: player.X + MathF.Sin(player.Yaw) * 60f, + AimWorldZ: player.Z + MathF.Cos(player.Yaw) * 60f, + Fire: tick % 10 == 0, + InteractPickup: false, + Brake: false)); + session.Step(); + + for (int cIdx = 0; cIdx < state.Contenders.Count; cIdx++) + { + var c = state.Contenders[cIdx]; + if (!c.Alive) continue; + Assert.True(float.IsFinite(c.X) && float.IsFinite(c.Y) && float.IsFinite(c.Z), + $"Non-finite contender {c.Id} pose at tick {tick}"); + float gh = state.Terrain.SampleHeight(c.X, c.Z); + float bottomY = c.Y - c.Grid.Spec.HalfHeight; + Assert.True(bottomY >= gh - 0.85f, + $"Contender {c.Id} ({c.Grid.Spec.Id}) fell below Sion terrain at tick {tick}: bottom={bottomY:F2}m < ground={gh:F2}m"); + } + + for (int sIdx = 0; sIdx < state.Spectators.Spectators.Count; sIdx++) + { + var s = state.Spectators.Spectators[sIdx]; + if (!s.Alive) continue; + Assert.True(float.IsFinite(s.X) && float.IsFinite(s.Y) && float.IsFinite(s.Z), + $"Non-finite spectator {s.Id} pose at tick {tick}"); + } + } + + float pDisp = MathF.Sqrt((player.X - pStartX) * (player.X - pStartX) + (player.Z - pStartZ) * (player.Z - pStartZ)); + Assert.True(pDisp > 5f, $"Expected player displacement > 5m on Sion after 180 ticks, got {pDisp:F2}m"); + } + + [Fact] + public void SionBox3DTile_CraterRebuildsLocalTileOnlyAndLeavesNeighborsIntact() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true); + var terrain = session.State.Terrain; + + // Tile (7, 7) spans [-192, 0) x [-192, 0); neighbor tile (8, 7) spans [0, 192) x [-192, 0). + // Pick an open-sky coordinate strictly inside tile (7, 7) away from any building footprint. + var sion = session.State.SionMap!; + float cx = -96f, cz = -96f; + bool foundSpot = false; + for (float z = -176f; z <= -16f && !foundSpot; z += 8f) + { + for (float x = -176f; x <= -16f; x += 8f) + { + if (!sion.IsInsideAnyBuildingXz(x, z, padding: 10f)) + { + cx = x; + cz = z; + foundSpot = true; + break; + } + } + } + Assert.True(foundSpot, "Expected open-sky spot inside Sion tile (7, 7)"); + + session.TileSync.EnsureTileRegion(session.World, terrain, cx, cz, halfTileRadius: 1); + + Assert.True(session.TileSync.TryGetResidentHandle(7, 7, terrain.TileGridCount, out var handleTargetBefore)); + Assert.True(session.TileSync.TryGetResidentHandle(8, 7, terrain.TileGridCount, out var handleNeighborBefore)); + + float rayStartY = sion.Metadata.MaxY + 25f; + float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f); + var hitBefore = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f)); + Assert.True(hitBefore.Hit); + Assert.Equal(Box3DPhysicsTileSync.HeightfieldTileStableIdBase + (ulong)(7 * 16 + 7), hitBefore.StableId); + + // Stamp crater strictly inside tile (7, 7) + session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = cx, + Z = cz, + Radius = 6f, + Depth = 2.0f + }); + int rebuilt = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 4); + Assert.Equal(1, rebuilt); + + Assert.True(session.TileSync.TryGetResidentHandle(7, 7, terrain.TileGridCount, out var handleTargetAfter)); + Assert.True(session.TileSync.TryGetResidentHandle(8, 7, terrain.TileGridCount, out var handleNeighborAfter)); + + Assert.NotEqual(handleTargetBefore, handleTargetAfter); + Assert.Equal(handleNeighborBefore, handleNeighborAfter); + + var hitAfter = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f)); + Assert.True(hitAfter.Hit); + Assert.True(hitAfter.Point.Y < hitBefore.Point.Y - 1.2f, + $"Expected Box3D raycast impact height to drop in crater (before={hitBefore.Point.Y:F3}, after={hitAfter.Point.Y:F3})"); + } + + [Fact] + public void ArenaScarLedgerStore_PersistsCratersAndRubbleAcrossResetAndRepairsToLayer0() + { + string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-scar-test-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + string scarPath = Path.Combine(tempDir, "sion_scars_test.cultcache"); + + try + { + const float craterX = -120f; + const float craterZ = 180f; + const float rubbleX = 140f; + const float rubbleZ = 180f; + float baseCraterH; + float baseRubbleH; + float scarredCraterH; + float scarredRubbleH; + + using (var host1 = new ServerMatchHost( + IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, + autoRestartSec: 0, scarFilePath: scarPath, persistScars: true)) + { + var state1 = host1.Session.State; + baseCraterH = state1.Terrain.SampleHeight(craterX, craterZ); + baseRubbleH = state1.Terrain.SampleHeight(rubbleX, rubbleZ); + + state1.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = craterX, + Z = craterZ, + Radius = 5.5f, + Depth = 1.8f + }); + state1.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Rubble, + X = rubbleX, + Z = rubbleZ, + Radius = 6.0f, + Depth = 1.2f, + Yaw = 0.4f + }); + + scarredCraterH = state1.Terrain.SampleHeight(craterX, craterZ); + scarredRubbleH = state1.Terrain.SampleHeight(rubbleX, rubbleZ); + Assert.True(scarredCraterH < baseCraterH - 1.2f); + Assert.True(scarredRubbleH > baseRubbleH + 0.6f); + + // ResetMatch preserves scars in RAM & flushes to CultCache + host1.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false); + Assert.Equal(scarredCraterH, host1.Session.State.Terrain.SampleHeight(craterX, craterZ), precision: 3); + Assert.Equal(scarredRubbleH, host1.Session.State.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3); + } + + Assert.True(File.Exists(scarPath), "Expected CultCache scar file on disk after host dispose"); + + using (var host2 = new ServerMatchHost( + IPAddress.Loopback, 0, seed: 44, ArenaMapKind.Sion, + autoRestartSec: 0, scarFilePath: scarPath, persistScars: true)) + { + var state2 = host2.Session.State; + Assert.Equal(scarredCraterH, state2.Terrain.SampleHeight(craterX, craterZ), precision: 3); + Assert.Equal(scarredRubbleH, state2.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3); + + // RepairArenaScars zeroes back to Layer 0 + host2.RepairArenaScars(); + Assert.Equal(baseCraterH, state2.Terrain.SampleHeight(craterX, craterZ), precision: 3); + Assert.Equal(baseRubbleH, state2.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3); + Assert.Empty(state2.ScarLedger.Terrain); + } + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, recursive: true); + } + } + } + + [Fact] + public void ValereSlopeHits_ClassifyAsTerrainNeverStaticCover_ForHitscanAndProjectile() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true); + var terrain = session.State.Terrain; + var sion = session.State.SionMap!; + + // Ensure Valere hill heightfield tiles are resident so Box3D heightfields are active on the slope ray + session.TileSync.EnsureTileRegion(session.World, terrain, 113f, -211f, halfTileRadius: 1); + + // Find an open-sky steep Valere slope point and an unobstructed muzzle above it (zero buildings on ray) + Vector3 muzzle = default; + Vector3 dir = default; + bool foundSlope = false; + for (float sz = -290f; sz <= -175f && !foundSlope; sz += 6f) + { + for (float sx = 40f; sx <= 185f && !foundSlope; sx += 6f) + { + if (sion.IsInsideAnyBuildingXz(sx, sz, padding: 8.0f)) + { + continue; + } + float sh = terrain.SampleHeight(sx, sz); + var (nx, ny, nz) = terrain.SampleNormal(sx, sz); + if (sh < 55f || ny >= 0.88f) + { + continue; + } + Vector3 slopePt = new(sx, sh, sz); + Vector3 nrm = Vector3.Normalize(new Vector3(nx, ny, nz)); + Vector3 candMuzzle = slopePt + nrm * 32f + Vector3.UnitY * 8f; + Vector3 candDir = Vector3.Normalize(slopePt - candMuzzle); + float dist = Vector3.Distance(candMuzzle, slopePt) + 5f; + if (!sion.IntersectsAnyBuildingAabb(candMuzzle.X, candMuzzle.Y, candMuzzle.Z, candDir.X, candDir.Y, candDir.Z, dist) && + terrain.Raycast(candMuzzle.X, candMuzzle.Y, candMuzzle.Z, candDir.X, candDir.Y, candDir.Z, dist, out float tx, out _, out float tz, out _) && + !sion.IsInsideAnyBuildingXz(tx, tz, padding: 2.0f)) + { + muzzle = candMuzzle; + dir = candDir; + foundSlope = true; + } + } + } + Assert.True(foundSlope, "Expected open-sky steep Valere slope ray unobstructed by buildings"); + session.TileSync.EnsureTileRegion(session.World, terrain, muzzle.X, muzzle.Z, halfTileRadius: 1); + + var events = new List(); + session.DrainStepEvents(events); + + // 1. Fire hitscan directly into Valere slope + var hitscanSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.RotaryAutocannon); + session.Ordnance.FireWeapon(new OrdnanceFireRequest( + Module: new MountedModule(hitscanSpec.Module, "hp.weapon.main", 0f), + ShooterStableId: ArenaSession.ContenderStableIdBase, + ShooterContender: session.State.Contenders[0], + ShooterLabel: "Tester", + IsSpectatorShooter: false, + ShooterEntityId: 0, + ShooterPos: muzzle, + MuzzlePos: muzzle, + AimDir: dir, + AimDist: 160f, + SpreadRad: 0f, + TargetEntityStableId: 0UL, + RootDef: hitscanSpec.RootNode, + WeaponKey: hitscanSpec.Key)); + + // 2. Fire ballistic projectile into Valere slope + var projSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.SabotSlugCannon); + session.Ordnance.FireWeapon(new OrdnanceFireRequest( + Module: new MountedModule(projSpec.Module, "hp.weapon.main", 0f), + ShooterStableId: ArenaSession.ContenderStableIdBase, + ShooterContender: session.State.Contenders[0], + ShooterLabel: "Tester", + IsSpectatorShooter: false, + ShooterEntityId: 0, + ShooterPos: muzzle, + MuzzlePos: muzzle, + AimDir: dir, + AimDist: 160f, + SpreadRad: 0f, + TargetEntityStableId: 0UL, + RootDef: projSpec.RootNode, + WeaponKey: projSpec.Key)); + + var impacts = new List(); + for (int tick = 0; tick < 60; tick++) + { + session.Step(); + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is HitImpactEvent hit) + { + impacts.Add(hit); + } + } + if (impacts.Count >= 2) + { + break; + } + } + + Assert.True(impacts.Count >= 2, $"Expected >= 2 slope impacts (hitscan + projectile), got {impacts.Count}"); + Assert.All(impacts, h => Assert.Equal((byte)HitTargetKind.Terrain, h.TargetKind)); + } + + [Fact] + public void RepairArenaScars_ManyScarredTilesRebuildIncrementallyWithoutExhaustingWorldCapacity() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true); + var terrain = session.State.Terrain; + + // Materialize 20 resident tiles in a 5x4 grid and crater all 20 + var spots = new List<(float X, float Z, float BaseH)>(); + for (int tz = 5; tz <= 8; tz++) + { + for (int tx = 5; tx <= 9; tx++) + { + float wx = -terrain.MapHalfExtent + (tx + 0.5f) * terrain.MapTileSize; + float wz = -terrain.MapHalfExtent + (tz + 0.5f) * terrain.MapTileSize; + session.TileSync.EnsureTileResident(session.World, terrain, tx, tz); + float baseH = terrain.SampleHeight(wx, wz); + spots.Add((wx, wz, baseH)); + session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = wx, + Z = wz, + Radius = 5f, + Depth = 1.6f + }); + } + } + + // Flush all 20 cratered tiles into Box3D heightfields without evicting non-actor tiles + int flushedBeforeRepair = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 20); + Assert.Equal(20, flushedBeforeRepair); + session.World.Step(1f / 60f); + + var sion = session.State.SionMap!; + var sionMeta = sion.Metadata; + (float X, float Z, float BaseH) openSpot = default; + bool foundOpenSpot = false; + foreach (var s in spots) + { + if (!sion.IsInsideAnyBuildingXz(s.X, s.Z, padding: 6f)) + { + openSpot = s; + foundOpenSpot = true; + break; + } + } + Assert.True(foundOpenSpot, "Expected at least one open-sky spot among the 20 cratered tiles"); + + float rayStartY = sionMeta.MaxY + 25f; + float raySpanY = -(sionMeta.MaxY - sionMeta.MinY + 60f); + var hitCratered = session.CastWorldRayClosest(new Vector3(openSpot.X, rayStartY, openSpot.Z), new Vector3(0f, raySpanY, 0f)); + Assert.True(hitCratered.Hit); + Assert.True(hitCratered.Point.Y < openSpot.BaseH - 1.0f, + $"Expected cratered Box3D raycast height ({hitCratered.Point.Y:F3}) well below base ({openSpot.BaseH:F3})"); + + int freeBeforeRepair = session.World.FreeBodySlots; + Assert.True(freeBeforeRepair >= 20 + 32); + session.RepairArenaScars(); + // When FreeBodySlots >= dirtyResidentCount + 32, RepairArenaScars flushes all dirty resident tiles immediately on tick 0 + Assert.True(session.World.View.Count < ArenaSession.WorldBodyCapacity - 256, + $"Expected View.Count ({session.World.View.Count}) well below WorldBodyCapacity ({ArenaSession.WorldBodyCapacity}) after repair"); + Assert.Equal(0, session.TileSync.CountDirtyResidentTiles(terrain)); + + var hitTick0 = session.CastWorldRayClosest(new Vector3(openSpot.X, rayStartY, openSpot.Z), new Vector3(0f, raySpanY, 0f)); + Assert.True(hitTick0.Hit); + Assert.True(MathF.Abs(hitTick0.Point.Y - openSpot.BaseH) < 0.05f, + $"Expected tick-0 Box3D raycast height ({hitTick0.Point.Y:F3}) to match restored base ({openSpot.BaseH:F3})"); + + // Step across ticks so recycled slots remain healthy without exhausting world capacity + for (int t = 0; t < 20; t++) + { + session.Step(); + Assert.True(session.World.View.Count < ArenaSession.WorldBodyCapacity - 256, + $"Expected View.Count ({session.World.View.Count}) well below WorldBodyCapacity ({ArenaSession.WorldBodyCapacity}) at tick {t}"); + } + + foreach (var (wx, wz, baseH) in spots) + { + Assert.Equal(baseH, terrain.SampleHeight(wx, wz), precision: 3); + } + } + + [Fact] + public void ServerMatchHost_SionDesertSion_PreservesSionScarsAndDoesNotClobberExplicitScarFile() + { + string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-mapswitch-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + string explicitSionPath = Path.Combine(tempDir, "sion_scars_explicit.cultcache"); + + try + { + const float craterX = -120f; + const float craterZ = 180f; + float sionBaseH; + float sionScarredH; + + using (var host = new ServerMatchHost( + IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, + autoRestartSec: 0, scarFilePath: explicitSionPath, persistScars: true)) + { + sionBaseH = host.Session.State.Terrain.SampleHeight(craterX, craterZ); + host.Session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = craterX, + Z = craterZ, + Radius = 5.5f, + Depth = 1.8f + }); + sionScarredH = host.Session.State.Terrain.SampleHeight(craterX, craterZ); + Assert.True(sionScarredH < sionBaseH - 1.2f); + + // Switch Sion -> Desert: Desert must NOT inherit Sion craters, nor overwrite explicitSionPath + float desertBaseH; + host.ResetMatch(42, ArenaMapKind.Desert, startInLobby: false); + Assert.Empty(host.Session.State.ScarLedger.Terrain); + desertBaseH = host.Session.State.Terrain.SampleHeight(0f, 0f); + host.Session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = 0f, + Z = 0f, + Radius = 4.5f, + Depth = 1.4f + }); + float desertScarredH = host.Session.State.Terrain.SampleHeight(0f, 0f); + Assert.True(desertScarredH < desertBaseH - 0.8f); + + // Switch Desert -> Sion: Sion craters must be restored cleanly! + host.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false); + Assert.Equal(sionScarredH, host.Session.State.Terrain.SampleHeight(craterX, craterZ), precision: 3); + + // Verify explicitSionPath on disk still holds Sion's AssetFingerprint & crater (never clobbered by Desert) + var diskSnap = ArenaScarLedgerStore.Load(explicitSionPath, host.Session.State.SionMap!.AssetFingerprint); + Assert.Single(diskSnap.Terrain); + Assert.Equal(craterX, diskSnap.Terrain[0].X); + Assert.Equal(craterZ, diskSnap.Terrain[0].Z); + } + + // Also verify LocalArenaSession & ListenHostArenaSession carry scars across rounds and Sion -> Desert -> Sion + using (var local = new LocalArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, skipInitialDrop: true)) + { + local.Inner.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = craterX, + Z = craterZ, + Radius = 5.5f, + Depth = 1.8f + }); + local.RequestNewMatch(43, ArenaMapKind.Sion); + Assert.Equal(sionScarredH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3); + + local.RequestNewMatch(42, ArenaMapKind.Desert); + Assert.Empty(local.ViewState.ScarLedger.Terrain); + + local.RequestNewMatch(44, ArenaMapKind.Sion); + Assert.Equal(sionScarredH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3); + + local.RepairArenaScars(); + local.RequestNewMatch(45, ArenaMapKind.Sion); + Assert.Equal(sionBaseH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3); + } + + using (var listen = new ListenHostArenaSession(IPAddress.Loopback, 0, seed: 42, mapKind: ArenaMapKind.Sion)) + { + listen.Host.Session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = craterX, + Z = craterZ, + Radius = 5.5f, + Depth = 1.8f + }); + listen.RequestNewMatch(43, ArenaMapKind.Desert); + Assert.Empty(listen.ViewState.ScarLedger.Terrain); + + listen.RequestNewMatch(44, ArenaMapKind.Sion); + Assert.Equal(sionScarredH, listen.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3); + } + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, recursive: true); + } + } + } + + [Fact] + public void FlushDirtyHeightfields_RecycledFreeSlots_DoesNotWedgeAtHighViewCount() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true); + var terrain = session.State.Terrain; + var sion = session.State.SionMap!; + + float cx = -96f, cz = -96f; + bool foundSpot = false; + for (float z = -176f; z <= -16f && !foundSpot; z += 8f) + { + for (float x = -176f; x <= -16f; x += 8f) + { + if (!sion.IsInsideAnyBuildingXz(x, z, padding: 10f)) + { + cx = x; + cz = z; + foundSpot = true; + break; + } + } + } + Assert.True(foundSpot, "Expected open-sky spot inside Sion tile (7, 7)"); + + session.TileSync.EnsureTileRegion(session.World, terrain, cx, cz, halfTileRadius: 0); + + // Push View.Count >= 1016, then remove those temporary bodies and step to recycle FreeBodySlots > 500 + var tempHandles = new List(); + ulong nextId = 900_000UL; + while (session.World.View.Count < 1016 && session.World.FreeBodySlots > 0) + { + tempHandles.Add(session.World.AddStaticBox(nextId++, (0f, -500f, 0f), (0.5f, 0.5f, 0.5f))); + } + Assert.True(session.World.View.Count >= 1016, $"Expected View.Count >= 1016, got {session.World.View.Count}"); + + foreach (var h in tempHandles) + { + session.World.RemoveBody(h); + } + session.World.Step(1f / 60f); + + Assert.True(session.World.View.Count >= 1016, $"Expected monotonic View.Count >= 1016, got {session.World.View.Count}"); + Assert.True(session.World.FreeBodySlots > 500, $"Expected recycled FreeBodySlots > 500, got {session.World.FreeBodySlots}"); + + session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = cx, + Z = cz, + Radius = 6f, + Depth = 2.5f + }); + int rebuilt = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 4); + Assert.Equal(1, rebuilt); + + float cpuH = terrain.SampleHeight(cx, cz); + float rayStartY = sion.Metadata.MaxY + 25f; + float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f); + var hit = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f)); + Assert.True(hit.Hit); + Assert.True(MathF.Abs(hit.Point.Y - cpuH) < 0.05f, + $"Expected Box3D raycast height ({hit.Point.Y:F3}) to match CPU height ({cpuH:F3}) within 0.05 m"); + } + + [Fact] + public void ServerMatchHost_ResetMatch_RepairScarsOnCrossMapSwitch_ClearsTargetOnlyAndPreservesSource() + { + string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-repairswitch-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + string explicitSionPath = Path.Combine(tempDir, "sion_scars_explicit.cultcache"); + string desertPath = ServerMatchHost.ResolveScarFilePath(explicitSionPath, ArenaMapKind.Sion, ArenaMapKind.Desert); + + try + { + using var host = new ServerMatchHost( + IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, + autoRestartSec: 0, scarFilePath: explicitSionPath, persistScars: true); + + string sionFp = host.Session.State.SionMap!.AssetFingerprint; + + // Stamp Sion crater + host.Session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = -120f, + Z = 180f, + Radius = 5.5f, + Depth = 1.8f + }); + + // Switch to Desert and stamp Desert crater + host.ResetMatch(42, ArenaMapKind.Desert, startInLobby: false); + host.Session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = 0f, + Z = 0f, + Radius = 4.5f, + Depth = 1.4f + }); + + // Switch back to Sion, then ResetMatch(42, Desert, repairScars: true) FROM Sion + host.ResetMatch(42, ArenaMapKind.Sion, startInLobby: false); + Assert.Single(host.Session.State.ScarLedger.Terrain); + + host.ResetMatch(42, ArenaMapKind.Desert, startInLobby: false, repairScars: true); + + Assert.Empty(host.Session.State.ScarLedger.Terrain); + var sionDisk = ArenaScarLedgerStore.Load(explicitSionPath, sionFp); + var desertDisk = ArenaScarLedgerStore.Load(desertPath, "desert:42"); + Assert.Single(sionDisk.Terrain); + Assert.Empty(desertDisk.Terrain); + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, recursive: true); + } + } + } + } +} diff --git a/tests/RustToDust.Tests/SpectatorRingTests.cs b/tests/RustToDust.Tests/SpectatorRingTests.cs new file mode 100644 index 0000000..7b54630 --- /dev/null +++ b/tests/RustToDust.Tests/SpectatorRingTests.cs @@ -0,0 +1,150 @@ +using System; +using System.Linq; +using RustToDust.Core; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class SpectatorRingTests + { + [Fact] + public void Clearance_ZeroInsideSafeCircle_MonotonicOutside() + { + var ring = new SpectatorRing(seed: 101); + float r = ring.SafeRadius; // 560f + Assert.Equal(56, ring.Spectators.Count); + + // Inside safe circle -> 0 cleared + ring.UpdateClearance(new[] { new RingContact(0, r - 20f, 0f, true) }); + Assert.Equal(0, ring.CountClearedFor(0)); + + // Just outside safe circle (+5m) -> 1 cleared + ring.UpdateClearance(new[] { new RingContact(0, r + 5f, 0f, true) }); + int clearedNear = ring.CountClearedFor(0); + Assert.Equal(1, clearedNear); + + // Further outside (+30m) -> 1 + floor(30/12) = 3 cleared + ring.UpdateClearance(new[] { new RingContact(0, r + 30f, 0f, true) }); + int clearedMid = ring.CountClearedFor(0); + Assert.True(clearedMid > clearedNear); + + // Far outside (+100m) -> capped at 8 cleared + ring.UpdateClearance(new[] { new RingContact(0, r + 100f, 0f, true) }); + int clearedFar = ring.CountClearedFor(0); + Assert.Equal(8, clearedFar); + + // Stepping back inside safe circle revokes non-provoked clearance back to 0 + ring.UpdateClearance(new[] { new RingContact(0, 0f, 0f, true) }); + Assert.Equal(0, ring.CountClearedFor(0)); + } + + [Fact] + public void Provocation_AttackingNeutralSpectatorLocksOntoAttackerEvenInsideSafeCircle() + { + var ring = new SpectatorRing(seed: 202); + var targetSpec = ring.Spectators[0]; + Assert.Equal(SpectatorStance.Neutral, targetSpec.Stance); + + // Contender 0 is dead center (well inside SafeRadius) + var contenders = new[] { new RingContact(0, 0f, 0f, true) }; + ring.UpdateClearance(contenders); + Assert.Equal(0, ring.CountClearedFor(0)); + + bool provoked = ring.OnSpectatorDamaged(targetSpec, attackerContenderId: 0); + Assert.True(provoked); + Assert.Equal(SpectatorStance.Provoked, targetSpec.Stance); + Assert.Equal(0, targetSpec.TargetContenderId); + + // Subsequent clearance updates inside the safe circle must NOT clear Provoked lock + ring.UpdateClearance(contenders); + Assert.Equal(SpectatorStance.Provoked, targetSpec.Stance); + Assert.Equal(1, ring.CountProvokedFor(0)); + + // Once attacker dies, provocation reverts to Neutral + ring.UpdateClearance(new[] { new RingContact(0, 0f, 0f, false) }); + Assert.Equal(SpectatorStance.Neutral, targetSpec.Stance); + Assert.Null(targetSpec.TargetContenderId); + } + + [Fact] + public void SalvageDrops_TouristDropsImperialGearWhileExemplarDoesNot() + { + var ring = new SpectatorRing(seed: 303); + var rng = new Random(99); + + var tourists = ring.Spectators.Where(s => s.Tier == SpectatorTier.Tourist).ToList(); + var exemplars = ring.Spectators.Where(s => s.Tier == SpectatorTier.Exemplar).ToList(); + + Assert.NotEmpty(tourists); + Assert.NotEmpty(exemplars); + + foreach (var tourist in tourists) + { + var drops = SpectatorRing.RollSalvageDrops(tourist, rng); + Assert.InRange(drops.Count, 1, 2); + Assert.All(drops, d => Assert.True(d.IsImperial)); + } + + foreach (var exemplar in exemplars) + { + var drops = SpectatorRing.RollSalvageDrops(exemplar, rng); + Assert.DoesNotContain(drops, d => d.IsImperial); + } + } + + [Fact] + public void SpawnedSpectators_EveryTierMountsEngineAndWeapon() + { + var ring = new SpectatorRing(seed: 42); + + Assert.Contains(ring.Spectators, s => s.Tier == SpectatorTier.Tourist); + Assert.Contains(ring.Spectators, s => s.Tier == SpectatorTier.Patron); + Assert.Contains(ring.Spectators, s => s.Tier == SpectatorTier.Exemplar); + + foreach (var spec in ring.Spectators) + { + Assert.Contains(spec.Grid.Mounted, m => m.Spec.Kind == HardpointKind.Engine); + Assert.Contains(spec.Grid.Mounted, m => m.Spec.Kind == HardpointKind.Weapon); + } + } + + [Fact] + public void Provocation_AttackingClearedSpectatorSwitchesToProvokedAndPersistsInsideSafeCircle() + { + var ring = new SpectatorRing(seed: 505); + float outsideR = ring.SafeRadius + 15f; + + // Contender 0 steps outside safe circle -> clears at least 1 spectator + ring.UpdateClearance(new[] { new RingContact(0, outsideR, 0f, true) }); + var clearedSpec = ring.Spectators.FirstOrDefault(s => s.Stance == SpectatorStance.Cleared); + Assert.NotNull(clearedSpec); + + // Contender 0 fights back against the Cleared spectator + bool provoked = ring.OnSpectatorDamaged(clearedSpec!, attackerContenderId: 0); + Assert.True(provoked); + Assert.Equal(SpectatorStance.Provoked, clearedSpec!.Stance); + Assert.Equal(0, clearedSpec.TargetContenderId); + + // Returning inside the safe circle must NOT clear the Provoked lock + ring.UpdateClearance(new[] { new RingContact(0, 0f, 0f, true) }); + Assert.Equal(SpectatorStance.Provoked, clearedSpec.Stance); + Assert.Equal(1, ring.CountProvokedFor(0)); + } + + [Fact] + public void BroadcastFeed_VersionAdvancesPastRingBufferCap() + { + var feed = new BroadcastFeed(); + for (int i = 0; i < 40; i++) + { + long prev = feed.Version; + feed.Emit(i, BroadcastKind.TouristPull, $"line-{i}"); + Assert.Equal(prev + 1, feed.Version); + } + + Assert.Equal(32, feed.Lines.Count); + Assert.Equal(40, feed.Version); + Assert.Equal("line-39", feed.Latest?.Text); + } + } +} diff --git a/tests/RustToDust.Tests/TerrainTests.cs b/tests/RustToDust.Tests/TerrainTests.cs new file mode 100644 index 0000000..1e17818 --- /dev/null +++ b/tests/RustToDust.Tests/TerrainTests.cs @@ -0,0 +1,403 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class TerrainTests + { + [Fact] + public void Generate_ProducesDeterministicNonFlatReliefWithinBounds() + { + Assert.Equal(1536f, TerrainField.ArenaSize); + Assert.Equal(8, TerrainField.DesertTileGridCount); + Assert.Equal(192f, TerrainField.TileSize); + Assert.Equal(-18f, TerrainField.MinWorldHeight); + Assert.Equal(52f, TerrainField.MaxWorldHeight); + + var emptyCover = Array.Empty(); + var a = TerrainField.Generate(42UL, emptyCover); + var b = TerrainField.Generate(42UL, emptyCover); + var c = TerrainField.Generate(999UL, emptyCover); + + float minH = float.PositiveInfinity; + float maxH = float.NegativeInfinity; + bool anyDifferentSeed = false; + + for (int gx = -700; gx <= 700; gx += 50) + { + for (int gz = -700; gz <= 700; gz += 50) + { + float ha = a.SampleHeight(gx, gz); + float hb = b.SampleHeight(gx, gz); + float hc = c.SampleHeight(gx, gz); + + Assert.Equal(ha, hb); + if (MathF.Abs(ha - hc) > 0.05f) + { + anyDifferentSeed = true; + } + + minH = MathF.Min(minH, ha); + maxH = MathF.Max(maxH, ha); + } + } + + Assert.True(maxH - minH >= 25f, $"Expected dramatic mesa/dune/canyon relief >= 25m span, got [{minH:F2}, {maxH:F2}]"); + Assert.InRange(minH, TerrainField.MinWorldHeight, -3.0f); + Assert.InRange(maxH, 18.0f, TerrainField.MaxWorldHeight); + Assert.True(anyDifferentSeed, "Different seeds should generate distinct desert relief"); + } + + [Fact] + public void StampCrater_LowersCenterRaisesRimAndDirtyOnlyOverlappingTiles() + { + var terrain = TerrainField.Generate(42UL, Array.Empty()); + + // Tile (3, 3) spans X in [-192, 0), Z in [-192, 0). + // Point (-96, -96) with radius 6m is strictly inside tile (3, 3) and nowhere else. + const float cx = -96f; + const float cz = -96f; + const float radius = 6f; + const float depth = 1.6f; + + float beforeCenter = terrain.SampleHeight(cx, cz); + float beforeRim = terrain.SampleHeight(cx + radius * 0.775f, cz); + + terrain.StampCrater(cx, cz, radius, depth); + + float afterCenter = terrain.SampleHeight(cx, cz); + float afterRim = terrain.SampleHeight(cx + radius * 0.775f, cz); + + Assert.True(afterCenter < beforeCenter - 1.0f, + $"Expected crater center to drop >1.0m (before {beforeCenter:F2}, after {afterCenter:F2})"); + Assert.True(afterRim > beforeRim + 0.2f, + $"Expected crater ejecta rim to rise >0.2m (before {beforeRim:F2}, after {afterRim:F2})"); + + // Only tile (3, 3) should have incremented from version 1 to 2 + for (int tz = 0; tz < terrain.TileGridCount; tz++) + { + for (int tx = 0; tx < terrain.TileGridCount; tx++) + { + int expected = (tx == 3 && tz == 3) ? 2 : 1; + Assert.Equal(expected, terrain.StructuralTileVersions[tx, tz]); + Assert.Equal(expected, terrain.VisualTileVersions[tx, tz]); + } + } + } + + [Fact] + public void Raycast_DetectsBlockingMesaAndClearsAboveCrest() + { + var terrain = TerrainField.Generate(42UL, Array.Empty()); + TerrainBrush? tallMesa = null; + for (int i = 0; i < terrain.Brushes.Count; i++) + { + var b = terrain.Brushes[i]; + if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f) + { + tallMesa = b; + break; + } + } + + Assert.NotNull(tallMesa); + var mesa = tallMesa!.Value; + + float startX = mesa.X - mesa.RadiusX - 25f; + float endX = mesa.X + mesa.RadiusX + 25f; + float span = endX - startX; + float lowY = terrain.SampleHeight(startX, mesa.Z) + 4f; + + bool blocked = terrain.Raycast( + startX, lowY, mesa.Z, + 1f, 0f, 0f, + span, + out float hx, out _, out _, out _); + + Assert.True(blocked, "Expected low ray across tall mesa to be blocked by terrain"); + Assert.InRange(hx, startX, endX); + + float highY = terrain.SampleHeight(mesa.X, mesa.Z) + 6f; + bool clear = terrain.Raycast( + startX, highY, mesa.Z, + 1f, 0f, 0f, + span, + out _, out _, out _, out _); + + Assert.False(clear, "Expected ray above mesa plateau to pass unobstructed"); + } + + [Fact] + public void StampTrack_BoundsDynamicDecalCount() + { + var terrain = TerrainField.Generate(7UL, Array.Empty()); + int initialCount = terrain.Brushes.Count; + + for (int i = 0; i < TerrainField.MaxDynamicDecals + 40; i++) + { + float x = -80f + (i % 40) * 4f; + float z = -80f + (i / 40) * 8f; + terrain.StampTrack(x, z, yaw: 0.4f, width: 1.6f, length: 2.5f); + } + + Assert.Equal(initialCount + TerrainField.MaxDynamicDecals, terrain.Brushes.Count); + } + + [Fact] + public void ArenaSession_BuggyDrivesAcrossDunesWithoutNanAndTracksElevation() + { + using var session = new ArenaSession(seed: 42, slot0Human: true, skipInitialDrop: true); + var player = session.State.Contenders[0]; + int initialBrushes = session.State.Terrain.Brushes.Count; + + float minGround = float.PositiveInfinity; + float maxGround = float.NegativeInfinity; + + for (int tick = 0; tick < 360; tick++) + { + float steer = MathF.Sin(tick * 0.025f) * 0.45f; + session.SetHumanInput(0, new PlayerInput( + Throttle: 1f, + Steer: steer, + AimWorldX: player.X + 30f, + AimWorldZ: player.Z, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + Assert.False(float.IsNaN(player.X) || float.IsNaN(player.Y) || float.IsNaN(player.Z), + $"NaN pose at tick {tick}"); + + float gh = session.State.Terrain.SampleHeight(player.X, player.Z); + minGround = MathF.Min(minGround, gh); + maxGround = MathF.Max(maxGround, gh); + + // Chassis should remain supported near the terrain surface (never sink under -12m or rocket into orbit) + float bottomY = player.Y - player.Grid.Spec.HalfHeight; + Assert.InRange(bottomY - gh, -0.75f, 4.0f); + } + + Assert.True(session.State.Terrain.Brushes.Count > initialBrushes, + "Driving across dust should stamp tire track brushes"); + Assert.True(maxGround - minGround > 0.25f, + $"Expected buggy to traverse non-flat terrain (span {maxGround - minGround:F2}m)"); + } + + [Theory] + [InlineData(42)] + [InlineData(101)] + [InlineData(999)] + public void CoverBoxes_HaveFlatFootprintWithinHalfMeterAcrossAllCorners(int seed) + { + var state = new MatchState(seed); + float maxCoverCornerDelta = 0f; + + foreach (var box in state.ArenaCoverBoxes) + { + float[] heights = + { + state.Terrain.SampleHeight(box.X, box.Z), + state.Terrain.SampleHeight(box.X - box.HalfX, box.Z - box.HalfZ), + state.Terrain.SampleHeight(box.X + box.HalfX, box.Z - box.HalfZ), + state.Terrain.SampleHeight(box.X - box.HalfX, box.Z + box.HalfZ), + state.Terrain.SampleHeight(box.X + box.HalfX, box.Z + box.HalfZ) + }; + + float minH = float.PositiveInfinity; + float maxH = float.NegativeInfinity; + for (int i = 0; i < heights.Length; i++) + { + minH = MathF.Min(minH, heights[i]); + maxH = MathF.Max(maxH, heights[i]); + } + + maxCoverCornerDelta = MathF.Max(maxCoverCornerDelta, maxH - minH); + float boxBottom = box.Y - box.HalfY; + Assert.True(boxBottom <= minH + 0.01f, + $"Cover box at ({box.X}, {box.Z}) bottom {boxBottom:F2}m floats above corner height {minH:F2}m"); + } + + Assert.Equal(36, state.ArenaCoverBoxes.Count); + Assert.True(maxCoverCornerDelta <= 0.6f, + $"Expected MaxCoverCornerDelta <= 0.6m for seed {seed}, got {maxCoverCornerDelta:F3}m"); + } + + [Fact] + public void RoadBrushes_MajorAxisRunsTangentiallyToFormRingLoop() + { + var terrain = TerrainField.Generate(42UL, Array.Empty()); + var roads = new List(); + for (int i = 0; i < terrain.Brushes.Count; i++) + { + if (terrain.Brushes[i].Kind == TerrainBrushKind.Road) + { + roads.Add(terrain.Brushes[i]); + } + } + + Assert.Equal(16, roads.Count); + foreach (var road in roads) + { + Assert.True(road.RadiusX > road.RadiusZ, + $"Expected Road RadiusX ({road.RadiusX}) > RadiusZ ({road.RadiusZ}) so major axis follows tangential u"); + + float rLen = MathF.Sqrt(road.X * road.X + road.Z * road.Z); + float radX = road.X / rLen; + float radZ = road.Z / rLen; + float axisX = MathF.Cos(road.RotationRad); + float axisZ = MathF.Sin(road.RotationRad); + float radialDot = MathF.Abs(radX * axisX + radZ * axisZ); + + Assert.True(radialDot < 1e-4f, + $"Expected Road major axis to be tangential (dot ~ 0), got {radialDot:F4}"); + } + } + + [Theory] + [InlineData(42)] + [InlineData(101)] + public void SteepMesaAndDuneTraversal_AllSixChassis_NoTunnelingSkyLaunchOrOverturning(int seed) + { + foreach (var chassis in Catalog.AllChassis) + { + RunSteepTerrainStress(seed, chassis, testDune: false); + RunSteepTerrainStress(seed, chassis, testDune: true); + } + } + + private static void RunSteepTerrainStress(int seed, ChassisSpec chassis, bool testDune) + { + using var session = new ArenaSession(seed, slot0Human: true); + var player = session.State.Contenders[0]; + + TerrainBrush targetBrush = default; + float startX = 0f; + float startZ = 0f; + float bestScore = -1f; + for (int i = 0; i < session.State.Terrain.Brushes.Count; i++) + { + var b = session.State.Terrain.Brushes[i]; + bool matches = testDune + ? b.Kind == TerrainBrushKind.DuneRidge && b.HeightDelta >= 14f + : b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f; + if (!matches) + { + continue; + } + + if (MathF.Sqrt(b.X * b.X + b.Z * b.Z) > SpectatorRing.InitialRadius - 90f) + { + continue; + } + + float peakH = session.State.Terrain.SampleHeight(b.X, b.Z); + for (int k = 0; k < 8; k++) + { + float localAng = k * (MathF.PI * 0.25f); + float localX = MathF.Cos(localAng) * (b.RadiusX + 18f); + float localZ = MathF.Sin(localAng) * (b.RadiusZ + 18f); + float cosR = MathF.Cos(b.RotationRad); + float sinR = MathF.Sin(b.RotationRad); + float candX = b.X + localX * cosR - localZ * sinR; + float candZ = b.Z + localX * sinR + localZ * cosR; + if (MathF.Sqrt(candX * candX + candZ * candZ) > SpectatorRing.InitialRadius - 35f) + { + continue; + } + + float baseH = session.State.Terrain.SampleHeight(candX, candZ); + float relief = peakH - baseH; + if (relief > bestScore) + { + bestScore = relief; + targetBrush = b; + startX = candX; + startZ = candZ; + } + } + } + Assert.True(bestScore >= 10f, $"Expected a climbable {(testDune ? "dune" : "mesa")} approach inside safe circle in seed {seed}"); + + // Keep AI contenders on the opposite side of the safe zone so combat does not kill the vehicle mid-traversal + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(session.State.Contenders[i].Id, -targetBrush.X * 0.5f + (i - 6) * 14f, -targetBrush.Z * 0.5f); + } + + float yawToTarget = MathF.Atan2(targetBrush.X - startX, targetBrush.Z - startZ); + session.SetContenderPose(player.Id, startX, startZ, yawToTarget); + + if (chassis.Id != player.Grid.Spec.Id) + { + session.State.SpawnChassisDrop(player.X, player.Z, chassis); + Assert.True(session.TrySwapNearbyChassis(0), $"Expected swap to {chassis.Id} to succeed"); + Assert.Equal(chassis.Id, player.Grid.Spec.Id); + } + + float startGroundY = session.State.Terrain.SampleHeight(player.X, player.Z); + float maxGroundY = startGroundY; + float minBottomRel = float.PositiveInfinity; + float maxAirGap = float.NegativeInfinity; + float minUpDot = float.PositiveInfinity; + + for (int tick = 0; tick < 600; tick++) + { + float steer = MathF.Sin(tick * 0.03f) * 0.15f; + session.SetHumanInput(0, new PlayerInput( + Throttle: 1f, + Steer: steer, + AimWorldX: targetBrush.X, + AimWorldZ: targetBrush.Z, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + Assert.False( + float.IsNaN(player.X) || float.IsNaN(player.Y) || float.IsNaN(player.Z), + $"NaN pose at tick {tick} (seed={seed}, chassis={chassis.Id}, dune={testDune})"); + + var body = session.GetContenderBody(player.Id); + Assert.True(body.HasValue, $"Expected live contender body at tick {tick} (seed={seed}, chassis={chassis.Id})"); + + int lane = body!.Value.Lane; + var view = session.World.View; + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var up = Vector3.Transform(Vector3.UnitY, q); + Assert.False(float.IsNaN(up.Y), $"NaN orientation at tick {tick}"); + + float gh = session.State.Terrain.SampleHeight(player.X, player.Z); + float hullHalfH = player.Grid.Spec.IsWalker + ? ArenaSession.GetPhysicsHalfHeight(player.Grid.Spec) + : player.Grid.Spec.HalfHeight; + float bottomRel = (player.Y - hullHalfH) - gh; + float airGapRel = (player.Y - player.Grid.Spec.HalfHeight) - gh; + + maxGroundY = MathF.Max(maxGroundY, gh); + minBottomRel = MathF.Min(minBottomRel, bottomRel); + maxAirGap = MathF.Max(maxAirGap, airGapRel); + minUpDot = MathF.Min(minUpDot, up.Y); + } + + float climbProgress = maxGroundY - startGroundY; + float minRequiredClimb = testDune ? 4.0f : 2.0f; + float minAllowedUpDot = chassis.IsWalker ? 0.927f : 0.50f; + // VTOLs spawn at 10m AGL and glide under gravity over mesa cliff drops instead of slamming downward + float maxAllowedAirGap = chassis.IsVtol ? targetBrush.HeightDelta + 15f : 5.0f; + + Assert.True(climbProgress >= minRequiredClimb, + $"Insufficient uphill climb progress (seed={seed}, chassis={chassis.Id}, dune={testDune}): climb={climbProgress:F2}m start=({startX:F1},{startZ:F1},h={startGroundY:F2}) end=({player.X:F1},{player.Z:F1},maxH={maxGroundY:F2}) brush=({targetBrush.X:F1},{targetBrush.Z:F1},rx={targetBrush.RadiusX:F1},rz={targetBrush.RadiusZ:F1},rot={targetBrush.RotationRad:F2},dh={targetBrush.HeightDelta:F1})"); + Assert.True(minBottomRel >= -0.35f, + $"Terrain tunneling detected (seed={seed}, chassis={chassis.Id}, dune={testDune}): minBottomRel={minBottomRel:F2}m"); + Assert.True(maxAirGap <= maxAllowedAirGap, + $"Excessive sky launch detected (seed={seed}, chassis={chassis.Id}, dune={testDune}): maxAirGap={maxAirGap:F2}m (max={maxAllowedAirGap:F1}m)"); + Assert.True(minUpDot >= minAllowedUpDot, + $"Excessive chassis tilt (seed={seed}, chassis={chassis.Id}, dune={testDune}): minUpDot={minUpDot:F3} (req>={minAllowedUpDot:F3})"); + } + } +} diff --git a/tests/RustToDust.Tests/VehiclePackageTests.cs b/tests/RustToDust.Tests/VehiclePackageTests.cs new file mode 100644 index 0000000..5cd85ba --- /dev/null +++ b/tests/RustToDust.Tests/VehiclePackageTests.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using RustToDust.Core; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class VehiclePackageTests + { + private static readonly string[] Expected15Ids = + { + "jackal", "mule", "ferret", "hornet", "mammoth", + "ironclad", "anvil", "condor", "breaker", "paladin", + "raptor", "manticore", "bastion", "spectre", "kestrel" + }; + + [Fact] + public void All15VehicleArchives_LoadFromCultCacheAndMatchManifests() + { + Assert.Equal(15, Catalog.AllChassis.Count); + Assert.Equal(15, Catalog.PackagesById.Count); + + string vehiclesRoot = VehicleCatalogLoader.LocateVehiclesDirectory(); + foreach (string id in Expected15Ids) + { + string ccPath = Path.Combine(vehiclesRoot, id, "vehicle.cc"); + string manifestPath = Path.Combine(vehiclesRoot, id, "manifest.json"); + Assert.True(File.Exists(ccPath), $"Missing vehicle.cc for {id}"); + Assert.True(File.Exists(manifestPath), $"Missing manifest.json for {id}"); + + VehiclePackage pkg = VehiclePackageStore.Read(ccPath); + Assert.Equal(id, pkg.Id); + Assert.True(File.Exists(Path.Combine(vehiclesRoot, id, pkg.ModelAsset)), $"Missing GLB {pkg.ModelAsset}"); + + using var doc = JsonDocument.Parse(File.ReadAllText(manifestPath)); + var root = doc.RootElement; + + Assert.Equal(root.GetProperty("gridWidth").GetInt32(), pkg.GridWidth); + Assert.Equal(root.GetProperty("gridHeight").GetInt32(), pkg.GridHeight); + + var manifestHps = root.GetProperty("hardpoints").EnumerateArray().ToArray(); + Assert.Equal(manifestHps.Length, pkg.Hardpoints.Count); + for (int i = 0; i < manifestHps.Length; i++) + { + string expectedId = manifestHps[i].GetProperty("id").GetString()!; + string expectedAnchor = manifestHps[i].GetProperty("modelNodeId").GetString()!; + Assert.Equal(expectedId, pkg.Hardpoints[i].Id); + Assert.Equal(expectedAnchor, pkg.Hardpoints[i].AnchorId); + } + + var manifestJoints = root.GetProperty("joints").EnumerateArray().ToArray(); + Assert.Equal(manifestJoints.Length, pkg.Joints.Count); + for (int i = 0; i < manifestJoints.Length; i++) + { + Assert.Equal(manifestJoints[i].GetProperty("id").GetString(), pkg.Joints[i].Id); + } + + var boundsSize = root.GetProperty("bounds").GetProperty("size").EnumerateArray().Select(e => e.GetSingle()).ToArray(); + Assert.Equal(boundsSize[0] * 0.5f, pkg.HalfWidth, precision: 3); + Assert.Equal(boundsSize[1] * 0.5f, pkg.HalfHeight, precision: 3); + Assert.Equal(boundsSize[2] * 0.5f, pkg.HalfLength, precision: 3); + + Assert.NotEmpty(pkg.PartCells); + var spec = pkg.ToChassisSpec(); + Assert.All(pkg.PartCells, pc => + { + Assert.False(string.IsNullOrWhiteSpace(pc.NodeName)); + Assert.True(spec.IsActive(pc.CellX, pc.CellY), $"{id}: PartCell '{pc.NodeName}' mapped to inactive ({pc.CellX},{pc.CellY})"); + }); + } + } + + [Fact] + public void BreakerArchive_RoundTripsFullMechanismHierarchy() + { + string vehiclesRoot = VehicleCatalogLoader.LocateVehiclesDirectory(); + string manifestPath = Path.Combine(vehiclesRoot, "breaker", "manifest.json"); + using var doc = JsonDocument.Parse(File.ReadAllText(manifestPath)); + var mechJson = doc.RootElement.GetProperty("mechanisms"); + + var breaker = Catalog.PackagesById["breaker"]; + Assert.NotNull(breaker.Mechanisms); + Assert.Equal(mechJson.GetProperty("dofs").GetArrayLength(), breaker.Mechanisms!.Dofs.Count); + Assert.Equal(35, breaker.Mechanisms.Dofs.Count); + Assert.Equal(mechJson.GetProperty("rams").GetArrayLength(), breaker.Mechanisms.Rams.Count); + Assert.Equal(4, breaker.Mechanisms.Rams.Count); + Assert.Equal(2, breaker.Mechanisms.Scissors.Count); + Assert.Equal(2, breaker.Mechanisms.Struts.Count); + + Assert.Equal("LegL.Hip", breaker.Mechanisms.Dofs[0].Name); + Assert.Equal( + new[] { "LegL.RecessRam0", "LegL.RecessRam1", "LegR.RecessRam0", "LegR.RecessRam1" }, + breaker.Mechanisms.Rams.Select(r => r.Name).ToArray()); + Assert.Equal("LegL.Torque", breaker.Mechanisms.Scissors[0].Name); + Assert.Equal("LegL.Oleo", breaker.Mechanisms.Struts[0].Name); + Assert.Equal(0.2f, breaker.Mechanisms.Struts[0].Travel, precision: 4); + } + + [Fact] + public void AliasesAndVtolBalance_MatchSpecification() + { + Assert.Same(Catalog.Jackal, Catalog.Buggy); + Assert.Same(Catalog.Mule, Catalog.Technical); + Assert.Same(Catalog.Anvil, Catalog.Tank); + + // VTOL glass-cannon balance vs ground equivalents + Assert.Equal(MobilityKind.Vtol, Catalog.Hornet.Mobility); + Assert.Equal(MobilityKind.Vtol, Catalog.Condor.Mobility); + Assert.Equal(42f, Catalog.Hornet.HoverMaxAltitudeM); + Assert.Equal(36f, Catalog.Condor.HoverMaxAltitudeM); + Assert.Equal(0f, Catalog.Jackal.HoverMaxAltitudeM); + Assert.Equal(0f, Catalog.Anvil.HoverMaxAltitudeM); + + Assert.True(Catalog.Hornet.BaseCellArmor < Catalog.Jackal.BaseCellArmor, + $"Hornet armor ({Catalog.Hornet.BaseCellArmor}) must be lighter than Jackal ({Catalog.Jackal.BaseCellArmor})"); + Assert.True(Catalog.Hornet.BaseCellArmor < Catalog.Ferret.BaseCellArmor, + $"Hornet armor ({Catalog.Hornet.BaseCellArmor}) must be lighter than Ferret ({Catalog.Ferret.BaseCellArmor})"); + Assert.True(Catalog.Condor.BaseCellArmor < Catalog.Ironclad.BaseCellArmor, + $"Condor armor ({Catalog.Condor.BaseCellArmor}) must be lighter than Ironclad ({Catalog.Ironclad.BaseCellArmor})"); + Assert.True(Catalog.Condor.BaseCellArmor < Catalog.Anvil.BaseCellArmor, + $"Condor armor ({Catalog.Condor.BaseCellArmor}) must be lighter than Anvil ({Catalog.Anvil.BaseCellArmor})"); + + // All 14 non-starter chassis launch in Wave 0 orbital gear pods and touch down into GroundDrops + var state = new MatchState(seed: 42); + for (int t = 0; t < 900; t++) + { + state.Time += 1f / 60f; + state.OrbitalDrop.Step(1f / 60f); + } + var droppedChassisIds = state.GroundDrops + .Where(d => d.Chassis is not null) + .Select(d => d.Chassis!.Id) + .ToHashSet(StringComparer.Ordinal); + foreach (string id in Expected15Ids.Where(x => x != "jackal")) + { + Assert.Contains(id, droppedChassisIds); + } + } + } +} diff --git a/tests/RustToDust.Tests/VtolAndArcTests.cs b/tests/RustToDust.Tests/VtolAndArcTests.cs new file mode 100644 index 0000000..c7fd2b2 --- /dev/null +++ b/tests/RustToDust.Tests/VtolAndArcTests.cs @@ -0,0 +1,521 @@ +using System; +using System.Linq; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class VtolAndArcTests + { + private static void IsolateContenders(ArenaSession session, params int[] keepIds) + { + var keep = keepIds.ToHashSet(); + for (int i = 0; i < session.State.Contenders.Count; i++) + { + var c = session.State.Contenders[i]; + if (!keep.Contains(c.Id)) + { + session.SetContenderPose(c.Id, -650f + i * 10f, -650f); + } + } + for (int i = 0; i < session.State.Spectators.Spectators.Count; i++) + { + var s = session.State.Spectators.Spectators[i]; + session.SetSpectatorPose(s.Id, 650f, -650f + i * 4f); + } + } + + [Fact] + public void Vtol_HornetAndCondor_ClimbHoverAndDescendViaVerticalThrottle() + { + foreach (var vtolSpec in new[] { Catalog.Hornet, Catalog.Condor }) + { + using var session = new ArenaSession(seed: 42, slot0Human: true); + IsolateContenders(session, 0); + var player = session.State.Contenders[0]; + session.SetContenderPose(player.Id, 0f, 0f, 0f); + + session.State.SpawnChassisDrop(player.X, player.Z, vtolSpec); + Assert.True(session.TrySwapNearbyChassis(0)); + Assert.Equal(vtolSpec.Id, player.Grid.Spec.Id); + Assert.True(player.Grid.Spec.IsVtol); + + float gh0 = session.State.Terrain.SampleHeight(player.X, player.Z); + float initialAgl = player.Y - vtolSpec.HalfHeight - gh0; + + // Climb with VerticalThrottle = +1 for 2.5s (150 ticks) + for (int t = 0; t < 150; t++) + { + session.SetHumanInput(0, new PlayerInput(0.4f, 0.1f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 1f)); + session.Step(); + } + + float ghClimbed = session.State.Terrain.SampleHeight(player.X, player.Z); + float climbedAgl = player.Y - vtolSpec.HalfHeight - ghClimbed; + Assert.True(climbedAgl > initialAgl + 12f, + $"{vtolSpec.Id}: expected climb > 12m, got initial={initialAgl:F2}m -> climbed={climbedAgl:F2}m"); + Assert.True(climbedAgl <= vtolSpec.HoverMaxAltitudeM + 2.0f, + $"{vtolSpec.Id}: exceeded HoverMaxAltitudeM {vtolSpec.HoverMaxAltitudeM}m (got {climbedAgl:F2}m)"); + + // Hold hover with VerticalThrottle = 0 for 2.0s (120 ticks) -> settles to TargetHoverAltAgl and holds steady + for (int t = 0; t < 60; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 0f)); + session.Step(); + } + float ghSettled = session.State.Terrain.SampleHeight(player.X, player.Z); + float settledAgl = player.Y - vtolSpec.HalfHeight - ghSettled; + for (int t = 0; t < 60; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 0f)); + session.Step(); + } + float ghHeld = session.State.Terrain.SampleHeight(player.X, player.Z); + float heldAgl = player.Y - vtolSpec.HalfHeight - ghHeld; + Assert.InRange(heldAgl, player.TargetHoverAltAgl - 1.5f, player.TargetHoverAltAgl + 1.5f); + Assert.InRange(heldAgl, settledAgl - 1.0f, settledAgl + 1.0f); + + // Descend with VerticalThrottle = -1 for 3s (180 ticks) - should settle smoothly near 2.5m clearance + for (int t = 0; t < 180; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: -1f)); + session.Step(); + } + float ghDesc = session.State.Terrain.SampleHeight(player.X, player.Z); + float descAgl = player.Y - vtolSpec.HalfHeight - ghDesc; + Assert.True(descAgl < heldAgl - 8f, $"{vtolSpec.Id}: expected descent from {heldAgl:F2}m, got {descAgl:F2}m"); + Assert.InRange(descAgl, 1.5f, 4.5f); + } + } + + [Fact] + public void MwllTriangle_ZenithBlindSpot_MainCannonBlocked_WideArcPdAndDistantGroundRigHit() + { + using var session = new ArenaSession(seed: 42, slot0Human: true); + var player = session.State.Contenders[0]; + var overheadVtol = session.State.Contenders[1]; + var distantGroundRig = session.State.Contenders[2]; + IsolateContenders(session, player.Id, overheadVtol.Id); + + // Swap player to Anvil (heavy tracked tank, weapons capped at +30 deg pitch) + session.SetContenderPose(player.Id, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil); + Assert.True(session.TrySwapNearbyChassis(0)); + Assert.Equal("anvil", player.Grid.Spec.Id); + + // Swap contender 1 to Hornet and position it high overhead (~14m horizontal, ~38m above player => ~+69 deg pitch!) + session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f); + session.State.SpawnChassisDrop(0f, 14f, Catalog.Hornet); + Assert.True(session.State.TrySwapNearbyChassis(overheadVtol.Id)); + Assert.Equal("hornet", overheadVtol.Grid.Spec.Id); + overheadVtol.AiScavengeCooldown = 999f; + overheadVtol.TargetHoverAltAgl = 38f; + session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f); + // Step once to seat bodies cleanly + session.SetHumanInput(0, new PlayerInput(0f, 0f, overheadVtol.X, overheadVtol.Z, false, false, true, AimWorldY: overheadVtol.Y)); + session.Step(); + + float vtolArmorBefore = overheadVtol.Grid.TotalArmorRatio(); + + // 1. Anvil's main cannons (-10..+30 deg) CANNOT fire at +69 deg overhead VTOL + for (int t = 0; t < 20; t++) + { + overheadVtol.TargetHoverAltAgl = 38f; + session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f); + session.SetHumanInput(0, new PlayerInput( + 0f, 0f, + overheadVtol.X, overheadVtol.Z, + Fire: true, + InteractPickup: false, + Brake: true, + AimWorldY: overheadVtol.Y)); + session.Step(); + } + Assert.True(player.AllWeaponsOutOfArc, + $"Expected Anvil main cannons to report AllWeaponsOutOfArc (in={player.InArcWeaponCount}, out={player.OutOfArcWeaponCount}, pY={player.Y:F1}, vY={overheadVtol.Y:F1}, vSpec={overheadVtol.Grid.Spec.Id}, vAlt={overheadVtol.TargetHoverAltAgl:F1}, vAlive={overheadVtol.Alive}, vPos=({overheadVtol.X:F1},{overheadVtol.Z:F1}))"); + Assert.All(player.Grid.Mounted.Where(m => m.Spec.Kind == HardpointKind.Weapon), w => Assert.Equal(0f, w.Cooldown)); + Assert.Equal(vtolArmorBefore, overheadVtol.Grid.TotalArmorRatio()); + + // 2. Mount a 1x1 Wide-Arc PointDefenseFlak (-10..+85 deg) onto Anvil's hp.weapon.sponson_r -> CAN hit overhead VTOL! + Assert.True(player.Grid.TryMount(Catalog.PointDefenseFlak, "hp.weapon.sponson_r")); + int pdTracers = 0; + for (int t = 0; t < 25; t++) + { + overheadVtol.TargetHoverAltAgl = 38f; + session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f); + session.SetHumanInput(0, new PlayerInput( + 0f, 0f, + overheadVtol.X, overheadVtol.Z, + Fire: true, + InteractPickup: false, + Brake: true, + AimWorldY: overheadVtol.Y)); + session.Step(); + pdTracers += session.State.Tracers.Count; + } + Assert.False(player.AllWeaponsOutOfArc, "Expected Wide-Arc PD module to clear overhead out-of-arc block"); + Assert.True(pdTracers > 0, "Expected Wide-Arc PD to fire at overhead VTOL"); + Assert.True(overheadVtol.Grid.TotalArmorRatio() < vtolArmorBefore, + "Expected Wide-Arc PD burst to damage overhead VTOL"); + + // 3. Second ground rig (Anvil, MaxPitchDeg = 30 deg) placed 140m away (~+15 deg pitch) CAN hit the overhead VTOL! + session.SetContenderPose(distantGroundRig.Id, 0f, 154f, MathF.PI); + session.State.SpawnChassisDrop(0f, 154f, Catalog.Anvil); + Assert.True(session.State.TrySwapNearbyChassis(distantGroundRig.Id)); + Assert.True(distantGroundRig.Grid.TryMount(Catalog.Autocannon, "hp.weapon.siege_l")); + session.SetContenderPose(distantGroundRig.Id, 0f, 154f, MathF.PI); + // Unmount player's PD so only distant rig shoots now + player.Grid.TryMount(Catalog.Mg762, "hp.weapon.sponson_r"); + + float vtolArmorBeforeDistant = overheadVtol.Grid.TotalArmorRatio(); + for (int t = 0; t < 90; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, -20f, false, false, true)); + session.Step(); + } + Assert.True(overheadVtol.Grid.TotalArmorRatio() < vtolArmorBeforeDistant, + "Expected distant ground rig 140m away (~15 deg pitch) to hit the hovering Hornet inside its 30 deg cannon arc"); + } + + [Fact] + public void GroundRigWithWideArcPd_AutoTracksNearbyAirborneVtolWithoutManualFire() + { + using var session = new ArenaSession(seed: 42, slot0Human: true); + var player = session.State.Contenders[0]; + var overheadVtol = session.State.Contenders[1]; + IsolateContenders(session, player.Id, overheadVtol.Id); + + // Swap player to Jackal, mount Wide-Arc PD, leave Fire = false and aim elsewhere! + session.SetContenderPose(player.Id, 0f, 0f, 0f); + Assert.True(player.Grid.TryMount(Catalog.PointDefenseFlak, "hp.weapon.roof")); + + session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); + session.State.SpawnChassisDrop(20f, 25f, Catalog.Hornet); + Assert.True(session.State.TrySwapNearbyChassis(overheadVtol.Id)); + Assert.Equal("hornet", overheadVtol.Grid.Spec.Id); + overheadVtol.AiScavengeCooldown = 999f; + overheadVtol.TargetHoverAltAgl = 28f; + session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); + + float vtolArmorBefore = overheadVtol.Grid.TotalArmorRatio(); + bool sawAutoTracer = false; + for (int t = 0; t < 45; t++) + { + overheadVtol.TargetHoverAltAgl = 28f; + session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); + session.SetHumanInput(0, new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: 0f, + AimWorldZ: -50f, + Fire: false, + InteractPickup: false, + Brake: true)); + session.Step(); + if (session.State.Tracers.Count > 0) + { + sawAutoTracer = true; + } + } + + Assert.True(sawAutoTracer, "Expected auto-PD to fire tracers at airborne VTOL within 140m even while Fire=false"); + Assert.True(overheadVtol.Grid.TotalArmorRatio() < vtolArmorBefore, + $"Expected auto-PD tracking to hit airborne VTOL (before={vtolArmorBefore:F3}, after={overheadVtol.Grid.TotalArmorRatio():F3}, vY={overheadVtol.Y:F1}, vSpec={overheadVtol.Grid.Spec.Id}, tracers={session.State.Tracers.Count}, lastTracer={(session.State.Tracers.Count > 0 ? $"{session.State.Tracers[^1].EndX:F1},{session.State.Tracers[^1].EndY:F1},{session.State.Tracers[^1].EndZ:F1}" : "none")})"); + } + + [Fact] + public void QuickBolt_MountsScavengedModuleIntoEmptyMatchingHardpointBeforeCargo() + { + var state = new MatchState(seed: 42, skipInitialDrop: true); + var player = state.Contenders[0]; + player.IsHuman = true; + + // Swap to Anvil (starter Jackal transfers 1 weapon into hp.weapon.sponson_l, leaving hp.weapon.siege_l, hp.weapon.siege_r, hp.weapon.sponson_r empty!) + state.SpawnChassisDrop(player.X, player.Z, Catalog.Anvil); + Assert.True(state.TrySwapNearbyChassis(0)); + Assert.Null(player.Grid.GetMountedOn("hp.weapon.siege_l")); + int cargoBefore = player.Grid.Cargo.Count; + + // Drop 1x1 PointDefenseFlak right at player and press [E] + state.SpawnModuleDrop(player.X + 0.5f, player.Z, Catalog.PointDefenseFlak); + MatchRules.ApplyHumanInput(state, 0, new PlayerInput( + 0f, 0f, player.X, player.Z + 10f, + Fire: false, + InteractPickup: true, + Brake: false)); + + // Must bolt straight onto empty hp.weapon.siege_l, NOT Cargo! + var mountedSiege = player.Grid.GetMountedOn("hp.weapon.siege_l"); + Assert.NotNull(mountedSiege); + Assert.Equal(Catalog.PointDefenseFlak.Id, mountedSiege!.Spec.Id); + Assert.Equal(cargoBefore, player.Grid.Cargo.Count); + Assert.Equal(BroadcastKind.QuickBolt, state.Broadcast.Latest?.Kind); + + // Now fill remaining weapon slots; next weapon pickup must fall back to Cargo! + Assert.True(player.Grid.TryMount(Catalog.Autocannon, "hp.weapon.siege_r")); + Assert.True(player.Grid.TryMount(Catalog.Mg762, "hp.weapon.sponson_r")); + state.SpawnModuleDrop(player.X + 0.5f, player.Z, Catalog.Flak); + MatchRules.ApplyHumanInput(state, 0, new PlayerInput( + 0f, 0f, player.X, player.Z + 10f, + Fire: false, + InteractPickup: true, + Brake: false)); + + Assert.Equal(cargoBefore + 1, player.Grid.Cargo.Count); + Assert.Equal(Catalog.Flak.Id, player.Grid.Cargo[^1].Id); + } + + [Fact] + public void Vtol_ReverseIntoTallMesaAndCliffDrop_ZeroUndergroundTicks() + { + using var session = new ArenaSession(seed: 42, slot0Human: true, skipInitialDrop: true); + var player = session.State.Contenders[0]; + IsolateContenders(session, player.Id); + + // Pick the tallest Mesa in generated terrain + TerrainBrush tallMesa = default; + float bestHeight = -1f; + for (int i = 0; i < session.State.Terrain.Brushes.Count; i++) + { + var b = session.State.Terrain.Brushes[i]; + if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta > bestHeight) + { + bestHeight = b.HeightDelta; + tallMesa = b; + } + } + Assert.True(bestHeight >= 22f, "Expected a tall Mesa in seed 42"); + + session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Hornet); + Assert.True(session.TrySwapNearbyChassis(0)); + Assert.Equal("hornet", player.Grid.Spec.Id); + + // 1. Reverse (-Z/+X away from yaw) straight into the tall Mesa cliff face + float startX = tallMesa.X - tallMesa.RadiusX - 24f; + session.SetContenderPose(player.Id, startX, tallMesa.Z, -MathF.PI * 0.5f); // facing -X so Throttle=-1 reverses into +X Mesa + player.TargetHoverAltAgl = 10f; + + float minReverseAgl = float.PositiveInfinity; + int undergroundReverseTicks = 0; + for (int t = 0; t < 240; t++) + { + session.SetHumanInput(0, new PlayerInput(-1f, 0f, player.X - 30f, player.Z, false, false, false)); + session.Step(); + float gh = session.State.Terrain.SampleHeight(player.X, player.Z); + float agl = (player.Y - player.Grid.Spec.HalfHeight) - gh; + if (agl < minReverseAgl) minReverseAgl = agl; + if (agl < 0f) undergroundReverseTicks++; + } + + Assert.Equal(0, undergroundReverseTicks); + Assert.True(minReverseAgl >= 0.5f, $"Reverse into +{bestHeight:F1}m mesa dipped too low: minAgl={minReverseAgl:F2}m"); + + // 2. Drive off the Mesa cliff edge onto the surrounding plain (must never slam underground) + session.SetContenderPose(player.Id, tallMesa.X + tallMesa.RadiusX * 0.15f, tallMesa.Z, MathF.PI * 0.5f); // facing +X off edge + player.TargetHoverAltAgl = 10f; + // Re-seat on plateau top + float plateauGh = session.State.Terrain.SampleHeight(player.X, player.Z); + session.SetContenderPose(player.Id, player.X, player.Z, MathF.PI * 0.5f); + Assert.True(plateauGh > 15f, $"Expected plateau height > 15m, got {plateauGh:F2}m"); + + float minDropAgl = float.PositiveInfinity; + int undergroundDropTicks = 0; + for (int t = 0; t < 240; t++) + { + session.SetHumanInput(0, new PlayerInput(1f, 0f, player.X + 30f, player.Z, false, false, false)); + session.Step(); + float gh = session.State.Terrain.SampleHeight(player.X, player.Z); + float agl = (player.Y - player.Grid.Spec.HalfHeight) - gh; + if (agl < minDropAgl) minDropAgl = agl; + if (agl < 0f) undergroundDropTicks++; + } + + Assert.Equal(0, undergroundDropTicks); + Assert.True(minDropAgl >= 0.5f, $"Cliff drop off +{bestHeight:F1}m mesa dipped too low: minAgl={minDropAgl:F2}m"); + } + + [Fact] + public void Vtol_OverheatedEngineToZeroPerf_LosesClimbAuthorityAndSinksTowardMinClearance() + { + using var session = new ArenaSession(seed: 42, slot0Human: true); + var player = session.State.Contenders[0]; + IsolateContenders(session, player.Id); + + session.SetContenderPose(player.Id, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, Catalog.Hornet); + Assert.True(session.TrySwapNearbyChassis(0)); + + // Establish steady 20m hover + player.TargetHoverAltAgl = 20f; + session.SetContenderPose(player.Id, 0f, 0f, 0f); + for (int t = 0; t < 45; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 30f, false, false, false)); + session.Step(); + } + float hoverAglBefore = (player.Y - player.Grid.Spec.HalfHeight) - session.State.Terrain.SampleHeight(player.X, player.Z); + Assert.InRange(hoverAglBefore, 17.5f, 22.5f); + + // Overheat engine to Performance == 0.00 continuously during sink check + for (int t = 0; t < 150; t++) + { + player.Grid.InjectHardpointHeat("hp.engine.core", 15000f); + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 30f, false, false, false, VerticalThrottle: 1f)); + session.Step(); + } + + float hoverAglAfter = (player.Y - player.Grid.Spec.HalfHeight) - session.State.Terrain.SampleHeight(player.X, player.Z); + Assert.Equal(0f, player.Grid.ComputeEngineThermalPerformance(), precision: 2); + Assert.True(hoverAglAfter < hoverAglBefore - 5f, + $"Expected overheated VTOL (enginePerf=0.00) to sink from {hoverAglBefore:F2}m, got {hoverAglAfter:F2}m"); + Assert.True(hoverAglAfter >= 0.5f, $"Overheated sink went underground: {hoverAglAfter:F2}m"); + } + + [Fact] + public void StrippedZeroArmorHardpoint_DisablesManualFireAndAutoPointDefense() + { + // 1. Manual FireMountedWeapons disabled when hardpoint armor == 0 + using (var session = new ArenaSession(seed: 42, slot0Human: true)) + { + var player = session.State.Contenders[0]; + var target = session.State.Contenders[1]; + IsolateContenders(session, player.Id, target.Id); + + session.SetContenderPose(player.Id, 0f, 0f, 0f); + session.SetContenderPose(target.Id, 0f, 30f, MathF.PI); + target.Grid.Mounted.RemoveAll(m => m.Spec.Kind == HardpointKind.Weapon); + float targetArmorBefore = target.Grid.TotalArmorRatio(); + + var roofHp = player.Grid.FindHardpoint("hp.weapon.roof"); + Assert.NotNull(roofHp); + Assert.True(player.Grid.IsHardpointOperational(roofHp!)); + + // Strip all armor cells under hp.weapon.roof to 0 + for (int dy = 0; dy < roofHp!.Height; dy++) + { + for (int dx = 0; dx < roofHp.Width; dx++) + { + player.Grid.Armor[roofHp.X + dx, roofHp.Y + dy] = 0f; + } + } + Assert.False(player.Grid.IsHardpointOperational(roofHp)); + + int tracersFired = 0; + for (int t = 0; t < 20; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, target.X, target.Z, Fire: true, InteractPickup: false, Brake: true, AimWorldY: target.Y)); + session.Step(); + tracersFired += session.State.Tracers.Count(tr => + MathF.Abs(tr.StartX - player.X) < 10f && MathF.Abs(tr.StartZ - player.Z) < 10f); + } + + Assert.Equal(0, tracersFired); + Assert.Equal(targetArmorBefore, target.Grid.TotalArmorRatio()); + Assert.True(player.DisabledWeaponCount > 0); + Assert.All(player.Grid.Mounted.Where(m => m.Spec.Kind == HardpointKind.Weapon), w => Assert.Equal(0f, w.Cooldown)); + } + + // 2. Auto-PD TryAutoPointDefenseFire disabled when PD hardpoint armor == 0 + using (var session = new ArenaSession(seed: 42, slot0Human: true)) + { + var player = session.State.Contenders[0]; + var overheadVtol = session.State.Contenders[1]; + IsolateContenders(session, player.Id, overheadVtol.Id); + + session.SetContenderPose(player.Id, 0f, 0f, 0f); + Assert.True(player.Grid.TryMount(Catalog.PointDefenseFlak, "hp.weapon.roof")); + var roofHp = player.Grid.FindHardpoint("hp.weapon.roof")!; + for (int dy = 0; dy < roofHp.Height; dy++) + { + for (int dx = 0; dx < roofHp.Width; dx++) + { + player.Grid.Armor[roofHp.X + dx, roofHp.Y + dy] = 0f; + } + } + Assert.False(player.Grid.IsHardpointOperational(roofHp)); + + session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); + session.State.SpawnChassisDrop(20f, 25f, Catalog.Hornet); + Assert.True(session.State.TrySwapNearbyChassis(overheadVtol.Id)); + overheadVtol.Grid.Mounted.RemoveAll(m => m.Spec.Kind == HardpointKind.Weapon); + overheadVtol.AiScavengeCooldown = 999f; + overheadVtol.TargetHoverAltAgl = 28f; + session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); + + float vtolArmorBefore = overheadVtol.Grid.TotalArmorRatio(); + int pdTracers = 0; + for (int t = 0; t < 45; t++) + { + overheadVtol.TargetHoverAltAgl = 28f; + session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, -50f, Fire: false, InteractPickup: false, Brake: true)); + session.Step(); + pdTracers += session.State.Tracers.Count(tr => + MathF.Abs(tr.StartX - player.X) < 10f && MathF.Abs(tr.StartZ - player.Z) < 10f); + } + + Assert.Equal(0, pdTracers); + Assert.Equal(vtolArmorBefore, overheadVtol.Grid.TotalArmorRatio()); + } + } + + [Fact] + public void SwapChassis_VtolToGroundToVtol_ResetsTargetHoverAltAgl() + { + using var session = new ArenaSession(seed: 42, slot0Human: true); + var player = session.State.Contenders[0]; + IsolateContenders(session, player.Id); + + session.SetContenderPose(player.Id, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, Catalog.Hornet); + Assert.True(session.TrySwapNearbyChassis(0)); + Assert.Equal(10f, player.TargetHoverAltAgl); + + player.TargetHoverAltAgl = 42f; + player.VerticalThrottleCmd = 1f; + + // Swap to ground rig + session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Jackal); + Assert.True(session.TrySwapNearbyChassis(0)); + Assert.Equal(3.0f, player.TargetHoverAltAgl); + Assert.Equal(0f, player.VerticalThrottleCmd); + + // Swap back to VTOL -> must spawn cleanly at 10m hover, NOT stale 42m + session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Condor); + Assert.True(session.TrySwapNearbyChassis(0)); + Assert.Equal(10.0f, player.TargetHoverAltAgl); + Assert.Equal(0f, player.VerticalThrottleCmd); + float gh = session.State.Terrain.SampleHeight(player.X, player.Z); + float agl = (player.Y - player.Grid.Spec.HalfHeight) - gh; + Assert.InRange(agl, 9.5f, 10.5f); + } + + [Fact] + public void InteractPickup_UsesUnifiedNearestDropPriority_ChassisCloserThanModule() + { + var state = new MatchState(seed: 42, skipInitialDrop: true); + var player = state.Contenders[0]; + player.IsHuman = true; + + // Remove pre-scattered drops near player to keep test deterministic + state.GroundDrops.Clear(); + + var modDrop = state.SpawnModuleDrop(player.X + 3.0f, player.Z, Catalog.Flak); + var chassisDrop = state.SpawnChassisDrop(player.X + 0.5f, player.Z, Catalog.Anvil); + + var nearest = state.FindNearestInteractableDrop(0); + Assert.Same(chassisDrop, nearest); + + MatchRules.ApplyHumanInput(state, 0, new PlayerInput( + 0f, 0f, player.X, player.Z + 10f, + Fire: false, + InteractPickup: true, + Brake: false)); + + Assert.Equal(Catalog.Anvil.Id, player.Grid.Spec.Id); + Assert.True(chassisDrop.PickedUp); + Assert.False(modDrop.PickedUp); + } + } +} diff --git a/tools/VehiclePacker/Program.cs b/tools/VehiclePacker/Program.cs new file mode 100644 index 0000000..7e0d6af --- /dev/null +++ b/tools/VehiclePacker/Program.cs @@ -0,0 +1,924 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Numerics; +using System.Text; +using System.Text.Json; +using RustToDust.Core; + +namespace VehiclePacker +{ + internal sealed record HardpointTune( + float ArmorBonus, + float MinPitchDeg = -15f, + float MaxPitchDeg = 45f, + bool IsWideArc = false); + + internal sealed record VehicleTuning( + MobilityKind Mobility, + float MassKg, + float MaxSpeed, + float TurnRate, + float ThrustNewtons, + float HoverMaxAltitudeM, + float ArmorPerCell, + float Conductivity, + float BaseCellThermalMass, + int CargoCapacity, + Dictionary DefaultLoadout, + Dictionary HardpointTuning); + + internal static class Program + { + private static readonly Dictionary Tunings = BuildTunings(); + + private static int Main(string[] args) + { + string vehiclesRoot = args.Length > 0 + ? Path.GetFullPath(args[0]) + : LocateDefaultVehiclesRoot(); + + if (!Directory.Exists(vehiclesRoot)) + { + Console.Error.WriteLine($"Vehicles directory not found: {vehiclesRoot}"); + return 1; + } + + int packedCount = 0; + foreach (string dir in Directory.GetDirectories(vehiclesRoot).OrderBy(d => d, StringComparer.Ordinal)) + { + string id = Path.GetFileName(dir); + string manifestPath = Path.Combine(dir, "manifest.json"); + string glbPath = Path.Combine(dir, $"{id}.glb"); + if (!File.Exists(manifestPath) || !File.Exists(glbPath)) + { + continue; + } + + if (!Tunings.TryGetValue(id, out var tuning)) + { + Console.Error.WriteLine($"Missing gameplay tuning entry for vehicle '{id}'."); + return 2; + } + + var pkg = BuildPackage(id, manifestPath, glbPath, tuning); + string outPath = Path.Combine(dir, "vehicle.cc"); + VehiclePackageStore.Write(outPath, pkg); + var roundTrip = VehiclePackageStore.Read(outPath); + + Console.WriteLine( + $"Packed {roundTrip.Id,-10} | {roundTrip.Mobility,-7} | {roundTrip.Plane,-7} | " + + $"{roundTrip.GridWidth}x{roundTrip.GridHeight} | arm={roundTrip.ArmorPerCell,2:F0} | " + + $"hps={roundTrip.Hardpoints.Count} | joints={roundTrip.Joints.Count,2} | " + + $"partCells={roundTrip.PartCells.Count,3} | {new FileInfo(outPath).Length / 1024.0:F1} KiB"); + packedCount++; + } + + Console.WriteLine($"Done: packed {packedCount} vehicle.cc archives."); + return packedCount == 15 ? 0 : 3; + } + + private static string LocateDefaultVehiclesRoot() + { + foreach (string start in new[] { Directory.GetCurrentDirectory(), AppContext.BaseDirectory }) + { + var dir = new DirectoryInfo(Path.GetFullPath(start)); + while (dir is not null) + { + string candidate = Path.Combine(dir.FullName, "assets", "vehicles"); + if (Directory.Exists(candidate)) + { + return candidate; + } + dir = dir.Parent; + } + } + throw new DirectoryNotFoundException("Could not locate assets/vehicles directory."); + } + + private static VehiclePackage BuildPackage(string id, string manifestPath, string glbPath, VehicleTuning tuning) + { + using var manifestDoc = JsonDocument.Parse(File.ReadAllText(manifestPath, Encoding.UTF8)); + var root = manifestDoc.RootElement; + + string manifestId = root.GetProperty("id").GetString()!; + if (!string.Equals(manifestId, id, StringComparison.Ordinal)) + { + throw new InvalidOperationException($"{manifestPath}: id '{manifestId}' != directory '{id}'."); + } + + string name = root.GetProperty("name").GetString()!; + string vClass = root.GetProperty("class").GetString()!; + var plane = Enum.Parse(root.GetProperty("plane").GetString()!, ignoreCase: true); + int gw = root.GetProperty("gridWidth").GetInt32(); + int gh = root.GetProperty("gridHeight").GetInt32(); + + var maskBools = root.GetProperty("mask").EnumerateArray().Select(e => e.GetBoolean()).ToArray(); + if (maskBools.Length != gw * gh) + { + throw new InvalidOperationException($"{id}: mask length {maskBools.Length} != {gw * gh}."); + } + + var maskRows = new string[gh]; + for (int y = 0; y < gh; y++) + { + var sb = new StringBuilder(gw); + for (int x = 0; x < gw; x++) + { + sb.Append(maskBools[y * gw + x] ? '#' : '.'); + } + maskRows[y] = sb.ToString(); + } + + var boundsSize = root.GetProperty("bounds").GetProperty("size").EnumerateArray().Select(e => e.GetSingle()).ToArray(); + var boundsMin = root.GetProperty("bounds").GetProperty("min").EnumerateArray().Select(e => e.GetSingle()).ToArray(); + var boundsMax = root.GetProperty("bounds").GetProperty("max").EnumerateArray().Select(e => e.GetSingle()).ToArray(); + + var (gltfJsonBytes, binBlob) = ReadGlbChunks(glbPath); + using var gltfDoc = JsonDocument.Parse(gltfJsonBytes); + var gltf = gltfDoc.RootElement; + + var hardpoints = ParseHardpoints(id, root.GetProperty("hardpoints"), gltf, tuning); + var joints = ParseJoints(id, root.GetProperty("joints"), gltf); + var mechanisms = root.TryGetProperty("mechanisms", out var mechElem) && mechElem.ValueKind == JsonValueKind.Object + ? ParseMechanisms(mechElem) + : null; + var partCells = ComputePartCells(gltf, binBlob, plane, gw, gh, maskBools, boundsMin, boundsMax); + + return new VehiclePackage + { + Id = id, + Name = name, + VehicleClass = vClass, + Mobility = tuning.Mobility, + Plane = plane, + GridWidth = gw, + GridHeight = gh, + Mask = maskRows, + MassKg = tuning.MassKg, + MaxSpeed = tuning.MaxSpeed, + TurnRate = tuning.TurnRate, + ThrustNewtons = tuning.ThrustNewtons, + HoverMaxAltitudeM = tuning.HoverMaxAltitudeM, + ArmorPerCell = tuning.ArmorPerCell, + Conductivity = tuning.Conductivity, + BaseCellThermalMass = tuning.BaseCellThermalMass, + CargoCapacity = tuning.CargoCapacity, + HalfWidth = boundsSize[0] * 0.5f, + HalfHeight = boundsSize[1] * 0.5f, + HalfLength = boundsSize[2] * 0.5f, + ModelAsset = $"{id}.glb", + DefaultLoadout = new Dictionary(tuning.DefaultLoadout, StringComparer.Ordinal), + Hardpoints = hardpoints, + Joints = joints, + Mechanisms = mechanisms, + PartCells = partCells + }; + } + + private static List ParseHardpoints( + string vehicleId, + JsonElement hpsElem, + JsonElement gltf, + VehicleTuning tuning) + { + var rtdAnchors = new HashSet(StringComparer.Ordinal); + if (gltf.TryGetProperty("nodes", out var nodes)) + { + foreach (var n in nodes.EnumerateArray()) + { + if (n.TryGetProperty("extras", out var ex) && + ex.TryGetProperty("rtd.id", out var rtdId) && + rtdId.ValueKind == JsonValueKind.String) + { + rtdAnchors.Add(rtdId.GetString()!); + } + } + } + + var list = new List(); + foreach (var hp in hpsElem.EnumerateArray()) + { + string hpId = hp.GetProperty("id").GetString()!; + string modelNodeId = hp.GetProperty("modelNodeId").GetString()!; + if (!rtdAnchors.Contains(modelNodeId)) + { + throw new InvalidOperationException($"{vehicleId}: GLB missing extras[\"rtd.id\"] == '{modelNodeId}'."); + } + + var kind = Enum.Parse(hp.GetProperty("kind").GetString()!, ignoreCase: true); + int x = hp.GetProperty("x").GetInt32(); + int y = hp.GetProperty("y").GetInt32(); + int w = hp.GetProperty("w").GetInt32(); + int h = hp.GetProperty("h").GetInt32(); + + HardpointTune tune = tuning.HardpointTuning.TryGetValue(hpId, out var found) + ? found + : new HardpointTune(ArmorBonus: kind == HardpointKind.Armor ? 14f : (kind == HardpointKind.Engine ? 8f : 6f)); + + list.Add(new VehicleHardpointRecord + { + Id = hpId, + AnchorId = modelNodeId, + Kind = kind, + X = x, + Y = y, + W = w, + H = h, + MinPitchDeg = tune.MinPitchDeg, + MaxPitchDeg = tune.MaxPitchDeg, + IsWideArc = tune.IsWideArc, + ArmorBonus = tune.ArmorBonus + }); + } + return list; + } + + private static List ParseJoints(string vehicleId, JsonElement jointsElem, JsonElement gltf) + { + var nodeByJointId = new Dictionary(StringComparer.Ordinal); + if (gltf.TryGetProperty("nodes", out var nodes)) + { + foreach (var n in nodes.EnumerateArray()) + { + if (n.TryGetProperty("extras", out var ex) && + ex.TryGetProperty("rtd.joint", out var rtdJoint) && + rtdJoint.ValueKind == JsonValueKind.String) + { + string jid = rtdJoint.GetString()!; + string nodeName = n.TryGetProperty("name", out var nm) ? nm.GetString() ?? jid : jid; + nodeByJointId[jid] = nodeName; + } + } + } + + var list = new List(); + foreach (var j in jointsElem.EnumerateArray()) + { + string jid = j.GetProperty("id").GetString()!; + if (!nodeByJointId.TryGetValue(jid, out var nodeName)) + { + throw new InvalidOperationException($"{vehicleId}: GLB missing extras[\"rtd.joint\"] == '{jid}'."); + } + + list.Add(new VehicleJointRecord + { + Id = jid, + NodeName = nodeName, + Axis = j.GetProperty("axis").EnumerateArray().Select(e => e.GetSingle()).ToArray(), + MinVal = j.GetProperty("min").GetSingle(), + MaxVal = j.GetProperty("max").GetSingle() + }); + } + return list; + } + + private static VehicleMechanismsRecord ParseMechanisms(JsonElement mechElem) + { + var rec = new VehicleMechanismsRecord + { + Frame = mechElem.GetProperty("frame").GetString() ?? string.Empty, + RootOrigin = mechElem.GetProperty("rootOrigin").EnumerateArray().Select(e => e.GetSingle()).ToArray() + }; + + if (mechElem.TryGetProperty("dofs", out var dofsElem)) + { + foreach (var d in dofsElem.EnumerateArray()) + { + float? damp = null; + float? hz = null; + if (d.TryGetProperty("compliance", out var comp) && comp.ValueKind == JsonValueKind.Object) + { + if (comp.TryGetProperty("damping_ratio", out var dr)) damp = dr.GetSingle(); + if (comp.TryGetProperty("hertz", out var h)) hz = h.GetSingle(); + } + rec.Dofs.Add(new MechanismDofRecord + { + Name = d.GetProperty("name").GetString()!, + Parent = d.GetProperty("parent").GetInt32(), + Kind = d.GetProperty("kind").GetString()!, + Mechanism = d.TryGetProperty("mechanism", out var m) && m.ValueKind == JsonValueKind.String ? m.GetString() : null, + Side = d.TryGetProperty("side", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString() : null, + Origin = d.GetProperty("origin").EnumerateArray().Select(e => e.GetSingle()).ToArray(), + Axis = d.GetProperty("axis").EnumerateArray().Select(e => e.GetSingle()).ToArray(), + Lo = d.GetProperty("lo").GetSingle(), + Hi = d.GetProperty("hi").GetSingle(), + Depth = d.GetProperty("depth").GetInt32(), + StoppedBy = d.TryGetProperty("stopped_by", out var sb) && sb.ValueKind == JsonValueKind.String ? sb.GetString() : null, + ComplianceDampingRatio = damp, + ComplianceHertz = hz + }); + } + } + + if (mechElem.TryGetProperty("rams", out var ramsElem)) + { + foreach (var r in ramsElem.EnumerateArray()) + { + rec.Rams.Add(new MechanismRamRecord + { + Name = r.GetProperty("name").GetString()!, + BarrelBone = r.GetProperty("barrel_bone").GetString()!, + RodBone = r.GetProperty("rod_bone").GetString()!, + Spans = r.TryGetProperty("spans", out var sp) ? sp.EnumerateArray().Select(e => e.GetString()!).ToArray() : Array.Empty(), + Bore = r.TryGetProperty("bore", out var br) && br.ValueKind == JsonValueKind.Number ? br.GetSingle() : 0f, + Body = r.TryGetProperty("body", out var bd) && bd.ValueKind == JsonValueKind.Number ? bd.GetSingle() : 0f, + Inner = r.TryGetProperty("inner", out var inn) && inn.ValueKind == JsonValueKind.Number ? inn.GetSingle() : 0f, + Extension = r.TryGetProperty("extension", out var ext) && ext.ValueKind == JsonValueKind.Number ? ext.GetSingle() : 0f, + Rest = r.TryGetProperty("rest", out var rst) && rst.ValueKind == JsonValueKind.Number ? rst.GetSingle() : 0f, + Stroke = r.TryGetProperty("stroke", out var st) && st.ValueKind == JsonValueKind.Array ? st.EnumerateArray().Select(e => e.GetSingle()).ToArray() : Array.Empty(), + AParentDof = r.TryGetProperty("a_parent_dof", out var apd) && apd.ValueKind == JsonValueKind.Number ? apd.GetInt32() : null, + APos = r.TryGetProperty("a_pos", out var ap) && ap.ValueKind == JsonValueKind.Array ? ap.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null, + BParentDof = r.TryGetProperty("b_parent_dof", out var bpd) && bpd.ValueKind == JsonValueKind.Number ? bpd.GetInt32() : null, + BPos = r.TryGetProperty("b_pos", out var bp) && bp.ValueKind == JsonValueKind.Array ? bp.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null, + PinDir = r.TryGetProperty("pin_dir", out var pd) && pd.ValueKind == JsonValueKind.Array ? pd.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null + }); + } + } + + if (mechElem.TryGetProperty("scissors", out var scissorsElem)) + { + foreach (var sc in scissorsElem.EnumerateArray()) + { + rec.Scissors.Add(new MechanismScissorRecord + { + Name = sc.GetProperty("name").GetString()!, + UpperBone = sc.GetProperty("upper_bone").GetString()!, + LowerBone = sc.GetProperty("lower_bone").GetString()!, + Arm = sc.TryGetProperty("arm", out var arm) && arm.ValueKind == JsonValueKind.Number ? arm.GetSingle() : 0f, + AParentDof = sc.TryGetProperty("a_parent_dof", out var apd) && apd.ValueKind == JsonValueKind.Number ? apd.GetInt32() : null, + APos = sc.TryGetProperty("a_pos", out var ap) && ap.ValueKind == JsonValueKind.Array ? ap.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null, + BParentDof = sc.TryGetProperty("b_parent_dof", out var bpd) && bpd.ValueKind == JsonValueKind.Number ? bpd.GetInt32() : null, + BPos = sc.TryGetProperty("b_pos", out var bp) && bp.ValueKind == JsonValueKind.Array ? bp.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null, + OutDir = sc.TryGetProperty("out_dir", out var od) && od.ValueKind == JsonValueKind.Array ? od.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null + }); + } + } + + if (mechElem.TryGetProperty("struts", out var strutsElem)) + { + foreach (var st in strutsElem.EnumerateArray()) + { + rec.Struts.Add(new MechanismStrutRecord + { + Name = st.GetProperty("name").GetString()!, + Side = st.TryGetProperty("side", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString() : null, + Dof = st.GetProperty("dof").GetString()!, + Travel = st.GetProperty("travel").GetSingle(), + Hertz = st.GetProperty("hertz").GetSingle(), + DampingRatio = st.GetProperty("damping_ratio").GetSingle() + }); + } + } + + return rec; + } + + private static (byte[] JsonBytes, byte[] BinBytes) ReadGlbChunks(string glbPath) + { + byte[] data = File.ReadAllBytes(glbPath); + if (data.Length < 20) throw new InvalidDataException($"{glbPath}: GLB too small."); + + uint magic = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(0, 4)); + uint version = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(4, 4)); + if (magic != 0x46546C67 || version != 2) + throw new InvalidDataException($"{glbPath}: invalid GLB header."); + + uint jsonLen = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(12, 4)); + uint jsonType = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(16, 4)); + if (jsonType != 0x4E4F534A) + throw new InvalidDataException($"{glbPath}: first chunk is not JSON."); + + byte[] jsonBytes = data.AsSpan(20, (int)jsonLen).ToArray(); + byte[] binBytes = Array.Empty(); + int binOff = 20 + (int)jsonLen; + if (binOff + 8 <= data.Length) + { + uint binLen = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(binOff, 4)); + uint binType = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(binOff + 4, 4)); + if (binType == 0x004E4942) + { + binBytes = data.AsSpan(binOff + 8, (int)binLen).ToArray(); + } + } + return (jsonBytes, binBytes); + } + + private static List ComputePartCells( + JsonElement gltf, + byte[] binBlob, + GridPlane plane, + int gw, + int gh, + bool[] mask, + float[] boundsMin, + float[] boundsMax) + { + var nodes = gltf.GetProperty("nodes").EnumerateArray().ToArray(); + var meshes = gltf.GetProperty("meshes").EnumerateArray().ToArray(); + var accessors = gltf.GetProperty("accessors").EnumerateArray().ToArray(); + var bufferViews = gltf.GetProperty("bufferViews").EnumerateArray().ToArray(); + + var parentOf = new Dictionary(); + for (int i = 0; i < nodes.Length; i++) + { + if (nodes[i].TryGetProperty("children", out var ch)) + { + foreach (var c in ch.EnumerateArray()) + { + parentOf[c.GetInt32()] = i; + } + } + } + + // Exclude hardpoint slot_frame.* subtrees and rtd.id anchor subtrees + var hpNodeSet = new HashSet(); + void MarkSubtree(int idx) + { + if (!hpNodeSet.Add(idx)) return; + if (nodes[idx].TryGetProperty("children", out var ch)) + { + foreach (var c in ch.EnumerateArray()) + { + MarkSubtree(c.GetInt32()); + } + } + } + + for (int i = 0; i < nodes.Length; i++) + { + string nodeName = nodes[i].TryGetProperty("name", out var nm) ? nm.GetString() ?? "" : ""; + bool isSlotFrame = nodeName.StartsWith("slot_frame.", StringComparison.Ordinal); + bool hasRtdId = nodes[i].TryGetProperty("extras", out var ex) && ex.TryGetProperty("rtd.id", out _); + if (isSlotFrame || hasRtdId) + { + if (parentOf.TryGetValue(i, out int p) && + nodes[p].TryGetProperty("name", out var pnm) && + (pnm.GetString() ?? "").StartsWith("slot_frame.", StringComparison.Ordinal)) + { + MarkSubtree(p); + } + else + { + MarkSubtree(i); + } + } + } + + var rootIndices = new List(); + if (gltf.TryGetProperty("scenes", out var scenes) && scenes.GetArrayLength() > 0) + { + int sceneIdx = gltf.TryGetProperty("scene", out var si) ? si.GetInt32() : 0; + foreach (var r in scenes[sceneIdx].GetProperty("nodes").EnumerateArray()) + { + rootIndices.Add(r.GetInt32()); + } + } + else + { + for (int i = 0; i < nodes.Length; i++) + { + if (!parentOf.ContainsKey(i)) rootIndices.Add(i); + } + } + + float spanX = MathF.Max(1e-4f, boundsMax[0] - boundsMin[0]); + float spanY = MathF.Max(1e-4f, boundsMax[1] - boundsMin[1]); + float spanZ = MathF.Max(1e-4f, boundsMax[2] - boundsMin[2]); + + var results = new List(); + var visited = new HashSet(); + + void Walk(int nodeIdx, Matrix4x4 parentWorld) + { + if (!visited.Add(nodeIdx)) return; + var node = nodes[nodeIdx]; + Matrix4x4 local = ReadNodeLocalMatrix(node); + // Column-vector math: world = parentWorld * local; System.Numerics uses row-vectors for Transform, so multiply in reverse order + Matrix4x4 world = local * parentWorld; + + if (!hpNodeSet.Contains(nodeIdx) && node.TryGetProperty("mesh", out var meshProp)) + { + int meshIdx = meshProp.GetInt32(); + Vector3 centroid = ComputeMeshWorldCentroid(meshes[meshIdx], accessors, bufferViews, binBlob, world); + + // +X is vehicle LEFT (cell x=0), -X is vehicle RIGHT (cell x=gw-1) + float ux = Math.Clamp((boundsMax[0] - centroid.X) / spanX, 0f, 1f); + // Dorsal: +Z is FRONT (cell y=0), -Z is REAR (cell y=gh-1) + // Coronal: +Y is TOP (cell y=0), minY is FEET (cell y=gh-1) + float uy = plane == GridPlane.Dorsal + ? Math.Clamp((boundsMax[2] - centroid.Z) / spanZ, 0f, 1f) + : Math.Clamp((boundsMax[1] - centroid.Y) / spanY, 0f, 1f); + + float targetX = ux * (gw - 1); + float targetY = uy * (gh - 1); + (int cellX, int cellY) = FindNearestActiveCell(targetX, targetY, gw, gh, mask); + + string nodeName = node.TryGetProperty("name", out var nm) ? nm.GetString() ?? $"node_{nodeIdx}" : $"node_{nodeIdx}"; + string partKind = ClassifyPartKind(nodeName); + + results.Add(new VehiclePartCellRecord + { + NodeName = nodeName, + CellX = cellX, + CellY = cellY, + Kind = partKind + }); + } + + if (node.TryGetProperty("children", out var ch)) + { + foreach (var c in ch.EnumerateArray()) + { + Walk(c.GetInt32(), world); + } + } + } + + foreach (int r in rootIndices) + { + Walk(r, Matrix4x4.Identity); + } + + return results; + } + + private static Matrix4x4 ReadNodeLocalMatrix(JsonElement node) + { + if (node.TryGetProperty("matrix", out var mElem)) + { + float[] m = mElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); + // glTF stores column-major 4x4; System.Numerics Matrix4x4 fields M11..M44 match row-major so transpose on construction + return new Matrix4x4( + m[0], m[1], m[2], m[3], + m[4], m[5], m[6], m[7], + m[8], m[9], m[10], m[11], + m[12], m[13], m[14], m[15]); + } + + Vector3 scale = Vector3.One; + if (node.TryGetProperty("scale", out var sElem)) + { + float[] s = sElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); + scale = new Vector3(s[0], s[1], s[2]); + } + + Quaternion rot = Quaternion.Identity; + if (node.TryGetProperty("rotation", out var rElem)) + { + float[] r = rElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); + rot = new Quaternion(r[0], r[1], r[2], r[3]); + } + + Vector3 trans = Vector3.Zero; + if (node.TryGetProperty("translation", out var tElem)) + { + float[] t = tElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); + trans = new Vector3(t[0], t[1], t[2]); + } + + return Matrix4x4.CreateScale(scale) * Matrix4x4.CreateFromQuaternion(rot) * Matrix4x4.CreateTranslation(trans); + } + + private static Vector3 ComputeMeshWorldCentroid( + JsonElement mesh, + JsonElement[] accessors, + JsonElement[] bufferViews, + byte[] binBlob, + Matrix4x4 world) + { + Vector3 sum = Vector3.Zero; + long count = 0; + + foreach (var prim in mesh.GetProperty("primitives").EnumerateArray()) + { + if (!prim.TryGetProperty("attributes", out var attrs) || + !attrs.TryGetProperty("POSITION", out var posIdxElem)) + { + continue; + } + + var acc = accessors[posIdxElem.GetInt32()]; + int accCount = acc.GetProperty("count").GetInt32(); + int compType = acc.GetProperty("componentType").GetInt32(); + string accType = acc.GetProperty("type").GetString() ?? ""; + + if (binBlob.Length > 0 && + acc.TryGetProperty("bufferView", out var bvIdxElem) && + compType == 5126 && + accType == "VEC3") + { + var bv = bufferViews[bvIdxElem.GetInt32()]; + int bvOff = bv.TryGetProperty("byteOffset", out var bo) ? bo.GetInt32() : 0; + int accOff = acc.TryGetProperty("byteOffset", out var ao) ? ao.GetInt32() : 0; + int stride = bv.TryGetProperty("byteStride", out var bs) ? bs.GetInt32() : 12; + int offset = bvOff + accOff; + + for (int i = 0; i < accCount; i++) + { + int p = offset + i * stride; + float x = BinaryPrimitives.ReadSingleLittleEndian(binBlob.AsSpan(p, 4)); + float y = BinaryPrimitives.ReadSingleLittleEndian(binBlob.AsSpan(p + 4, 4)); + float z = BinaryPrimitives.ReadSingleLittleEndian(binBlob.AsSpan(p + 8, 4)); + sum += Vector3.Transform(new Vector3(x, y, z), world); + count++; + } + } + else if (acc.TryGetProperty("min", out var minElem) && acc.TryGetProperty("max", out var maxElem)) + { + float[] mn = minElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); + float[] mx = maxElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); + var mid = new Vector3((mn[0] + mx[0]) * 0.5f, (mn[1] + mx[1]) * 0.5f, (mn[2] + mx[2]) * 0.5f); + sum += Vector3.Transform(mid, world); + count++; + } + } + + return count > 0 ? sum / count : world.Translation; + } + + private static (int X, int Y) FindNearestActiveCell(float targetX, float targetY, int gw, int gh, bool[] mask) + { + int bestX = 0; + int bestY = 0; + float bestDistSq = float.PositiveInfinity; + for (int y = 0; y < gh; y++) + { + for (int x = 0; x < gw; x++) + { + if (!mask[y * gw + x]) continue; + float dx = x - targetX; + float dy = y - targetY; + float d2 = dx * dx + dy * dy; + if (d2 < bestDistSq) + { + bestDistSq = d2; + bestX = x; + bestY = y; + } + } + } + return (bestX, bestY); + } + + private static string ClassifyPartKind(string nodeName) + { + string lower = nodeName.ToLowerInvariant(); + if (lower.StartsWith("shroud.", StringComparison.Ordinal) || lower.Contains("shroud")) + return "shroud"; + if (lower.Contains("armor") || lower.Contains("plate") || lower.Contains("glacis") || + lower.Contains("skirt") || lower.Contains("shield") || lower.Contains("fender") || + lower.Contains("bullbar") || lower.Contains("bumper") || lower.Contains("collar") || + lower.Contains("cheek") || lower.Contains("cowling") || lower.Contains("greave")) + return "armor"; + if (lower.Contains("wheel") || lower.Contains("tire") || lower.Contains("track") || + lower.Contains("rotor") || lower.Contains("blade") || lower.Contains("spinner") || + lower.Contains("nacelle")) + return "mobility"; + return "hull"; + } + + private static Dictionary BuildTunings() + { + return new Dictionary(StringComparer.Ordinal) + { + ["jackal"] = new( + Mobility: MobilityKind.Wheeled, + MassKg: 950f, MaxSpeed: 34f, TurnRate: 4.2f, ThrustNewtons: 14500f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 24f, Conductivity: 8.0f, BaseCellThermalMass: 10f, CargoCapacity: 4, + DefaultLoadout: new() { ["hp.weapon.roof"] = "mg_762", ["hp.engine.rear"] = "diesel_core", ["hp.radiator.rear"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.weapon.roof"] = new(5f, -15f, 45f), + ["hp.engine.rear"] = new(5f), + ["hp.radiator.rear"] = new(0f) + }), + + ["mule"] = new( + Mobility: MobilityKind.Wheeled, + MassKg: 1850f, MaxSpeed: 29f, TurnRate: 3.3f, ThrustNewtons: 23500f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 34f, Conductivity: 8.5f, BaseCellThermalMass: 13f, CargoCapacity: 6, + DefaultLoadout: new() { ["hp.weapon.cab"] = "mg_762", ["hp.weapon.bed_main"] = "autocannon", ["hp.engine.front"] = "turbo_core", ["hp.radiator.left"] = "copper_rad", ["hp.armor.front"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.armor.front"] = new(12f), + ["hp.radiator.left"] = new(0f), + ["hp.engine.front"] = new(6f), + ["hp.radiator.right"] = new(0f), + ["hp.weapon.cab"] = new(6f, -15f, 45f), + ["hp.weapon.bed_main"] = new(8f, -12f, 35f) + }), + + ["ferret"] = new( + Mobility: MobilityKind.Tracked, + MassKg: 1450f, MaxSpeed: 28f, TurnRate: 3.8f, ThrustNewtons: 21000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 32f, Conductivity: 8.5f, BaseCellThermalMass: 12f, CargoCapacity: 5, + DefaultLoadout: new() { ["hp.weapon.turret"] = "autocannon", ["hp.weapon.pod"] = "mg_762", ["hp.engine.rear"] = "diesel_core", ["hp.radiator.deck"] = "copper_rad", ["hp.armor.glacis"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.armor.glacis"] = new(14f), + ["hp.weapon.pod"] = new(6f, -15f, 45f), + ["hp.weapon.turret"] = new(10f, -10f, 32f), + ["hp.engine.rear"] = new(6f), + ["hp.radiator.deck"] = new(0f) + }), + + ["ironclad"] = new( + Mobility: MobilityKind.Tracked, + MassKg: 3600f, MaxSpeed: 22f, TurnRate: 2.4f, ThrustNewtons: 34000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 54f, Conductivity: 9.5f, BaseCellThermalMass: 17f, CargoCapacity: 8, + DefaultLoadout: new() { ["hp.weapon.main"] = "recoilless", ["hp.weapon.coax"] = "mg_762", ["hp.engine.rear"] = "turbo_core", ["hp.radiator.l"] = "copper_rad", ["hp.armor.front"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.armor.front"] = new(22f), + ["hp.weapon.coax"] = new(10f, -10f, 40f), + ["hp.weapon.main"] = new(18f, -10f, 30f), + ["hp.armor.skirts"] = new(14f), + ["hp.radiator.l"] = new(0f), + ["hp.engine.rear"] = new(10f), + ["hp.radiator.r"] = new(0f) + }), + + ["mammoth"] = new( + Mobility: MobilityKind.Wheeled, + MassKg: 3900f, MaxSpeed: 24f, TurnRate: 2.3f, ThrustNewtons: 37000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 52f, Conductivity: 9.5f, BaseCellThermalMass: 16f, CargoCapacity: 8, + DefaultLoadout: new() { ["hp.weapon.turret_l"] = "autocannon", ["hp.weapon.turret_r"] = "autocannon", ["hp.weapon.bow"] = "mg_762", ["hp.engine.rear"] = "turbo_core", ["hp.radiator.l"] = "copper_rad", ["hp.armor.glacis"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.armor.glacis"] = new(20f), + ["hp.weapon.bow"] = new(10f, -15f, 45f), + ["hp.weapon.turret_l"] = new(15f, -10f, 30f), + ["hp.weapon.turret_r"] = new(15f, -10f, 30f), + ["hp.armor.flanks"] = new(14f), + ["hp.engine.rear"] = new(10f), + ["hp.radiator.l"] = new(0f), + ["hp.radiator.r"] = new(0f) + }), + + ["anvil"] = new( + Mobility: MobilityKind.Tracked, + MassKg: 4800f, MaxSpeed: 19f, TurnRate: 2.0f, ThrustNewtons: 42000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 66f, Conductivity: 9.5f, BaseCellThermalMass: 19f, CargoCapacity: 9, + DefaultLoadout: new() { ["hp.weapon.siege_l"] = "autocannon", ["hp.weapon.siege_r"] = "autocannon", ["hp.weapon.sponson_l"] = "mg_762", ["hp.engine.rear"] = "turbo_core", ["hp.radiator.l"] = "copper_rad", ["hp.armor.front"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.armor.front"] = new(26f), + ["hp.weapon.sponson_l"] = new(14f, -10f, 30f), + ["hp.weapon.siege_l"] = new(18f, -10f, 30f), + ["hp.armor.sides"] = new(18f), + ["hp.weapon.siege_r"] = new(18f, -10f, 30f), + ["hp.weapon.sponson_r"] = new(14f, -10f, 30f), + ["hp.engine.rear"] = new(12f), + ["hp.radiator.l"] = new(0f), + ["hp.radiator.r"] = new(0f) + }), + + ["hornet"] = new( + Mobility: MobilityKind.Vtol, + MassKg: 820f, MaxSpeed: 42f, TurnRate: 4.8f, ThrustNewtons: 18500f, HoverMaxAltitudeM: 42f, + ArmorPerCell: 14f, Conductivity: 9.0f, BaseCellThermalMass: 9f, CargoCapacity: 4, + DefaultLoadout: new() { ["hp.weapon.chin"] = "autocannon", ["hp.weapon.wing_l"] = "mg_762", ["hp.weapon.wing_r"] = "mg_762", ["hp.engine.core"] = "turbo_core", ["hp.radiator.nacelle_l"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.weapon.chin"] = new(2f, -55f, 20f), + ["hp.radiator.nacelle_l"] = new(0f), + ["hp.radiator.nacelle_r"] = new(0f), + ["hp.weapon.wing_l"] = new(2f, -55f, 20f), + ["hp.engine.core"] = new(4f), + ["hp.weapon.wing_r"] = new(2f, -55f, 20f) + }), + + ["condor"] = new( + Mobility: MobilityKind.Vtol, + MassKg: 1950f, MaxSpeed: 35f, TurnRate: 3.6f, ThrustNewtons: 32000f, HoverMaxAltitudeM: 36f, + ArmorPerCell: 22f, Conductivity: 10.0f, BaseCellThermalMass: 12f, CargoCapacity: 7, + DefaultLoadout: new() { ["hp.weapon.sponson_l"] = "autocannon", ["hp.weapon.sponson_r"] = "autocannon", ["hp.weapon.nose"] = "mg_762", ["hp.weapon.dorsal"] = "pd_flak", ["hp.engine.core"] = "turbo_core", ["hp.radiator.spine_l"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.weapon.nose"] = new(4f, -55f, 20f), + ["hp.armor.hull"] = new(8f), + ["hp.weapon.sponson_l"] = new(4f, -55f, 20f), + ["hp.weapon.dorsal"] = new(4f, -10f, 85f, IsWideArc: true), + ["hp.weapon.sponson_r"] = new(4f, -55f, 20f), + ["hp.engine.core"] = new(6f), + ["hp.radiator.spine_l"] = new(0f), + ["hp.radiator.spine_r"] = new(0f) + }), + + ["manticore"] = new( + Mobility: MobilityKind.Walker, + MassKg: 2800f, MaxSpeed: 26f, TurnRate: 3.6f, ThrustNewtons: 34500f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 46f, Conductivity: 11.0f, BaseCellThermalMass: 15f, CargoCapacity: 7, + DefaultLoadout: new() { ["hp.weapon.chin"] = "flak", ["hp.weapon.l"] = "mg_762", ["hp.weapon.r"] = "mg_762", ["hp.engine.core"] = "turbo_core", ["hp.radiator.flank_l"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.weapon.chin"] = new(10f, -15f, 45f), + ["hp.radiator.flank_l"] = new(4f), + ["hp.engine.core"] = new(12f), + ["hp.radiator.flank_r"] = new(4f), + ["hp.weapon.l"] = new(8f, -15f, 45f), + ["hp.weapon.r"] = new(8f, -15f, 45f), + ["hp.armor.prow"] = new(18f) + }), + + ["bastion"] = new( + Mobility: MobilityKind.Walker, + MassKg: 4600f, MaxSpeed: 20f, TurnRate: 2.4f, ThrustNewtons: 46000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 64f, Conductivity: 11.5f, BaseCellThermalMass: 19f, CargoCapacity: 9, + DefaultLoadout: new() { ["hp.weapon.turret_main"] = "recoilless", ["hp.weapon.turret_pd"] = "pd_flak", ["hp.weapon.flank_l"] = "autocannon", ["hp.engine.core"] = "turbo_core", ["hp.radiator.rear_l"] = "copper_rad", ["hp.armor.prow"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.armor.prow"] = new(24f), + ["hp.weapon.turret_pd"] = new(10f, -10f, 85f, IsWideArc: true), + ["hp.weapon.turret_main"] = new(20f, -10f, 30f), + ["hp.weapon.flank_l"] = new(12f, -10f, 35f), + ["hp.weapon.flank_r"] = new(12f, -10f, 35f), + ["hp.engine.core"] = new(14f), + ["hp.radiator.rear_l"] = new(0f), + ["hp.radiator.rear_r"] = new(0f) + }), + + ["kestrel"] = new( + Mobility: MobilityKind.Walker, + MassKg: 1650f, MaxSpeed: 34f, TurnRate: 4.6f, ThrustNewtons: 27500f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 32f, Conductivity: 10.0f, BaseCellThermalMass: 12f, CargoCapacity: 5, + DefaultLoadout: new() { ["hp.weapon.arm_r"] = "autocannon", ["hp.weapon.dorsal"] = "mg_762", ["hp.engine.core"] = "turbo_core", ["hp.radiator.back"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.weapon.dorsal"] = new(8f, -10f, 85f, IsWideArc: true), + ["hp.armor.chest"] = new(14f), + ["hp.radiator.back"] = new(4f), + ["hp.engine.core"] = new(10f), + ["hp.weapon.arm_r"] = new(8f, -15f, 45f) + }), + + ["raptor"] = new( + Mobility: MobilityKind.Walker, + MassKg: 2300f, MaxSpeed: 30f, TurnRate: 4.1f, ThrustNewtons: 33000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 42f, Conductivity: 10.5f, BaseCellThermalMass: 14f, CargoCapacity: 6, + DefaultLoadout: new() { ["hp.weapon.arm_l"] = "autocannon", ["hp.weapon.arm_r"] = "flak", ["hp.engine.chest"] = "turbo_core", ["hp.radiator.sh_l"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.radiator.sh_l"] = new(4f), + ["hp.radiator.sh_r"] = new(4f), + ["hp.weapon.arm_l"] = new(8f, -15f, 45f), + ["hp.engine.chest"] = new(12f), + ["hp.weapon.arm_r"] = new(8f, -15f, 45f) + }), + + ["spectre"] = new( + Mobility: MobilityKind.Walker, + MassKg: 2450f, MaxSpeed: 31f, TurnRate: 4.2f, ThrustNewtons: 35000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 44f, Conductivity: 10.5f, BaseCellThermalMass: 14f, CargoCapacity: 6, + DefaultLoadout: new() { ["hp.weapon.arm_l"] = "autocannon", ["hp.weapon.arm_r"] = "autocannon", ["hp.weapon.shoulder_l"] = "pd_flak", ["hp.engine.core"] = "turbo_core", ["hp.radiator.back_l"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.weapon.shoulder_l"] = new(8f, -10f, 85f, IsWideArc: true), + ["hp.armor.torso"] = new(16f), + ["hp.weapon.arm_l"] = new(10f, -15f, 45f), + ["hp.radiator.back_l"] = new(4f), + ["hp.engine.core"] = new(12f), + ["hp.radiator.back_r"] = new(4f), + ["hp.weapon.arm_r"] = new(10f, -15f, 45f) + }), + + ["breaker"] = new( + Mobility: MobilityKind.Walker, + MassKg: 3800f, MaxSpeed: 24f, TurnRate: 3.0f, ThrustNewtons: 41000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 56f, Conductivity: 11.0f, BaseCellThermalMass: 17f, CargoCapacity: 8, + DefaultLoadout: new() { ["hp.weapon.arm_l"] = "autocannon", ["hp.weapon.arm_r"] = "autocannon", ["hp.weapon.shoulder_l"] = "mg_762", ["hp.engine.chest"] = "turbo_core", ["hp.radiator.back_l"] = "copper_rad", ["hp.armor.torso"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.weapon.arm_l"] = new(12f, -15f, 45f), + ["hp.weapon.arm_r"] = new(12f, -15f, 45f), + ["hp.weapon.shoulder_l"] = new(10f, -10f, 85f, IsWideArc: true), + ["hp.armor.torso"] = new(20f), + ["hp.engine.chest"] = new(14f), + ["hp.radiator.back_l"] = new(6f), + ["hp.radiator.back_r"] = new(6f) + }), + + ["paladin"] = new( + Mobility: MobilityKind.Walker, + MassKg: 4100f, MaxSpeed: 22f, TurnRate: 2.7f, ThrustNewtons: 43000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 58f, Conductivity: 11.5f, BaseCellThermalMass: 18f, CargoCapacity: 9, + DefaultLoadout: new() { ["hp.weapon.arm_l"] = "autocannon", ["hp.weapon.arm_r"] = "autocannon", ["hp.weapon.sh_l"] = "pd_flak", ["hp.engine.chest"] = "turbo_core", ["hp.radiator.back_l"] = "copper_rad", ["hp.armor.torso"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.weapon.sh_l"] = new(12f, -10f, 85f, IsWideArc: true), + ["hp.armor.torso"] = new(22f), + ["hp.weapon.sh_r"] = new(12f, -10f, 85f, IsWideArc: true), + ["hp.weapon.arm_l"] = new(12f, -15f, 45f), + ["hp.engine.chest"] = new(16f), + ["hp.weapon.arm_r"] = new(12f, -15f, 45f), + ["hp.radiator.back_l"] = new(6f), + ["hp.armor.legs"] = new(20f), + ["hp.radiator.back_r"] = new(6f) + }), + }; + } + } +} diff --git a/tools/VehiclePacker/VehiclePacker.csproj b/tools/VehiclePacker/VehiclePacker.csproj new file mode 100644 index 0000000..a53a965 --- /dev/null +++ b/tools/VehiclePacker/VehiclePacker.csproj @@ -0,0 +1,14 @@ + + + + Exe + net10.0 + enable + disable + + + + + + + diff --git a/tools/audio/curate_haven_audio.py b/tools/audio/curate_haven_audio.py new file mode 100644 index 0000000..1204b79 --- /dev/null +++ b/tools/audio/curate_haven_audio.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Curate 25 original Haven Kendrick MWO WAVs into mono 44.1 kHz 16-bit PCM WAVs. + +Strictly read-only on D:\\Google Drive\\Gamecult\\Aetheria\\Audio\\WIP & Ideas\\Haven\\MWO Soundpack. +Explicitly excludes SW01_*, MW4*, Utilities-*, and desktop.ini. +""" + +from __future__ import annotations + +import array +import math +import os +import subprocess +import sys +import wave +from dataclasses import dataclass +from pathlib import Path + +SOURCE_DIR = Path(r"D:\Google Drive\Gamecult\Aetheria\Audio\WIP & Ideas\Haven\MWO Soundpack") +REPO_ROOT = Path(__file__).resolve().parents[2] +DEST_DIR = REPO_ROOT / "assets" / "audio" / "haven" +TARGET_SAMPLE_RATE = 44100 +TARGET_PEAK = 0.89 + +FORBIDDEN_PREFIXES = ("SW01_", "MW4", "Utilities-") +FORBIDDEN_EXACT = {"desktop.ini"} + + +@dataclass(frozen=True) +class ClipSpec: + dest_name: str + src_name: str + lead_trim_s: float + max_dur_s: float + fade_out_s: float + auto_trim_lead: bool = True + + +CLIPS: tuple[ClipSpec, ...] = ( + # Machine guns (mg_762) + ClipSpec("mg_shot_01.wav", "ClanMG3_fixed.wav", 0.0, 0.24, 0.035), + ClipSpec("mg_shot_02.wav", "New_MG 2.wav", 0.0, 0.24, 0.035), + ClipSpec("mg_tail.wav", "mgtail.wav", 0.0, 0.66, 0.030), + # Autocannons (autocannon) + ClipSpec("ac_light_01.wav", "AC5.wav", 0.0, 0.85, 0.040), + ClipSpec("ac_light_02.wav", "AC5_2.wav", 0.065, 0.80, 0.040, auto_trim_lead=False), + ClipSpec("ac_med_01.wav", "AC10.wav", 0.0, 0.95, 0.040), + ClipSpec("ac_rotary.wav", "RAC5.wav", 0.0, 1.01, 0.040), + # Flak & heavy recoilless (flak, recoilless) + ClipSpec("flak_blast_01.wav", "ClanLBX7_2019.wav", 0.0, 1.15, 0.045), + ClipSpec("flak_blast_02.wav", "IS_LBX20_2.wav", 0.0, 1.35, 0.045), + ClipSpec("cannon_heavy_01.wav", "BigCannon1.wav", 0.070, 1.80, 0.050, auto_trim_lead=False), + ClipSpec("cannon_heavy_02.wav", "AC20.wav", 0.0, 1.50, 0.050), + # Point defense (pd_flak, aegis_pd) + ClipSpec("pd_bark_01.wav", "AMS3.wav", 0.0, 0.28, 0.030), + ClipSpec("pd_bark_02.wav", "amsTP.wav", 0.0, 0.28, 0.030), + ClipSpec("pd_laser.wav", "laserams.wav", 0.0, 0.32, 0.030), + # Missiles / Rockets (Cut 7) + ClipSpec("rocket_salvo_01.wav", "MRM1.wav", 0.0, 1.20, 0.045), + ClipSpec("rocket_salvo_02.wav", "NEWSRM1.wav", 0.0, 1.35, 0.045), + # Energy / Plasma / Thermal Lance / Gauss (touring_plasma, gilded_lance, Cut 7) + ClipSpec("plasma_ppc_01.wav", "Snub_PPC2.wav", 0.0, 1.25, 0.045), + ClipSpec("plasma_ppc_02.wav", "PPcSWEET.wav", 0.045, 0.78, 0.040, auto_trim_lead=False), + ClipSpec("lance_beam_01.wav", "CPPC_DEC2018_2.wav", 0.0, 1.55, 0.050), + ClipSpec("laser_heavy_01.wav", "CLL3.wav", 0.0, 1.20, 0.045), + ClipSpec("gauss_rail_01.wav", "Gauss Sweet 1.wav", 0.015, 1.15, 0.045, auto_trim_lead=False), + # Mechanical / Bolt-clank / Chassis swap + ClipSpec("mech_reload_bolt.wav", "CannonReload2.wav", 0.0, 1.25, 0.045), + ClipSpec("mech_quick_bolt.wav", "reload.wav", 0.0, 0.94, 0.040), + ClipSpec("mech_eject.wav", "eject.wav", 0.0, 0.74, 0.035), + ClipSpec("mech_turret_servo.wav", "turret9.wav", 0.0, 1.10, 0.040), +) + + +def validate_source_name(name: str) -> None: + if name in FORBIDDEN_EXACT or any(name.startswith(p) for p in FORBIDDEN_PREFIXES): + raise ValueError(f"Refusing forbidden third-party/system file: {name}") + + +def decode_mono_f32(src_path: Path) -> list[float]: + cmd = [ + "ffmpeg", + "-v", + "error", + "-i", + str(src_path), + "-ac", + "1", + "-ar", + str(TARGET_SAMPLE_RATE), + "-f", + "f32le", + "-", + ] + proc = subprocess.run(cmd, capture_output=True, check=False) + if proc.returncode != 0: + err = proc.stderr.decode("utf-8", errors="replace").strip() + raise RuntimeError(f"ffmpeg failed on '{src_path}': {err}") + arr = array.array("f") + arr.frombytes(proc.stdout) + if sys.byteorder != "little": + arr.byteswap() + return list(arr) + + +def process_clip(spec: ClipSpec, src_path: Path, dst_path: Path) -> tuple[float, float, int]: + samples = decode_mono_f32(src_path) + if not samples: + raise RuntimeError(f"Decoded zero samples from '{src_path}'") + + lead_idx = int(round(spec.lead_trim_s * TARGET_SAMPLE_RATE)) + if lead_idx > 0 and lead_idx < len(samples): + samples = samples[lead_idx:] + + if spec.auto_trim_lead: + # Trim only genuinely silent leading padding (>10 ms below -54 dBFS) + silence_thresh = 0.002 + first_active = 0 + for idx, s in enumerate(samples): + if abs(s) >= silence_thresh: + first_active = idx + break + if first_active > int(0.010 * TARGET_SAMPLE_RATE): + samples = samples[first_active:] + + max_samples = int(round(spec.max_dur_s * TARGET_SAMPLE_RATE)) + if len(samples) > max_samples: + samples = samples[:max_samples] + + # Trim trailing near-silence beyond 15ms if tail is quieter than -60 dBFS, keeping at least 150ms + min_keep = min(len(samples), int(0.15 * TARGET_SAMPLE_RATE)) + last_active = len(samples) - 1 + while last_active > min_keep and abs(samples[last_active]) < 0.001: + last_active -= 1 + samples = samples[: min(len(samples), last_active + int(0.015 * TARGET_SAMPLE_RATE))] + + n = len(samples) + if n < 256: + raise RuntimeError(f"Clip '{spec.dest_name}' became too short ({n} samples)") + + # Short 4ms fade-in only if attack begins non-zero, avoiding click + fade_in = min(n // 8, int(0.004 * TARGET_SAMPLE_RATE)) + if fade_in > 0 and abs(samples[0]) > 0.005: + for i in range(fade_in): + gain = 0.5 * (1.0 - math.cos(math.pi * (i + 0.5) / fade_in)) + samples[i] *= gain + + # Smooth cosine fade-out on tail + fade_out = min(n // 2, int(round(spec.fade_out_s * TARGET_SAMPLE_RATE))) + if fade_out > 0: + start = n - fade_out + for i in range(fade_out): + gain = 0.5 * (1.0 + math.cos(math.pi * (i + 1) / fade_out)) + samples[start + i] *= gain + + peak = max(abs(x) for x in samples) + if peak < 1e-4: + raise RuntimeError(f"Clip '{spec.dest_name}' is silent (peak={peak})") + + scale = TARGET_PEAK / peak + pcm = array.array("h") + final_peak = 0.0 + for s in samples: + v = max(-1.0, min(1.0, s * scale)) + final_peak = max(final_peak, abs(v)) + pcm.append(int(round(v * 32767.0))) + + if sys.byteorder != "little": + pcm.byteswap() + + with wave.open(str(dst_path), "wb") as wf: + wf.setnchannels(1) + wf.setsampwidth(2) + wf.setframerate(TARGET_SAMPLE_RATE) + wf.writeframes(pcm.tobytes()) + + size_bytes = dst_path.stat().st_size + dur_s = n / TARGET_SAMPLE_RATE + return dur_s, final_peak, size_bytes + + +def main() -> int: + if len(CLIPS) != 25: + raise AssertionError(f"Expected exactly 25 clips, got {len(CLIPS)}") + if not SOURCE_DIR.is_dir(): + raise FileNotFoundError(f"Source directory not found: {SOURCE_DIR}") + + DEST_DIR.mkdir(parents=True, exist_ok=True) + expected_names = {c.dest_name for c in CLIPS} + for existing in DEST_DIR.glob("*"): + if existing.is_file() and existing.name not in expected_names: + existing.unlink() + + total_bytes = 0 + for spec in CLIPS: + validate_source_name(spec.src_name) + src_path = SOURCE_DIR / spec.src_name + if not src_path.is_file(): + raise FileNotFoundError(f"Missing Haven source WAV: {src_path}") + dst_path = DEST_DIR / spec.dest_name + dur_s, peak, size_bytes = process_clip(spec, src_path, dst_path) + total_bytes += size_bytes + print(f" {spec.dest_name:<22} <- {spec.src_name:<22} {dur_s:5.2f}s peak={peak:.3f} {size_bytes/1024:6.1f} KiB") + + produced = sorted(p.name for p in DEST_DIR.glob("*.wav")) + if len(produced) != 25: + raise RuntimeError(f"Expected 25 WAVs in {DEST_DIR}, found {len(produced)}") + + total_mib = total_bytes / (1024.0 * 1024.0) + print(f"Curated {len(produced)} WAVs into {DEST_DIR} (total {total_mib:.2f} MiB)") + if total_mib >= 4.0: + raise RuntimeError(f"Total audio size {total_mib:.2f} MiB exceeds 4.0 MiB budget") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/build_release.ps1 b/tools/build_release.ps1 new file mode 100644 index 0000000..ff2c083 --- /dev/null +++ b/tools/build_release.ps1 @@ -0,0 +1,458 @@ +[CmdletBinding()] +param( + [string]$OutDir = "dist", + [string]$Tag = "", + [switch]$Publish, + [string]$ForgeUrl = "https://eureka.gamecult.org/forge", + [string]$Repo = "GameCult/RustToDust", + [string]$Token = "", + [string]$GodotExe = "", + [string]$YmirRoot = "", + [string]$CultLibRoot = "" +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +try { + [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 +} +catch { + # Ignore on runtimes where SecurityProtocol is managed by OS +} + +$MinReleaseYmirDllBytes = 400000L +$MaxReleaseYmirDllBytes = 2000000L # Release is ~750-900 KB; Debug (with BOX3D_VALIDATE) is > 4 MB +$MinReleaseHbGpuDllBytes = 100000L +$MaxReleaseHbGpuDllBytes = 2621440L # < 2.5 MiB HarfBuzz 15.2.0 hb-gpu DLL budget + +function Resolve-RepoPath { + param([string]$PathValue, [string]$BaseDir) + if ([System.IO.Path]::IsPathRooted($PathValue)) { + return [System.IO.Path]::GetFullPath($PathValue) + } + return [System.IO.Path]::GetFullPath((Join-Path $BaseDir $PathValue)) +} + +function Resolve-DependencyRoot { + param( + [string]$Explicit, + [string]$EnvName, + [string]$SiblingName, + [string]$FallbackPath, + [string]$RepoRoot + ) + if (-not [string]::IsNullOrWhiteSpace($Explicit) -and (Test-Path $Explicit)) { + return (Resolve-Path $Explicit).Path + } + $envVal = [Environment]::GetEnvironmentVariable($EnvName) + if (-not [string]::IsNullOrWhiteSpace($envVal) -and (Test-Path $envVal)) { + return (Resolve-Path $envVal).Path + } + $sibling = Join-Path (Split-Path $RepoRoot -Parent) $SiblingName + if (Test-Path $sibling) { + return (Resolve-Path $sibling).Path + } + if (Test-Path $FallbackPath) { + return (Resolve-Path $FallbackPath).Path + } + throw "Could not locate $SiblingName root. Set -$($SiblingName)Root or `$env:$EnvName." +} + +function Resolve-GodotConsoleExe { + param([string]$Explicit) + if (-not [string]::IsNullOrWhiteSpace($Explicit)) { + if (-not (Test-Path $Explicit)) { + throw "Godot console executable not found at '$Explicit'." + } + return (Resolve-Path $Explicit).Path + } + $candidates = @( + $env:GODOT_CONSOLE_EXE, + "F:\Applications\Godot_v4.7.2-stable_mono_win64\Godot_v4.7.2-stable_mono_win64_console.exe", + "C:\Program Files\Godot\Godot_v4.7.2-stable_mono_win64_console.exe" + ) + foreach ($c in $candidates) { + if (-not [string]::IsNullOrWhiteSpace($c) -and (Test-Path $c)) { + return (Resolve-Path $c).Path + } + } + $cmd = Get-Command "Godot_v4.7.2-stable_mono_win64_console.exe" -ErrorAction SilentlyContinue + if ($cmd) { + return $cmd.Source + } + throw "Could not locate Godot_v4.7.2-stable_mono_win64_console.exe. Pass -GodotExe or set GODOT_CONSOLE_EXE." +} + +function Resolve-ForgejoToken { + param([string]$Explicit, [string]$ForgeBaseUrl) + if (-not [string]::IsNullOrWhiteSpace($Explicit)) { + return $Explicit.Trim() + } + if (-not [string]::IsNullOrWhiteSpace($env:FORGEJO_TOKEN)) { + return $env:FORGEJO_TOKEN.Trim() + } + + $eurekaTokenPath = Join-Path $env:USERPROFILE ".config\forgejo\eureka-pr-token" + if (Test-Path $eurekaTokenPath) { + $tok = (Get-Content $eurekaTokenPath -Raw).Trim() + if (-not [string]::IsNullOrWhiteSpace($tok)) { + return $tok + } + } + + $teaPaths = @( + (Join-Path $env:USERPROFILE ".config\tea\config.yml"), + (Join-Path $env:APPDATA "tea\config.yml") + ) + $forgeHost = ([Uri]$ForgeBaseUrl).Host + foreach ($teaPath in $teaPaths) { + if (Test-Path $teaPath) { + $blockUrl = "" + $blockToken = "" + foreach ($line in (Get-Content $teaPath)) { + if ($line -match "^\s*-\s+") { + if ($blockUrl -match [regex]::Escape($forgeHost) -and -not [string]::IsNullOrWhiteSpace($blockToken)) { + return $blockToken + } + $blockUrl = "" + $blockToken = "" + } + if ($line -match "url:\s*(.+)") { + $blockUrl = $Matches[1].Trim().Trim('"').Trim("'") + } + elseif ($line -match "token:\s*(.+)") { + $blockToken = $Matches[1].Trim().Trim('"').Trim("'") + } + } + if ($blockUrl -match [regex]::Escape($forgeHost) -and -not [string]::IsNullOrWhiteSpace($blockToken)) { + return $blockToken + } + } + } + + $gitCredPath = Join-Path $env:USERPROFILE ".git-credentials" + if (Test-Path $gitCredPath) { + foreach ($line in Get-Content $gitCredPath) { + if ($line -match "^https?://[^:]+:([^@]+)@$([regex]::Escape($forgeHost))") { + return [Uri]::UnescapeDataString($Matches[1]) + } + } + } + + throw "Forgejo token not found. Pass -Token, set `$env:FORGEJO_TOKEN, or store a token in ~/.config/forgejo/eureka-pr-token or ~/.config/tea/config.yml." +} + +function Copy-FilteredTree { + param( + [string]$SourceDir, + [string]$DestDir, + [string[]]$IncludeExtensions + ) + if (-not (Test-Path $SourceDir)) { + throw "Required asset source directory missing: '$SourceDir'" + } + $srcFull = (Resolve-Path $SourceDir).Path.TrimEnd('\', '/') + New-Item -ItemType Directory -Force -Path $DestDir | Out-Null + $files = Get-ChildItem -Path $srcFull -Recurse -File + $count = 0 + foreach ($file in $files) { + if ($IncludeExtensions -notcontains $file.Extension.ToLowerInvariant()) { + continue + } + $rel = $file.FullName.Substring($srcFull.Length + 1) + $target = Join-Path $DestDir $rel + $targetParent = Split-Path $target -Parent + if (-not (Test-Path $targetParent)) { + New-Item -ItemType Directory -Force -Path $targetParent | Out-Null + } + Copy-Item -Path $file.FullName -Destination $target -Force + $count++ + } + return $count +} + +function Invoke-ForgeApiJson { + param( + [string]$Method, + [string]$Url, + [string]$Token, + [object]$Body = $null + ) + $headers = @{ + "Authorization" = "token $Token" + "Accept" = "application/json" + } + $params = @{ + Method = $Method + Uri = $Url + Headers = $headers + ErrorAction = "Stop" + } + if ($null -ne $Body) { + $params["ContentType"] = "application/json" + $params["Body"] = ($Body | ConvertTo-Json -Depth 6) + } + return Invoke-RestMethod @params +} + +$RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path +$ClientDir = Join-Path $RepoRoot "client" +$AssetsSrcDir = Join-Path $RepoRoot "assets" + +$fullSha = (& git -C $RepoRoot rev-parse HEAD).Trim() +if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($fullSha)) { + throw "Failed to resolve git HEAD SHA." +} + +if ([string]::IsNullOrWhiteSpace($Tag)) { + $shortSha = (& git -C $RepoRoot rev-parse --short HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($shortSha)) { + throw "Failed to resolve git short SHA for default tag." + } + $dateStamp = (Get-Date).ToUniversalTime().ToString("yyyyMMdd") + $Tag = "rtd-$dateStamp-$shortSha" +} + +$ResolvedOutDir = Resolve-RepoPath -PathValue $OutDir -BaseDir $RepoRoot +$StageDir = Join-Path $ResolvedOutDir "stage-$Tag" +$ZipName = "RustToDust-win64-$Tag.zip" +$ZipPath = Join-Path $ResolvedOutDir $ZipName +$ShaPath = Join-Path $ResolvedOutDir "SHA256SUMS.txt" + +$YmirRoot = Resolve-DependencyRoot -Explicit $YmirRoot -EnvName "YMIR_ROOT" -SiblingName "Ymir" -FallbackPath "F:\Projects\Ymir" -RepoRoot $RepoRoot +$CultLibRoot = Resolve-DependencyRoot -Explicit $CultLibRoot -EnvName "CULTLIB_ROOT" -SiblingName "CultLib" -FallbackPath "F:\Projects\CultLib" -RepoRoot $RepoRoot +$GodotConsole = Resolve-GodotConsoleExe -Explicit $GodotExe + +$TemplateDir = Join-Path $env:APPDATA "Godot\export_templates\4.7.2.stable.mono" +if (-not (Test-Path $TemplateDir)) { + throw "Godot 4.7.2.stable.mono export templates missing at '$TemplateDir'." +} + +$env:YMIR_ROOT = $YmirRoot +$env:CULTLIB_ROOT = $CultLibRoot +$env:MSBUILDDISABLENODEREUSE = "1" +$env:DOTNET_CLI_DO_NOT_USE_MSBUILD_SERVER = "1" +$env:UseSharedCompilation = "false" + +Write-Host "=== Rust to Dust win64 Release Build ===" +Write-Host "RepoRoot : $RepoRoot" +Write-Host "Tag : $Tag" +Write-Host "YmirRoot : $YmirRoot" +Write-Host "CultLibRoot: $CultLibRoot" +Write-Host "Godot : $GodotConsole" +Write-Host "OutDir : $ResolvedOutDir" + +# Step 1: Build Release ymir_box3d.dll and verify exact Release binary size +Write-Host "`n[1/5] Building Release ymir_box3d.dll..." +$ymirProj = Join-Path $YmirRoot "src\Ymir.Box3D\Ymir.Box3D.csproj" +& dotnet build $ymirProj -c Release -p:YmirNativeConfiguration=Release --disable-build-servers -p:UseSharedCompilation=false -nr:false +if ($LASTEXITCODE -ne 0) { + throw "dotnet build Ymir.Box3D failed with exit code $LASTEXITCODE." +} + +$ymirDllPath = Join-Path $YmirRoot "artifacts\box3d-native\production\Release\bin\Release\ymir_box3d.dll" +if (-not (Test-Path $ymirDllPath)) { + throw "Release ymir_box3d.dll not found at '$ymirDllPath'." +} +$ymirDllLen = (Get-Item $ymirDllPath).Length +if ($ymirDllLen -lt $MinReleaseYmirDllBytes -or $ymirDllLen -gt $MaxReleaseYmirDllBytes) { + throw "ymir_box3d.dll size outside Release range ($MinReleaseYmirDllBytes..$MaxReleaseYmirDllBytes B; Debug is >4 MB): got $ymirDllLen bytes at '$ymirDllPath'." +} +Write-Host "Verified Release ymir_box3d.dll ($ymirDllLen B)." + +Write-Host "`n[1b/5] Building Release rtd_hbgpu.dll..." +$hbGpuProj = Join-Path $RepoRoot "src\RustToDust.HbGpu\RustToDust.HbGpu.csproj" +& dotnet build $hbGpuProj -c Release -p:HbGpuNativeConfiguration=Release --disable-build-servers -p:UseSharedCompilation=false -nr:false +if ($LASTEXITCODE -ne 0) { + throw "dotnet build RustToDust.HbGpu failed with exit code $LASTEXITCODE." +} + +$hbGpuDllPath = Join-Path $RepoRoot "artifacts\hbgpu-native\Release\bin\Release\rtd_hbgpu.dll" +if (-not (Test-Path $hbGpuDllPath)) { + throw "Release rtd_hbgpu.dll not found at '$hbGpuDllPath'." +} +$hbGpuDllLen = (Get-Item $hbGpuDllPath).Length +if ($hbGpuDllLen -lt $MinReleaseHbGpuDllBytes -or $hbGpuDllLen -gt $MaxReleaseHbGpuDllBytes) { + throw "rtd_hbgpu.dll size outside Release range ($MinReleaseHbGpuDllBytes..$MaxReleaseHbGpuDllBytes B): got $hbGpuDllLen bytes at '$hbGpuDllPath'." +} +Write-Host "Verified Release rtd_hbgpu.dll ($hbGpuDllLen B)." + +# Step 2: Export Windows Desktop Release via Godot +Write-Host "`n[2/5] Exporting Windows Desktop Release..." +if (Test-Path $StageDir) { + Remove-Item -Recurse -Force $StageDir +} +New-Item -ItemType Directory -Force -Path $StageDir | Out-Null + +$exportExePath = Join-Path $StageDir "RustToDust.exe" +$clientSlnPath = Join-Path $ClientDir "RustToDust.Client.sln" +$createdTempSln = $false + +try { + if (-not (Test-Path $clientSlnPath)) { + Write-Host "Creating temporary client/RustToDust.Client.sln for Godot export..." + & dotnet new sln -n "RustToDust.Client" -o $ClientDir --format sln | Out-Null + if ($LASTEXITCODE -ne 0) { + throw "dotnet new sln failed with exit code $LASTEXITCODE." + } + $createdTempSln = $true + & dotnet sln $clientSlnPath add (Join-Path $ClientDir "RustToDust.Client.csproj") | Out-Null + if ($LASTEXITCODE -ne 0) { + throw "dotnet sln add failed with exit code $LASTEXITCODE." + } + } + + if (-not (Test-Path (Join-Path $ClientDir ".godot"))) { + Write-Host "Bootstrapping client/.godot import cache (headless)..." + & $GodotConsole --headless --audio-driver Dummy --path $ClientDir --import --quit + if ($LASTEXITCODE -ne 0) { + throw "Godot headless --import failed with exit code $LASTEXITCODE." + } + } + + & $GodotConsole --headless --audio-driver Dummy --path $ClientDir --quit --export-release "Windows Desktop" $exportExePath + if ($LASTEXITCODE -ne 0) { + throw "Godot --export-release failed with exit code $LASTEXITCODE." + } +} +finally { + if ($createdTempSln -and (Test-Path $clientSlnPath)) { + Remove-Item -Force $clientSlnPath -ErrorAction SilentlyContinue + } +} +if (-not (Test-Path $exportExePath)) { + throw "Expected exported executable missing: '$exportExePath'." +} + +$dataDirCandidates = @( + (Join-Path $StageDir "data_RustToDust_windows_x86_64"), + (Join-Path $StageDir "data_RustToDust.Client_windows_x86_64") +) +$stagedDataDir = $dataDirCandidates | Where-Object { Test-Path $_ } | Select-Object -First 1 +if (-not $stagedDataDir) { + throw "Expected Godot Mono data directory missing under '$StageDir'." +} + +# Remove PDBs if any slipped through +Get-ChildItem -Path $StageDir -Recurse -Filter "*.pdb" -File | Remove-Item -Force + +# Step 3: Stage Release ymir_box3d.dll, rtd_hbgpu.dll, licenses & runtime assets/ +Write-Host "`n[3/5] Staging Release native DLLs, licenses, and runtime assets/..." +Copy-Item -Path $ymirDllPath -Destination (Join-Path $StageDir "ymir_box3d.dll") -Force +Copy-Item -Path $ymirDllPath -Destination (Join-Path $stagedDataDir "ymir_box3d.dll") -Force +Copy-Item -Path $hbGpuDllPath -Destination (Join-Path $StageDir "rtd_hbgpu.dll") -Force +Copy-Item -Path $hbGpuDllPath -Destination (Join-Path $stagedDataDir "rtd_hbgpu.dll") -Force + +$fontLicenseSrc = Join-Path $ClientDir "fonts\MONASPACE_LICENSE.txt" +if (-not (Test-Path $fontLicenseSrc)) { + throw "Required font license notice missing: '$fontLicenseSrc'." +} +Copy-Item -Path $fontLicenseSrc -Destination (Join-Path $StageDir "MONASPACE_LICENSE.txt") -Force + +$thirdPartySrc = Join-Path $RepoRoot "THIRD_PARTY_NOTICES.txt" +if (-not (Test-Path $thirdPartySrc)) { + throw "Required third-party notices missing: '$thirdPartySrc'." +} +Copy-Item -Path $thirdPartySrc -Destination (Join-Path $StageDir "THIRD_PARTY_NOTICES.txt") -Force + +$stagedAssetsDir = Join-Path $StageDir "assets" +$vCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "vehicles") -DestDir (Join-Path $stagedAssetsDir "vehicles") -IncludeExtensions @(".glb", ".cc", ".json") +$gCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "gear") -DestDir (Join-Path $stagedAssetsDir "gear") -IncludeExtensions @(".glb") +$dCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "decals") -DestDir (Join-Path $stagedAssetsDir "decals") -IncludeExtensions @(".png") +$aCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "audio") -DestDir (Join-Path $stagedAssetsDir "audio") -IncludeExtensions @(".wav", ".md") +$fCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "fonts") -DestDir (Join-Path $stagedAssetsDir "fonts") -IncludeExtensions @(".ttf", ".txt", ".md") +$mCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "maps\sion") -DestDir (Join-Path $stagedAssetsDir "maps\sion") -IncludeExtensions @(".json", ".u16z", ".png", ".bin", ".glb") +foreach ($reqFontFile in @("Krypton.ttf", "OFL-1.1.txt", "HARFBUZZ-COPYING.txt")) { + $reqPath = Join-Path (Join-Path $stagedAssetsDir "fonts") $reqFontFile + if (-not (Test-Path $reqPath)) { + throw "Required staged font/license file missing: '$reqPath'." + } +} +Write-Host "Staged runtime assets: vehicles=$vCount gear=$gCount decals=$dCount audio=$aCount fonts=$fCount sion=$mCount" + +# Step 4: Create ZIP and SHA256SUMS.txt +Write-Host "`n[4/5] Packaging $ZipName..." +New-Item -ItemType Directory -Force -Path $ResolvedOutDir | Out-Null +if (Test-Path $ZipPath) { + Remove-Item -Force $ZipPath +} +Add-Type -AssemblyName System.IO.Compression.FileSystem +[System.IO.Compression.ZipFile]::CreateFromDirectory($StageDir, $ZipPath, [System.IO.Compression.CompressionLevel]::Optimal, $false) + +$zipInfo = Get-Item $ZipPath +$zipHash = (Get-FileHash -Path $ZipPath -Algorithm SHA256).Hash.ToLowerInvariant() +"$zipHash $ZipName" | Set-Content -Path $ShaPath -Encoding ASCII +Write-Host "Created $ZipPath ($($zipInfo.Length) B, sha256=$zipHash)" + +# Remove intermediate stage directory so dist/ holds clean release outputs +Remove-Item -Recurse -Force $StageDir + +# Step 5: Optional Forgejo Release publish +if ($Publish) { + Write-Host "`n[5/5] Publishing release '$Tag' to $ForgeUrl ($Repo)..." + $resolvedToken = Resolve-ForgejoToken -Explicit $Token -ForgeBaseUrl $ForgeUrl + $apiBase = "$($ForgeUrl.TrimEnd('/'))/api/v1/repos/$Repo" + + $release = $null + try { + $release = Invoke-ForgeApiJson -Method "GET" -Url "$apiBase/releases/tags/$Tag" -Token $resolvedToken + Write-Host "Found existing release id=$($release.id) for tag '$Tag'." + } + catch { + $statusCode = $null + $ex = $_.Exception + if ($ex -is [System.Net.WebException] -and $ex.Response) { + $statusCode = [int]$ex.Response.StatusCode + } + elseif ($ex.PSObject.Properties['Response'] -and $ex.Response -and $ex.Response.PSObject.Properties['StatusCode']) { + $statusCode = [int]$ex.Response.StatusCode + } + if ($statusCode -ne 404) { + throw + } + } + + $releaseNotes = "Standalone Windows x64 build ($Tag). Unzip and run RustToDust.exe." + if ($null -eq $release) { + $release = Invoke-ForgeApiJson -Method "POST" -Url "$apiBase/releases" -Token $resolvedToken -Body @{ + tag_name = $Tag + target_commitish = $fullSha + name = $Tag + body = $releaseNotes + draft = $false + prerelease = $false + } + Write-Host "Created release id=$($release.id) for tag '$Tag' ($fullSha)." + } + else { + $release = Invoke-ForgeApiJson -Method "PATCH" -Url "$apiBase/releases/$($release.id)" -Token $resolvedToken -Body @{ + name = $Tag + body = $releaseNotes + draft = $false + prerelease = $false + } + } + + foreach ($assetPath in @($ZipPath, $ShaPath)) { + $assetName = [System.IO.Path]::GetFileName($assetPath) + if ($release.assets) { + foreach ($existing in $release.assets) { + if ($existing.name -eq $assetName) { + Write-Host "Removing existing release asset '$assetName' (id=$($existing.id))..." + Invoke-ForgeApiJson -Method "DELETE" -Url "$apiBase/releases/$($release.id)/assets/$($existing.id)" -Token $resolvedToken | Out-Null + } + } + } + Write-Host "Uploading '$assetName'..." + $uploadUrl = "$apiBase/releases/$($release.id)/assets?name=$([Uri]::EscapeDataString($assetName))" + & curl.exe -fsS -X POST -H "Authorization: token $resolvedToken" -F "attachment=@$assetPath" $uploadUrl | Out-Null + if ($LASTEXITCODE -ne 0) { + throw "curl.exe failed uploading '$assetName' (exit $LASTEXITCODE)." + } + } + Write-Host "Published: $($ForgeUrl.TrimEnd('/'))/$Repo/releases/tag/$Tag" +} +else { + Write-Host "`n[5/5] Skipping Forgejo publish (-Publish not set)." +} diff --git a/tools/decals/build_decal_atlas.py b/tools/decals/build_decal_atlas.py new file mode 100644 index 0000000..a2c1d40 --- /dev/null +++ b/tools/decals/build_decal_atlas.py @@ -0,0 +1,939 @@ +"""Procedural 4x4 hard-surface & combat POM decal trim-sheet atlas generator. + +Outputs three 1024x1024 RGBA/RGB PNG textures under assets/decals/: + - decal_atlas_albedo.png (RGBA: sRGB albedo + alpha mask, dilated into alpha=0) + - decal_atlas_normal.png (RGB: tangent-space normal map, OpenGL/Godot +X right, +Y down) + - decal_atlas_ormh.png (RGBA: R=AO, G=Roughness, B=Metallic, A=Height [1=surface, 0=deep recess]) + +4x4 tile layout (256x256 each, row 0 = top): + Row 0: (0) louvered armor vent, (1) recessed bolted maintenance hatch, + (2) 4-bolt recessed fastener strip, (3) slotted intake grille + Row 1: (4) rivet panel seam, (5) welded armor repair patch, + (6) recessed lift-lug pocket, (7) weathered hazard caution chevron strip + Row 2: (8) tactical stencil "03", (9) tactical stencil "07", + (10) radiation/heat warning stencil, (11) faction chevron emblem + Row 3: (12) deep AP autocannon penetration hole, (13) diagonal shrapnel/flak armor gouge, + (14) molten plasma burn crater, (15) radial blast scorch mark +""" +from __future__ import annotations + +from pathlib import Path +import numpy as np +from PIL import Image + +REPO_ROOT = Path(__file__).resolve().parents[2] +OUT_DIR = REPO_ROOT / "assets" / "decals" + +TILE_SIZE = 256 +GRID = 4 +ATLAS_SIZE = TILE_SIZE * GRID # 1024 + + +# --------------------------------------------------------------------------- +# Deterministic vectorized noise & SDF primitives (on normalized [-1, 1]^2 tile coords) +# --------------------------------------------------------------------------- + +def _hash2(ix: np.ndarray, iy: np.ndarray, seed: int) -> np.ndarray: + n = (ix.astype(np.int64) * 374761393 + + iy.astype(np.int64) * 668265263 + + np.int64(seed) * 1442695041) & 0xFFFFFFFF + n = ((n ^ (n >> 13)) * 1274126177) & 0xFFFFFFFF + n = n ^ (n >> 16) + return (n & 0xFFFFFF).astype(np.float32) / float(0x1000000) + + +def value_noise(x: np.ndarray, y: np.ndarray, freq: float, seed: int = 1) -> np.ndarray: + px = x * freq + py = y * freq + ix = np.floor(px).astype(np.int64) + iy = np.floor(py).astype(np.int64) + fx = px - ix + fy = py - iy + ux = fx * fx * (3.0 - 2.0 * fx) + uy = fy * fy * (3.0 - 2.0 * fy) + a = _hash2(ix, iy, seed) + b = _hash2(ix + 1, iy, seed) + c = _hash2(ix, iy + 1, seed) + d = _hash2(ix + 1, iy + 1, seed) + return (a * (1.0 - ux) + b * ux) * (1.0 - uy) + (c * (1.0 - ux) + d * ux) * uy + + +def fbm(x: np.ndarray, y: np.ndarray, base_freq: float, octaves: int = 4, seed: int = 1) -> np.ndarray: + acc = np.zeros_like(x, dtype=np.float32) + amp = 0.5 + norm = 0.0 + f = base_freq + for o in range(octaves): + acc += amp * value_noise(x, y, f, seed + o * 37) + norm += amp + amp *= 0.5 + f *= 2.03 + return acc / norm + + +def smoothstep(e0: float, e1: float, x: np.ndarray) -> np.ndarray: + t = np.clip((x - e0) / (e1 - e0), 0.0, 1.0) + return t * t * (3.0 - 2.0 * t) + + +def sd_box(x: np.ndarray, y: np.ndarray, cx: float, cy: float, hx: float, hy: float, r: float = 0.0) -> np.ndarray: + qx = np.abs(x - cx) - (hx - r) + qy = np.abs(y - cy) - (hy - r) + out = np.sqrt(np.maximum(qx, 0.0) ** 2 + np.maximum(qy, 0.0) ** 2) + ins = np.minimum(np.maximum(qx, qy), 0.0) + return out + ins - r + + +def sd_circle(x: np.ndarray, y: np.ndarray, cx: float, cy: float, r: float) -> np.ndarray: + return np.sqrt((x - cx) ** 2 + (y - cy) ** 2) - r + + +def sd_segment(x: np.ndarray, y: np.ndarray, ax: float, ay: float, bx: float, by: float) -> np.ndarray: + pax = x - ax + pay = y - ay + bax = bx - ax + bay = by - ay + denom = bax * bax + bay * bay + 1e-12 + h = np.clip((pax * bax + pay * bay) / denom, 0.0, 1.0) + return np.sqrt((pax - bax * h) ** 2 + (pay - bay * h) ** 2) + + +def sd_hexagon(x: np.ndarray, y: np.ndarray, cx: float, cy: float, r: float) -> np.ndarray: + px = np.abs(x - cx) + py = np.abs(y - cy) + # Regular hexagon with flat top/bottom + d = np.maximum(px * 0.8660254 + py * 0.5, py) - r + return d + + +def sd_triangle_eq(x: np.ndarray, y: np.ndarray, cx: float, cy: float, r: float) -> np.ndarray: + # Pointing up (-y in image space) + px = np.abs(x - cx) + py = -(y - cy) + r * 0.25 + px_k = np.sqrt(3.0) + # Standard IQ equilateral triangle SDF + px2 = px - r + py2 = py + r / px_k + cond = (px + px_k * py) > 0.0 + nx = np.where(cond, (px - px_k * py) * 0.5, px) + ny = np.where(cond, (-px_k * px - py) * 0.5, py) + nx -= np.clip(nx, -2.0 * r, 0.0) + return -np.sqrt(nx * nx + ny * ny) * np.sign(ny) + + +def tile_coords() -> tuple[np.ndarray, np.ndarray]: + lin = np.linspace(-1.0 + 1.0 / TILE_SIZE, 1.0 - 1.0 / TILE_SIZE, TILE_SIZE, dtype=np.float32) + yy, xx = np.meshgrid(lin, lin, indexing="ij") + return xx, yy + + +def new_tile() -> dict[str, np.ndarray]: + shape = (TILE_SIZE, TILE_SIZE) + return { + "rgb": np.full((*shape, 3), 0.18, dtype=np.float32), + "alpha": np.zeros(shape, dtype=np.float32), + "height": np.ones(shape, dtype=np.float32), + "rough": np.full(shape, 0.56, dtype=np.float32), + "metal": np.full(shape, 0.35, dtype=np.float32), + } + + +def add_hex_bolt( + t: dict[str, np.ndarray], + x: np.ndarray, + y: np.ndarray, + cx: float, + cy: float, + pocket_r: float = 0.095, + head_r: float = 0.064, + base_h: float = 0.85, +) -> None: + dp = sd_circle(x, y, cx, cy, pocket_r) + dh = sd_circle(x, y, cx, cy, head_r) + dhex = sd_hexagon(x, y, cx, cy, head_r * 0.48) + + in_pocket = smoothstep(0.015, -0.015, dp) + in_head = smoothstep(0.012, -0.012, dh) + in_socket = smoothstep(0.010, -0.010, dhex) + + # Countersunk floor + pocket_h = base_h - 0.52 * in_pocket + # Raised chamfered bolt head inside pocket + head_profile = np.clip(1.0 - np.maximum(dh / head_r + 1.0, 0.0) ** 4 * 0.15, 0.0, 1.0) + bolt_h = base_h - 0.06 + 0.04 * head_profile + bolt_h = bolt_h - 0.36 * in_socket + + t["height"] = np.where(in_head > 0.5, bolt_h, np.minimum(t["height"], pocket_h)) + # Colors & PBR + pocket_col = np.array([0.055, 0.058, 0.056], dtype=np.float32) + bolt_col = np.array([0.24, 0.25, 0.24], dtype=np.float32) + sock_col = np.array([0.035, 0.036, 0.036], dtype=np.float32) + + t["rgb"] = t["rgb"] * (1.0 - in_pocket[..., None]) + pocket_col * in_pocket[..., None] + t["rgb"] = t["rgb"] * (1.0 - in_head[..., None]) + bolt_col * in_head[..., None] + t["rgb"] = t["rgb"] * (1.0 - in_socket[..., None]) + sock_col * in_socket[..., None] + t["metal"] = np.where(in_head > 0.5, 0.88, np.where(in_pocket > 0.5, 0.65, t["metal"])) + t["rough"] = np.where(in_head > 0.5, 0.34, np.where(in_pocket > 0.5, 0.62, t["rough"])) + + +def add_domed_rivet( + t: dict[str, np.ndarray], + x: np.ndarray, + y: np.ndarray, + cx: float, + cy: float, + r: float = 0.052, + base_h: float = 0.88, +) -> None: + d = sd_circle(x, y, cx, cy, r) + mask = smoothstep(0.012, -0.012, d) + ring = smoothstep(0.018, 0.0, np.abs(d - 0.005)) + dist_norm = np.clip(np.sqrt((x - cx) ** 2 + (y - cy) ** 2) / r, 0.0, 1.0) + dome = np.sqrt(np.maximum(1.0 - dist_norm ** 2, 0.0)) + rivet_h = base_h - 0.08 * ring + 0.11 * dome * mask + t["height"] = t["height"] * (1.0 - mask) + np.clip(rivet_h, 0.0, 1.0) * mask + col = np.array([0.28, 0.29, 0.27], dtype=np.float32) + t["rgb"] = t["rgb"] * (1.0 - mask[..., None]) + col * mask[..., None] + t["metal"] = t["metal"] * (1.0 - mask) + 0.85 * mask + t["rough"] = t["rough"] * (1.0 - mask) + 0.32 * mask + + +# --------------------------------------------------------------------------- +# Individual tiles (0..15) +# --------------------------------------------------------------------------- + +def tile_00_louvered_vent(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(0) Louvered armor vent.""" + t = new_tile() + n1 = fbm(x, y, 10.0, 4, seed=101) + n2 = fbm(x, y, 36.0, 3, seed=102) + + d_outer = sd_box(x, y, 0.0, 0.0, 0.80, 0.72, r=0.06) + d_inner = sd_box(x, y, 0.0, 0.0, 0.65, 0.56, r=0.03) + d_seam = np.abs(d_outer) + + outer_m = smoothstep(0.025, -0.025, d_outer) + inner_m = smoothstep(0.02, -0.02, d_inner) + + # Frame plate + frame_h = 0.96 - 0.04 * smoothstep(0.0, 0.14, np.maximum(-d_outer, 0.0)) + frame_h -= 0.45 * smoothstep(0.03, 0.0, d_seam) + # Recessed bay behind louvers + h = np.where(inner_m > 0.5, 0.04, frame_h) + + # 5 angled louvers inside d_inner + slat_centers = np.linspace(-0.42, 0.42, 5) + slat_mask_all = np.zeros_like(x) + for sc in slat_centers: + # Each louver spans x=[-0.62, 0.62], y=[sc-0.065, sc+0.065] + ds = sd_box(x, y, 0.0, float(sc), 0.62, 0.068, r=0.015) + sm = smoothstep(0.015, -0.015, ds) + # Slope from top (high) down to bottom (low), exposing dark gap underneath + local_t = np.clip((y - (sc - 0.068)) / 0.136, 0.0, 1.0) + slat_h = 0.92 - 0.62 * local_t + h = np.maximum(h, sm * slat_h) + slat_mask_all = np.maximum(slat_mask_all, sm) + + # Paint + worn steel + soot inside vent + olive = np.array([0.16, 0.18, 0.14], dtype=np.float32) * (0.85 + 0.30 * n1[..., None]) + steel = np.array([0.26, 0.27, 0.26], dtype=np.float32) * (0.85 + 0.30 * n2[..., None]) + void = np.array([0.025, 0.025, 0.027], dtype=np.float32) + + edge_wear = smoothstep(0.05, 0.0, np.abs(d_inner)) * smoothstep(0.35, 0.65, n2) + slat_top_wear = slat_mask_all * smoothstep(0.70, 0.92, h) * smoothstep(0.35, 0.70, n2) + wear = np.clip(np.maximum(edge_wear, slat_top_wear), 0.0, 1.0) + + col = olive * (1.0 - wear[..., None]) + steel * wear[..., None] + # Darken recessed gap + in_void = inner_m * (1.0 - slat_mask_all) + col = col * (1.0 - in_void[..., None]) + void * in_void[..., None] + # Soot darkening on lower slope of slats + col *= (1.0 - 0.45 * slat_mask_all[..., None] * smoothstep(0.85, 0.30, h)[..., None]) + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = outer_m + t["height"] = np.where(outer_m > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.35 + 0.55 * wear + 0.25 * slat_mask_all, 0.0, 1.0) + t["rough"] = np.clip(0.58 - 0.26 * wear + 0.25 * in_void, 0.18, 0.95) + + for bx, by in [(-0.71, -0.63), (0.71, -0.63), (-0.71, 0.63), (0.71, 0.63)]: + add_hex_bolt(t, x, y, bx, by, pocket_r=0.055, head_r=0.036, base_h=0.95) + return t + + +def tile_01_bolted_hatch(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(1) Recessed bolted maintenance hatch.""" + t = new_tile() + n1 = fbm(x, y, 8.0, 4, seed=201) + n2 = fbm(x, y, 28.0, 3, seed=202) + + d_outer = sd_box(x, y, 0.0, 0.0, 0.80, 0.80, r=0.08) + d_groove = np.abs(sd_box(x, y, 0.0, 0.0, 0.66, 0.66, r=0.06)) + d_door = sd_box(x, y, 0.0, 0.0, 0.63, 0.63, r=0.05) + d_latch = sd_box(x, y, 0.32, 0.0, 0.13, 0.22, r=0.03) + d_bar = sd_box(x, y, 0.32, 0.0, 0.045, 0.16, r=0.02) + + outer_m = smoothstep(0.025, -0.025, d_outer) + groove_m = smoothstep(0.032, 0.0, d_groove) + latch_m = smoothstep(0.02, -0.02, d_latch) + bar_m = smoothstep(0.015, -0.015, d_bar) + + h = np.full_like(x, 0.96) + # Bevel down into perimeter seam + h = np.where(d_door < 0.0, 0.88, h) + h -= 0.72 * groove_m + # Recessed latch pocket with grab bar + h = np.where(latch_m > 0.5, 0.22, h) + h = np.where(bar_m > 0.5, 0.86, h) + + base_col = np.array([0.19, 0.21, 0.16], dtype=np.float32) * (0.86 + 0.28 * n1[..., None]) + door_col = np.array([0.22, 0.24, 0.19], dtype=np.float32) * (0.86 + 0.28 * n1[..., None]) + seam_col = np.array([0.04, 0.04, 0.038], dtype=np.float32) + bar_col = np.array([0.34, 0.34, 0.32], dtype=np.float32) + + in_door = smoothstep(0.02, -0.02, d_door) + col = base_col * (1.0 - in_door[..., None]) + door_col * in_door[..., None] + # Paint chip around door edge + chip = smoothstep(0.05, 0.0, np.abs(d_door)) * smoothstep(0.45, 0.68, n2) + col = col * (1.0 - chip[..., None]) + np.array([0.32, 0.33, 0.32], dtype=np.float32) * chip[..., None] + col = col * (1.0 - groove_m[..., None]) + seam_col * groove_m[..., None] + col = col * (1.0 - latch_m[..., None]) + np.array([0.05, 0.05, 0.05], dtype=np.float32) * latch_m[..., None] + col = col * (1.0 - bar_m[..., None]) + bar_col * bar_m[..., None] + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = outer_m + t["height"] = np.where(outer_m > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.30 + 0.55 * chip + 0.60 * bar_m, 0.0, 1.0) + t["rough"] = np.clip(0.56 - 0.24 * chip + 0.25 * groove_m, 0.2, 0.95) + + for bx, by in [(-0.50, -0.50), (0.0, -0.52), (0.50, -0.50), + (-0.50, 0.50), (0.0, 0.52), (0.50, 0.50), + (-0.52, 0.0)]: + add_hex_bolt(t, x, y, bx, by, pocket_r=0.068, head_r=0.044, base_h=0.88) + return t + + +def tile_02_fastener_strip(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(2) 4-bolt recessed fastener strip.""" + t = new_tile() + n1 = fbm(x, y, 12.0, 4, seed=301) + n2 = fbm(x, y, 40.0, 3, seed=302) + + d_strip = sd_box(x, y, 0.0, 0.0, 0.84, 0.28, r=0.08) + d_bevel = sd_box(x, y, 0.0, 0.0, 0.78, 0.22, r=0.05) + mask = smoothstep(0.025, -0.025, d_strip) + + # Raised beveled plate with seam around edge + h = np.where(d_bevel < 0.0, 0.93, 0.82) + h -= 0.45 * smoothstep(0.03, 0.0, np.abs(d_strip)) + + col = np.array([0.21, 0.22, 0.19], dtype=np.float32) * (0.86 + 0.28 * n1[..., None]) + edge_wear = smoothstep(0.05, 0.0, np.abs(d_bevel)) * smoothstep(0.35, 0.70, n2) + col = col * (1.0 - edge_wear[..., None]) + np.array([0.36, 0.37, 0.36], dtype=np.float32) * edge_wear[..., None] + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = mask + t["height"] = np.where(mask > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.45 + 0.45 * edge_wear, 0.0, 1.0) + t["rough"] = np.clip(0.48 - 0.18 * edge_wear, 0.22, 0.9) + + for bx in (-0.57, -0.19, 0.19, 0.57): + add_hex_bolt(t, x, y, bx, 0.0, pocket_r=0.115, head_r=0.075, base_h=0.93) + return t + + +def tile_03_intake_grille(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(3) Slotted intake grille.""" + t = new_tile() + n1 = fbm(x, y, 10.0, 4, seed=401) + n2 = fbm(x, y, 32.0, 3, seed=402) + + d_outer = sd_box(x, y, 0.0, 0.0, 0.80, 0.76, r=0.07) + d_inner = sd_box(x, y, 0.0, 0.0, 0.66, 0.60, r=0.04) + outer_m = smoothstep(0.025, -0.025, d_outer) + inner_m = smoothstep(0.02, -0.02, d_inner) + + h = np.where(inner_m > 0.5, 0.88, 0.96) + h -= 0.38 * smoothstep(0.03, 0.0, np.abs(d_inner)) + + # 6 vertical intake slots (2 rows of 6 or 6 tall slots) + slot_void = np.zeros_like(x) + for sx in np.linspace(-0.48, 0.48, 6): + for sy in (-0.27, 0.27): + ds = sd_box(x, y, float(sx), float(sy), 0.046, 0.21, r=0.038) + sm = smoothstep(0.015, -0.015, ds) + # Chamfered rim then deep void + rim = smoothstep(0.035, 0.0, np.abs(ds - 0.012)) + h = np.where(sm > 0.5, 0.02, h - 0.18 * rim) + slot_void = np.maximum(slot_void, sm) + + plate_col = np.array([0.16, 0.17, 0.16], dtype=np.float32) * (0.85 + 0.3 * n1[..., None]) + rib_wear = smoothstep(0.45, 0.75, n2) * inner_m * (1.0 - slot_void) * 0.45 + col = plate_col * (1.0 - rib_wear[..., None]) + np.array([0.30, 0.31, 0.30], dtype=np.float32) * rib_wear[..., None] + col = col * (1.0 - slot_void[..., None]) + np.array([0.02, 0.02, 0.022], dtype=np.float32) * slot_void[..., None] + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = outer_m + t["height"] = np.where(outer_m > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.55 + 0.35 * rib_wear - 0.5 * slot_void, 0.0, 1.0) + t["rough"] = np.clip(0.46 - 0.15 * rib_wear + 0.4 * slot_void, 0.2, 0.95) + + for rx, ry in [(-0.72, -0.68), (0.72, -0.68), (-0.72, 0.68), (0.72, 0.68)]: + add_domed_rivet(t, x, y, rx, ry, r=0.042, base_h=0.95) + return t + + +def tile_04_rivet_seam(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(4) Rivet panel seam.""" + t = new_tile() + n1 = fbm(x, y, 10.0, 4, seed=501) + n2 = fbm(x, y, 36.0, 3, seed=502) + + d_strip = sd_box(x, y, 0.0, 0.0, 0.84, 0.32, r=0.04) + mask = smoothstep(0.025, -0.025, d_strip) + # Central recessed panel seam groove along y=0, clipped inside strip + groove = smoothstep(0.042, 0.0, np.abs(y)) * mask + h = 0.90 - 0.72 * groove + + col = np.array([0.20, 0.21, 0.17], dtype=np.float32) * (0.85 + 0.3 * n1[..., None]) + chip = smoothstep(0.08, 0.0, np.abs(y)) * smoothstep(0.48, 0.70, n2) * mask + col = col * (1.0 - chip[..., None]) + np.array([0.34, 0.35, 0.34], dtype=np.float32) * chip[..., None] + col = col * (1.0 - groove[..., None]) + np.array([0.04, 0.04, 0.036], dtype=np.float32) * groove[..., None] + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = mask + t["height"] = np.where(mask > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.32 + 0.55 * chip, 0.0, 1.0) + t["rough"] = np.clip(0.56 - 0.24 * chip + 0.30 * groove, 0.2, 0.95) + + for rx in np.linspace(-0.70, 0.70, 6): + add_domed_rivet(t, x, y, float(rx), -0.15, r=0.046, base_h=0.90) + add_domed_rivet(t, x, y, float(rx), 0.15, r=0.046, base_h=0.90) + return t + + +def tile_05_welded_patch(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(5) Welded armor repair patch.""" + t = new_tile() + n1 = fbm(x, y, 9.0, 4, seed=601) + n2 = fbm(x, y, 42.0, 3, seed=602) + + # Slightly rotated/chamfered patch shape + ca, sa = np.cos(0.08), np.sin(0.08) + xr = x * ca - y * sa + yr = x * sa + y * ca + d_patch = sd_box(xr, yr, 0.0, 0.0, 0.64, 0.50, r=0.05) + # Irregular outer weld apron + d_outer = d_patch - 0.12 + outer_m = smoothstep(0.025, -0.025, d_outer) + patch_m = smoothstep(0.018, -0.018, d_patch) + + # Weld bead ripple along perimeter d_patch ~= 0 + bead_band = smoothstep(0.085, 0.0, np.abs(d_patch - 0.01)) + # Ripple along perimeter coordinate + ripple = 0.5 + 0.5 * np.sin((xr + yr) * 48.0 + n2 * 6.0) + bead_h = 0.72 + 0.27 * bead_band * (0.65 + 0.35 * ripple) + + h = np.where(patch_m > 0.5, 0.92 - 0.03 * n1, 0.68) + h = np.maximum(h, bead_h * bead_band) + + patch_col = np.array([0.23, 0.24, 0.21], dtype=np.float32) * (0.85 + 0.30 * n1[..., None]) + weld_col = np.array([0.38, 0.36, 0.33], dtype=np.float32) * (0.80 + 0.35 * ripple[..., None]) + # Heat-affected straw/blue oxide halo outside weld + haz = smoothstep(0.14, 0.02, np.abs(d_patch - 0.03)) * (1.0 - bead_band) + haz_col = np.array([0.14, 0.12, 0.14], dtype=np.float32) + + col = haz_col * haz[..., None] + patch_col * patch_m[..., None] + col = col * (1.0 - bead_band[..., None]) + weld_col * bead_band[..., None] + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = np.clip(np.maximum(patch_m, bead_band * 0.95 + haz * 0.75) * outer_m, 0.0, 1.0) + t["height"] = np.where(t["alpha"] > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.35 + 0.58 * bead_band, 0.0, 1.0) + t["rough"] = np.clip(0.55 - 0.28 * bead_band, 0.18, 0.92) + return t + + +def tile_06_lift_lug(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(6) Recessed lift-lug pocket.""" + t = new_tile() + n1 = fbm(x, y, 11.0, 4, seed=701) + n2 = fbm(x, y, 34.0, 3, seed=702) + + d_outer = sd_box(x, y, 0.0, 0.0, 0.74, 0.74, r=0.10) + d_pocket = sd_box(x, y, 0.0, 0.0, 0.52, 0.52, r=0.09) + outer_m = smoothstep(0.025, -0.025, d_outer) + pocket_m = smoothstep(0.02, -0.02, d_pocket) + + # Chamfered pit wall + wall_t = np.clip(-d_pocket / 0.14, 0.0, 1.0) + pit_h = 0.94 - 0.84 * smoothstep(0.0, 1.0, wall_t) + h = np.where(pocket_m > 0.5, pit_h, 0.96) + + # Cylindrical steel crossbar along X (spanning the recessed pocket) + d_bar_y = np.abs(y) / 0.135 + d_bar_x = np.abs(x) - 0.50 + bar_m = smoothstep(1.06, 0.94, d_bar_y) * smoothstep(0.02, -0.02, d_bar_x) + cyl_z = np.sqrt(np.maximum(1.0 - np.clip(d_bar_y, 0.0, 1.0) ** 2, 0.0)) + bar_h = 0.45 + 0.50 * cyl_z + h = np.where(bar_m > 0.5, np.maximum(h, bar_h), h) + + flange_col = np.array([0.18, 0.19, 0.16], dtype=np.float32) * (0.85 + 0.30 * n1[..., None]) + pit_col = np.array([0.055, 0.056, 0.055], dtype=np.float32) * (0.8 + 0.3 * n1[..., None]) + bar_col = np.array([0.36, 0.37, 0.36], dtype=np.float32) * (0.85 + 0.25 * n2[..., None]) + + col = flange_col * (1.0 - pocket_m[..., None]) + pit_col * pocket_m[..., None] + col = col * (1.0 - bar_m[..., None]) + bar_col * bar_m[..., None] + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = outer_m + t["height"] = np.where(outer_m > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.35 + 0.58 * bar_m, 0.0, 1.0) + t["rough"] = np.clip(0.55 - 0.28 * bar_m + 0.20 * pocket_m * (1.0 - bar_m), 0.18, 0.95) + return t + + +def tile_07_hazard_chevron(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(7) Weathered hazard caution chevron strip.""" + t = new_tile() + n1 = fbm(x, y, 8.0, 4, seed=801) + n2 = fbm(x, y, 34.0, 4, seed=802) + + d_strip = sd_box(x, y, 0.0, 0.0, 0.84, 0.26, r=0.025) + d_inner = sd_box(x, y, 0.0, 0.0, 0.78, 0.20, r=0.015) + strip_m = smoothstep(0.02, -0.02, d_strip) + inner_m = smoothstep(0.015, -0.015, d_inner) + + # Diagonal stripes + stripe_wave = np.sin((x * 2.2 + y * 2.2) * np.pi * 2.4) + is_yellow = smoothstep(-0.08, 0.08, stripe_wave) + + yellow = np.array([0.68, 0.44, 0.06], dtype=np.float32) + black = np.array([0.055, 0.055, 0.052], dtype=np.float32) + steel = np.array([0.28, 0.29, 0.28], dtype=np.float32) + + col = black * (1.0 - is_yellow[..., None]) + yellow * is_yellow[..., None] + # Thin dark border frame + col = black * (1.0 - inner_m[..., None]) + col * inner_m[..., None] + # Grime + paint chips + chip = smoothstep(0.62, 0.69, n2) + col *= (0.78 + 0.35 * n1[..., None]) + col = col * (1.0 - chip[..., None] * 0.75) + steel * (chip[..., None] * 0.75) + + # Subtle paint film thickness + border recess + h = 0.98 - 0.08 * (1.0 - inner_m) - 0.04 * chip + edge_wear = smoothstep(0.06, 0.0, np.abs(d_strip)) * smoothstep(0.55, 0.72, n2) + alpha = np.clip(strip_m * (1.0 - 0.80 * edge_wear), 0.0, 1.0) + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = np.clip(alpha, 0.0, 1.0) + t["height"] = np.where(strip_m > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.15 + 0.65 * chip, 0.0, 1.0) + t["rough"] = np.clip(0.60 - 0.25 * chip, 0.25, 0.92) + return t + + +# --------------------------------------------------------------------------- +# Row 2: Stencils & Emblems +# --------------------------------------------------------------------------- + +def _sd_digit_0(x: np.ndarray, y: np.ndarray, cx: float, cy: float) -> np.ndarray: + d_out = sd_box(x, y, cx, cy, 0.28, 0.46, r=0.14) + d_in = sd_box(x, y, cx, cy, 0.11, 0.28, r=0.05) + d = np.maximum(d_out, -d_in) + # Stencil bridge gaps top/bottom + gap = np.abs(x - cx) - 0.032 + d_bridge = np.maximum(gap, 0.25 - np.abs(y - cy)) + return np.maximum(d, -d_bridge) + + +def _sd_digit_3(x: np.ndarray, y: np.ndarray, cx: float, cy: float) -> np.ndarray: + d_out = sd_box(x, y, cx, cy, 0.28, 0.46, r=0.14) + d_in_top = sd_box(x, y, cx - 0.04, cy - 0.20, 0.16, 0.11, r=0.03) + d_in_bot = sd_box(x, y, cx - 0.04, cy + 0.20, 0.16, 0.11, r=0.03) + d_open_l = sd_box(x, y, cx - 0.24, cy, 0.16, 0.15, r=0.0) + d = np.maximum(d_out, -np.minimum(np.minimum(d_in_top, d_in_bot), d_open_l)) + # Stencil bridge on right spine + gap = np.maximum(np.abs(y - cy) - 0.028, (cx - 0.05) - x) + return np.maximum(d, -gap) + + +def _sd_digit_7(x: np.ndarray, y: np.ndarray, cx: float, cy: float) -> np.ndarray: + d_top = sd_box(x, y, cx, cy - 0.37, 0.28, 0.09, r=0.02) + # Slanted leg from (cx+0.20, cy-0.36) to (cx-0.08, cy+0.39) + d_leg = sd_segment(x, y, cx + 0.18, cy - 0.34, cx - 0.07, cy + 0.38) - 0.088 + d = np.minimum(d_top, d_leg) + # Stencil gap between top bar & leg + gap = sd_box(x, y, cx + 0.12, cy - 0.25, 0.20, 0.025, r=0.0) + return np.maximum(d, -gap) + + +def _finish_stencil( + x: np.ndarray, + y: np.ndarray, + mask: np.ndarray, + paint_col: np.ndarray, + seed: int, +) -> dict[str, np.ndarray]: + t = new_tile() + n1 = fbm(x, y, 10.0, 4, seed=seed) + n2 = fbm(x, y, 40.0, 4, seed=seed + 1) + + # Flaking & scratching across stencil paint + flake = smoothstep(0.58, 0.72, n2) + scratches = smoothstep(0.68, 0.74, fbm(x * 0.4 + y * 1.8, y * 0.4, 24.0, 3, seed=seed + 2)) + wear = np.clip(flake * 0.85 + scratches * 0.7, 0.0, 1.0) + + alpha = np.clip(mask * (1.0 - wear * 0.85), 0.0, 1.0) + col = paint_col * (0.82 + 0.25 * n1[..., None]) + h = 1.0 - 0.02 * mask * (1.0 - wear) - 0.04 * (1.0 - mask) + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = alpha + t["height"] = np.where(alpha > 0.02, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.full_like(x, 0.08) + t["rough"] = np.clip(0.68 + 0.15 * n1, 0.4, 0.9) + return t + + +def tile_08_stencil_03(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(8) Tactical stencil '03'.""" + d = np.minimum(_sd_digit_0(x, y, -0.36, 0.0), _sd_digit_3(x, y, 0.36, 0.0)) + mask = smoothstep(0.02, -0.02, d) + return _finish_stencil(x, y, mask, np.array([0.74, 0.71, 0.62], dtype=np.float32), seed=901) + + +def tile_09_stencil_07(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(9) Tactical stencil '07'.""" + d = np.minimum(_sd_digit_0(x, y, -0.36, 0.0), _sd_digit_7(x, y, 0.36, 0.0)) + mask = smoothstep(0.02, -0.02, d) + return _finish_stencil(x, y, mask, np.array([0.74, 0.71, 0.62], dtype=np.float32), seed=1001) + + +def tile_10_radiation_warning(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(10) Radiation / thermal warning stencil.""" + r = np.sqrt(x * x + y * y) + ang = np.arctan2(y, x) + + # Outer dashed warning ring + d_ring = np.abs(r - 0.66) - 0.065 + ring_seg = np.abs(((ang + np.pi) / (np.pi / 3.0)) % 1.0 - 0.5) - 0.34 + d_ring = np.maximum(d_ring, ring_seg * 0.5) + + # Central dot + 3 trefoil blades + d_core = r - 0.11 + blade_annulus = np.maximum(0.18 - r, r - 0.52) + blade_ang = np.cos(3.0 * (ang + np.pi / 6.0)) + d_blades = np.maximum(blade_annulus, (0.45 - blade_ang) * 0.28) + + d = np.minimum(np.minimum(d_ring, d_core), d_blades) + mask = smoothstep(0.02, -0.02, d) + return _finish_stencil(x, y, mask, np.array([0.78, 0.36, 0.09], dtype=np.float32), seed=1101) + + +def tile_11_faction_emblem(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(11) Faction chevron emblem.""" + ax = np.abs(x) + # Double military chevron + diamond center + d1 = np.abs((y + 0.14) + ax * 0.85) - 0.085 + d1 = np.maximum(d1, ax - 0.68) + d2 = np.abs((y - 0.22) + ax * 0.85) - 0.065 + d2 = np.maximum(d2, ax - 0.52) + d_diamond = (ax * 0.9 + np.abs(y + 0.42)) - 0.18 + d_chev = np.minimum(d1, d2) + + m_chev = smoothstep(0.02, -0.02, d_chev) + m_dia = smoothstep(0.02, -0.02, d_diamond) + mask = np.maximum(m_chev, m_dia) + + t = _finish_stencil(x, y, mask, np.array([0.76, 0.72, 0.60], dtype=np.float32), seed=1201) + # Signal orange center diamond + orange = np.array([0.74, 0.27, 0.10], dtype=np.float32) + t["rgb"] = t["rgb"] * (1.0 - m_dia[..., None]) + orange * m_dia[..., None] + return t + + +# --------------------------------------------------------------------------- +# Row 3: Dynamic combat hits (12..15) +# --------------------------------------------------------------------------- + +def tile_12_ap_penetration(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(12) Deep AP autocannon penetration hole (rolled metallic rim + black bore + hot rim).""" + t = new_tile() + n1 = fbm(x, y, 7.0, 4, seed=1301) + n2 = fbm(x, y, 24.0, 4, seed=1302) + ang = np.arctan2(y, x) + # Jagged petal modulation around bore + jagged = 0.065 * np.sin(ang * 7.0 + 1.1) + 0.045 * np.cos(ang * 13.0 - 0.4) + 0.09 * (n2 - 0.5) + r = np.sqrt(x * x + y * y) + jagged + + bore_r = 0.28 + rim_r = 0.44 + scorch_r = 0.82 + + bore_m = smoothstep(bore_r + 0.03, bore_r - 0.02, r) + rim_m = smoothstep(0.10, 0.0, np.abs(r - (bore_r + 0.05))) + scorch_m = smoothstep(scorch_r, bore_r * 0.8, r) * (0.55 + 0.45 * n1) + + # Height: flush 1.0 outside -> raised/rolled rim at 0.96 -> sharp drop into 0.0 pitch-black bore + hole_wall = smoothstep(bore_r - 0.04, rim_r, r) + h = np.clip(hole_wall * 0.96 + 0.04 * smoothstep(rim_r + 0.12, rim_r, r), 0.0, 1.0) + h = np.where(r > rim_r + 0.12, 1.0, h) + + soot_col = np.array([0.04, 0.035, 0.032], dtype=np.float32) + steel_col = np.array([0.52, 0.54, 0.56], dtype=np.float32) * (0.75 + 0.45 * n2[..., None]) + bore_col = np.array([0.012, 0.010, 0.010], dtype=np.float32) + + col = soot_col * (1.0 - rim_m[..., None]) + steel_col * rim_m[..., None] + col = col * (1.0 - bore_m[..., None]) + bore_col * bore_m[..., None] + + # Alpha: opaque in bore + metal rim, softly feathered soot halo + alpha = np.clip(np.maximum(np.maximum(bore_m, rim_m), scorch_m * 0.88), 0.0, 1.0) + # Keep zero bleed at outer margin + border = smoothstep(0.92, 0.78, np.maximum(np.abs(x), np.abs(y))) + alpha *= border + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = alpha + t["height"] = np.where(alpha > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(rim_m * 0.94 + bore_m * 0.10, 0.0, 1.0) + t["rough"] = np.clip(0.92 - rim_m * 0.66, 0.22, 0.96) + return t + + +def tile_13_shrapnel_gouge(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(13) Diagonal shrapnel/flak armor gouge.""" + t = new_tile() + n1 = fbm(x, y, 8.0, 4, seed=1401) + n2 = fbm(x, y, 28.0, 4, seed=1402) + + # Rotate -35 degrees for diagonal ricochet trench + ca, sa = np.cos(-0.62), np.sin(-0.62) + u = x * ca - y * sa + v = x * sa + y * ca + 0.04 * (n2 - 0.5) + + # Tapered V-trough from u=-0.62 to u=+0.62 + d_trench = sd_segment(u, v, -0.58, 0.0, 0.58, 0.0) + width = 0.13 + 0.05 * np.clip((u + 0.58) / 1.16, 0.0, 1.0) + trough_t = np.clip(1.0 - d_trench / width, 0.0, 1.0) + burr_m = smoothstep(0.06, 0.0, np.abs(d_trench - width)) + + h = 1.0 - 0.88 * smoothstep(0.0, 1.0, trough_t) + # Upturned burr ridge at edge + h = np.clip(h + 0.04 * burr_m, 0.0, 1.0) + + soot = np.array([0.045, 0.04, 0.036], dtype=np.float32) + torn_steel = np.array([0.50, 0.52, 0.54], dtype=np.float32) * (0.75 + 0.45 * n2[..., None]) + furrow_dark = np.array([0.09, 0.09, 0.095], dtype=np.float32) + + trench_m = smoothstep(0.05, 0.25, trough_t) + col = soot * (1.0 - trench_m[..., None]) + torn_steel * trench_m[..., None] + col = col * (1.0 - smoothstep(0.60, 0.95, trough_t)[..., None] * 0.7) + furrow_dark * (smoothstep(0.60, 0.95, trough_t)[..., None] * 0.7) + col = col * (1.0 - burr_m[..., None] * 0.65) + torn_steel * (burr_m[..., None] * 0.65) + + scorch_halo = smoothstep(0.42, 0.08, d_trench) * (0.5 + 0.5 * n1) + alpha = np.clip(np.maximum(trench_m, np.maximum(burr_m, scorch_halo * 0.85)), 0.0, 1.0) + border = smoothstep(0.92, 0.78, np.maximum(np.abs(x), np.abs(y))) + alpha *= border + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = alpha + t["height"] = np.where(alpha > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(np.maximum(trench_m, burr_m) * 0.90, 0.0, 1.0) + t["rough"] = np.clip(0.90 - np.maximum(trench_m, burr_m) * 0.62, 0.24, 0.95) + return t + + +def tile_14_plasma_crater(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(14) Molten plasma burn crater.""" + t = new_tile() + n1 = fbm(x, y, 7.5, 4, seed=1501) + n2 = fbm(x, y, 22.0, 4, seed=1502) + r = np.sqrt(x * x + y * y) + 0.08 * (n2 - 0.5) + + crater_r = 0.44 + bowl_m = smoothstep(crater_r + 0.04, crater_r - 0.08, r) + rim_m = smoothstep(0.08, 0.0, np.abs(r - crater_r)) + scorch_m = smoothstep(0.84, 0.36, r) * (0.5 + 0.5 * n1) + + # Slag ripples in bowl + crisp crater rim + ripples = 0.5 + 0.5 * np.sin(r * 34.0 + n2 * 4.0) + bowl_depth = smoothstep(crater_r, 0.04, r) + h = 1.0 - 0.88 * bowl_depth + 0.08 * ripples * bowl_m + 0.06 * rim_m + + carbon = np.array([0.035, 0.030, 0.028], dtype=np.float32) + slag = np.array([0.22, 0.16, 0.14], dtype=np.float32) * (0.8 + 0.4 * ripples[..., None]) + molten_lip = np.array([0.46, 0.38, 0.32], dtype=np.float32) + + col = carbon * (1.0 - bowl_m[..., None]) + slag * bowl_m[..., None] + col = col * (1.0 - rim_m[..., None] * 0.7) + molten_lip * (rim_m[..., None] * 0.7) + + alpha = np.clip(np.maximum(bowl_m, np.maximum(rim_m, scorch_m * 0.90)), 0.0, 1.0) + border = smoothstep(0.92, 0.78, np.maximum(np.abs(x), np.abs(y))) + alpha *= border + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = alpha + t["height"] = np.where(alpha > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(bowl_m * 0.78 + rim_m * 0.85, 0.0, 1.0) + t["rough"] = np.clip(0.92 - bowl_m * 0.50 - rim_m * 0.45, 0.28, 0.96) + return t + + +def tile_15_blast_scorch(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(15) Radial blast scorch mark.""" + t = new_tile() + n1 = fbm(x, y, 6.0, 4, seed=1601) + n2 = fbm(x, y, 20.0, 4, seed=1602) + ang = np.arctan2(y, x) + r = np.sqrt(x * x + y * y) + + # Radial blast rays + rays = 0.55 + 0.45 * value_noise(np.cos(ang) * 3.0, np.sin(ang) * 3.0, 3.5, seed=1603) + rays *= (0.7 + 0.3 * np.sin(ang * 11.0 + n2 * 3.0)) + r_eff = r / np.maximum(rays, 0.35) + + scorch = smoothstep(0.95, 0.08, r_eff) * (0.65 + 0.35 * n1) + pock = smoothstep(0.24, 0.05, r + 0.05 * (n2 - 0.5)) + h = 1.0 - 0.45 * pock - 0.04 * scorch + + soot = np.array([0.032, 0.028, 0.025], dtype=np.float32) + ash = np.array([0.11, 0.095, 0.082], dtype=np.float32) + col = soot * (1.0 - pock[..., None] * 0.35) + ash * (pock[..., None] * 0.35) + + border = smoothstep(0.93, 0.78, np.maximum(np.abs(x), np.abs(y))) + alpha = np.clip(scorch * 0.92 * border, 0.0, 1.0) + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = alpha + t["height"] = np.where(alpha > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.05 + 0.25 * pock, 0.0, 1.0) + t["rough"] = np.clip(0.94 - 0.20 * pock, 0.65, 0.98) + return t + + +# --------------------------------------------------------------------------- +# Normal map, AO, color dilation, and atlas assembly +# --------------------------------------------------------------------------- + +def compute_normal_map(height: np.ndarray, strength: float = 5.5) -> np.ndarray: + """Sobel tangent-space normal map matching OpenGL/Godot (+X right, +Y down, +Z out).""" + h = np.pad(height, 1, mode="edge") + # Sobel X (+right) and Y (+down) + dx = ((h[:-2, 2:] + 2.0 * h[1:-1, 2:] + h[2:, 2:]) + - (h[:-2, :-2] + 2.0 * h[1:-1, :-2] + h[2:, :-2])) * 0.125 + dy = ((h[2:, :-2] + 2.0 * h[2:, 1:-1] + h[2:, 2:]) + - (h[:-2, :-2] + 2.0 * h[:-2, 1:-1] + h[:-2, 2:])) * 0.125 + nx = -dx * strength + ny = -dy * strength + nz = np.ones_like(nx) + inv_len = 1.0 / np.sqrt(nx * nx + ny * ny + nz * nz + 1e-12) + return np.stack([nx * inv_len * 0.5 + 0.5, + ny * inv_len * 0.5 + 0.5, + nz * inv_len * 0.5 + 0.5], axis=-1) + + +def compute_height_ao(height: np.ndarray) -> np.ndarray: + """Fast multi-radius horizon/cavity AO from the heightfield.""" + ao = np.ones_like(height, dtype=np.float32) + dirs = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, 1), (1, -1), (-1, -1)] + radii = (2, 5, 10) + occ_sum = np.zeros_like(height, dtype=np.float32) + count = 0 + h_pad = np.pad(height, 12, mode="edge") + H, W = height.shape + for r in radii: + for dx, dy in dirs: + ox = 12 + dx * r + oy = 12 + dy * r + sample_h = h_pad[oy : oy + H, ox : ox + W] + diff = np.maximum(sample_h - height, 0.0) + occ_sum += np.clip(diff * 2.8, 0.0, 1.0) + count += 1 + cavity = occ_sum / float(count) + # Also darken deep recesses naturally + ao = np.clip((1.0 - cavity * 1.35) * (0.30 + 0.70 * height), 0.08, 1.0) + return ao + + +def dilate_albedo(rgb: np.ndarray, alpha: np.ndarray, steps: int = 8) -> np.ndarray: + """Propagate opaque RGB into transparent pixels to eliminate bilinear dark fringes.""" + out = rgb.copy() + mask = alpha > 0.04 + for _ in range(steps): + if np.all(mask): + break + acc = np.zeros_like(out) + wsum = np.zeros(mask.shape, dtype=np.float32) + p_rgb = np.pad(out, ((1, 1), (1, 1), (0, 0)), mode="edge") + p_m = np.pad(mask.astype(np.float32), ((1, 1), (1, 1)), mode="edge") + H, W = mask.shape + for dy in (-1, 0, 1): + for dx in (-1, 0, 1): + if dx == 0 and dy == 0: + continue + m_nb = p_m[1 + dy : 1 + dy + H, 1 + dx : 1 + dx + W] + acc += p_rgb[1 + dy : 1 + dy + H, 1 + dx : 1 + dx + W] * m_nb[..., None] + wsum += m_nb + fill = (~mask) & (wsum > 0.0) + out[fill] = acc[fill] / wsum[fill, None] + mask = mask | fill + return out + + +def main() -> int: + OUT_DIR.mkdir(parents=True, exist_ok=True) + x, y = tile_coords() + + builders = [ + tile_00_louvered_vent, + tile_01_bolted_hatch, + tile_02_fastener_strip, + tile_03_intake_grille, + tile_04_rivet_seam, + tile_05_welded_patch, + tile_06_lift_lug, + tile_07_hazard_chevron, + tile_08_stencil_03, + tile_09_stencil_07, + tile_10_radiation_warning, + tile_11_faction_emblem, + tile_12_ap_penetration, + tile_13_shrapnel_gouge, + tile_14_plasma_crater, + tile_15_blast_scorch, + ] + + atlas_albedo = np.zeros((ATLAS_SIZE, ATLAS_SIZE, 4), dtype=np.uint8) + atlas_normal = np.zeros((ATLAS_SIZE, ATLAS_SIZE, 3), dtype=np.uint8) + atlas_ormh = np.zeros((ATLAS_SIZE, ATLAS_SIZE, 4), dtype=np.uint8) + + for idx, fn in enumerate(builders): + row = idx // GRID + col = idx % GRID + t = fn(x, y) + + rgb_dilated = dilate_albedo(t["rgb"], t["alpha"], steps=12) + nrm = compute_normal_map(t["height"], strength=6.0) + ao = compute_height_ao(t["height"]) + + y0, y1 = row * TILE_SIZE, (row + 1) * TILE_SIZE + x0, x1 = col * TILE_SIZE, (col + 1) * TILE_SIZE + + albedo_rgba = np.dstack([rgb_dilated, t["alpha"]]) + ormh_rgba = np.dstack([ao, t["rough"], t["metal"], t["height"]]) + + atlas_albedo[y0:y1, x0:x1] = np.clip(np.round(albedo_rgba * 255.0), 0, 255).astype(np.uint8) + atlas_normal[y0:y1, x0:x1] = np.clip(np.round(nrm * 255.0), 0, 255).astype(np.uint8) + atlas_ormh[y0:y1, x0:x1] = np.clip(np.round(ormh_rgba * 255.0), 0, 255).astype(np.uint8) + + Image.fromarray(atlas_albedo, mode="RGBA").save(OUT_DIR / "decal_atlas_albedo.png") + Image.fromarray(atlas_normal, mode="RGB").save(OUT_DIR / "decal_atlas_normal.png") + Image.fromarray(atlas_ormh, mode="RGBA").save(OUT_DIR / "decal_atlas_ormh.png") + + print(f"Wrote 1024x1024 decal atlas textures to {OUT_DIR}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/decals/previews/visual_substrate_preview.png b/tools/decals/previews/visual_substrate_preview.png new file mode 100644 index 0000000..5ded766 Binary files /dev/null and b/tools/decals/previews/visual_substrate_preview.png differ diff --git a/tools/maps/sion/bake_sion.py b/tools/maps/sion/bake_sion.py new file mode 100644 index 0000000..18a2658 --- /dev/null +++ b/tools/maps/sion/bake_sion.py @@ -0,0 +1,2272 @@ +#!/usr/bin/env python3 +""" +Offline Sion, Switzerland real-world map baker for RustToDust. +Fetches swissALTI3D DEM + swissBUILDINGS3D 3.0 LOD2 from Swisstopo STAC +(plus Swisstopo TLM WMS surface masks), caches raw downloads in $TEMP/sion-cache, +and bakes a 3072m x 3072m (6x6 grid of 512m tiles) playable arena: + - assets/maps/sion/heightmap.f32 (1025x1025 float32, 3.0m grid, 3072m x 3072m) + - assets/maps/sion/terrain_surface.png (2048x2048 RGB surface albedo) + - assets/maps/sion/metadata.json + - assets/maps/sion/buildings_manifest.json + - assets/maps/sion/tiles/lod2__.glb (semantic LOD2 per non-empty tile) + - assets/maps/sion/tiles/lod1__.glb (procedural LOD1 per non-empty tile) + - assets/maps/sion/tiles/col__.bin (packed RCOL v1 collision trimesh) +""" + +from __future__ import annotations + +import argparse +import ctypes +import glob +import hashlib +import json +import math +import os +import re +import struct +import urllib.parse +import urllib.request +import zipfile +import zlib +from collections import Counter, defaultdict +from pathlib import Path + +import imagecodecs +import numpy as np +import pygltflib +import pyogrio +import pyproj +import shapely +from scipy.ndimage import ( + binary_closing, + binary_dilation, + binary_opening, + gaussian_filter, + map_coordinates, + maximum_filter1d, + zoom, +) +from shapely.geometry import Polygon, box +from shapely.ops import unary_union +import tifffile + +# --------------------------------------------------------------------------- +# Arena & Swisstopo constants +# --------------------------------------------------------------------------- +ARENA_SIZE_M = 3072.0 +HALF_EXTENT_M = 1536.0 +GRID_RES = 6145 +CELL_SIZE_M = ARENA_SIZE_M / (GRID_RES - 1) # 0.5m exact +TILE_GRID = 16 +TILE_SIZE_M = ARENA_SIZE_M / TILE_GRID # 192.0m exact +BUILDING_TILE_GRID = 6 +BUILDING_TILE_SIZE_M = ARENA_SIZE_M / BUILDING_TILE_GRID # 512.0m legacy until Cut 13b + +SURFACE_TEX_RES = 4096 +SURFACE_MASK_RES = 2048 + +# Centered around Valere & Tourbillon twin citadels to frame: +# - Valere & Tourbillon fortress hills +# - Full Sion Old Town +# - Railway & industrial yards (south-west / central) +# - Rhone river corridor + highway bridges (south/east-to-west) +# - Terraced alpine hillsides & vineyards (north/east/south) +DEFAULT_CENTER_E = 2594150.0 +DEFAULT_CENTER_N = 1120050.0 + +STAC_ALTI_URL = "https://data.geo.admin.ch/api/stac/v0.9/collections/ch.swisstopo.swissalti3d/items" +STAC_BLDG_URL = "https://data.geo.admin.ch/api/stac/v0.9/collections/ch.swisstopo.swissbuildings3d_3_0/items" +WMS_BASE_URL = "https://wms.geo.admin.ch/" + +SKIRT_DEPTH_M = 4.0 +MAX_LOD1_TRIS = 275_000 +MAX_TILES_GLB_BYTES = 28_000_000 +MAX_SURFACE_PNG_BYTES = 14_000_000 +MAX_TOTAL_ASSETS_BYTES = 85_000_000 + + +# --------------------------------------------------------------------------- +# GDAL / OGR ctypes wrapper (uses pyogrio's bundled GDAL 3.12+ DLL) +# --------------------------------------------------------------------------- +class OgrReader: + def __init__(self) -> None: + libs_dir = os.path.abspath(os.path.join(os.path.dirname(pyogrio.__file__), "..", "pyogrio.libs")) + os.add_dll_directory(libs_dir) + dlls = glob.glob(os.path.join(libs_dir, "gdal-*.dll")) + if not dlls: + raise RuntimeError(f"Could not locate gdal-*.dll in {libs_dir}") + g = ctypes.CDLL(dlls[0]) + g.GDALAllRegister() + g.GDALOpenEx.argtypes = [ctypes.c_char_p, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] + g.GDALOpenEx.restype = ctypes.c_void_p + g.GDALClose.argtypes = [ctypes.c_void_p] + g.GDALDatasetGetLayerByName.argtypes = [ctypes.c_void_p, ctypes.c_char_p] + g.GDALDatasetGetLayerByName.restype = ctypes.c_void_p + g.OGR_L_SetSpatialFilterRect.argtypes = [ + ctypes.c_void_p, ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.c_double + ] + g.OGR_L_GetNextFeature.argtypes = [ctypes.c_void_p] + g.OGR_L_GetNextFeature.restype = ctypes.c_void_p + g.OGR_F_Destroy.argtypes = [ctypes.c_void_p] + g.OGR_F_GetFieldIndex.argtypes = [ctypes.c_void_p, ctypes.c_char_p] + g.OGR_F_GetFieldIndex.restype = ctypes.c_int + g.OGR_F_GetFieldAsString.argtypes = [ctypes.c_void_p, ctypes.c_int] + g.OGR_F_GetFieldAsString.restype = ctypes.c_char_p + g.OGR_F_GetFieldAsDouble.argtypes = [ctypes.c_void_p, ctypes.c_int] + g.OGR_F_GetFieldAsDouble.restype = ctypes.c_double + g.OGR_F_GetGeometryRef.argtypes = [ctypes.c_void_p] + g.OGR_F_GetGeometryRef.restype = ctypes.c_void_p + g.OGR_G_WkbSize.argtypes = [ctypes.c_void_p] + g.OGR_G_WkbSize.restype = ctypes.c_int + g.OGR_G_ExportToIsoWkb.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p] + g.OGR_G_ExportToIsoWkb.restype = ctypes.c_int + self.g = g + + def read_layer( + self, + gdb_path: str, + layer_name: str, + bbox: tuple[float, float, float, float], + fields: list[str], + ) -> list[tuple[dict[str, str | float], list[np.ndarray]]]: + ds = self.g.GDALOpenEx(gdb_path.encode("utf-8"), 0x04, None, None, None) + if not ds: + raise RuntimeError(f"Failed to open GDB: {gdb_path}") + try: + lyr = self.g.GDALDatasetGetLayerByName(ds, layer_name.encode("utf-8")) + if not lyr: + raise RuntimeError(f"Layer {layer_name} not found in {gdb_path}") + self.g.OGR_L_SetSpatialFilterRect(lyr, *bbox) + out = [] + field_indices: dict[str, int] | None = None + while True: + feat = self.g.OGR_L_GetNextFeature(lyr) + if not feat: + break + try: + if field_indices is None: + field_indices = { + fn: self.g.OGR_F_GetFieldIndex(feat, fn.encode("utf-8")) for fn in fields + } + attrs: dict[str, str | float] = {} + for fn, idx in field_indices.items(): + if idx < 0: + attrs[fn] = "" + elif fn in ("DACH_MIN", "DACH_MAX", "GELAENDEPUNKT", "GESAMTHOEHE"): + attrs[fn] = float(self.g.OGR_F_GetFieldAsDouble(feat, idx)) + else: + raw = self.g.OGR_F_GetFieldAsString(feat, idx) + attrs[fn] = raw.decode("utf-8", "replace") if raw else "" + geom = self.g.OGR_F_GetGeometryRef(feat) + if not geom: + continue + sz = self.g.OGR_G_WkbSize(geom) + if sz <= 0: + continue + buf = ctypes.create_string_buffer(sz) + self.g.OGR_G_ExportToIsoWkb(geom, 1, buf) + faces = parse_iso_wkb_outer_rings(buf.raw) + if faces: + out.append((attrs, faces)) + finally: + self.g.OGR_F_Destroy(feat) + return out + finally: + self.g.GDALClose(ds) + + +def parse_iso_wkb_outer_rings(wkb: bytes) -> list[np.ndarray]: + """Parse ISO WKB (TINZ / PolyhedralSurfaceZ / MultiPolygonZ / PolygonZ / TriangleZ) -> outer ring arrays (N,3).""" + faces: list[np.ndarray] = [] + mv = memoryview(wkb) + + def read_geom(p: int) -> int: + bo = wkb[p] + endian = "<" if bo == 1 else ">" + (wt,) = struct.unpack_from(endian + "I", wkb, p + 1) + p += 5 + has_z = (wt // 1000) in (1, 3) or (wt & 0x80000000) != 0 + base = wt % 1000 if wt < 4000 else (wt & 0xFF) + dims = 3 if has_z else 2 + if base in (3, 17): # Polygon or Triangle + (nrings,) = struct.unpack_from(endian + "I", wkb, p) + p += 4 + for ri in range(nrings): + (npts,) = struct.unpack_from(endian + "I", wkb, p) + p += 4 + pts = np.frombuffer(mv[p : p + npts * dims * 8], dtype=endian + "f8").reshape(npts, dims) + p += npts * dims * 8 + if ri == 0 and npts >= 3: + if dims == 2: + pts = np.column_stack([pts, np.zeros(npts, dtype=np.float64)]) + # Strip closing duplicate point if present + if np.allclose(pts[0], pts[-1], atol=1e-7) and len(pts) > 3: + pts = pts[:-1] + if len(pts) >= 3: + faces.append(pts.copy()) + elif base in (6, 7, 15, 16): # MultiPolygon, GeometryCollection, PolyhedralSurface, TIN + (ngeoms,) = struct.unpack_from(endian + "I", wkb, p) + p += 4 + for _ in range(ngeoms): + p = read_geom(p) + else: + raise ValueError(f"Unsupported ISO WKB geometry type: {wt}") + return p + + read_geom(0) + return faces + + +# --------------------------------------------------------------------------- +# STAC query & download cache +# --------------------------------------------------------------------------- +def download_cached(url: str, dest: Path) -> Path: + dest.parent.mkdir(parents=True, exist_ok=True) + if dest.exists() and dest.stat().st_size > 0: + return dest + tmp = dest.with_suffix(dest.suffix + ".part") + print(f" [STAC download] {url} -> {dest.name}") + urllib.request.urlretrieve(url, str(tmp)) + tmp.replace(dest) + return dest + + +def fetch_stac_items(base_url: str, wgs84_bbox: tuple[float, float, float, float]) -> list[dict]: + bbox_str = ",".join(f"{v:.6f}" for v in wgs84_bbox) + items: list[dict] = [] + url: str | None = f"{base_url}?bbox={bbox_str}&limit=100" + while url: + with urllib.request.urlopen(url, timeout=30) as resp: + data = json.loads(resp.read().decode("utf-8")) + items.extend(data.get("features", [])) + url = None + for link in data.get("links", []): + if link.get("rel") == "next": + url = link.get("href") + break + return items + + +def acquire_swisstopo_data( + cache_dir: Path, e0: float, n0: float, e1: float, n1: float +) -> tuple[dict[tuple[int, int], Path], list[Path], list[str]]: + tr = pyproj.Transformer.from_crs("EPSG:2056", "EPSG:4326", always_xy=True) + lon0, lat0 = tr.transform(e0 - 20.0, n0 - 20.0) + lon1, lat1 = tr.transform(e1 + 20.0, n1 + 20.0) + wgs_bbox = (lon0, lat0, lon1, lat1) + + # 1. swissALTI3D: pick latest year per 1km tile intersecting [e0, e1] x [n0, n1] + alti_items = fetch_stac_items(STAC_ALTI_URL, wgs_bbox) + req_ekm = range(int(math.floor(e0 / 1000.0)), int(math.floor((e1 - 1e-6) / 1000.0)) + 1) + req_nkm = range(int(math.floor(n0 / 1000.0)), int(math.floor((n1 - 1e-6) / 1000.0)) + 1) + needed_tiles = {(ek, nk) for ek in req_ekm for nk in req_nkm} + + best_alti: dict[tuple[int, int], tuple[int, str, str, str]] = {} + for item in alti_items: + m = re.match(r"swissalti3d_(\d{4})_(\d{4})-(\d{4})$", item["id"]) + if not m: + continue + yr, ek, nk = int(m.group(1)), int(m.group(2)), int(m.group(3)) + if (ek, nk) not in needed_tiles: + continue + for asset_name, asset in item.get("assets", {}).items(): + if "_0.5_2056_5728.tif" in asset_name: + prev = best_alti.get((ek, nk)) + if prev is None or yr > prev[0]: + best_alti[(ek, nk)] = (yr, item["id"], asset_name, asset["href"]) + + if len(best_alti) != len(needed_tiles): + missing = needed_tiles - set(best_alti.keys()) + raise RuntimeError(f"Missing swissALTI3D tiles for bbox: {missing}") + + tif_paths: dict[tuple[int, int], Path] = {} + stac_ids: list[str] = [] + for key, (_, item_id, fname, href) in sorted(best_alti.items()): + tif_paths[key] = download_cached(href, cache_dir / fname) + stac_ids.append(item_id) + + # 2. swissBUILDINGS3D 3.0: pick latest per-sheet tiled GDB (skip multi-GB whole-CH monoliths) + bldg_items = fetch_stac_items(STAC_BLDG_URL, wgs_bbox) + best_sheets: dict[str, tuple[int, str, str, str]] = {} + for item in bldg_items: + m = re.match(r"swissbuildings3d_3_0_(\d{4})_(\d{4}-\d{2})$", item["id"]) + if not m: + continue + yr, sheet = int(m.group(1)), m.group(2) + for asset_name, asset in item.get("assets", {}).items(): + if asset_name.endswith(".gdb.zip"): + prev = best_sheets.get(sheet) + if prev is None or yr > prev[0]: + best_sheets[sheet] = (yr, item["id"], asset_name, asset["href"]) + + if not best_sheets: + raise RuntimeError("No per-sheet swissBUILDINGS3D 3.0 GDB assets returned from STAC") + + gdb_paths: list[Path] = [] + for sheet, (_, item_id, fname, href) in sorted(best_sheets.items()): + zip_path = download_cached(href, cache_dir / fname) + stac_ids.append(item_id) + with zipfile.ZipFile(zip_path) as zf: + gdb_roots = {name.split("/")[0] for name in zf.namelist() if ".gdb/" in name} + for root in sorted(gdb_roots): + gdb_dir = cache_dir / root + if not gdb_dir.exists(): + print(f" [Extract GDB] {fname} -> {root}") + zf.extractall(cache_dir) + gdb_paths.append(gdb_dir) + + return tif_paths, gdb_paths, stac_ids + + +# --------------------------------------------------------------------------- +# DEM stitching, heightmap resampling & surface albedo synthesis +# --------------------------------------------------------------------------- +def sample_mosaic_grid( + mosaic: np.ndarray, e_origin: float, n_top: float, center_e: float, center_n: float, res: int +) -> np.ndarray: + pixel_m = 0.5 + step_m = ARENA_SIZE_M / (res - 1) + xs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m + zs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m + e_grid = center_e + xs + n_grid = center_n - zs + col_1d = (e_grid - e_origin) / pixel_m - 0.5 + row_1d = (n_top - n_grid) / pixel_m - 0.5 + row_coords, col_coords = np.meshgrid(row_1d, col_1d, indexing="ij") + return map_coordinates(mosaic, [row_coords, col_coords], order=1, mode="nearest").astype(np.float32) + + +def build_heightmap( + tif_paths: dict[tuple[int, int], Path], center_e: float, center_n: float +) -> tuple[np.ndarray, np.ndarray, float, float, float]: + ekms = sorted({k[0] for k in tif_paths}) + nkms = sorted({k[1] for k in tif_paths}, reverse=True) # north-to-south rows + tile_px = 2000 + mosaic = np.zeros((len(nkms) * tile_px, len(ekms) * tile_px), dtype=np.float32) + + for ni, nk in enumerate(nkms): + for ei, ek in enumerate(ekms): + arr = tifffile.imread(str(tif_paths[(ek, nk)])) + if arr.shape != (tile_px, tile_px): + raise RuntimeError(f"Unexpected DEM tile shape {arr.shape} in {tif_paths[(ek, nk)]}") + mosaic[ni * tile_px : (ni + 1) * tile_px, ei * tile_px : (ei + 1) * tile_px] = arr + + e_origin = ekms[0] * 1000.0 + n_top = (nkms[0] + 1) * 1000.0 + + # Grid coordinates in RustToDust: + # row iz (0..6144): Z = -1536 + iz * 0.5 (North -> South), N = center_n - Z + # col ix (0..6144): X = -1536 + ix * 0.5 (West -> East), E = center_e + X + hm_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, GRID_RES) + surf_dem_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, SURFACE_TEX_RES) + + # Anchor valley floor near y = 0m using 5th percentile + base_elev = round(float(np.percentile(hm_asl, 5.0)), 2) + hm_rel = (hm_asl - base_elev).astype(np.float32) + return hm_rel, surf_dem_asl, base_elev, float(hm_rel.min()), float(hm_rel.max()) + + +def export_heightmap_u16z(hm: np.ndarray, out_path: Path) -> tuple[float, float, str]: + """ + Export 0.5m quantized heightmap as heightmap_05m.u16z: + Header (24 bytes LE): + magic="RDHM", uint32 version=2, uint32 gridRes=6145, + float32 minY, float32 scale, uint32 rawByteCount + Payload: + zlib-compressed row-wise zig-zag int16 spatial prediction residuals of uint16[gridRes*gridRes]. + """ + min_y = float(np.float32(hm.min())) + max_y = float(np.float32(hm.max())) + scale = float(np.float32(max(1e-6, (max_y - min_y) / 65535.0))) + q = np.clip(np.round((hm.astype(np.float64) - min_y) / scale), 0, 65535).astype(np.uint16) + + pred = np.empty_like(q) + pred[0, 0] = 0 + pred[1:, 0] = q[:-1, 0] + pred[:, 1:] = q[:, :-1] + + diff = (q.astype(np.int32) - pred.astype(np.int32)).astype(np.int16) + d32 = diff.astype(np.int32) + zz = (((d32 << 1) ^ (d32 >> 15)) & 0xFFFF).astype(np.uint16) + raw_bytes = np.ascontiguousarray(zz, dtype=" dict[str, np.ndarray]: + """Fetch and cache Swisstopo label-free TLM WMS layers for water, roads, rail, and forest.""" + bbox_key = f"{int(round(e0))}_{int(round(n0))}_{int(round(e1))}_{int(round(n1))}_{res}" + specs = { + "tlm_color": ("ch.swisstopo.swisstlm3d-karte-farbe", "FALSE"), + "roads": ("ch.swisstopo.swisstlm3d-strassen", "TRUE"), + "rail": ("ch.swisstopo.swisstlm3d-eisenbahnnetz", "TRUE"), + "forest": ("ch.swisstopo.swisstlm3d-wald", "TRUE"), + } + out: dict[str, np.ndarray] = {} + for key, (layer, transparent) in specs.items(): + dest = cache_dir / f"wms_{key}_{bbox_key}.png" + if not (dest.exists() and dest.stat().st_size > 0): + url = ( + f"{WMS_BASE_URL}?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap" + f"&LAYERS={layer}&STYLES=default&CRS=EPSG:2056" + f"&BBOX={e0:.1f},{n0:.1f},{e1:.1f},{n1:.1f}" + f"&WIDTH={res}&HEIGHT={res}&FORMAT=image/png&TRANSPARENT={transparent}" + ) + print(f" [WMS fetch] {layer} -> {dest.name}") + req = urllib.request.Request(url, headers={"User-Agent": "RustToDust-SionBaker/1.0"}) + tmp = dest.with_suffix(".png.part") + try: + with urllib.request.urlopen(req, timeout=45) as resp: + tmp.write_bytes(resp.read()) + tmp.replace(dest) + except Exception: + if res > 2048: + fallback = acquire_wms_masks(cache_dir, e0, n0, e1, n1, 2048) + return { + k: zoom(v, (res / v.shape[0], res / v.shape[1], 1), order=1) + for k, v in fallback.items() + } + raise + out[key] = imagecodecs.png_decode(dest.read_bytes()) + return out + + +def rasterize_triangles_xz(tris_list: list[np.ndarray], res: int) -> np.ndarray: + """Rasterize 3D (N, 3, 3) triangles projected to (X, Z) onto a (res, res) boolean mask.""" + mask = np.zeros((res, res), dtype=bool) + if not tris_list: + return mask + tris = np.asarray(tris_list, dtype=np.float64) + scale = (res - 1) / ARENA_SIZE_M + px = (tris[:, :, 0] + HALF_EXTENT_M) * scale + pz = (tris[:, :, 2] + HALF_EXTENT_M) * scale + + for i in range(len(tris)): + x0, x1, x2 = px[i, 0], px[i, 1], px[i, 2] + y0, y1, y2 = pz[i, 0], pz[i, 1], pz[i, 2] + area = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) + if abs(area) < 0.25: + continue + if area < 0.0: + x1, x2 = x2, x1 + y1, y2 = y2, y1 + ix0 = max(0, int(math.floor(min(x0, x1, x2)))) + ix1 = min(res - 1, int(math.ceil(max(x0, x1, x2)))) + iy0 = max(0, int(math.floor(min(y0, y1, y2)))) + iy1 = min(res - 1, int(math.ceil(max(y0, y1, y2)))) + if ix1 < ix0 or iy1 < iy0: + continue + gx = np.arange(ix0, ix1 + 1, dtype=np.float64)[None, :] + 0.5 + gy = np.arange(iy0, iy1 + 1, dtype=np.float64)[:, None] + 0.5 + e0 = (x1 - x0) * (gy - y0) - (y1 - y0) * (gx - x0) + e1 = (x2 - x1) * (gy - y1) - (y2 - y1) * (gx - x1) + e2 = (x0 - x2) * (gy - y2) - (y0 - y2) * (gx - x2) + inside = (e0 >= -0.05) & (e1 >= -0.05) & (e2 >= -0.05) + mask[iy0 : iy1 + 1, ix0 : ix1 + 1] |= inside + return mask + + +def smooth_fbm_2d(res: int, seed: int = 42) -> np.ndarray: + """Deterministic multi-octave smooth value noise in [0, 1] without high-frequency PNG-bloating grain.""" + rng = np.random.default_rng(seed) + acc = np.zeros((res, res), dtype=np.float32) + weights = [(16, 0.45), (48, 0.30), (128, 0.17), (320, 0.08)] + for grid_n, w in weights: + coarse = rng.random((grid_n, grid_n), dtype=np.float32) + up = zoom(coarse, res / grid_n, order=1)[:res, :res] + if up.shape != (res, res): + pad = np.zeros((res, res), dtype=np.float32) + pad[: up.shape[0], : up.shape[1]] = up + up = pad + acc += up * w + acc = (acc - acc.min()) / max(1e-6, float(acc.max() - acc.min())) + return acc + + +def build_terrain_surface_texture( + dem_asl: np.ndarray, + base_elev: float, + wms_masks: dict[str, np.ndarray] | None, + fp_res_tris: list[np.ndarray], + fp_ind_tris: list[np.ndarray], + fp_fort_tris: list[np.ndarray], +) -> tuple[bytes, bytes]: + """ + Synthesize 4096x4096 RGB surface albedo PNG and 2048x2048 RGBA8 surface class mask PNG + (R=rock_cliff, G=grass_vineyard, B=asphalt_gravel, A=water_channel). + """ + res = dem_asl.shape[0] + px_m = ARENA_SIZE_M / (res - 1) # 1.5m/px + elev_rel = dem_asl - base_elev + + # DEM slope & aspect (row increases South, col increases East) + dem_smooth = gaussian_filter(dem_asl, sigma=0.75) + gy, gx = np.gradient(dem_smooth, px_m) + slope = np.hypot(gx, gy) + normal_y = 1.0 / np.sqrt(1.0 + slope * slope) + + fbm = smooth_fbm_2d(res, seed=2056) + fbm2 = smooth_fbm_2d(res, seed=1120) + + # 1. Base valley meadow & hillside terraced vineyards + # Valley grass -> warm terraced hillside olive/sage + hill_t = np.clip((elev_rel - 10.0) / 85.0, 0.0, 1.0) + valley_col = np.array([0.31, 0.36, 0.22], dtype=np.float32) + hill_col = np.array([0.25, 0.32, 0.17], dtype=np.float32) + rgb = valley_col * (1.0 - hill_t[..., None]) + hill_col * hill_t[..., None] + + # Subtle meadow & hillside variation + rgb += (fbm[..., None] - 0.5) * np.array([0.07, 0.08, 0.05], dtype=np.float32) + + # Sunny south-facing vineyard terrace contours (gy < 0 means elevation drops going South) + south_facing = np.clip((-gy - 0.05) / 0.35, 0.0, 1.0) + vine_band = np.clip((elev_rel - 14.0) / 18.0, 0.0, 1.0) * np.clip((260.0 - elev_rel) / 60.0, 0.0, 1.0) + vine_slope = np.clip((slope - 0.10) / 0.18, 0.0, 1.0) * np.clip((0.68 - slope) / 0.25, 0.0, 1.0) + terrace_wave = 0.5 + 0.5 * np.sin(dem_asl * 1.15 + fbm2 * 2.0) + vine_w = south_facing * vine_band * vine_slope * (0.25 + 0.55 * terrace_wave) + vine_col = np.array([0.33, 0.36, 0.20], dtype=np.float32) + rgb = rgb * (1.0 - vine_w[..., None] * 0.65) + vine_col * (vine_w[..., None] * 0.65) + + # Forest canopy tint from Swisstopo Wald mask (darker alpine pine/oak green) + if wms_masks and "forest" in wms_masks: + f_rgba = wms_masks["forest"] + forest_mask = f_rgba[..., 3] > 60 + forest_soft = gaussian_filter(forest_mask.astype(np.float32), sigma=2.2) + forest_col = np.array([0.16, 0.23, 0.13], dtype=np.float32) + (fbm2[..., None] - 0.5) * 0.04 + rgb = rgb * (1.0 - forest_soft[..., None] * 0.72) + forest_col * (forest_soft[..., None] * 0.72) + + # 2. Urban building footprint plazas & yards + mask_res = rasterize_triangles_xz(fp_res_tris, res) + mask_ind = rasterize_triangles_xz(fp_ind_tris, res) + mask_fort = rasterize_triangles_xz(fp_fort_tris, res) + + # Local building density distinguishes dense Old Town stone plazas from suburban lawns + bldg_density = gaussian_filter((mask_res | mask_fort).astype(np.float32), sigma=22.0) + urban_core = np.clip(bldg_density * 5.5, 0.0, 1.0) + + res_plaza = binary_dilation(mask_res, iterations=7) & (normal_y > 0.87) + res_soft = gaussian_filter(res_plaza.astype(np.float32), sigma=2.0) * (0.35 + 0.65 * urban_core) + plaza_col = np.array([0.45, 0.42, 0.37], dtype=np.float32) + (fbm[..., None] - 0.5) * 0.05 + rgb = rgb * (1.0 - res_soft[..., None] * 0.88) + plaza_col * (res_soft[..., None] * 0.88) + + ind_yard = binary_dilation(mask_ind, iterations=10) & (normal_y > 0.90) + ind_soft = gaussian_filter(ind_yard.astype(np.float32), sigma=2.0) + ind_col = np.array([0.36, 0.36, 0.35], dtype=np.float32) + (fbm2[..., None] - 0.5) * 0.04 + rgb = rgb * (1.0 - ind_soft[..., None] * 0.88) + ind_col * (ind_soft[..., None] * 0.88) + + fort_court = binary_dilation(mask_fort, iterations=5) & (normal_y > 0.82) + fort_soft = gaussian_filter(fort_court.astype(np.float32), sigma=1.8) + fort_col = np.array([0.43, 0.40, 0.35], dtype=np.float32) + rgb = rgb * (1.0 - fort_soft[..., None] * 0.82) + fort_col * (fort_soft[..., None] * 0.82) + + # 3. Railway yard ballast corridor + if wms_masks and "rail" in wms_masks: + rail_alpha = wms_masks["rail"][..., 3] > 50 + rail_corridor = binary_dilation(rail_alpha, iterations=4) + rail_soft = gaussian_filter(rail_corridor.astype(np.float32), sigma=1.2) + rail_col = np.array([0.33, 0.30, 0.27], dtype=np.float32) + rgb = rgb * (1.0 - rail_soft[..., None] * 0.85) + rail_col * (rail_soft[..., None] * 0.85) + + # 4. Steep alpine limestone cliff faces (Valere / Tourbillon / escarpments) + # Applied after ground lawns/plazas so sheer cliffs always expose limestone rock! + cliff_t = np.clip((0.88 - normal_y) / (0.88 - 0.72), 0.0, 1.0) + strata = 0.5 + 0.5 * np.sin(dem_asl * 0.85 + fbm * 3.0) + cliff_col = ( + np.array([0.48, 0.46, 0.42], dtype=np.float32) + + (strata[..., None] - 0.5) * np.array([0.07, 0.07, 0.06], dtype=np.float32) + + (fbm2[..., None] - 0.5) * 0.05 + ) + rgb = rgb * (1.0 - cliff_t[..., None]) + cliff_col * cliff_t[..., None] + + # 5. Rhone river, Borgne tributary & canals (gravel banks + glacial teal water) + water_mask = np.zeros((res, res), dtype=bool) + if wms_masks and "tlm_color" in wms_masks: + c_rgb = wms_masks["tlm_color"][..., :3].astype(np.int16) + cyan = (c_rgb[..., 2] - c_rgb[..., 0] > 55) & (c_rgb[..., 2] > 200) & (c_rgb[..., 1] > 170) & (c_rgb[..., 0] < 180) + # Heal blue river name text gaps inside the river polygon + water_mask = binary_closing(cyan, structure=np.ones((9, 9))) + water_mask &= elev_rel < 25.0 + else: + # Pure-DEM fallback for leveed river channels + r_px = 60 + n_max = maximum_filter1d(dem_asl, size=r_px, axis=0, origin=-(r_px // 2)) + s_max = maximum_filter1d(dem_asl, size=r_px, axis=0, origin=(r_px // 2)) + w_max = maximum_filter1d(dem_asl, size=r_px, axis=1, origin=-(r_px // 2)) + e_max = maximum_filter1d(dem_asl, size=r_px, axis=1, origin=(r_px // 2)) + trough = np.maximum(np.minimum(n_max, s_max) - dem_asl, np.minimum(w_max, e_max) - dem_asl) + water_mask = (trough > 3.2) & (slope < 0.03) & (elev_rel < 10.0) + water_mask = binary_closing(binary_opening(water_mask, structure=np.ones((3, 3))), structure=np.ones((7, 7))) + + if np.any(water_mask): + bank_mask = binary_dilation(water_mask, iterations=4) & (~water_mask) + bank_soft = gaussian_filter(bank_mask.astype(np.float32), sigma=1.2) + bank_col = np.array([0.44, 0.42, 0.37], dtype=np.float32) + rgb = rgb * (1.0 - bank_soft[..., None] * 0.80) + bank_col * (bank_soft[..., None] * 0.80) + + water_soft = gaussian_filter(water_mask.astype(np.float32), sigma=1.0) + water_col = np.array([0.13, 0.27, 0.34], dtype=np.float32) + (fbm[..., None] - 0.5) * 0.03 + rgb = rgb * (1.0 - water_soft[..., None] * 0.96) + water_col * (water_soft[..., None] * 0.96) + + road_total = np.zeros((res, res), dtype=np.float32) + # 6. Roads, highway A9 & bridges (drawn after water so bridges span the Rhone!) + if wms_masks and "roads" in wms_masks: + r_rgba = wms_masks["roads"] + r_rgb = r_rgba[..., :3].astype(np.int16) + r_alpha = r_rgba[..., 3] > 80 + # Major arterial / highway (orange/red/yellow in TLM roads) vs local streets + is_major = r_alpha & ((r_rgb[..., 0] - r_rgb[..., 2]) > 45) + is_minor = r_alpha & (~is_major) + minor_soft = gaussian_filter(is_minor.astype(np.float32), sigma=0.6) + major_soft = gaussian_filter(binary_dilation(is_major, iterations=1).astype(np.float32), sigma=0.7) + street_col = np.array([0.35, 0.34, 0.32], dtype=np.float32) + highway_col = np.array([0.25, 0.25, 0.26], dtype=np.float32) + rgb = rgb * (1.0 - minor_soft[..., None] * 0.72) + street_col * (minor_soft[..., None] * 0.72) + rgb = rgb * (1.0 - major_soft[..., None] * 0.88) + highway_col * (major_soft[..., None] * 0.88) + road_total = np.clip(np.maximum(minor_soft, major_soft), 0.0, 1.0) + + # Darken slightly under exact building footprints for subtle ambient grounding + bldg_under = (mask_res | mask_ind | mask_fort) & (normal_y > 0.75) + rgb[bldg_under] *= 0.88 + + # Build 2048x2048 RGBA8 surface class mask: + # R = rock_cliff, G = grass_vineyard, B = asphalt_gravel, A = water_channel + water_ch = gaussian_filter(water_mask.astype(np.float32), sigma=1.0) if np.any(water_mask) else np.zeros((res, res), dtype=np.float32) + rail_ch = gaussian_filter(binary_dilation(wms_masks["rail"][..., 3] > 50, iterations=4).astype(np.float32), sigma=1.2) if (wms_masks and "rail" in wms_masks) else np.zeros((res, res), dtype=np.float32) + asphalt_gravel = np.clip(np.maximum(road_total, np.maximum(rail_ch, np.maximum(res_soft, np.maximum(ind_soft, fort_soft)))), 0.0, 1.0) + rock_cliff = np.clip(cliff_t, 0.0, 1.0) + grass_vineyard = np.clip((1.0 - rock_cliff) * (1.0 - water_ch) * (1.0 - asphalt_gravel * 0.85), 0.0, 1.0) + mask_full = np.stack([rock_cliff, grass_vineyard, asphalt_gravel, np.clip(water_ch, 0.0, 1.0)], axis=-1) + step = max(1, res // SURFACE_MASK_RES) + if step > 1: + mask_ds = mask_full.reshape(SURFACE_MASK_RES, step, SURFACE_MASK_RES, step, 4).mean(axis=(1, 3)) + else: + mask_ds = mask_full + mask_u8 = np.clip(np.round(mask_ds * 255.0), 0, 255).astype(np.uint8) + mask_png_bytes = imagecodecs.png_encode(mask_u8, level=9) + + rgb_u8 = np.clip(np.round(rgb * 255.0), 0, 255).astype(np.uint8) + png_bytes = imagecodecs.png_encode(rgb_u8, level=9) + if len(png_bytes) >= MAX_SURFACE_PNG_BYTES: + # Mild bit-depth quantization (7-bit per channel) preserves smooth gradients while halving PNG size + rgb_u8 = (rgb_u8 & 0xFE) + png_bytes = imagecodecs.png_encode(rgb_u8, level=9) + if len(png_bytes) >= MAX_SURFACE_PNG_BYTES: + rgb_u8 = (rgb_u8 & 0xFC) + png_bytes = imagecodecs.png_encode(rgb_u8, level=9) + return png_bytes, mask_png_bytes + + +def sample_heightmap(hm: np.ndarray, x: np.ndarray | float, z: np.ndarray | float) -> np.ndarray | float: + fx = np.clip((np.asarray(x) + HALF_EXTENT_M) / CELL_SIZE_M, 0.0, GRID_RES - 1.00001) + fz = np.clip((np.asarray(z) + HALF_EXTENT_M) / CELL_SIZE_M, 0.0, GRID_RES - 1.00001) + ix = np.floor(fx).astype(np.int32) + iz = np.floor(fz).astype(np.int32) + tx = fx - ix + tz = fz - iz + h00 = hm[iz, ix] + h10 = hm[iz, ix + 1] + h01 = hm[iz + 1, ix] + h11 = hm[iz + 1, ix + 1] + return (h00 * (1.0 - tx) + h10 * tx) * (1.0 - tz) + (h01 * (1.0 - tx) + h11 * tx) * tz + + +# --------------------------------------------------------------------------- +# Coordinate conversion & geometry utilities +# --------------------------------------------------------------------------- +def enz_to_rtd(pts: np.ndarray, center_e: float, center_n: float, base_elev: float) -> np.ndarray: + """EPSG:2056 (E, N, Z) -> RustToDust right-handed glTF (X=E-cE, Y=Z-base, Z=-(N-cN)). det=+1.""" + out = np.empty_like(pts, dtype=np.float64) + out[:, 0] = pts[:, 0] - center_e + out[:, 1] = pts[:, 2] - base_elev + out[:, 2] = -(pts[:, 1] - center_n) + return out + + +def newell_normal(pts: np.ndarray) -> np.ndarray: + p0 = pts + p1 = np.roll(pts, -1, axis=0) + n = np.array( + [ + np.sum((p0[:, 1] - p1[:, 1]) * (p0[:, 2] + p1[:, 2])), + np.sum((p0[:, 2] - p1[:, 2]) * (p0[:, 0] + p1[:, 0])), + np.sum((p0[:, 0] - p1[:, 0]) * (p0[:, 1] + p1[:, 1])), + ], + dtype=np.float64, + ) + length = float(np.linalg.norm(n)) + return n / length if length > 1e-12 else np.array([0.0, 1.0, 0.0], dtype=np.float64) + + +def triangulate_polygon_3d(pts: np.ndarray) -> np.ndarray: + """Triangulate a 3D simple polygon (N, 3) into (M, 3, 3) triangles preserving winding.""" + n_pts = len(pts) + if n_pts == 3: + return pts[None, :, :] + if n_pts == 4: + # Check convexity via normal consistency, split along shorter diagonal + d02 = np.sum((pts[2] - pts[0]) ** 2) + d13 = np.sum((pts[3] - pts[1]) ** 2) + if d02 <= d13: + return np.stack([pts[[0, 1, 2]], pts[[0, 2, 3]]], axis=0) + return np.stack([pts[[1, 2, 3]], pts[[1, 3, 0]]], axis=0) + + # Project onto dominant plane for ear-clipping + normal = newell_normal(pts) + ref = np.array([1.0, 0.0, 0.0]) if abs(normal[0]) < 0.8 else np.array([0.0, 1.0, 0.0]) + u = np.cross(normal, ref) + u /= np.linalg.norm(u) + v = np.cross(normal, u) + pts2 = np.column_stack([pts @ u, pts @ v]) + + # Ensure CCW in 2D for ear-clipping test, track if flipped + area2 = 0.0 + for i in range(n_pts): + j = (i + 1) % n_pts + area2 += pts2[i, 0] * pts2[j, 1] - pts2[j, 0] * pts2[i, 1] + order = list(range(n_pts)) + if area2 < 0: + order.reverse() + + tris_idx: list[tuple[int, int, int]] = [] + idx = list(order) + guard = 0 + while len(idx) > 3 and guard < n_pts * n_pts: + guard += 1 + ear_found = False + m = len(idx) + for k in range(m): + ia, ib, ic = idx[(k - 1) % m], idx[k], idx[(k + 1) % m] + a, b, c = pts2[ia], pts2[ib], pts2[ic] + cross = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + if cross <= 1e-10: + continue + # Check if any other point lies inside triangle (a, b, c) + inside = False + for o in idx: + if o in (ia, ib, ic): + continue + p = pts2[o] + c1 = (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) + c2 = (c[0] - b[0]) * (p[1] - b[1]) - (c[1] - b[1]) * (p[0] - b[0]) + c3 = (a[0] - c[0]) * (p[1] - c[1]) - (a[1] - c[1]) * (p[0] - c[0]) + if c1 >= -1e-9 and c2 >= -1e-9 and c3 >= -1e-9: + inside = True + break + if not inside: + tris_idx.append((ia, ib, ic) if area2 >= 0 else (ia, ic, ib)) + del idx[k] + ear_found = True + break + if not ear_found: + break + if len(idx) == 3: + ia, ib, ic = idx + tris_idx.append((ia, ib, ic) if area2 >= 0 else (ia, ic, ib)) + if not tris_idx: + # Fallback fan + tris_idx = [(0, k, k + 1) for k in range(1, n_pts - 1)] + return pts[np.array(tris_idx, dtype=np.int32)] + + +def rays_inside_solid( + points: np.ndarray, normals: np.ndarray, solid_tris: np.ndarray, eps: float = 0.03 +) -> np.ndarray: + """ + For each query (point + eps*normal), test 3 rays against closed solid_tris (K,3,3) via Moller-Trumbore. + Returns boolean mask: True if point+eps*normal is INSIDE solid (meaning normal points INWARD and must flip). + """ + if len(solid_tris) < 4 or len(points) == 0: + return np.zeros(len(points), dtype=bool) + v0 = solid_tris[:, 0, :] # (K, 3) + e1 = solid_tris[:, 1, :] - v0 + e2 = solid_tris[:, 2, :] - v0 + origins = points + normals * eps # (M, 3) + + ray_dirs = np.array( + [ + [0.37139068, 0.21899573, 0.90226797], + [-0.81239412, 0.41502134, 0.40984511], + [0.29510421, -0.88142173, 0.36901342], + ], + dtype=np.float64, + ) + + votes = np.zeros(len(points), dtype=np.int32) + # Process in chunks to keep peak memory tiny even for Basilique de Valere + chunk = 256 + for d in ray_dirs: + pvec = np.cross(d[None, :], e2) # (K, 3) + det = np.sum(e1 * pvec, axis=1) # (K,) + valid = np.abs(det) > 1e-10 + inv_det = np.zeros_like(det) + inv_det[valid] = 1.0 / det[valid] + q_e1 = e1[valid] + q_e2 = e2[valid] + q_v0 = v0[valid] + q_pvec = pvec[valid] + q_inv = inv_det[valid] + if len(q_v0) == 0: + continue + for s in range(0, len(origins), chunk): + orig = origins[s : s + chunk] # (C, 3) + tvec = orig[:, None, :] - q_v0[None, :, :] # (C, K', 3) + u = np.sum(tvec * q_pvec[None, :, :], axis=2) * q_inv[None, :] + m = (u >= 0.0) & (u <= 1.0) + qvec = np.cross(tvec, q_e1[None, :, :]) + v = np.sum(d[None, None, :] * qvec, axis=2) * q_inv[None, :] + m &= (v >= 0.0) & (u + v <= 1.0) + t = np.sum(q_e2[None, :, :] * qvec, axis=2) * q_inv[None, :] + m &= t > 1e-5 + hits = m.sum(axis=1) + votes[s : s + chunk] += (hits % 2).astype(np.int32) + return votes >= 2 + + +# --------------------------------------------------------------------------- +# Building extraction, classification, orientation & skirt generation +# --------------------------------------------------------------------------- +def classify_building( + objektart: str, name: str, pts_enz: np.ndarray, roof_faces_rtd: list[np.ndarray] +) -> str: + nl = name.lower() + if objektart in ("Sakrales Gebaeude", "Kapelle", "Sakraler Turm", "Mauer gross"): + return "fortress" + if any(k in nl for k in ("valère", "valere", "tourbillon", "basilique", "château", "chateau", "cathédral")): + return "fortress" + # Fortress hilltop zone (Valere & Tourbillon ridges) + ce = float(pts_enz[:, 0].mean()) + cn = float(pts_enz[:, 1].mean()) + min_z = float(pts_enz[:, 2].min()) + if 2594180.0 <= ce <= 2594650.0 and 1120180.0 <= cn <= 1120660.0 and min_z > 545.0: + return "fortress" + + if objektart in ("Hochhaus", "Offenes Gebaeude", "Flugdach", "Unterirdisches Gebaeude", "Im Bau", "Lagertank", "Treibhaus"): + return "industrial" + + # Large flat-roofed industrial/commercial blocks in the valley flats + dx = float(pts_enz[:, 0].max() - pts_enz[:, 0].min()) + dn = float(pts_enz[:, 1].max() - pts_enz[:, 1].min()) + area_box = dx * dn + if area_box > 750.0 and min_z < 508.0 and roof_faces_rtd: + # Weighted average roof slope + flat_area = 0.0 + total_area = 0.0 + for rf in roof_faces_rtd: + n = newell_normal(rf) + a = 0.5 * float(np.linalg.norm(np.cross(rf[1] - rf[0], rf[-1] - rf[0]))) + total_area += a + if abs(n[1]) > 0.985: # < ~10 deg + flat_area += a + if total_area > 1.0 and (flat_area / total_area) > 0.75: + return "industrial" + + return "residential" + + +def orient_faces_outward( + faces_rtd: list[np.ndarray], + solid_tris_rtd: np.ndarray | None, + layer_kind: str, + bldg_center_rtd: np.ndarray, +) -> list[np.ndarray]: + if not faces_rtd: + return [] + centers = np.array([f.mean(axis=0) for f in faces_rtd], dtype=np.float64) + normals = np.array([newell_normal(f) for f in faces_rtd], dtype=np.float64) + + if layer_kind == "Roof": + # Roof shells are open surfaces: non-vertical roof slopes must face UP (+Y). + flip = normals[:, 1] < -0.05 + # Near-vertical dormer cheeks/fascia: face away from building horizontal center + vert = np.abs(normals[:, 1]) <= 0.05 + if np.any(vert): + d_xz = centers[vert][:, [0, 2]] - bldg_center_rtd[[0, 2]] + dot = np.sum(d_xz * normals[vert][:, [0, 2]], axis=1) + flip[vert] = dot < 0 + elif layer_kind == "Floor": + # Floor caps face DOWN (-Y) unless steep step risers + flip = normals[:, 1] > 0.05 + vert = np.abs(normals[:, 1]) <= 0.05 + if np.any(vert) and solid_tris_rtd is not None and len(solid_tris_rtd) >= 4: + flip[vert] = rays_inside_solid(centers[vert], normals[vert], solid_tris_rtd, eps=0.025) + else: + # Wall faces: exact 3D solid parity against Building_solid when closed, else centroid fallback + if solid_tris_rtd is not None and len(solid_tris_rtd) >= 8: + flip = rays_inside_solid(centers, normals, solid_tris_rtd, eps=0.025) + else: + d_xz = centers[:, [0, 2]] - bldg_center_rtd[[0, 2]] + flip = np.sum(d_xz * normals[:, [0, 2]], axis=1) < 0 + + oriented = [] + for i, f in enumerate(faces_rtd): + oriented.append(f[::-1].copy() if flip[i] else f) + return oriented + + +def build_foundation_skirt_tris( + wall_tris: np.ndarray, + floor_faces: list[np.ndarray], + hm: np.ndarray, + min_y: float, + simplify_tol: float = 0.0, +) -> np.ndarray: + """ + Build -4.0m downward perimeter skirt quads from the building's base footprint / bottom wall edges + so no building floats on steep terrain slopes. + """ + if len(wall_tris) == 0: + return np.zeros((0, 3, 3), dtype=np.float64) + + # Sample terrain height across the building's XZ extent (corners + center) + pts_all = wall_tris.reshape(-1, 3) + x0, z0 = float(pts_all[:, 0].min()), float(pts_all[:, 2].min()) + x1, z1 = float(pts_all[:, 0].max()), float(pts_all[:, 2].max()) + gx = np.linspace(x0, x1, 5) + gz = np.linspace(z0, z1, 5) + mx, mz = np.meshgrid(gx, gz) + terrain_vals = sample_heightmap(hm, mx, mz) + terrain_min_y = float(np.min(terrain_vals)) + # If building base already sits >= 0.45m below the lowest terrain sample across its footprint, + # no downward skirt is needed. + if min_y <= terrain_min_y - 0.45: + return np.zeros((0, 3, 3), dtype=np.float64) + skirt_bottom_y = min(min_y, terrain_min_y) - SKIRT_DEPTH_M + + skirt_tris: list[np.ndarray] = [] + + # Primary method: extrude outer boundary of Floor polygons (projected to XZ, matching floor edge Y) + if floor_faces: + polys_2d = [] + floor_verts = [] + for ff in floor_faces: + floor_verts.append(ff) + p2 = Polygon(ff[:, [0, 2]]) + if not p2.is_valid: + p2 = p2.buffer(0) + if not p2.is_empty and p2.area > 0.05: + polys_2d.append(p2) + if polys_2d: + fv = np.vstack(floor_verts) + merged = unary_union(polys_2d) + geoms = list(merged.geoms) if hasattr(merged, "geoms") else [merged] + for poly in geoms: + if not isinstance(poly, Polygon) or poly.is_empty: + continue + if simplify_tol > 0.0: + poly = poly.simplify(simplify_tol, preserve_topology=True) + if not isinstance(poly, Polygon) or poly.is_empty: + continue + # Ensure exterior ring is CCW in (X, Z) -> in right-handed (X, Y, Z), + # wait: for vertical wall from p0->p1 down to bottom, if cross(p1-p0, down) points OUTWARD: + # let tangent t = (dx, 0, dz), down = (0, -1, 0). + # t x down = (dz, 0, -dx). In (X, Z), (dz, -dx) is right-hand normal to (dx, dz)! + # A CCW polygon in (X, Z) has interior on LEFT and exterior on RIGHT (+dz, -dx)! + ring = shapely.geometry.polygon.orient(poly, sign=1.0).exterior.coords + coords = list(ring) + for k in range(len(coords) - 1): + ax, az = coords[k] + bx, bz = coords[k + 1] + if (ax - bx) ** 2 + (az - bz) ** 2 < 1e-4: + continue + # Nearest floor vertex Y so stepped hillside floors anchor seamlessly + da = (fv[:, 0] - ax) ** 2 + (fv[:, 2] - az) ** 2 + db = (fv[:, 0] - bx) ** 2 + (fv[:, 2] - bz) ** 2 + ya = float(fv[int(np.argmin(da)), 1]) + 0.05 + yb = float(fv[int(np.argmin(db)), 1]) + 0.05 + p0 = np.array([ax, ya, az]) + p1 = np.array([bx, yb, bz]) + p0b = np.array([ax, skirt_bottom_y, az]) + p1b = np.array([bx, skirt_bottom_y, bz]) + # Outward normal: cross(p1-p0, p0b-p0) = (dx, dy, dz) x (0, -H, 0) = (dz*H, 0, -dx*H) + skirt_tris.append(np.stack([p0, p1, p1b], axis=0)) + skirt_tris.append(np.stack([p0, p1b, p0b], axis=0)) + + # Fallback for Floor-less structures (e.g. Mauer gross retaining walls): + # extrude lowest boundary edges of wall_tris straight down + if not skirt_tris: + # Quantize vertices to 2mm to match directed edges + def qkey(v: np.ndarray) -> tuple[int, int, int]: + return (int(round(v[0] * 500)), int(round(v[1] * 500)), int(round(v[2] * 500))) + + directed: dict[tuple[tuple[int, int, int], tuple[int, int, int]], tuple[np.ndarray, np.ndarray]] = {} + for tri in wall_tris: + for e in ((0, 1), (1, 2), (2, 0)): + va, vb = tri[e[0]], tri[e[1]] + ka, kb = qkey(va), qkey(vb) + if (kb, ka) in directed: + del directed[(kb, ka)] + else: + directed[(ka, kb)] = (va, vb) + y_thresh = min_y + 1.5 + for va, vb in directed.values(): + if va[1] <= y_thresh and vb[1] <= y_thresh and ((va[0] - vb[0]) ** 2 + (va[2] - vb[2]) ** 2) > 0.04: + # Wall triangle has (va -> vb) on its boundary; in an outward-wound wall, bottom edge runs + # left-to-right when viewed from outside -> (va -> vb) x down points INWARD, so reverse! + p0, p1 = vb, va + p0b = np.array([p0[0], skirt_bottom_y, p0[2]]) + p1b = np.array([p1[0], skirt_bottom_y, p1[2]]) + skirt_tris.append(np.stack([p0, p1, p1b], axis=0)) + skirt_tris.append(np.stack([p0, p1b, p0b], axis=0)) + + return np.array(skirt_tris, dtype=np.float64) if skirt_tris else np.zeros((0, 3, 3), dtype=np.float64) + + +# --------------------------------------------------------------------------- +# Procedural LOD1 generator (from semantic LOD2 Wall & Roof faces) +# --------------------------------------------------------------------------- +def append_box_face_outward( + out_tris: list[np.ndarray], + origin: np.ndarray, + u_axis: np.ndarray, + v_axis: np.ndarray, + n_axis: np.ndarray, + u0: float, + u1: float, + v0: float, + v1: float, + d0: float, + d1: float, + include_back: bool = False, +) -> None: + """Append an axis-aligned prism in local (u, v, n) frame with outward CCW triangles.""" + def pt(u: float, v: float, d: float) -> np.ndarray: + return origin + u * u_axis + v * v_axis + d * n_axis + + p000, p100, p110, p010 = pt(u0, v0, d0), pt(u1, v0, d0), pt(u1, v1, d0), pt(u0, v1, d0) + p001, p101, p111, p011 = pt(u0, v0, d1), pt(u1, v0, d1), pt(u1, v1, d1), pt(u0, v1, d1) + # Front (+n) + out_tris.append(np.stack([p001, p101, p111], axis=0)) + out_tris.append(np.stack([p001, p111, p011], axis=0)) + if include_back: + out_tris.append(np.stack([p000, p110, p100], axis=0)) + out_tris.append(np.stack([p000, p010, p110], axis=0)) + # Left (-u), Right (+u), Bottom (-v), Top (+v) + out_tris.append(np.stack([p000, p001, p011], axis=0)) + out_tris.append(np.stack([p000, p011, p010], axis=0)) + out_tris.append(np.stack([p101, p100, p110], axis=0)) + out_tris.append(np.stack([p101, p110, p111], axis=0)) + out_tris.append(np.stack([p000, p100, p101], axis=0)) + out_tris.append(np.stack([p000, p101, p001], axis=0)) + out_tris.append(np.stack([p011, p111, p110], axis=0)) + out_tris.append(np.stack([p011, p110, p010], axis=0)) + + +def append_lean_ledge( + out_tris: list[np.ndarray], + origin: np.ndarray, + u_axis: np.ndarray, + v_axis: np.ndarray, + n_axis: np.ndarray, + u0: float, + u1: float, + v0: float, + v1: float, + depth: float, + top_bevel: bool = True, +) -> None: + """Append a lean 4-tri architectural ledge (front face + top or bottom bevel).""" + def pt(u: float, v: float, d: float) -> np.ndarray: + return origin + u * u_axis + v * v_axis + d * n_axis + + f00, f10, f11, f01 = pt(u0, v0, depth), pt(u1, v0, depth), pt(u1, v1, depth), pt(u0, v1, depth) + out_tris.append(np.stack([f00, f10, f11], axis=0)) + out_tris.append(np.stack([f00, f11, f01], axis=0)) + if top_bevel: + b01, b11 = pt(u0, v1, 0.0), pt(u1, v1, 0.0) + out_tris.append(np.stack([f01, f11, b11], axis=0)) + out_tris.append(np.stack([f01, b11, b01], axis=0)) + else: + b00, b10 = pt(u0, v0, 0.0), pt(u1, v0, 0.0) + out_tris.append(np.stack([b00, b10, f10], axis=0)) + out_tris.append(np.stack([b00, f10, f00], axis=0)) + + +def append_quad_outward( + out_tris: list[np.ndarray], + origin: np.ndarray, + u_axis: np.ndarray, + v_axis: np.ndarray, + n_axis: np.ndarray, + u0: float, + u1: float, + v0: float, + v1: float, + d: float, +) -> None: + p00 = origin + u0 * u_axis + v0 * v_axis + d * n_axis + p10 = origin + u1 * u_axis + v0 * v_axis + d * n_axis + p11 = origin + u1 * u_axis + v1 * v_axis + d * n_axis + p01 = origin + u0 * u_axis + v1 * v_axis + d * n_axis + out_tris.append(np.stack([p00, p10, p11], axis=0)) + out_tris.append(np.stack([p00, p11, p01], axis=0)) + + +def merge_coplanar_faces( + faces: list[np.ndarray], n_quant: float = 40.0, d_quant: float = 5.0, min_area: float = 0.2 +) -> list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Polygon]]: + """ + Merge coplanar connected faces into clean planar 2D shapely polygons with local (origin, u_axis, v_axis, n_axis). + Returns list of (origin, u_axis, v_axis, n_axis, poly_2d). + """ + if not faces: + return [] + # Quantize plane key: normal rounded + plane offset d + groups: dict[tuple[int, int, int, int], list[tuple[np.ndarray, np.ndarray]]] = defaultdict(list) + for f in faces: + n = newell_normal(f) + d = float(np.dot(n, f[0])) + key = ( + int(round(n[0] * n_quant)), + int(round(n[1] * n_quant)), + int(round(n[2] * n_quant)), + int(round(d * d_quant)), + ) + groups[key].append((f, n)) + + merged_planes = [] + up = np.array([0.0, 1.0, 0.0], dtype=np.float64) + for items in groups.values(): + n_avg = np.mean([it[1] for it in items], axis=0) + ln = float(np.linalg.norm(n_avg)) + if ln < 1e-8: + continue + n_axis = n_avg / ln + origin = items[0][0][0] + if abs(n_axis[1]) < 0.9: + u_axis = np.cross(up, n_axis) + u_axis /= np.linalg.norm(u_axis) + v_axis = np.cross(n_axis, u_axis) + else: + u_axis = np.cross(np.array([0.0, 0.0, -1.0]), n_axis) + u_axis /= np.linalg.norm(u_axis) + v_axis = np.cross(n_axis, u_axis) + + polys = [] + for f, _ in items: + rel = f - origin + pts2 = np.column_stack([rel @ u_axis, rel @ v_axis]) + p = Polygon(pts2) + if not p.is_valid: + p = p.buffer(0) + if not p.is_empty and p.area > 0.02: + polys.append(p) + if not polys: + continue + u = unary_union(polys) + geoms = list(u.geoms) if hasattr(u, "geoms") else [u] + for g in geoms: + if isinstance(g, Polygon) and g.area > min_area: + merged_planes.append((origin, u_axis, v_axis, n_axis, g)) + return merged_planes + + +def triangulate_planar_polygon( + origin: np.ndarray, + u_axis: np.ndarray, + v_axis: np.ndarray, + poly: Polygon, + simplify_tol: float = 0.08, +) -> list[np.ndarray]: + """Triangulate a 2D shapely Polygon (with holes) in (u, v) and lift to 3D with +n_axis winding.""" + use_tol = simplify_tol if (simplify_tol > 0.0 and poly.area >= 1.0 and len(poly.exterior.coords) > 4) else 0.0 + p = poly.simplify(use_tol, preserve_topology=True) if use_tol > 0.0 else poly + if p.is_empty or p.area < 0.05: + p = poly + geoms = list(p.geoms) if hasattr(p, "geoms") else [p] + tris_3d: list[np.ndarray] = [] + for g in geoms: + if not isinstance(g, Polygon) or g.is_empty or g.area < 0.02: + continue + cdt = shapely.constrained_delaunay_triangles(g) + for tri_poly in cdt.geoms: + coords = list(tri_poly.exterior.coords) + if len(coords) < 4: + continue + a, b, c = coords[0], coords[1], coords[2] + if (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) < 0.0: + b, c = c, b + p0 = origin + a[0] * u_axis + a[1] * v_axis + p1 = origin + b[0] * u_axis + b[1] * v_axis + p2 = origin + c[0] * u_axis + c[1] * v_axis + tris_3d.append(np.stack([p0, p1, p2], axis=0)) + return tris_3d + + +def prepare_lod1_building( + bldg_uuid: str, + arch_style: str, + objektart: str, + in_core: bool, + wall_faces: list[np.ndarray], + roof_faces: list[np.ndarray], + wall_tris_raw: np.ndarray, + roof_tris_raw: np.ndarray, + skirt_tris_simp: np.ndarray, +) -> tuple: + """Precompute simplified coplanar planes, clean LOD2/COL & LOD1 shells, and roof trim once per building.""" + if arch_style == "fortress": + wall_planes = merge_coplanar_faces(wall_faces, n_quant=40.0, d_quant=5.0, min_area=0.2) + roof_planes = merge_coplanar_faces(roof_faces, n_quant=40.0, d_quant=5.0, min_area=0.2) + l1_wtol, l1_rtol = 0.08, 0.06 + l2_wtol, l2_rtol, l2_min = 0.08, 0.06, 0.2 + else: + wall_planes = merge_coplanar_faces(wall_faces, n_quant=14.0, d_quant=2.0, min_area=0.8) + roof_planes = merge_coplanar_faces(roof_faces, n_quant=20.0, d_quant=3.0, min_area=0.6) + l1_wtol, l1_rtol = 0.38, 0.28 + l2_wtol, l2_rtol, l2_min = 0.78, 0.58, 1.6 + + lod1_wall_tris: list[np.ndarray] = [] + lod2_wall_tris: list[np.ndarray] = [] + if wall_planes: + for origin, u_axis, v_axis, _, poly in wall_planes: + lod1_wall_tris.extend(triangulate_planar_polygon(origin, u_axis, v_axis, poly, simplify_tol=l1_wtol)) + if poly.area >= l2_min: + lod2_wall_tris.extend(triangulate_planar_polygon(origin, u_axis, v_axis, poly, simplify_tol=l2_wtol)) + if not lod1_wall_tris and len(wall_tris_raw) > 0: + lod1_wall_tris = list(wall_tris_raw) + if not lod2_wall_tris: + lod2_wall_tris = lod1_wall_tris + + lod1_roof_tris: list[np.ndarray] = [] + lod2_roof_tris: list[np.ndarray] = [] + if roof_planes: + for origin, u_axis, v_axis, _, poly in roof_planes: + lod1_roof_tris.extend(triangulate_planar_polygon(origin, u_axis, v_axis, poly, simplify_tol=l1_rtol)) + if poly.area >= l2_min: + lod2_roof_tris.extend(triangulate_planar_polygon(origin, u_axis, v_axis, poly, simplify_tol=l2_rtol)) + if not lod1_roof_tris and len(roof_tris_raw) > 0: + lod1_roof_tris = list(roof_tris_raw) + if not lod2_roof_tris: + lod2_roof_tris = lod1_roof_tris + + # Precompute roof eaves overhang (~0.35m), ridge caps, and chimneys once + roof_mat = {"fortress": "roof_fortress", "industrial": "roof_industrial", "residential": "roof_terracotta"}[arch_style] + roof_detail_mats: dict[str, list[np.ndarray]] = defaultdict(list) + if roof_planes: + all_roof_xz = [] + for origin, u_axis, v_axis, n_axis, poly in roof_planes: + pts2 = np.array(poly.exterior.coords) + pts3 = origin + pts2[:, 0:1] * u_axis + pts2[:, 1:2] * v_axis + pxz = Polygon(pts3[:, [0, 2]]) + if not pxz.is_valid: + pxz = pxz.buffer(0) + if not pxz.is_empty: + all_roof_xz.append(pxz) + roof_union_xz = unary_union(all_roof_xz) if all_roof_xz else None + ext_boundary = roof_union_xz.boundary if roof_union_xz is not None else None + + ridge_edges: list[tuple[np.ndarray, np.ndarray]] = [] + pitched_planes: list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Polygon]] = [] + min_roof_area = 12.0 if arch_style == "fortress" else (24.0 if in_core else 42.0) + + for origin, u_axis, v_axis, n_axis, poly in roof_planes: + slope_cos = float(abs(n_axis[1])) + if 0.15 < slope_cos < 0.993 and ext_boundary is not None and poly.area > min_roof_area: + pitched_planes.append((origin, u_axis, v_axis, n_axis, poly)) + simp = shapely.geometry.polygon.orient(poly, sign=1.0).simplify(0.45, preserve_topology=True) + if isinstance(simp, Polygon) and not simp.is_empty: + c2 = np.array(simp.exterior.coords) + c3 = origin + c2[:, 0:1] * u_axis + c2[:, 1:2] * v_axis + for k in range(len(c2) - 1): + p0_3, p1_3 = c3[k], c3[k + 1] + elen = float(np.linalg.norm(p1_3 - p0_3)) + if elen < 2.4: + continue + mid_xz = shapely.geometry.Point(0.5 * (p0_3[0] + p1_3[0]), 0.5 * (p0_3[2] + p1_3[2])) + if ext_boundary.distance(mid_xz) < 0.30: + du, dv = c2[k + 1, 0] - c2[k, 0], c2[k + 1, 1] - c2[k, 1] + out2 = np.array([dv, -du], dtype=np.float64) + ln2 = float(np.linalg.norm(out2)) + if ln2 < 1e-6: + continue + out2 /= ln2 + out3 = out2[0] * u_axis + out2[1] * v_axis + if out3[1] <= 0.15: + e0 = p0_3 + out3 * 0.35 + e1 = p1_3 + out3 * 0.35 + roof_detail_mats[roof_mat].append(np.stack([p0_3, e0, e1], axis=0)) + roof_detail_mats[roof_mat].append(np.stack([p0_3, e1, p1_3], axis=0)) + elif 0.5 * (p0_3[1] + p1_3[1]) > float(c3[:, 1].mean()) + 0.4 and elen > 3.2: + ridge_edges.append((p0_3, p1_3)) + + seen_ridges: list[tuple[np.ndarray, np.ndarray]] = [] + for a, b in ridge_edges: + mid = 0.5 * (a + b) + if any(np.linalg.norm(mid - 0.5 * (sa + sb)) < 0.8 for sa, sb in seen_ridges): + continue + seen_ridges.append((a, b)) + d_ab = b - a + rlen = float(np.linalg.norm(d_ab)) + ru = d_ab / rlen + rn = np.cross(np.array([0.0, 1.0, 0.0]), ru) + ln = float(np.linalg.norm(rn)) + if ln < 1e-4: + continue + rn /= ln + peak = np.array([0.0, 0.15, 0.0]) + a_l, a_r = a - rn * 0.15, a + rn * 0.15 + b_l, b_r = b - rn * 0.15, b + rn * 0.15 + a_p, b_p = a + peak, b + peak + roof_detail_mats[roof_mat].append(np.stack([a_l, b_l, b_p], axis=0)) + roof_detail_mats[roof_mat].append(np.stack([a_l, b_p, a_p], axis=0)) + roof_detail_mats[roof_mat].append(np.stack([a_r, a_p, b_p], axis=0)) + roof_detail_mats[roof_mat].append(np.stack([a_r, b_p, b_r], axis=0)) + + if arch_style == "residential" and pitched_planes: + h_byte = hashlib.blake2b(bldg_uuid.encode("utf-8"), digest_size=1).digest()[0] + if h_byte % 4 == 0: + origin, u_axis, v_axis, n_axis, poly = max(pitched_planes, key=lambda it: it[4].area) + if poly.area > 55.0: + rp = poly.representative_point() + c3 = origin + rp.x * u_axis + rp.y * v_axis + cy = float(c3[1]) + up_v = np.array([0.0, 1.0, 0.0]) + cu = np.array([1.0, 0.0, 0.0]) + cz = np.array([0.0, 0.0, 1.0]) + append_box_face_outward( + roof_detail_mats["stone_trim"], np.array([c3[0], cy - 0.4, c3[2]]), + cu, up_v, cz, -0.32, 0.32, 0.0, 1.45, -0.32, 0.32, include_back=False, + ) + append_box_face_outward( + roof_detail_mats["stone_trim"], np.array([c3[0], cy + 1.05, c3[2]]), + cu, up_v, cz, -0.40, 0.40, 0.0, 0.14, -0.40, 0.40, include_back=False, + ) + + return ( + bldg_uuid, + arch_style, + objektart, + in_core, + wall_planes, + lod1_wall_tris, + lod1_roof_tris, + lod2_wall_tris, + lod2_roof_tris, + list(skirt_tris_simp) if len(skirt_tris_simp) > 0 else [], + dict(roof_detail_mats), + ) + + +def generate_lod1_building( + prepared: tuple, + bay_scale: float = 1.0, +) -> dict[str, list[np.ndarray]]: + """ + Derive procedural LOD1 architectural geometry from precomputed semantic Wall & Roof planes: + - Subdivides vertical walls (>3.5m tall, >3.0m wide) into realistic floor bays & architectural openings + - Attaches precomputed pitched roof eaves overhang (~0.35m), ridge caps, and chimneys + Returns dict mapping material key -> list of (3,3) triangle arrays. + """ + ( + _bldg_uuid, + arch_style, + objektart, + in_core, + wall_planes, + lod1_wall_tris, + lod1_roof_tris, + _lod2_wall_tris, + _lod2_roof_tris, + skirt_tris, + roof_detail_mats, + ) = prepared + out: dict[str, list[np.ndarray]] = defaultdict(list) + + wall_mat = { + "fortress": "wall_fortress", + "industrial": "wall_industrial", + "residential": "wall_plaster", + }[arch_style] + roof_mat = { + "fortress": "roof_fortress", + "industrial": "roof_industrial", + "residential": "roof_terracotta", + }[arch_style] + trim_mat = "stone_trim" if arch_style != "industrial" else "concrete_trim" + + if lod1_wall_tris: + out[wall_mat].extend(lod1_wall_tris) + if skirt_tris: + out["foundation_stone"].extend(skirt_tris) + + # 1. Procedural facade detailing from merged vertical semantic Wall panels + # Prioritize Old Town core & fortress landmarks with rich window bays, while scaling outer suburbs cleanly + local_scale = (bay_scale * 0.72) if in_core else (bay_scale * 1.65) + area_thresh = (14.0 * (local_scale ** 1.15)) if in_core else (34.0 * (bay_scale ** 1.55)) + eff_bay_scale = min(max(1.0, local_scale), 2.4) + for origin, u_axis, v_axis, n_axis, poly in wall_planes: + if abs(n_axis[1]) > 0.25: + continue # non-vertical wall slope + umin, vmin, umax, vmax = poly.bounds + w = umax - umin + h = vmax - vmin + # Always detail fortress hero walls (>14m2); prioritize larger facades first on residential/industrial + min_area = 14.0 if arch_style == "fortress" else area_thresh + if h <= 3.5 or w <= 3.2 or poly.area < min_area: + continue + + if arch_style == "fortress": + if objektart == "Mauer gross": + if w >= 6.0: + n_but = max(2, min(7, int(w / (8.0 * eff_bay_scale)) + 1)) + for bi in range(n_but): + bu = umin + 0.6 + (w - 1.2) * (bi / max(1, n_but - 1)) + if poly.contains(box(bu - 0.25, vmin + 0.2, bu + 0.25, vmax - 0.2)): + append_lean_ledge( + out[trim_mat], origin, u_axis, v_axis, n_axis, + bu - 0.24, bu + 0.24, vmin, vmax - 0.1, 0.34, top_bevel=True, + ) + if poly.contains(box(umin + 0.2, vmax - 0.35, umax - 0.2, vmax - 0.05)): + append_quad_outward( + out[trim_mat], origin, u_axis, v_axis, n_axis, + umin - 0.06, umax + 0.06, vmax - 0.24, vmax + 0.04, 0.18, + ) + else: + if w >= 7.5: + n_but = max(2, min(7, int(w / (8.0 * eff_bay_scale)) + 1)) + for bi in range(n_but): + bu = umin + 0.45 + (w - 0.9) * (bi / max(1, n_but - 1)) + if poly.contains(box(bu - 0.25, vmin + 0.3, bu + 0.25, vmax - 0.3)): + append_lean_ledge( + out[trim_mat], origin, u_axis, v_axis, n_axis, + bu - 0.22, bu + 0.22, vmin, vmax - 0.15, 0.32, top_bevel=True, + ) + bay_w = 3.2 * eff_bay_scale + story_h = 3.8 + nx = max(1, int((w - 1.2) / bay_w)) + ny = max(1, int((h - 1.0) / story_h)) + step_u = (w - 1.2) / nx + step_v = (h - 1.0) / ny + for iy in range(ny): + vc = vmin + 0.6 + (iy + 0.52) * step_v + win_h = min(2.1, step_v * 0.56) + win_w = 0.58 + for ix in range(nx): + uc = umin + 0.6 + (ix + 0.5) * step_u + if poly.contains(box(uc - 0.45, vc - win_h * 0.5 - 0.2, uc + 0.45, vc + win_h * 0.5 + 0.2)): + append_quad_outward( + out["window_glass"], origin, u_axis, v_axis, n_axis, + uc - win_w * 0.5, uc + win_w * 0.5, vc - win_h * 0.5, vc + win_h * 0.5, 0.03, + ) + append_quad_outward( + out[trim_mat], origin, u_axis, v_axis, n_axis, + uc - win_w * 0.72, uc + win_w * 0.72, vc - win_h * 0.5 - 0.16, vc - win_h * 0.5, 0.14, + ) + append_quad_outward( + out[trim_mat], origin, u_axis, v_axis, n_axis, + uc - win_w * 0.72, uc + win_w * 0.72, vc + win_h * 0.5, vc + win_h * 0.5 + 0.18, 0.14, + ) + + elif arch_style == "industrial": + story_h = 3.5 + ny = max(1, int((h - 0.6) / story_h)) + step_v = (h - 0.5) / ny + if w >= 6.0: + door_step = 6.2 * eff_bay_scale + nd = max(1, int((w - 1.4) / door_step)) + du = (w - 1.4) / nd + for ix in range(nd): + uc = umin + 0.7 + (ix + 0.5) * du + dw = min(3.4, du * 0.62) + dh = min(3.0, step_v * 0.82) + if poly.contains(box(uc - dw * 0.5 - 0.15, vmin + 0.05, uc + dw * 0.5 + 0.15, vmin + dh + 0.2)): + append_quad_outward( + out["industrial_door"], origin, u_axis, v_axis, n_axis, + uc - dw * 0.5, uc + dw * 0.5, vmin + 0.05, vmin + dh, 0.03, + ) + append_quad_outward( + out[trim_mat], origin, u_axis, v_axis, n_axis, + uc - dw * 0.54, uc + dw * 0.54, vmin + dh, vmin + dh + 0.18, 0.14, + ) + for iy in range(1 if w >= 6.0 and ny > 1 else 0, ny): + vc = vmin + 0.3 + (iy + 0.62) * step_v + ch = min(0.95, step_v * 0.34) + cw = w - 1.2 + if cw >= 2.2 and poly.contains(box(umin + 0.5, vc - ch * 0.5 - 0.1, umax - 0.5, vc + ch * 0.5 + 0.1)): + append_quad_outward( + out["window_glass"], origin, u_axis, v_axis, n_axis, + umin + 0.6, umax - 0.6, vc - ch * 0.5, vc + ch * 0.5, 0.03, + ) + append_quad_outward( + out[trim_mat], origin, u_axis, v_axis, n_axis, + umin + 0.55, umax - 0.55, vc - ch * 0.5 - 0.11, vc - ch * 0.5, 0.12, + ) + + else: + # Residential / Old Town / Civic: ~3.1m stories, ~2.4m-3.4m multi-bay windows + story_h = 3.1 + bay_w = 2.4 * eff_bay_scale + ny = max(1, int((h - 0.5) / story_h)) + nx = max(1, int((w - 0.7) / bay_w)) + step_v = (h - 0.4) / ny + step_u = (w - 0.6) / nx + + # Subtle horizontal floor belt-courses on multi-story main facades + if ny >= 3 and w >= 7.0: + for iy in range(1, ny): + bv = vmin + 0.2 + iy * step_v + if poly.contains(box(umin + 0.25, bv - 0.08, umax - 0.25, bv + 0.08)): + append_quad_outward( + out[trim_mat], origin, u_axis, v_axis, n_axis, + umin + 0.05, umax - 0.05, bv - 0.07, bv + 0.07, 0.08, + ) + + win_w = min(1.15, step_u * 0.48) + win_h = min(1.48, step_v * 0.52) + has_lintel = w >= 7.0 and bay_scale <= 1.25 + for iy in range(ny): + vc = vmin + 0.25 + (iy + 0.52) * step_v + for ix in range(nx): + uc = umin + 0.3 + (ix + 0.5) * step_u + if poly.contains( + box(uc - win_w * 0.62, vc - win_h * 0.55 - 0.14, uc + win_w * 0.62, vc + win_h * 0.55 + 0.14) + ): + append_quad_outward( + out["window_glass"], origin, u_axis, v_axis, n_axis, + uc - win_w * 0.5, uc + win_w * 0.5, vc - win_h * 0.5, vc + win_h * 0.5, 0.03, + ) + append_quad_outward( + out[trim_mat], origin, u_axis, v_axis, n_axis, + uc - win_w * 0.58, uc + win_w * 0.58, vc - win_h * 0.5 - 0.13, vc - win_h * 0.5, 0.13, + ) + if has_lintel: + append_quad_outward( + out[trim_mat], origin, u_axis, v_axis, n_axis, + uc - win_w * 0.56, uc + win_w * 0.56, vc + win_h * 0.5, vc + win_h * 0.5 + 0.11, 0.09, + ) + + # 2. Precomputed Roof detailing: eaves overhang (~0.35m), ridge caps, chimneys + if lod1_roof_tris: + out[roof_mat].extend(lod1_roof_tris) + for mk, tlist in roof_detail_mats.items(): + if tlist: + out[mk].extend(tlist) + + return out + + +# --------------------------------------------------------------------------- +# Fast GLB exporter (indexed flat-shaded per material) +# --------------------------------------------------------------------------- +MATERIAL_SPECS: dict[str, tuple[tuple[float, float, float, float], float, float]] = { + # name: ((r, g, b, a), metallic, roughness) + "roof_terracotta": ((0.50, 0.16, 0.09, 1.0), 0.02, 0.74), + "roof_fortress": ((0.19, 0.21, 0.24, 1.0), 0.05, 0.78), + "roof_industrial": ((0.29, 0.32, 0.35, 1.0), 0.12, 0.80), + "wall_plaster": ((0.76, 0.67, 0.55, 1.0), 0.00, 0.86), + "wall_fortress": ((0.35, 0.31, 0.26, 1.0), 0.02, 0.90), + "wall_industrial": ((0.48, 0.48, 0.46, 1.0), 0.08, 0.84), + "foundation_stone": ((0.22, 0.20, 0.18, 1.0), 0.02, 0.93), + "stone_trim": ((0.52, 0.48, 0.42, 1.0), 0.02, 0.86), + "concrete_trim": ((0.42, 0.43, 0.44, 1.0), 0.06, 0.85), + "window_glass": ((0.04, 0.07, 0.11, 1.0), 0.25, 0.12), + "industrial_door": ((0.16, 0.19, 0.22, 1.0), 0.45, 0.55), +} + + +def export_glb(mat_tris: dict[str, list[np.ndarray]], out_path: Path, mesh_name: str) -> tuple[int, int]: + out_path.parent.mkdir(parents=True, exist_ok=True) + blob = bytearray() + buffer_views = [] + accessors = [] + materials = [] + primitives = [] + + total_tris = 0 + for mat_idx, (mat_name, tri_list) in enumerate(sorted(mat_tris.items())): + if not tri_list: + continue + tris = np.asarray(tri_list, dtype=np.float32) # (N, 3, 3) + # Filter degenerate triangles + e1 = tris[:, 1] - tris[:, 0] + e2 = tris[:, 2] - tris[:, 0] + cross = np.cross(e1, e2) + nlen = np.linalg.norm(cross, axis=1) + valid = nlen > 1e-6 + tris = tris[valid] + if len(tris) == 0: + continue + n_face = (cross[valid] / nlen[valid, None]).astype(np.float32) + + total_tris += len(tris) + raw_verts = tris.reshape(-1, 3) # (N*3, 3) + raw_norms = np.repeat(n_face, 3, axis=0) # (N*3, 3) + + # Deduplicate vertices sharing identical (position, hard-surface normal) + q_pos = np.round(raw_verts * 2000.0).astype(np.int64) + q_nrm = np.round(raw_norms * 250.0).astype(np.int64) + keys = np.ascontiguousarray(np.hstack([q_pos, q_nrm])).view( + np.dtype((np.void, 6 * 8)) + ).ravel() + _, uniq_idx, inv_idx = np.unique(keys, return_index=True, return_inverse=True) + verts = np.ascontiguousarray(raw_verts[uniq_idx], dtype=np.float32) + norms = np.ascontiguousarray(raw_norms[uniq_idx], dtype=np.float32) + if len(verts) < 65535: + indices = inv_idx.astype(np.uint16) + idx_comp_type = pygltflib.UNSIGNED_SHORT + idx_elem_bytes = 2 + else: + indices = inv_idx.astype(np.uint32) + idx_comp_type = pygltflib.UNSIGNED_INT + idx_elem_bytes = 4 + + # Position buffer view + while len(blob) % 4 != 0: + blob.append(0) + pos_off = len(blob) + blob.extend(verts.tobytes()) + pos_bv = len(buffer_views) + buffer_views.append(pygltflib.BufferView(buffer=0, byteOffset=pos_off, byteLength=len(verts) * 12, target=pygltflib.ARRAY_BUFFER)) + pos_acc = len(accessors) + accessors.append( + pygltflib.Accessor( + bufferView=pos_bv, + componentType=pygltflib.FLOAT, + count=len(verts), + type=pygltflib.VEC3, + min=verts.min(axis=0).tolist(), + max=verts.max(axis=0).tolist(), + ) + ) + + # Normal buffer view + nrm_off = len(blob) + blob.extend(norms.tobytes()) + nrm_bv = len(buffer_views) + buffer_views.append(pygltflib.BufferView(buffer=0, byteOffset=nrm_off, byteLength=len(norms) * 12, target=pygltflib.ARRAY_BUFFER)) + nrm_acc = len(accessors) + accessors.append( + pygltflib.Accessor( + bufferView=nrm_bv, + componentType=pygltflib.FLOAT, + count=len(norms), + type=pygltflib.VEC3, + ) + ) + + # Index buffer view + while len(blob) % 4 != 0: + blob.append(0) + idx_off = len(blob) + blob.extend(indices.tobytes()) + idx_bv = len(buffer_views) + buffer_views.append( + pygltflib.BufferView( + buffer=0, byteOffset=idx_off, byteLength=len(indices) * idx_elem_bytes, target=pygltflib.ELEMENT_ARRAY_BUFFER + ) + ) + idx_acc = len(accessors) + accessors.append( + pygltflib.Accessor( + bufferView=idx_bv, + componentType=idx_comp_type, + count=len(indices), + type=pygltflib.SCALAR, + ) + ) + + col, met, rough = MATERIAL_SPECS[mat_name] + m_id = len(materials) + materials.append( + pygltflib.Material( + name=mat_name, + pbrMetallicRoughness=pygltflib.PbrMetallicRoughness( + baseColorFactor=list(col), + metallicFactor=met, + roughnessFactor=rough, + ), + ) + ) + primitives.append( + pygltflib.Primitive( + attributes=pygltflib.Attributes(POSITION=pos_acc, NORMAL=nrm_acc), + indices=idx_acc, + material=m_id, + ) + ) + + gltf = pygltflib.GLTF2( + asset=pygltflib.Asset(version="2.0", generator="RustToDust Sion Map Baker"), + scene=0, + scenes=[pygltflib.Scene(nodes=[0])], + nodes=[pygltflib.Node(mesh=0, name=mesh_name)], + meshes=[pygltflib.Mesh(name=mesh_name, primitives=primitives)], + materials=materials, + buffers=[pygltflib.Buffer(byteLength=len(blob))], + bufferViews=buffer_views, + accessors=accessors, + ) + gltf.set_binary_blob(bytes(blob)) + gltf.save_binary(str(out_path)) + return total_tris, out_path.stat().st_size + + +def export_collision_bin( + tris_list: list[np.ndarray], out_path: Path, tx: int, tz: int +) -> tuple[int, int, int, list[float], list[float]]: + """ + Export compact RCOL v1 binary static collision trimesh for Ymir.AddStaticMesh: + Header (48 bytes LE): + magic[4] = b"RCOL", uint32 version = 1, int32 tx, int32 tz, + uint32 vertexCount, uint32 indexCount, + float32[3] boundsMin, float32[3] boundsMax + Payload: + float32[vertexCount * 3] positions (X, Y, Z in arena glTF space) + int32[indexCount] triangle indices (CCW outward) + """ + out_path.parent.mkdir(parents=True, exist_ok=True) + if not tris_list: + raise RuntimeError(f"Cannot export empty collision bin for tile ({tx}, {tz})") + + tris = np.asarray(tris_list, dtype=np.float32) + e1 = tris[:, 1] - tris[:, 0] + e2 = tris[:, 2] - tris[:, 0] + cross = np.cross(e1, e2) + valid = np.linalg.norm(cross, axis=1) > 1e-5 + tris = tris[valid] + if len(tris) == 0: + raise RuntimeError(f"All collision triangles degenerate for tile ({tx}, {tz})") + + raw_verts = tris.reshape(-1, 3) + # Position-only deduplication at 2mm grid (collision has no per-face normals) + q_pos = np.round(raw_verts * 500.0).astype(np.int64) + keys = np.ascontiguousarray(q_pos).view(np.dtype((np.void, 3 * 8))).ravel() + _, uniq_idx, inv_idx = np.unique(keys, return_index=True, return_inverse=True) + verts = np.ascontiguousarray(raw_verts[uniq_idx], dtype=" None: + parser = argparse.ArgumentParser(description="Bake Sion, Switzerland 3km tiled map assets for RustToDust.") + parser.add_argument("--repo-root", default=str(Path(__file__).resolve().parents[3])) + parser.add_argument("--cache-dir", default=os.path.join(os.environ.get("TEMP", "/tmp"), "sion-cache")) + parser.add_argument("--center-e", type=float, default=DEFAULT_CENTER_E) + parser.add_argument("--center-n", type=float, default=DEFAULT_CENTER_N) + parser.add_argument("--terrain-only", action="store_true", help="Re-bake 0.5m DEM, surface, mask & metadata.json while preserving existing tiles/ & buildings_manifest.json") + args = parser.parse_args() + + repo_root = Path(args.repo_root).resolve() + out_dir = repo_root / "assets" / "maps" / "sion" + tiles_dir = out_dir / "tiles" + out_dir.mkdir(parents=True, exist_ok=True) + tiles_dir.mkdir(parents=True, exist_ok=True) + cache_dir = Path(args.cache_dir) + cache_dir.mkdir(parents=True, exist_ok=True) + + # Cut obsolete single-monolith GLBs & legacy float32 heightmap + for obsolete in ("sion_lod2.glb", "sion_lod1.glb", "heightmap.f32"): + obs_path = out_dir / obsolete + if obs_path.exists(): + obs_path.unlink() + print(f"[Sion Baker] Removed obsolete {obs_path.name}") + if not args.terrain_only: + for stale in tiles_dir.iterdir(): + if stale.is_file(): + stale.unlink() + + cE, cN = args.center_e, args.center_n + e0, n0, e1, n1 = cE - HALF_EXTENT_M, cN - HALF_EXTENT_M, cE + HALF_EXTENT_M, cN + HALF_EXTENT_M + + print( + f"[Sion Baker] Arena {ARENA_SIZE_M:.0f}m x {ARENA_SIZE_M:.0f}m (terrain {TILE_GRID}x{TILE_GRID} @ {TILE_SIZE_M:.0f}m, " + f"bldg {BUILDING_TILE_GRID}x{BUILDING_TILE_GRID} @ {BUILDING_TILE_SIZE_M:.0f}m) " + f"EPSG:2056 center=({cE:.1f}, {cN:.1f}) bbox=[{e0:.1f}..{e1:.1f}, {n0:.1f}..{n1:.1f}]" + ) + tif_paths, gdb_paths, stac_ids = acquire_swisstopo_data(cache_dir, e0, n0, e1, n1) + + wms_masks: dict[str, np.ndarray] | None = None + try: + wms_masks = acquire_wms_masks(cache_dir, e0, n0, e1, n1, SURFACE_TEX_RES) + except Exception as exc: + print(f" [WMS warning] Falling back to DEM-only river/road synthesis ({exc})") + + print(f"[Sion Baker] Stitching & resampling swissALTI3D 0.5m to {GRID_RES}x{GRID_RES}...") + hm, surf_dem_asl, base_elev, min_y, max_y = build_heightmap(tif_paths, cE, cN) + hm_path = out_dir / "heightmap_05m.u16z" + hm_min_y, hm_scale, dem_hash = export_heightmap_u16z(hm, hm_path) + print( + f" heightmap_05m.u16z: {hm.shape}, {hm_path.stat().st_size:,} bytes, " + f"baseElevationM={base_elev:.2f}m, Y=[{min_y:.2f}, {max_y:.2f}]m (scale={hm_scale:.6f}m/step, sha256={dem_hash[:12]}...)" + ) + + if args.terrain_only: + meta_path = out_dir / "metadata.json" + existing_meta = json.loads(meta_path.read_text(encoding="utf-8")) if meta_path.exists() else {} + manifest_path = out_dir / "buildings_manifest.json" + manifest_data = json.loads(manifest_path.read_text(encoding="utf-8")) + fp_res_tris: list[np.ndarray] = [] + fp_ind_tris: list[np.ndarray] = [] + fp_fort_tris: list[np.ndarray] = [] + for b in manifest_data.get("buildings", []): + cx, cz = float(b["center"][0]), float(b["center"][2]) + hx, hz = float(b["size"][0]) * 0.5, float(b["size"][2]) * 0.5 + gy = float(b.get("groundY", 0.0)) + p0 = np.array([cx - hx, gy, cz - hz]) + p1 = np.array([cx + hx, gy, cz - hz]) + p2 = np.array([cx + hx, gy, cz + hz]) + p3 = np.array([cx - hx, gy, cz + hz]) + t1 = np.stack([p0, p1, p2], axis=0) + t2 = np.stack([p0, p2, p3], axis=0) + st = b.get("archStyle", "residential") + if st == "fortress": + fp_fort_tris.extend((t1, t2)) + elif st == "industrial": + fp_ind_tris.extend((t1, t2)) + else: + fp_res_tris.extend((t1, t2)) + + print(f"[Sion Baker] Synthesizing {SURFACE_TEX_RES}x{SURFACE_TEX_RES} terrain_surface.png + {SURFACE_MASK_RES}x{SURFACE_MASK_RES} terrain_surface_mask.png...") + surf_png, mask_png = build_terrain_surface_texture( + surf_dem_asl, base_elev, wms_masks, fp_res_tris, fp_ind_tris, fp_fort_tris + ) + surf_path = out_dir / "terrain_surface.png" + surf_path.write_bytes(surf_png) + mask_path = out_dir / "terrain_surface_mask.png" + mask_path.write_bytes(mask_png) + print(f" terrain_surface.png: {len(surf_png):,} bytes ({len(surf_png)/1e6:.2f} MB)") + print(f" terrain_surface_mask.png: {len(mask_png):,} bytes ({len(mask_png)/1e6:.2f} MB)") + + meta = { + "name": "Sion, Valais, Switzerland", + "attribution": "Federal Office of Topography swisstopo", + "sources": [ + "ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)", + "ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)", + ], + "stacItems": stac_ids, + "demAssetHash": dem_hash, + "crs": "EPSG:2056", + "originE": e0, + "originN": n0, + "centerE": cE, + "centerN": cN, + "baseElevationM": base_elev, + "minY": round(min_y, 3), + "maxY": round(max_y, 3), + "reliefM": round(max_y - min_y, 3), + "sizeMeters": ARENA_SIZE_M, + "tileGrid": TILE_GRID, + "tileSizeMeters": TILE_SIZE_M, + "buildingTileGrid": BUILDING_TILE_GRID, + "buildingTileSizeMeters": BUILDING_TILE_SIZE_M, + "gridRes": GRID_RES, + "cellSizeMeters": CELL_SIZE_M, + "heightmapFile": "heightmap_05m.u16z", + "heightmapFormat": "rdhm_v2_u16_zigzag_zlib", + "heightmapMinY": hm_min_y, + "heightmapScale": hm_scale, + "surfaceTexture": "terrain_surface.png", + "surfaceTextureSize": SURFACE_TEX_RES, + "surfaceTextureFormat": "png_rgb_north_to_south_west_to_east", + "surfaceMaskTexture": "terrain_surface_mask.png", + "surfaceMaskTextureSize": SURFACE_MASK_RES, + "surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water", + "collisionFormat": existing_meta.get("collisionFormat", {}), + "rowOrder": "north_to_south_z_neg_to_pos", + "colOrder": "west_to_east_x_neg_to_pos", + "coordinateTransform": { + "X": "E - centerE (East = +X)", + "Y": "Z_asl - baseElevationM (Up = +Y)", + "Z": "-(N - centerN) (North = -Z)", + }, + "tileCount": existing_meta.get("tileCount", len(existing_meta.get("tiles", []))), + "tiles": existing_meta.get("tiles", []), + } + meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8") + total_assets_bytes = sum(p.stat().st_size for p in out_dir.rglob("*") if p.is_file()) + print(f"[Sion Baker] Terrain-only complete | Total assets/maps/sion = {total_assets_bytes/1e6:.2f} MB (< {MAX_TOTAL_ASSETS_BYTES/1e6:.0f} MB limit)") + if total_assets_bytes >= MAX_TOTAL_ASSETS_BYTES: + raise RuntimeError(f"Total asset budget exceeded: {total_assets_bytes} bytes >= {MAX_TOTAL_ASSETS_BYTES}") + return + + # Read semantic layers across intersecting GDB tiles + print("[Sion Baker] Reading swissBUILDINGS3D 3.0 layers (Building_solid, Wall, Roof, Floor)...") + reader = OgrReader() + bbox = (e0, n0, e1, n1) + fields = ["UUID", "OBJEKTART", "NAME_KOMPLETT", "DACH_MIN", "DACH_MAX", "GELAENDEPUNKT", "EGID"] + + solids_by_uuid: dict[str, tuple[dict, list[np.ndarray]]] = {} + walls_by_uuid: dict[str, tuple[dict, list[np.ndarray]]] = {} + floors_by_uuid: dict[str, tuple[dict, list[np.ndarray]]] = {} + roofs_list: list[tuple[dict, list[np.ndarray]]] = [] + + for gdb in gdb_paths: + for attrs, faces in reader.read_layer(str(gdb), "Building_solid", bbox, fields): + u = str(attrs.get("UUID", "")) + if u and u not in solids_by_uuid: + solids_by_uuid[u] = (attrs, faces) + for attrs, faces in reader.read_layer(str(gdb), "Wall", bbox, fields): + u = str(attrs.get("UUID", "")) + if u and u not in walls_by_uuid: + walls_by_uuid[u] = (attrs, faces) + for attrs, faces in reader.read_layer(str(gdb), "Floor", bbox, fields): + u = str(attrs.get("UUID", "")) + if u and u not in floors_by_uuid: + floors_by_uuid[u] = (attrs, faces) + for attrs, faces in reader.read_layer(str(gdb), "Roof", bbox, fields): + roofs_list.append((attrs, faces)) + + # Index roofs by UUID, and attach orphan/empty-UUID roofs by EGID or 2D AABB overlap + roofs_by_uuid: dict[str, list[list[np.ndarray]]] = defaultdict(list) + bldg_egids: dict[str, str] = {} + bldg_boxes: list[tuple[str, float, float, float, float]] = [] + for u, (attrs, faces) in walls_by_uuid.items(): + pts = np.vstack(faces) + bldg_boxes.append((u, float(pts[:, 0].min()), float(pts[:, 1].min()), float(pts[:, 0].max()), float(pts[:, 1].max()))) + egid = str(attrs.get("EGID", "")).strip() + if egid: + bldg_egids[egid] = u + + standalone_roofs: list[tuple[str, dict, list[np.ndarray]]] = [] + seen_roof_sigs: set[tuple[int, int, int]] = set() + for idx_r, (attrs, faces) in enumerate(roofs_list): + pts = np.vstack(faces) + sig = (int(round(pts[:, 0].mean() * 10)), int(round(pts[:, 1].mean() * 10)), len(faces)) + if sig in seen_roof_sigs: + continue + seen_roof_sigs.add(sig) + u = str(attrs.get("UUID", "")).strip() + if u and u in walls_by_uuid: + roofs_by_uuid[u].append(faces) + continue + egid = str(attrs.get("EGID", "")).strip() + if egid and egid in bldg_egids: + roofs_by_uuid[bldg_egids[egid]].append(faces) + continue + rx, ry = float(pts[:, 0].mean()), float(pts[:, 1].mean()) + matched_u = None + for bu, bx0, by0, bx1, by1 in bldg_boxes: + if bx0 - 0.5 <= rx <= bx1 + 0.5 and by0 - 0.5 <= ry <= by1 + 0.5: + matched_u = bu + break + if matched_u: + roofs_by_uuid[matched_u].append(faces) + else: + standalone_roofs.append((u or f"roof_{idx_r:04d}", attrs, faces)) + + print( + f" Raw extracted: {len(walls_by_uuid)} wall-buildings, " + f"{len(roofs_by_uuid)} matched roofs, {len(standalone_roofs)} roof-only structures" + ) + + # Spatial 6x6 tile buckets + tile_lod2_mats: dict[tuple[int, int], dict[str, list[np.ndarray]]] = defaultdict(lambda: defaultdict(list)) + tile_col_tris: dict[tuple[int, int], list[np.ndarray]] = defaultdict(list) + tile_lod1_prepared: dict[tuple[int, int], list[tuple]] = defaultdict(list) + tile_bldg_counts: Counter[tuple[int, int]] = Counter() + + fp_res_tris: list[np.ndarray] = [] + fp_ind_tris: list[np.ndarray] = [] + fp_fort_tris: list[np.ndarray] = [] + + manifest_entries: list[dict] = [] + class_counts: Counter[str] = Counter() + + all_records: list[tuple[str, dict, list[np.ndarray], list[np.ndarray], list[np.ndarray], list[np.ndarray]]] = [] + for u, (attrs, w_faces) in walls_by_uuid.items(): + r_faces = [f for grp in roofs_by_uuid.get(u, []) for f in grp] + fl_faces = floors_by_uuid[u][1] if u in floors_by_uuid else [] + s_faces = solids_by_uuid[u][1] if u in solids_by_uuid else [] + all_records.append((u, attrs, w_faces, r_faces, fl_faces, s_faces)) + for u, attrs, r_faces in standalone_roofs: + all_records.append((u, attrs, [], r_faces, [], [])) + + bldg_seq = 0 + for u, attrs, w_faces_enz, r_faces_enz, fl_faces_enz, s_faces_enz in all_records: + all_enz = np.vstack(w_faces_enz + r_faces_enz + fl_faces_enz) + cx_enz, cy_enz = float(all_enz[:, 0].mean()), float(all_enz[:, 1].mean()) + # Keep buildings whose centroid falls inside the 3072x3072 arena (with 2m edge margin) + if not (e0 + 2.0 <= cx_enz <= e1 - 2.0 and n0 + 2.0 <= cy_enz <= n1 - 2.0): + continue + + bldg_seq += 1 + bid = f"sion_{bldg_seq:04d}" + objektart = str(attrs.get("OBJEKTART", "") or "Gebaeude Einzelhaus") + name = str(attrs.get("NAME_KOMPLETT", "") or "") + class_counts[objektart] += 1 + + w_rtd = [enz_to_rtd(f, cE, cN, base_elev) for f in w_faces_enz] + r_rtd = [enz_to_rtd(f, cE, cN, base_elev) for f in r_faces_enz] + fl_rtd = [enz_to_rtd(f, cE, cN, base_elev) for f in fl_faces_enz] + s_rtd = [enz_to_rtd(f, cE, cN, base_elev) for f in s_faces_enz] + + solid_tris = np.concatenate([triangulate_polygon_3d(f) for f in s_rtd], axis=0) if s_rtd else None + all_rtd_pts = np.vstack(w_rtd + r_rtd + fl_rtd) + bldg_center = all_rtd_pts.mean(axis=0) + bmin = all_rtd_pts.min(axis=0) + bmax = all_rtd_pts.max(axis=0) + box_center = (bmin + bmax) * 0.5 + + tx = max(0, min(BUILDING_TILE_GRID - 1, int(math.floor((float(box_center[0]) + HALF_EXTENT_M) / BUILDING_TILE_SIZE_M)))) + tz = max(0, min(BUILDING_TILE_GRID - 1, int(math.floor((float(box_center[2]) + HALF_EXTENT_M) / BUILDING_TILE_SIZE_M)))) + tkey = (tx, tz) + tile_bldg_counts[tkey] += 1 + + w_oriented = orient_faces_outward(w_rtd, solid_tris, "Wall", bldg_center) + r_oriented = orient_faces_outward(r_rtd, solid_tris, "Roof", bldg_center) + fl_oriented = orient_faces_outward(fl_rtd, solid_tris, "Floor", bldg_center) + + arch_style = classify_building(objektart, name, all_enz, r_oriented) + wall_mat = {"fortress": "wall_fortress", "industrial": "wall_industrial", "residential": "wall_plaster"}[arch_style] + roof_mat = {"fortress": "roof_fortress", "industrial": "roof_industrial", "residential": "roof_terracotta"}[arch_style] + + wall_tris = np.concatenate([triangulate_polygon_3d(f) for f in w_oriented], axis=0) if w_oriented else np.zeros((0, 3, 3)) + roof_tris = np.concatenate([triangulate_polygon_3d(f) for f in r_oriented], axis=0) if r_oriented else np.zeros((0, 3, 3)) + + min_bldg_y = float(all_rtd_pts[:, 1].min()) + max_bldg_y = float(all_rtd_pts[:, 1].max()) + skirt_tol = 0.35 if arch_style == "fortress" else 0.85 + skirt_tris_simp = build_foundation_skirt_tris(wall_tris, fl_oriented, hm, min_bldg_y, simplify_tol=skirt_tol) + in_core = (arch_style == "fortress") or (math.hypot(float(box_center[0]), float(box_center[2])) < 680.0) + + prep = prepare_lod1_building(u, arch_style, objektart, in_core, w_oriented, r_oriented, wall_tris, roof_tris, skirt_tris_simp) + tile_lod1_prepared[tkey].append(prep) + + # Clean coplanar LOD2 hull (walls + roofs + simplified foundation skirt; omits buried downward floor caps) + clean_walls = prep[7] + clean_roofs = prep[8] + clean_skirts = prep[9] + + # Footprint triangles for terrain_surface.png plaza masks + if clean_roofs: + if arch_style == "fortress": + fp_fort_tris.extend(clean_roofs) + elif arch_style == "industrial": + fp_ind_tris.extend(clean_roofs) + else: + fp_res_tris.extend(clean_roofs) + + if clean_walls: + tile_lod2_mats[tkey][wall_mat].extend(clean_walls) + tile_col_tris[tkey].extend(clean_walls) + if clean_roofs: + tile_lod2_mats[tkey][roof_mat].extend(clean_roofs) + tile_col_tris[tkey].extend(clean_roofs) + if clean_skirts: + tile_lod2_mats[tkey]["foundation_stone"].extend(clean_skirts) + + manifest_entries.append( + { + "id": bid, + "uuid": u, + "name": name, + "class": objektart, + "archStyle": arch_style, + "tile": [tx, tz], + "center": [round(float(v), 3) for v in box_center], + "size": [round(float(v), 3) for v in (bmax - bmin)], + "groundY": round(min_bldg_y, 3), + "roofY": round(max_bldg_y, 3), + "wallCount": int(len(clean_walls)), + "roofCount": int(len(clean_roofs)), + } + ) + + # Bake 4096x4096 terrain_surface.png albedo + 2048x2048 terrain_surface_mask.png + print(f"[Sion Baker] Synthesizing {SURFACE_TEX_RES}x{SURFACE_TEX_RES} terrain_surface.png + {SURFACE_MASK_RES}x{SURFACE_MASK_RES} terrain_surface_mask.png...") + surf_png, mask_png = build_terrain_surface_texture( + surf_dem_asl, base_elev, wms_masks, fp_res_tris, fp_ind_tris, fp_fort_tris + ) + surf_path = out_dir / "terrain_surface.png" + surf_path.write_bytes(surf_png) + mask_path = out_dir / "terrain_surface_mask.png" + mask_path.write_bytes(mask_png) + print(f" terrain_surface.png: {len(surf_png):,} bytes ({len(surf_png)/1e6:.2f} MB)") + print(f" terrain_surface_mask.png: {len(mask_png):,} bytes ({len(mask_png)/1e6:.2f} MB)") + if len(surf_png) >= MAX_SURFACE_PNG_BYTES: + raise RuntimeError(f"terrain_surface.png exceeded budget: {len(surf_png)} bytes") + + # Export per-tile LOD2 GLBs & RCOL v1 collision bins + non_empty_tiles = sorted(tile_bldg_counts.keys()) + tile_stats: dict[tuple[int, int], dict] = {} + total_lod2_tris = 0 + total_lod2_bytes = 0 + total_col_tris = 0 + total_col_bytes = 0 + + for tkey in non_empty_tiles: + tx, tz = tkey + lod2_path = tiles_dir / f"lod2_{tx}_{tz}.glb" + col_path = tiles_dir / f"col_{tx}_{tz}.bin" + l2_tris, l2_bytes = export_glb(tile_lod2_mats[tkey], lod2_path, f"Sion_LOD2_{tx}_{tz}") + c_verts, c_tris, c_bytes, bmin, bmax = export_collision_bin(tile_col_tris[tkey], col_path, tx, tz) + total_lod2_tris += l2_tris + total_lod2_bytes += l2_bytes + total_col_tris += c_tris + total_col_bytes += c_bytes + tile_cx = -HALF_EXTENT_M + (tx + 0.5) * BUILDING_TILE_SIZE_M + tile_cz = -HALF_EXTENT_M + (tz + 0.5) * BUILDING_TILE_SIZE_M + tile_stats[tkey] = { + "tx": tx, + "tz": tz, + "lod2": f"tiles/lod2_{tx}_{tz}.glb", + "lod1": f"tiles/lod1_{tx}_{tz}.glb", + "collision": f"tiles/col_{tx}_{tz}.bin", + "buildingCount": int(tile_bldg_counts[tkey]), + "lod2Tris": int(l2_tris), + "lod2Bytes": int(l2_bytes), + "colVerts": int(c_verts), + "colTris": int(c_tris), + "colBytes": int(c_bytes), + "center": [round(tile_cx, 2), 0.0, round(tile_cz, 2)], + "boundsMin": bmin, + "boundsMax": bmax, + } + + print( + f"[Sion Baker] Exported {len(non_empty_tiles)}/{TILE_GRID*TILE_GRID} non-empty LOD2+COL tiles: " + f"LOD2={total_lod2_tris:,} tris ({total_lod2_bytes/1e6:.2f} MB), " + f"COL={total_col_tris:,} tris ({total_col_bytes/1e6:.2f} MB)" + ) + + # Adaptive procedural LOD1 across all tiles so combined GLB footprint stays strictly < 28 MB + bay_scale = 1.0 + all_preps = [p for tkey in non_empty_tiles for p in tile_lod1_prepared[tkey]] + for attempt in range(16): + est_tris = 0 + for prep in all_preps: + per_mat = generate_lod1_building(prep, bay_scale=bay_scale) + est_tris += sum(len(v) for v in per_mat.values()) + print(f" LOD1 global pass (bay_scale={bay_scale:.2f}): {est_tris:,} raw tris") + if est_tris <= MAX_LOD1_TRIS: + break + bay_scale *= max(1.16, math.sqrt(est_tris / (MAX_LOD1_TRIS * 0.90))) + + total_lod1_tris = 0 + total_lod1_bytes = 0 + for tkey in non_empty_tiles: + tx, tz = tkey + t_mats: dict[str, list[np.ndarray]] = defaultdict(list) + for prep in tile_lod1_prepared[tkey]: + per_mat = generate_lod1_building(prep, bay_scale=bay_scale) + for mk, tlist in per_mat.items(): + t_mats[mk].extend(tlist) + lod1_path = tiles_dir / f"lod1_{tx}_{tz}.glb" + l1_tris, l1_bytes = export_glb(t_mats, lod1_path, f"Sion_LOD1_{tx}_{tz}") + total_lod1_tris += l1_tris + total_lod1_bytes += l1_bytes + tile_stats[tkey]["lod1Tris"] = int(l1_tris) + tile_stats[tkey]["lod1Bytes"] = int(l1_bytes) + + print( + f"[Sion Baker] Exported {len(non_empty_tiles)} LOD1 tiles (bay_scale={bay_scale:.2f}): " + f"{total_lod1_tris:,} tris ({total_lod1_bytes/1e6:.2f} MB)" + ) + + manifest = { + "map": "sion", + "coordinateSystem": "rusttodust_arena_gltf", + "attribution": "Federal Office of Topography swisstopo", + "sizeMeters": ARENA_SIZE_M, + "tileGrid": BUILDING_TILE_GRID, + "tileSizeMeters": BUILDING_TILE_SIZE_M, + "count": len(manifest_entries), + "classes": dict(class_counts.most_common()), + "buildings": manifest_entries, + } + manifest_path = out_dir / "buildings_manifest.json" + manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8") + + meta = { + "name": "Sion, Valais, Switzerland", + "attribution": "Federal Office of Topography swisstopo", + "sources": [ + "ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)", + "ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)", + ], + "stacItems": stac_ids, + "demAssetHash": dem_hash, + "crs": "EPSG:2056", + "originE": e0, + "originN": n0, + "centerE": cE, + "centerN": cN, + "baseElevationM": base_elev, + "minY": round(min_y, 3), + "maxY": round(max_y, 3), + "reliefM": round(max_y - min_y, 3), + "sizeMeters": ARENA_SIZE_M, + "tileGrid": TILE_GRID, + "tileSizeMeters": TILE_SIZE_M, + "buildingTileGrid": BUILDING_TILE_GRID, + "buildingTileSizeMeters": BUILDING_TILE_SIZE_M, + "gridRes": GRID_RES, + "cellSizeMeters": CELL_SIZE_M, + "heightmapFile": "heightmap_05m.u16z", + "heightmapFormat": "rdhm_v2_u16_zigzag_zlib", + "heightmapMinY": hm_min_y, + "heightmapScale": hm_scale, + "surfaceTexture": "terrain_surface.png", + "surfaceTextureSize": SURFACE_TEX_RES, + "surfaceTextureFormat": "png_rgb_north_to_south_west_to_east", + "surfaceMaskTexture": "terrain_surface_mask.png", + "surfaceMaskTextureSize": SURFACE_MASK_RES, + "surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water", + "collisionFormat": { + "magic": "RCOL", + "version": 1, + "headerBytes": 48, + "headerLayout": "magic[4], uint32 version, int32 tx, int32 tz, uint32 vertexCount, uint32 indexCount, float32[3] boundsMin, float32[3] boundsMax", + "vertexLayout": "float32[vertexCount * 3] (X, Y, Z in arena glTF space)", + "indexLayout": "int32[indexCount] (CCW outward triangles)", + }, + "rowOrder": "north_to_south_z_neg_to_pos", + "colOrder": "west_to_east_x_neg_to_pos", + "coordinateTransform": { + "X": "E - centerE (East = +X)", + "Y": "Z_asl - baseElevationM (Up = +Y)", + "Z": "-(N - centerN) (North = -Z)", + }, + "tileCount": len(non_empty_tiles), + "tiles": [tile_stats[k] for k in non_empty_tiles], + } + meta_path = out_dir / "metadata.json" + meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8") + + combined_glb_bytes = total_lod1_bytes + total_lod2_bytes + total_assets_bytes = sum(p.stat().st_size for p in out_dir.rglob("*") if p.is_file()) + print( + f"[Sion Baker] Summary: {len(manifest_entries)} buildings across {len(non_empty_tiles)} tiles | " + f"LOD1+LOD2 GLBs = {combined_glb_bytes/1e6:.2f} MB (< 28 MB limit) | " + f"Total assets/maps/sion = {total_assets_bytes/1e6:.2f} MB (< 85 MB limit)" + ) + if combined_glb_bytes >= MAX_TILES_GLB_BYTES: + raise RuntimeError(f"Combined tile GLB budget exceeded: {combined_glb_bytes} bytes >= {MAX_TILES_GLB_BYTES}") + if total_assets_bytes >= MAX_TOTAL_ASSETS_BYTES: + raise RuntimeError(f"Total asset budget exceeded: {total_assets_bytes} bytes >= {MAX_TOTAL_ASSETS_BYTES}") + + +if __name__ == "__main__": + main() diff --git a/tools/maps/sion/previews/sion_3km_overview.png b/tools/maps/sion/previews/sion_3km_overview.png new file mode 100644 index 0000000..01483b4 Binary files /dev/null and b/tools/maps/sion/previews/sion_3km_overview.png differ diff --git a/tools/maps/sion/previews/sion_lod1_closeup.png b/tools/maps/sion/previews/sion_lod1_closeup.png new file mode 100644 index 0000000..86b0d4e Binary files /dev/null and b/tools/maps/sion/previews/sion_lod1_closeup.png differ diff --git a/tools/maps/sion/render_previews.py b/tools/maps/sion/render_previews.py new file mode 100644 index 0000000..a26692e --- /dev/null +++ b/tools/maps/sion/render_previews.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +""" +Blender 5.3.0 headless preview renderer for Sion, Switzerland 3km tiled map assets. +Produces: + - tools/maps/sion/previews/sion_3km_overview.png + - tools/maps/sion/previews/sion_lod1_closeup.png +""" + +from __future__ import annotations + +import json +import math +import struct +import sys +from pathlib import Path + +import bpy +import numpy as np +from mathutils import Vector + + +def clear_scene() -> None: + bpy.ops.wm.read_factory_settings(use_empty=True) + + +def create_terrain_mesh(hm_path: Path, meta: dict) -> bpy.types.Object: + grid_res = int(meta["gridRes"]) + size_m = float(meta["sizeMeters"]) + half = size_m * 0.5 + step = size_m / (grid_res - 1) + + raw = hm_path.read_bytes() + expected = grid_res * grid_res * 4 + if len(raw) != expected: + raise RuntimeError(f"heightmap.f32 size mismatch: {len(raw)} != {expected}") + heights = np.frombuffer(raw, dtype=" Blender (X_east, Y_north = -Z_south, Z_up = Y_up) + xs = -half + np.arange(grid_res, dtype=np.float32) * step + zs = -half + np.arange(grid_res, dtype=np.float32) * step + gx, gz = np.meshgrid(xs, zs) # (grid_res, grid_res), row iz=0..N-1 (North->South) + verts_np = np.column_stack([gx.ravel(), (-gz).ravel(), heights.ravel()]).astype(np.float32) + + # Quad indices: iz increases southward (-Y_bl), ix increases eastward (+X_bl) + # CCW looking from +Z_bl: (r1+ix) -> (r1+ix+1) -> (r0+ix+1) -> (r0+ix) + ix = np.arange(grid_res - 1, dtype=np.int32) + iz = np.arange(grid_res - 1, dtype=np.int32) + ixg, izg = np.meshgrid(ix, iz) + r0 = izg * grid_res + ixg + r1 = (izg + 1) * grid_res + ixg + quads = np.stack([r1, r1 + 1, r0 + 1, r0], axis=-1).reshape(-1, 4) + + mesh = bpy.data.meshes.new("SionTerrainMesh") + n_verts = len(verts_np) + n_faces = len(quads) + mesh.vertices.add(n_verts) + mesh.vertices.foreach_set("co", verts_np.ravel()) + mesh.loops.add(n_faces * 4) + mesh.loops.foreach_set("vertex_index", quads.ravel()) + mesh.polygons.add(n_faces) + mesh.polygons.foreach_set("loop_start", np.arange(0, n_faces * 4, 4, dtype=np.int32)) + mesh.polygons.foreach_set("loop_total", np.full(n_faces, 4, dtype=np.int32)) + mesh.polygons.foreach_set("use_smooth", [True] * n_faces) + + # UV coordinates matching terrain_surface.png (row 0 = North -> v=1.0, row H-1 = South -> v=0.0) + u_vert = (gx.ravel() + half) / size_m + v_vert = 1.0 - (gz.ravel() + half) / size_m + uv_vert = np.column_stack([u_vert, v_vert]).astype(np.float32) + loop_vidx = quads.ravel() + uv_loops = uv_vert[loop_vidx] + uv_layer = mesh.uv_layers.new(name="UVMap") + uv_layer.data.foreach_set("uv", uv_loops.ravel()) + + mesh.update() + obj = bpy.data.objects.new("SionTerrain", mesh) + bpy.context.collection.objects.link(obj) + return obj + + +def build_terrain_material(assets_dir: Path, meta: dict) -> bpy.types.Material: + mat = bpy.data.materials.new("SionTerrainMat") + mat.use_nodes = True + nt = mat.node_tree + nt.nodes.clear() + + out = nt.nodes.new("ShaderNodeOutputMaterial") + bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") + bsdf.inputs["Roughness"].default_value = 0.86 + nt.links.new(bsdf.outputs["BSDF"], out.inputs["Surface"]) + + surf_name = meta.get("surfaceTexture", "terrain_surface.png") + surf_path = assets_dir / surf_name + if not surf_path.exists(): + raise FileNotFoundError(f"Missing terrain surface texture: {surf_path}") + + tex_coord = nt.nodes.new("ShaderNodeTexCoord") + tex_img = nt.nodes.new("ShaderNodeTexImage") + img = bpy.data.images.load(str(surf_path)) + img.colorspace_settings.name = "sRGB" + tex_img.image = img + tex_img.extension = "EXTEND" + nt.links.new(tex_coord.outputs["UV"], tex_img.inputs["Vector"]) + nt.links.new(tex_img.outputs["Color"], bsdf.inputs["Base Color"]) + return mat + + +def setup_lighting_and_world() -> None: + world = bpy.data.worlds.new("SionWorld") + bpy.context.scene.world = world + world.use_nodes = True + nt = world.node_tree + nt.nodes.clear() + out = nt.nodes.new("ShaderNodeOutputWorld") + bg = nt.nodes.new("ShaderNodeBackground") + sky = nt.nodes.new("ShaderNodeTexSky") + sky_types = [i.identifier for i in sky.bl_rna.properties["sky_type"].enum_items] + for candidate in ("MULTIPLE_SCATTERING", "NISHITA", "HOSEK_WILKIE", "PREETHAM"): + if candidate in sky_types: + sky.sky_type = candidate + break + sky.sun_elevation = math.radians(26.0) + sky.sun_rotation = math.radians(235.0) # SW afternoon sun + if hasattr(sky, "sun_disc"): + sky.sun_disc = False + if hasattr(sky, "air_density"): + sky.air_density = 1.2 + if hasattr(sky, "dust_density"): + sky.dust_density = 1.4 + bg.inputs["Strength"].default_value = 0.045 + nt.links.new(sky.outputs["Color"], bg.inputs["Color"]) + nt.links.new(bg.outputs["Background"], out.inputs["Surface"]) + + # Crisp directional sun matching sky direction + sun_data = bpy.data.lights.new("AlpineSun", type="SUN") + sun_data.energy = 2.6 + sun_data.color = (1.0, 0.96, 0.90) + sun_data.angle = math.radians(1.0) + sun_obj = bpy.data.objects.new("AlpineSun", sun_data) + bpy.context.collection.objects.link(sun_obj) + sun_dir = Vector((-0.72, -0.45, 0.52)).normalized() + sun_obj.rotation_euler = sun_dir.to_track_quat("Z", "Y").to_euler() + + +def point_camera_at(cam_obj: bpy.types.Object, target: Vector) -> None: + direction = target - cam_obj.location + cam_obj.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler() + + +def configure_renderer(scene: bpy.types.Scene, width: int = 1600, height: int = 1000) -> None: + scene.render.resolution_x = width + scene.render.resolution_y = height + scene.render.resolution_percentage = 100 + scene.render.image_settings.file_format = "PNG" + + # Prefer Cycles (GPU if available, else CPU + denoiser) for crisp shadow/recess readability + scene.render.engine = "CYCLES" + prefs = bpy.context.preferences.addons["cycles"].preferences + for dev_type in ("OPTIX", "CUDA", "HIP", "ONEAPI"): + try: + prefs.compute_device_type = dev_type + prefs.get_devices() + devices = [d for d in prefs.devices if d.type == dev_type] + if devices: + for d in prefs.devices: + d.use = (d.type == dev_type) + scene.cycles.device = "GPU" + print(f"[Render] Using Cycles GPU ({dev_type})") + break + except Exception: + continue + else: + scene.cycles.device = "CPU" + print("[Render] Using Cycles CPU") + + scene.cycles.samples = 48 + scene.cycles.use_denoising = True + scene.view_settings.view_transform = "AgX" if "AgX" in [i.identifier for i in scene.view_settings.bl_rna.properties["view_transform"].enum_items] else "Filmic" + scene.view_settings.exposure = -0.25 + + +def main() -> None: + argv = sys.argv + if "--" in argv: + argv = argv[argv.index("--") + 1 :] + else: + argv = [] + repo_root = Path(argv[0]) if argv else Path(__file__).resolve().parents[3] + + assets_dir = repo_root / "assets" / "maps" / "sion" + preview_dir = repo_root / "tools" / "maps" / "sion" / "previews" + preview_dir.mkdir(parents=True, exist_ok=True) + + meta = json.loads((assets_dir / "metadata.json").read_text(encoding="utf-8")) + manifest = json.loads((assets_dir / "buildings_manifest.json").read_text(encoding="utf-8")) + + clear_scene() + setup_lighting_and_world() + + terrain_obj = create_terrain_mesh(assets_dir / "heightmap.f32", meta) + terrain_obj.data.materials.append(build_terrain_material(assets_dir, meta)) + + # Load all tiled buildings (LOD1 for central core tiles, LOD2 for outer ring tiles) + tiles = meta.get("tiles", []) + if not tiles: + raise RuntimeError("No tiles found in metadata.json") + for t in tiles: + tx, tz = int(t["tx"]), int(t["tz"]) + use_lod1 = (1 <= tx <= 4 and 1 <= tz <= 4) + rel = t["lod1"] if use_lod1 else t["lod2"] + bpy.ops.import_scene.gltf(filepath=str(assets_dir / rel)) + + scene = bpy.context.scene + configure_renderer(scene, 1600, 1000) + + cam_data = bpy.data.cameras.new("PreviewCam") + cam_data.clip_start = 1.0 + cam_data.clip_end = 10000.0 + cam_obj = bpy.data.objects.new("PreviewCam", cam_data) + bpy.context.collection.objects.link(cam_obj) + scene.camera = cam_obj + + # 1. 3km Overview render: WSW elevated aerial framing Valere, Tourbillon, Old Town, + # railway/industrial yards, Rhone river + bridges, and terraced northern hillsides + cam_data.lens = 25.0 + cam_obj.location = Vector((-1620.0, -1380.0, 960.0)) + point_camera_at(cam_obj, Vector((110.0, 90.0, 40.0))) + scene.render.filepath = str(preview_dir / "sion_3km_overview.png") + bpy.ops.render.render(write_still=True) + print(f"[Render] Saved {scene.render.filepath}") + + # Remove obsolete 1.5km overview if present + old_overview = preview_dir / "sion_overview.png" + if old_overview.exists(): + old_overview.unlink() + + # 2. Low hero close-up: locate Valere from manifest and frame Old Town slope + Valere citadel + Tourbillon + valere = None + for b in manifest["buildings"]: + if "valère" in b.get("name", "").lower() or "valere" in b.get("name", "").lower(): + valere = b + break + if valere is not None: + vx, vy, vz = valere["center"] # glTF coords: (X, Y_up, Z_south) + target = Vector((vx - 70.0, -vz - 10.0, vy - 28.0)) # Blender coords: Old Town roofs + Valere + else: + target = Vector((15.0, 70.0, 105.0)) + + cam_data.lens = 34.0 + # Street/rooftop-level vantage in Sion Old Town looking ENE up at multi-bay facades & Valere citadel + cam_obj.location = Vector((target.x - 185.0, target.y - 125.0, target.z - 52.0)) + point_camera_at(cam_obj, target + Vector((15.0, 12.0, -6.0))) + scene.render.filepath = str(preview_dir / "sion_lod1_closeup.png") + bpy.ops.render.render(write_still=True) + print(f"[Render] Saved {scene.render.filepath}") + + +if __name__ == "__main__": + main() diff --git a/tools/vehicles/bake_vertex_weathering.py b/tools/vehicles/bake_vertex_weathering.py new file mode 100644 index 0000000..068c2f9 --- /dev/null +++ b/tools/vehicles/bake_vertex_weathering.py @@ -0,0 +1,556 @@ +"""Bake geometric weathering vertex attributes (COLOR_0) into Brokkr vehicle GLBs. + +Writes COLOR_0 (VEC4 normalized UNSIGNED_BYTE) onto every mesh primitive: + R = geometric cavity AO (0 = deep crevice, 1 = open exposed face) + G = convex dihedral edge curvature (0 = flat, 1 = sharp exposed edge) + B = connected-component per-island hash (0..1) + A = normalized rest-pose height above minY (meters / 6.0, clamped 0..1) + +Pure numpy + struct; runs in < 1s per vehicle and is idempotent on re-run. +Preserves all glTF nodes, transforms, materials, hardpoint anchors, joints, and bounds. + +Usage: + python tools/vehicles/bake_vertex_weathering.py paladin jackal + python tools/vehicles/bake_vertex_weathering.py --all +""" +from __future__ import annotations + +import argparse +import json +import math +import struct +import time +from pathlib import Path +from typing import Any + +import numpy as np + +REPO_ROOT = Path(__file__).resolve().parents[2] +VEHICLES_DIR = REPO_ROOT / "assets" / "vehicles" + +ALL_VEHICLES = ( + "jackal", "mule", "ferret", "hornet", "mammoth", "ironclad", "anvil", "condor", + "breaker", "paladin", "raptor", "manticore", "bastion", "spectre", "kestrel", +) + + +# --------------------------------------------------------------------------- +# glTF / GLB helpers +# --------------------------------------------------------------------------- + +def _node_local_matrix(node: dict[str, Any]) -> np.ndarray: + if "matrix" in node: + return np.array(node["matrix"], dtype=np.float64).reshape(4, 4).T + m = np.eye(4, dtype=np.float64) + if "scale" in node: + sx, sy, sz = node["scale"] + m = m @ np.diag([sx, sy, sz, 1.0]) + if "rotation" in node: + qx, qy, qz, qw = node["rotation"] + xx, yy, zz = qx * qx, qy * qy, qz * qz + xy, xz, yz = qx * qy, qx * qz, qy * qz + wx, wy, wz = qw * qx, qw * qy, qw * qz + r = np.array([ + [1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy), 0.0], + [2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx), 0.0], + [2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy), 0.0], + [0.0, 0.0, 0.0, 1.0], + ], dtype=np.float64) + m = r @ m + if "translation" in node: + tx, ty, tz = node["translation"] + m[:3, 3] = [tx, ty, tz] + return m + + +def _read_accessor( + accessors: list[dict[str, Any]], + buffer_views: list[dict[str, Any]], + bin_blob: bytes, + acc_idx: int, +) -> np.ndarray: + acc = accessors[acc_idx] + bv = buffer_views[acc["bufferView"]] + off = bv.get("byteOffset", 0) + acc.get("byteOffset", 0) + count = acc["count"] + ct = acc["componentType"] + typ = acc["type"] + if typ == "VEC3" and ct == 5126: + stride = bv.get("byteStride", 12) + if stride == 12: + return np.frombuffer(bin_blob, dtype=" float: + x = (a * 0x9E3779B97F4A7C15 + b * 0xBF58476D1CE4E5B9 + c * 0x94D049BB133111EB) & 0xFFFFFFFFFFFFFFFF + x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & 0xFFFFFFFFFFFFFFFF + x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & 0xFFFFFFFFFFFFFFFF + x = x ^ (x >> 31) + return float((x >> 40) & 0xFFFFFF) / float(0x1000000) + + +# --------------------------------------------------------------------------- +# Fast geometric operators (pure numpy) +# --------------------------------------------------------------------------- + +def _weld_positions(pos: np.ndarray) -> tuple[np.ndarray, int]: + """Quantize positions to 0.1 mm and return (weld_id_per_vert, unique_count).""" + q = np.round(pos * 10000.0).astype(np.int64) + # View rows as structured void for fast single-pass np.unique + q_contig = np.ascontiguousarray(q) + view = q_contig.view([("x", np.int64), ("y", np.int64), ("z", np.int64)]).ravel() + _, inv = np.unique(view, return_inverse=True) + return inv.astype(np.int64), int(inv.max()) + 1 if len(inv) else 0 + + +def _connected_components(n_weld: int, tris_weld: np.ndarray) -> np.ndarray: + """Fast union-find connected components on welded vertex indices.""" + parent = list(range(n_weld)) + + def find(x: int) -> int: + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + + for a, b, c in tris_weld.tolist(): + ra, rb, rc = find(a), find(b), find(c) + if ra != rb: + parent[rb] = ra + if ra != rc: + parent[rc] = ra + + roots = np.empty(n_weld, dtype=np.int64) + root_map: dict[int, int] = {} + nxt = 0 + for i in range(n_weld): + r = find(i) + cid = root_map.get(r) + if cid is None: + cid = nxt + root_map[r] = cid + nxt += 1 + roots[i] = cid + return roots + + +def _dihedral_edge_and_crevice( + pos: np.ndarray, + nrm: np.ndarray, + tris: np.ndarray, + weld_id: np.ndarray, + n_weld: int, +) -> tuple[np.ndarray, np.ndarray]: + """Compute (convex_edge_curvature, local_concave_ao) per vertex.""" + edge_out = np.zeros(len(pos), dtype=np.float32) + conc_ao = np.ones(len(pos), dtype=np.float32) + if len(tris) == 0 or n_weld == 0: + return edge_out, conc_ao + + v0 = pos[tris[:, 0]] + v1 = pos[tris[:, 1]] + v2 = pos[tris[:, 2]] + fn_raw = np.cross(v1 - v0, v2 - v0) + fn_len = np.linalg.norm(fn_raw, axis=1, keepdims=True) + valid_tri = (fn_len[:, 0] > 1e-12) + fn = np.divide(fn_raw, np.maximum(fn_len, 1e-12)) + fc = (v0 + v1 + v2) / 3.0 + + wt = weld_id[tris] # (T, 3) + t_idx = np.arange(len(tris), dtype=np.int64) + + e0 = np.stack([np.minimum(wt[:, 0], wt[:, 1]), np.maximum(wt[:, 0], wt[:, 1]), t_idx], axis=1) + e1 = np.stack([np.minimum(wt[:, 1], wt[:, 2]), np.maximum(wt[:, 1], wt[:, 2]), t_idx], axis=1) + e2 = np.stack([np.minimum(wt[:, 2], wt[:, 0]), np.maximum(wt[:, 2], wt[:, 0]), t_idx], axis=1) + edges = np.concatenate([e0, e1, e2], axis=0) + # Remove degenerate edges + edges = edges[edges[:, 0] != edges[:, 1]] + if len(edges) == 0: + return edge_out, conc_ao + + order = np.lexsort((edges[:, 1], edges[:, 0])) + edges = edges[order] + + same = (edges[:-1, 0] == edges[1:, 0]) & (edges[:-1, 1] == edges[1:, 1]) + idx_a = edges[:-1, 2][same] + idx_b = edges[1:, 2][same] + eu = edges[:-1, 0][same] + ev = edges[:-1, 1][same] + + both_valid = valid_tri[idx_a] & valid_tri[idx_b] + idx_a, idx_b, eu, ev = idx_a[both_valid], idx_b[both_valid], eu[both_valid], ev[both_valid] + + weld_convex_sum = np.zeros(n_weld, dtype=np.float32) + weld_convex_cnt = np.zeros(n_weld, dtype=np.float32) + weld_convex_max = np.zeros(n_weld, dtype=np.float32) + weld_concave = np.zeros(n_weld, dtype=np.float32) + + if len(idx_a) > 0: + na = fn[idx_a] + nb = fn[idx_b] + dots = np.clip(np.sum(na * nb, axis=1), -1.0, 1.0) + angles = np.arccos(dots) # radians [0, pi] + delta_c = fc[idx_b] - fc[idx_a] + # Convex if triangle B center lies behind triangle A's front plane + proj_a = np.sum(na * delta_c, axis=1) + proj_b = np.sum(nb * (-delta_c), axis=1) + sign_val = 0.5 * (proj_a + proj_b) + + is_convex = (sign_val < -1e-5) & (angles > 0.55) + is_concave = (sign_val > 1e-5) & (angles > 0.28) + + convex_val = np.where(is_convex, np.clip((angles - 0.55) / 0.95, 0.0, 1.0), 0.0).astype(np.float32) + concave_val = np.where(is_concave, np.clip((angles - 0.28) / 1.20, 0.0, 1.0), 0.0).astype(np.float32) + + np.add.at(weld_convex_sum, eu, convex_val) + np.add.at(weld_convex_sum, ev, convex_val) + np.add.at(weld_convex_cnt, eu, 1.0) + np.add.at(weld_convex_cnt, ev, 1.0) + np.maximum.at(weld_convex_max, eu, convex_val) + np.maximum.at(weld_convex_max, ev, convex_val) + np.maximum.at(weld_concave, eu, concave_val) + np.maximum.at(weld_concave, ev, concave_val) + + weld_convex_mean = np.divide(weld_convex_sum, np.maximum(weld_convex_cnt, 1.0)) + weld_convex = 0.55 * weld_convex_mean + 0.45 * weld_convex_max + edge_out = weld_convex[weld_id] + conc_ao = np.clip(1.0 - 0.55 * weld_concave[weld_id], 0.35, 1.0).astype(np.float32) + return edge_out, conc_ao + + +def _compute_voxel_ao( + all_wpos: np.ndarray, + all_wnrm: np.ndarray, + sample_pts: np.ndarray, +) -> np.ndarray: + """Fast 3D spatial occupancy ray-marched AO across the whole rest-pose vehicle.""" + if len(all_wpos) == 0 or len(sample_pts) == 0: + return np.ones(len(all_wpos), dtype=np.float32) + + bmin = sample_pts.min(axis=0) + bmax = sample_pts.max(axis=0) + extent = np.maximum(bmax - bmin, 0.2) + max_ext = float(extent.max()) + voxel = max(0.075, max_ext / 84.0) + pad = voxel * 8.0 + origin = bmin - pad + dims = np.ceil((extent + 2.0 * pad) / voxel).astype(np.int64) + nx, ny, nz = int(dims[0]), int(dims[1]), int(dims[2]) + + grid = np.zeros((nx, ny, nz), dtype=np.uint8) + idx = np.floor((sample_pts - origin) / voxel).astype(np.int64) + idx[:, 0] = np.clip(idx[:, 0], 0, nx - 1) + idx[:, 1] = np.clip(idx[:, 1], 0, ny - 1) + idx[:, 2] = np.clip(idx[:, 2], 0, nz - 1) + grid[idx[:, 0], idx[:, 1], idx[:, 2]] = 1 + grid_flat = grid.ravel() + sy = nz + sx = ny * nz + + # 18 well-distributed unit ray directions (6 axial + 12 diagonal) + raw_dirs = [ + (1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1), + (1, 1, 0), (-1, 1, 0), (1, -1, 0), (-1, -1, 0), + (1, 0, 1), (-1, 0, 1), (1, 0, -1), (-1, 0, -1), + (0, 1, 1), (0, -1, 1), (0, 1, -1), (0, -1, -1), + ] + dirs = np.array(raw_dirs, dtype=np.float32) + dirs /= np.linalg.norm(dirs, axis=1, keepdims=True) + + # Start rays slightly outside the vertex surface to prevent self-hit + p0 = all_wpos.astype(np.float32) + all_wnrm.astype(np.float32) * (1.35 * voxel) + steps = np.array([0.14, 0.25, 0.38, 0.54, 0.72], dtype=np.float32) + step_weights = np.array([1.0, 0.85, 0.65, 0.45, 0.28], dtype=np.float32) + + nrm_f = all_wnrm.astype(np.float32) + inv_vox = np.float32(1.0 / voxel) + orig_f = origin.astype(np.float32) + + occ_acc = np.zeros(len(all_wpos), dtype=np.float32) + weight_acc = np.zeros(len(all_wpos), dtype=np.float32) + + for d in dirs: + cos_w = np.maximum(nrm_f @ d, 0.0) + active = cos_w > 0.08 + if not np.any(active): + continue + w_act = cos_w[active] + p_act = p0[active] + hit_max = np.zeros(len(p_act), dtype=np.float32) + + for st, sw in zip(steps, step_weights): + q = p_act + d * st + gx = np.floor((q[:, 0] - orig_f[0]) * inv_vox).astype(np.int64) + gy = np.floor((q[:, 1] - orig_f[1]) * inv_vox).astype(np.int64) + gz = np.floor((q[:, 2] - orig_f[2]) * inv_vox).astype(np.int64) + inside = (gx >= 0) & (gx < nx) & (gy >= 0) & (gy < ny) & (gz >= 0) & (gz < nz) + if not np.any(inside): + continue + flat_i = np.where(inside, gx * sx + gy * sy + gz, 0) + occ = grid_flat[flat_i] & inside + hit_max = np.maximum(hit_max, occ.astype(np.float32) * sw) + + occ_acc[active] += hit_max * w_act + weight_acc[active] += w_act + + raw_occ = np.divide(occ_acc, np.maximum(weight_acc, 1e-4)) + return np.clip(1.0 - raw_occ * 0.92, 0.06, 1.0).astype(np.float32) + + +# --------------------------------------------------------------------------- +# GLB baker +# --------------------------------------------------------------------------- + +def bake_glb(glb_path: Path) -> dict[str, Any]: + t0 = time.perf_counter() + data = glb_path.read_bytes() + magic, version, total_len = struct.unpack_from(" None: + node = nodes[node_idx] + world = parent_mat @ _node_local_matrix(node) + if "mesh" in node and node["mesh"] not in mesh_world: + mesh_world[node["mesh"]] = world + for c in node.get("children", []): + walk(c, world) + + ident = np.eye(4, dtype=np.float64) + for r_idx in root_indices: + walk(r_idx, ident) + + # Pass 1: Read all primitives, compute rest-pose world positions/normals, edges, islands, and surface samples + prim_records: list[dict[str, Any]] = [] + wpos_chunks: list[np.ndarray] = [] + wnrm_chunks: list[np.ndarray] = [] + sample_chunks: list[np.ndarray] = [] + global_min_y = math.inf + vert_cursor = 0 + + for m_idx, mesh in enumerate(meshes): + wmat = mesh_world.get(m_idx, ident) + rot_lin = wmat[:3, :3] + det = float(np.linalg.det(rot_lin)) + nrm_mat = np.linalg.inv(rot_lin).T if abs(det) > 1e-12 else rot_lin + + for p_idx, prim in enumerate(mesh.get("primitives", [])): + attrs = prim.get("attributes", {}) + if "POSITION" not in attrs: + continue + pos = _read_accessor(accessors, buffer_views, bin_blob, attrs["POSITION"]) + vcount = len(pos) + if vcount == 0: + continue + if "NORMAL" in attrs: + nrm = _read_accessor(accessors, buffer_views, bin_blob, attrs["NORMAL"]) + else: + nrm = np.tile(np.array([0.0, 1.0, 0.0]), (vcount, 1)) + + if prim.get("mode", 4) == 4: + if "indices" in prim: + tris = _read_accessor(accessors, buffer_views, bin_blob, prim["indices"]).reshape(-1, 3) + else: + tris = np.arange((vcount // 3) * 3, dtype=np.int64).reshape(-1, 3) + else: + tris = np.empty((0, 3), dtype=np.int64) + + wpos = pos @ rot_lin.T + wmat[:3, 3] + wnrm = nrm @ nrm_mat.T + wnrm_len = np.linalg.norm(wnrm, axis=1, keepdims=True) + wnrm = np.divide(wnrm, np.maximum(wnrm_len, 1e-12)) + + global_min_y = min(global_min_y, float(wpos[:, 1].min())) + + weld_id, n_weld = _weld_positions(pos) + if len(tris) > 0 and n_weld > 0: + comp_weld = _connected_components(n_weld, weld_id[tris]) + max_c = int(comp_weld.max()) + 1 + comp_hashes = np.array([_splitmix64_hash(m_idx, p_idx, c) for c in range(max_c)], dtype=np.float32) + island_hash = comp_hashes[comp_weld[weld_id]] + else: + island_hash = np.full(vcount, _splitmix64_hash(m_idx, p_idx, 0), dtype=np.float32) + + edge_curv, local_conc_ao = _dihedral_edge_and_crevice(pos, nrm, tris, weld_id, n_weld) + + # Surface samples for voxel AO (vertices + face centroids + edge midpoints) + sample_chunks.append(wpos) + if len(tris) > 0: + tv0, tv1, tv2 = wpos[tris[:, 0]], wpos[tris[:, 1]], wpos[tris[:, 2]] + sample_chunks.append((tv0 + tv1 + tv2) / 3.0) + sample_chunks.append((tv0 + tv1) * 0.5) + sample_chunks.append((tv1 + tv2) * 0.5) + sample_chunks.append((tv2 + tv0) * 0.5) + + wpos_chunks.append(wpos) + wnrm_chunks.append(wnrm) + prim_records.append({ + "prim": prim, + "vcount": vcount, + "vstart": vert_cursor, + "edge": edge_curv, + "local_ao": local_conc_ao, + "island": island_hash, + }) + vert_cursor += vcount + + if not prim_records: + raise RuntimeError(f"No mesh primitives found in {glb_path}") + + all_wpos = np.concatenate(wpos_chunks, axis=0) + all_wnrm = np.concatenate(wnrm_chunks, axis=0) + all_samples = np.concatenate(sample_chunks, axis=0) + + # Pass 2: Global 3D voxel ambient occlusion + voxel_ao = _compute_voxel_ao(all_wpos, all_wnrm, all_samples) + rest_height = np.clip((all_wpos[:, 1] - global_min_y) / 6.0, 0.0, 1.0).astype(np.float32) + + # Pass 3: Append COLOR_0 bufferViews & accessors cleanly + new_bin = bytearray(bin_blob) + if len(new_bin) % 4 != 0: + new_bin.extend(b"\x00" * (4 - (len(new_bin) % 4))) + + ao_vals = [] + edge_vals = [] + for rec in prim_records: + s, n = rec["vstart"], rec["vcount"] + ao = np.clip(voxel_ao[s : s + n] * rec["local_ao"], 0.0, 1.0) + edge = rec["edge"] + island = rec["island"] + h = rest_height[s : s + n] + ao_vals.append(ao) + edge_vals.append(edge) + + rgba = np.stack([ao, edge, island, h], axis=1) + rgba_u8 = np.clip(np.round(rgba * 255.0), 0, 255).astype(np.uint8) + raw_bytes = rgba_u8.tobytes() + + byte_off = len(new_bin) + new_bin.extend(raw_bytes) + if len(new_bin) % 4 != 0: + new_bin.extend(b"\x00" * (4 - (len(new_bin) % 4))) + + bv_idx = len(buffer_views) + buffer_views.append({ + "buffer": 0, + "byteOffset": byte_off, + "byteLength": len(raw_bytes), + "target": 34962, # ARRAY_BUFFER + }) + acc_idx = len(accessors) + accessors.append({ + "bufferView": bv_idx, + "byteOffset": 0, + "componentType": 5121, # UNSIGNED_BYTE + "normalized": True, + "count": n, + "type": "VEC4", + }) + rec["prim"]["attributes"]["COLOR_0"] = acc_idx + + gltf["buffers"][0]["byteLength"] = len(new_bin) + gltf.setdefault("extras", {}) + gltf["extras"]["rtd.color0_base_bin_len"] = base_bin_len + gltf["extras"]["rtd.color0_base_bv_count"] = base_bv_count + gltf["extras"]["rtd.color0_base_acc_count"] = base_acc_count + + json_bytes = json.dumps(gltf, separators=(",", ":")).encode("utf-8") + if len(json_bytes) % 4 != 0: + json_bytes += b" " * (4 - (len(json_bytes) % 4)) + if len(new_bin) % 4 != 0: + new_bin.extend(b"\x00" * (4 - (len(new_bin) % 4))) + + total_out = 12 + 8 + len(json_bytes) + 8 + len(new_bin) + out = bytearray() + out.extend(struct.pack(" 0.3).mean()), + "size_kib": len(out) / 1024.0, + } + + +def main() -> int: + parser = argparse.ArgumentParser(description="Bake COLOR_0 weathering attributes onto vehicle GLBs.") + parser.add_argument("vehicles", nargs="*", help="Vehicle IDs to bake (e.g. paladin jackal).") + parser.add_argument("--all", action="store_true", help="Bake all 15 vehicles.") + args = parser.parse_args() + + targets = ALL_VEHICLES if args.all else (tuple(args.vehicles) if args.vehicles else ("paladin", "jackal")) + for vid in targets: + glb_path = VEHICLES_DIR / vid / f"{vid}.glb" + if not glb_path.is_file(): + raise FileNotFoundError(f"Missing vehicle GLB: {glb_path}") + stats = bake_glb(glb_path) + print( + f"Baked {vid:10s} | verts={stats['verts']:6d} | prims={stats['prims']:3d} " + f"| {stats['elapsed_s']:.3f}s | ao=[{stats['ao_min']:.2f}, mean={stats['ao_mean']:.2f}] " + f"| edge>0.3={stats['edge_gt_03']*100:.1f}% | {stats['size_kib']:.1f} KiB" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/vehicles/build_anvil.py b/tools/vehicles/build_anvil.py new file mode 100644 index 0000000..871f408 --- /dev/null +++ b/tools/vehicles/build_anvil.py @@ -0,0 +1,468 @@ +"""Build the Anvil (Heavy Quad-Track Siege Tank) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _build_quad_track_pod(name: str, side: float, y_center: float, is_front: bool, parent) -> None: + """Build one heavy articulated armored quad-track pod grounded at Z = 0.""" + pod_x = side * 1.56 + pod = vc.make_empty(name, parent=parent, location=(pod_x, y_center, 0.0)) + + rw_r = 0.27 + rw_z = rw_r + 0.045 + rw_ys = (-0.54, 0.0, 0.54) + front_y, front_z, front_r = -0.98, 0.54, 0.24 + rear_y, rear_z, rear_r = 0.98, 0.54, 0.24 + track_w = 0.62 + + # 3 roadwheels + front/rear sprockets + for i, ry in enumerate(rw_ys): + vc.make_tube_part( + f"{name}_rw_tire_{i}", rw_r, rw_r, track_w * 0.84, segments=14, + mat_name="rubber_dark", parent=pod, location=(-track_w * 0.42, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_rw_hub_{i}", rw_r * 0.64, rw_r * 0.64, track_w * 0.90, segments=10, + mat_name="olive_armor", parent=pod, location=(-track_w * 0.45, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_sproc_f", front_r, front_r, track_w * 0.80, segments=12, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.40, front_y, front_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_sproc_r", rear_r, rear_r, track_w * 0.80, segments=12, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.40, rear_y, rear_z), rotation_deg=(0.0, 90.0, 0.0), + ) + + # Track loop polyline in (y, z) + loop_yz: list[tuple[float, float]] = [] + for k in range(6): + ang = math.radians(100.0 + 135.0 * (k / 5.0)) + loop_yz.append((front_y + math.cos(ang) * (front_r + 0.03), front_z + math.sin(ang) * (front_r + 0.03))) + loop_yz.append((-0.54, 0.025)) + loop_yz.append((0.54, 0.025)) + for k in range(6): + ang = math.radians(-55.0 + 135.0 * (k / 5.0)) + loop_yz.append((rear_y + math.cos(ang) * (rear_r + 0.03), rear_z + math.sin(ang) * (rear_r + 0.03))) + loop_yz.append((0.46, 0.83)) + loop_yz.append((-0.46, 0.83)) + + path_3d = [[0.0, y, z] for (y, z) in loop_yz] + vc.make_swept_profile( + f"{name}_track_band", + "box", + 0.034, + track_w * 0.92, + 0.034, + path_3d, + up=[1.0, 0.0, 0.0], + mat_name="rubber_dark", + parent=pod, + closed=True, + ) + + pts = loop_yz + [loop_yz[0]] + segs = [math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]) for i in range(len(loop_yz))] + total_len = sum(segs) + n_shoes = 28 + + def build_shoes(bm: bmesh.types.BMesh) -> None: + for s_idx in range(n_shoes): + target_d = (s_idx / n_shoes) * total_len + acc = 0.0 + for i, sl in enumerate(segs): + if acc + sl >= target_d or i == len(segs) - 1: + t = (target_d - acc) / max(sl, 1e-6) + y0, z0 = pts[i] + y1, z1 = pts[i + 1] + py = y0 + (y1 - y0) * t + pz = z0 + (z1 - z0) * t + ang = math.atan2(z1 - z0, y1 - y0) + m = ( + Matrix.Translation((0.0, py, pz)) + @ Matrix.Rotation(ang, 4, "X") + @ Matrix.Diagonal((track_w, 0.11, 0.034, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + break + acc += sl + + vc.make_bmesh_object(f"{name}_shoes", build_shoes, "gunmetal", parent=pod) + + # Heavy sloped armored pod housing (top deck + chamfered nose/tail + outer bolted side skirts) + vc.make_box(f"{name}_cover_top", (track_w + 0.12, 1.98, 0.14), "olive_armor", parent=pod, location=(0.0, 0.0, 0.92), bevel=0.012) + vc.make_box(f"{name}_cover_f", (track_w + 0.12, 0.42, 0.14), "olive_armor", parent=pod, location=(0.0, -1.14, 0.80), rotation_deg=(36.0, 0.0, 0.0), bevel=0.01) + vc.make_box(f"{name}_cover_r", (track_w + 0.12, 0.42, 0.14), "olive_armor", parent=pod, location=(0.0, 1.14, 0.80), rotation_deg=(-36.0, 0.0, 0.0), bevel=0.01) + # Outer bolted track pod side skirt + skirt_pts = [ + [side * (track_w * 0.5 + 0.04), -1.12, 0.72], + [side * (track_w * 0.5 + 0.04), 1.12, 0.72], + [side * (track_w * 0.5 + 0.04), 0.98, 0.94], + [side * (track_w * 0.5 + 0.04), -0.98, 0.94], + [side * (track_w * 0.5 + 0.04), -0.74, 0.34], + [side * (track_w * 0.5 + 0.04), 0.74, 0.34], + [side * (track_w * 0.5 + 0.04), 1.12, 0.56], + [side * (track_w * 0.5 + 0.04), -1.12, 0.56], + ] + # Use clean trapezoidal slab for outer pod skirt with bolts + vc.make_plates( + { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": f"{name}_outer_skirt", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "one", + "mirror": False, + "slab": { + "at": [side * (track_w * 0.5 + 0.04), 0.0, 0.64], + "normal": [side, 0.0, 0.0], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -side, 0.0], + "outline": [[-1.08, -0.08], [-0.74, -0.32], [0.74, -0.32], [1.08, -0.08], [0.96, 0.28], [-0.96, 0.28]], + "thick": 0.055, + "taper": 0.012, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.025, "spacing": 0.34, "mat": "gunmetal", "params": "r=0.014"}, + ], + } + ], + }, + parent=pod, + ) + # Inner pod cheek & front headlight block + vc.make_box(f"{name}_inner_cheek", (0.06, 1.84, 0.48), "gunmetal", parent=pod, location=(-side * (track_w * 0.5 + 0.02), 0.0, 0.64), bevel=0.008) + if is_front: + vc.make_box(f"{name}_headlight_pod", (0.28, 0.20, 0.14), "gunmetal", parent=pod, location=(0.0, -1.04, 1.00), bevel=0.008) + vc.make_box(f"{name}_headlight_lens", (0.20, 0.05, 0.08), "smoked_glass", parent=pod, location=(0.0, -1.14, 1.00), bevel=0.004) + + +def build_anvil() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("AnvilRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # --- 1. Central Lower Belly Tub, Ribbed Prow & Pod Outrigger Beams --- + vc.make_box("lower_tub", (2.14, 4.78, 0.64), "gunmetal", parent=chassis, location=(0.0, 0.04, 0.74), bevel=0.016) + # Corrugated lower prow armor ribs + vc.make_box("lower_prow_plate", (2.06, 0.44, 0.52), "olive_armor", parent=chassis, location=(0.0, -2.32, 0.74), rotation_deg=(24.0, 0.0, 0.0), bevel=0.012) + for rx in (-0.84, -0.56, -0.28, 0.0, 0.28, 0.56, 0.84): + vc.make_box(f"prow_rib_{rx:.2f}", (0.08, 0.14, 0.48), "gunmetal", parent=chassis, location=(rx, -2.50, 0.72), rotation_deg=(24.0, 0.0, 0.0), bevel=0.006) + # Outrigger pod axle beams + suspension rams + for p_tag, py in (("f", -1.48), ("r", 1.48)): + vc.make_box(f"pod_crossbeam_{p_tag}", (3.08, 0.58, 0.32), "gunmetal", parent=chassis, location=(0.0, py, 0.62), bevel=0.012) + for side in (-1.0, 1.0): + s_tag = "L" if side > 0 else "R" + vc.make_ram_span( + f"pod_strut_{p_tag}_{s_tag}", + [side * 1.04, py, 1.02], + [side * 1.38, py, 0.74], + body_r=0.048, + rod_r=0.026, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + + # --- 2. Wide Sloped Composite Hull & Tall Casemate Superstructure (Brokkr plate.v0) --- + hull_pts = [ + # Lower hull belt above track pods + [-1.18, -2.38, 0.96], [1.18, -2.38, 0.96], + [-1.22, -0.50, 1.02], [1.22, -0.50, 1.02], + [-1.22, 2.58, 1.02], [1.22, 2.58, 1.02], + # Tall casemate roof (y = -0.48 .. +1.28, z = 1.98) + [-1.16, -0.48, 1.98], [1.16, -0.48, 1.98], + [-1.18, 1.28, 1.98], [1.18, 1.28, 1.98], + # Stepped rear engine deck (y = +1.30 .. +2.64, z = 1.70) + [-1.18, 1.32, 1.70], [1.18, 1.32, 1.70], + [-1.14, 2.64, 1.68], [1.14, 2.64, 1.68], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "anvil_hull", + "mat": "olive_armor", + "bevel": 0.016, + "sides": "one", + "mirror": False, + "points": hull_pts, + "clad": { + "mat": "olive_armor", + "facets": [{"n": [0.0, -0.45, 0.89], "cos": 0.86}], + "min_area": 0.22, + "lifts": [0.008, 0.015], + "inset": 0.07, + "gap": 0.020, + "split": 0.88, + "seed": 901, + "bolt_r": 0.014, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + }, + # Heavy bolted forward superstructure cheek plates + { + "name": "anvil_casemate_cheek", + "mat": "olive_armor", + "bevel": 0.010, + "sides": "both", + "mirror": False, + "slab": { + "at": [1.20, 0.42, 1.54], + "normal": [1.0, 0.0, 0.0], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.86, -0.34], [0.86, -0.34], [0.78, 0.36], [-0.52, 0.36]], + "thick": 0.055, + "taper": 0.014, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.03, "spacing": 0.34, "mat": "gunmetal", "params": "r=0.014"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Sponson weapon shelves (left/right forward flanks) + rear radiator housing + driver periscope + vc.make_box("driver_periscope", (0.58, 0.18, 0.11), "smoked_glass", parent=chassis, location=(0.0, -0.78, 1.84), rotation_deg=(-24.0, 0.0, 0.0), bevel=0.006) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"sponson_shelf_{tag}", (0.48, 0.72, 0.24), "gunmetal", parent=chassis, location=(side * 1.24, -0.76, 1.42), bevel=0.01) + vc.make_box(f"rad_housing_{tag}", (0.16, 1.18, 0.62), "olive_armor", parent=chassis, location=(side * 1.20, 1.50, 1.42), bevel=0.01) + vc.make_box(f"tow_shackle_{tag}", (0.09, 0.16, 0.16), "signal_orange", parent=chassis, location=(side * 0.68, -2.54, 0.64), bevel=0.006) + + # --- 3. 4 Articulated Quad-Track Pods --- + _build_quad_track_pod("pod_fl", 1.0, -1.48, True, chassis) + _build_quad_track_pod("pod_fr", -1.0, -1.48, True, chassis) + _build_quad_track_pod("pod_rl", 1.0, 1.48, False, chassis) + _build_quad_track_pod("pod_rr", -1.0, 1.48, False, chassis) + + # --- 4. Towering Rear Exhaust Stacks --- + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + for s_idx, sy in enumerate((2.40, 2.62)): + vc.make_swept_tube( + f"exhaust_stack_{tag}_{s_idx}", + [ + [side * 0.96, sy - 0.14, 1.48], + [side * 1.04, sy, 1.66], + [side * 1.04, sy, 2.86], + [side * 1.04, sy + 0.14, 2.98], + ], + 0.072, + segments=12, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.06, + ) + vc.make_tube_part( + f"exhaust_shroud_{tag}_{s_idx}", + 0.105, + 0.105, + 0.68, + segments=10, + inner0=0.09, + inner1=0.09, + mat_name="olive_armor", + parent=chassis, + location=(side * 1.04, sy, 1.76), + ) + + # --- 5. Broad Reinforced Siege Turret (joint.turret_yaw) --- + turret_pivot = vc.make_empty("joint.turret_yaw", parent=chassis, location=(0.0, 0.04, 1.98)) + vc.tag_joint(turret_pivot, "joint.turret_yaw", [0.0, 1.0, 0.0], -180.0, 180.0) + joints_manifest = [{"id": "joint.turret_yaw", "axis": [0.0, 1.0, 0.0], "min": -180.0, "max": 180.0}] + + vc.make_tube_part("turret_race", 0.88, 0.94, 0.10, segments=24, mat_name="gunmetal", parent=turret_pivot) + + turret_pts = [ + [-0.76, -0.92, 0.10], [0.76, -0.92, 0.10], + [0.98, -0.22, 0.10], [0.88, 1.04, 0.10], + [-0.88, 1.04, 0.10], [-0.98, -0.22, 0.10], + [-0.58, -0.70, 0.62], [0.58, -0.70, 0.62], + [0.76, -0.14, 0.62], [0.68, 0.86, 0.62], + [-0.68, 0.86, 0.62], [-0.76, -0.14, 0.62], + ] + turret_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "anvil_turret_shell", + "mat": "olive_armor", + "bevel": 0.016, + "sides": "one", + "mirror": False, + "points": turret_pts, + }, + { + "name": "anvil_turret_cheek", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.86, 0.16, 0.34], + "normal": [0.94, 0.0, 0.34], + "up": [-0.34, 0.0, 0.94], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.58, -0.18], [0.58, -0.18], [0.46, 0.18], [-0.46, 0.18]], + "thick": 0.055, + "taper": 0.014, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.025, "spacing": 0.26, "mat": "gunmetal", "params": "r=0.013"}, + ], + }, + ], + } + vc.make_plates(turret_doc, parent=turret_pivot) + + vc.make_box("turret_mantlet_bar", (1.12, 0.22, 0.24), "gunmetal", parent=turret_pivot, location=(0.0, -0.84, 0.34), bevel=0.012) + vc.make_box("turret_bustle", (1.28, 0.46, 0.38), "olive_armor", parent=turret_pivot, location=(0.0, 1.10, 0.38), bevel=0.012) + vc.make_tube_part("commander_cupola", 0.22, 0.24, 0.11, segments=14, mat_name="olive_armor", parent=turret_pivot, location=(0.0, 0.48, 0.62)) + vc.make_box("turret_optic", (0.20, 0.22, 0.16), "smoked_glass", parent=turret_pivot, location=(0.0, -0.46, 0.68), bevel=0.008) + + # --- 6. Visible Exterior Hardpoints (5x6 Dorsal Grid) --- + # 1) hp.armor.front (0,0, 5x1) on steep front glacis + vc.add_hardpoint_slot( + "hp.armor.front", + "armor", + parent=chassis, + location=(0.0, -1.48, 1.46), + rotation_deg=(62.0, 0.0, 0.0), + size=(1.88, 0.42, 0.10), + plinth_depth=0.04, + ) + # 2 & 3) hp.weapon.sponson_l (0,1, 1x2) & hp.weapon.sponson_r (4,1, 1x2) + vc.add_hardpoint_slot( + "hp.weapon.sponson_l", + "weapon", + parent=chassis, + location=(1.26, -0.76, 1.54), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.50, 0.50, 0.09), + ) + vc.add_hardpoint_slot( + "hp.weapon.sponson_r", + "weapon", + parent=chassis, + location=(-1.26, -0.76, 1.54), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.50, 0.50, 0.09), + ) + # 4 & 5) hp.weapon.siege_l (1,1, 1x2) & hp.weapon.siege_r (3,1, 1x2) on turret roof + vc.add_hardpoint_slot( + "hp.weapon.siege_l", + "weapon", + parent=turret_pivot, + location=(0.42, -0.04, 0.63), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.62, 0.62, 0.11), + ) + vc.add_hardpoint_slot( + "hp.weapon.siege_r", + "weapon", + parent=turret_pivot, + location=(-0.42, -0.04, 0.63), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.62, 0.62, 0.11), + ) + # 6) hp.armor.sides (2,1, 1x2) on right (-X) casemate cheek + vc.add_hardpoint_slot( + "hp.armor.sides", + "armor", + parent=chassis, + location=(-1.20, 0.42, 1.54), + rotation_deg=(90.0, 0.0, -90.0), + size=(1.12, 0.34, 0.10), + plinth_depth=0.03, + ) + # 7) hp.engine.rear (1,3, 3x2) on sloped rear engine deck (y=1.98 -> hull surface z=1.825) + vc.add_hardpoint_slot( + "hp.engine.rear", + "engine", + parent=chassis, + location=(0.0, 1.98, 1.815), + rotation_deg=(-12.5, 0.0, 0.0), + size=(1.42, 0.96, 0.15), + plinth_depth=0.04, + ) + # 8 & 9) hp.radiator.l (0,4, 1x2) & hp.radiator.r (4,4, 1x2) + vc.add_hardpoint_slot( + "hp.radiator.l", + "radiator", + parent=chassis, + location=(1.28, 1.50, 1.42), + rotation_deg=(90.0, 0.0, 90.0), + size=(1.04, 0.52, 0.13), + ) + vc.add_hardpoint_slot( + "hp.radiator.r", + "radiator", + parent=chassis, + location=(-1.28, 1.50, 1.42), + rotation_deg=(90.0, 0.0, -90.0), + size=(1.04, 0.52, 0.13), + ) + + # --- 7. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "anvil" / "anvil.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "anvil" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "anvil_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="anvil", + name="Anvil", + vehicle_class="Heavy Quad-Track Siege Tank", + grid_width=5, + grid_height=6, + mask=[ + "#####", + "#####", + "#####", + "#####", + "#####", + "#####", + ], + hardpoints=[ + {"id": "hp.armor.front", "kind": "armor", "x": 0, "y": 0, "w": 5, "h": 1, "modelNodeId": "hp.armor.front"}, + {"id": "hp.weapon.sponson_l", "kind": "weapon", "x": 0, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.sponson_l"}, + {"id": "hp.weapon.siege_l", "kind": "weapon", "x": 1, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.siege_l"}, + {"id": "hp.armor.sides", "kind": "armor", "x": 2, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.armor.sides"}, + {"id": "hp.weapon.siege_r", "kind": "weapon", "x": 3, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.siege_r"}, + {"id": "hp.weapon.sponson_r", "kind": "weapon", "x": 4, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.sponson_r"}, + {"id": "hp.engine.rear", "kind": "engine", "x": 1, "y": 3, "w": 3, "h": 2, "modelNodeId": "hp.engine.rear"}, + {"id": "hp.radiator.l", "kind": "radiator", "x": 0, "y": 4, "w": 1, "h": 2, "modelNodeId": "hp.radiator.l"}, + {"id": "hp.radiator.r", "kind": "radiator", "x": 4, "y": 4, "w": 1, "h": 2, "modelNodeId": "hp.radiator.r"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[anvil] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "anvil", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_anvil() diff --git a/tools/vehicles/build_condor.py b/tools/vehicles/build_condor.py new file mode 100644 index 0000000..b6d3e67 --- /dev/null +++ b/tools/vehicles/build_condor.py @@ -0,0 +1,508 @@ +"""Build the Condor (Heavy Quad-Thruster Assault VTOL) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _build_jet_nacelle( + name: str, + joint_id: str, + rotor_id: str, + side: float, + location: tuple[float, float, float], + scale: float, + tilt_deg: float, + parent, + joints_manifest: list[dict], +) -> None: + """Build a pivoting vectored-thrust armored jet nacelle with copper exhaust skirt and spinning turbine.""" + nacelle_pivot = vc.make_empty( + joint_id, + parent=parent, + location=location, + rotation_deg=(tilt_deg, 0.0, 0.0), + ) + vc.tag_joint(nacelle_pivot, joint_id, [1.0, 0.0, 0.0], -45.0, 75.0) + joints_manifest.append({"id": joint_id, "axis": [1.0, 0.0, 0.0], "min": -45.0, "max": 75.0}) + + r_in = 0.31 * scale + r_out = 0.43 * scale + # Armored olive intake shroud + jet housing + shroud_prof = [ + [r_in, -0.18 * scale], + [r_out * 0.96, -0.18 * scale], + [r_out * 1.05, 0.02 * scale], + [r_out * 1.05, 0.34 * scale], + [r_out * 0.92, 0.44 * scale], + [r_in * 1.02, 0.44 * scale], + [r_in * 0.96, 0.26 * scale], + [r_in, -0.18 * scale], + ] + vc.make_lathe_part( + f"{name}_shroud", + shroud_prof[:-1], + segments=20, + loop=True, + smooth=True, + mat_name="olive_armor", + parent=nacelle_pivot, + ) + # Vectored copper thermal exhaust nozzle petals + nozzle_prof = [ + [r_in * 0.92, -0.44 * scale], + [r_out * 0.86, -0.44 * scale], + [r_out * 0.96, -0.18 * scale], + [r_in, -0.18 * scale], + ] + vc.make_lathe_part( + f"{name}_nozzle", + nozzle_prof, + segments=20, + loop=True, + smooth=True, + mat_name="copper_rad", + parent=nacelle_pivot, + ) + # Inner gunmetal stator vanes + outer hinge trunnion lug + for ang_deg in (0.0, 90.0): + vc.make_box( + f"{name}_stator_{int(ang_deg)}", + (r_in * 1.92, 0.04 * scale, 0.06 * scale), + "gunmetal", + parent=nacelle_pivot, + location=(0.0, 0.0, -0.16 * scale), + rotation_deg=(0.0, 0.0, ang_deg), + bevel=0.004, + ) + vc.make_box( + f"{name}_trunnion_lug", + (0.18 * scale, 0.28 * scale, 0.20 * scale), + "gunmetal", + parent=nacelle_pivot, + location=(-side * (r_out * 0.98), 0.0, 0.12 * scale), + bevel=0.008, + ) + + # Spinning axial turbine rotor + rotor_pivot = vc.make_empty(rotor_id, parent=nacelle_pivot, location=(0.0, 0.0, 0.14 * scale)) + vc.tag_joint(rotor_pivot, rotor_id, [0.0, 1.0, 0.0], -360.0, 360.0) + joints_manifest.append({"id": rotor_id, "axis": [0.0, 1.0, 0.0], "min": -360.0, "max": 360.0}) + + spinner_prof = [ + [0.0, -0.06 * scale], + [0.11 * scale, -0.06 * scale], + [0.11 * scale, 0.08 * scale], + [0.06 * scale, 0.22 * scale], + [0.0, 0.30 * scale], + ] + vc.make_lathe_part(f"{name}_spinner", spinner_prof, segments=12, loop=False, smooth=True, mat_name="gunmetal", parent=rotor_pivot) + + def build_blades(bm: bmesh.types.BMesh) -> None: + for i in range(6): + a = i * math.pi / 3.0 + m = ( + Matrix.Rotation(a, 4, "Z") + @ Matrix.Translation((0.19 * scale, 0.0, 0.02 * scale)) + @ Matrix.Rotation(math.radians(26.0), 4, "X") + @ Matrix.Diagonal((0.20 * scale, 0.072 * scale, 0.014 * scale, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + + vc.make_bmesh_object(f"{name}_blades", build_blades, "gunmetal", parent=rotor_pivot) + + +def build_condor() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("CondorRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # --- 1. 4 Stubby Hydraulic Landing Legs (grounded at Z = 0) --- + # Front twin nose/cheek wheel-legs at y = -1.56, x = +/- 0.42 + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_ram_span( + f"gear_front_strut_{tag}", + [side * 0.34, -1.52, 0.64], + [side * 0.44, -1.60, 0.16], + body_r=0.052, + rod_r=0.030, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + vc.make_ram_span( + f"gear_front_drag_{tag}", + [side * 0.30, -1.16, 0.58], + [side * 0.44, -1.58, 0.18], + body_r=0.030, + rod_r=0.018, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="gunmetal", + ) + vc.make_knobby_wheel( + f"gear_front_wheel_{tag}", + radius=0.16, + width=0.14, + parent=chassis, + location=(side * 0.46, -1.60, 0.16), + tread_lugs=10, + rim_segments=12, + side_sign=int(side), + ) + # Rear splayed outrigger hydraulic legs with armored ski-pads at y = +1.08 + vc.make_box(f"gear_rear_sponson_{tag}", (0.26, 0.46, 0.24), "olive_armor", parent=chassis, location=(side * 0.78, 1.06, 0.68), bevel=0.01) + vc.make_ram_span( + f"gear_rear_strut_{tag}", + [side * 0.78, 1.06, 0.64], + [side * 1.04, 1.08, 0.08], + body_r=0.058, + rod_r=0.032, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + vc.make_ram_span( + f"gear_rear_brace_{tag}", + [side * 0.62, 0.68, 0.56], + [side * 1.02, 1.06, 0.10], + body_r=0.032, + rod_r=0.020, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="gunmetal", + ) + # Articulated ski-pad foot + small bogie wheel grounded at Z = 0 + vc.make_box(f"gear_rear_ski_{tag}", (0.26, 0.66, 0.055), "gunmetal", parent=chassis, location=(side * 1.04, 1.08, 0.028), bevel=0.008) + vc.make_box(f"gear_rear_ski_tip_{tag}", (0.26, 0.16, 0.055), "gunmetal", parent=chassis, location=(side * 1.04, 0.72, 0.065), rotation_deg=(28.0, 0.0, 0.0), bevel=0.006) + + # --- 2. Brutalist Angular Bolted Fuselage & Canopy (Brokkr plate.v0) --- + hull_pts = [ + # Nose prow (y = -2.78) + [-0.38, -2.78, 0.84], [0.38, -2.78, 0.84], + [-0.44, -2.72, 1.06], [0.44, -2.72, 1.06], + # Forward cabin shoulder (y = -1.54) + [-0.78, -1.54, 0.56], [0.78, -1.54, 0.56], + [-0.86, -1.42, 1.24], [0.86, -1.42, 1.24], + [-0.58, -1.24, 1.62], [0.58, -1.24, 1.62], + # Mid troop bay (y = +1.12) + [-0.78, 1.12, 0.56], [0.78, 1.12, 0.56], + [-0.88, 1.12, 1.28], [0.88, 1.12, 1.28], + [-0.64, 1.12, 1.66], [0.64, 1.12, 1.66], + # Tapered rear tail boom (y = +2.78) + [-0.36, 2.78, 1.08], [0.36, 2.78, 1.08], + [-0.38, 2.78, 1.48], [0.38, 2.78, 1.48], + ] + canopy_pts = [ + [-0.42, -2.42, 1.06], [0.42, -2.42, 1.06], + [-0.56, -1.36, 1.26], [0.56, -1.36, 1.26], + [-0.48, -1.20, 1.66], [0.48, -1.20, 1.66], + [-0.40, -1.86, 1.62], [0.40, -1.86, 1.62], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "condor_fuselage", + "mat": "olive_armor", + "bevel": 0.016, + "sides": "one", + "mirror": False, + "points": hull_pts, + }, + { + "name": "condor_canopy", + "mat": "smoked_glass", + "bevel": 0.008, + "sides": "one", + "mirror": False, + "points": canopy_pts, + }, + # Bolted side troop-bay armor plates + crew doors + { + "name": "condor_flank_armor", + "mat": "olive_armor", + "bevel": 0.010, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.86, -0.14, 0.94], + "normal": [0.98, 0.0, -0.18], + "up": [0.18, 0.0, 0.98], + "right": [0.0, -1.0, 0.0], + "outline": [[-1.18, -0.32], [1.18, -0.32], [1.08, 0.34], [-1.08, 0.34]], + "thick": 0.05, + "taper": 0.014, + "back": 0.92, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.14, + "lifts": [0.008, 0.014], + "inset": 0.05, + "gap": 0.016, + "split": 0.72, + "seed": 1001, + "bolt_r": 0.013, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "bolts", "inset": 0.025, "spacing": 0.34, "mat": "gunmetal", "params": "r=0.013"}, + {"kind": "part", "part": "handle", "at": [0.32, 0.02], "roll": 0.0, "mat": "gunmetal", "params": "length=0.22;lift=0.045;r=0.012"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Canopy structural armor ribs + dorsal radiator spine housing + rear APU jet nozzle + V-tail stabilizers + vc.make_swept_tube( + "canopy_spine", + [[0.0, -2.44, 1.06], [0.0, -1.86, 1.64], [0.0, -1.18, 1.68]], + 0.028, segments=6, mat_name="olive_armor", parent=chassis, fillet_r=0.04, + ) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_swept_tube( + f"canopy_rib_{tag}", + [[side * 0.40, -2.40, 1.06], [side * 0.42, -1.84, 1.62], [side * 0.48, -1.20, 1.66]], + 0.022, segments=6, mat_name="olive_armor", parent=chassis, fillet_r=0.04, + ) + # Side weapon sponson boxes on forward cheek flanks + vc.make_box(f"weapon_sponson_box_{tag}", (0.24, 0.76, 0.36), "olive_armor", parent=chassis, location=(side * 0.92, -1.16, 0.96), bevel=0.01) + # Fore nacelle shoulder sponsons (y = -0.86) + vc.make_box(f"fore_wing_{tag}", (0.64, 0.44, 0.22), "olive_armor", parent=chassis, location=(side * 0.86, -0.86, 1.48), rotation_deg=(0.0, side * -6.0, 0.0), bevel=0.012) + # Aft main high-mounted swept wings (y = +0.74) + vc.make_box(f"aft_wing_{tag}", (1.06, 0.72, 0.22), "olive_armor", parent=chassis, location=(side * 1.18, 0.74, 1.60), rotation_deg=(0.0, side * -5.0, side * -8.0), bevel=0.014) + # Tilt actuator rams for fore & aft nacelles + vc.make_ram_span( + f"tilt_ram_f_{tag}", + [side * 0.68, -1.04, 1.54], + [side * 1.06, -0.86, 1.50], + body_r=0.032, + rod_r=0.018, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + vc.make_ram_span( + f"tilt_ram_r_{tag}", + [side * 1.18, 0.50, 1.68], + [side * 1.56, 0.74, 1.66], + body_r=0.038, + rod_r=0.020, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + # Canted twin tail stabilizers + ventral strakes + vc.make_box( + f"tail_fin_{tag}", + (0.06, 0.66, 0.94), + "olive_armor", + parent=chassis, + location=(side * 0.56, 2.58, 1.72), + rotation_deg=(24.0, side * -32.0, 0.0), + bevel=0.01, + ) + vc.make_box( + f"tail_horiz_{tag}", + (0.46, 0.54, 0.07), + "olive_armor", + parent=chassis, + location=(side * 0.44, 2.54, 1.34), + rotation_deg=(0.0, side * 10.0, side * -12.0), + bevel=0.008, + ) + + # Dorsal radiator spine ridge (runs behind canopy to tail root) + vc.make_box("dorsal_spine_core", (0.78, 2.48, 0.26), "olive_armor", parent=chassis, location=(0.0, 0.28, 1.70), bevel=0.014) + vc.make_box("dorsal_spine_cap", (0.48, 2.38, 0.14), "gunmetal", parent=chassis, location=(0.0, 0.28, 1.84), bevel=0.01) + + # Rear tail APU / main jet exhaust cone + rear_nozzle_prof = [ + [0.18, 0.0], + [0.27, 0.0], + [0.29, 0.18], + [0.24, 0.36], + [0.16, 0.36], + [0.18, 0.0], + ] + vc.make_lathe_part( + "rear_jet_nozzle", + rear_nozzle_prof[:-1], + segments=18, + loop=True, + smooth=True, + mat_name="copper_rad", + parent=chassis, + location=(0.0, 2.74, 1.28), + rotation_deg=(-90.0, 0.0, 0.0), + ) + + # --- 3. 4 Pivoting Vectored-Thrust Jet Nacelles (joint.nacelle_fl/fr/rl/rr) --- + joints_manifest: list[dict] = [] + # Fore nacelles + for side, j_tag in ((1.0, "fl"), (-1.0, "fr")): + _build_jet_nacelle( + f"nacelle_{j_tag}", + f"joint.nacelle_{j_tag}", + f"joint.rotor_{j_tag}", + side, + location=(side * 1.42, -0.86, 1.48), + scale=0.82, + tilt_deg=-16.0, + parent=chassis, + joints_manifest=joints_manifest, + ) + # Aft main nacelles (larger vectored jet pods) + for side, j_tag in ((1.0, "rl"), (-1.0, "rr")): + _build_jet_nacelle( + f"nacelle_{j_tag}", + f"joint.nacelle_{j_tag}", + f"joint.rotor_{j_tag}", + side, + location=(side * 1.88, 0.74, 1.62), + scale=1.06, + tilt_deg=-14.0, + parent=chassis, + joints_manifest=joints_manifest, + ) + + # --- 4. Heavy Nose Chin Turret (joint.turret_yaw) --- + turret_pivot = vc.make_empty("joint.turret_yaw", parent=chassis, location=(0.0, -2.26, 0.74)) + vc.tag_joint(turret_pivot, "joint.turret_yaw", [0.0, 1.0, 0.0], -180.0, 180.0) + joints_manifest.append({"id": "joint.turret_yaw", "axis": [0.0, 1.0, 0.0], "min": -180.0, "max": 180.0}) + + vc.make_tube_part("chin_turret_ring", 0.28, 0.30, 0.10, segments=16, mat_name="gunmetal", parent=turret_pivot, location=(0.0, 0.0, -0.04)) + vc.make_box("chin_turret_housing", (0.44, 0.48, 0.22), "olive_armor", parent=turret_pivot, location=(0.0, 0.0, -0.14), bevel=0.012) + vc.make_box("chin_optics", (0.20, 0.10, 0.10), "smoked_glass", parent=turret_pivot, location=(0.0, -0.24, -0.10), bevel=0.005) + + # --- 5. Visible Exterior Hardpoints (5x6 Masked Dorsal Grid) --- + # 1) hp.weapon.nose (1,0, 2x1) under chin turret + vc.add_hardpoint_slot( + "hp.weapon.nose", + "weapon", + parent=turret_pivot, + location=(0.0, 0.0, -0.25), + rotation_deg=(0.0, 180.0, 0.0), + size=(0.46, 0.46, 0.08), + ) + # 2) hp.armor.hull (3,0, 1x1) on sloped upper nose glacis in front of canopy + vc.add_hardpoint_slot( + "hp.armor.hull", + "armor", + parent=chassis, + location=(0.0, -2.56, 1.13), + rotation_deg=(69.0, 0.0, 0.0), + size=(0.64, 0.26, 0.09), + plinth_depth=0.04, + ) + # 3 & 4) hp.weapon.sponson_l (0,1, 1x2) & hp.weapon.sponson_r (4,1, 1x2) on cheek weapon sponsons + vc.add_hardpoint_slot( + "hp.weapon.sponson_l", + "weapon", + parent=chassis, + location=(1.04, -1.16, 0.96), + rotation_deg=(0.0, 90.0, 0.0), + size=(0.44, 0.44, 0.08), + ) + vc.add_hardpoint_slot( + "hp.weapon.sponson_r", + "weapon", + parent=chassis, + location=(-1.04, -1.16, 0.96), + rotation_deg=(0.0, -90.0, 0.0), + size=(0.44, 0.44, 0.08), + ) + # 5) hp.weapon.dorsal (2,1, 1x1) on forward dorsal spine behind cockpit + vc.add_hardpoint_slot( + "hp.weapon.dorsal", + "weapon", + parent=chassis, + location=(0.0, -0.78, 1.91), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.54, 0.54, 0.09), + ) + # 6) hp.engine.core (1,2, 3x2) central dorsal turbine bay (dorsal_spine_core width 0.78, cap top at z=1.91) + vc.add_hardpoint_slot( + "hp.engine.core", + "engine", + parent=chassis, + location=(0.0, 0.36, 1.89), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.74, 1.14, 0.14), + plinth_depth=0.05, + ) + # 7 & 8) hp.radiator.spine_l (0,3, 1x2) & hp.radiator.spine_r (4,3, 1x2) along canted dorsal spine flanks + vc.add_hardpoint_slot( + "hp.radiator.spine_l", + "radiator", + parent=chassis, + location=(0.56, 1.02, 1.68), + rotation_deg=(0.0, 56.0, 0.0), + size=(0.40, 1.04, 0.11), + ) + vc.add_hardpoint_slot( + "hp.radiator.spine_r", + "radiator", + parent=chassis, + location=(-0.56, 1.02, 1.68), + rotation_deg=(0.0, -56.0, 0.0), + size=(0.40, 1.04, 0.11), + ) + + # --- 6. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "condor" / "condor.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "condor" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "condor_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="condor", + name="Condor", + vehicle_class="Heavy Quad-Thruster Assault VTOL", + grid_width=5, + grid_height=6, + mask=[ + ".###.", + "#####", + "#####", + "#####", + "#####", + "..#..", + ], + hardpoints=[ + {"id": "hp.weapon.nose", "kind": "weapon", "x": 1, "y": 0, "w": 2, "h": 1, "modelNodeId": "hp.weapon.nose"}, + {"id": "hp.armor.hull", "kind": "armor", "x": 3, "y": 0, "w": 1, "h": 1, "modelNodeId": "hp.armor.hull"}, + {"id": "hp.weapon.sponson_l", "kind": "weapon", "x": 0, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.sponson_l"}, + {"id": "hp.weapon.dorsal", "kind": "weapon", "x": 2, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.weapon.dorsal"}, + {"id": "hp.weapon.sponson_r", "kind": "weapon", "x": 4, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.sponson_r"}, + {"id": "hp.engine.core", "kind": "engine", "x": 1, "y": 2, "w": 3, "h": 2, "modelNodeId": "hp.engine.core"}, + {"id": "hp.radiator.spine_l", "kind": "radiator", "x": 0, "y": 3, "w": 1, "h": 2, "modelNodeId": "hp.radiator.spine_l"}, + {"id": "hp.radiator.spine_r", "kind": "radiator", "x": 4, "y": 3, "w": 1, "h": 2, "modelNodeId": "hp.radiator.spine_r"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[condor] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "condor", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_condor() diff --git a/tools/vehicles/build_drop_pod.py b/tools/vehicles/build_drop_pod.py new file mode 100644 index 0000000..58bac25 --- /dev/null +++ b/tools/vehicles/build_drop_pod.py @@ -0,0 +1,407 @@ +"""Build the Brokkr-powered Imperial Orbital Drop Pod GLB into assets/vehicles/drop_pod/drop_pod.glb.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _add_prism_wedge( + bm: bmesh.types.BMesh, + x0_bot: float, + x1_bot: float, + x0_top: float, + x1_top: float, + hw_bot: float, + hw_top: float, + z0: float, + z1: float, + mat_idx: int, + taper_edge: float = 0.14, +) -> None: + """Create a tapered trapezoidal armored hull plate oriented with outward face along +X.""" + # Inner face (4 corners), outer face beveled slightly narrower for crisp chamfers + v_in_bl = bm.verts.new((x0_bot, -hw_bot, z0)) + v_in_br = bm.verts.new((x0_bot, hw_bot, z0)) + v_in_tr = bm.verts.new((x0_top, hw_top, z1)) + v_in_tl = bm.verts.new((x0_top, -hw_top, z1)) + + hw_ob = max(0.05, hw_bot - taper_edge) + hw_ot = max(0.05, hw_top - taper_edge) + v_out_bl = bm.verts.new((x1_bot, -hw_ob, z0 + 0.05)) + v_out_br = bm.verts.new((x1_bot, hw_ob, z0 + 0.05)) + v_out_tr = bm.verts.new((x1_top, hw_ot, z1 - 0.05)) + v_out_tl = bm.verts.new((x1_top, -hw_ot, z1 - 0.05)) + + quads = [ + (v_out_bl, v_out_br, v_out_tr, v_out_tl), # outer (+X) + (v_in_br, v_in_bl, v_in_tl, v_in_tr), # inner (-X) + (v_in_bl, v_out_bl, v_out_tl, v_in_tl), # -Y flank + (v_out_br, v_in_br, v_in_tr, v_out_tr), # +Y flank + (v_in_bl, v_in_br, v_out_br, v_out_bl), # bottom (-Z) + (v_out_tl, v_out_tr, v_in_tr, v_in_tl), # top (+Z) + ] + for q in quads: + f = bm.faces.new(q) + f.material_index = mat_idx + + +def _add_local_box( + bm: bmesh.types.BMesh, + center: tuple[float, float, float], + size: tuple[float, float, float], + rot_deg: tuple[float, float, float], + mat_idx: int, +) -> None: + rot_m = ( + Matrix.Rotation(math.radians(rot_deg[2]), 4, "Z") + @ Matrix.Rotation(math.radians(rot_deg[1]), 4, "Y") + @ Matrix.Rotation(math.radians(rot_deg[0]), 4, "X") + ) + mat = Matrix.Translation(center) @ rot_m @ Matrix.Diagonal((size[0], size[1], size[2], 1.0)) + ret = bmesh.ops.create_cube(bm, size=1.0, matrix=mat) + verts_set = set(ret["verts"]) + for f in bm.faces: + if all(v in verts_set for v in f.verts): + f.material_index = mat_idx + + +def _build_petal_mesh(name: str, mats: dict[str, bpy.types.Material]) -> tuple[bpy.types.Mesh, Vector]: + """Build a single armored blow-off hull petal with local origin at its exact geometric centroid. + + Authored in local radial coordinates where +X is outward, Y is tangential width, Z is vertical. + Returns (mesh, world_centroid_offset_in_radial_XZ). + """ + mat_order = ("olive_armor", "signal_orange", "gunmetal", "socket_bay") + bm = bmesh.new() + + # World-space radial placement before centroid centering: + # Pod petal spans Z = 0.56..3.32m, leaning inward from r ~ 1.32m (bottom) to 0.94m (top). + z0, z1 = 0.56, 3.32 + x0_b, x1_b = 1.04, 1.34 + x0_t, x1_t = 0.72, 0.96 + hw_b, hw_t = 0.54, 0.37 + + # 0: Main armored outer shell (olive_armor) + _add_prism_wedge(bm, x0_b, x1_b, x0_t, x1_t, hw_b, hw_t, z0, z1, mat_idx=0, taper_edge=0.11) + + # 3: Recessed dark inner liner plate (socket_bay) + _add_prism_wedge(bm, x0_b - 0.04, x0_b + 0.01, x0_t - 0.04, x0_t + 0.01, hw_b - 0.09, hw_t - 0.07, z0 + 0.14, z1 - 0.14, mat_idx=3, taper_edge=0.02) + + # Mid-slope angle for surface-aligned ribs and chevron plates + dx = x1_t - x1_b + dz = z1 - z0 + pitch_deg = math.degrees(math.atan2(-dx, dz)) # tilt inward toward +Z + + # 0: Heavy vertical central blast rib (olive_armor) + mid_x = 0.5 * (x1_b + x1_t) + 0.04 + mid_z = 0.5 * (z0 + z1) + _add_local_box(bm, (mid_x, 0.0, mid_z), (0.14, 0.22, 2.24), (0.0, pitch_deg, 0.0), mat_idx=0) + + # 1: Imperial accent chevron / hazard stripe band near upper third (signal_orange) + stripe_z = 2.48 + t_s = (stripe_z - z0) / dz + stripe_x = x1_b + dx * t_s + 0.025 + _add_local_box(bm, (stripe_x, 0.0, stripe_z), (0.08, 0.54, 0.22), (0.0, pitch_deg, 0.0), mat_idx=1) + _add_local_box(bm, (x1_b + dx * 0.22 + 0.025, 0.0, 1.15), (0.07, 0.68, 0.14), (0.0, pitch_deg, 0.0), mat_idx=1) + + # 2: Explosive bolt hinge lugs at base & top clamp collar (gunmetal) + for side in (-1.0, 1.0): + _add_local_box(bm, (x1_b - 0.04, side * 0.34, z0 + 0.16), (0.14, 0.12, 0.20), (0.0, pitch_deg, 0.0), mat_idx=2) + _add_local_box(bm, (x1_t - 0.03, side * 0.22, z1 - 0.15), (0.12, 0.10, 0.18), (0.0, pitch_deg, 0.0), mat_idx=2) + + # Bevel crisp armor edges slightly + bmesh.ops.recalc_face_normals(bm, faces=bm.faces) + bmesh.ops.bevel( + bm, + geom=list(bm.edges), + offset=0.015, + segments=1, + affect="EDGES", + clamp_overlap=True, + ) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces) + + # Compute exact AABB centroid of the petal and shift all vertices so local origin == centroid! + coords = np.array([v.co[:] for v in bm.verts], dtype=np.float64) + c_min = coords.min(axis=0) + c_max = coords.max(axis=0) + centroid = Vector(((c_min[0] + c_max[0]) * 0.5, (c_min[1] + c_max[1]) * 0.5, (c_min[2] + c_max[2]) * 0.5)) + bmesh.ops.translate(bm, verts=bm.verts, vec=-centroid) + + mesh = bpy.data.meshes.new(name) + bm.to_mesh(mesh) + bm.free() + + for m_name in mat_order: + mesh.materials.append(mats[m_name]) + + sharp = mesh.attributes.get("sharp_face") or mesh.attributes.new("sharp_face", "BOOLEAN", "FACE") + sharp.data.foreach_set("value", np.ones(len(mesh.polygons), dtype=bool)) + mesh.update() + return mesh, centroid + + +def build_drop_pod() -> Path: + vc.reset_scene() + mats = vc.ensure_materials() + + root = vc.make_empty("DropPodRoot") + body_empty = vc.make_empty("CoreBody", parent=root) + + # 1. Heavy Octagonal Ablative Heatshield Base (Z = 0.00 .. 0.62, width ~2.80m) + shield_prof = [ + [0.00, 0.00], + [1.12, 0.00], + [1.36, 0.14], + [1.40, 0.34], + [1.24, 0.56], + [0.98, 0.64], + [0.00, 0.64], + ] + vc.make_lathe_part( + "HeatshieldBase", + shield_prof, + segments=8, + loop=False, + smooth=False, + mat_name="gunmetal", + parent=body_empty, + rotation_deg=(0.0, 0.0, 22.5), + bevel=0.015, + ) + + # Armored lower skirt bumper ring + skirt_prof = [ + [1.33, 0.22], + [1.43, 0.25], + [1.42, 0.42], + [1.28, 0.50], + ] + vc.make_lathe_part( + "HeatshieldSkirt", + skirt_prof, + segments=8, + loop=True, + smooth=False, + mat_name="olive_armor", + parent=body_empty, + rotation_deg=(0.0, 0.0, 22.5), + bevel=0.012, + ) + + # Central ventral retro-exhaust port + vc.make_tube_part( + "RetroNozzle", + 0.34, + 0.46, + 0.18, + segments=12, + inner0=0.22, + inner1=0.32, + smooth=False, + mat_name="copper_rad", + parent=body_empty, + location=(0.0, 0.0, 0.01), + ) + + # 2. Inner Armored Pressure Core (Gunmetal + dark bulkhead ribs inside the 4 petals) + core_prof = [ + [0.86, 0.58], + [0.84, 1.45], + [0.78, 2.55], + [0.72, 3.35], + [0.82, 3.55], + [0.00, 3.55], + ] + vc.make_lathe_part( + "PressureVessel", + core_prof, + segments=8, + loop=False, + smooth=False, + mat_name="gunmetal", + parent=body_empty, + rotation_deg=(0.0, 0.0, 22.5), + bevel=0.012, + ) + for ring_z, ring_r in ((1.20, 0.87), (2.05, 0.83), (2.90, 0.77)): + vc.make_tube_part( + f"BulkheadRing_{ring_z:.1f}", + ring_r, + ring_r, + 0.16, + segments=8, + smooth=False, + mat_name="socket_bay", + parent=body_empty, + location=(0.0, 0.0, ring_z), + rotation_deg=(0.0, 0.0, 22.5), + ) + + # 3. Four Structural Spine Buttresses + Retro-Thruster Pods at 0, 90, 180, 270 deg + nozzle_prof = [ + [0.14, 0.00], + [0.24, 0.00], + [0.19, 0.16], + [0.13, 0.34], + [0.17, 0.42], + [0.08, 0.42], + [0.11, 0.14], + ] + for i in range(4): + ang_deg = i * 90.0 + ang = math.radians(ang_deg) + ca, sa = math.cos(ang), math.sin(ang) + + # Vertical structural spine rib between petals + vc.make_box( + f"SpineButtress_{i}", + (0.40, 0.28, 2.86), + "gunmetal", + parent=body_empty, + location=(0.94 * ca, 0.94 * sa, 1.98), + rotation_deg=(0.0, 10.5, ang_deg), + bevel=0.014, + ) + vc.make_box( + f"SpineStripe_{i}", + (0.10, 0.22, 0.56), + "signal_orange", + parent=body_empty, + location=(1.04 * ca, 1.04 * sa, 2.42), + rotation_deg=(0.0, 10.5, ang_deg), + bevel=0.006, + ) + + # Retro-thruster housing & flared copper bell nozzle + vc.make_box( + f"ThrusterPod_{i}", + (0.46, 0.40, 0.72), + "olive_armor", + parent=body_empty, + location=(1.18 * ca, 1.18 * sa, 0.68), + rotation_deg=(0.0, -14.0, ang_deg), + bevel=0.014, + ) + vc.make_lathe_part( + f"RetroNozzle_{i}", + nozzle_prof, + segments=12, + loop=True, + smooth=False, + mat_name="copper_rad", + parent=body_empty, + location=(1.26 * ca, 1.26 * sa, 0.12), + rotation_deg=(0.0, -14.0, ang_deg), + ) + + # 4. Upper Drogue Collar, Airbrake Fins & Ballistic Crown (Z = 3.34 .. 4.60) + crown_prof = [ + [0.00, 3.34], + [0.98, 3.34], + [1.04, 3.55], + [0.88, 3.92], + [0.64, 4.30], + [0.44, 4.54], + [0.24, 4.60], + [0.00, 4.60], + ] + vc.make_lathe_part( + "DrogueCrown", + crown_prof, + segments=8, + loop=False, + smooth=False, + mat_name="olive_armor", + parent=body_empty, + rotation_deg=(0.0, 0.0, 22.5), + bevel=0.015, + ) + vc.make_tube_part( + "DrogueCapRim", + 0.48, + 0.34, + 0.28, + segments=8, + smooth=False, + mat_name="gunmetal", + parent=body_empty, + location=(0.0, 0.0, 4.32), + rotation_deg=(0.0, 0.0, 22.5), + bevel=0.010, + ) + vc.make_tube_part( + "DrogueChuteWell", + 0.24, + 0.24, + 0.10, + segments=12, + smooth=False, + mat_name="socket_bay", + parent=body_empty, + location=(0.0, 0.0, 4.52), + ) + + for i in range(4): + ang_deg = i * 90.0 + ang = math.radians(ang_deg) + ca, sa = math.cos(ang), math.sin(ang) + vc.make_box( + f"AeroFin_{i}", + (0.44, 0.12, 0.62), + "gunmetal", + parent=body_empty, + location=(0.94 * ca, 0.94 * sa, 3.96), + rotation_deg=(0.0, 22.0, ang_deg), + bevel=0.010, + ) + vc.make_box( + f"CrownChevron_{i}", + (0.14, 0.34, 0.16), + "signal_orange", + parent=body_empty, + location=(0.86 * ca, 0.86 * sa, 3.82), + rotation_deg=(0.0, 24.0, ang_deg), + bevel=0.006, + ) + vc.make_box( + f"BeaconNode_{i}", + (0.08, 0.12, 0.08), + "cyan_coil", + parent=body_empty, + location=(0.56 * ca, 0.56 * sa, 4.36), + rotation_deg=(0.0, 0.0, ang_deg), + bevel=0.004, + ) + + # 5. Four Distinct Armored Petals (Petal_0..3) at 45, 135, 225, 315 deg + # Each petal has its own mesh datablock with origin at its EXACT geometric centroid! + for i in range(4): + ang_deg = 45.0 + i * 90.0 + ang = math.radians(ang_deg) + petal_mesh, centroid_local = _build_petal_mesh(f"PetalMesh_{i}", mats) + p_obj = bpy.data.objects.new(f"Petal_{i}", petal_mesh) + world_loc = ( + centroid_local.x * math.cos(ang) - centroid_local.y * math.sin(ang), + centroid_local.x * math.sin(ang) + centroid_local.y * math.cos(ang), + centroid_local.z, + ) + vc._link_object(p_obj, parent=root, location=world_loc, rotation_deg=(0.0, 0.0, ang_deg)) + + glb_path = vc.ASSETS_VEHICLES_DIR / "drop_pod" / "drop_pod.glb" + tris, bounds = vc.export_vehicle_glb(glb_path, root=root) + print(f"[drop_pod] tris={tris} bounds={bounds} glb={glb_path}") + return glb_path + + +if __name__ == "__main__": + build_drop_pod() diff --git a/tools/vehicles/build_ferret.py b/tools/vehicles/build_ferret.py new file mode 100644 index 0000000..1c17c8f --- /dev/null +++ b/tools/vehicles/build_ferret.py @@ -0,0 +1,344 @@ +"""Build the Ferret (Light Tracked Scout Tankette) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _build_track_pod(name: str, side: float, parent) -> None: + """Build one wide articulated steel track pod with roadwheels, drive sprockets, and track shoes.""" + pod_x = side * 0.86 + pod = vc.make_empty(name, parent=parent, location=(pod_x, 0.0, 0.0)) + + # Track loop keypoints in (y, z): front idler -> bottom roadwheels -> rear sprocket -> top return + # Ground at z = 0.0 (track shoe thickness ~0.04 -> wheel bottom at z = 0.04) + rw_r = 0.25 + rw_z = rw_r + 0.04 + rw_ys = (-0.90, -0.30, 0.30, 0.90) + idler_y, idler_z, idler_r = -1.48, 0.46, 0.22 + sproc_y, sproc_z, sproc_r = 1.46, 0.48, 0.23 + track_w = 0.40 + + # Roadwheels (4) + Front Idler + Rear Drive Sprocket + for i, ry in enumerate(rw_ys): + vc.make_tube_part( + f"{name}_rw_tire_{i}", rw_r, rw_r, track_w * 0.82, segments=16, + mat_name="rubber_dark", parent=pod, location=(-track_w * 0.41, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_rw_hub_{i}", rw_r * 0.66, rw_r * 0.66, track_w * 0.88, segments=12, + mat_name="olive_armor", parent=pod, location=(-track_w * 0.44, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_idler", idler_r, idler_r, track_w * 0.78, segments=14, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.39, idler_y, idler_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_sprocket", sproc_r, sproc_r, track_w * 0.82, segments=14, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.41, sproc_y, sproc_z), rotation_deg=(0.0, 90.0, 0.0), + ) + + # Track belt loop + articulated grouser shoes sampled evenly around closed perimeter + # Build loop path points in (y, z) + loop_yz: list[tuple[float, float]] = [] + # Front idler arc (from top-front down to bottom-front) + for k in range(7): + ang = math.radians(95.0 + 145.0 * (k / 6.0)) + loop_yz.append((idler_y + math.cos(ang) * (idler_r + 0.025), idler_z + math.sin(ang) * (idler_r + 0.025))) + # Bottom run across roadwheels + loop_yz.append((-0.90, 0.02)) + loop_yz.append((0.90, 0.02)) + # Rear sprocket arc (from bottom-rear up to top-rear) + for k in range(7): + ang = math.radians(-65.0 + 145.0 * (k / 6.0)) + loop_yz.append((sproc_y + math.cos(ang) * (sproc_r + 0.025), sproc_z + math.sin(ang) * (sproc_r + 0.025))) + # Top return run + loop_yz.append((0.40, 0.73)) + loop_yz.append((-0.40, 0.73)) + + # Continuous inner track band via core.sweep (with up=+X, outline's h spans X and w spans thickness) + path_3d = [[0.0, y, z] for (y, z) in loop_yz] + vc.make_swept_profile( + f"{name}_track_band", + "box", + 0.030, + track_w * 0.92, + 0.030, + path_3d, + up=[1.0, 0.0, 0.0], + mat_name="rubber_dark", + parent=pod, + closed=True, + ) + + # Articulated steel grouser shoes along loop + # Compute cumulative arc length + pts = loop_yz + [loop_yz[0]] + segs = [math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]) for i in range(len(loop_yz))] + total_len = sum(segs) + n_shoes = 38 + + def build_shoes(bm: bmesh.types.BMesh) -> None: + for s_idx in range(n_shoes): + target_d = total_d = (s_idx / n_shoes) * total_len + acc = 0.0 + for i, sl in enumerate(segs): + if acc + sl >= target_d or i == len(segs) - 1: + t = (target_d - acc) / max(sl, 1e-6) + y0, z0 = pts[i] + y1, z1 = pts[i + 1] + py = y0 + (y1 - y0) * t + pz = z0 + (z1 - z0) * t + ang = math.atan2(z1 - z0, y1 - y0) + # Normal pointing outward from loop (y, z) + m = ( + Matrix.Translation((0.0, py, pz)) + @ Matrix.Rotation(ang, 4, "X") + @ Matrix.Diagonal((track_w, 0.085, 0.026, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + break + acc += sl + + vc.make_bmesh_object(f"{name}_shoes", build_shoes, "gunmetal", parent=pod) + + # Armored track fender & upper side skirt (Brokkr plate.v0 slab) + vc.make_box(f"{name}_fender_top", (track_w + 0.06, 3.24, 0.055), "olive_armor", parent=pod, location=(0.0, -0.02, 0.79), bevel=0.008) + vc.make_box(f"{name}_fender_front", (track_w + 0.06, 0.34, 0.055), "olive_armor", parent=pod, location=(0.0, -1.72, 0.68), rotation_deg=(36.0, 0.0, 0.0), bevel=0.008) + vc.make_box(f"{name}_fender_rear", (track_w + 0.06, 0.32, 0.055), "olive_armor", parent=pod, location=(0.0, 1.66, 0.68), rotation_deg=(-36.0, 0.0, 0.0), bevel=0.008) + + # Outer bolted track skirt covering upper roadwheels + skirt_pts = [ + [side * 0.22, -1.36, 0.78], + [side * 0.22, 1.36, 0.78], + [side * 0.22, 1.18, 0.36], + [side * 0.22, -1.16, 0.36], + ] + vc.make_box( + f"{name}_skirt", + (0.045, 2.52, 0.40), + "olive_armor", + parent=pod, + location=(side * (track_w * 0.5 + 0.025), 0.0, 0.58), + bevel=0.008, + ) + + +def build_ferret() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("FerretRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # --- 1. Lower Tub & Wedge Glacis Hull (Brokkr plate.v0 convex hull) --- + vc.make_box("lower_tub", (1.28, 3.06, 0.44), "gunmetal", parent=chassis, location=(0.0, -0.04, 0.46), bevel=0.012) + + hull_pts = [ + [-0.64, -1.68, 0.46], [0.64, -1.68, 0.46], + [0.68, -1.68, 0.64], [-0.68, -1.68, 0.64], + [-0.68, -0.78, 1.04], [0.68, -0.78, 1.04], + [-0.68, 0.66, 1.04], [0.68, 0.66, 1.04], + [-0.64, 1.66, 0.80], [0.64, 1.66, 0.80], + [-0.64, 1.66, 0.50], [0.64, 1.66, 0.50], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "ferret_hull", + "mat": "olive_armor", + "bevel": 0.014, + "sides": "one", + "mirror": False, + "points": hull_pts, + "clad": { + "mat": "olive_armor", + "facets": [{"n": [0.0, -0.45, 0.89], "cos": 0.90}], + "min_area": 0.12, + "lifts": [0.008, 0.014], + "inset": 0.05, + "gap": 0.016, + "split": 0.90, + "seed": 601, + "bolt_r": 0.012, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + }, + # Sloped upper hull sponson cheek plates + { + "name": "ferret_sponson", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.76, 0.14, 0.90], + "normal": [0.85, 0.0, 0.52], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.94, -0.14], [0.94, -0.14], [0.76, 0.14], [-0.78, 0.14]], + "thick": 0.05, + "taper": 0.014, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.30, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Headlights, tow shackles, and flank cylindrical mufflers + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"headlight_{tag}", (0.12, 0.12, 0.10), "gunmetal", parent=chassis, location=(side * 0.82, -1.52, 0.88), bevel=0.008) + vc.make_box(f"tow_shackle_{tag}", (0.06, 0.10, 0.10), "signal_orange", parent=chassis, location=(side * 0.42, -1.72, 0.56), bevel=0.005) + # Side exhaust muffler + copper pipes + vc.make_tube_part( + f"muffler_{tag}", 0.085, 0.085, 0.62, segments=12, + mat_name="gunmetal", parent=chassis, location=(side * 0.80, 0.72, 0.92), rotation_deg=(-90.0, 0.0, 0.0), + ) + vc.make_swept_tube( + f"muffler_pipe_{tag}", + [[side * 0.62, 0.64, 0.92], [side * 0.80, 0.72, 0.92], [side * 0.80, 1.44, 0.90]], + 0.032, segments=8, mat_name="copper_rad", parent=chassis, fillet_r=0.03, + ) + + # --- 2. Wide Articulated Track Pods --- + _build_track_pod("track_pod_L", 1.0, chassis) + _build_track_pod("track_pod_R", -1.0, chassis) + + # --- 3. Low Octagonal Turret (joint.turret_yaw) --- + turret_pivot = vc.make_empty("joint.turret_yaw", parent=chassis, location=(0.0, -0.18, 1.04)) + vc.tag_joint(turret_pivot, "joint.turret_yaw", [0.0, 1.0, 0.0], -180.0, 180.0) + joints_manifest = [{"id": "joint.turret_yaw", "axis": [0.0, 1.0, 0.0], "min": -180.0, "max": 180.0}] + + # Turret ring race + vc.make_tube_part("turret_race", 0.54, 0.58, 0.07, segments=20, mat_name="gunmetal", parent=turret_pivot, location=(0.0, 0.0, 0.0)) + + turret_pts = [ + [-0.46, -0.52, 0.06], [0.46, -0.52, 0.06], + [0.54, -0.10, 0.06], [0.48, 0.56, 0.06], + [-0.48, 0.56, 0.06], [-0.54, -0.10, 0.06], + [-0.36, -0.40, 0.42], [0.36, -0.40, 0.42], + [0.42, -0.06, 0.42], [0.38, 0.46, 0.42], + [-0.38, 0.46, 0.42], [-0.42, -0.06, 0.42], + ] + turret_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "ferret_turret_shell", + "mat": "olive_armor", + "bevel": 0.012, + "sides": "one", + "mirror": False, + "points": turret_pts, + }, + ], + } + vc.make_plates(turret_doc, parent=turret_pivot) + + # Commander hatch & front optic prism + cheek pylon shelf + vc.make_tube_part("commander_cupola", 0.17, 0.18, 0.08, segments=12, mat_name="olive_armor", parent=turret_pivot, location=(-0.16, 0.14, 0.42)) + vc.make_box("turret_optic", (0.14, 0.16, 0.10), "smoked_glass", parent=turret_pivot, location=(0.18, -0.26, 0.45), bevel=0.006) + vc.make_box("turret_mantlet_collar", (0.28, 0.16, 0.22), "gunmetal", parent=turret_pivot, location=(0.0, -0.50, 0.24), bevel=0.008) + vc.make_box("cheek_pylon_shelf", (0.24, 0.34, 0.08), "gunmetal", parent=turret_pivot, location=(0.56, 0.02, 0.22), bevel=0.006) + + # --- 4. Visible Exterior Hardpoints (3x4 Dorsal Grid) --- + # 1) Front wedge glacis armor stud rail + vc.add_hardpoint_slot( + "hp.armor.glacis", + "armor", + parent=chassis, + location=(0.0, -1.24, 0.85), + rotation_deg=(66.0, 0.0, 0.0), + size=(1.12, 0.34, 0.08), + plinth_depth=0.03, + ) + # 2) Main turret weapon collar + vc.add_hardpoint_slot( + "hp.weapon.turret", + "weapon", + parent=turret_pivot, + location=(0.0, -0.02, 0.43), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.62, 0.62, 0.10), + ) + # 3) Turret cheek pod weapon collar (on left +X cheek pylon shelf) + vc.add_hardpoint_slot( + "hp.weapon.pod", + "weapon", + parent=turret_pivot, + location=(0.58, 0.02, 0.27), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.34, 0.34, 0.07), + ) + # 4) Rear engine bay frame (sloped deck surface at y=0.82 is z=1.00) + vc.add_hardpoint_slot( + "hp.engine.rear", + "engine", + parent=chassis, + location=(0.0, 0.82, 0.99), + rotation_deg=(-13.5, 0.0, 0.0), + size=(0.86, 0.66, 0.13), + plinth_depth=0.04, + ) + # 5) Rear deck copper radiator louver bay (sloped deck surface at y=1.42 is z=0.858) + vc.add_hardpoint_slot( + "hp.radiator.deck", + "radiator", + parent=chassis, + location=(0.0, 1.42, 0.845), + rotation_deg=(-13.5, 0.0, 0.0), + size=(0.88, 0.44, 0.09), + plinth_depth=0.04, + ) + + # --- 5. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "ferret" / "ferret.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "ferret" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "ferret_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="ferret", + name="Ferret", + vehicle_class="Light Tracked Scout Tankette", + grid_width=3, + grid_height=4, + mask=[ + "###", + "###", + "###", + "###", + ], + hardpoints=[ + {"id": "hp.armor.glacis", "kind": "armor", "x": 0, "y": 0, "w": 3, "h": 1, "modelNodeId": "hp.armor.glacis"}, + {"id": "hp.weapon.pod", "kind": "weapon", "x": 0, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.weapon.pod"}, + {"id": "hp.weapon.turret", "kind": "weapon", "x": 1, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.turret"}, + {"id": "hp.engine.rear", "kind": "engine", "x": 2, "y": 2, "w": 1, "h": 2, "modelNodeId": "hp.engine.rear"}, + {"id": "hp.radiator.deck", "kind": "radiator", "x": 1, "y": 3, "w": 1, "h": 1, "modelNodeId": "hp.radiator.deck"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[ferret] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "ferret", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_ferret() diff --git a/tools/vehicles/build_gear.py b/tools/vehicles/build_gear.py new file mode 100644 index 0000000..60b095d --- /dev/null +++ b/tools/vehicles/build_gear.py @@ -0,0 +1,144 @@ +"""Build the 6 modular starter gear GLBs into assets/gear/.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _export_gear(name: str, root) -> tuple[int, dict]: + glb_path = vc.ASSETS_GEAR_DIR / f"{name}.glb" + tris, bounds = vc.export_vehicle_glb(glb_path, root=root) + print(f"[gear:{name}] tris={tris} bounds={bounds} glb={glb_path}") + return tris, bounds + + +def build_mg_762() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Pintle base + yoke + receiver + perforated barrel shroud + side ammo box + spade grips + vc.make_tube_part("pintle_base", 0.14, 0.12, 0.06, segments=12, mat_name="gunmetal", parent=root) + vc.make_box("cradle_yoke", (0.14, 0.18, 0.18), "gunmetal", parent=root, location=(0.0, 0.0, 0.15), bevel=0.006) + vc.make_box("receiver", (0.12, 0.44, 0.14), "olive_armor", parent=root, location=(0.0, -0.04, 0.28), bevel=0.006) + vc.make_tube_part("barrel_shroud", 0.032, 0.028, 0.48, segments=10, mat_name="gunmetal", parent=root, location=(0.0, -0.24, 0.29), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part("barrel_inner", 0.014, 0.014, 0.68, segments=8, mat_name="gunmetal", parent=root, location=(0.0, -0.24, 0.29), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_box("ammo_box", (0.14, 0.22, 0.16), "olive_armor", parent=root, location=(0.14, -0.02, 0.25), bevel=0.006) + vc.make_box("ammo_latch", (0.04, 0.10, 0.04), "signal_orange", parent=root, location=(0.14, -0.02, 0.34), bevel=0.003) + for side in (-1.0, 1.0): + vc.make_tube_part(f"grip_{'L' if side > 0 else 'R'}", 0.012, 0.012, 0.10, segments=6, mat_name="rubber_dark", parent=root, location=(side * 0.06, 0.22, 0.23)) + _export_gear("mg_762", root) + + +def build_autocannon() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Turret base ring + twin armored trunnion cheeks + dual 20mm barrels + twin ammo drums + vc.make_tube_part("turret_collar", 0.26, 0.24, 0.08, segments=16, mat_name="gunmetal", parent=root) + vc.make_box("gun_housing", (0.30, 0.46, 0.24), "olive_armor", parent=root, location=(0.0, 0.04, 0.20), bevel=0.010) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_tube_part(f"barrel_jacket_{tag}", 0.036, 0.030, 0.42, segments=10, mat_name="gunmetal", parent=root, location=(side * 0.085, -0.18, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part(f"barrel_tube_{tag}", 0.018, 0.018, 0.88, segments=8, mat_name="gunmetal", parent=root, location=(side * 0.085, -0.18, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part(f"muzzle_brake_{tag}", 0.028, 0.028, 0.09, segments=8, mat_name="copper_rad", parent=root, location=(side * 0.085, -1.00, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part(f"ammo_drum_{tag}", 0.13, 0.13, 0.16, segments=14, mat_name="olive_armor", parent=root, location=(side * 0.22, 0.14, 0.24), rotation_deg=(0.0, 90.0 * side, 0.0)) + vc.make_box("optic_pod", (0.10, 0.14, 0.09), "smoked_glass", parent=root, location=(0.0, -0.08, 0.36), bevel=0.005) + _export_gear("autocannon", root) + + +def build_recoilless() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Pedestal + heavy long recoilless tube + flared rear venturi + top optic rail + vc.make_tube_part("base_flange", 0.20, 0.18, 0.07, segments=14, mat_name="gunmetal", parent=root) + vc.make_box("trunnion_post", (0.14, 0.20, 0.20), "gunmetal", parent=root, location=(0.0, 0.02, 0.16), bevel=0.008) + tube_prof = [ + [0.055, -0.58], + [0.085, -0.58], + [0.095, -0.35], + [0.095, 0.42], + [0.072, 0.46], + [0.072, 0.78], + [0.088, 0.82], + [0.062, 0.82], + [0.055, 0.44], + ] + vc.make_lathe_part("launcher_tube", tube_prof, segments=16, loop=True, smooth=True, mat_name="olive_armor", parent=root, location=(0.0, 0.0, 0.32), rotation_deg=(-90.0, 0.0, 0.0)) + vc.make_box("breech_band", (0.20, 0.12, 0.20), "signal_orange", parent=root, location=(0.0, 0.26, 0.32), bevel=0.006) + vc.make_tube_part("sight_tube", 0.028, 0.032, 0.22, segments=10, mat_name="gunmetal", parent=root, location=(0.11, -0.02, 0.36), rotation_deg=(90.0, 0.0, 0.0)) + _export_gear("recoilless", root) + + +def build_copper_rad() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Industrial copper finned radiator bank + armored end tanks + coolant pipes + base flange + vc.make_box("base_flange", (0.48, 0.42, 0.045), "gunmetal", parent=root, location=(0.0, 0.0, 0.0225), bevel=0.006) + vc.make_kit_part( + "copper_fins", + "mechanical", + "radiator_stack", + {"fins": 10, "fin_w": 0.36, "fin_h": 0.24, "fin_t": 0.008, "pitch": 0.032, "segments": 10}, + mat_name="copper_rad", + parent=root, + location=(0.0, -0.145, 0.18), + rotation_deg=(-90.0, 0.0, 0.0), + ) + for side in (-1.0, 1.0): + vc.make_box(f"end_tank_{'L' if side > 0 else 'R'}", (0.06, 0.38, 0.26), "gunmetal", parent=root, location=(side * 0.21, 0.0, 0.18), bevel=0.008) + vc.make_swept_tube(f"coolant_pipe_{'L' if side > 0 else 'R'}", [[side * 0.21, 0.14, 0.26], [side * 0.21, 0.24, 0.18], [side * 0.16, 0.24, 0.06]], 0.018, segments=8, mat_name="copper_rad", parent=root, fillet_r=0.02) + vc.make_box("top_cap_bar", (0.44, 0.06, 0.04), "signal_orange", parent=root, location=(0.0, -0.15, 0.31), bevel=0.004) + _export_gear("copper_rad", root) + + +def build_gilded_lance() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Imperial Tourist ornate gilded thermal lance with ivory cowl, gold flutes, and cyan condenser rings + vc.make_tube_part("imperial_base", 0.24, 0.21, 0.08, segments=18, mat_name="imperial_gold", parent=root) + vc.make_box("ivory_cowl", (0.28, 0.52, 0.22), "imperial_ivory", parent=root, location=(0.0, 0.02, 0.20), bevel=0.014) + vc.make_box("gold_crest", (0.10, 0.44, 0.08), "imperial_gold", parent=root, location=(0.0, 0.02, 0.32), bevel=0.008) + vc.make_tube_part("lance_core", 0.042, 0.026, 0.96, segments=14, mat_name="imperial_gold", parent=root, location=(0.0, -0.20, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + for i, dy in enumerate((-0.42, -0.64, -0.86)): + vc.make_tube_part(f"condenser_ring_{i}", 0.062 - i * 0.006, 0.062 - i * 0.006, 0.04, segments=14, mat_name="cyan_coil", parent=root, location=(0.0, dy, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + _export_gear("gilded_lance", root) + + +def build_gold_radiator() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Imperial Tourist ornate gilded louver array with ivory housing & cyan thermal core + vc.make_box("imperial_flange", (0.48, 0.42, 0.045), "imperial_gold", parent=root, location=(0.0, 0.0, 0.0225), bevel=0.006) + vc.make_box("ivory_shroud", (0.44, 0.38, 0.22), "imperial_ivory", parent=root, location=(0.0, 0.0, 0.155), bevel=0.012) + vc.make_box("cyan_core", (0.34, 0.28, 0.16), "cyan_coil", parent=root, location=(0.0, 0.0, 0.16), bevel=0.004) + def build_gold_vanes(bm: bmesh.types.BMesh) -> None: + for i in range(7): + y = -0.14 + 0.28 * (i / 6.0) + m = Matrix.Translation((0.0, y, 0.265)) @ Matrix.Rotation(math.radians(20.0), 4, "X") @ Matrix.Diagonal((0.38, 0.022, 0.055, 1.0)) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + vc.make_bmesh_object("gold_vanes", build_gold_vanes, "imperial_gold", parent=root) + _export_gear("gold_radiator", root) + + +def build_all_gear() -> None: + build_mg_762() + build_autocannon() + build_recoilless() + build_copper_rad() + build_gilded_lance() + build_gold_radiator() + + +if __name__ == "__main__": + build_all_gear() diff --git a/tools/vehicles/build_hornet.py b/tools/vehicles/build_hornet.py new file mode 100644 index 0000000..bb073e1 --- /dev/null +++ b/tools/vehicles/build_hornet.py @@ -0,0 +1,400 @@ +"""Build the Hornet (Light Ducted-Fan VTOL Gunship) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _build_ducted_nacelle(name: str, side: float, parent, joints_manifest: list[dict]) -> None: + """Build a pivoting armored ducted-fan nacelle with inner copper thrust collar and spinning rotor.""" + nacelle_id = f"joint.nacelle_{'l' if side > 0 else 'r'}" + nacelle_pivot = vc.make_empty( + nacelle_id, + parent=parent, + location=(side * 1.18, 0.10, 1.32), + rotation_deg=(-18.0, 0.0, 0.0), + ) + vc.tag_joint(nacelle_pivot, nacelle_id, [1.0, 0.0, 0.0], -45.0, 75.0) + joints_manifest.append({"id": nacelle_id, "axis": [1.0, 0.0, 0.0], "min": -45.0, "max": 75.0}) + + # Upper olive-drab armored duct shroud (CCW in (r, z) for core.lathe) + shroud_prof = [ + [0.34, -0.06], + [0.44, -0.06], + [0.47, 0.02], + [0.47, 0.22], + [0.43, 0.28], + [0.35, 0.28], + [0.33, 0.20], + [0.34, -0.06], + ] + vc.make_lathe_part( + f"{name}_shroud", + shroud_prof[:-1], + segments=22, + loop=True, + smooth=True, + mat_name="olive_armor", + parent=nacelle_pivot, + ) + # Lower copper thermal exhaust skirt + skirt_prof = [ + [0.33, -0.20], + [0.41, -0.20], + [0.44, -0.06], + [0.34, -0.06], + ] + vc.make_lathe_part( + f"{name}_skirt", + skirt_prof, + segments=22, + loop=True, + smooth=True, + mat_name="copper_rad", + parent=nacelle_pivot, + ) + # Stator cross vanes + hinge yoke collar + for ang_deg in (0.0, 90.0): + vc.make_box( + f"{name}_stator_{int(ang_deg)}", + (0.68, 0.04, 0.06), + "gunmetal", + parent=nacelle_pivot, + location=(0.0, 0.0, -0.08), + rotation_deg=(0.0, 0.0, ang_deg), + bevel=0.004, + ) + vc.make_box( + f"{name}_hinge_lug", + (0.16, 0.22, 0.16), + "gunmetal", + parent=nacelle_pivot, + location=(-side * 0.44, 0.0, 0.08), + bevel=0.008, + ) + + # Spinning rotor hub + 4 pitched fan blades (about glTF +Y = Blender +Z) + rotor_id = f"joint.rotor_{'l' if side > 0 else 'r'}" + rotor_pivot = vc.make_empty(rotor_id, parent=nacelle_pivot, location=(0.0, 0.0, 0.04)) + vc.tag_joint(rotor_pivot, rotor_id, [0.0, 1.0, 0.0], -360.0, 360.0) + joints_manifest.append({"id": rotor_id, "axis": [0.0, 1.0, 0.0], "min": -360.0, "max": 360.0}) + + spinner_prof = [ + [0.0, -0.04], + [0.10, -0.04], + [0.10, 0.06], + [0.06, 0.16], + [0.0, 0.22], + ] + vc.make_lathe_part(f"{name}_spinner", spinner_prof, segments=14, loop=False, smooth=True, mat_name="gunmetal", parent=rotor_pivot) + + def build_blades(bm: bmesh.types.BMesh) -> None: + for i in range(4): + a = i * math.pi * 0.5 + m = ( + Matrix.Rotation(a, 4, "Z") + @ Matrix.Translation((0.20, 0.0, 0.02)) + @ Matrix.Rotation(math.radians(22.0), 4, "X") + @ Matrix.Diagonal((0.24, 0.085, 0.014, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + + vc.make_bmesh_object(f"{name}_blades", build_blades, "gunmetal", parent=rotor_pivot) + + +def build_hornet() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("HornetRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # --- 1. Rugged Steel Landing Skids (grounded at Z = 0) --- + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_swept_tube( + f"skid_runner_{tag}", + [ + [side * 0.72, -1.56, 0.16], + [side * 0.72, -1.24, 0.032], + [side * 0.72, 1.06, 0.032], + ], + 0.032, + segments=8, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.08, + ) + # Front & rear diagonal skid struts up to fuselage belly + for s_tag, sy_lo, sy_hi in (("f", -0.82, -0.68), ("r", 0.52, 0.44)): + vc.make_swept_tube( + f"skid_strut_{tag}_{s_tag}", + [[side * 0.72, sy_lo, 0.04], [side * 0.40, sy_hi, 0.54]], + 0.026, + segments=8, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.0, + ) + + # --- 2. Faceted Armored Cockpit & Fuselage Hull (Brokkr plate.v0) --- + hull_pts = [ + [-0.28, -1.86, 0.56], [0.28, -1.86, 0.56], + [-0.36, -1.78, 0.78], [0.36, -1.78, 0.78], + [-0.58, -0.86, 0.46], [0.58, -0.86, 0.46], + [-0.64, -0.64, 1.02], [0.64, -0.64, 1.02], + [-0.64, 0.76, 1.02], [0.64, 0.76, 1.02], + [-0.56, 0.88, 0.54], [0.56, 0.88, 0.54], + [-0.44, 0.64, 1.44], [0.44, 0.64, 1.44], + [-0.44, -0.26, 1.44], [0.44, -0.26, 1.44], + ] + canopy_pts = [ + [-0.34, -1.66, 0.78], [0.34, -1.66, 0.78], + [-0.52, -0.88, 1.02], [0.52, -0.88, 1.02], + [-0.42, -0.28, 1.40], [0.42, -0.28, 1.40], + [-0.36, -0.88, 1.38], [0.36, -0.88, 1.38], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "hornet_fuselage", + "mat": "olive_armor", + "bevel": 0.014, + "sides": "one", + "mirror": False, + "points": hull_pts, + }, + { + "name": "hornet_canopy", + "mat": "smoked_glass", + "bevel": 0.008, + "sides": "one", + "mirror": False, + "points": canopy_pts, + }, + # Cheek armor skirts with bolts + { + "name": "hornet_cheek", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.58, -0.62, 0.76], + "normal": [0.92, -0.28, 0.26], + "up": [0.0, 0.0, 1.0], + "right": [-0.28, -0.96, 0.0], + "outline": [[-0.56, -0.14], [0.52, -0.18], [0.48, 0.16], [-0.46, 0.14]], + "thick": 0.04, + "taper": 0.012, + "back": 0.90, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.24, "mat": "gunmetal", "params": "r=0.011"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Canopy structural armor ribs + nose EO/IR optics pod + vc.make_swept_tube( + "canopy_spine", + [[0.0, -1.68, 0.78], [0.0, -0.90, 1.40], [0.0, -0.26, 1.44]], + 0.024, segments=6, mat_name="olive_armor", parent=chassis, fillet_r=0.04, + ) + for side in (-1.0, 1.0): + vc.make_swept_tube( + f"canopy_rib_{'L' if side > 0 else 'R'}", + [[side * 0.33, -1.65, 0.78], [side * 0.37, -0.89, 1.38], [side * 0.43, -0.28, 1.42]], + 0.020, segments=6, mat_name="olive_armor", parent=chassis, fillet_r=0.04, + ) + vc.make_box("nose_optics_housing", (0.24, 0.20, 0.18), "gunmetal", parent=chassis, location=(0.0, -1.86, 0.66), bevel=0.01) + vc.make_tube_part("nose_optics_lens", 0.065, 0.065, 0.06, segments=12, mat_name="smoked_glass", parent=chassis, location=(0.0, -1.94, 0.66), rotation_deg=(90.0, 0.0, 0.0)) + + # Stub wings + nacelle outrigger arms + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box( + f"stub_wing_{tag}", + (0.68, 0.56, 0.09), + "olive_armor", + parent=chassis, + location=(side * 0.74, 0.14, 0.74), + rotation_deg=(0.0, side * 8.0, side * -10.0), + bevel=0.01, + ) + vc.make_box( + f"nacelle_arm_{tag}", + (0.46, 0.30, 0.18), + "gunmetal", + parent=chassis, + location=(side * 0.62, 0.10, 1.32), + bevel=0.01, + ) + + # --- 3. Pivoting Ducted-Fan Nacelles + Hydraulic Tilt Actuators --- + joints_manifest: list[dict] = [] + for side in (1.0, -1.0): + tag = "L" if side > 0 else "R" + _build_ducted_nacelle(f"nacelle_{tag}", side, chassis, joints_manifest) + # Dual hydraulic tilt actuator from dorsal shoulder clevis out to nacelle hinge lug + vc.make_box(f"tilt_clevis_{tag}", (0.10, 0.14, 0.10), "gunmetal", parent=chassis, location=(side * 0.44, -0.10, 1.38), bevel=0.005) + vc.make_ram_span( + f"tilt_actuator_{tag}", + [side * 0.44, -0.10, 1.38], + [side * 0.78, 0.08, 1.38], + body_r=0.028, + rod_r=0.015, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + + # --- 4. Skeletal Truss Tail Boom & V/T Tailfins --- + # Rear boom mounting bulkhead + 3-chord space-frame tail boom anchored inside fuselage + vc.make_box("tail_boom_collar", (0.44, 0.28, 0.42), "gunmetal", parent=chassis, location=(0.0, 0.74, 1.10), bevel=0.01) + boom_top_l = [0.16, 0.62, 1.24] + boom_top_r = [-0.16, 0.62, 1.24] + boom_bot = [0.0, 0.62, 0.94] + tail_top_l = [0.07, 2.38, 1.34] + tail_top_r = [-0.07, 2.38, 1.34] + tail_bot = [0.0, 2.38, 1.16] + for cname, p0, p1 in [ + ("boom_tl", boom_top_l, tail_top_l), + ("boom_tr", boom_top_r, tail_top_r), + ("boom_bt", boom_bot, tail_bot), + ]: + vc.make_swept_tube(cname, [p0, p1], 0.020, segments=6, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + + # Truss bay diagonals along the tail boom + n_bays = 5 + def lerp3(a, b, t): + return [a[k] + (b[k] - a[k]) * t for k in range(3)] + + for i in range(n_bays): + t0 = i / n_bays + t1 = (i + 1) / n_bays + p_tl0, p_tr0, p_b0 = lerp3(boom_top_l, tail_top_l, t0), lerp3(boom_top_r, tail_top_r, t0), lerp3(boom_bot, tail_bot, t0) + p_tl1, p_tr1, p_b1 = lerp3(boom_top_l, tail_top_l, t1), lerp3(boom_top_r, tail_top_r, t1), lerp3(boom_bot, tail_bot, t1) + vc.make_swept_tube(f"boom_cross_{i}", [p_tl1, p_tr1, p_b1, p_tl1], 0.012, segments=6, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + vc.make_swept_tube(f"boom_diag_l_{i}", [p_tl0, p_b1], 0.011, segments=6, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + vc.make_swept_tube(f"boom_diag_r_{i}", [p_tr0, p_b1], 0.011, segments=6, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + + # Swept-back V-tail stabilizers + ventral fin + tail hub + vc.make_box("tail_fin_hub", (0.16, 0.24, 0.20), "gunmetal", parent=chassis, location=(0.0, 2.36, 1.26), bevel=0.008) + for side in (-1.0, 1.0): + vc.make_box( + f"vtail_{'L' if side > 0 else 'R'}", + (0.04, 0.34, 0.62), + "olive_armor", + parent=chassis, + location=(side * 0.24, 2.40, 1.54), + rotation_deg=(22.0, side * -38.0, 0.0), + bevel=0.006, + ) + vc.make_box("ventral_fin", (0.035, 0.26, 0.24), "olive_armor", parent=chassis, location=(0.0, 2.36, 1.04), rotation_deg=(22.0, 0.0, 0.0), bevel=0.006) + + # --- 5. Visible Exterior Hardpoints (4x4 Dorsal Grid) --- + # 1) Chin gimbal collar (under nose, pointing +Z forward and -Y downward) + vc.add_hardpoint_slot( + "hp.weapon.chin", + "weapon", + parent=chassis, + location=(0.0, -1.46, 0.525), + rotation_deg=(5.7, 180.0, 0.0), + size=(0.42, 0.42, 0.08), + plinth_depth=0.04, + ) + # 2 & 3) Stub-wing weapon pylons (under left/right wings) + vc.add_hardpoint_slot( + "hp.weapon.wing_l", + "weapon", + parent=chassis, + location=(0.88, 0.14, 0.69), + rotation_deg=(0.0, 180.0, 0.0), + size=(0.34, 0.34, 0.07), + ) + vc.add_hardpoint_slot( + "hp.weapon.wing_r", + "weapon", + parent=chassis, + location=(-0.88, 0.14, 0.69), + rotation_deg=(0.0, 180.0, 0.0), + size=(0.34, 0.34, 0.07), + ) + # 4) Dorsal turbine core engine bay + vc.add_hardpoint_slot( + "hp.engine.core", + "engine", + parent=chassis, + location=(0.0, 0.26, 1.44), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.74, 0.80, 0.13), + ) + # 5 & 6) Twin copper-louvered nacelle root exhaust radiator bays + vc.add_hardpoint_slot( + "hp.radiator.nacelle_l", + "radiator", + parent=chassis, + location=(0.54, -0.32, 1.23), + rotation_deg=(72.0, 0.0, 34.0), + size=(0.36, 0.32, 0.09), + plinth_depth=0.04, + ) + vc.add_hardpoint_slot( + "hp.radiator.nacelle_r", + "radiator", + parent=chassis, + location=(-0.54, -0.32, 1.23), + rotation_deg=(72.0, 0.0, -34.0), + size=(0.36, 0.32, 0.09), + plinth_depth=0.04, + ) + + # --- 6. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "hornet" / "hornet.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "hornet" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "hornet_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="hornet", + name="Hornet", + vehicle_class="Light Ducted-Fan VTOL Gunship", + grid_width=4, + grid_height=4, + mask=[ + ".##.", + "####", + "####", + ".##.", + ], + hardpoints=[ + {"id": "hp.weapon.chin", "kind": "weapon", "x": 1, "y": 0, "w": 1, "h": 2, "modelNodeId": "hp.weapon.chin"}, + {"id": "hp.radiator.nacelle_l", "kind": "radiator", "x": 0, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.radiator.nacelle_l"}, + {"id": "hp.radiator.nacelle_r", "kind": "radiator", "x": 3, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.radiator.nacelle_r"}, + {"id": "hp.weapon.wing_l", "kind": "weapon", "x": 0, "y": 2, "w": 1, "h": 1, "modelNodeId": "hp.weapon.wing_l"}, + {"id": "hp.engine.core", "kind": "engine", "x": 1, "y": 2, "w": 2, "h": 2, "modelNodeId": "hp.engine.core"}, + {"id": "hp.weapon.wing_r", "kind": "weapon", "x": 3, "y": 2, "w": 1, "h": 1, "modelNodeId": "hp.weapon.wing_r"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[hornet] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "hornet", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_hornet() diff --git a/tools/vehicles/build_ironclad.py b/tools/vehicles/build_ironclad.py new file mode 100644 index 0000000..a20dfeb --- /dev/null +++ b/tools/vehicles/build_ironclad.py @@ -0,0 +1,423 @@ +"""Build the Ironclad (Medium Tracked Battle Tank) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _build_mbt_track_pod(name: str, side: float, parent) -> None: + """Build one wide MBT track assembly with 5 double roadwheels, idler, sprocket, shoes, and bolted side skirt.""" + pod_x = side * 1.12 + pod = vc.make_empty(name, parent=parent, location=(pod_x, 0.0, 0.0)) + + rw_r = 0.28 + rw_z = rw_r + 0.045 + rw_ys = (-1.28, -0.64, 0.0, 0.64, 1.28) + idler_y, idler_z, idler_r = -1.94, 0.56, 0.25 + sproc_y, sproc_z, sproc_r = 1.92, 0.58, 0.26 + track_w = 0.48 + + # Roadwheels (5) + 3 return rollers + Front Idler + Rear Drive Sprocket + for i, ry in enumerate(rw_ys): + vc.make_tube_part( + f"{name}_rw_tire_{i}", rw_r, rw_r, track_w * 0.84, segments=16, + mat_name="rubber_dark", parent=pod, location=(-track_w * 0.42, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_rw_dish_{i}", rw_r * 0.68, rw_r * 0.68, track_w * 0.90, segments=12, + mat_name="olive_armor", parent=pod, location=(-track_w * 0.45, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_rw_cap_{i}", rw_r * 0.28, rw_r * 0.28, track_w * 0.94, segments=10, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.47, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + for j, rry in enumerate((-0.96, 0.0, 0.96)): + vc.make_tube_part( + f"{name}_ret_{j}", 0.09, 0.09, track_w * 0.68, segments=10, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.34, rry, 0.78), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_idler", idler_r, idler_r, track_w * 0.80, segments=14, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.40, idler_y, idler_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_sprocket", sproc_r, sproc_r, track_w * 0.84, segments=14, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.42, sproc_y, sproc_z), rotation_deg=(0.0, 90.0, 0.0), + ) + + # Track loop polyline in (y, z) + loop_yz: list[tuple[float, float]] = [] + for k in range(7): + ang = math.radians(95.0 + 145.0 * (k / 6.0)) + loop_yz.append((idler_y + math.cos(ang) * (idler_r + 0.03), idler_z + math.sin(ang) * (idler_r + 0.03))) + loop_yz.append((-1.28, 0.025)) + loop_yz.append((1.28, 0.025)) + for k in range(7): + ang = math.radians(-65.0 + 145.0 * (k / 6.0)) + loop_yz.append((sproc_y + math.cos(ang) * (sproc_r + 0.03), sproc_z + math.sin(ang) * (sproc_r + 0.03))) + loop_yz.append((0.60, 0.89)) + loop_yz.append((-0.60, 0.89)) + + path_3d = [[0.0, y, z] for (y, z) in loop_yz] + vc.make_swept_profile( + f"{name}_track_band", + "box", + 0.034, + track_w * 0.92, + 0.034, + path_3d, + up=[1.0, 0.0, 0.0], + mat_name="rubber_dark", + parent=pod, + closed=True, + ) + + # Articulated steel grouser shoes + pts = loop_yz + [loop_yz[0]] + segs = [math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]) for i in range(len(loop_yz))] + total_len = sum(segs) + n_shoes = 46 + + def build_shoes(bm: bmesh.types.BMesh) -> None: + for s_idx in range(n_shoes): + target_d = (s_idx / n_shoes) * total_len + acc = 0.0 + for i, sl in enumerate(segs): + if acc + sl >= target_d or i == len(segs) - 1: + t = (target_d - acc) / max(sl, 1e-6) + y0, z0 = pts[i] + y1, z1 = pts[i + 1] + py = y0 + (y1 - y0) * t + pz = z0 + (z1 - z0) * t + ang = math.atan2(z1 - z0, y1 - y0) + m = ( + Matrix.Translation((0.0, py, pz)) + @ Matrix.Rotation(ang, 4, "X") + @ Matrix.Diagonal((track_w, 0.095, 0.030, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + break + acc += sl + + vc.make_bmesh_object(f"{name}_shoes", build_shoes, "gunmetal", parent=pod) + + # Full-length top track fender + front/rear mudflaps + vc.make_box(f"{name}_fender_top", (track_w + 0.08, 4.18, 0.065), "olive_armor", parent=pod, location=(0.0, -0.02, 0.96), bevel=0.01) + vc.make_box(f"{name}_fender_front", (track_w + 0.08, 0.36, 0.06), "olive_armor", parent=pod, location=(0.0, -2.20, 0.84), rotation_deg=(38.0, 0.0, 0.0), bevel=0.008) + vc.make_box(f"{name}_fender_rear", (track_w + 0.08, 0.34, 0.06), "olive_armor", parent=pod, location=(0.0, 2.16, 0.84), rotation_deg=(-38.0, 0.0, 0.0), bevel=0.008) + + +def build_ironclad() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("IroncladRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # --- 1. Lower Armored Tub & Welded Angular MBT Hull (Brokkr plate.v0) --- + vc.make_box("lower_tub", (1.74, 4.10, 0.52), "gunmetal", parent=chassis, location=(0.0, -0.02, 0.56), bevel=0.014) + + hull_pts = [ + [-0.87, -2.26, 0.52], [0.87, -2.26, 0.52], + [-0.90, -2.24, 0.74], [0.90, -2.24, 0.74], + [-0.92, -1.16, 1.16], [0.92, -1.16, 1.16], + [-0.92, 0.96, 1.16], [0.92, 0.96, 1.16], + [-0.88, 2.18, 0.96], [0.88, 2.18, 0.96], + [-0.86, 2.16, 0.54], [0.86, 2.16, 0.54], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "ironclad_hull", + "mat": "olive_armor", + "bevel": 0.015, + "sides": "one", + "mirror": False, + "points": hull_pts, + "clad": { + "mat": "olive_armor", + "facets": [{"n": [0.0, -0.36, 0.93], "cos": 0.88}], + "min_area": 0.16, + "lifts": [0.008, 0.014], + "inset": 0.06, + "gap": 0.018, + "split": 0.88, + "seed": 701, + "bolt_r": 0.013, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + }, + # Heavy bolted forward/mid track skirts (leaves rear flank clear for radiator bays) + { + "name": "ironclad_track_skirt", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [1.39, -0.44, 0.68], + "normal": [1.0, 0.0, 0.0], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -1.0, 0.0], + "outline": [[-1.34, -0.26], [1.44, -0.26], [1.26, 0.28], [-1.34, 0.28]], + "thick": 0.048, + "taper": 0.010, + "back": 0.92, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.10, + "lifts": [0.008, 0.014], + "inset": 0.04, + "gap": 0.016, + "split": 0.72, + "seed": 702, + "bolt_r": 0.013, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "bolts", "inset": 0.025, "spacing": 0.34, "mat": "gunmetal", "params": "r=0.013"}, + ], + }, + # Sloped upper hull sponson shoulders + { + "name": "ironclad_sponson", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [1.08, 0.16, 1.04], + "normal": [0.76, 0.0, 0.65], + "up": [-0.65, 0.0, 0.76], + "right": [0.0, -1.0, 0.0], + "outline": [[-1.72, -0.18], [1.72, -0.18], [1.56, 0.18], [-1.56, 0.18]], + "thick": 0.05, + "taper": 0.014, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.36, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Rear flank armored housings for radiator bays + driver periscope + headlights + tow shackles + vc.make_box("driver_periscope", (0.42, 0.14, 0.09), "smoked_glass", parent=chassis, location=(-0.30, -1.32, 1.18), bevel=0.005) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"headlight_box_{tag}", (0.18, 0.14, 0.12), "gunmetal", parent=chassis, location=(side * 1.08, -2.06, 1.04), bevel=0.008) + vc.make_box(f"headlight_lens_{tag}", (0.12, 0.04, 0.07), "smoked_glass", parent=chassis, location=(side * 1.08, -2.13, 1.04), bevel=0.003) + vc.make_box(f"tow_shackle_{tag}", (0.07, 0.12, 0.12), "signal_orange", parent=chassis, location=(side * 0.56, -2.28, 0.62), bevel=0.006) + # Rear flank radiator mounting box + exhaust armor box + vc.make_box(f"rear_rad_housing_{tag}", (0.18, 1.04, 0.50), "olive_armor", parent=chassis, location=(side * 1.28, 1.36, 0.78), bevel=0.01) + vc.make_box(f"rear_exhaust_box_{tag}", (0.42, 0.34, 0.24), "gunmetal", parent=chassis, location=(side * 0.62, 2.08, 0.86), bevel=0.01) + vc.make_swept_tube( + f"exhaust_pipe_{tag}", + [[side * 0.62, 2.12, 0.86], [side * 0.72, 2.26, 0.88], [side * 0.72, 2.34, 0.78]], + 0.042, + segments=10, + mat_name="copper_rad", + parent=chassis, + fillet_r=0.03, + ) + # External cylindrical stern fuel drums (signature Ironclad silhouette; tank extends along local +Z) + vc.make_kit_part( + f"stern_fuel_drum_{tag}", + "mechanical", + "tank", + {"radius": 0.17, "length": 0.76, "segments": 14}, + mat_name="olive_armor", + parent=chassis, + location=(side * 0.06, 2.24, 1.04), + rotation_deg=(0.0, side * 90.0, 0.0), + ) + + # --- 2. Wide Articulated MBT Track Pods --- + _build_mbt_track_pod("track_pod_L", 1.0, chassis) + _build_mbt_track_pod("track_pod_R", -1.0, chassis) + + # --- 3. Faceted Central MBT Turret (joint.turret_yaw) --- + turret_pivot = vc.make_empty("joint.turret_yaw", parent=chassis, location=(0.0, -0.18, 1.16)) + vc.tag_joint(turret_pivot, "joint.turret_yaw", [0.0, 1.0, 0.0], -180.0, 180.0) + joints_manifest = [{"id": "joint.turret_yaw", "axis": [0.0, 1.0, 0.0], "min": -180.0, "max": 180.0}] + + vc.make_tube_part("turret_race", 0.76, 0.82, 0.08, segments=24, mat_name="gunmetal", parent=turret_pivot) + + turret_pts = [ + [-0.58, -0.84, 0.08], [0.58, -0.84, 0.08], + [0.86, -0.20, 0.08], [0.76, 0.88, 0.08], + [-0.76, 0.88, 0.08], [-0.86, -0.20, 0.08], + [-0.46, -0.60, 0.50], [0.46, -0.60, 0.50], + [0.64, -0.10, 0.50], [0.58, 0.76, 0.50], + [-0.58, 0.76, 0.50], [-0.64, -0.10, 0.50], + ] + turret_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "ironclad_turret_shell", + "mat": "olive_armor", + "bevel": 0.014, + "sides": "one", + "mirror": False, + "points": turret_pts, + }, + { + "name": "ironclad_turret_cheek", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.62, -0.52, 0.28], + "normal": [0.64, -0.68, 0.35], + "up": [-0.24, 0.25, 0.94], + "right": [-0.73, -0.68, 0.0], + "outline": [[-0.28, -0.16], [0.28, -0.16], [0.22, 0.16], [-0.22, 0.16]], + "thick": 0.05, + "taper": 0.012, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.20, "mat": "gunmetal", "params": "r=0.011"}, + ], + }, + ], + } + vc.make_plates(turret_doc, parent=turret_pivot) + + # Turret mantlet, bustle rack, commander cupola, CITV optic, smoke dischargers & coax bracket + vc.make_box("turret_mantlet", (0.52, 0.24, 0.26), "gunmetal", parent=turret_pivot, location=(0.0, -0.82, 0.28), bevel=0.01) + vc.make_box("turret_bustle", (1.10, 0.44, 0.32), "olive_armor", parent=turret_pivot, location=(0.0, 0.98, 0.32), bevel=0.01) + vc.make_tube_part("commander_cupola", 0.17, 0.19, 0.09, segments=14, mat_name="olive_armor", parent=turret_pivot, location=(-0.36, 0.46, 0.50)) + vc.make_box("turret_citv_pod", (0.18, 0.20, 0.16), "gunmetal", parent=turret_pivot, location=(0.34, -0.32, 0.56), bevel=0.008) + vc.make_box("turret_citv_lens", (0.12, 0.05, 0.09), "smoked_glass", parent=turret_pivot, location=(0.34, -0.42, 0.57), bevel=0.004) + vc.make_box("coax_bracket", (0.36, 0.42, 0.10), "gunmetal", parent=turret_pivot, location=(0.64, -0.22, 0.34), bevel=0.008) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + for k in range(3): + vc.make_tube_part( + f"smoke_tube_{tag}_{k}", 0.030, 0.030, 0.17, segments=8, + mat_name="gunmetal", parent=turret_pivot, + location=(side * 0.80, 0.36 + k * 0.10, 0.30), rotation_deg=(-58.0, 0.0, side * 22.0), + ) + + # --- 4. Visible Exterior Hardpoints (4x5 Dorsal Grid) --- + # 1) hp.armor.front (0,0, 4x1) + vc.add_hardpoint_slot( + "hp.armor.front", + "armor", + parent=chassis, + location=(0.0, -1.72, 0.94), + rotation_deg=(68.0, 0.0, 0.0), + size=(1.46, 0.36, 0.09), + plinth_depth=0.04, + ) + # 2) hp.weapon.main (1,1, 2x2) + vc.add_hardpoint_slot( + "hp.weapon.main", + "weapon", + parent=turret_pivot, + location=(0.0, -0.02, 0.51), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.82, 0.82, 0.11), + ) + # 3) hp.weapon.coax (0,1, 1x1) on left turret cheek bracket + vc.add_hardpoint_slot( + "hp.weapon.coax", + "weapon", + parent=turret_pivot, + location=(0.66, -0.22, 0.39), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.38, 0.38, 0.08), + ) + # 4) hp.armor.skirts (3,1, 1x2) on right (-X) track skirt + vc.add_hardpoint_slot( + "hp.armor.skirts", + "armor", + parent=chassis, + location=(-1.42, -0.38, 0.68), + rotation_deg=(90.0, 0.0, -90.0), + size=(1.28, 0.32, 0.09), + ) + # 5) hp.engine.rear (1,3, 2x2) + vc.add_hardpoint_slot( + "hp.engine.rear", + "engine", + parent=chassis, + location=(0.0, 1.48, 1.08), + rotation_deg=(-9.0, 0.0, 0.0), + size=(1.08, 0.92, 0.13), + ) + # 6 & 7) hp.radiator.l (0,3, 1x2) & hp.radiator.r (3,3, 1x2) + vc.add_hardpoint_slot( + "hp.radiator.l", + "radiator", + parent=chassis, + location=(1.36, 1.36, 0.78), + rotation_deg=(90.0, 0.0, 90.0), + size=(0.94, 0.44, 0.12), + ) + vc.add_hardpoint_slot( + "hp.radiator.r", + "radiator", + parent=chassis, + location=(-1.36, 1.36, 0.78), + rotation_deg=(90.0, 0.0, -90.0), + size=(0.94, 0.44, 0.12), + ) + + # --- 5. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "ironclad" / "ironclad.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "ironclad" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "ironclad_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="ironclad", + name="Ironclad", + vehicle_class="Medium Tracked Battle Tank", + grid_width=4, + grid_height=5, + mask=[ + "####", + "####", + "####", + "####", + "####", + ], + hardpoints=[ + {"id": "hp.armor.front", "kind": "armor", "x": 0, "y": 0, "w": 4, "h": 1, "modelNodeId": "hp.armor.front"}, + {"id": "hp.weapon.coax", "kind": "weapon", "x": 0, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.weapon.coax"}, + {"id": "hp.weapon.main", "kind": "weapon", "x": 1, "y": 1, "w": 2, "h": 2, "modelNodeId": "hp.weapon.main"}, + {"id": "hp.armor.skirts", "kind": "armor", "x": 3, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.armor.skirts"}, + {"id": "hp.radiator.l", "kind": "radiator", "x": 0, "y": 3, "w": 1, "h": 2, "modelNodeId": "hp.radiator.l"}, + {"id": "hp.engine.rear", "kind": "engine", "x": 1, "y": 3, "w": 2, "h": 2, "modelNodeId": "hp.engine.rear"}, + {"id": "hp.radiator.r", "kind": "radiator", "x": 3, "y": 3, "w": 1, "h": 2, "modelNodeId": "hp.radiator.r"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[ironclad] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "ironclad", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_ironclad() diff --git a/tools/vehicles/build_jackal.py b/tools/vehicles/build_jackal.py new file mode 100644 index 0000000..97bd932 --- /dev/null +++ b/tools/vehicles/build_jackal.py @@ -0,0 +1,405 @@ +"""Build the Jackal (Light Wheeled Dune Buggy) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def build_jackal() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("JackalRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # Dimensions & key coordinates (Blender: -Y forward, +Z up, +X left) + front_y = -1.12 + rear_y = 1.08 + track_x = 0.84 + wheel_r = 0.41 + wheel_w = 0.29 + axle_z = wheel_r + + # --- 1. Belly pan & central backbone --- + vc.make_box("belly_pan", (0.76, 2.24, 0.08), "gunmetal", parent=chassis, location=(0.0, 0.0, 0.34), bevel=0.01) + vc.make_box("front_diff", (0.28, 0.28, 0.20), "gunmetal", parent=chassis, location=(0.0, front_y, 0.42), bevel=0.01) + vc.make_box("rear_transaxle", (0.34, 0.36, 0.24), "gunmetal", parent=chassis, location=(0.0, rear_y, 0.44), bevel=0.01) + + # --- 2. Tubular Chromoly Rollcage & Bullbar (Brokkr core.sweep) --- + r_main = 0.025 + r_brace = 0.020 + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + # Lower sill rail + vc.make_swept_tube( + f"cage_sill_{tag}", + [ + [side * 0.30, -1.42, 0.48], + [side * 0.48, -0.78, 0.36], + [side * 0.48, 0.56, 0.36], + [side * 0.42, 1.38, 0.56], + ], + r_main, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + # Main A-pillar -> roof rail -> fastback B/C-pillar + vc.make_swept_tube( + f"cage_arch_{tag}", + [ + [side * 0.34, -1.24, 0.62], + [side * 0.44, -0.70, 0.82], + [side * 0.39, -0.14, 1.44], + [side * 0.39, 0.44, 1.44], + [side * 0.42, 1.38, 0.82], + [side * 0.42, 1.38, 0.56], + ], + r_main, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + # Mid beltline side bar + diagonal door brace + vc.make_swept_tube( + f"cage_belt_{tag}", + [ + [side * 0.45, -0.70, 0.78], + [side * 0.48, 0.52, 0.78], + [side * 0.42, 1.36, 0.80], + ], + r_brace, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + vc.make_swept_tube( + f"cage_diag_{tag}", + [[side * 0.46, -0.45, 0.42], [side * 0.41, 0.42, 1.42]], + r_brace, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + # Shock tower hoop + vc.make_swept_tube( + f"shock_hoop_{tag}", + [ + [side * 0.32, -1.28, 0.54], + [side * 0.38, -1.04, 0.80], + [side * 0.38, -0.78, 0.74], + ], + r_brace, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + + # Transverse rollcage crossbars & front tubular bullbar + for idx, (y_pos, z_pos, half_w) in enumerate([ + (-0.70, 0.82, 0.44), + (-0.14, 1.44, 0.39), + (0.44, 1.44, 0.39), + (0.54, 0.78, 0.46), + (1.38, 0.82, 0.42), + (1.38, 0.56, 0.42), + ]): + vc.make_swept_tube( + f"cage_cross_{idx}", + [[-half_w, y_pos, z_pos], [half_w, y_pos, z_pos]], + r_brace, + segments=8, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.0, + ) + + # Front stinger bullbar + twin headlights + vc.make_swept_tube( + "front_bullbar", + [ + [-0.32, -1.40, 0.48], + [-0.24, -1.64, 0.56], + [-0.16, -1.68, 0.68], + [0.16, -1.68, 0.68], + [0.24, -1.64, 0.56], + [0.32, -1.40, 0.48], + ], + r_main, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + for side in (-1.0, 1.0): + vc.make_tube_part( + f"headlight_{'L' if side > 0 else 'R'}", + r0=0.045, + r1=0.055, + length=0.08, + segments=12, + mat_name="gunmetal", + parent=chassis, + location=(side * 0.28, -1.46, 0.66), + rotation_deg=(90.0, 0.0, 0.0), + ) + + # --- 3. Hard Armour Plates (Brokkr plate.v0) --- + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "jackal_side", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.47, -0.05, 0.58], + "normal": [1.0, 0.0, 0.14], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.58, -0.16], [0.58, -0.14], [0.68, 0.16], [-0.42, 0.22]], + "thick": 0.04, + "taper": 0.015, + "back": 0.92, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.04, + "lifts": [0.008, 0.012], + "inset": 0.04, + "gap": 0.015, + "split": 0.55, + "seed": 401, + "bolt_r": 0.012, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.26, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + { + "name": "jackal_hood", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "one", + "mirror": False, + "slab": { + "at": [0.0, -0.98, 0.73], + "normal": [0.0, -0.32, 0.95], + "up": [0.0, -0.95, -0.32], + "right": [1.0, 0.0, 0.0], + "outline": [[-0.28, 0.30], [0.28, 0.30], [0.38, -0.28], [-0.38, -0.28]], + "thick": 0.045, + "taper": 0.018, + "back": 0.90, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.05, + "lifts": [0.008, 0.014], + "inset": 0.04, + "gap": 0.014, + "split": 0.60, + "seed": 402, + "bolt_r": 0.012, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.24, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + { + "name": "jackal_roof", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "one", + "mirror": False, + "slab": { + "at": [0.0, 0.14, 1.455], + "normal": [0.0, 0.0, 1.0], + "up": [0.0, -1.0, 0.0], + "right": [1.0, 0.0, 0.0], + "outline": {"w": 0.74, "h": 0.62, "clip": 0.08}, + "thick": 0.036, + "taper": 0.012, + "back": 0.94, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.22, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # --- 4. Cockpit Seats & Firewall --- + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"seat_base_{tag}", (0.32, 0.34, 0.08), "rubber_dark", parent=chassis, location=(side * 0.20, 0.08, 0.42), bevel=0.01) + vc.make_box(f"seat_back_{tag}", (0.30, 0.08, 0.48), "rubber_dark", parent=chassis, location=(side * 0.20, 0.24, 0.68), rotation_deg=(14.0, 0.0, 0.0), bevel=0.01) + vc.make_box("rear_firewall", (0.76, 0.04, 0.42), "gunmetal", parent=chassis, location=(0.0, 0.46, 0.60), bevel=0.005) + vc.make_swept_tube("steer_col", [[0.18, -0.58, 0.80], [0.18, -0.34, 0.92]], 0.018, segments=8, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + + # --- 5. Double-Wishbone Suspension, Coilovers & 4 Knobby Wheels --- + joints_manifest: list[dict] = [] + + for is_front, y_ax, prefix in [(True, front_y, "f"), (False, rear_y, "r")]: + for side, s_tag in [(1.0, "l"), (-1.0, "r")]: + j_suffix = f"{prefix}{s_tag}" + in_x = side * 0.24 + out_x = side * 0.68 + # Upper & lower A-arms (two separate wishbone legs meeting at the ball joint) + for leg_tag, dy in (("a", -0.16), ("b", 0.16)): + vc.make_swept_tube( + f"wishbone_lo_{j_suffix}_{leg_tag}", + [[in_x, y_ax + dy, 0.36], [out_x, y_ax, axle_z - 0.06]], + 0.018, + segments=6, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.0, + ) + for leg_tag, dy in (("a", -0.14), ("b", 0.14)): + vc.make_swept_tube( + f"wishbone_hi_{j_suffix}_{leg_tag}", + [[in_x, y_ax + dy, 0.52], [out_x, y_ax, axle_z + 0.08]], + 0.016, + segments=6, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.0, + ) + # Coilover shock strut from knuckle up to shock tower + tower_z = 0.80 if is_front else 0.86 + tower_y = y_ax + (0.04 if is_front else -0.06) + vc.make_ram_span( + f"coilover_{j_suffix}", + [side * 0.40, tower_y, tower_z], + [side * 0.62, y_ax, axle_z - 0.02], + body_r=0.028, + rod_r=0.016, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="gunmetal", + coil_rings=6, + ) + + # Steering knuckle (front only) + wheel hub spin joint + knuckle_loc = (side * track_x, y_ax, axle_z) + if is_front: + steer_id = f"joint.steer_{j_suffix}" + steer_node = vc.make_empty(steer_id, parent=chassis, location=(side * 0.68, y_ax, axle_z)) + vc.tag_joint(steer_node, steer_id, [0.0, 1.0, 0.0], -32.0, 32.0) + joints_manifest.append({"id": steer_id, "axis": [0.0, 1.0, 0.0], "min": -32.0, "max": 32.0}) + vc.make_box(f"knuckle_{j_suffix}", (0.08, 0.11, 0.18), "gunmetal", parent=steer_node, bevel=0.005) + wheel_parent = steer_node + wheel_loc = (side * (track_x - 0.68), 0.0, 0.0) + else: + vc.make_box(f"hub_carrier_{j_suffix}", (0.10, 0.12, 0.18), "gunmetal", parent=chassis, location=(side * 0.68, y_ax, axle_z), bevel=0.005) + wheel_parent = chassis + wheel_loc = knuckle_loc + + wheel_id = f"joint.wheel_{j_suffix}" + wheel_pivot = vc.make_knobby_wheel( + wheel_id, + radius=wheel_r, + width=wheel_w, + parent=wheel_parent, + location=wheel_loc, + tread_lugs=16, + rim_segments=18, + side_sign=int(side), + ) + wheel_pivot.name = wheel_id + vc.tag_joint(wheel_pivot, wheel_id, [1.0, 0.0, 0.0], -360.0, 360.0) + joints_manifest.append({"id": wheel_id, "axis": [1.0, 0.0, 0.0], "min": -360.0, "max": 360.0}) + + # --- 6. Visible Exterior Hardpoint Slots --- + # 1) Roof weapon collar ring + vc.add_hardpoint_slot( + "hp.weapon.roof", + "weapon", + parent=chassis, + location=(0.0, 0.14, 1.47), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.62, 0.62, 0.10), + ) + # 2) Open rear engine bay frame + mounting tray + twin exhaust sweeps + vc.make_box("rear_engine_tray", (0.64, 0.74, 0.06), "gunmetal", parent=chassis, location=(0.0, 0.90, 0.51), bevel=0.006) + vc.add_hardpoint_slot( + "hp.engine.rear", + "engine", + parent=chassis, + location=(0.0, 0.90, 0.53), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.62, 0.72, 0.16), + ) + for side in (-1.0, 1.0): + vc.make_swept_tube( + f"exhaust_{'L' if side > 0 else 'R'}", + [ + [side * 0.24, 0.78, 0.68], + [side * 0.36, 1.12, 0.66], + [side * 0.38, 1.48, 0.74], + ], + 0.028, + segments=8, + mat_name="copper_rad", + parent=chassis, + ) + # 3) Upright rear copper radiator louver bay seated on rear cage shroud + vc.make_box("rear_rad_shroud", (0.60, 0.06, 0.36), "gunmetal", parent=chassis, location=(0.0, 1.36, 0.74), rotation_deg=(28.0, 0.0, 0.0), bevel=0.006) + vc.add_hardpoint_slot( + "hp.radiator.rear", + "radiator", + parent=chassis, + location=(0.0, 1.34, 0.75), + rotation_deg=(-62.0, 0.0, 0.0), + size=(0.58, 0.44, 0.11), + ) + vc.make_box("rad_header_tank", (0.58, 0.09, 0.08), "copper_rad", parent=chassis, location=(0.0, 1.44, 0.95), bevel=0.008) + + # --- 7. Export GLB, Manifest & 4-Panel Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "jackal" / "jackal.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "jackal" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "jackal_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="jackal", + name="Jackal", + vehicle_class="Light Wheeled Dune Buggy", + grid_width=3, + grid_height=4, + mask=[ + "###", + "###", + "###", + "###", + ], + hardpoints=[ + {"id": "hp.weapon.roof", "kind": "weapon", "x": 1, "y": 0, "w": 1, "h": 2, "modelNodeId": "hp.weapon.roof"}, + {"id": "hp.engine.rear", "kind": "engine", "x": 1, "y": 2, "w": 1, "h": 2, "modelNodeId": "hp.engine.rear"}, + {"id": "hp.radiator.rear", "kind": "radiator", "x": 2, "y": 3, "w": 1, "h": 1, "modelNodeId": "hp.radiator.rear"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[jackal] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "jackal", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_jackal() diff --git a/tools/vehicles/build_mammoth.py b/tools/vehicles/build_mammoth.py new file mode 100644 index 0000000..e4292ff --- /dev/null +++ b/tools/vehicles/build_mammoth.py @@ -0,0 +1,460 @@ +"""Build the Mammoth (Heavy 8x8 Armored Fire Support Rig) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def build_mammoth() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("MammothRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # Dimensions (Blender: -Y forward, +Z up, +X left) + axle_ys = [ + ("f1", -1.90, True), + ("f2", -0.74, True), + ("r1", 0.74, False), + ("r2", 1.90, False), + ] + track_x = 1.24 + wheel_r = 0.52 + wheel_w = 0.38 + axle_z = wheel_r + + # --- 1. Heavy Armored Lower Tub, Frame Rails, Axles & Suspension --- + vc.make_box("lower_tub", (1.64, 4.94, 0.62), "gunmetal", parent=chassis, location=(0.0, -0.02, 0.82), bevel=0.015) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"frame_rail_{tag}", (0.14, 5.10, 0.20), "gunmetal", parent=chassis, location=(side * 0.68, -0.04, 0.62), bevel=0.01) + # Side fuel tank / battery box tucked between front and rear tandem wheel pairs + vc.make_box(f"side_stowage_{tag}", (0.42, 0.72, 0.44), "olive_armor", parent=chassis, location=(side * 1.08, 0.0, 0.86), bevel=0.01) + # Crew entry door + boarding ladder step on mid-hull flank + vc.make_box(f"crew_step_{tag}", (0.16, 0.44, 0.06), "gunmetal", parent=chassis, location=(side * 1.32, 0.0, 0.62), bevel=0.006) + vc.make_box(f"crew_door_{tag}", (0.06, 0.56, 0.78), "olive_armor", parent=chassis, location=(side * 1.28, 0.0, 1.24), bevel=0.008) + + for idx, (a_tag, y_ax, _) in enumerate(axle_ys): + vc.make_tube_part( + f"axle_tube_{a_tag}", + 0.075, + 0.075, + track_x * 1.68, + segments=10, + mat_name="gunmetal", + parent=chassis, + location=(-track_x * 0.84, y_ax, axle_z), + rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_box(f"diff_{a_tag}", (0.34, 0.34, 0.28), "gunmetal", parent=chassis, location=(0.0, y_ax, axle_z), bevel=0.012) + for side in (-1.0, 1.0): + s_tag = "L" if side > 0 else "R" + vc.make_ram_span( + f"strut_{a_tag}_{s_tag}", + [side * 0.74, y_ax, 1.02], + [side * 0.98, y_ax, axle_z + 0.02], + body_r=0.040, + rod_r=0.022, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + coil_rings=0, + ) + + # --- 2. Faceted 8x8 Armored Hull & Bolted Sponson Plates (Brokkr plate.v0) --- + hull_pts = [ + # Lower hull belt above wheel arches (z = 1.14) + [-1.34, -2.26, 1.14], [1.34, -2.26, 1.14], + [-1.36, 2.26, 1.14], [1.36, 2.26, 1.14], + # Lower nose & lower tail bevel + [-1.08, -2.62, 1.02], [1.08, -2.62, 1.02], + [-1.12, 2.64, 1.12], [1.12, 2.64, 1.12], + # Roof deck (z = 1.66) + [-1.14, -1.78, 1.66], [1.14, -1.78, 1.66], + [-1.16, 1.88, 1.66], [1.16, 1.88, 1.66], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "mammoth_hull", + "mat": "olive_armor", + "bevel": 0.016, + "sides": "one", + "mirror": False, + "points": hull_pts, + "clad": { + "mat": "olive_armor", + "facets": [{"n": [0.0, -0.55, 0.83], "cos": 0.85}, {"n": [0.0, 0.0, 1.0], "cos": 0.95}], + "min_area": 0.18, + "lifts": [0.008, 0.014], + "inset": 0.06, + "gap": 0.018, + "split": 0.88, + "seed": 801, + "bolt_r": 0.014, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + }, + # Sloped upper side cheek armor with bolted applique panels + { + "name": "mammoth_side_cheek", + "mat": "olive_armor", + "bevel": 0.010, + "sides": "both", + "mirror": False, + "slab": { + "at": [1.26, -0.04, 1.40], + "normal": [0.92, 0.0, 0.38], + "up": [-0.38, 0.0, 0.92], + "right": [0.0, -1.0, 0.0], + "outline": [[-1.92, -0.24], [1.92, -0.24], [1.72, 0.24], [-1.72, 0.24]], + "thick": 0.055, + "taper": 0.015, + "back": 0.92, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.14, + "lifts": [0.008, 0.014], + "inset": 0.05, + "gap": 0.016, + "split": 0.72, + "seed": 802, + "bolt_r": 0.013, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "bolts", "inset": 0.025, "spacing": 0.36, "mat": "gunmetal", "params": "r=0.013"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Heavy flared wheel arches over all 4 wheel stations on each side + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + for a_tag, y_ax, _ in axle_ys: + # Top arch cap + angled front/rear lip flaps + vc.make_box(f"arch_top_{tag}_{a_tag}", (0.44, 0.68, 0.07), "olive_armor", parent=chassis, location=(side * 1.24, y_ax, 1.14), bevel=0.008) + vc.make_box(f"arch_f_{tag}_{a_tag}", (0.44, 0.32, 0.07), "olive_armor", parent=chassis, location=(side * 1.24, y_ax - 0.44, 1.02), rotation_deg=(36.0, 0.0, 0.0), bevel=0.008) + vc.make_box(f"arch_r_{tag}_{a_tag}", (0.44, 0.32, 0.07), "olive_armor", parent=chassis, location=(side * 1.24, y_ax + 0.44, 1.02), rotation_deg=(-36.0, 0.0, 0.0), bevel=0.008) + + # Front nose recessed grille, armored headlights, driver slit & rearview mirrors + vc.make_box("front_grille", (1.22, 0.14, 0.34), "socket_bay", parent=chassis, location=(0.0, -2.58, 0.96), bevel=0.008) + for k in range(4): + vc.make_box(f"grille_slat_{k}", (1.16, 0.06, 0.03), "gunmetal", parent=chassis, location=(0.0, -2.64, 0.86 + k * 0.07), bevel=0.003) + vc.make_box("driver_periscope", (0.56, 0.16, 0.10), "smoked_glass", parent=chassis, location=(-0.38, -1.96, 1.60), rotation_deg=(-22.0, 0.0, 0.0), bevel=0.005) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"headlight_box_{tag}", (0.24, 0.16, 0.16), "gunmetal", parent=chassis, location=(side * 0.88, -2.54, 1.06), bevel=0.008) + vc.make_box(f"headlight_lens_{tag}", (0.16, 0.04, 0.09), "smoked_glass", parent=chassis, location=(side * 0.88, -2.62, 1.06), bevel=0.003) + vc.make_box(f"tow_shackle_{tag}", (0.08, 0.14, 0.14), "signal_orange", parent=chassis, location=(side * 0.48, -2.66, 0.72), bevel=0.006) + # Rear corner tail light housing + vc.make_box(f"taillight_{tag}", (0.18, 0.12, 0.14), "gunmetal", parent=chassis, location=(side * 1.04, 2.58, 1.12), bevel=0.006) + + # --- 3. Reinforced Front Dozer Ram Plow --- + plow_root = vc.make_empty("dozer_plow", parent=chassis, location=(0.0, -2.86, 0.56)) + def build_plow_blade(bm: bmesh.types.BMesh) -> None: + # Curved multi-segment scoop profile extruded across width X = [-1.34, +1.34] + prof = [ + (-0.34, -0.34), # bottom cutting lip + (-0.22, -0.14), + (-0.04, 0.06), + (0.02, 0.26), + (-0.14, 0.42), # upper curved spill lip + (0.04, 0.42), + (0.14, 0.22), + (0.08, -0.12), + (-0.18, -0.34), + ] + hw = 1.34 + verts_l = [bm.verts.new((hw, y, z)) for (y, z) in prof] + verts_r = [bm.verts.new((-hw, y, z)) for (y, z) in prof] + n = len(prof) + for i in range(n): + j = (i + 1) % n + bm.faces.new([verts_l[i], verts_l[j], verts_r[j], verts_r[i]]) + bm.faces.new(verts_l) + bm.faces.new(list(reversed(verts_r))) + + vc.make_bmesh_object("plow_moldboard", build_plow_blade, "olive_armor", parent=plow_root, bevel=0.012) + vc.make_box("plow_cutting_edge", (2.72, 0.16, 0.07), "gunmetal", parent=plow_root, location=(0.0, -0.28, -0.32), rotation_deg=(16.0, 0.0, 0.0), bevel=0.006) + for gx in (-0.98, -0.48, 0.0, 0.48, 0.98): + vc.make_box(f"plow_rib_{gx:.2f}", (0.07, 0.18, 0.62), "gunmetal", parent=plow_root, location=(gx, 0.12, 0.06), bevel=0.006) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"plow_wing_{tag}", (0.12, 0.48, 0.68), "olive_armor", parent=plow_root, location=(side * 1.36, -0.10, 0.04), bevel=0.008) + # Hydraulic push arms + tilt rams + vc.make_box(f"plow_pusharm_{tag}", (0.12, 0.72, 0.14), "gunmetal", parent=chassis, location=(side * 0.66, -2.56, 0.56), bevel=0.008) + vc.make_ram_span( + f"plow_ram_{tag}", + [side * 0.66, -2.42, 0.90], + [side * 0.66, -2.80, 0.76], + body_r=0.042, + rod_r=0.024, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + + # --- 4. Rear Diesel Exhaust Stacks --- + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_swept_tube( + f"exhaust_stack_{tag}", + [ + [side * 1.02, 2.24, 1.36], + [side * 1.06, 2.46, 1.56], + [side * 1.06, 2.46, 2.18], + [side * 1.06, 2.60, 2.30], + ], + 0.062, + segments=12, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.06, + ) + vc.make_tube_part( + f"exhaust_shield_{tag}", + 0.09, + 0.09, + 0.52, + segments=10, + inner0=0.078, + inner1=0.078, + mat_name="copper_rad", + parent=chassis, + location=(side * 1.06, 2.46, 1.62), + ) + + # --- 5. 8x8 Wheels & Front 4 Steering Knuckles --- + joints_manifest: list[dict] = [] + for a_tag, y_ax, steerable in axle_ys: + for side, s_tag in ((1.0, "l"), (-1.0, "r")): + j_suffix = f"{a_tag[0]}{s_tag}{a_tag[1]}" # fl1, fr1, fl2, fr2, rl1, rr1, rl2, rr2 + if steerable: + steer_id = f"joint.steer_{j_suffix}" + steer_node = vc.make_empty(steer_id, parent=chassis, location=(side * 0.98, y_ax, axle_z)) + vc.tag_joint(steer_node, steer_id, [0.0, 1.0, 0.0], -28.0, 28.0) + joints_manifest.append({"id": steer_id, "axis": [0.0, 1.0, 0.0], "min": -28.0, "max": 28.0}) + vc.make_box(f"knuckle_{j_suffix}", (0.10, 0.14, 0.22), "gunmetal", parent=steer_node, bevel=0.006) + wheel_parent = steer_node + wheel_loc = (side * (track_x - 0.98), 0.0, 0.0) + else: + vc.make_box(f"hub_carrier_{j_suffix}", (0.12, 0.16, 0.22), "gunmetal", parent=chassis, location=(side * 0.98, y_ax, axle_z), bevel=0.006) + wheel_parent = chassis + wheel_loc = (side * track_x, y_ax, axle_z) + + wheel_id = f"joint.wheel_{j_suffix}" + wheel_pivot = vc.make_knobby_wheel( + wheel_id, + radius=wheel_r, + width=wheel_w, + parent=wheel_parent, + location=wheel_loc, + tread_lugs=14, + rim_segments=16, + side_sign=int(side), + ) + wheel_pivot.name = wheel_id + vc.tag_joint(wheel_pivot, wheel_id, [1.0, 0.0, 0.0], -360.0, 360.0) + joints_manifest.append({"id": wheel_id, "axis": [1.0, 0.0, 0.0], "min": -360.0, "max": 360.0}) + + # --- 6. Broad Angular Central Turret (joint.turret_yaw) --- + turret_pivot = vc.make_empty("joint.turret_yaw", parent=chassis, location=(0.0, -0.18, 1.66)) + vc.tag_joint(turret_pivot, "joint.turret_yaw", [0.0, 1.0, 0.0], -180.0, 180.0) + joints_manifest.append({"id": "joint.turret_yaw", "axis": [0.0, 1.0, 0.0], "min": -180.0, "max": 180.0}) + + vc.make_tube_part("turret_race", 0.74, 0.80, 0.08, segments=24, mat_name="gunmetal", parent=turret_pivot) + turret_pts = [ + [-0.64, -0.78, 0.08], [0.64, -0.78, 0.08], + [0.84, -0.22, 0.08], [0.76, 0.94, 0.08], + [-0.76, 0.94, 0.08], [-0.84, -0.22, 0.08], + [-0.50, -0.60, 0.56], [0.50, -0.60, 0.56], + [0.64, -0.14, 0.56], [0.58, 0.78, 0.56], + [-0.58, 0.78, 0.56], [-0.64, -0.14, 0.56], + ] + turret_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "mammoth_turret_shell", + "mat": "olive_armor", + "bevel": 0.015, + "sides": "one", + "mirror": False, + "points": turret_pts, + }, + { + "name": "mammoth_turret_cheek", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.74, 0.14, 0.30], + "normal": [0.94, 0.0, 0.34], + "up": [-0.34, 0.0, 0.94], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.52, -0.16], [0.52, -0.16], [0.42, 0.16], [-0.42, 0.16]], + "thick": 0.045, + "taper": 0.012, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.24, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + ], + } + vc.make_plates(turret_doc, parent=turret_pivot) + + # Turret bustle stowage rack, commander hatch, optics & smoke launchers + vc.make_box("turret_bustle", (1.08, 0.42, 0.34), "gunmetal", parent=turret_pivot, location=(0.0, 0.98, 0.34), bevel=0.01) + vc.make_tube_part("commander_cupola", 0.22, 0.24, 0.10, segments=14, mat_name="olive_armor", parent=turret_pivot, location=(-0.28, 0.34, 0.56)) + vc.make_box("turret_sight", (0.20, 0.22, 0.14), "smoked_glass", parent=turret_pivot, location=(0.24, -0.38, 0.62), bevel=0.008) + vc.make_box("turret_mantlet_bar", (0.94, 0.18, 0.18), "gunmetal", parent=turret_pivot, location=(0.0, -0.70, 0.30), bevel=0.01) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + for k in range(3): + vc.make_tube_part( + f"smoke_tube_{tag}_{k}", + 0.032, + 0.032, + 0.18, + segments=8, + mat_name="gunmetal", + parent=turret_pivot, + location=(side * 0.78, 0.42 + k * 0.10, 0.34), + rotation_deg=(-58.0, 0.0, side * 22.0), + ) + + # --- 7. Visible Exterior Hardpoints (4x6 Dorsal Grid) --- + # 1) hp.armor.glacis (0,0, 4x1) + vc.add_hardpoint_slot( + "hp.armor.glacis", + "armor", + parent=chassis, + location=(0.0, -2.20, 1.36), + rotation_deg=(53.0, 0.0, 0.0), + size=(1.54, 0.38, 0.10), + plinth_depth=0.03, + ) + # 2) hp.weapon.bow (0,1, 1x1) on front-left bow deck + vc.make_box("bow_weapon_plinth", (0.48, 0.50, 0.12), "gunmetal", parent=chassis, location=(0.88, -1.48, 1.62), bevel=0.008) + vc.add_hardpoint_slot( + "hp.weapon.bow", + "weapon", + parent=chassis, + location=(0.88, -1.48, 1.68), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.46, 0.46, 0.09), + ) + # 3) hp.weapon.turret_l (1,1, 1x2) & 4) hp.weapon.turret_r (2,1, 1x2) on turret roof + vc.add_hardpoint_slot( + "hp.weapon.turret_l", + "weapon", + parent=turret_pivot, + location=(0.36, -0.10, 0.57), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.56, 0.56, 0.10), + ) + vc.add_hardpoint_slot( + "hp.weapon.turret_r", + "weapon", + parent=turret_pivot, + location=(-0.36, -0.10, 0.57), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.56, 0.56, 0.10), + ) + # 5) hp.armor.flanks (3,1, 1x2) on right (-X) upper cheek + vc.add_hardpoint_slot( + "hp.armor.flanks", + "armor", + parent=chassis, + location=(-1.32, -0.16, 1.38), + rotation_deg=(90.0, 0.0, -90.0), + size=(1.12, 0.32, 0.10), + ) + # 6) hp.engine.rear (1,3, 2x2) + vc.add_hardpoint_slot( + "hp.engine.rear", + "engine", + parent=chassis, + location=(0.0, 1.34, 1.66), + rotation_deg=(0.0, 0.0, 0.0), + size=(1.14, 1.04, 0.14), + ) + # 7 & 8) hp.radiator.l (0,4, 1x2) & hp.radiator.r (3,4, 1x2) + vc.add_hardpoint_slot( + "hp.radiator.l", + "radiator", + parent=chassis, + location=(1.28, 1.40, 1.38), + rotation_deg=(90.0, 0.0, 90.0), + size=(0.98, 0.44, 0.12), + ) + vc.add_hardpoint_slot( + "hp.radiator.r", + "radiator", + parent=chassis, + location=(-1.28, 1.40, 1.38), + rotation_deg=(90.0, 0.0, -90.0), + size=(0.98, 0.44, 0.12), + ) + + # --- 8. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "mammoth" / "mammoth.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "mammoth" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "mammoth_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="mammoth", + name="Mammoth", + vehicle_class="Heavy 8x8 Armored Fire Support Rig", + grid_width=4, + grid_height=6, + mask=[ + "####", + "####", + "####", + "####", + "####", + "####", + ], + hardpoints=[ + {"id": "hp.armor.glacis", "kind": "armor", "x": 0, "y": 0, "w": 4, "h": 1, "modelNodeId": "hp.armor.glacis"}, + {"id": "hp.weapon.bow", "kind": "weapon", "x": 0, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.weapon.bow"}, + {"id": "hp.weapon.turret_l", "kind": "weapon", "x": 1, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.turret_l"}, + {"id": "hp.weapon.turret_r", "kind": "weapon", "x": 2, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.turret_r"}, + {"id": "hp.armor.flanks", "kind": "armor", "x": 3, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.armor.flanks"}, + {"id": "hp.engine.rear", "kind": "engine", "x": 1, "y": 3, "w": 2, "h": 2, "modelNodeId": "hp.engine.rear"}, + {"id": "hp.radiator.l", "kind": "radiator", "x": 0, "y": 4, "w": 1, "h": 2, "modelNodeId": "hp.radiator.l"}, + {"id": "hp.radiator.r", "kind": "radiator", "x": 3, "y": 4, "w": 1, "h": 2, "modelNodeId": "hp.radiator.r"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[mammoth] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "mammoth", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_mammoth() diff --git a/tools/vehicles/build_mule.py b/tools/vehicles/build_mule.py new file mode 100644 index 0000000..b5223dd --- /dev/null +++ b/tools/vehicles/build_mule.py @@ -0,0 +1,299 @@ +"""Build the Mule (Medium 6x6 Armored Gun Truck) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def build_mule() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("MuleRoot") + chassis = vc.make_empty("Chassis", parent=root) + + front_y = -1.52 + mid_y = 0.88 + rear_y = 1.92 + track_x = 0.98 + wheel_r = 0.49 + wheel_w = 0.34 + axle_z = wheel_r + + # --- 1. Ladder Frame Rails, Axles, Bumper & Fuel Tanks --- + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"frame_rail_{tag}", (0.12, 4.54, 0.18), "gunmetal", parent=chassis, location=(side * 0.46, 0.0, 0.62), bevel=0.008) + # Side cylindrical fuel tanks (Brokkr mechanical kit tank) + vc.make_kit_part( + f"fuel_tank_{tag}", + "mechanical", + "tank", + {"radius": 0.19, "length": 0.86, "segments": 14}, + mat_name="gunmetal", + parent=chassis, + location=(side * 0.78, -0.35, 0.56), + rotation_deg=(90.0, 0.0, 0.0), + ) + + for idx, y_ax in enumerate((front_y, mid_y, rear_y)): + vc.make_tube_part( + f"axle_tube_{idx}", + 0.065, + 0.065, + track_x * 1.66, + segments=10, + mat_name="gunmetal", + parent=chassis, + location=(-track_x * 0.83, y_ax, axle_z), + rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_box(f"diff_{idx}", (0.28, 0.28, 0.24), "gunmetal", parent=chassis, location=(0.0, y_ax, axle_z), bevel=0.01) + + # Heavy front steel bumper + tow shackles + vc.make_box("front_bumper", (2.16, 0.24, 0.24), "gunmetal", parent=chassis, location=(0.0, -2.26, 0.66), bevel=0.014) + for side in (-1.0, 1.0): + vc.make_box(f"bumper_shackle_{'L' if side > 0 else 'R'}", (0.07, 0.12, 0.14), "signal_orange", parent=chassis, location=(side * 0.52, -2.40, 0.62), bevel=0.006) + vc.make_box(f"headlight_box_{'L' if side > 0 else 'R'}", (0.16, 0.12, 0.14), "gunmetal", parent=chassis, location=(side * 0.78, -2.18, 0.92), bevel=0.008) + + # --- 2. Armored Hood & Sloped Armored Cab (Brokkr plate.v0 + faceted cab) --- + # Hood core + front grille frame + vc.make_box("hood_core", (1.36, 1.06, 0.60), "olive_armor", parent=chassis, location=(0.0, -1.66, 1.04), bevel=0.015) + vc.make_box("cab_lower", (1.84, 1.18, 0.68), "olive_armor", parent=chassis, location=(0.0, -0.54, 1.06), bevel=0.015) + + # Sloped upper armored cab via plate.v0 convex hull ("faces" / "points") + cab_pts = [ + [-0.90, -1.12, 1.34], [0.90, -1.12, 1.34], + [0.90, 0.04, 1.34], [-0.90, 0.04, 1.34], + [-0.78, -0.82, 2.02], [0.78, -0.82, 2.02], + [0.80, 0.02, 2.02], [-0.80, 0.02, 2.02], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "mule_cab_upper", + "mat": "olive_armor", + "bevel": 0.016, + "sides": "one", + "mirror": False, + "points": cab_pts, + }, + # Flared front wheel fenders + { + "name": "mule_fender_front", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.92, -1.52, 1.08], + "normal": [0.18, 0.0, 0.98], + "up": [0.0, -1.0, 0.0], + "right": [0.98, 0.0, -0.18], + "outline": [[-0.24, 0.54], [0.24, 0.54], [0.24, -0.54], [-0.24, -0.54]], + "thick": 0.06, + "taper": 0.015, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.28, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + # Armored cab doors with stepped clad panels + { + "name": "mule_door", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.93, -0.54, 1.18], + "normal": [1.0, 0.0, 0.0], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.44, -0.34], [0.44, -0.34], [0.40, 0.36], [-0.44, 0.36]], + "thick": 0.04, + "taper": 0.012, + "back": 0.94, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.06, + "lifts": [0.008, 0.012], + "inset": 0.04, + "gap": 0.014, + "split": 0.65, + "seed": 501, + "bolt_r": 0.012, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "part", "part": "handle", "at": [0.24, -0.04], "roll": 0.0, "mat": "gunmetal", "params": "length=0.20;lift=0.045;r=0.012"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Armored smoked glass windshield slit & side viewports + vc.make_box("windshield_slit", (1.28, 0.08, 0.16), "smoked_glass", parent=chassis, location=(0.0, -0.98, 1.68), rotation_deg=(-22.0, 0.0, 0.0), bevel=0.004) + for side in (-1.0, 1.0): + vc.make_box(f"side_glass_{'L' if side > 0 else 'R'}", (0.06, 0.46, 0.22), "smoked_glass", parent=chassis, location=(side * 0.86, -0.46, 1.66), rotation_deg=(0.0, side * -12.0, 0.0), bevel=0.004) + + # --- 3. Open Armored Cargo Bed + Rear Mudguards --- + vc.make_box("bed_floor", (2.06, 2.26, 0.12), "gunmetal", parent=chassis, location=(0.0, 1.24, 0.92), bevel=0.01) + # Bed side walls (stepped armor with ribs & tubular top grab rail) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"bed_wall_{tag}", (0.10, 2.22, 0.68), "olive_armor", parent=chassis, location=(side * 0.98, 1.24, 1.32), bevel=0.01) + for ry in (0.35, 0.95, 1.55, 2.15): + vc.make_box(f"bed_rib_{tag}_{ry:.2f}", (0.05, 0.08, 0.64), "olive_armor", parent=chassis, location=(side * 1.04, ry, 1.32), bevel=0.004) + vc.make_swept_tube( + f"bed_rail_{tag}", + [[side * 0.98, 0.16, 1.68], [side * 0.98, 0.16, 1.82], [side * 0.98, 2.32, 1.82], [side * 0.98, 2.32, 1.68]], + 0.022, + segments=8, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.03, + ) + # Rear tandem fender flare + vc.make_box(f"rear_fender_{tag}", (0.38, 1.98, 0.08), "olive_armor", parent=chassis, location=(side * 0.94, 1.40, 1.06), bevel=0.008) + + # Tailgate + vc.make_box("bed_tailgate", (1.92, 0.10, 0.62), "olive_armor", parent=chassis, location=(0.0, 2.32, 1.29), bevel=0.01) + # Central turret pedestal drum in cargo bed + vc.make_tube_part("bed_pedestal", 0.44, 0.48, 0.58, segments=16, mat_name="gunmetal", parent=chassis, location=(0.0, 1.36, 0.98)) + + # --- 4. 6x6 Off-Road Wheels & Front Steering Knuckles --- + joints_manifest: list[dict] = [] + for axle_tag, y_ax, steerable in (("f", front_y, True), ("m", mid_y, False), ("r", rear_y, False)): + for side, s_tag in ((1.0, "l"), (-1.0, "r")): + j_suffix = f"{axle_tag}{s_tag}" + if steerable: + steer_id = f"joint.steer_{j_suffix}" + steer_node = vc.make_empty(steer_id, parent=chassis, location=(side * 0.80, y_ax, axle_z)) + vc.tag_joint(steer_node, steer_id, [0.0, 1.0, 0.0], -30.0, 30.0) + joints_manifest.append({"id": steer_id, "axis": [0.0, 1.0, 0.0], "min": -30.0, "max": 30.0}) + wheel_parent = steer_node + wheel_loc = (side * (track_x - 0.80), 0.0, 0.0) + else: + wheel_parent = chassis + wheel_loc = (side * track_x, y_ax, axle_z) + + wheel_id = f"joint.wheel_{j_suffix}" + wheel_pivot = vc.make_knobby_wheel( + wheel_id, + radius=wheel_r, + width=wheel_w, + parent=wheel_parent, + location=wheel_loc, + tread_lugs=16, + rim_segments=18, + side_sign=int(side), + ) + wheel_pivot.name = wheel_id + vc.tag_joint(wheel_pivot, wheel_id, [1.0, 0.0, 0.0], -360.0, 360.0) + joints_manifest.append({"id": wheel_id, "axis": [1.0, 0.0, 0.0], "min": -360.0, "max": 360.0}) + + # --- 5. Visible Exterior Hardpoints (3x5 Dorsal Grid) --- + # Front bumper/grille armor rail + vc.add_hardpoint_slot( + "hp.armor.front", + "armor", + parent=chassis, + location=(0.0, -2.18, 1.00), + rotation_deg=(90.0, 0.0, 0.0), + size=(1.32, 0.36, 0.09), + plinth_depth=0.03, + ) + # Hood engine bay frame + vc.add_hardpoint_slot( + "hp.engine.front", + "engine", + parent=chassis, + location=(0.0, -1.66, 1.32), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.88, 0.86, 0.14), + ) + # Cab roof weapon pintle ring + vc.add_hardpoint_slot( + "hp.weapon.cab", + "weapon", + parent=chassis, + location=(0.0, -0.44, 2.02), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.56, 0.56, 0.09), + ) + # Main cargo-bed turret ring + vc.add_hardpoint_slot( + "hp.weapon.bed_main", + "weapon", + parent=chassis, + location=(0.0, 1.36, 1.56), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.98, 0.98, 0.12), + ) + # Twin flank radiator louver pods behind cab (horizontal louvers: local +Y = +Z up) + vc.add_hardpoint_slot( + "hp.radiator.left", + "radiator", + parent=chassis, + location=(1.04, 0.56, 1.40), + rotation_deg=(90.0, 0.0, 90.0), + size=(0.78, 0.72, 0.14), + ) + vc.add_hardpoint_slot( + "hp.radiator.right", + "radiator", + parent=chassis, + location=(-1.04, 0.56, 1.40), + rotation_deg=(90.0, 0.0, -90.0), + size=(0.78, 0.72, 0.14), + ) + + # --- 6. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "mule" / "mule.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "mule" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "mule_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="mule", + name="Mule", + vehicle_class="Medium 6x6 Armored Gun Truck", + grid_width=3, + grid_height=5, + mask=[ + "###", + "###", + "###", + "###", + "###", + ], + hardpoints=[ + {"id": "hp.armor.front", "kind": "armor", "x": 0, "y": 0, "w": 3, "h": 1, "modelNodeId": "hp.armor.front"}, + {"id": "hp.radiator.left", "kind": "radiator", "x": 0, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.radiator.left"}, + {"id": "hp.engine.front", "kind": "engine", "x": 1, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.engine.front"}, + {"id": "hp.radiator.right", "kind": "radiator", "x": 2, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.radiator.right"}, + {"id": "hp.weapon.cab", "kind": "weapon", "x": 0, "y": 3, "w": 1, "h": 1, "modelNodeId": "hp.weapon.cab"}, + {"id": "hp.weapon.bed_main", "kind": "weapon", "x": 1, "y": 3, "w": 2, "h": 2, "modelNodeId": "hp.weapon.bed_main"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[mule] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "mule", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_mule() diff --git a/tools/vehicles/build_weapon_parts.py b/tools/vehicles/build_weapon_parts.py new file mode 100644 index 0000000..0cbf0ec --- /dev/null +++ b/tools/vehicles/build_weapon_parts.py @@ -0,0 +1,353 @@ +"""Build the 16 modular Brokkr procedural weapon sub-parts into assets/gear/parts/*.glb.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path +from typing import Any + +import bmesh +import bpy +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 +import bake_vertex_weathering as bvw # noqa: E402 + +PARTS_DIR = vc.ASSETS_GEAR_DIR / "parts" + +WEAPON_PART_PALETTE: dict[str, dict[str, Any]] = { + "mfg_primary": {"hex": "#4e5740", "metallic": 0.35, "roughness": 0.50}, + "mfg_accent": {"hex": "#e8621a", "metallic": 0.38, "roughness": 0.40}, + "mfg_glow": {"hex": "#38e8ff", "metallic": 0.18, "roughness": 0.24, "emission": "#38e8ff", "emission_strength": 1.85}, +} + + +def ensure_weapon_part_materials() -> None: + vc.ensure_materials() + for name, spec in WEAPON_PART_PALETTE.items(): + mat = bpy.data.materials.get(name) + if mat is None: + mat = bpy.data.materials.new(name=name) + mat.use_nodes = True + nt = mat.node_tree + nt.nodes.clear() + out = nt.nodes.new("ShaderNodeOutputMaterial") + bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") + nt.links.new(bsdf.outputs["BSDF"], out.inputs["Surface"]) + bsdf.inputs["Base Color"].default_value = vc.srgb_hex_to_linear(spec["hex"]) + bsdf.inputs["Metallic"].default_value = float(spec["metallic"]) + bsdf.inputs["Roughness"].default_value = float(spec["roughness"]) + if "emission" in spec: + bsdf.inputs["Emission Color"].default_value = vc.srgb_hex_to_linear(spec["emission"]) + bsdf.inputs["Emission Strength"].default_value = float(spec.get("emission_strength", 1.0)) + + +def _make_socket(name: str, socket_tag: str, parent: bpy.types.Object, location: tuple[float, float, float]) -> bpy.types.Object: + emp = vc.make_empty(name, parent=parent, location=location, display_size=0.06) + emp["rtd.socket"] = socket_tag + return emp + + +def _export_part(name: str, slot: str, root: bpy.types.Object, ground: bool) -> None: + root["rtd.part_slot"] = slot + glb_path = PARTS_DIR / f"{name}.glb" + tris, bounds = vc.export_vehicle_glb(glb_path, root=root if ground else None) + stats = bvw.bake_glb(glb_path) + print(f"[weapon_part:{slot}:{name}] tris={tris} bounds={bounds} ao_min={stats['ao_min']:.2f} bytes={glb_path.stat().st_size}") + + +# --------------------------------------------------------------------------- +# 4 RECEIVERS (grounded at minY = 0, forward = -Y_blender = +Z_gltf) +# --------------------------------------------------------------------------- + +def build_rx_salvage_frame() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_tube_part("pintle_base", 0.16, 0.14, 0.06, segments=12, mat_name="gunmetal", parent=root) + vc.make_box("cradle_yoke", (0.20, 0.24, 0.14), "gunmetal", parent=root, location=(0.0, 0.02, 0.12), bevel=0.006) + vc.make_box("receiver_hull", (0.18, 0.44, 0.16), "mfg_primary", parent=root, location=(0.0, -0.02, 0.22), bevel=0.008) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"cheek_plate_{tag}", (0.04, 0.30, 0.11), "mfg_accent", parent=root, location=(side * 0.105, -0.04, 0.23), bevel=0.005) + vc.make_tube_part(f"rear_grip_{tag}", 0.013, 0.013, 0.11, segments=8, mat_name="rubber_dark", parent=root, location=(side * 0.065, 0.22, 0.18)) + vc.make_box("status_lamp", (0.06, 0.08, 0.03), "mfg_glow", parent=root, location=(0.0, 0.06, 0.31), bevel=0.003) + _make_socket("socket.barrel", "barrel", root, (0.0, -0.24, 0.22)) + _make_socket("socket.feed", "feed", root, (0.125, 0.02, 0.22)) + _export_part("rx_salvage_frame", "receiver", root, ground=True) + + +def build_rx_korrathi_cradle() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_tube_part("turret_collar", 0.24, 0.21, 0.07, segments=8, smooth=False, mat_name="gunmetal", parent=root) + vc.make_box("armored_breech", (0.30, 0.48, 0.22), "mfg_primary", parent=root, location=(0.0, 0.0, 0.18), bevel=0.012) + vc.make_box("brow_visor", (0.26, 0.34, 0.06), "mfg_accent", parent=root, location=(0.0, -0.06, 0.31), bevel=0.006) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_tube_part(f"recoil_piston_{tag}", 0.028, 0.028, 0.34, segments=10, mat_name="copper_rad", parent=root, location=(side * 0.11, 0.16, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_box(f"side_rib_{tag}", (0.045, 0.28, 0.12), "gunmetal", parent=root, location=(side * 0.165, -0.02, 0.18), bevel=0.005) + vc.make_box("charge_strip", (0.14, 0.18, 0.025), "mfg_glow", parent=root, location=(0.0, -0.10, 0.345), bevel=0.003) + _make_socket("socket.barrel", "barrel", root, (0.0, -0.24, 0.20)) + _make_socket("socket.feed", "feed", root, (0.185, 0.02, 0.19)) + _export_part("rx_korrathi_cradle", "receiver", root, ground=True) + + +def build_rx_auralian_prism() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_tube_part("gimbal_base", 0.21, 0.17, 0.075, segments=16, mat_name="mfg_accent", parent=root) + vc.make_box("condenser_shroud", (0.24, 0.50, 0.20), "mfg_primary", parent=root, location=(0.0, 0.0, 0.175), bevel=0.015) + vc.make_box("dorsal_crest", (0.09, 0.40, 0.075), "mfg_accent", parent=root, location=(0.0, 0.02, 0.30), bevel=0.008) + vc.make_box("optic_spine", (0.036, 0.32, 0.032), "mfg_glow", parent=root, location=(0.0, 0.0, 0.345), bevel=0.004) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"side_vent_{tag}", (0.03, 0.26, 0.06), "mfg_glow", parent=root, location=(side * 0.125, -0.02, 0.18), bevel=0.003) + _make_socket("socket.barrel", "barrel", root, (0.0, -0.25, 0.19)) + _make_socket("socket.feed", "feed", root, (0.135, 0.02, 0.18)) + _export_part("rx_auralian_prism", "receiver", root, ground=True) + + +def build_rx_vex_pod_rack() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_tube_part("hex_pedestal", 0.22, 0.20, 0.065, segments=6, smooth=False, mat_name="gunmetal", parent=root) + vc.make_box("turret_core", (0.28, 0.42, 0.20), "mfg_primary", parent=root, location=(0.0, 0.02, 0.165), bevel=0.012) + vc.make_box("sensor_cowl", (0.22, 0.24, 0.09), "mfg_accent", parent=root, location=(0.0, -0.06, 0.295), bevel=0.008) + for idx, ox in enumerate((-0.065, 0.0, 0.065)): + vc.make_tube_part(f"seeker_eye_{idx}", 0.022, 0.022, 0.05, segments=10, mat_name="mfg_glow", parent=root, location=(ox, -0.17, 0.30), rotation_deg=(90.0, 0.0, 0.0)) + for side in (-1.0, 1.0): + vc.make_box(f"wing_cheek_{'L' if side > 0 else 'R'}", (0.05, 0.32, 0.12), "gunmetal", parent=root, location=(side * 0.16, 0.02, 0.17), rotation_deg=(0.0, 12.0 * side, 0.0), bevel=0.005) + _make_socket("socket.barrel", "barrel", root, (0.0, -0.19, 0.18)) + _make_socket("socket.feed", "feed", root, (0.18, 0.02, 0.17)) + _export_part("rx_vex_pod_rack", "receiver", root, ground=True) + + +# --------------------------------------------------------------------------- +# 4 BARRELS (origin = rear breech at (0,0,0), forward = -Y_blender = +Z_gltf) +# --------------------------------------------------------------------------- + +def build_brl_autocannon() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_box("breech_collar", (0.18, 0.12, 0.13), "gunmetal", parent=root, location=(0.0, -0.06, 0.0), bevel=0.006) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_tube_part(f"jacket_{tag}", 0.036, 0.032, 0.38, segments=10, mat_name="mfg_primary", parent=root, location=(side * 0.048, 0.0, 0.0), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part(f"barrel_{tag}", 0.019, 0.019, 0.58, segments=10, mat_name="gunmetal", parent=root, location=(side * 0.048, 0.0, 0.0), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_box("clamp_band_a", (0.15, 0.04, 0.09), "mfg_accent", parent=root, location=(0.0, -0.22, 0.0), bevel=0.004) + vc.make_box("clamp_band_b", (0.14, 0.04, 0.08), "mfg_accent", parent=root, location=(0.0, -0.44, 0.0), bevel=0.004) + _make_socket("socket.muzzle", "muzzle", root, (0.0, -0.58, 0.0)) + _export_part("brl_autocannon", "barrel", root, ground=False) + + +def build_brl_sabot_rail() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_box("rail_breech", (0.20, 0.14, 0.15), "mfg_primary", parent=root, location=(0.0, -0.07, 0.0), bevel=0.008) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"rail_bar_{tag}", (0.035, 0.68, 0.075), "gunmetal", parent=root, location=(side * 0.052, -0.34, 0.0), bevel=0.004) + vc.make_box(f"rail_glow_{tag}", (0.014, 0.56, 0.025), "mfg_glow", parent=root, location=(side * 0.028, -0.37, 0.0), bevel=0.002) + vc.make_box("rail_spine", (0.08, 0.58, 0.035), "mfg_accent", parent=root, location=(0.0, -0.36, 0.055), bevel=0.004) + for idx, dy in enumerate((-0.20, -0.38, -0.54)): + vc.make_box(f"coil_yoke_{idx}", (0.15, 0.045, 0.11), "copper_rad", parent=root, location=(0.0, dy, 0.0), bevel=0.004) + _make_socket("socket.muzzle", "muzzle", root, (0.0, -0.68, 0.0)) + _export_part("brl_sabot_rail", "barrel", root, ground=False) + + +def build_brl_prism_lance() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_tube_part("emitter_collar", 0.085, 0.070, 0.14, segments=14, mat_name="mfg_accent", parent=root, location=(0.0, 0.0, 0.0), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part("lance_core", 0.048, 0.028, 0.66, segments=12, mat_name="mfg_primary", parent=root, location=(0.0, 0.0, 0.0), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_box("focus_vane", (0.028, 0.52, 0.055), "mfg_accent", parent=root, location=(0.0, -0.32, 0.058), bevel=0.004) + for idx, dy in enumerate((-0.22, -0.39, -0.56)): + r = 0.068 - idx * 0.007 + vc.make_tube_part(f"condenser_ring_{idx}", r, r, 0.038, segments=14, mat_name="mfg_glow", parent=root, location=(0.0, dy, 0.0), rotation_deg=(90.0, 0.0, 0.0)) + _make_socket("socket.muzzle", "muzzle", root, (0.0, -0.66, 0.0)) + _export_part("brl_prism_lance", "barrel", root, ground=False) + + +def build_brl_missile_tube() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_box("launch_shroud", (0.24, 0.44, 0.22), "mfg_primary", parent=root, location=(0.0, -0.22, 0.0), bevel=0.012) + vc.make_box("front_flare_lip", (0.265, 0.06, 0.245), "mfg_accent", parent=root, location=(0.0, -0.45, 0.0), bevel=0.006) + for ix in (-0.055, 0.055): + for iz in (-0.050, 0.050): + vc.make_tube_part(f"cell_{ix:+.2f}_{iz:+.2f}", 0.038, 0.038, 0.49, segments=10, mat_name="gunmetal", parent=root, location=(ix, 0.0, iz), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_box("arm_led_bar", (0.16, 0.04, 0.025), "mfg_glow", parent=root, location=(0.0, -0.40, 0.12), bevel=0.003) + _make_socket("socket.muzzle", "muzzle", root, (0.0, -0.48, 0.0)) + _export_part("brl_missile_tube", "barrel", root, ground=False) + + +# --------------------------------------------------------------------------- +# 4 FEEDS (origin = inboard mount flange at (0,0,0), body extends +X) +# --------------------------------------------------------------------------- + +def build_fd_belt_drum() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_box("mount_bracket", (0.06, 0.14, 0.12), "gunmetal", parent=root, location=(0.03, 0.0, 0.0), bevel=0.004) + vc.make_tube_part("ammo_drum", 0.12, 0.12, 0.15, segments=14, mat_name="mfg_primary", parent=root, location=(0.06, 0.0, 0.0), rotation_deg=(0.0, 90.0, 0.0)) + vc.make_box("feed_chute", (0.10, 0.10, 0.06), "mfg_accent", parent=root, location=(0.07, -0.02, 0.12), bevel=0.004) + vc.make_box("belt_latch", (0.04, 0.08, 0.08), "rubber_dark", parent=root, location=(0.21, 0.0, 0.0), bevel=0.003) + _export_part("fd_belt_drum", "feed", root, ground=False) + + +def build_fd_rotary_loader() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_box("drive_housing", (0.07, 0.16, 0.16), "gunmetal", parent=root, location=(0.035, 0.0, 0.0), bevel=0.005) + for i in range(6): + ang = i * (math.tau / 6.0) + cy = math.cos(ang) * 0.078 + cz = math.sin(ang) * 0.078 + vc.make_tube_part(f"carousel_{i}", 0.034, 0.034, 0.16, segments=8, mat_name="mfg_primary", parent=root, location=(0.06, cy, cz), rotation_deg=(0.0, 90.0, 0.0)) + vc.make_tube_part("hub_cap", 0.055, 0.045, 0.04, segments=12, mat_name="mfg_accent", parent=root, location=(0.22, 0.0, 0.0), rotation_deg=(0.0, 90.0, 0.0)) + vc.make_tube_part("spin_ring", 0.062, 0.062, 0.02, segments=12, mat_name="mfg_glow", parent=root, location=(0.21, 0.0, 0.0), rotation_deg=(0.0, 90.0, 0.0)) + _export_part("fd_rotary_loader", "feed", root, ground=False) + + +def build_fd_capacitor_bank() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_box("cap_rail", (0.06, 0.24, 0.14), "gunmetal", parent=root, location=(0.03, 0.0, 0.0), bevel=0.005) + vc.make_kit_part( + "cap_fins", + "mechanical", + "radiator_stack", + {"fins": 7, "fin_w": 0.15, "fin_h": 0.16, "fin_t": 0.007, "pitch": 0.026, "segments": 8}, + mat_name="copper_rad", + parent=root, + location=(0.135, -0.08, 0.0), + rotation_deg=(-90.0, 0.0, 0.0), + ) + vc.make_box("cap_end_plate", (0.04, 0.22, 0.16), "mfg_primary", parent=root, location=(0.22, 0.0, 0.0), bevel=0.005) + vc.make_box("busbar_glow", (0.05, 0.20, 0.03), "mfg_glow", parent=root, location=(0.135, 0.0, 0.095), bevel=0.003) + vc.make_box("trim_bar", (0.05, 0.20, 0.03), "mfg_accent", parent=root, location=(0.135, 0.0, -0.095), bevel=0.003) + _export_part("fd_capacitor_bank", "feed", root, ground=False) + + +def build_fd_swarm_magazine() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_box("swarm_mount", (0.05, 0.18, 0.14), "gunmetal", parent=root, location=(0.025, 0.0, 0.0), bevel=0.004) + vc.make_box("honeycomb_box", (0.16, 0.26, 0.18), "mfg_primary", parent=root, location=(0.12, 0.0, 0.0), bevel=0.008) + vc.make_box("swarm_latch", (0.12, 0.08, 0.20), "mfg_accent", parent=root, location=(0.12, -0.08, 0.0), bevel=0.004) + for row in (-0.042, 0.042): + for col in (-0.06, 0.0, 0.06): + vc.make_tube_part(f"cell_{row:+.2f}_{col:+.2f}", 0.022, 0.022, 0.04, segments=6, smooth=False, mat_name="gunmetal", parent=root, location=(0.12, -0.14, row) if col == 0 else (0.12 + col * 0.4, -0.14, row), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_box("telemetry_bar", (0.03, 0.18, 0.03), "mfg_glow", parent=root, location=(0.205, 0.0, 0.06), bevel=0.002) + _export_part("fd_swarm_magazine", "feed", root, ground=False) + + +# --------------------------------------------------------------------------- +# 4 MUZZLES (origin = rear collar at (0,0,0), forward = -Y_blender = +Z_gltf) +# --------------------------------------------------------------------------- + +def build_mz_slotted_brake() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_tube_part("brake_collar", 0.062, 0.058, 0.05, segments=12, mat_name="gunmetal", parent=root, location=(0.0, 0.0, 0.0), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_box("brake_body", (0.15, 0.16, 0.095), "mfg_primary", parent=root, location=(0.0, -0.11, 0.0), bevel=0.006) + for dy in (-0.075, -0.125, -0.17): + vc.make_box(f"baffle_{dy:.3f}", (0.175, 0.022, 0.105), "mfg_accent", parent=root, location=(0.0, dy, 0.0), bevel=0.003) + vc.make_tube_part("bore_sleeve", 0.034, 0.034, 0.21, segments=10, mat_name="gunmetal", parent=root, location=(0.0, 0.0, 0.0), rotation_deg=(90.0, 0.0, 0.0)) + _make_socket("muzzle_tip", "muzzle_tip", root, (0.0, -0.21, 0.0)) + _export_part("mz_slotted_brake", "muzzle", root, ground=False) + + +def build_mz_mirv_warhead() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + profile = [ + [0.068, 0.0], + [0.088, 0.05], + [0.088, 0.13], + [0.054, 0.21], + [0.018, 0.25], + [0.0, 0.25], + ] + vc.make_lathe_part("warhead_cone", profile, segments=8, loop=False, smooth=False, mat_name="mfg_primary", parent=root, location=(0.0, 0.0, 0.0), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part("arm_ring", 0.091, 0.091, 0.032, segments=12, mat_name="mfg_glow", parent=root, location=(0.0, -0.07, 0.0), rotation_deg=(90.0, 0.0, 0.0)) + for i in range(4): + ang = i * 90.0 + 45.0 + vc.make_box(f"strake_{i}", (0.018, 0.12, 0.045), "mfg_accent", parent=root, location=(math.cos(math.radians(ang)) * 0.082, -0.08, math.sin(math.radians(ang)) * 0.082), rotation_deg=(0.0, ang, 0.0), bevel=0.002) + _make_socket("muzzle_tip", "muzzle_tip", root, (0.0, -0.25, 0.0)) + _export_part("mz_mirv_warhead", "muzzle", root, ground=False) + + +def build_mz_loiter_aero_fin() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + # Sleek deployable drone fuselage + swept delta wings + twin V-tail + glowing sensor eye + vc.make_tube_part("drone_fuselage", 0.060, 0.036, 0.26, segments=12, mat_name="mfg_primary", parent=root, location=(0.0, 0.0, 0.0), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_box("sensor_nose", (0.072, 0.06, 0.052), "mfg_glow", parent=root, location=(0.0, -0.24, 0.0), bevel=0.005) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"delta_wing_{tag}", (0.20, 0.13, 0.018), "mfg_accent", parent=root, location=(side * 0.125, -0.10, 0.0), rotation_deg=(0.0, 0.0, -24.0 * side), bevel=0.003) + vc.make_box(f"v_tail_{tag}", (0.018, 0.08, 0.085), "mfg_primary", parent=root, location=(side * 0.055, -0.04, 0.052), rotation_deg=(0.0, 28.0 * side, 0.0), bevel=0.002) + _make_socket("muzzle_tip", "muzzle_tip", root, (0.0, -0.28, 0.0)) + _export_part("mz_loiter_aero_fin", "muzzle", root, ground=False) + + +def build_mz_plasma_diffuser() -> None: + vc.reset_scene() + ensure_weapon_part_materials() + root = vc.make_empty("PartRoot") + vc.make_tube_part("choke_collar", 0.068, 0.062, 0.06, segments=6, smooth=False, mat_name="gunmetal", parent=root, location=(0.0, 0.0, 0.0), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part("containment_ring", 0.078, 0.078, 0.04, segments=14, mat_name="mfg_glow", parent=root, location=(0.0, -0.08, 0.0), rotation_deg=(90.0, 0.0, 0.0)) + for i in range(3): + ang = i * 120.0 + 90.0 + rad = math.radians(ang) + px = math.cos(rad) * 0.068 + pz = math.sin(rad) * 0.068 + vc.make_box(f"copper_prong_{i}", (0.024, 0.19, 0.036), "copper_rad", parent=root, location=(px, -0.145, pz), rotation_deg=(0.0, ang, 0.0), bevel=0.003) + vc.make_box(f"guard_fin_{i}", (0.020, 0.10, 0.046), "mfg_accent", parent=root, location=(px * 1.18, -0.07, pz * 1.18), rotation_deg=(0.0, ang, 0.0), bevel=0.002) + _make_socket("muzzle_tip", "muzzle_tip", root, (0.0, -0.24, 0.0)) + _export_part("mz_plasma_diffuser", "muzzle", root, ground=False) + + +def build_all_weapon_parts() -> None: + PARTS_DIR.mkdir(parents=True, exist_ok=True) + # 4 Receivers + build_rx_salvage_frame() + build_rx_korrathi_cradle() + build_rx_auralian_prism() + build_rx_vex_pod_rack() + # 4 Barrels + build_brl_autocannon() + build_brl_sabot_rail() + build_brl_prism_lance() + build_brl_missile_tube() + # 4 Feeds + build_fd_belt_drum() + build_fd_rotary_loader() + build_fd_capacitor_bank() + build_fd_swarm_magazine() + # 4 Muzzles + build_mz_slotted_brake() + build_mz_mirv_warhead() + build_mz_loiter_aero_fin() + build_mz_plasma_diffuser() + + +if __name__ == "__main__": + build_all_weapon_parts() diff --git a/tools/vehicles/previews/anvil_preview.png b/tools/vehicles/previews/anvil_preview.png new file mode 100644 index 0000000..4e5fc09 Binary files /dev/null and b/tools/vehicles/previews/anvil_preview.png differ diff --git a/tools/vehicles/previews/bastion_preview.png b/tools/vehicles/previews/bastion_preview.png new file mode 100644 index 0000000..96022c9 Binary files /dev/null and b/tools/vehicles/previews/bastion_preview.png differ diff --git a/tools/vehicles/previews/breaker_preview.png b/tools/vehicles/previews/breaker_preview.png new file mode 100644 index 0000000..2a62be9 Binary files /dev/null and b/tools/vehicles/previews/breaker_preview.png differ diff --git a/tools/vehicles/previews/condor_preview.png b/tools/vehicles/previews/condor_preview.png new file mode 100644 index 0000000..c8ef101 Binary files /dev/null and b/tools/vehicles/previews/condor_preview.png differ diff --git a/tools/vehicles/previews/ferret_preview.png b/tools/vehicles/previews/ferret_preview.png new file mode 100644 index 0000000..a6fe46e Binary files /dev/null and b/tools/vehicles/previews/ferret_preview.png differ diff --git a/tools/vehicles/previews/hornet_preview.png b/tools/vehicles/previews/hornet_preview.png new file mode 100644 index 0000000..dbdf035 Binary files /dev/null and b/tools/vehicles/previews/hornet_preview.png differ diff --git a/tools/vehicles/previews/ironclad_preview.png b/tools/vehicles/previews/ironclad_preview.png new file mode 100644 index 0000000..2c217db Binary files /dev/null and b/tools/vehicles/previews/ironclad_preview.png differ diff --git a/tools/vehicles/previews/jackal_preview.png b/tools/vehicles/previews/jackal_preview.png new file mode 100644 index 0000000..7cf2b1a Binary files /dev/null and b/tools/vehicles/previews/jackal_preview.png differ diff --git a/tools/vehicles/previews/kestrel_preview.png b/tools/vehicles/previews/kestrel_preview.png new file mode 100644 index 0000000..e177be2 Binary files /dev/null and b/tools/vehicles/previews/kestrel_preview.png differ diff --git a/tools/vehicles/previews/mammoth_preview.png b/tools/vehicles/previews/mammoth_preview.png new file mode 100644 index 0000000..ce921ce Binary files /dev/null and b/tools/vehicles/previews/mammoth_preview.png differ diff --git a/tools/vehicles/previews/manticore_preview.png b/tools/vehicles/previews/manticore_preview.png new file mode 100644 index 0000000..e90a2bb Binary files /dev/null and b/tools/vehicles/previews/manticore_preview.png differ diff --git a/tools/vehicles/previews/mule_preview.png b/tools/vehicles/previews/mule_preview.png new file mode 100644 index 0000000..5180720 Binary files /dev/null and b/tools/vehicles/previews/mule_preview.png differ diff --git a/tools/vehicles/previews/paladin_preview.png b/tools/vehicles/previews/paladin_preview.png new file mode 100644 index 0000000..8cebb84 Binary files /dev/null and b/tools/vehicles/previews/paladin_preview.png differ diff --git a/tools/vehicles/previews/raptor_preview.png b/tools/vehicles/previews/raptor_preview.png new file mode 100644 index 0000000..6e662e4 Binary files /dev/null and b/tools/vehicles/previews/raptor_preview.png differ diff --git a/tools/vehicles/previews/spectre_preview.png b/tools/vehicles/previews/spectre_preview.png new file mode 100644 index 0000000..9506ebb Binary files /dev/null and b/tools/vehicles/previews/spectre_preview.png differ diff --git a/tools/vehicles/retrofit_mechs.py b/tools/vehicles/retrofit_mechs.py new file mode 100644 index 0000000..e936f7e --- /dev/null +++ b/tools/vehicles/retrofit_mechs.py @@ -0,0 +1,2499 @@ +"""Retrofit Brokkr kit-built mechs for Rust to Dust: +- Strip built-in weapon loadouts and studio backdrop/rig helpers (read-only on source .blend/.json). +- Normalize procedural Brokkr shaders to clean glTF 2.0 Principled BSDF PBR materials. +- Apply skinning-preserving / silhouette-preserving LOD decimation (target ~26k-32k tris). +- Reorient from Brokkr (+Y forward, -X left) to RTD (+Z forward glTF / -Y Blender, +X left), grounded at minY = 0. +- Attach visible exterior hardpoint collars/bays (`add_hardpoint_slot`) and joint tags (`tag_joint`). +- Emit `.glb`, `manifest.json` (including `mechanisms` when model JSON has rams/scissors/struts), and 4-panel preview PNG. + +Adding a future Brokkr mech (e.g. `bastion`, `seraph`): add a `MechRetrofitSpec` entry in `SPECS`. +""" +from __future__ import annotations + +import argparse +import json +import math +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import bmesh +import bpy +from mathutils import Euler, Matrix, Vector +from mathutils.bvhtree import BVHTree + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +@dataclass(frozen=True) +class HardpointMount: + hp_id: str + kind: str + x: int + y: int + w: int + h: int + parent_name: str + parent_bone: str | None + world_pos: tuple[float, float, float] + world_normal: tuple[float, float, float] + size: tuple[float, float, float] + + +@dataclass(frozen=True) +class JointTagSpec: + joint_id: str + target_name: str + parent_bone: str | None + axis_gltf: tuple[float, float, float] + min_val: float + max_val: float + + +@dataclass(frozen=True) +class MechRetrofitSpec: + mech_id: str + name: str + vehicle_class: str + plane: str + grid_width: int + grid_height: int + mask: tuple[str, ...] + blend_path: Path + model_json_path: Path | None + target_mech_tris: int + drop_collections: tuple[str, ...] = () + strip_prefixes: tuple[str, ...] = () + strip_vertex_groups: tuple[str, ...] = () + strip_islands: tuple[tuple[str, str, float], ...] = () + armature_name: str | None = None + hardpoints: tuple[HardpointMount, ...] = () + joints: tuple[JointTagSpec, ...] = () + extra_notes: str = "" + + +SPECS: dict[str, MechRetrofitSpec] = { + "breaker": MechRetrofitSpec( + mech_id="breaker", + name="Breaker", + vehicle_class="Heavy Assault Biped", + plane="Coronal", + grid_width=5, + grid_height=6, + mask=( + ".###.", + "#####", + "#####", + "#####", + ".#.#.", + ".#.#.", + ), + blend_path=Path(r"F:\aeth-wt\fable-breaker-3\out\breaker\breaker_walk.blend"), + model_json_path=None, + target_mech_tris=32000, + drop_collections=(), + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "CannonL", "CannonR"), + strip_vertex_groups=(), + armature_name=None, + hardpoints=( + HardpointMount("hp.weapon.arm_l", "weapon", 0, 1, 1, 2, "ForearmL", None, (-2.18, 0.45, 3.52), (-1.0, 0.0, 0.0), (0.54, 0.54, 0.11)), + HardpointMount("hp.weapon.arm_r", "weapon", 4, 1, 1, 2, "ForearmR", None, (2.14, 0.65, 3.55), (1.0, 0.0, 0.0), (0.54, 0.54, 0.11)), + HardpointMount("hp.weapon.shoulder_l", "weapon", 1, 0, 1, 1, "Core", None, (-1.48, 0.12, 5.99), (0.0, 0.0, 1.0), (0.72, 0.72, 0.12)), + HardpointMount("hp.armor.torso", "armor", 2, 1, 1, 1, "Core", None, (0.0, 1.32, 5.05), (0.0, 0.82, 0.57), (1.02, 0.40, 0.11)), + HardpointMount("hp.engine.chest", "engine", 2, 2, 1, 2, "Core", None, (0.0, 1.76, 4.48), (0.0, 1.0, 0.0), (0.78, 0.56, 0.13)), + HardpointMount("hp.radiator.back_l", "radiator", 1, 1, 1, 1, "Core", None, (-1.50, -1.14, 5.22), (0.0, -1.0, 0.0), (0.68, 0.92, 0.12)), + HardpointMount("hp.radiator.back_r", "radiator", 3, 1, 1, 1, "Core", None, (1.50, -1.14, 5.22), (0.0, -1.0, 0.0), (0.68, 0.92, 0.12)), + ), + joints=( + JointTagSpec("joint.torso_yaw", "Core", None, (0.0, 1.0, 0.0), -90.0, 90.0), + JointTagSpec("joint.arm_l_pitch", "ShoulderYokeL", None, (1.0, 0.0, 0.0), -45.0, 60.0), + JointTagSpec("joint.arm_r_pitch", "ShoulderYokeR", None, (1.0, 0.0, 0.0), -45.0, 60.0), + ), + ), + "paladin": MechRetrofitSpec( + mech_id="paladin", + name="Paladin", + vehicle_class="Heavy Assault Biped", + plane="Coronal", + grid_width=6, + grid_height=7, + mask=( + "..##..", + ".####.", + "######", + "######", + ".####.", + ".#..#.", + ".#..#.", + ), + blend_path=Path(r"F:\aeth-wt\fable-paladin-3\out\paladin\paladin.blend"), + model_json_path=None, + target_mech_tris=29000, + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "Battery.", "EW.", "EWLow.", "Gatling.", "Emitter."), + hardpoints=( + HardpointMount("hp.weapon.sh_l", "weapon", 1, 1, 1, 1, "Trunk", None, (-2.88, 0.35, 9.82), (0.0, 0.0, 1.0), (0.94, 0.94, 0.15)), + HardpointMount("hp.armor.torso", "armor", 2, 1, 2, 1, "Trunk", None, (0.0, 1.80, 8.75), (0.0, 0.60, 0.80), (1.22, 0.40, 0.12)), + HardpointMount("hp.weapon.sh_r", "weapon", 4, 1, 1, 1, "Trunk", None, (2.88, 0.35, 9.82), (0.0, 0.0, 1.0), (0.94, 0.94, 0.15)), + HardpointMount("hp.weapon.arm_l", "weapon", 0, 2, 1, 2, "ArmL.Lower", None, (-3.44, 0.85, 5.75), (-1.0, 0.0, 0.0), (0.74, 0.74, 0.13)), + HardpointMount("hp.engine.chest", "engine", 2, 2, 2, 2, "Trunk", None, (0.0, 2.22, 8.05), (0.0, 0.94, 0.34), (0.82, 0.54, 0.14)), + HardpointMount("hp.weapon.arm_r", "weapon", 5, 2, 1, 2, "ArmR.Lower", None, (3.52, 1.05, 6.22), (1.0, 0.0, 0.0), (0.72, 0.72, 0.13)), + HardpointMount("hp.radiator.back_l", "radiator", 1, 4, 1, 1, "Trunk", None, (-0.92, -1.44, 8.65), (0.0, -1.0, 0.0), (0.82, 1.35, 0.14)), + HardpointMount("hp.armor.legs", "armor", 2, 4, 2, 1, "Pelvis", None, (0.0, 1.18, 5.55), (0.0, 1.0, 0.0), (0.95, 0.38, 0.11)), + HardpointMount("hp.radiator.back_r", "radiator", 4, 4, 1, 1, "Trunk", None, (0.92, -1.44, 8.65), (0.0, -1.0, 0.0), (0.82, 1.35, 0.14)), + ), + joints=( + JointTagSpec("joint.torso_yaw", "Trunk", None, (0.0, 1.0, 0.0), -90.0, 90.0), + JointTagSpec("joint.arm_l_pitch", "ArmL.Upper", None, (1.0, 0.0, 0.0), -40.0, 70.0), + JointTagSpec("joint.arm_r_pitch", "ArmR.Upper", None, (1.0, 0.0, 0.0), -40.0, 70.0), + ), + ), + "raptor": MechRetrofitSpec( + mech_id="raptor", + name="Raptor", + vehicle_class="Medium Theropod Biped", + plane="Coronal", + grid_width=5, + grid_height=6, + mask=( + "..#..", + ".###.", + "#####", + "#.#.#", + ".#.#.", + ".#.#.", + ), + blend_path=Path(r"F:\aeth-wt\fable-raptor-4\out\raptor\raptor.blend"), + model_json_path=None, + target_mech_tris=28000, + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "Bank0.", "Bank1.", "LaserL.", "LaserR."), + hardpoints=( + HardpointMount("hp.radiator.sh_l", "radiator", 1, 1, 1, 1, "_ROOT_", None, (-0.56, 0.05, 6.26), (-0.25, 0.0, 0.97), (0.64, 1.00, 0.12)), + HardpointMount("hp.radiator.sh_r", "radiator", 3, 1, 1, 1, "_ROOT_", None, (0.56, 0.05, 6.26), (0.25, 0.0, 0.97), (0.64, 1.00, 0.12)), + HardpointMount("hp.weapon.arm_l", "weapon", 0, 2, 1, 2, "ArmL.Fore", None, (-1.32, 2.14, 3.86), (-1.0, 0.0, 0.0), (0.48, 0.48, 0.11)), + HardpointMount("hp.engine.chest", "engine", 2, 2, 1, 2, "_ROOT_", None, (0.0, -2.02, 6.78), (0.0, 0.0, 1.0), (0.82, 1.06, 0.14)), + HardpointMount("hp.weapon.arm_r", "weapon", 4, 2, 1, 2, "ArmR.Fore", None, (1.32, 2.14, 3.86), (1.0, 0.0, 0.0), (0.48, 0.48, 0.11)), + ), + joints=( + JointTagSpec("joint.arm_l_pitch", "ArmL.Upper", None, (1.0, 0.0, 0.0), -45.0, 45.0), + JointTagSpec("joint.arm_r_pitch", "ArmR.Upper", None, (1.0, 0.0, 0.0), -45.0, 45.0), + ), + ), + "manticore": MechRetrofitSpec( + mech_id="manticore", + name="Manticore", + vehicle_class="Heavy Quadruped Scorpion", + plane="Dorsal", + grid_width=5, + grid_height=5, + mask=( + "#####", + ".###.", + "#####", + ".###.", + "#.#.#", + ), + blend_path=Path(r"F:\aeth-wt\fable-manticore-3\out\manticore\manticore.blend"), + model_json_path=None, + target_mech_tris=28000, + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "Laser.light", "Launcher.", "ArmGunL.", "ArmGunR."), + hardpoints=( + HardpointMount("hp.weapon.chin", "weapon", 2, 0, 1, 1, "Hull", None, (0.0, 3.34, 1.38), (0.0, 0.94, -0.34), (0.64, 0.64, 0.12)), + HardpointMount("hp.radiator.flank_l", "radiator", 1, 1, 1, 1, "Hull", None, (-1.18, -0.35, 2.76), (-0.22, 0.0, 0.97), (0.56, 0.98, 0.12)), + HardpointMount("hp.engine.core", "engine", 2, 1, 1, 2, "Hull", None, (0.0, -0.25, 2.94), (0.0, 0.14, 0.99), (0.86, 1.20, 0.14)), + HardpointMount("hp.radiator.flank_r", "radiator", 3, 1, 1, 1, "Hull", None, (1.18, -0.35, 2.76), (0.22, 0.0, 0.97), (0.56, 0.98, 0.12)), + HardpointMount("hp.weapon.l", "weapon", 0, 2, 1, 1, "ArmL.Upper", None, (-0.96, 2.75, 0.72), (-0.65, 0.76, 0.0), (0.56, 0.56, 0.11)), + HardpointMount("hp.weapon.r", "weapon", 4, 2, 1, 1, "ArmR.Upper", None, (0.96, 2.75, 0.72), (0.65, 0.76, 0.0), (0.56, 0.56, 0.11)), + HardpointMount("hp.armor.prow", "armor", 2, 3, 1, 1, "Hull", None, (0.0, 3.14, 1.94), (0.0, 0.85, 0.53), (0.88, 0.34, 0.11)), + ), + joints=( + JointTagSpec("joint.tail_yaw", "Tail.Coxa", None, (0.0, 1.0, 0.0), -75.0, 75.0), + JointTagSpec("joint.tail_s1", "Tail.S1", None, (1.0, 0.0, 0.0), -60.0, 60.0), + JointTagSpec("joint.tail_s2", "Tail.S2", None, (1.0, 0.0, 0.0), -75.0, 15.0), + JointTagSpec("joint.tail_s3", "Tail.S3", None, (1.0, 0.0, 0.0), -80.0, 10.0), + JointTagSpec("joint.tail_elev", "Tail.Elev", None, (1.0, 0.0, 0.0), -40.0, 30.0), + ), + ), + "bastion": MechRetrofitSpec( + mech_id="bastion", + name="Bastion", + vehicle_class="Heavy Siege Quadruped", + plane="Dorsal", + grid_width=6, + grid_height=6, + mask=( + "..##..", + ".####.", + "######", + "######", + ".####.", + ".#..#.", + ), + blend_path=Path(r"F:\aeth-wt\fable-bastion-2\out\bastion\bastion.blend"), + model_json_path=None, + target_mech_tris=32000, + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "Aim.Gun", "Gun.", "Magazine.", "Interceptor."), + hardpoints=( + HardpointMount("hp.armor.prow", "armor", 2, 0, 2, 1, "Trunk", None, (0.0, 5.16, 6.50), (0.0, 0.29, 0.96), (1.35, 0.42, 0.12)), + HardpointMount("hp.weapon.turret_pd", "weapon", 1, 1, 1, 1, "Aim.Turret", None, (0.0, -1.80, 9.11), (0.0, 0.0, 1.0), (0.68, 0.68, 0.12)), + HardpointMount("hp.weapon.turret_main", "weapon", 2, 1, 2, 2, "Aim.Turret", None, (0.0, 0.45, 9.07), (0.0, 0.03, 1.0), (1.30, 1.30, 0.16)), + HardpointMount("hp.weapon.flank_l", "weapon", 0, 2, 1, 2, "Trunk", None, (-3.70, -0.22, 6.18), (-1.0, 0.0, 0.0), (0.85, 0.85, 0.14)), + HardpointMount("hp.weapon.flank_r", "weapon", 5, 2, 1, 2, "Trunk", None, (3.70, -0.22, 6.18), (1.0, 0.0, 0.0), (0.85, 0.85, 0.14)), + HardpointMount("hp.engine.core", "engine", 2, 3, 2, 2, "Trunk", None, (0.0, -5.70, 7.34), (0.0, 0.0, 1.0), (1.50, 1.35, 0.16)), + HardpointMount("hp.radiator.rear_l", "radiator", 1, 4, 1, 2, "Trunk", None, (-2.55, -5.75, 7.38), (0.0, 0.0, 1.0), (0.98, 1.38, 0.14)), + HardpointMount("hp.radiator.rear_r", "radiator", 4, 4, 1, 2, "Trunk", None, (2.55, -5.75, 7.38), (0.0, 0.0, 1.0), (0.98, 1.38, 0.14)), + ), + joints=( + JointTagSpec("joint.turret_yaw", "Aim.Turret", None, (0.0, 1.0, 0.0), -180.0, 180.0), + ), + ), + "spectre": MechRetrofitSpec( + mech_id="spectre", + name="Spectre", + vehicle_class="Medium Recon/Skirmisher Biped", + plane="Coronal", + grid_width=5, + grid_height=6, + mask=( + ".#...", + ".###.", + "#####", + "#####", + ".#.#.", + ".#.#.", + ), + blend_path=Path(r"F:\aeth-wt\fable-spectre-3\out\spectre\spectre.blend"), + model_json_path=None, + target_mech_tris=27000, + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "Rack.", "RackTail.", "GunL.lamp", "GunR.lamp", "GunR.glass"), + strip_islands=( + ("GunL.gunmetal", "max_y>", 2.0), + ("GunR.gunmetal", "max_y>", 3.15), + ("GunR.khaki", "max_y>", 3.15), + ), + hardpoints=( + HardpointMount("hp.weapon.shoulder_l", "weapon", 1, 0, 1, 1, "Waist", None, (-2.22, 0.15, 7.48), (-0.17, 0.23, 0.96), (0.78, 0.78, 0.13)), + HardpointMount("hp.armor.torso", "armor", 2, 1, 1, 1, "Waist", None, (0.0, 3.10, 5.68), (0.0, 0.11, -0.99), (0.74, 0.28, 0.10)), + HardpointMount("hp.weapon.arm_l", "weapon", 0, 2, 1, 2, "ShoulderL", None, (-2.81, 1.75, 5.15), (-1.0, 0.0, 0.0), (0.52, 0.52, 0.11)), + HardpointMount("hp.radiator.back_l", "radiator", 1, 2, 1, 1, "Waist", None, (-2.20, -0.79, 7.00), (0.0, -1.0, 0.0), (0.76, 0.96, 0.12)), + HardpointMount("hp.engine.core", "engine", 2, 2, 1, 2, "Waist", None, (0.0, -2.30, 7.00), (0.0, -1.0, 0.0), (0.86, 1.18, 0.14)), + HardpointMount("hp.radiator.back_r", "radiator", 3, 2, 1, 1, "Waist", None, (2.20, -0.79, 7.00), (0.0, -1.0, 0.0), (0.76, 0.96, 0.12)), + HardpointMount("hp.weapon.arm_r", "weapon", 4, 2, 1, 2, "ShoulderR", None, (2.66, 1.75, 5.05), (1.0, 0.0, 0.0), (0.52, 0.52, 0.11)), + ), + joints=( + JointTagSpec("joint.torso_yaw", "Waist", None, (0.0, 1.0, 0.0), -90.0, 90.0), + JointTagSpec("joint.arm_l_pitch", "ShoulderL", None, (1.0, 0.0, 0.0), -45.0, 60.0), + JointTagSpec("joint.arm_r_pitch", "ShoulderR", None, (1.0, 0.0, 0.0), -45.0, 60.0), + ), + ), + "kestrel": MechRetrofitSpec( + mech_id="kestrel", + name="Kestrel", + vehicle_class="Light Scout Biped", + plane="Coronal", + grid_width=5, + grid_height=5, + mask=( + "..#..", + ".###.", + ".####", + ".####", + ".#.#.", + ), + blend_path=Path(r"F:\aeth-wt\fable-kestrel-2\out\kestrel\kestrel.blend"), + model_json_path=None, + target_mech_tris=27000, + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "WeaponArm.accent_yellow"), + strip_islands=( + ("WeaponArm.gunmetal", "max_y>", 2.30), + ), + hardpoints=( + HardpointMount("hp.weapon.dorsal", "weapon", 2, 0, 1, 1, "Torso.pose", None, (0.0, 0.23, 9.25), (0.0, 0.38, 0.92), (0.56, 0.56, 0.11)), + HardpointMount("hp.armor.chest", "armor", 2, 1, 1, 1, "Torso.pose", None, (0.0, 2.28, 6.87), (0.0, 0.88, -0.47), (0.72, 0.32, 0.10)), + HardpointMount("hp.radiator.back", "radiator", 1, 2, 1, 1, "Torso.pose", None, (-1.02, -1.86, 8.35), (0.0, -0.97, 0.26), (0.58, 0.78, 0.11)), + HardpointMount("hp.engine.core", "engine", 2, 2, 1, 2, "Torso.pose", None, (0.0, -1.72, 8.20), (0.0, -0.93, 0.36), (0.76, 1.02, 0.13)), + HardpointMount("hp.weapon.arm_r", "weapon", 4, 2, 1, 2, "ArmR", None, (2.29, 1.15, 5.95), (1.0, 0.0, 0.0), (0.46, 0.46, 0.10)), + ), + joints=( + JointTagSpec("joint.torso_yaw", "Torso.pose", None, (0.0, 1.0, 0.0), -90.0, 90.0), + JointTagSpec("joint.arm_l_pitch", "ArmL", None, (1.0, 0.0, 0.0), -45.0, 60.0), + JointTagSpec("joint.arm_r_pitch", "ArmR", None, (1.0, 0.0, 0.0), -45.0, 60.0), + ), + ), +} + + +def _should_strip(name: str, prefixes: tuple[str, ...]) -> bool: + return any(name == p or name.startswith(p) or name.startswith(p.rstrip(".")) and name == p.rstrip(".") for p in prefixes) + + +def _remove_object_recursive(obj: bpy.types.Object) -> None: + for ch in list(obj.children): + _remove_object_recursive(ch) + if obj.name in bpy.data.objects: + bpy.data.objects.remove(obj, do_unlink=True) + + +def _strip_scene_objects(spec: MechRetrofitSpec) -> list[str]: + stripped: list[str] = [] + + # 1. Drop excluded build collections (e.g. breaker.build) + for col_name in spec.drop_collections: + col = bpy.data.collections.get(col_name) + if col is not None: + for obj_name in [o.name for o in col.objects]: + stripped.append(obj_name) + obj = bpy.data.objects.get(obj_name) + if obj is not None: + bpy.data.objects.remove(obj, do_unlink=True) + bpy.data.collections.remove(col) + + # 2. Strip matching prefixes, studio lights/cameras/fonts, and hidden boolean cutters + for obj_name in [o.name for o in bpy.data.objects]: + obj = bpy.data.objects.get(obj_name) + if obj is None: + continue + if obj.type in ("LIGHT", "CAMERA", "FONT"): + stripped.append(obj_name) + bpy.data.objects.remove(obj, do_unlink=True) + continue + is_skeleton_pivot = obj.get("kit_part") in ("bone", "trunk") + if not is_skeleton_pivot and (obj.hide_viewport or obj.hide_render or obj.display_type in ("WIRE", "BOUNDS")): + stripped.append(obj_name) + bpy.data.objects.remove(obj, do_unlink=True) + continue + if _should_strip(obj_name, spec.strip_prefixes): + stripped.append(obj_name) + _remove_object_recursive(obj) + continue + if not spec.armature_name and ".bolts" in obj_name: + stripped.append(obj_name) + bpy.data.objects.remove(obj, do_unlink=True) + + return sorted(set(stripped)) + + +def _strip_vertex_groups_from_mesh(obj: bpy.types.Object, vg_names: tuple[str, ...]) -> int: + if not vg_names or obj.type != "MESH": + return 0 + target_indices = { + obj.vertex_groups[name].index + for name in vg_names + if name in obj.vertex_groups + } + if not target_indices: + return 0 + bm = bmesh.new() + bm.from_mesh(obj.data) + dlayer = bm.verts.layers.deform.active + removed_verts = 0 + if dlayer is not None: + to_delete = [] + for v in bm.verts: + dw = v[dlayer] + if any(dw.get(idx, 0.0) > 0.5 for idx in target_indices): + to_delete.append(v) + removed_verts = len(to_delete) + if to_delete: + bmesh.ops.delete(bm, geom=to_delete, context="VERTS") + bm.to_mesh(obj.data) + bm.free() + obj.data.validate(verbose=False) + obj.data.update() + return removed_verts + + +def _strip_mesh_islands(strip_islands: tuple[tuple[str, str, float], ...]) -> dict[str, int]: + """Remove disconnected mesh islands matching world-space predicates (e.g. protruding gun barrels).""" + removed: dict[str, int] = {} + for obj_name, op, thresh in strip_islands: + obj = bpy.data.objects.get(obj_name) + if obj is None or obj.type != "MESH" or obj.data is None: + continue + bm = bmesh.new() + bm.from_mesh(obj.data) + bm.verts.ensure_lookup_table() + mw = obj.matrix_world + visited: set[int] = set() + del_verts: list[bmesh.types.BMVert] = [] + for v in bm.verts: + if v.index in visited: + continue + comp: list[bmesh.types.BMVert] = [] + stack = [v] + visited.add(v.index) + while stack: + cur = stack.pop() + comp.append(cur) + for e in cur.link_edges: + ov = e.other_vert(cur) + if ov.index not in visited: + visited.add(ov.index) + stack.append(ov) + pts = [mw @ c.co for c in comp] + hit = False + if op == "max_y>": + hit = max(p.y for p in pts) > thresh + elif op == "min_y<": + hit = min(p.y for p in pts) < thresh + elif op == "max_z>": + hit = max(p.z for p in pts) > thresh + if hit: + del_verts.extend(comp) + if del_verts: + bmesh.ops.delete(bm, geom=del_verts, context="VERTS") + bm.to_mesh(obj.data) + obj.data.validate(verbose=False) + obj.data.update() + removed[obj_name] = len(del_verts) + bm.free() + return removed + + +def _reparent_keep_world(obj: bpy.types.Object, parent: bpy.types.Object) -> None: + mw = obj.matrix_world.copy() + obj.parent = parent + obj.matrix_parent_inverse = Matrix.Identity(4) + obj.matrix_local = parent.matrix_world.inverted() @ mw + + +def _split_mesh_by_world_z( + obj: bpy.types.Object, + z_split: float, + upper_name: str, + lower_name: str, +) -> tuple[bpy.types.Object, bpy.types.Object]: + """Split a disconnected multi-island mesh object into upper (z > z_split) and lower (z <= z_split) objects.""" + lower_obj = obj.copy() + lower_obj.data = obj.data.copy() + for col in obj.users_collection: + col.objects.link(lower_obj) + if not obj.users_collection: + bpy.context.scene.collection.objects.link(lower_obj) + + mw = obj.matrix_world.copy() + for target, keep_upper in ((obj, True), (lower_obj, False)): + bm = bmesh.new() + bm.from_mesh(target.data) + drop_verts = [ + v for v in bm.verts + if (keep_upper and (mw @ v.co).z <= z_split) or (not keep_upper and (mw @ v.co).z > z_split) + ] + if drop_verts: + bmesh.ops.delete(bm, geom=drop_verts, context="VERTS") + bm.to_mesh(target.data) + bm.free() + target.data.update() + + obj.name = upper_name + obj.data.name = upper_name + lower_obj.name = lower_name + lower_obj.data.name = lower_name + return obj, lower_obj + + +def _assemble_kestrel_hierarchy() -> None: + """Group Kestrel's flat root parts under Pelvis, Leg{L,R}.{Thigh,Shin,Foot}, Torso.pose, ArmL, and ArmR pivots.""" + torso_pose = bpy.data.objects.get("Torso.pose") + if torso_pose is None: + return + + pelvis = vc.make_empty("Pelvis", parent=None, location=(0.0, 0.0, 0.0)) + arm_l = vc.make_empty("ArmL", parent=torso_pose, location=(-1.62, 0.65, 1.50)) + arm_r = vc.make_empty("ArmR", parent=torso_pose, location=(1.62, 0.65, 1.50)) + bpy.context.view_layer.update() + + # Split combined LegJoints{L,R}.* (hip + knee drums in one mesh) into distinct hip (z > 5.0) and knee (z <= 5.0) meshes + for side in ("L", "R"): + for mat_suffix in ("gunmetal", "khaki", "machine"): + joint_obj = bpy.data.objects.get(f"LegJoints{side}.{mat_suffix}") + if joint_obj is not None and joint_obj.type == "MESH": + _split_mesh_by_world_z( + joint_obj, + z_split=5.0, + upper_name=f"LegJoints{side}Hip.{mat_suffix}", + lower_name=f"LegJoints{side}Knee.{mat_suffix}", + ) + + # Create articulated leg pivot chains at exact hip, knee, and ankle drum centers + leg_pivots: dict[str, tuple[bpy.types.Object, bpy.types.Object, bpy.types.Object]] = {} + for side in ("L", "R"): + hip_b = _obj_bounds_in_ref([f"LegJoints{side}Hip.gunmetal"], pelvis) + knee_b = _obj_bounds_in_ref([f"LegJoints{side}Knee.gunmetal"], pelvis) + ankle_b = _obj_bounds_in_ref([f"Ankle{side}.foot.machine.body"], pelvis) + assert hip_b is not None and knee_b is not None and ankle_b is not None, ( + f"kestrel: missing leg drum bounds for side {side}" + ) + hip_c = 0.5 * (hip_b[0] + hip_b[1]) + knee_c = 0.5 * (knee_b[0] + knee_b[1]) + ankle_c = 0.5 * (ankle_b[0] + ankle_b[1]) + + leg_thigh = vc.make_empty(f"Leg{side}.Thigh", parent=pelvis, location=tuple(hip_c)) + bpy.context.view_layer.update() + leg_shin = vc.make_empty(f"Leg{side}.Shin", parent=leg_thigh, location=tuple(knee_c - hip_c)) + bpy.context.view_layer.update() + leg_foot = vc.make_empty(f"Leg{side}.Foot", parent=leg_shin, location=tuple(ankle_c - knee_c)) + bpy.context.view_layer.update() + leg_pivots[side] = (leg_thigh, leg_shin, leg_foot) + + protected = {pelvis, torso_pose, arm_l, arm_r} + for pivots in leg_pivots.values(): + protected.update(pivots) + + for obj in list(bpy.data.objects): + if obj in protected: + continue + name = obj.name + if obj.parent is None and name.startswith("Pelvis."): + _reparent_keep_world(obj, pelvis) + elif obj.parent is None and name.startswith(("ThighL.", "LegJointsLHip.")): + _reparent_keep_world(obj, leg_pivots["L"][0]) + elif obj.parent is None and name.startswith(("ThighR.", "LegJointsRHip.")): + _reparent_keep_world(obj, leg_pivots["R"][0]) + elif obj.parent is None and name.startswith(("ShinL.", "LegJointsLKnee.", "AnkleL.root.")): + _reparent_keep_world(obj, leg_pivots["L"][1]) + elif obj.parent is None and name.startswith(("ShinR.", "LegJointsRKnee.", "AnkleR.root.")): + _reparent_keep_world(obj, leg_pivots["R"][1]) + elif obj.parent is None and name.startswith(("FootL.", "AnkleL.foot.")): + _reparent_keep_world(obj, leg_pivots["L"][2]) + elif obj.parent is None and name.startswith(("FootR.", "AnkleR.foot.")): + _reparent_keep_world(obj, leg_pivots["R"][2]) + elif obj.parent is None and (name.startswith("Neck.") or name.startswith("Shoulder")): + _reparent_keep_world(obj, torso_pose) + elif name.startswith("UpperArmL.") or name.startswith("ElbowL.") or name.startswith("ForearmL.") or name.startswith("HandL."): + _reparent_keep_world(obj, arm_l) + elif name.startswith("UpperArmR.") or name.startswith("ElbowR.") or name.startswith("WeaponArm."): + _reparent_keep_world(obj, arm_r) + bpy.context.view_layer.update() + + +def _apply_existing_modifiers() -> None: + """Drop BEVEL (which causes decimate spikes) and bake SOLIDIFY/BOOLEAN before stripping cutters.""" + for obj_name in [o.name for o in bpy.data.objects]: + obj = bpy.data.objects.get(obj_name) + if obj is None or obj.type != "MESH" or not obj.modifiers: + continue + for mod in list(obj.modifiers): + if mod.type == "BEVEL": + obj.modifiers.remove(mod) + depsgraph = bpy.context.evaluated_depsgraph_get() + for obj_name in [o.name for o in bpy.data.objects]: + obj = bpy.data.objects.get(obj_name) + if obj is None or obj.type != "MESH" or not obj.modifiers: + continue + if any(m.type == "ARMATURE" for m in obj.modifiers): + continue + ev = obj.evaluated_get(depsgraph) + new_mesh = bpy.data.meshes.new_from_object(ev, preserve_all_data_layers=True, depsgraph=depsgraph) + new_mesh.name = f"{obj.name}_baked" + obj.modifiers.clear() + obj.data = new_mesh + + +def _convert_surviving_curves() -> None: + """Convert surviving CURVE hydraulic hoses to MESH.""" + view_layer = bpy.context.view_layer + curves = [o for o in bpy.data.objects if o.type == "CURVE"] + if curves: + bpy.ops.object.select_all(action="DESELECT") + for c in curves: + c.select_set(True) + view_layer.objects.active = curves[0] + bpy.ops.object.convert(target="MESH") + + +def _normalize_materials_for_gltf() -> None: + """Replace linked procedural shader trees with clean flat Principled BSDF PBR values.""" + vc.ensure_materials() + pal_map = { + "armour": "olive_armor", + "armor": "olive_armor", + "olive": "olive_armor", + "khaki": "olive_armor", + "metal": "gunmetal", + "gunmetal": "gunmetal", + "machine": "gunmetal", + "rubber": "rubber_dark", + "hazard": "signal_orange", + "brass": "copper_rad", + "copper": "copper_rad", + "glass": "smoked_glass", + "optic": "smoked_glass", + "pit": "socket_bay", + } + for mat in list(bpy.data.materials): + if mat.name in vc.PALETTE or not mat.use_nodes or not mat.node_tree: + continue + nt = mat.node_tree + bsdf = next((n for n in nt.nodes if n.type == "BSDF_PRINCIPLED"), None) + if bsdf is None: + continue + lname = mat.name.lower() + + # Extract Group node overrides if authored by Brokkr paint_pinned + grp = next((n for n in nt.nodes if n.type == "GROUP"), None) + base_col = None + cover_col = None + cover_amt = 0.0 + metallic = None + roughness = None + if grp is not None: + if "Base Color" in grp.inputs and hasattr(grp.inputs["Base Color"], "default_value"): + base_col = tuple(grp.inputs["Base Color"].default_value) + if "Cover Color" in grp.inputs and hasattr(grp.inputs["Cover Color"], "default_value"): + cover_col = tuple(grp.inputs["Cover Color"].default_value) + if "Cover" in grp.inputs and hasattr(grp.inputs["Cover"], "default_value"): + cover_amt = float(grp.inputs["Cover"].default_value) + if "Metallic" in grp.inputs and hasattr(grp.inputs["Metallic"], "default_value"): + metallic = float(grp.inputs["Metallic"].default_value) + if "Roughness" in grp.inputs and hasattr(grp.inputs["Roughness"], "default_value"): + roughness = float(grp.inputs["Roughness"].default_value) + + # Fallback to matching shared RTD palette entry for linked/procedural mats + matched_pal = None + for key, pal_name in pal_map.items(): + if key in lname: + matched_pal = vc.PALETTE[pal_name] + break + + # Clear links on Principled BSDF and reset overrides (e.g. Emission/Transmission) + for inp in bsdf.inputs: + for lk in list(inp.links): + nt.links.remove(lk) + if "Emission Strength" in bsdf.inputs: + bsdf.inputs["Emission Strength"].default_value = 0.0 + if "Emission Color" in bsdf.inputs: + bsdf.inputs["Emission Color"].default_value = (0.0, 0.0, 0.0, 1.0) + if "Transmission Weight" in bsdf.inputs: + bsdf.inputs["Transmission Weight"].default_value = 0.0 + if "Coat Weight" in bsdf.inputs: + bsdf.inputs["Coat Weight"].default_value = 0.0 + + if "glow_blue" in lname: + bsdf.inputs["Base Color"].default_value = vc.srgb_hex_to_linear("#38c9d8") + bsdf.inputs["Roughness"].default_value = 0.20 + bsdf.inputs["Emission Color"].default_value = vc.srgb_hex_to_linear("#38c9d8") + bsdf.inputs["Emission Strength"].default_value = 2.4 + elif any(k in lname for k in ("lamp", "glow", "amber")): + col = vc.srgb_hex_to_linear("#ff9f2e") + bsdf.inputs["Base Color"].default_value = col + bsdf.inputs["Roughness"].default_value = 0.20 + bsdf.inputs["Emission Color"].default_value = col + bsdf.inputs["Emission Strength"].default_value = 2.2 + elif "steel" in lname: + bsdf.inputs["Base Color"].default_value = (0.58, 0.60, 0.62, 1.0) + bsdf.inputs["Metallic"].default_value = 0.94 + bsdf.inputs["Roughness"].default_value = 0.22 + elif "optic_red" in lname: + bsdf.inputs["Base Color"].default_value = (0.14, 0.02, 0.015, 1.0) + bsdf.inputs["Metallic"].default_value = 0.0 + bsdf.inputs["Roughness"].default_value = 0.15 + if "Emission Color" in bsdf.inputs: + bsdf.inputs["Emission Color"].default_value = (1.0, 0.08, 0.03, 1.0) + if "Emission Strength" in bsdf.inputs: + bsdf.inputs["Emission Strength"].default_value = 1.6 + elif "warhead" in lname: + bsdf.inputs["Base Color"].default_value = (0.28, 0.10, 0.06, 1.0) + bsdf.inputs["Metallic"].default_value = 0.35 + bsdf.inputs["Roughness"].default_value = 0.45 + elif "mark" in lname: + bsdf.inputs["Base Color"].default_value = cover_col if (cover_col is not None and cover_amt >= 0.5) else (0.48, 0.46, 0.42, 1.0) + bsdf.inputs["Metallic"].default_value = 0.0 + bsdf.inputs["Roughness"].default_value = roughness if roughness is not None else 0.72 + elif matched_pal is not None: + bsdf.inputs["Base Color"].default_value = vc.srgb_hex_to_linear(matched_pal["hex"]) + bsdf.inputs["Metallic"].default_value = float(matched_pal["metallic"]) + bsdf.inputs["Roughness"].default_value = float(matched_pal["roughness"]) + if "alpha" in matched_pal: + bsdf.inputs["Alpha"].default_value = float(matched_pal["alpha"]) + if hasattr(mat, "blend_method"): + mat.blend_method = "BLEND" + elif base_col is not None: + bsdf.inputs["Base Color"].default_value = base_col + if metallic is not None: + bsdf.inputs["Metallic"].default_value = metallic + if roughness is not None: + bsdf.inputs["Roughness"].default_value = roughness + + +def _mesh_tri_count(obj: bpy.types.Object) -> int: + obj.data.calc_loop_triangles() + return len(obj.data.loop_triangles) + + +def _apply_crisp_normals_and_decimate(obj: bpy.types.Object, ratio: float) -> int: + view_layer = bpy.context.view_layer + if obj.data.users > 1: + obj.data = obj.data.copy() + bpy.ops.object.select_all(action="DESELECT") + obj.select_set(True) + view_layer.objects.active = obj + + if ratio < 0.99: + mod = obj.modifiers.new("LOD_Decimate", "DECIMATE") + mod.decimate_type = "COLLAPSE" + mod.ratio = ratio + mod.use_collapse_triangulate = True + if len(obj.modifiers) > 1: + bpy.ops.object.modifier_move_to_index(modifier=mod.name, index=0) + bpy.ops.object.modifier_apply(modifier=mod.name) + + # Split sharp armor edges (>36 deg) so decimated bevel corners never look pillowed + es = obj.modifiers.new("LOD_EdgeSplit", "EDGE_SPLIT") + es.use_edge_angle = True + es.split_angle = math.radians(36.0) + es.use_edge_sharp = True + if len(obj.modifiers) > 1: + bpy.ops.object.modifier_move_to_index(modifier=es.name, index=0) + bpy.ops.object.modifier_apply(modifier=es.name) + obj.data.validate(verbose=False) + obj.data.update() + return _mesh_tri_count(obj) + + +def _decimate_mech_meshes(meshes: list[bpy.types.Object], target_tris: int, min_keep_tris: int = 48) -> tuple[int, int]: + """Decimate mech meshes adaptively to target_tris while keeping armor plates crisp and spike-free.""" + tri_counts = [_mesh_tri_count(o) for o in meshes] + raw_total = sum(tri_counts) + if raw_total == 0: + return 0, 0 + + # Single-mesh rigged path (e.g. breaker.mesh) -> modifier_apply preserves armature + skinning + if len(meshes) == 1: + obj = meshes[0] + ratio = max(0.02, min(1.0, target_tris / raw_total)) + after = _apply_crisp_normals_and_decimate(obj, ratio) + return raw_total, after + + min_main_ratio = 0.125 if raw_total > 150000 else 0.20 + + def _target_for(obj: bpy.types.Object, t: int, k_val: float) -> int: + if t <= min_keep_tris: + return t + is_detail = ( + obj.name.startswith("Foot") + or ".Foot" in obj.name + or ".fit." in obj.name + or ".ferrules" in obj.name + or ".panels" in obj.name + ) + if is_detail: + return max(24, int(round(t * max(k_val * 0.50, 0.06)))) + if t <= 220: + return max(min(t, 44), int(round(t * max(k_val, 0.28)))) + return max(84, int(round(t * max(k_val, min_main_ratio)))) + + if raw_total <= target_tris: + k = 1.0 + else: + lo, hi = 0.10, 1.0 + for _ in range(28): + mid = 0.5 * (lo + hi) + est = sum(_target_for(obj, t, mid) for obj, t in zip(meshes, tri_counts)) + if est > target_tris: + hi = mid + else: + lo = mid + k = 0.5 * (lo + hi) + + # Queue DECIMATE + EDGE_SPLIT on all objects, then evaluate in one depsgraph pass + for obj, t in zip(meshes, tri_counts): + tgt = _target_for(obj, t, k) + if tgt < t: + ratio = max(0.08, min(1.0, tgt / t)) + if ratio < 0.99: + mod = obj.modifiers.new("LOD_Decimate", "DECIMATE") + mod.decimate_type = "COLLAPSE" + mod.ratio = ratio + mod.use_collapse_triangulate = True + es = obj.modifiers.new("LOD_EdgeSplit", "EDGE_SPLIT") + es.use_edge_angle = True + es.split_angle = math.radians(36.0) + es.use_edge_sharp = True + + depsgraph = bpy.context.evaluated_depsgraph_get() + after_total = 0 + for obj in meshes: + ev = obj.evaluated_get(depsgraph) + new_mesh = bpy.data.meshes.new_from_object(ev, preserve_all_data_layers=True, depsgraph=depsgraph) + new_mesh.name = f"{obj.name}_lod" + new_mesh.validate(verbose=False) + obj.modifiers.clear() + obj.data = new_mesh + after_total += _mesh_tri_count(obj) + + return raw_total, after_total + + +def _collect_subtree_meshes(root_obj: bpy.types.Object) -> list[bpy.types.Object]: + out: list[bpy.types.Object] = [] + def walk(obj: bpy.types.Object) -> None: + if obj.name.startswith("slot_frame."): + return + if obj.type == "MESH" and obj.data is not None and len(obj.data.polygons) > 0: + out.append(obj) + for ch in obj.children: + walk(ch) + walk(root_obj) + return out + + +def _build_hull_bvh(mesh_objs: list[bpy.types.Object]) -> BVHTree | None: + if not mesh_objs: + return None + depsgraph = bpy.context.evaluated_depsgraph_get() + bm = bmesh.new() + for obj in mesh_objs: + ev = obj.evaluated_get(depsgraph) + me = ev.to_mesh() + if me is not None and len(me.polygons) > 0: + me.transform(obj.matrix_world) + bm.from_mesh(me) + ev.to_mesh_clear() + if len(bm.verts) == 0 or len(bm.faces) == 0: + bm.free() + return None + bvh = BVHTree.FromBMesh(bm) + bm.free() + return bvh + + +def _snap_hardpoint_bvh( + hp: HardpointMount, + parent_obj: bpy.types.Object, + root_obj: bpy.types.Object, + full_bvh: BVHTree, + bvh_cache: dict[str, BVHTree], +) -> tuple[Vector, float, tuple[float, float, float]]: + """Snap hardpoint anchor onto actual hull surface via 5-point BVH raycast + recessed plinth.""" + bvh = full_bvh + if parent_obj != root_obj and hp.parent_bone is None: + if parent_obj.name not in bvh_cache: + sub_meshes = _collect_subtree_meshes(parent_obj) + sub_bvh = _build_hull_bvh(sub_meshes) + if sub_bvh is not None: + bvh_cache[parent_obj.name] = sub_bvh + bvh = bvh_cache.get(parent_obj.name, full_bvh) + + p0 = Vector(hp.world_pos) + n = Vector(hp.world_normal).normalized() + q = Vector((0.0, 0.0, 1.0)).rotation_difference(n) + tu = q @ Vector((1.0, 0.0, 0.0)) + tv = q @ Vector((0.0, 1.0, 0.0)) + + sx, sy, sz = hp.size + if hp.kind == "weapon": + r = min(sx, sy) * 0.48 * 0.78 + rx, ry = r, r + elif hp.kind == "armor": + rx, ry = sx * 0.38, sy * 0.14 + else: + rx, ry = sx * 0.38, sy * 0.38 + + offsets = [(0.0, 0.0), (-rx, -ry), (rx, -ry), (rx, ry), (-rx, ry)] + raw_hits: list[float | None] = [] + for ox, oy in offsets: + pt = p0 + tu * ox + tv * oy + # Cast from +1.5m along +normal toward -normal; guard against far overhang hits by also trying +0.55m + loc, _, _, _ = bvh.ray_cast(pt + n * 0.65, -n, 1.35) + if loc is None: + loc, _, _, _ = bvh.ray_cast(pt + n * 1.5, -n, 3.0) + raw_hits.append((loc - p0).dot(n) if loc is not None else None) + + h_center = raw_hits[0] + if h_center is None: + near_loc, _, _, _ = bvh.find_nearest(p0) + if near_loc is not None: + h_center = (near_loc - p0).dot(n) + else: + h_center = 0.0 + # Guard against thin lifting-eye/antenna spikes lifting the entire base off the armor roof + corner_vals = sorted(h for h in raw_hits[1:] if h is not None) + if len(corner_vals) >= 3: + c_med = corner_vals[len(corner_vals) // 2] + if h_center - c_med > 0.08: + tight_hits: list[float] = [] + for tx, ty in ((-0.07, 0.0), (0.07, 0.0), (0.0, -0.07), (0.0, 0.07)): + t_loc, _, _, _ = bvh.ray_cast(p0 + tu * tx + tv * ty + n * 0.65, -n, 1.35) + if t_loc is not None: + tight_hits.append((t_loc - p0).dot(n)) + t_med = sorted(tight_hits)[len(tight_hits) // 2] if tight_hits else h_center + if h_center - t_med > 0.06: + h_center = c_med + + # Keep corner hits near the local surface patch; replace misses/cliffs with nearest or conservative drop + valid_corners: list[float] = [h_center] + misses = 0 + for idx, h in enumerate(raw_hits[1:], start=1): + if h is None or abs(h - h_center) > 0.18: + misses += 1 + ox, oy = offsets[idx] + near_loc, _, _, _ = bvh.find_nearest(p0 + tu * ox + tv * oy + n * h_center) + if near_loc is not None: + hn = (near_loc - p0).dot(n) + if abs(hn - h_center) <= 0.18: + valid_corners.append(hn) + continue + valid_corners.append(h_center - 0.035) + else: + valid_corners.append(h) + + h_min = min(valid_corners) + h_max = max(valid_corners) + # Seat bay origin recessed into surface at center (<= 0.022m from surface so verify_glbs passes) + # while extending plinth down past h_min and keeping rim proud above h_max + h_seat = h_center - 0.020 + if h_max - h_seat > sz * 0.55: + sz_out = max(sz, (h_max - h_seat) + 0.055) + else: + sz_out = sz + plinth_depth = max(0.050, min(0.18, (h_seat - h_min) + 0.045)) + snapped_pos = p0 + n * h_seat + print( + f" [snap] {hp.hp_id:22s} | dh_c={h_center:+.3f} span=[{h_min:+.3f},{h_max:+.3f}] " + f"seat={h_seat:+.3f} plinth={plinth_depth:.3f} miss={misses}" + ) + return snapped_pos, plinth_depth, (sx, sy, sz_out) + + +def _attach_hardpoint_world( + hp: HardpointMount, + root_obj: bpy.types.Object, + full_bvh: BVHTree, + bvh_cache: dict[str, BVHTree], +) -> None: + parent_obj = root_obj if hp.parent_name == "_ROOT_" else bpy.data.objects[hp.parent_name] + snapped_pos, plinth_depth, adj_size = _snap_hardpoint_bvh(hp, parent_obj, root_obj, full_bvh, bvh_cache) + anchor = vc.add_hardpoint_slot( + hp.hp_id, + hp.kind, + parent=parent_obj, + location=(0.0, 0.0, 0.0), + rotation_deg=(0.0, 0.0, 0.0), + size=adj_size, + plinth_depth=plinth_depth, + ) + bay_root = anchor.parent + if hp.parent_bone is not None: + bay_root.parent_type = "BONE" + bay_root.parent_bone = hp.parent_bone + + bpy.context.view_layer.update() + n = Vector(hp.world_normal).normalized() + q = Vector((0.0, 0.0, 1.0)).rotation_difference(n) + m_world = Matrix.Translation(snapped_pos) @ q.to_matrix().to_4x4() + + if hp.parent_bone is not None and parent_obj.type == "ARMATURE": + pb = parent_obj.pose.bones[hp.parent_bone] + # Blender bone parenting attaches at the pose bone tail with bone axes + bone_tail_mat = parent_obj.matrix_world @ pb.matrix @ Matrix.Translation((0.0, pb.length, 0.0)) + m_local = bone_tail_mat.inverted() @ m_world + else: + m_local = parent_obj.matrix_world.inverted() @ m_world + + loc, rot, _ = m_local.decompose() + bay_root.location = loc + bay_root.rotation_mode = "XYZ" + bay_root.rotation_euler = rot.to_euler("XYZ") + + +def _apply_joint_tags(spec: MechRetrofitSpec) -> list[dict[str, Any]]: + joints_manifest: list[dict[str, Any]] = [] + for j in spec.joints: + target = bpy.data.objects[j.target_name] + if j.parent_bone is not None and target.type == "ARMATURE": + node = vc.make_empty(j.joint_id, parent=target, display_size=0.16) + node.parent_type = "BONE" + node.parent_bone = j.parent_bone + bpy.context.view_layer.update() + pb = target.pose.bones[j.parent_bone] + bone_head_w = target.matrix_world @ pb.head + bone_tail_mat = target.matrix_world @ pb.matrix @ Matrix.Translation((0.0, pb.length, 0.0)) + m_local = bone_tail_mat.inverted() @ Matrix.Translation(bone_head_w) + node.location = m_local.to_translation() + else: + node = target + vc.tag_joint(node, j.joint_id, j.axis_gltf, j.min_val, j.max_val) + joints_manifest.append({ + "id": j.joint_id, + "axis": [float(v) for v in j.axis_gltf], + "min": float(j.min_val), + "max": float(j.max_val), + }) + return joints_manifest + + +def _brokkr_vec_to_gltf(v: list[float], ground_z_shift: float = 0.0) -> list[float]: + """Convert raw Brokkr Blender (+Y fwd, -X left, +Z up) after 180 deg Z rot to glTF (+Z fwd, +X left, +Y up).""" + return [round(-float(v[0]), 6), round(float(v[2]) + ground_z_shift, 6), round(float(v[1]), 6)] + + +def _brokkr_dir_to_gltf(v: list[float]) -> list[float]: + return [round(-float(v[0]), 6), round(float(v[2]), 6), round(float(v[1]), 6)] + + +def _extract_mechanisms(model_json_path: Path, ground_z_shift: float = 0.0) -> dict[str, Any]: + raw = json.loads(model_json_path.read_text(encoding="utf-8")) + dofs_out = [] + for d in raw.get("dofs", []): + entry = { + "name": d["name"], + "parent": d["parent"], + "kind": d["kind"], + "mechanism": d.get("mechanism"), + "side": d.get("side"), + "origin": _brokkr_vec_to_gltf(d["origin"], ground_z_shift), + "axis": _brokkr_dir_to_gltf(d["axis"]), + "lo": d["lo"], + "hi": d["hi"], + "depth": d["depth"], + } + if "compliance" in d: + entry["compliance"] = d["compliance"] + if "stopped_by" in d: + entry["stopped_by"] = d["stopped_by"] + dofs_out.append(entry) + + points_raw = raw.get("points", {}) + dirs_raw = raw.get("dirs", {}) + rams_out = [] + for r in raw.get("rams", []): + pt_a = points_raw.get(r["a"]) + pt_b = points_raw.get(r["b"]) + dir_pin = dirs_raw.get(r["pin"]) + rams_out.append({ + "name": r["name"], + "barrel_bone": r["barrel_bone"], + "rod_bone": r["rod_bone"], + "spans": r.get("spans", []), + "bore": r.get("bore"), + "body": r.get("body"), + "inner": r.get("inner"), + "extension": r.get("extension"), + "rest": r.get("rest"), + "stroke": r.get("stroke"), + "a_parent_dof": pt_a[0] if pt_a else None, + "a_pos": _brokkr_vec_to_gltf(pt_a[1], ground_z_shift) if pt_a else None, + "b_parent_dof": pt_b[0] if pt_b else None, + "b_pos": _brokkr_vec_to_gltf(pt_b[1], ground_z_shift) if pt_b else None, + "pin_dir": _brokkr_dir_to_gltf(dir_pin[1]) if dir_pin else None, + }) + + scissors_out = [] + for s in raw.get("scissors", []): + pt_a = points_raw.get(s["a"]) + pt_b = points_raw.get(s["b"]) + dir_out = dirs_raw.get(s["out"]) + scissors_out.append({ + "name": s["name"], + "upper_bone": s["upper_bone"], + "lower_bone": s["lower_bone"], + "arm": s.get("arm"), + "a_parent_dof": pt_a[0] if pt_a else None, + "a_pos": _brokkr_vec_to_gltf(pt_a[1], ground_z_shift) if pt_a else None, + "b_parent_dof": pt_b[0] if pt_b else None, + "b_pos": _brokkr_vec_to_gltf(pt_b[1], ground_z_shift) if pt_b else None, + "out_dir": _brokkr_dir_to_gltf(dir_out[1]) if dir_out else None, + }) + + struts_out = [ + { + "name": st["name"], + "side": st.get("side"), + "dof": st["dof"], + "travel": st["travel"], + "hertz": st["hertz"], + "damping_ratio": st["damping_ratio"], + } + for st in raw.get("struts", []) + ] + + return { + "frame": "gltf (+Y up, +Z forward, +X left, meters)", + "rootOrigin": _brokkr_vec_to_gltf(raw.get("root", [0.0, 0.0, 0.0]), ground_z_shift), + "dofs": dofs_out, + "rams": rams_out, + "scissors": scissors_out, + "struts": struts_out, + } + + +def _extract_mechanisms_from_blend_raw(root_name: str = "Pelvis") -> dict[str, Any] | None: + """Extract raw Brokkr-frame DOFs, hydraulic rams, torque scissors, and oleo struts from kit_* props.""" + root_obj = bpy.data.objects.get(root_name) + if root_obj is None or "kit_part" not in root_obj: + return None + bpy.context.view_layer.update() + + def _side_of(name: str) -> str: + for tag, s in (("LegL", "L"), ("LegR", "R")): + if name.startswith(tag): + return s + base = name.split(".")[0] + if base.endswith("L"): + return "L" + if base.endswith("R"): + return "R" + return "" + + limits_deg = { + "hip": (-60.0, 60.0), "hip yaw": (-35.0, 35.0), "knee": (-100.0, 100.0), + "ankle": (-40.0, 40.0), "waist": (-110.0, 110.0), "shoulder slew": (-100.0, 100.0), + "shoulder hinge": (-45.0, 45.0), "arm twist": (-90.0, 90.0), "elbow": (-100.0, 100.0), + "hinge": (-60.0, 60.0), "slew": (-90.0, 90.0), + } + + dofs_raw: list[dict[str, Any]] = [] + obj_to_dof: dict[str, int] = {} + + def walk(obj: bpy.types.Object, parent_dof: int, depth: int) -> None: + here = parent_dof + here_depth = depth + if obj != root_obj and "kit_socket" in obj and obj.get("kit_part") != "ram" and obj.parent is not None and "kit_part" in obj.parent: + part = str(obj["kit_part"]) + ppart = str(obj.parent["kit_part"]) + psock = str(obj.get("kit_parent_socket", "")) + kind: str | None = None + if ppart == "slew_ring" and psock == "top": + kind = "slew" + elif str(obj.get("kit_mechanism", "")) == "oleo": + kind = "slide" + elif psock == "clevis": + kind = "hinge" + if kind is not None: + if kind == "slew": + # Slew axis is the parent slew_ring's Z axis at the top socket + origin_v = obj.parent.matrix_world.translation.copy() + axis_v = obj.parent.matrix_world.to_3x3().col[2].normalized() + else: + origin_v = obj.matrix_world.translation.copy() + axis_v = obj.matrix_world.to_3x3().col[2].normalized() + + grand = obj.parent.parent.get("kit_part", "") if obj.parent.parent else "" + if kind == "slide": + mech = str(obj.get("kit_mechanism", "oleo")) + val = float(obj.get("kit_slide", 0.0)) + lo = float(obj.get("kit_min", 0.0)) - val + hi = float(obj.get("kit_max", 0.2)) - val + elif kind == "slew": + mech = ( + "hip" if part in ("thigh", "hip_stub") + else "hip yaw" if part == "shank" + else "waist" if part == "chassis" + else ("shoulder slew" if grand == "chassis" else "arm twist") if part == "yoke" + else "slew" + ) + lo, hi = (math.radians(v) for v in limits_deg[mech]) + else: + if "kit_min" in obj and obj.get("kit_mechanism"): + mech = str(obj["kit_mechanism"]).replace("_", " ") + roll = float(obj.get("kit_roll", 0.0)) + lo = math.radians(float(obj["kit_min"]) - roll) + hi = math.radians(float(obj["kit_max"]) - roll) + else: + if part in ("foot", "foot_core"): + mech = "ankle" + elif part in ("link", "strut_shin"): + mech = "knee" + elif part == "wrist": + up_m = dofs_raw[parent_dof]["mechanism"] if parent_dof >= 0 else "" + mech = "shoulder hinge" if up_m == "shoulder slew" else "elbow" if up_m == "arm twist" else "hinge" + else: + mech = "hinge" + lo, hi = (math.radians(v) for v in limits_deg[mech]) + + entry: dict[str, Any] = { + "name": obj.name, + "parent": parent_dof, + "kind": kind, + "mechanism": mech, + "side": _side_of(obj.name), + "origin": [float(origin_v.x), float(origin_v.y), float(origin_v.z)], + "axis": [float(axis_v.x), float(axis_v.y), float(axis_v.z)], + "lo": float(lo), + "hi": float(hi), + "depth": depth, + } + if obj.get("kit_compliance"): + entry["compliance"] = json.loads(str(obj["kit_compliance"])) + if mech == "ankle": + entry["stopped_by"] = "ram" + here = len(dofs_raw) + here_depth = depth + 1 + dofs_raw.append(entry) + obj_to_dof[obj.name] = here + for ch in obj.children: + walk(ch, here, here_depth) + + walk(root_obj, -1, 0) + + rams_raw: list[dict[str, Any]] = [] + for obj in sorted(bpy.data.objects, key=lambda o: o.name): + if obj.get("kit_part") != "ram" or obj.parent is None: + continue + raw_close = obj.get("kit_close_to") + if raw_close is None: + continue + close_to = ( + raw_close + if isinstance(raw_close, bpy.types.Object) + else bpy.data.objects.get(raw_close.name if hasattr(raw_close, "name") else str(raw_close)) + ) + if close_to is None: + continue + params = json.loads(str(obj.get("kit_params", "{}"))) + lug_b_params = json.loads(str(close_to.get("kit_params", "{}"))) + a_pos = obj.matrix_world.translation.copy() + # Lug pivot sits at local (0, 0, height) + b_h = float(lug_b_params.get("height", 0.234)) + b_pos = close_to.matrix_world @ Vector((0.0, 0.0, b_h)) + rest = float((b_pos - a_pos).length) + pin_dir = obj.parent.matrix_world.to_3x3().col[0].normalized() + body = float(params.get("body_len", 0.68)) + ext = float(params.get("extension", 0.40)) + a_dof = obj_to_dof.get(obj.parent.name, -1) + b_dof = obj_to_dof.get(close_to.name, -1) + rams_raw.append({ + "name": obj.name, + "barrel_bone": f"{obj.name}.barrel", + "rod_bone": f"{obj.name}.rod", + "spans": [dofs_raw[i]["name"] for i in (a_dof + 1, b_dof) if 0 <= i < len(dofs_raw)], + "bore": float(params.get("bore_r", 0.09)), + "body": body, + "inner": rest - body * 0.85, + "extension": ext, + "rest": rest, + "stroke": [-ext, max(0.2, body - 0.15)], + "a_parent_dof": a_dof, + "a_pos": [float(a_pos.x), float(a_pos.y), float(a_pos.z)], + "b_parent_dof": b_dof, + "b_pos": [float(b_pos.x), float(b_pos.y), float(b_pos.z)], + "pin_dir": [float(pin_dir.x), float(pin_dir.y), float(pin_dir.z)], + }) + + scissors_raw: list[dict[str, Any]] = [] + for sc in json.loads(str(bpy.context.scene.get("mech_scissors", "[]"))): + oa = bpy.data.objects.get(sc["a"][0]) + ob = bpy.data.objects.get(sc["b"][0]) + oo = bpy.data.objects.get(sc["out"][0]) + if oa is None or ob is None or oo is None: + continue + pa = oa.matrix_world @ Vector(sc["a"][1]) + pb = ob.matrix_world @ Vector(sc["b"][1]) + dout = (oo.matrix_world.to_3x3() @ Vector(sc["out"][1])).normalized() + scissors_raw.append({ + "name": sc["name"], + "upper_bone": f"{sc['name']}.upper", + "lower_bone": f"{sc['name']}.lower", + "arm": float(sc["arm"]), + "a_parent_dof": obj_to_dof.get(oa.name, -1), + "a_pos": [float(pa.x), float(pa.y), float(pa.z)], + "b_parent_dof": obj_to_dof.get(ob.name, -1), + "b_pos": [float(pb.x), float(pb.y), float(pb.z)], + "out_dir": [float(dout.x), float(dout.y), float(dout.z)], + }) + + struts_raw = [ + { + "name": d["name"], + "side": d["side"], + "dof": d["name"], + "travel": round(abs(d["hi"] - d["lo"]), 6), + "hertz": float(d["compliance"]["hertz"]), + "damping_ratio": float(d["compliance"]["damping_ratio"]), + } + for d in dofs_raw + if d.get("mechanism") == "oleo" and "compliance" in d + ] + + r_pos = root_obj.matrix_world.translation + return { + "root": [float(r_pos.x), float(r_pos.y), float(r_pos.z)], + "dofs": dofs_raw, + "rams": rams_raw, + "scissors": scissors_raw, + "struts": struts_raw, + } + + +def _finalize_mechanisms_gltf(raw: dict[str, Any], ground_z_shift: float) -> dict[str, Any]: + dofs_out = [] + for d in raw["dofs"]: + entry = { + **d, + "origin": _brokkr_vec_to_gltf(d["origin"], ground_z_shift), + "axis": _brokkr_dir_to_gltf(d["axis"]), + } + dofs_out.append(entry) + rams_out = [ + { + **r, + "a_pos": _brokkr_vec_to_gltf(r["a_pos"], ground_z_shift), + "b_pos": _brokkr_vec_to_gltf(r["b_pos"], ground_z_shift), + "pin_dir": _brokkr_dir_to_gltf(r["pin_dir"]), + } + for r in raw["rams"] + ] + scissors_out = [ + { + **s, + "a_pos": _brokkr_vec_to_gltf(s["a_pos"], ground_z_shift), + "b_pos": _brokkr_vec_to_gltf(s["b_pos"], ground_z_shift), + "out_dir": _brokkr_dir_to_gltf(s["out_dir"]), + } + for s in raw["scissors"] + ] + return { + "frame": "gltf (+Y up, +Z forward, +X left, meters)", + "rootOrigin": _brokkr_vec_to_gltf(raw["root"], ground_z_shift), + "dofs": dofs_out, + "rams": rams_out, + "scissors": scissors_out, + "struts": raw["struts"], + } + + +def _finalize_shroud_obj(obj: bpy.types.Object, bevel: float = 0.010) -> bpy.types.Object: + """Apply crisp hard-surface bevel + 36-deg edge split and bake to clean mesh.""" + if bevel > 0.0: + bv = obj.modifiers.new("Shroud_Bevel", "BEVEL") + bv.width = float(bevel) + bv.segments = 1 + bv.limit_method = "ANGLE" + bv.angle_limit = math.radians(30.0) + bv.harden_normals = False + es = obj.modifiers.new("Shroud_EdgeSplit", "EDGE_SPLIT") + es.use_edge_angle = True + es.split_angle = math.radians(36.0) + es.use_edge_sharp = True + depsgraph = bpy.context.evaluated_depsgraph_get() + ev = obj.evaluated_get(depsgraph) + new_mesh = bpy.data.meshes.new_from_object(ev, preserve_all_data_layers=True, depsgraph=depsgraph) + new_mesh.name = f"{obj.name}_mesh" + new_mesh.validate(verbose=False) + obj.modifiers.clear() + obj.data = new_mesh + return obj + + +def _make_loft_shroud( + name: str, + rings: list[list[Vector]], + parent: bpy.types.Object, + mat_name: str = "olive_armor", + bevel: float = 0.010, +) -> bpy.types.Object: + """Loft a closed manifold hard-surface armor shell across multi-station 3D rings in parent local space.""" + assert len(rings) >= 2 and all(len(r) == len(rings[0]) for r in rings) + m = len(rings[0]) + bm = bmesh.new() + bm_rings: list[list[bmesh.types.BMVert]] = [ + [bm.verts.new(tuple(float(c) for c in pt)) for pt in ring] + for ring in rings + ] + bm.verts.ensure_lookup_table() + for i in range(len(bm_rings) - 1): + r0, r1 = bm_rings[i], bm_rings[i + 1] + for j in range(m): + jn = (j + 1) % m + bm.faces.new((r0[j], r0[jn], r1[jn], r1[j])) + bm.faces.new(list(reversed(bm_rings[0]))) + bm.faces.new(bm_rings[-1]) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces) + mesh = bpy.data.meshes.new(name) + bm.to_mesh(mesh) + bm.free() + obj = bpy.data.objects.new(name, mesh) + vc._assign_material(obj, mat_name) + vc._link_object(obj, parent=parent, location=(0.0, 0.0, 0.0), rotation_deg=(0.0, 0.0, 0.0)) + return _finalize_shroud_obj(obj, bevel=bevel) + + +def _make_chamfer_box_shroud( + name: str, + x0: float, + x1: float, + y0: float, + y1: float, + z0: float, + z1: float, + parent: bpy.types.Object, + mat_name: str = "olive_armor", + chamfer: float = 0.035, + top_taper_xy: tuple[float, float] = (1.0, 1.0), + bevel: float = 0.010, +) -> bpy.types.Object: + """Create a tapered octagonal-section armor plate spanning [x0..x1] x [y0..y1] x [z0..z1].""" + cx, cy = 0.5 * (x0 + x1), 0.5 * (y0 + y1) + hx, hy = 0.5 * abs(x1 - x0), 0.5 * abs(y1 - y0) + c = min(chamfer, hx * 0.42, hy * 0.42) + + def _ring(z_val: float, sx: float, sy: float) -> list[Vector]: + rx, ry = hx * sx, hy * sy + cc = min(c, rx * 0.45, ry * 0.45) + pts = [ + (cx - rx + cc, cy - ry), + (cx + rx - cc, cy - ry), + (cx + rx, cy - ry + cc), + (cx + rx, cy + ry - cc), + (cx + rx - cc, cy + ry), + (cx - rx + cc, cy + ry), + (cx - rx, cy + ry - cc), + (cx - rx, cy - ry + cc), + ] + return [Vector((px, py, z_val)) for px, py in pts] + + tx, ty = top_taper_xy + rings = [_ring(z0, 1.0, 1.0), _ring(z1, tx, ty)] + return _make_loft_shroud(name, rings, parent=parent, mat_name=mat_name, bevel=bevel) + + +def _make_arc_fender( + name: str, + center: Vector, + axis: Vector, + fwd_dir: Vector, + up_dir: Vector, + r_in: float, + r_out: float, + half_w: float, + ang_start_deg: float, + ang_end_deg: float, + steps: int, + parent: bpy.types.Object, + mat_name: str = "olive_armor", + end_taper_w: float = 0.84, + bevel: float = 0.010, +) -> bpy.types.Object: + """Sweep a beveled armored fender arch around a cylindrical drum (0 deg = fwd_dir, 90 deg = up_dir).""" + ax = axis.normalized() + fd = fwd_dir.normalized() + ud = up_dir.normalized() + rings: list[list[Vector]] = [] + for k in range(steps + 1): + u = k / steps + ang = math.radians(ang_start_deg + (ang_end_deg - ang_start_deg) * u) + radial = fd * math.cos(ang) + ud * math.sin(ang) + # Slightly pinch width and thickness at the very ends for Brokkr fender silhouette + edge_fac = 1.0 - (1.0 - end_taper_w) * (abs(2.0 * u - 1.0) ** 2) + hw = half_w * edge_fac + hw_outer = hw * 0.86 + r_mid = r_in + (r_out - r_in) * 0.65 + pts = [ + center + radial * r_in - ax * hw, + center + radial * r_in + ax * hw, + center + radial * r_mid + ax * hw, + center + radial * r_out + ax * hw_outer, + center + radial * r_out - ax * hw_outer, + center + radial * r_mid - ax * hw, + ] + rings.append(pts) + return _make_loft_shroud(name, rings, parent=parent, mat_name=mat_name, bevel=bevel) + + +def _obj_bounds_in_ref(obj_names: list[str], ref_obj: bpy.types.Object, z_filter: tuple[float, float] | None = None) -> tuple[Vector, Vector] | None: + """Measure combined world vertices of named objects transformed into ref_obj local space.""" + inv_ref = ref_obj.matrix_world.inverted() + pts: list[Vector] = [] + for nm in obj_names: + o = bpy.data.objects.get(nm) + if o is None or o.type != "MESH" or o.data is None: + continue + mw = o.matrix_world + for v in o.data.vertices: + pw = mw @ v.co + if z_filter is not None and not (z_filter[0] <= pw.z <= z_filter[1]): + continue + pts.append(inv_ref @ pw) + if not pts: + return None + bmin = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts))) + bmax = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts))) + return bmin, bmax + + +def _add_kestrel_shrouds() -> list[bpy.types.Object]: + created: list[bpy.types.Object] = [] + torso = bpy.data.objects.get("Torso.pose") + pelvis = bpy.data.objects.get("Pelvis") + if torso is None or pelvis is None: + return created + + # 1. Sloped hooded shoulder pauldrons over exposed ribbed shoulder drums (parented to Torso.pose) + # Linearly tapered stations keep top/flank quads planar for crisp panel shading. + for side, sx in (("L", -1.0), ("R", 1.0)): + stations_spec = [ + # (|x|, y_rear, y_front, z_low_rear, z_low_front, z_top_rear, z_top_front) + (1.20, 0.00, 1.24, 1.54, 1.54, 2.26, 2.18), + (1.52, 0.02, 1.22, 1.36, 1.42, 2.18, 2.10), + (1.86, 0.04, 1.19, 1.22, 1.30, 2.07, 2.00), + (2.16, 0.06, 1.16, 1.16, 1.24, 1.92, 1.86), + (2.30, 0.10, 1.10, 1.24, 1.30, 1.74, 1.69), + ] + rings: list[list[Vector]] = [] + for ax, yr, yf, zlr, zlf, ztr, ztf in stations_spec: + px = sx * ax + yc = 0.5 * (yr + yf) + pts = [ + Vector((px, yr, zlr)), + Vector((px, yr + 0.14, zlr)), + Vector((px, yr + 0.16, ztr - 0.18)), + Vector((px, yc, min(ztr, ztf) - 0.12)), + Vector((px, yf - 0.16, ztf - 0.18)), + Vector((px, yf - 0.14, zlf)), + Vector((px, yf, zlf)), + Vector((px, yf - 0.08, ztf)), + Vector((px, yc, max(ztr, ztf) + 0.04)), + Vector((px, yr + 0.08, ztr)), + ] + if sx < 0: + pts = list(reversed(pts)) + rings.append(pts) + created.append(_make_loft_shroud(f"Shroud.Kestrel.Pauldron{side}", rings, torso, "olive_armor", bevel=0.012)) + + # Gunmetal mounting flange bracket bridging inner shoulder cowl to drum core + created.append( + _make_arc_fender( + f"Shroud.Kestrel.PauldronFlange{side}", + center=Vector((sx * 1.38, 0.65, 1.50)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.49, + r_out=0.56, + half_w=0.10, + ang_start_deg=15.0, + ang_end_deg=165.0, + steps=6, + parent=torso, + mat_name="gunmetal", + end_taper_w=0.92, + bevel=0.008, + ) + ) + + # 2. Compact sloped hip-fender guards + outer drum caps over bare hip cylinders (parented to Pelvis) + created.append( + _make_arc_fender( + f"Shroud.Kestrel.HipFender{side}", + center=Vector((sx * 1.28, 0.0, 6.20)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.515, + r_out=0.60, + half_w=0.38, + ang_start_deg=-10.0, + ang_end_deg=158.0, + steps=8, + parent=pelvis, + mat_name="olive_armor", + end_taper_w=0.80, + bevel=0.010, + ) + ) + leg_thigh = bpy.data.objects.get(f"Leg{side}.Thigh") or pelvis + leg_shin = bpy.data.objects.get(f"Leg{side}.Shin") or pelvis + + # Outer hip drum shield cap (rotates with Leg{side}.Thigh) + hip_cap_rings: list[list[Vector]] = [] + for x_off, r in ((1.46, 0.36), (1.58, 0.36), (1.64, 0.25)): + px = sx * x_off + pts = [ + Vector((px, r * math.cos(math.radians(a)), 6.20 + r * math.sin(math.radians(a)))) + for a in range(0, 360, 45) + ] + if sx < 0: + pts = list(reversed(pts)) + hip_cap_rings.append(pts) + hip_cap = _make_loft_shroud(f"Shroud.Kestrel.HipCap{side}", hip_cap_rings, pelvis, "olive_armor", bevel=0.008) + if leg_thigh != pelvis: + bpy.context.view_layer.update() + _reparent_keep_world(hip_cap, leg_thigh) + created.append(hip_cap) + created.append( + _make_arc_fender( + f"Shroud.Kestrel.HipFlange{side}", + center=Vector((sx * 1.02, 0.0, 6.20)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.49, + r_out=0.54, + half_w=0.07, + ang_start_deg=-5.0, + ang_end_deg=162.0, + steps=7, + parent=pelvis, + mat_name="gunmetal", + end_taper_w=0.95, + bevel=0.006, + ) + ) + + # 4. Faceted knee caps + outer cheek shields over bare black knee drums (parented to Leg{side}.Shin) + knee_bounds = _obj_bounds_in_ref( + [f"LegJoints{side}Knee.gunmetal", f"LegJoints{side}.gunmetal"], + pelvis, + z_filter=(3.0, 4.4), + ) + if knee_bounds is not None: + kmin, kmax = knee_bounds + kcx = 0.5 * (kmin.x + kmax.x) + kcy = 0.5 * (kmin.y + kmax.y) + kcz = 0.5 * (kmin.z + kmax.z) + knee_shrouds: list[bpy.types.Object] = [] + knee_shrouds.append( + _make_arc_fender( + f"Shroud.Kestrel.KneeCap{side}", + center=Vector((kcx, kcy, kcz)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.37, + r_out=0.465, + half_w=0.37, + ang_start_deg=-42.0, + ang_end_deg=72.0, + steps=6, + parent=pelvis, + mat_name="olive_armor", + end_taper_w=0.78, + bevel=0.010, + ) + ) + knee_shrouds.append( + _make_chamfer_box_shroud( + f"Shroud.Kestrel.KneeCapFront{side}", + kcx - 0.25, + kcx + 0.25, + kcy + 0.36, + kcy + 0.49, + kcz - 0.24, + kcz + 0.28, + parent=pelvis, + mat_name="olive_armor", + chamfer=0.06, + top_taper_xy=(0.86, 0.85), + bevel=0.009, + ) + ) + knee_side_rings: list[list[Vector]] = [] + for x_off, r in ((0.28, 0.28), (0.37, 0.28), (0.42, 0.19)): + px = kcx + sx * x_off + pts = [ + Vector((px, kcy + r * math.cos(math.radians(a)), kcz + r * math.sin(math.radians(a)))) + for a in range(0, 360, 45) + ] + if sx < 0: + pts = list(reversed(pts)) + knee_side_rings.append(pts) + knee_shrouds.append(_make_loft_shroud(f"Shroud.Kestrel.KneeCheek{side}", knee_side_rings, pelvis, "olive_armor", bevel=0.008)) + if leg_shin != pelvis: + bpy.context.view_layer.update() + for ks in knee_shrouds: + _reparent_keep_world(ks, leg_shin) + created.extend(knee_shrouds) + + # 5. Armored calf/shin shrouds wrapping rear twin ankle hydraulic pistons (parented to Leg{side}.Shin) + ram_objs = [f"Ankle{side}.root.machine.ram", f"Ankle{side}.root.steel.ram", f"Ankle{side}.root.steel.eye"] + top_b = _obj_bounds_in_ref(ram_objs, pelvis, z_filter=(2.05, 2.75)) + bot_b = _obj_bounds_in_ref(ram_objs, pelvis, z_filter=(0.95, 1.65)) + if top_b is not None and bot_b is not None: + t_cx = 0.5 * (top_b[0].x + top_b[1].x) + t_cy = 0.5 * (top_b[0].y + top_b[1].y) + b_cx = 0.5 * (bot_b[0].x + bot_b[1].x) + b_cy = 0.5 * (bot_b[0].y + bot_b[1].y) + z_bot, z_top = 1.16, 2.74 + # Interpolate exact piston spine centerline from z_bot..z_top and wrap a U-channel rear/flank greave + greave_rings: list[list[Vector]] = [] + for frac, hw, y_back, y_front in ( + (0.00, 0.145, -0.145, 0.13), + (0.22, 0.165, -0.165, 0.17), + (0.75, 0.180, -0.175, 0.22), + (1.00, 0.160, -0.145, 0.19), + ): + zz = z_bot + (z_top - z_bot) * frac + # top_b centroid is ~z=2.40, bot_b centroid is ~z=1.30 + t_u = (zz - 1.30) / 1.10 + px = b_cx + (t_cx - b_cx) * t_u + py = b_cy + (t_cy - b_cy) * t_u + c_in = hw * 0.58 + pts = [ + Vector((px - hw, py + y_front, zz)), + Vector((px - c_in, py + y_front, zz)), + Vector((px - c_in, py + y_back + 0.08, zz)), + Vector((px + c_in, py + y_back + 0.08, zz)), + Vector((px + c_in, py + y_front, zz)), + Vector((px + hw, py + y_front, zz)), + Vector((px + hw, py + y_back + 0.05, zz)), + Vector((px + hw * 0.62, py + y_back, zz)), + Vector((px - hw * 0.62, py + y_back, zz)), + Vector((px - hw, py + y_back + 0.05, zz)), + ] + greave_rings.append(pts) + shin_shrouds: list[bpy.types.Object] = [] + shin_shrouds.append(_make_loft_shroud(f"Shroud.Kestrel.AnkleGreave{side}", greave_rings, pelvis, "olive_armor", bevel=0.010)) + for idx_band, zb in enumerate((1.38, 2.38)): + t_u = (zb - 1.30) / 1.10 + px = b_cx + (t_cx - b_cx) * t_u + py = b_cy + (t_cy - b_cy) * t_u + shin_shrouds.append( + _make_chamfer_box_shroud( + f"Shroud.Kestrel.AnkleBand{side}{idx_band}", + px - 0.18, + px + 0.18, + py - 0.175, + py + 0.16, + zb - 0.045, + zb + 0.045, + parent=pelvis, + mat_name="gunmetal", + chamfer=0.03, + bevel=0.006, + ) + ) + if leg_shin != pelvis: + bpy.context.view_layer.update() + for ss in shin_shrouds: + _reparent_keep_world(ss, leg_shin) + created.extend(shin_shrouds) + + # 3. Segmented armored spine shroud over exposed rear waist hydraulic rods (parented to Torso.pose) + # In Torso.pose local space (offset 0, -0.15, 6.75), neck rings step forward in Y as Z rises from -0.05 to +0.88 + for idx_seg, (z0, z1, y_back, hx) in enumerate(( + (-0.04, 0.27, -0.66, 0.58), + (0.24, 0.56, -0.58, 0.54), + (0.53, 0.86, -0.49, 0.49), + )): + created.append( + _make_chamfer_box_shroud( + f"Shroud.Kestrel.WaistSpine{idx_seg}", + -hx, + hx, + y_back, + y_back + 0.34, + z0, + z1, + parent=torso, + mat_name="olive_armor", + chamfer=0.07, + top_taper_xy=(0.92, 0.90), + bevel=0.010, + ) + ) + created.append( + _make_chamfer_box_shroud( + "Shroud.Kestrel.WaistSpineRib", + -0.16, + 0.16, + -0.69, + -0.42, + 0.00, + 0.82, + parent=torso, + mat_name="gunmetal", + chamfer=0.03, + top_taper_xy=(0.88, 0.85), + bevel=0.008, + ) + ) + return created + + +def _add_spectre_shrouds() -> list[bpy.types.Object]: + created: list[bpy.types.Object] = [] + + # 1. Angled shin/hock hydraulic ram deflector greaves (parented to LegL.Cannon / LegR.Cannon) + for leg in ("LegL", "LegR"): + cannon = bpy.data.objects.get(f"{leg}.Cannon") + if cannon is None: + continue + inv_can = cannon.matrix_world.inverted() + ram_objs = [bpy.data.objects.get(f"{leg}.Hock.ram.barrel"), bpy.data.objects.get(f"{leg}.Hock.ram.rod")] + for side_tag, x_sign in (("Out", -1.0 if leg == "LegL" else 1.0), ("In", 1.0 if leg == "LegL" else -1.0)): + pts: list[Vector] = [] + for ro in ram_objs: + if ro is None or ro.type != "MESH" or ro.data is None: + continue + mw = ro.matrix_world + for v in ro.data.vertices: + pl = inv_can @ (mw @ v.co) + if pl.x * x_sign > 0.10: + pts.append(pl) + if not pts: + continue + xmin = min(p.x for p in pts) + xmax = max(p.x for p in pts) + ymax = max(p.y for p in pts) + ymin = min(p.y for p in pts) + # Deflector greave wrapping the front (+Y) and outer/side face of each exposed silver ram + x_in = (xmin - 0.02) if x_sign > 0 else (xmin - 0.055) + x_out = (xmax + 0.055) if x_sign > 0 else (xmax + 0.02) + y_f = ymax + 0.055 + y_b = max(ymin - 0.02, ymax - 0.24) + z_top = 0.28 + z_bot = 1.46 + # Loft from top bevel cap -> mid shield -> lower tapered deflector lip + rings: list[list[Vector]] = [] + for zz, x_pad, y_pad in ( + (z_top, -0.02, -0.03), + (z_top + 0.14, 0.0, 0.0), + (z_bot - 0.18, 0.0, 0.0), + (z_bot, -0.025, -0.04), + ): + xa, xb = x_in - x_pad * x_sign, x_out + x_pad * x_sign + if xa > xb: + xa, xb = xb, xa + yf = y_f + y_pad + yb = y_b + xm = 0.5 * (xa + xb) + ym = 0.5 * (yb + yf) + rings.append([ + Vector((xa, yb, zz)), + Vector((xb, yb, zz)), + Vector((xb, ym + 0.03, zz)), + Vector((xm + 0.04 * (xb - xa), yf, zz)), + Vector((xm - 0.04 * (xb - xa), yf, zz)), + Vector((xa, ym + 0.03, zz)), + ]) + created.append(_make_loft_shroud(f"Shroud.Spectre.{leg}RamGuard{side_tag}", rings, cannon, "olive_armor", bevel=0.009)) + # Gunmetal mounting bracket tying greave into Leg*.Shank + bx0 = min(x_in, x_out) - (0.06 if x_sign > 0 else 0.0) + bx1 = max(x_in, x_out) + (0.06 if x_sign < 0 else 0.0) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Spectre.{leg}RamBracket{side_tag}", + bx0, + bx1, + y_b - 0.08, + y_b + 0.04, + 0.55, + 0.78, + parent=cannon, + mat_name="gunmetal", + chamfer=0.025, + bevel=0.006, + ) + ) + + # 2. Compact armored waist collar / hip skirt around vertical waist spindle (parented to Waist) + waist = bpy.data.objects.get("Waist") + if waist is not None: + # Waist wloc=(0,0,5.30), WaistLug extends z_local=-0.35..0.14, WaistColumn z_local=0..0.81 + skirt_rings: list[list[Vector]] = [] + for zz, sx, sy in ( + (-0.28, 0.72, 0.62), + (-0.04, 0.74, 0.64), + (0.24, 0.64, 0.56), + (0.42, 0.55, 0.49), + ): + c = 0.16 + skirt_rings.append([ + Vector((-sx + c, -sy, zz)), + Vector((sx - c, -sy, zz)), + Vector((sx, -sy + c, zz)), + Vector((sx, sy - c, zz)), + Vector((sx - c, sy, zz)), + Vector((-sx + c, sy, zz)), + Vector((-sx, sy - c, zz)), + Vector((-sx, -sy + c, zz)), + ]) + created.append(_make_loft_shroud("Shroud.Spectre.WaistSkirt", skirt_rings, waist, "olive_armor", bevel=0.010)) + created.append( + _make_chamfer_box_shroud( + "Shroud.Spectre.WaistCollar", + -0.56, + 0.56, + -0.51, + 0.51, + 0.32, + 0.48, + parent=waist, + mat_name="gunmetal", + chamfer=0.10, + bevel=0.008, + ) + ) + + # 3. Outer shoulder-hinge axle caps (parented to ShoulderL / ShoulderR) + for side, sx in (("L", -1.0), ("R", 1.0)): + sh = bpy.data.objects.get(f"Shoulder{side}") + if sh is None: + continue + cap_rings: list[list[Vector]] = [] + for x_off, r in ((0.24, 0.305), (0.44, 0.305), (0.52, 0.225)): + px = sx * x_off + pts = [ + Vector((px, r * math.cos(math.radians(a)), r * math.sin(math.radians(a)))) + for a in range(0, 360, 45) + ] + if sx < 0: + pts = list(reversed(pts)) + cap_rings.append(pts) + created.append(_make_loft_shroud(f"Shroud.Spectre.ShoulderCap{side}", cap_rings, sh, "olive_armor", bevel=0.008)) + + return created + + +def _add_raptor_shrouds() -> list[bpy.types.Object]: + created: list[bpy.types.Object] = [] + pelvis = bpy.data.objects.get("Pelvis") + + for side, sx in (("L", -1.0), ("R", 1.0)): + # 1. Angled olive hip-fender cowl over protruding black hip drum (parented to Pelvis) + if pelvis is not None: + created.append( + _make_arc_fender( + f"Shroud.Raptor.HipFender{side}", + center=Vector((sx * 1.44, 0.0, 0.0)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.535, + r_out=0.615, + half_w=0.45, + ang_start_deg=18.0, + ang_end_deg=165.0, + steps=7, + parent=pelvis, + mat_name="olive_armor", + end_taper_w=0.82, + bevel=0.010, + ) + ) + created.append( + _make_arc_fender( + f"Shroud.Raptor.HipFlange{side}", + center=Vector((sx * 1.02, 0.0, 0.0)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.50, + r_out=0.555, + half_w=0.07, + ang_start_deg=15.0, + ang_end_deg=168.0, + steps=6, + parent=pelvis, + mat_name="gunmetal", + end_taper_w=0.95, + bevel=0.006, + ) + ) + + # 2. Outer hip drum cap + knee-cap shield + rear thigh actuator guard (parented to Leg*.Thigh) + thigh = bpy.data.objects.get(f"Leg{side}.Thigh") + if thigh is not None: + # In LegL.Thigh local space +X is outer left; in LegR.Thigh local space -X is outer right + x_out_sign = -sx + hip_cap_rings: list[list[Vector]] = [] + for x_off, r in ((0.48, 0.35), (0.60, 0.35), (0.66, 0.25)): + px = x_out_sign * x_off + pts = [ + Vector((px, r * math.cos(math.radians(a)), r * math.sin(math.radians(a)))) + for a in range(0, 360, 45) + ] + if x_out_sign < 0: + pts = list(reversed(pts)) + hip_cap_rings.append(pts) + created.append(_make_loft_shroud(f"Shroud.Raptor.HipCap{side}", hip_cap_rings, thigh, "olive_armor", bevel=0.008)) + + # KneeBearing*.gunmetal sits at z_local=[1.52..2.28], y_local=[-0.38..+0.38] (center 0.0, 1.90) + created.append( + _make_arc_fender( + f"Shroud.Raptor.KneeCap{side}", + center=Vector((x_out_sign * 0.06, 0.0, 1.90)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, -1.0)), + r_in=0.385, + r_out=0.475, + half_w=0.46, + ang_start_deg=-62.0, + ang_end_deg=62.0, + steps=7, + parent=thigh, + mat_name="olive_armor", + end_taper_w=0.78, + bevel=0.010, + ) + ) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Raptor.KneeCapFront{side}", + x_out_sign * 0.06 - 0.30, + x_out_sign * 0.06 + 0.30, + 0.37, + 0.50, + 1.64, + 2.16, + parent=thigh, + mat_name="olive_armor", + chamfer=0.06, + top_taper_xy=(0.86, 0.85), + bevel=0.009, + ) + ) + # Outer circular knee-drum cap + knee_cap_rings: list[list[Vector]] = [] + for x_off, r in ((0.46, 0.28), (0.58, 0.28), (0.64, 0.19)): + px = x_out_sign * x_off + pts = [ + Vector((px, r * math.cos(math.radians(a)), 1.90 + r * math.sin(math.radians(a)))) + for a in range(0, 360, 45) + ] + if x_out_sign < 0: + pts = list(reversed(pts)) + knee_cap_rings.append(pts) + created.append(_make_loft_shroud(f"Shroud.Raptor.KneeOuterCap{side}", knee_cap_rings, thigh, "olive_armor", bevel=0.008)) + + # Rear thigh actuator guard over Actuators*.steel (y_local=[-0.62..-0.42], z_local=[1.14..1.71]) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Raptor.ThighRam{side}", + -0.37, + 0.37, + -0.66, + -0.36, + 1.08, + 1.72, + parent=thigh, + mat_name="olive_armor", + chamfer=0.06, + top_taper_xy=(0.90, 0.88), + bevel=0.009, + ) + ) + + # 3. Shin upper rod shroud (parented to Leg*.Shin) + shin = bpy.data.objects.get(f"Leg{side}.Shin") + if shin is not None: + # HydraulicsShin*.gunmetal/steel: x=[-0.23..0.23], y=[0.46..0.66], z=[0.18..1.48] + created.append( + _make_chamfer_box_shroud( + f"Shroud.Raptor.ShinRod{side}", + -0.27, + 0.27, + 0.36, + 0.71, + 0.20, + 1.32, + parent=shin, + mat_name="olive_armor", + chamfer=0.06, + top_taper_xy=(0.82, 0.80), + bevel=0.009, + ) + ) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Raptor.ShinRodCollar{side}", + -0.29, + 0.29, + 0.34, + 0.72, + 0.82, + 0.98, + parent=shin, + mat_name="gunmetal", + chamfer=0.04, + bevel=0.006, + ) + ) + + # 4. Protruding rear calf hydraulic rod shroud (parented to Leg*.Cannon) + cannon = bpy.data.objects.get(f"Leg{side}.Cannon") + if cannon is not None: + # Hydraulics*.gunmetal/steel: x=[-0.23..0.23], y=[-0.57..-0.37], z=[0.18..1.61] + created.append( + _make_chamfer_box_shroud( + f"Shroud.Raptor.CalfRod{side}", + -0.28, + 0.28, + -0.63, + -0.27, + 0.20, + 1.40, + parent=cannon, + mat_name="olive_armor", + chamfer=0.07, + top_taper_xy=(0.80, 0.78), + bevel=0.009, + ) + ) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Raptor.CalfRodCollar{side}", + -0.30, + 0.30, + -0.64, + -0.26, + 0.88, + 1.04, + parent=cannon, + mat_name="gunmetal", + chamfer=0.04, + bevel=0.006, + ) + ) + + return created + + +def _add_manticore_shrouds() -> list[bpy.types.Object]: + created: list[bpy.types.Object] = [] + for leg in ("LegBL", "LegBR"): + # In LegBL local space -X is outward-left; in LegBR local space +X is outward-right + x_out_sign = -1.0 if leg == "LegBL" else 1.0 + + # 1. Rear hip armor cap over bare gunmetal coxa drum (parented to LegB*.Coxa) + coxa = bpy.data.objects.get(f"{leg}.Coxa") + if coxa is not None: + # coxa.dress.machine: x=[-0.446..0.446], y=[-0.30..0.30], z=[0.16..0.76]; +Y_local is outer-rear + created.append( + _make_chamfer_box_shroud( + f"Shroud.Manticore.{leg}HipCap", + -0.48, + 0.48, + -0.12, + 0.40, + -0.02, + 0.54, + parent=coxa, + mat_name="olive_armor", + chamfer=0.08, + top_taper_xy=(0.90, 0.86), + bevel=0.010, + ) + ) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Manticore.{leg}HipFlange", + -0.50, + 0.50, + -0.14, + 0.28, + -0.04, + 0.12, + parent=coxa, + mat_name="gunmetal", + chamfer=0.06, + bevel=0.006, + ) + ) + + # 2. Rear knee armor cap arching over bare gunmetal knee drum + outer drum cap (parented to LegB*.S1) + s1 = bpy.data.objects.get(f"{leg}.S1") + if s1 is not None: + # knee.dress.machine: x=[-0.44..0.44], y=[-0.34..0.34], z=[1.242..1.922]; femur.plate ends at z=1.25, y=[0.30..0.42] + created.append( + _make_arc_fender( + f"Shroud.Manticore.{leg}KneeCap", + center=Vector((0.0, 0.0, 1.58)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.345, + r_out=0.445, + half_w=0.48, + ang_start_deg=-38.0, + ang_end_deg=132.0, + steps=8, + parent=s1, + mat_name="olive_armor", + end_taper_w=0.84, + bevel=0.010, + ) + ) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Manticore.{leg}KneeCapTop", + -0.34, + 0.34, + 0.24, + 0.45, + 1.26, + 1.80, + parent=s1, + mat_name="olive_armor", + chamfer=0.06, + top_taper_xy=(0.88, 0.85), + bevel=0.009, + ) + ) + knee_side_rings: list[list[Vector]] = [] + for x_off, r in ((0.38, 0.28), (0.48, 0.28), (0.53, 0.19)): + px = x_out_sign * x_off + pts = [ + Vector((px, r * math.cos(math.radians(a)), 1.58 + r * math.sin(math.radians(a)))) + for a in range(0, 360, 45) + ] + if x_out_sign < 0: + pts = list(reversed(pts)) + knee_side_rings.append(pts) + created.append(_make_loft_shroud(f"Shroud.Manticore.{leg}KneeSideCap", knee_side_rings, s1, "olive_armor", bevel=0.008)) + + return created + + +def _add_paladin_shrouds() -> list[bpy.types.Object]: + created: list[bpy.types.Object] = [] + arm_r = bpy.data.objects.get("ArmR.Lower") + if arm_r is None: + return created + + # ArmR.Lower local box is [-0.297, -0.25, -0.144]..[0.297, 0.25, 1.55]. + # hp.weapon.arm_r sits on -X_local face at (-0.311, -0.124, 0.697) with 0.72x0.72 footprint -> keep -X_local z=[0.26..1.16] clear! + # Inner (+X), Front (+Y), and Rear (-Y) forearm plates: + created.append( + _make_chamfer_box_shroud( + "Shroud.Paladin.ArmRInner", + 0.28, + 0.42, + -0.27, + 0.27, + 0.14, + 1.44, + parent=arm_r, + mat_name="olive_armor", + chamfer=0.04, + top_taper_xy=(0.90, 0.88), + bevel=0.009, + ) + ) + created.append( + _make_chamfer_box_shroud( + "Shroud.Paladin.ArmRFront", + -0.31, + 0.36, + 0.23, + 0.39, + 0.14, + 1.44, + parent=arm_r, + mat_name="olive_armor", + chamfer=0.05, + top_taper_xy=(0.86, 0.86), + bevel=0.009, + ) + ) + created.append( + _make_chamfer_box_shroud( + "Shroud.Paladin.ArmRRear", + -0.31, + 0.36, + -0.39, + -0.23, + 0.14, + 1.44, + parent=arm_r, + mat_name="olive_armor", + chamfer=0.05, + top_taper_xy=(0.86, 0.86), + bevel=0.009, + ) + ) + # Upper elbow cuff & lower wrist cuff collar (staying clear of hp.weapon.arm_r around z=0.26..1.16 on -X) + created.append( + _make_chamfer_box_shroud( + "Shroud.Paladin.ArmRElbowCuff", + -0.38, + 0.38, + -0.33, + 0.33, + -0.02, + 0.22, + parent=arm_r, + mat_name="olive_armor", + chamfer=0.06, + bevel=0.009, + ) + ) + created.append( + _make_chamfer_box_shroud( + "Shroud.Paladin.ArmRWristBand", + -0.34, + 0.36, + -0.30, + 0.30, + 1.36, + 1.50, + parent=arm_r, + mat_name="gunmetal", + chamfer=0.04, + bevel=0.006, + ) + ) + return created + + +def _add_actuator_armor_shrouds(mech_id: str) -> list[bpy.types.Object]: + builders = { + "kestrel": _add_kestrel_shrouds, + "spectre": _add_spectre_shrouds, + "raptor": _add_raptor_shrouds, + "manticore": _add_manticore_shrouds, + "paladin": _add_paladin_shrouds, + } + fn = builders.get(mech_id) + if fn is None: + return [] + return fn() + + +def retrofit_mech(spec: MechRetrofitSpec) -> dict[str, Any]: + bpy.ops.wm.open_mainfile(filepath=str(spec.blend_path)) + scene = bpy.context.scene + scene.unit_settings.system = "METRIC" + scene.unit_settings.scale_length = 1.0 + + # 1. Apply SOLIDIFY/BOOLEAN/BEVEL BEFORE stripping hidden boolean cutters + if not spec.armature_name: + _apply_existing_modifiers() + + # 2. Strip studio rig/backdrop & built-in weapons + stripped = _strip_scene_objects(spec) + + if not spec.armature_name: + _convert_surviving_curves() + + # Square Breaker-3 torso yaw (-5 deg walk offset -> 0 deg neutral symmetric forward) + if spec.mech_id == "breaker" and "Core" in bpy.data.objects: + bpy.data.objects["Core"].rotation_euler.z = 0.0 + bpy.context.view_layer.update() + + raw_blend_mechs = ( + _extract_mechanisms_from_blend_raw("Pelvis") + if spec.model_json_path is None and spec.mech_id == "breaker" + else None + ) + + # 3. For rigged meshes, strip weapon vertex groups cleanly; strip protruding weapon islands + stripped_vgs: dict[str, int] = {} + if spec.strip_vertex_groups: + for obj in bpy.data.objects: + if obj.type == "MESH": + cnt = _strip_vertex_groups_from_mesh(obj, spec.strip_vertex_groups) + if cnt > 0: + stripped_vgs[obj.name] = cnt + if spec.strip_islands: + _strip_mesh_islands(spec.strip_islands) + if spec.mech_id == "kestrel": + _assemble_kestrel_hierarchy() + + # 4. Normalize procedural materials -> clean glTF PBR + _normalize_materials_for_gltf() + + # 5. Collect surviving mech meshes & decimate to game-ready LOD budget + mech_meshes = [o for o in bpy.data.objects if o.type == "MESH"] + raw_tris, lod_tris = _decimate_mech_meshes(mech_meshes, spec.target_mech_tris) + + # 5b. Add Brokkr-style olive-drab armor shrouds over exposed joints/actuators + shroud_objs = _add_actuator_armor_shrouds(spec.mech_id) + if shroud_objs: + shroud_tris = sum(_mesh_tri_count(o) for o in shroud_objs) + lod_tris += shroud_tris + print(f" [shroud] {spec.mech_id}: +{len(shroud_objs)} shrouds (+{shroud_tris} tris)") + + # 6. Parent everything cleanly under a root Empty (in raw Brokkr orientation first) + chassis_root = vc.make_empty(spec.mech_id, parent=None, location=(0.0, 0.0, 0.0)) + for obj in list(bpy.data.objects): + if obj == chassis_root or obj.parent is not None: + continue + mw = obj.matrix_world.copy() + obj.parent = chassis_root + obj.matrix_parent_inverse = Matrix.Identity(4) + obj.matrix_local = mw + bpy.context.view_layer.update() + + # 7. Build hull BVH over final LOD meshes, snap & recess every hardpoint bay, tag joints + full_bvh = _build_hull_bvh([o for o in bpy.data.objects if o.type == "MESH"]) + assert full_bvh is not None, f"{spec.mech_id}: empty hull BVH" + bvh_cache: dict[str, BVHTree] = {} + for hp in spec.hardpoints: + _attach_hardpoint_world(hp, chassis_root, full_bvh, bvh_cache) + joints_manifest = _apply_joint_tags(spec) + + # 8. Rotate chassis_root 180 deg around Z so Brokkr +Y forward -> RTD -Y forward (+Z glTF), -X left -> +X left + chassis_root.rotation_mode = "XYZ" + chassis_root.rotation_euler = Euler((0.0, 0.0, math.pi), "XYZ") + bpy.context.view_layer.update() + + # 9. Export GLB (grounding minZ=0.0), write manifest.json, render 4-panel preview + glb_path = vc.ASSETS_VEHICLES_DIR / spec.mech_id / f"{spec.mech_id}.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / spec.mech_id / "manifest.json" + preview_path = vc.PREVIEWS_DIR / f"{spec.mech_id}_preview.png" + + z_shift_before = chassis_root.location.z + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=chassis_root) + ground_z_shift = chassis_root.location.z - z_shift_before + + if spec.model_json_path is not None: + mechanisms = _extract_mechanisms(spec.model_json_path, ground_z_shift=ground_z_shift) + elif raw_blend_mechs is not None: + mechanisms = _finalize_mechanisms_gltf(raw_blend_mechs, ground_z_shift=ground_z_shift) + else: + mechanisms = None + + hp_manifest = [ + { + "id": hp.hp_id, + "kind": hp.kind, + "x": hp.x, + "y": hp.y, + "w": hp.w, + "h": hp.h, + "modelNodeId": hp.hp_id, + } + for hp in spec.hardpoints + ] + + vc.write_manifest( + manifest_path, + vehicle_id=spec.mech_id, + name=spec.name, + vehicle_class=spec.vehicle_class, + plane=spec.plane, + grid_width=spec.grid_width, + grid_height=spec.grid_height, + mask=spec.mask, + hardpoints=hp_manifest, + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + mechanisms=mechanisms, + ) + + vc.render_four_panel_preview(preview_path) + glb_bytes = glb_path.stat().st_size + summary = { + "id": spec.mech_id, + "raw_tris_after_strip": raw_tris, + "lod_mech_tris": lod_tris, + "exported_total_tris": tri_count, + "glb_bytes": glb_bytes, + "bounds": bounds, + "stripped_count": len(stripped), + "stripped_vgs": stripped_vgs, + } + print(f"[{spec.mech_id}] {json.dumps(summary)}") + return summary + + +def main() -> int: + argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else [] + parser = argparse.ArgumentParser(description="Retrofit Brokkr mechs for Rust to Dust.") + parser.add_argument("--mech", choices=sorted(SPECS.keys()), help="Single mech ID to retrofit.") + parser.add_argument("--all", action="store_true", help="Retrofit all configured mechs sequentially.") + args = parser.parse_args(argv) + + targets = list(SPECS.keys()) if (args.all or not args.mech) else [args.mech] + for mid in targets: + retrofit_mech(SPECS[mid]) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/vehicles/vehicle_common.py b/tools/vehicles/vehicle_common.py new file mode 100644 index 0000000..0077681 --- /dev/null +++ b/tools/vehicles/vehicle_common.py @@ -0,0 +1,1160 @@ +"""Shared Brokkr-powered vehicle construction, hardpoint sockets, joint tagging, +GLB export, manifest emission, and 4-panel preview rendering for Rust to Dust. + +All Blender geometry is authored in Blender right-handed Z-up coordinates with: + -Y = vehicle forward (+Z in exported glTF) + +Y = vehicle rear (-Z in exported glTF) + +Z = vehicle up (+Y in exported glTF, grounded at Z = 0) + +X = vehicle left (+X in exported glTF) + -X = vehicle right (-X in exported glTF) + +Export uses bpy.ops.export_scene.gltf(..., export_yup=True, export_extras=True) +so Godot receives +Z forward, +Y up, minY ~ 0.0, and rtd.* custom properties. +""" +from __future__ import annotations + +import json +import math +import sys +from pathlib import Path +from typing import Any, Callable, Sequence + +import bmesh +import bpy +import numpy as np +from mathutils import Euler, Matrix, Vector + +BROKKR_BLENDER_DIR = Path(r"F:\Projects\Brokkr\surfaces\blender") +if str(BROKKR_BLENDER_DIR) not in sys.path: + sys.path.insert(0, str(BROKKR_BLENDER_DIR)) + +import brokkr_mesh_polish # noqa: E402, F401 +import brokkr_kitbash # noqa: E402 +from brokkr_kitbash import core, plate, ram # noqa: E402, F401 + +REPO_ROOT = Path(__file__).resolve().parents[2] +ASSETS_VEHICLES_DIR = REPO_ROOT / "assets" / "vehicles" +ASSETS_GEAR_DIR = REPO_ROOT / "assets" / "gear" +PREVIEWS_DIR = Path(__file__).resolve().parent / "previews" + +# Shared industrial PBR palette (sRGB hex -> linear PBR base color) +PALETTE: dict[str, dict[str, Any]] = { + "olive_armor": {"hex": "#4e5740", "metallic": 0.28, "roughness": 0.58}, + "gunmetal": {"hex": "#2c302e", "metallic": 0.78, "roughness": 0.40}, + "rubber_dark": {"hex": "#191a19", "metallic": 0.04, "roughness": 0.86}, + "copper_rad": {"hex": "#9c5a34", "metallic": 0.86, "roughness": 0.34}, + "socket_bay": {"hex": "#151816", "metallic": 0.55, "roughness": 0.72}, + "signal_orange": {"hex": "#d96c27", "metallic": 0.18, "roughness": 0.44}, + "smoked_glass": {"hex": "#1e2a2d", "metallic": 0.12, "roughness": 0.10, "alpha": 0.82}, + # Imperial Tourist & salvage gear accents + "imperial_gold": {"hex": "#d4a634", "metallic": 0.90, "roughness": 0.26}, + "imperial_ivory": {"hex": "#ebe4d1", "metallic": 0.16, "roughness": 0.38}, + "cyan_coil": {"hex": "#38c9d8", "metallic": 0.20, "roughness": 0.25, "emission": "#38c9d8", "emission_strength": 1.8}, +} + +_KITS_CACHE: dict[str, dict] = {} + + +def srgb_hex_to_linear(hex_str: str) -> tuple[float, float, float, float]: + h = hex_str.lstrip("#") + vals = [int(h[i : i + 2], 16) / 255.0 for i in (0, 2, 4)] + + def to_lin(c: float) -> float: + return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 + + return (to_lin(vals[0]), to_lin(vals[1]), to_lin(vals[2]), 1.0) + + +def reset_scene() -> bpy.types.Scene: + """Clear all objects, meshes, materials, cameras, lights, and orphan data.""" + bpy.ops.wm.read_factory_settings(use_empty=True) + scene = bpy.context.scene + scene.unit_settings.system = "METRIC" + scene.unit_settings.scale_length = 1.0 + return scene + + +def ensure_materials() -> dict[str, bpy.types.Material]: + """Create shared industrial PBR materials cleanly on Principled BSDF.""" + mats: dict[str, bpy.types.Material] = {} + for name, spec in PALETTE.items(): + mat = bpy.data.materials.get(name) + if mat is None: + mat = bpy.data.materials.new(name=name) + mat.use_nodes = True + nt = mat.node_tree + nt.nodes.clear() + out = nt.nodes.new("ShaderNodeOutputMaterial") + bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") + nt.links.new(bsdf.outputs["BSDF"], out.inputs["Surface"]) + bsdf.inputs["Base Color"].default_value = srgb_hex_to_linear(spec["hex"]) + bsdf.inputs["Metallic"].default_value = float(spec["metallic"]) + bsdf.inputs["Roughness"].default_value = float(spec["roughness"]) + if "alpha" in spec: + bsdf.inputs["Alpha"].default_value = float(spec["alpha"]) + mat.blend_method = "BLEND" if hasattr(mat, "blend_method") else "HASHED" + if "emission" in spec: + bsdf.inputs["Emission Color"].default_value = srgb_hex_to_linear(spec["emission"]) + bsdf.inputs["Emission Strength"].default_value = float(spec.get("emission_strength", 1.0)) + mats[name] = mat + return mats + + +def load_kit(name: str) -> dict: + if name not in _KITS_CACHE: + _KITS_CACHE[name] = core.load_kit(name) + return _KITS_CACHE[name] + + +def _assign_material(obj: bpy.types.Object, mat_name: str) -> None: + mat = bpy.data.materials.get(mat_name) + if mat is None: + ensure_materials() + mat = bpy.data.materials[mat_name] + if len(obj.data.materials): + obj.data.materials[0] = mat + else: + obj.data.materials.append(mat) + + +def _link_object( + obj: bpy.types.Object, + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), +) -> bpy.types.Object: + scene = bpy.context.scene + if obj.name not in scene.collection.objects: + scene.collection.objects.link(obj) + if parent is not None: + obj.parent = parent + obj.matrix_parent_inverse = Matrix.Identity(4) + obj.location = Vector(location) + obj.rotation_mode = "XYZ" + obj.rotation_euler = Euler([math.radians(a) for a in rotation_deg], "XYZ") + return obj + + +def _add_bevel(obj: bpy.types.Object, width: float, segments: int = 1, angle_deg: float = 30.0) -> None: + if width <= 0.0: + return + mod = obj.modifiers.new("Bevel", "BEVEL") + mod.width = width + mod.segments = segments + mod.limit_method = "ANGLE" + mod.angle_limit = math.radians(angle_deg) + mod.harden_normals = False + + +def make_empty( + name: str, + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + display_type: str = "PLAIN_AXES", + display_size: float = 0.12, +) -> bpy.types.Object: + obj = bpy.data.objects.new(name, None) + obj.empty_display_type = display_type + obj.empty_display_size = display_size + return _link_object(obj, parent=parent, location=location, rotation_deg=rotation_deg) + + +def make_mesh_from_swept( + name: str, + swept: Any, + mat_name: str, + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, +) -> bpy.types.Object: + mesh = bpy.data.meshes.new(name) + brokkr_kitbash.write_mesh(mesh, swept) + obj = bpy.data.objects.new(name, mesh) + _assign_material(obj, mat_name) + _link_object(obj, parent=parent, location=location, rotation_deg=rotation_deg) + if bevel > 0.0: + _add_bevel(obj, bevel, segments=1) + return obj + + +def _build_inline_shape(name: str, shape_dict: dict[str, Any]) -> core.Built: + doc = { + "schema": core.SCHEMA, + "kit": "inline", + "doc": "inline part", + "socketTypes": {}, + "parts": [{ + "name": "p", + "doc": name, + "params": [], + "shapes": [shape_dict], + "sockets": [], + }], + } + checked = core.check_kit(doc) + return core.build(checked["parts"]["p"], {}) + + +def make_tube_part( + name: str, + r0: float, + r1: float, + length: float, + segments: int = 12, + inner0: float = 0.0, + inner1: float = 0.0, + smooth: bool = True, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, +) -> bpy.types.Object: + shape_dict: dict[str, Any] = { + "shape": "tube", + "r0": float(r0), + "r1": float(r1), + "length": float(length), + "segments": int(segments), + "smooth": bool(smooth), + } + if inner0 > 0.0 or inner1 > 0.0: + shape_dict["inner0"] = float(inner0) + shape_dict["inner1"] = float(inner1) + return make_mesh_from_swept( + name, + _build_inline_shape(name, shape_dict), + mat_name, + parent=parent, + location=location, + rotation_deg=rotation_deg, + bevel=bevel, + ) + + +def make_lathe_part( + name: str, + profile: Sequence[Sequence[float]], + segments: int = 16, + loop: bool = False, + smooth: bool = True, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, +) -> bpy.types.Object: + shape_dict = { + "shape": "lathe", + "segments": int(segments), + "loop": bool(loop), + "smooth": bool(smooth), + "profile": [[float(p[0]), float(p[1])] for p in profile], + } + return make_mesh_from_swept( + name, + _build_inline_shape(name, shape_dict), + mat_name, + parent=parent, + location=location, + rotation_deg=rotation_deg, + bevel=bevel, + ) + + +def make_kit_part( + name: str, + kit_name: str, + part_name: str, + params: dict[str, Any] | None = None, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, +) -> bpy.types.Object: + kit = load_kit(kit_name) + part_def = core.part(kit, part_name) + built = core.build(part_def, params or {}) + return make_mesh_from_swept( + name=name, + swept=built, + mat_name=mat_name, + parent=parent, + location=location, + rotation_deg=rotation_deg, + bevel=bevel, + ) + + +def _auto_ups(path: np.ndarray, closed: bool = False) -> np.ndarray: + """Compute smooth non-collinear up vectors along any 3D polyline for core.sweep.""" + n = len(path) + steps = (np.roll(path, -1, axis=0) - path)[: n if closed else n - 1] + lengths = np.linalg.norm(steps, axis=1, keepdims=True) + tangents = steps / np.maximum(lengths, 1e-9) + if closed: + vert_tan = tangents + np.roll(tangents, 1, axis=0) + else: + vert_tan = np.vstack([tangents[:1], tangents[:-1] + tangents[1:], tangents[-1:]]) + vert_tan /= np.maximum(np.linalg.norm(vert_tan, axis=1, keepdims=True), 1e-9) + ups = np.zeros_like(vert_tan) + ref = np.array([0.0, 0.0, 1.0]) if abs(vert_tan[0, 2]) < 0.85 else np.array([1.0, 0.0, 0.0]) + u0 = ref - vert_tan[0] * float(ref @ vert_tan[0]) + ups[0] = u0 / np.linalg.norm(u0) + for i in range(1, n): + u = ups[i - 1] - vert_tan[i] * float(ups[i - 1] @ vert_tan[i]) + norm = float(np.linalg.norm(u)) + if norm < 1e-5: + alt = np.array([1.0, 0.0, 0.0]) if abs(vert_tan[i, 0]) < 0.85 else np.array([0.0, 1.0, 0.0]) + u = alt - vert_tan[i] * float(alt @ vert_tan[i]) + norm = float(np.linalg.norm(u)) + ups[i] = u / norm + return ups + + +def fillet_polyline(points: Sequence[Sequence[float]], radius: float = 0.05, subdivs: int = 2, closed: bool = False) -> np.ndarray: + """Round interior corners of a 3D polyline so core.sweep stays well below TURN_LIMIT.""" + pts = np.asarray(points, dtype=np.float64) + if len(pts) < 3 or radius <= 0.0: + return pts + out: list[np.ndarray] = [] + n = len(pts) + indices = range(n) if closed else range(1, n - 1) + if not closed: + out.append(pts[0]) + for i in indices: + p_prev = pts[(i - 1) % n] + p_curr = pts[i] + p_next = pts[(i + 1) % n] + v_in = p_curr - p_prev + v_out = p_next - p_curr + l_in = float(np.linalg.norm(v_in)) + l_out = float(np.linalg.norm(v_out)) + if l_in < 1e-6 or l_out < 1e-6: + out.append(p_curr) + continue + d_in = v_in / l_in + d_out = v_out / l_out + if float(d_in @ d_out) > 0.995: + out.append(p_curr) + continue + trim = min(radius, 0.35 * l_in, 0.35 * l_out) + a = p_curr - d_in * trim + b = p_curr + d_out * trim + for k in range(subdivs + 1): + t = k / subdivs + # Quadratic Bezier corner blend + pt = (1 - t) ** 2 * a + 2 * (1 - t) * t * p_curr + t ** 2 * b + out.append(pt) + if not closed: + out.append(pts[-1]) + return np.array(out, dtype=np.float64) + + +def make_swept_tube( + name: str, + points: Sequence[Sequence[float]], + radius: float, + segments: int = 8, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + closed: bool = False, + fillet_r: float = 0.04, +) -> bpy.types.Object: + path = fillet_polyline(points, radius=fillet_r, subdivs=2, closed=closed) if fillet_r > 0 else np.asarray(points, dtype=np.float64) + ups = _auto_ups(path, closed=closed) + swept = core.sweep(path, core.circle(radius, segments), ups, closed=closed) + return make_mesh_from_swept(name, swept, mat_name, parent=parent, location=location, rotation_deg=rotation_deg) + + +def make_swept_profile( + name: str, + section: str, + w: float, + h: float, + t: float, + points: Sequence[Sequence[float]], + up: Sequence[float] | None = None, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + closed: bool = False, +) -> bpy.types.Object: + path = np.asarray(points, dtype=np.float64) + ups = np.asarray(up, dtype=np.float64) if up is not None else _auto_ups(path, closed=closed) + swept = core.sweep(path, core.profile(section, w, h, t), ups, closed=closed) + return make_mesh_from_swept(name, swept, mat_name, parent=parent, location=location, rotation_deg=rotation_deg) + + +def make_box( + name: str, + size: Sequence[float], + mat_name: str = "olive_armor", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.008, +) -> bpy.types.Object: + sx, sy, sz = (float(v) for v in size) + V = core.BOX_SIGNS * np.array([sx, sy, sz], dtype=np.float64) + swept = core.Swept( + V=V, + faces=core.BOX_FACES.ravel().astype(np.int32), + counts=np.full(6, 4, dtype=np.int32), + smooth=np.zeros(6, dtype=bool), + sharp=core.NO_SHARP.astype(np.int32), + ) + return make_mesh_from_swept(name, swept, mat_name, parent=parent, location=location, rotation_deg=rotation_deg, bevel=bevel) + + +def make_bmesh_object( + name: str, + builder: Callable[[bmesh.types.BMesh], None], + mat_name: str = "olive_armor", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, + smooth: bool = False, +) -> bpy.types.Object: + bm = bmesh.new() + builder(bm) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces) + mesh = bpy.data.meshes.new(name) + bm.to_mesh(mesh) + bm.free() + if smooth: + for poly in mesh.polygons: + poly.use_smooth = True + obj = bpy.data.objects.new(name, mesh) + _assign_material(obj, mat_name) + _link_object(obj, parent=parent, location=location, rotation_deg=rotation_deg) + if bevel > 0.0: + _add_bevel(obj, bevel, segments=1) + return obj + + +def _write_vf_mesh(name: str, V: np.ndarray, faces: list[list[int]], mat_name: str, parent: bpy.types.Object | None = None, bevel: float = 0.0) -> bpy.types.Object: + mesh = bpy.data.meshes.new(name) + mesh.from_pydata(np.asarray(V, dtype=np.float64).tolist(), [], [[int(k) for k in f] for f in faces]) + sharp = mesh.attributes.get("sharp_face") or mesh.attributes.new("sharp_face", "BOOLEAN", "FACE") + sharp.data.foreach_set("value", np.ones(len(mesh.polygons), dtype=bool)) + mesh.update() + obj = bpy.data.objects.new(name, mesh) + _assign_material(obj, mat_name) + _link_object(obj, parent=parent) + if bevel > 0.0: + _add_bevel(obj, bevel, segments=1, angle_deg=15.0) + return obj + + +def make_plates( + table_doc: dict[str, Any], + parent: bpy.types.Object | None = None, + prefix: str = "", + side: int = 1, +) -> list[bpy.types.Object]: + """Build Brokkr hard armour plates (brokkr.plates.v0) directly into Blender objects.""" + checked = plate.check(table_doc) + entries = plate.build(checked, side=side) + created: list[bpy.types.Object] = [] + for entry in entries: + row = checked["plates"][entry["row"]] + pname = f"{prefix}{entry['name']}" + solid_obj = _write_vf_mesh(pname, entry["solid"][0], entry["solid"][1], row["mat"], parent=parent, bevel=row["bevel"]) + created.append(solid_obj) + clad = row["clad"] + if clad: + if len(entry["panels"][1]): + p_obj = _write_vf_mesh(f"{pname}.panels", entry["panels"][0], entry["panels"][1], clad["mat"], parent=solid_obj, bevel=clad["bevel"]) + created.append(p_obj) + if len(entry["bolts"][1]): + b_obj = _write_vf_mesh(f"{pname}.bolts", entry["bolts"][0], entry["bolts"][1], clad["bolt_mat"], parent=solid_obj, bevel=0.0) + created.append(b_obj) + for fit_mat, fit_mesh in entry["fits"].items(): + if len(fit_mesh[1]): + f_obj = _write_vf_mesh(f"{pname}.fit.{fit_mat}", fit_mesh[0], fit_mesh[1], fit_mat, parent=solid_obj, bevel=0.0) + created.append(f_obj) + return created + + +def make_knobby_wheel( + name: str, + radius: float, + width: float, + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + tread_lugs: int = 18, + rim_segments: int = 20, + side_sign: int = 1, +) -> bpy.types.Object: + """Build a crisp game-ready off-road wheel centered at (0,0,0) spinning about local X. + + side_sign = +1 for left (+X) wheel (hub faces +X), -1 for right (-X) wheel (hub faces -X). + """ + hub_pivot = make_empty(f"{name}_hub", parent=parent, location=location) + # Tire carcass via lathe rotated onto X axis (tube/lathe builds along +Z, so rot_y = 90) + r_rim = radius * 0.56 + r_side = radius * 0.92 + hw = width * 0.5 + tire_profile = [ + [r_rim * 0.96, -hw * 0.85], + [r_side, -hw * 0.95], + [radius * 0.96, -hw * 0.72], + [radius * 0.96, hw * 0.72], + [r_side, hw * 0.95], + [r_rim * 0.96, hw * 0.85], + ] + make_lathe_part( + f"{name}_tire", + tire_profile, + segments=rim_segments, + loop=True, + smooth=True, + mat_name="rubber_dark", + parent=hub_pivot, + rotation_deg=(0.0, 90.0, 0.0), + ) + + # Staggered knobby tread lugs around circumference (compact, low poly, high visual read) + def build_tread(bm: bmesh.types.BMesh) -> None: + lug_w = width * 0.38 + lug_h = radius * 0.055 + lug_len = (2.0 * math.pi * radius / tread_lugs) * 0.52 + for i in range(tread_lugs): + ang = 2.0 * math.pi * i / tread_lugs + for row_s in (-1.0, 1.0): + a = ang + (0.5 if row_s > 0 else 0.0) * (2.0 * math.pi / tread_lugs) + cy = math.cos(a) * (radius * 0.965) + cz = math.sin(a) * (radius * 0.965) + cx = row_s * hw * 0.42 + mat = ( + Matrix.Translation((cx, cy, cz)) + @ Matrix.Rotation(a, 4, "X") + @ Matrix.Scale(lug_w, 4, (1, 0, 0)) + @ Matrix.Scale(lug_h, 4, (0, 1, 0)) + @ Matrix.Scale(lug_len, 4, (0, 0, 1)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=mat) + + make_bmesh_object(f"{name}_treads", build_tread, "rubber_dark", parent=hub_pivot) + + # Steel wheel dish rim + hub cap (CCW in (r, z); +Z points outward via rot_y = 90 * side_sign) + rim_profile = [ + [0.0, -hw * 0.45], + [r_rim * 0.98, -hw * 0.45], + [r_rim * 0.98, hw * 0.86], + [r_rim * 0.82, hw * 0.86], + [r_rim * 0.72, hw * 0.48], + [r_rim * 0.30, hw * 0.48], + [r_rim * 0.25, hw * 0.82], + [0.0, hw * 0.82], + ] + make_lathe_part( + f"{name}_rim", + rim_profile, + segments=16, + loop=False, + smooth=True, + mat_name="gunmetal", + parent=hub_pivot, + rotation_deg=(0.0, 90.0 * side_sign, 0.0), + ) + + # Hub lug ring + def build_lugs(bm: bmesh.types.BMesh) -> None: + hx = side_sign * hw * 0.62 + for i in range(6): + a = 2.0 * math.pi * i / 6.0 + r_b = r_rim * 0.50 + m = Matrix.Translation((hx, math.cos(a) * r_b, math.sin(a) * r_b)) @ Matrix.Rotation(math.pi * 0.5, 4, "Y") + bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=6, radius1=radius * 0.042, radius2=radius * 0.042, depth=width * 0.14, matrix=m) + + make_bmesh_object(f"{name}_hubbolts", build_lugs, "signal_orange", parent=hub_pivot) + return hub_pivot + + +def make_ram_span( + name: str, + p_base: Sequence[float], + p_tip: Sequence[float], + body_r: float = 0.036, + rod_r: float = 0.020, + parent: bpy.types.Object | None = None, + mat_barrel: str = "gunmetal", + mat_rod: str = "copper_rad", + coil_rings: int = 0, +) -> bpy.types.Object: + """Create a realistic hydraulic actuator or coilover strut spanning p_base -> p_tip.""" + a = np.asarray(p_base, dtype=np.float64) + b = np.asarray(p_tip, dtype=np.float64) + vec = b - a + total = float(np.linalg.norm(vec)) + if total < 1e-4: + raise ValueError(f"Ram {name} has zero span") + z_dir = Vector((vec / total).tolist()) + quat = Vector((0.0, 0.0, 1.0)).rotation_difference(z_dir) + rot_deg = tuple(math.degrees(v) for v in quat.to_euler("XYZ")) + root = make_empty(name, parent=parent, location=a.tolist(), rotation_deg=rot_deg) + + body_len = max(0.05, total * 0.54) + rod_len = max(0.05, total * 0.56) + if 0.05 <= body_r <= 0.12 and 0.2 <= body_len <= 1.0 and 0.2 <= rod_len <= 2.0 and 0.01 <= rod_r <= 0.02: + make_kit_part( + f"{name}_barrel", + "mechanical", + "ram_barrel", + {"body_r": body_r, "body_len": body_len, "rod_r": rod_r, "segments": 10}, + mat_name=mat_barrel, + parent=root, + ) + make_kit_part( + f"{name}_rod", + "mechanical", + "ram_rod", + {"body_r": body_r, "rod_r": rod_r, "length": rod_len, "segments": 10}, + mat_name=mat_rod, + parent=root, + location=(0.0, 0.0, total), + rotation_deg=(180.0, 0.0, 0.0), + ) + else: + make_tube_part(f"{name}_barrel", body_r, body_r, body_len, segments=10, mat_name=mat_barrel, parent=root) + make_tube_part( + f"{name}_rod", + rod_r, + rod_r, + rod_len, + segments=8, + mat_name=mat_rod, + parent=root, + location=(0.0, 0.0, total - rod_len), + ) + if coil_rings > 0: + def build_coils(bm: bmesh.types.BMesh) -> None: + z0 = total * 0.16 + z1 = total * 0.78 + for k in range(coil_rings): + z = z0 + (z1 - z0) * (k / max(1, coil_rings - 1)) + # Octagonal spring ring + pts = [] + rc = body_r * 1.48 + for s in range(10): + ang = 2.0 * math.pi * s / 10.0 + pts.append((rc * math.cos(ang), rc * math.sin(ang), z)) + # Build small torus-like faceted collar ring + for s in range(10): + p0 = Vector(pts[s]) + p1 = Vector(pts[(s + 1) % 10]) + mid = (p0 + p1) * 0.5 + seg_dir = (p1 - p0).normalized() + q_seg = Vector((0, 0, 1)).rotation_difference(seg_dir) + m = Matrix.Translation(mid) @ q_seg.to_matrix().to_4x4() + bmesh.ops.create_cone( + bm, cap_ends=True, cap_tris=False, segments=6, + radius1=body_r * 0.24, radius2=body_r * 0.24, + depth=(p1 - p0).length * 1.08, matrix=m, + ) + + make_bmesh_object(f"{name}_coil", build_coils, "signal_orange", parent=root) + return root + + +def add_hardpoint_slot( + hp_id: str, + kind: str, + parent: bpy.types.Object, + location: Sequence[float], + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + size: Sequence[float] = (0.55, 0.55, 0.12), + plinth_depth: float = 0.0, +) -> bpy.types.Object: + """Create standardized VISIBLE exterior hardpoint socket geometry + tagged rtd.id anchor Empty. + + The anchor Empty is named `hp_id`, carries custom properties `rtd.id` and `rtd.kind`, + and sits at the mounting plane origin with local +Z normal (+Y in glTF) pointing outward. + When `plinth_depth > 0`, a solid recessed base flange extends down to `z = -plinth_depth` + so sloped/curved armor corners physically intersect the hull with zero air gap. + """ + if kind not in ("weapon", "radiator", "engine", "armor"): + raise ValueError(f"Unsupported hardpoint kind {kind!r}") + + sx, sy, sz = (float(v) for v in size) + p_depth = max(0.0, float(plinth_depth)) + # Visual frame parented alongside the anchor + bay_root = make_empty(f"slot_frame.{hp_id}", parent=parent, location=location, rotation_deg=rotation_deg) + + if kind == "weapon": + r_outer = min(sx, sy) * 0.48 + r_inner = r_outer * 0.72 + collar_h = max(0.055, sz * 0.65) + if p_depth > 0.0: + make_tube_part( + f"{hp_id}.plinth", + r_outer * 0.96, + r_outer * 0.96, + p_depth + 0.025, + segments=12, + smooth=False, + mat_name="gunmetal", + parent=bay_root, + location=(0.0, 0.0, -p_depth), + ) + # Octagonal bolted collar ring via Brokkr lathe + collar_prof = [ + [r_inner, 0.0], + [r_outer, 0.0], + [r_outer, collar_h * 0.65], + [r_outer * 0.92, collar_h], + [r_inner * 1.04, collar_h], + [r_inner, collar_h * 0.35], + ] + make_lathe_part( + f"{hp_id}.collar", + collar_prof, + segments=12, + loop=True, + smooth=False, + mat_name="gunmetal", + parent=bay_root, + ) + # Recessed dark weapon socket floor + make_box(f"{hp_id}.well", (r_inner * 1.65, r_inner * 1.65, 0.024), "socket_bay", parent=bay_root, location=(0.0, 0.0, 0.012), bevel=0.0) + # Twin mounting rails + 4 signal-orange lock lugs + 8 perimeter bolts + rail_sep = r_inner * 0.52 + for side in (-1.0, 1.0): + make_box( + f"{hp_id}.rail_{'l' if side > 0 else 'r'}", + (0.04, r_inner * 1.45, collar_h * 0.72), + "gunmetal", + parent=bay_root, + location=(side * rail_sep, 0.0, collar_h * 0.38), + bevel=0.004, + ) + def build_lugs_and_bolts(bm: bmesh.types.BMesh) -> None: + for ang_deg in (45.0, 135.0, 225.0, 315.0): + a = math.radians(ang_deg) + rl = r_outer * 0.88 + m = Matrix.Translation((rl * math.cos(a), rl * math.sin(a), collar_h * 0.96)) @ Matrix.Rotation(a, 4, "Z") + bmesh.ops.create_cube(bm, size=1.0, matrix=m @ Matrix.Diagonal((0.065, 0.042, 0.032, 1.0))) + + make_bmesh_object(f"{hp_id}.lugs", build_lugs_and_bolts, "signal_orange", parent=bay_root) + + def build_bolts(bm: bmesh.types.BMesh) -> None: + for k in range(8): + a = 2.0 * math.pi * k / 8.0 + rb = r_outer * 0.84 + m = Matrix.Translation((rb * math.cos(a), rb * math.sin(a), collar_h * 0.85)) + bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=6, radius1=0.016, radius2=0.014, depth=0.02, matrix=m) + + make_bmesh_object(f"{hp_id}.bolts", build_bolts, "gunmetal", parent=bay_root) + anchor_z = collar_h * 0.82 + + elif kind == "radiator": + frame_t = max(0.035, min(sx, sy) * 0.09) + depth = max(0.07, sz) + if p_depth > 0.0: + make_box( + f"{hp_id}.plinth", + (sx * 0.98, sy * 0.98, p_depth + 0.025), + "gunmetal", + parent=bay_root, + location=(0.0, 0.0, (-p_depth + 0.025) * 0.5), + bevel=0.0, + ) + # Recessed dark bay floor + make_box(f"{hp_id}.well", (sx * 0.92, sy * 0.92, depth * 0.4), "socket_bay", parent=bay_root, location=(0.0, 0.0, depth * 0.2), bevel=0.0) + # Outer armored louver frame (4 bars) + make_box(f"{hp_id}.frame_top", (sx, frame_t, depth), "gunmetal", parent=bay_root, location=(0.0, sy * 0.5 - frame_t * 0.5, depth * 0.5), bevel=0.005) + make_box(f"{hp_id}.frame_bot", (sx, frame_t, depth), "gunmetal", parent=bay_root, location=(0.0, -sy * 0.5 + frame_t * 0.5, depth * 0.5), bevel=0.005) + make_box(f"{hp_id}.frame_l", (frame_t, sy - frame_t * 2, depth), "gunmetal", parent=bay_root, location=(sx * 0.5 - frame_t * 0.5, 0.0, depth * 0.5), bevel=0.005) + make_box(f"{hp_id}.frame_r", (frame_t, sy - frame_t * 2, depth), "gunmetal", parent=bay_root, location=(-sx * 0.5 + frame_t * 0.5, 0.0, depth * 0.5), bevel=0.005) + # Copper radiator core louvers inside the bay + n_fins = max(5, min(11, int(sy / 0.065))) + def build_louvers(bm: bmesh.types.BMesh) -> None: + inner_w = sx - frame_t * 2.2 + inner_h = sy - frame_t * 2.2 + for i in range(n_fins): + y = -inner_h * 0.44 + inner_h * 0.88 * (i / max(1, n_fins - 1)) + m = ( + Matrix.Translation((0.0, y, depth * 0.58)) + @ Matrix.Rotation(math.radians(24.0), 4, "X") + @ Matrix.Diagonal((inner_w, 0.018, depth * 0.42, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + + make_bmesh_object(f"{hp_id}.louvers", build_louvers, "copper_rad", parent=bay_root) + # Corner flange bolts + signal-orange lock tabs + def build_tabs(bm: bmesh.types.BMesh) -> None: + for xs in (-1.0, 1.0): + for ys in (-1.0, 1.0): + m = Matrix.Translation((xs * (sx * 0.42), ys * (sy * 0.42), depth * 1.02)) + bmesh.ops.create_cube(bm, size=1.0, matrix=m @ Matrix.Diagonal((0.045, 0.045, 0.022, 1.0))) + + make_bmesh_object(f"{hp_id}.locktabs", build_tabs, "signal_orange", parent=bay_root) + anchor_z = depth * 0.55 + + elif kind == "engine": + wall_t = max(0.045, min(sx, sy) * 0.10) + depth = max(0.11, sz) + if p_depth > 0.0: + make_box( + f"{hp_id}.plinth", + (sx * 0.98, sy * 0.98, p_depth + 0.025), + "gunmetal", + parent=bay_root, + location=(0.0, 0.0, (-p_depth + 0.025) * 0.5), + bevel=0.0, + ) + # Deep dark engine bay recess + make_box(f"{hp_id}.well", (sx * 0.90, sy * 0.90, depth * 0.35), "socket_bay", parent=bay_root, location=(0.0, 0.0, depth * 0.18), bevel=0.0) + # Armored coaming rails + for xs in (-1.0, 1.0): + make_box(f"{hp_id}.coam_{'l' if xs > 0 else 'r'}", (wall_t, sy, depth), "gunmetal", parent=bay_root, location=(xs * (sx * 0.5 - wall_t * 0.5), 0.0, depth * 0.5), bevel=0.006) + for ys in (-1.0, 1.0): + make_box(f"{hp_id}.coam_{'b' if ys > 0 else 'f'}", (sx - wall_t * 2, wall_t, depth * 0.85), "gunmetal", parent=bay_root, location=(0.0, ys * (sy * 0.5 - wall_t * 0.5), depth * 0.42), bevel=0.006) + # Twin internal engine mount cradle rails + exhaust manifold stubs + for xs in (-1.0, 1.0): + make_box(f"{hp_id}.cradle_{'l' if xs > 0 else 'r'}", (0.05, sy * 0.72, depth * 0.45), "gunmetal", parent=bay_root, location=(xs * sx * 0.22, 0.0, depth * 0.45), bevel=0.004) + make_swept_tube( + f"{hp_id}.manifold_{'l' if xs > 0 else 'r'}", + [ + [xs * sx * 0.16, -sy * 0.26, depth * 0.55], + [xs * sx * 0.30, -sy * 0.12, depth * 0.74], + [xs * sx * 0.30, sy * 0.20, depth * 0.74], + ], + 0.022, + segments=8, + mat_name="copper_rad", + parent=bay_root, + fillet_r=0.03, + ) + # Signal-orange lock pins at corners + def build_pins(bm: bmesh.types.BMesh) -> None: + for xs in (-1.0, 1.0): + for ys in (-1.0, 1.0): + m = Matrix.Translation((xs * (sx * 0.40), ys * (sy * 0.40), depth * 1.02)) + bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=8, radius1=0.022, radius2=0.018, depth=0.036, matrix=m) + + make_bmesh_object(f"{hp_id}.lockpins", build_pins, "signal_orange", parent=bay_root) + anchor_z = depth * 0.45 + + else: # "armor" + rail_h = max(0.05, sz) + if p_depth > 0.0: + make_box( + f"{hp_id}.plinth", + (sx * 0.90, sy * 0.44, p_depth + 0.025), + "gunmetal", + parent=bay_root, + location=(0.0, 0.0, (-p_depth + 0.025) * 0.5), + bevel=0.0, + ) + # Backing plate & stud rails across the glacis / flank + make_box(f"{hp_id}.rail", (sx * 0.92, sy * 0.32, rail_h * 0.55), "gunmetal", parent=bay_root, location=(0.0, 0.0, rail_h * 0.28), bevel=0.006) + n_boss = max(3, min(5, int(sx / 0.32) + 1)) + def build_bosses(bm: bmesh.types.BMesh) -> None: + for i in range(n_boss): + x = -sx * 0.38 + sx * 0.76 * (i / max(1, n_boss - 1)) + m = Matrix.Translation((x, 0.0, rail_h * 0.65)) + bmesh.ops.create_cube(bm, size=1.0, matrix=m @ Matrix.Diagonal((0.09, sy * 0.48, rail_h * 0.45, 1.0))) + + make_bmesh_object(f"{hp_id}.bosses", build_bosses, "gunmetal", parent=bay_root) + + def build_studs(bm: bmesh.types.BMesh) -> None: + for i in range(n_boss): + x = -sx * 0.38 + sx * 0.76 * (i / max(1, n_boss - 1)) + m = Matrix.Translation((x, 0.0, rail_h * 0.98)) + bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=8, radius1=0.024, radius2=0.018, depth=0.038, matrix=m) + + make_bmesh_object(f"{hp_id}.studs", build_studs, "signal_orange", parent=bay_root) + anchor_z = rail_h * 0.75 + + # Authoritative glTF Empty anchor + anchor = make_empty( + hp_id, + parent=bay_root, + location=(0.0, 0.0, anchor_z), + rotation_deg=(0.0, 0.0, 0.0), + display_type="ARROWS", + display_size=0.18, + ) + anchor["rtd.id"] = hp_id + anchor["rtd.kind"] = kind + anchor["rtd.size"] = [float(sx), float(sy), float(sz)] + return anchor + + +def tag_joint( + node: bpy.types.Object, + joint_id: str, + axis_gltf: Sequence[float], + min_val: float, + max_val: float, +) -> bpy.types.Object: + """Tag a pivot/mechanism node with rtd.joint metadata exported in glTF extras.""" + node["rtd.joint"] = joint_id + node["rtd.axis"] = [float(axis_gltf[0]), float(axis_gltf[1]), float(axis_gltf[2])] + node["rtd.min"] = float(min_val) + node["rtd.max"] = float(max_val) + return node + + +def scene_triangle_count(context: bpy.types.Context | None = None) -> int: + ctx = context or bpy.context + depsgraph = ctx.evaluated_depsgraph_get() + total = 0 + for obj in ctx.scene.objects: + if obj.type != "MESH" or obj.name.startswith("_preview_"): + continue + ev = obj.evaluated_get(depsgraph) + me = ev.to_mesh() + me.calc_loop_triangles() + total += len(me.loop_triangles) + ev.to_mesh_clear() + return total + + +def scene_bounds_blender(context: bpy.types.Context | None = None) -> tuple[Vector, Vector]: + ctx = context or bpy.context + depsgraph = ctx.evaluated_depsgraph_get() + mins = [math.inf, math.inf, math.inf] + maxs = [-math.inf, -math.inf, -math.inf] + for obj in ctx.scene.objects: + if obj.type != "MESH" or obj.name.startswith("_preview_"): + continue + ev = obj.evaluated_get(depsgraph) + me = ev.to_mesh() + mw = obj.matrix_world + for v in me.vertices: + w = mw @ v.co + for i in range(3): + mins[i] = min(mins[i], w[i]) + maxs[i] = max(maxs[i], w[i]) + ev.to_mesh_clear() + return Vector(mins), Vector(maxs) + + +def ground_root_to_z0(root: bpy.types.Object) -> float: + """Shift root along Z so the lowest evaluated mesh vertex sits at Z = 0.""" + bpy.context.view_layer.update() + b_min, _ = scene_bounds_blender() + if math.isfinite(b_min.z) and abs(b_min.z) > 1e-5: + root.location.z -= b_min.z + bpy.context.view_layer.update() + return -b_min.z + return 0.0 + + +def bounds_gltf_from_blender(b_min: Vector, b_max: Vector) -> dict[str, list[float]]: + """Convert Blender Z-up bounds to glTF Y-up bounds: (x, y, z)_gltf = (x, z, -y)_blender.""" + g_min = [round(b_min.x, 4), round(b_min.z, 4), round(-b_max.y, 4)] + g_max = [round(b_max.x, 4), round(b_max.z, 4), round(-b_min.y, 4)] + size = [round(g_max[i] - g_min[i], 4) for i in range(3)] + return {"min": g_min, "max": g_max, "size": size} + + +def export_vehicle_glb(glb_path: Path, root: bpy.types.Object | None = None) -> tuple[int, dict[str, list[float]]]: + """Ground scene (if root given), measure evaluated tris & glTF bounds, and export .glb.""" + if root is not None: + ground_root_to_z0(root) + bpy.context.view_layer.update() + tri_count = scene_triangle_count() + b_min, b_max = scene_bounds_blender() + bounds_gltf = bounds_gltf_from_blender(b_min, b_max) + + glb_path.parent.mkdir(parents=True, exist_ok=True) + # Hide any preview helper objects if present + bpy.ops.export_scene.gltf( + filepath=str(glb_path), + export_format="GLB", + export_yup=True, + export_extras=True, + export_apply=True, + export_materials="EXPORT", + export_normals=True, + export_texcoords=True, + use_visible=True, + ) + return tri_count, bounds_gltf + + +def write_manifest( + manifest_path: Path, + *, + vehicle_id: str, + name: str, + vehicle_class: str, + grid_width: int, + grid_height: int, + mask: Sequence[str] | Sequence[bool], + hardpoints: list[dict[str, Any]], + joints: list[dict[str, Any]], + bounds: dict[str, list[float]], + tri_count: int, + plane: str = "Dorsal", + mechanisms: dict[str, Any] | None = None, +) -> None: + if len(mask) == grid_height and isinstance(mask[0], str): + mask_bools = [ch == "#" for row in mask for ch in row] + else: + mask_bools = [bool(v) for v in mask] + doc = { + "schema": "rtd.vehicle.manifest.v1", + "id": vehicle_id, + "name": name, + "class": vehicle_class, + "plane": plane, + "gridWidth": grid_width, + "gridHeight": grid_height, + "mask": mask_bools, + "hardpoints": hardpoints, + "joints": joints, + "bounds": bounds, + "triCount": int(tri_count), + } + if mechanisms is not None: + doc["mechanisms"] = mechanisms + manifest_path.parent.mkdir(parents=True, exist_ok=True) + manifest_path.write_text(json.dumps(doc, indent=2) + "\n", encoding="utf-8") + + +def _aim_camera_at(cam_obj: bpy.types.Object, eye: Vector, target: Vector) -> None: + cam_obj.location = eye + direction = (target - eye).normalized() + cam_obj.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler() + + +def render_four_panel_preview(preview_path: Path, panel_w: int = 640, panel_h: int = 480) -> Path: + """Render 3/4 Hero, Front (-Y), Side (+X), and Top Dorsal (+Z) views via EEVEE into one 2x2 PNG.""" + scene = bpy.context.scene + bpy.context.view_layer.update() + b_min, b_max = scene_bounds_blender() + center = (b_min + b_max) * 0.5 + extent = max((b_max - b_min).length, 1.5) + + # Setup world + studio lighting + ground plinth + world = bpy.data.worlds.new("_preview_world") + scene.world = world + world.use_nodes = True + bg = world.node_tree.nodes.get("Background") + if bg: + bg.inputs["Color"].default_value = (0.045, 0.050, 0.048, 1.0) + bg.inputs["Strength"].default_value = 1.1 + + # Ground disc (dark slate) + floor_mat = bpy.data.materials.new("_preview_floor_mat") + floor_mat.use_nodes = True + f_bsdf = floor_mat.node_tree.nodes.get("Principled BSDF") + if f_bsdf: + f_bsdf.inputs["Base Color"].default_value = (0.08, 0.085, 0.082, 1.0) + f_bsdf.inputs["Roughness"].default_value = 0.88 + bpy.ops.mesh.primitive_cylinder_add(vertices=48, radius=extent * 1.4, depth=0.04, location=(center.x, center.y, b_min.z - 0.021)) + floor_obj = bpy.context.active_object + floor_obj.name = "_preview_floor" + floor_obj.data.materials.append(floor_mat) + + def add_sun(name: str, rot_deg: Sequence[float], energy: float, color: Sequence[float]) -> bpy.types.Object: + ldata = bpy.data.lights.new(name, type="SUN") + ldata.energy = energy + ldata.color = color + lobj = bpy.data.objects.new(name, ldata) + scene.collection.objects.link(lobj) + lobj.rotation_euler = Euler([math.radians(a) for a in rot_deg], "XYZ") + return lobj + + lights = [ + add_sun("_preview_key", (48.0, 12.0, -35.0), 3.4, (1.0, 0.96, 0.90)), + add_sun("_preview_fill", (55.0, -15.0, 135.0), 1.4, (0.78, 0.86, 0.98)), + add_sun("_preview_rim", (25.0, 0.0, 175.0), 1.6, (1.0, 0.90, 0.78)), + ] + + cam_data = bpy.data.cameras.new("_preview_cam") + cam_data.lens = 42.0 + cam_obj = bpy.data.objects.new("_preview_cam", cam_data) + scene.collection.objects.link(cam_obj) + scene.camera = cam_obj + + scene.render.engine = "BLENDER_EEVEE" + scene.render.resolution_x = panel_w + scene.render.resolution_y = panel_h + scene.render.resolution_percentage = 100 + scene.render.image_settings.file_format = "PNG" + scene.render.image_settings.color_mode = "RGBA" + if hasattr(scene, "eevee"): + scene.eevee.taa_render_samples = 16 + + size_vec = b_max - b_min + d_hero = extent * 1.18 + d_ortho = max(size_vec.x, size_vec.y, size_vec.z) * 1.25 + + views = [ + ("hero", "PERSP", center + Vector((d_hero * 0.72, -d_hero * 0.85, d_hero * 0.46)), center), + ("front", "ORTHO", center + Vector((0.0, -d_ortho * 2.0, size_vec.z * 0.04)), center), + ("side", "ORTHO", center + Vector((d_ortho * 2.0, 0.0, size_vec.z * 0.04)), center), + ("top", "ORTHO", center + Vector((0.0, 0.0, d_ortho * 2.0)), center), + ] + + preview_path.parent.mkdir(parents=True, exist_ok=True) + tmp_files: list[Path] = [] + panels: list[np.ndarray] = [] + + for idx, (tag, proj, eye, tgt) in enumerate(views): + cam_data.type = proj + if proj == "ORTHO": + aspect = panel_w / max(1, panel_h) + if tag == "front": + cam_data.ortho_scale = max(size_vec.x * 1.32, size_vec.z * aspect * 1.38) + elif tag == "side": + cam_data.ortho_scale = max(size_vec.y * 1.24, size_vec.z * aspect * 1.35) + else: + cam_data.ortho_scale = max(size_vec.x * 1.30, size_vec.y * aspect * 1.22) + _aim_camera_at(cam_obj, eye, tgt) + # Keep top view upright with nose (-Y) pointing up in image + if tag == "top": + cam_obj.rotation_euler = Euler((0.0, 0.0, math.radians(180.0)), "XYZ") + + tmp_png = preview_path.with_name(f".tmp_{preview_path.stem}_{tag}.png") + tmp_files.append(tmp_png) + scene.render.filepath = str(tmp_png) + bpy.ops.render.render(write_still=True) + + img = bpy.data.images.load(str(tmp_png), check_existing=False) + arr = np.empty(panel_w * panel_h * 4, dtype=np.float32) + img.pixels.foreach_get(arr) + bpy.data.images.remove(img) + panels.append(arr.reshape((panel_h, panel_w, 4))) + + # Stitch 2x2 grid (note Blender image pixel row 0 is bottom): + # Top row in final PNG = [hero (TL), front (TR)] -> higher Y in Blender image space + # Bottom row in final PNG = [side (BL), top (BR)] -> lower Y in Blender image space + top_row = np.concatenate([panels[0], panels[1]], axis=1) + bot_row = np.concatenate([panels[2], panels[3]], axis=1) + # 4px dark divider lines + grid = np.concatenate([bot_row, top_row], axis=0) + grid[:, panel_w - 2 : panel_w + 2, :3] = 0.25 + grid[panel_h - 2 : panel_h + 2, :, :3] = 0.25 + + out_img = bpy.data.images.new("_preview_composite", width=panel_w * 2, height=panel_h * 2, alpha=True) + out_img.pixels.foreach_set(grid.ravel().tolist()) + out_img.filepath_raw = str(preview_path) + out_img.file_format = "PNG" + out_img.save() + bpy.data.images.remove(out_img) + + # Cleanup temp renders and preview objects + for tmp in tmp_files: + if tmp.exists(): + tmp.unlink() + for obj in [floor_obj, cam_obj, *lights]: + bpy.data.objects.remove(obj, do_unlink=True) + bpy.data.materials.remove(floor_mat) + bpy.data.worlds.remove(world) + + return preview_path diff --git a/tools/vehicles/verify_glbs.py b/tools/vehicles/verify_glbs.py new file mode 100644 index 0000000..4d6b72b --- /dev/null +++ b/tools/vehicles/verify_glbs.py @@ -0,0 +1,637 @@ +"""Validate all exported vehicle GLBs, manifests, hardpoint anchors, joints, bounds, and gear GLBs.""" +from __future__ import annotations + +import json +import math +import struct +import sys +from pathlib import Path +from typing import Any + +import numpy as np + +REPO_ROOT = Path(__file__).resolve().parents[2] +VEHICLES_DIR = REPO_ROOT / "assets" / "vehicles" +GEAR_DIR = REPO_ROOT / "assets" / "gear" +WEAPON_PARTS_DIR = GEAR_DIR / "parts" + +EXPECTED_VEHICLES = ( + "jackal", "mule", "ferret", "hornet", "mammoth", "ironclad", "anvil", "condor", + "breaker", "paladin", "raptor", "manticore", "bastion", "spectre", "kestrel", +) +RETROFIT_MECHS = frozenset({"breaker", "paladin", "raptor", "manticore", "bastion", "spectre", "kestrel"}) +EXPECTED_GEAR = ("mg_762", "autocannon", "recoilless", "copper_rad", "gilded_lance", "gold_radiator") +EXPECTED_WEAPON_PARTS = { + "receiver": ("rx_salvage_frame", "rx_korrathi_cradle", "rx_auralian_prism", "rx_vex_pod_rack"), + "barrel": ("brl_autocannon", "brl_sabot_rail", "brl_prism_lance", "brl_missile_tube"), + "feed": ("fd_belt_drum", "fd_rotary_loader", "fd_capacitor_bank", "fd_swarm_magazine"), + "muzzle": ("mz_slotted_brake", "mz_mirv_warhead", "mz_loiter_aero_fin", "mz_plasma_diffuser"), +} + + +def parse_glb(glb_path: Path) -> tuple[dict[str, Any], bytes]: + data = glb_path.read_bytes() + if len(data) < 20: + raise AssertionError(f"{glb_path}: file too small ({len(data)} bytes)") + magic, version, total_len = struct.unpack_from(" dict[str, Any]: + return parse_glb(glb_path)[0] + + +def _node_local_matrix(node: dict[str, Any]) -> np.ndarray: + if "matrix" in node: + return np.array(node["matrix"], dtype=np.float64).reshape(4, 4).T + m = np.eye(4, dtype=np.float64) + if "scale" in node: + sx, sy, sz = node["scale"] + m = m @ np.diag([sx, sy, sz, 1.0]) + if "rotation" in node: + qx, qy, qz, qw = node["rotation"] + xx, yy, zz = qx * qx, qy * qy, qz * qz + xy, xz, yz = qx * qy, qx * qz, qy * qz + wx, wy, wz = qw * qx, qw * qy, qw * qz + r = np.array([ + [1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy), 0.0], + [2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx), 0.0], + [2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy), 0.0], + [0.0, 0.0, 0.0, 1.0], + ], dtype=np.float64) + m = r @ m + if "translation" in node: + tx, ty, tz = node["translation"] + m[:3, 3] = [tx, ty, tz] + return m + + +def compute_glb_stats(gltf: dict[str, Any], bin_blob: bytes = b"") -> tuple[int, np.ndarray, np.ndarray]: + nodes = gltf.get("nodes", []) + meshes = gltf.get("meshes", []) + accessors = gltf.get("accessors", []) + buffer_views = gltf.get("bufferViews", []) + scenes = gltf.get("scenes", []) + root_indices = scenes[gltf.get("scene", 0)]["nodes"] if scenes else list(range(len(nodes))) + + tri_total = 0 + g_min = np.array([math.inf, math.inf, math.inf], dtype=np.float64) + g_max = np.array([-math.inf, -math.inf, -math.inf], dtype=np.float64) + + def walk(node_idx: int, parent_mat: np.ndarray) -> None: + nonlocal tri_total, g_min, g_max + node = nodes[node_idx] + world = parent_mat @ _node_local_matrix(node) + if "mesh" in node: + mesh = meshes[node["mesh"]] + for prim in mesh.get("primitives", []): + mode = prim.get("mode", 4) + if mode == 4: + if "indices" in prim: + tri_total += accessors[prim["indices"]]["count"] // 3 + elif "POSITION" in prim.get("attributes", {}): + tri_total += accessors[prim["attributes"]["POSITION"]]["count"] // 3 + pos_acc_idx = prim.get("attributes", {}).get("POSITION") + if pos_acc_idx is not None: + acc = accessors[pos_acc_idx] + if bin_blob and "bufferView" in acc and acc.get("componentType") == 5126 and acc.get("type") == "VEC3": + bv = buffer_views[acc["bufferView"]] + off = bv.get("byteOffset", 0) + acc.get("byteOffset", 0) + stride = bv.get("byteStride", 12) + count = acc["count"] + if stride == 12: + pts = np.frombuffer(bin_blob, dtype=" np.ndarray: + acc = accessors[acc_idx] + bv = buffer_views[acc["bufferView"]] + off = bv.get("byteOffset", 0) + acc.get("byteOffset", 0) + count = acc["count"] + ct = acc["componentType"] + typ = acc["type"] + if typ == "VEC3" and ct == 5126: + stride = bv.get("byteStride", 12) + if stride == 12: + return np.frombuffer(bin_blob, dtype=" float: + ab = b - a + ac = c - a + ap = p - a + d1 = float(np.dot(ab, ap)) + d2 = float(np.dot(ac, ap)) + if d1 <= 0.0 and d2 <= 0.0: + return float(np.dot(ap, ap)) + bp = p - b + d3 = float(np.dot(ab, bp)) + d4 = float(np.dot(ac, bp)) + if d3 >= 0.0 and d4 <= d3: + return float(np.dot(bp, bp)) + vc = d1 * d4 - d3 * d2 + if vc <= 0.0 and d1 >= 0.0 and d3 <= 0.0: + denom = d1 - d3 + v = d1 / denom if denom > 1e-18 else 0.0 + q = a + v * ab + return float(np.dot(p - q, p - q)) + cp = p - c + d5 = float(np.dot(ab, cp)) + d6 = float(np.dot(ac, cp)) + if d6 >= 0.0 and d5 <= d6: + return float(np.dot(cp, cp)) + vb = d5 * d2 - d1 * d6 + if vb <= 0.0 and d2 >= 0.0 and d6 <= 0.0: + denom = d2 - d6 + w = d2 / denom if denom > 1e-18 else 0.0 + q = a + w * ac + return float(np.dot(p - q, p - q)) + va = d3 * d6 - d5 * d4 + if va <= 0.0 and (d4 - d3) >= 0.0 and (d5 - d6) >= 0.0: + denom = (d4 - d3) + (d5 - d6) + w = (d4 - d3) / denom if denom > 1e-18 else 0.0 + q = b + w * (c - b) + return float(np.dot(p - q, p - q)) + s = va + vb + vc + if s <= 1e-18: + return min(float(np.dot(ap, ap)), float(np.dot(bp, bp)), float(np.dot(cp, cp))) + denom = 1.0 / s + q = a + ab * (vb * denom) + ac * (vc * denom) + return float(np.dot(p - q, p - q)) + + +def _min_dist_to_tris( + pt: np.ndarray, + tris: np.ndarray, + tri_mins: np.ndarray, + tri_maxs: np.ndarray, +) -> float: + d_box = np.maximum(0.0, np.maximum(tri_mins - pt, pt - tri_maxs)) + d2_box = np.sum(d_box * d_box, axis=1) + order = np.argsort(d2_box) + min_d2 = math.inf + for idx in order: + if d2_box[idx] > min_d2: + break + t = tris[idx] + d2 = _pt_tri_dist2(pt, t[0], t[1], t[2]) + if d2 < min_d2: + min_d2 = d2 + return math.sqrt(min_d2) + + +def measure_hardpoint_gaps(gltf: dict[str, Any], bin_blob: bytes) -> dict[str, tuple[float, float]]: + """Return {hp_id: (center_to_hull_m, min_slot_vert_to_hull_m)} for all hardpoints in GLB.""" + nodes = gltf.get("nodes", []) + meshes = gltf.get("meshes", []) + accessors = gltf.get("accessors", []) + buffer_views = gltf.get("bufferViews", []) + scenes = gltf.get("scenes", []) + root_indices = scenes[gltf.get("scene", 0)]["nodes"] if scenes else list(range(len(nodes))) + + parent_of: dict[int, int] = {} + for idx, n in enumerate(nodes): + for c in n.get("children", []): + parent_of[c] = idx + + hp_roots: dict[int, str] = {} + hp_anchors: dict[str, int] = {} + for idx, n in enumerate(nodes): + extras = n.get("extras") or {} + if "rtd.id" in extras: + hp_id = str(extras["rtd.id"]) + hp_anchors[hp_id] = idx + p = parent_of.get(idx) + if p is not None and str(nodes[p].get("name", "")).startswith("slot_frame."): + hp_roots[p] = hp_id + + hp_node_set: dict[int, str] = {} + def mark_hp(idx: int, hp_id: str) -> None: + hp_node_set[idx] = hp_id + for c in nodes[idx].get("children", []): + mark_hp(c, hp_id) + for r_idx, hp_id in hp_roots.items(): + mark_hp(r_idx, hp_id) + + hull_tris: list[np.ndarray] = [] + hp_pts: dict[str, list[np.ndarray]] = {} + node_world: dict[int, np.ndarray] = {} + + def walk(idx: int, pmat: np.ndarray) -> None: + n = nodes[idx] + w = pmat @ _node_local_matrix(n) + node_world[idx] = w + if "mesh" in n: + for prim in meshes[n["mesh"]].get("primitives", []): + if prim.get("mode", 4) != 4: + continue + pos = _read_accessor(accessors, buffer_views, bin_blob, prim["attributes"]["POSITION"]) + wpos = pos @ w[:3, :3].T + w[:3, 3] + if idx in hp_node_set: + hp_pts.setdefault(hp_node_set[idx], []).append(wpos) + else: + if "indices" in prim: + ind = _read_accessor(accessors, buffer_views, bin_blob, prim["indices"]).reshape(-1, 3) + else: + ind = np.arange(len(pos), dtype=np.int64).reshape(-1, 3) + hull_tris.append(wpos[ind]) + for c in n.get("children", []): + walk(c, w) + + ident = np.eye(4, dtype=np.float64) + for r_idx in root_indices: + walk(r_idx, ident) + + if not hull_tris: + return {} + tris = np.concatenate(hull_tris, axis=0) + tri_mins = tris.min(axis=1) + tri_maxs = tris.max(axis=1) + + gaps: dict[str, tuple[float, float]] = {} + for r_idx, hp_id in hp_roots.items(): + p_slot = node_world[r_idx][:3, 3] + p_anchor = node_world[hp_anchors[hp_id]][:3, 3] + out_vec = p_anchor - p_slot + out_len = float(np.linalg.norm(out_vec)) + n_out = out_vec / out_len if out_len > 1e-6 else np.array([0.0, 1.0, 0.0]) + + d_center = _min_dist_to_tris(p_slot, tris, tri_mins, tri_maxs) + pts = np.concatenate(hp_pts.get(hp_id, []), axis=0) if hp_id in hp_pts else np.empty((0, 3)) + if len(pts) > 0: + proj = (pts - p_slot) @ n_out + base_pts = pts[proj <= 0.03] + if len(base_pts) == 0: + base_pts = pts + if len(base_pts) > 256: + base_pts = base_pts[np.linspace(0, len(base_pts) - 1, 256, dtype=int)] + d_vert = min(_min_dist_to_tris(p, tris, tri_mins, tri_maxs) for p in base_pts) + else: + d_vert = d_center + gaps[hp_id] = (d_center, d_vert) + return gaps + + +def validate_vehicle(vid: str) -> dict[str, Any]: + vdir = VEHICLES_DIR / vid + glb_path = vdir / f"{vid}.glb" + manifest_path = vdir / "manifest.json" + if not glb_path.is_file(): + raise AssertionError(f"Missing GLB: {glb_path}") + if not manifest_path.is_file(): + raise AssertionError(f"Missing manifest: {manifest_path}") + + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + gltf, bin_blob = parse_glb(glb_path) + nodes = gltf.get("nodes", []) + + # 1. Check hardpoint grid bounds, mask activity, and zero overlaps + gw, gh = int(manifest["gridWidth"]), int(manifest["gridHeight"]) + mask = manifest["mask"] + if len(mask) != gw * gh: + raise AssertionError(f"{vid}: mask length {len(mask)} != {gw * gh}") + + occupied: dict[tuple[int, int], str] = {} + for hp in manifest["hardpoints"]: + hx, hy, hw, hh = hp["x"], hp["y"], hp["w"], hp["h"] + if not (0 <= hx and hx + hw <= gw and 0 <= hy and hy + hh <= gh): + raise AssertionError(f"{vid}: hardpoint {hp['id']} out of grid bounds ({hx},{hy} {hw}x{hh} on {gw}x{gh})") + for cy in range(hy, hy + hh): + for cx in range(hx, hx + hw): + if not mask[cy * gw + cx]: + raise AssertionError(f"{vid}: hardpoint {hp['id']} covers inactive cell ({cx},{cy})") + if (cx, cy) in occupied: + raise AssertionError(f"{vid}: cell ({cx},{cy}) overlaps between {occupied[(cx, cy)]} and {hp['id']}") + occupied[(cx, cy)] = hp["id"] + + # 2. Check every manifest hardpoint modelNodeId exists as a unique node with extras["rtd.id"] and extras["rtd.kind"] + by_rtd_id: dict[str, list[dict]] = {} + by_rtd_joint: dict[str, list[dict]] = {} + for node in nodes: + extras = node.get("extras") or {} + if "rtd.id" in extras: + by_rtd_id.setdefault(str(extras["rtd.id"]), []).append(node) + if "rtd.joint" in extras: + by_rtd_joint.setdefault(str(extras["rtd.joint"]), []).append(node) + + for hp in manifest["hardpoints"]: + target_id = hp["modelNodeId"] + matches = by_rtd_id.get(target_id, []) + if len(matches) != 1: + raise AssertionError(f"{vid}: hardpoint {target_id!r} matched {len(matches)} GLB nodes (expected 1)") + node = matches[0] + extras = node.get("extras", {}) + if extras.get("rtd.kind") != hp["kind"]: + raise AssertionError(f"{vid}: node {target_id} rtd.kind={extras.get('rtd.kind')!r} != manifest {hp['kind']!r}") + if node.get("name") != target_id: + raise AssertionError(f"{vid}: node name {node.get('name')!r} != {target_id!r}") + + # 3. Check every manifest joint exists with rtd.joint, rtd.axis, rtd.min, rtd.max + for j in manifest["joints"]: + jid = j["id"] + matches = by_rtd_joint.get(jid, []) + if len(matches) != 1: + raise AssertionError(f"{vid}: joint {jid!r} matched {len(matches)} GLB nodes (expected 1)") + extras = matches[0].get("extras", {}) + for key in ("rtd.axis", "rtd.min", "rtd.max"): + if key not in extras: + raise AssertionError(f"{vid}: joint {jid!r} missing {key} in GLB extras") + + plane = manifest.get("plane") + if plane not in ("Dorsal", "Coronal"): + raise AssertionError(f"{vid}: invalid plane {plane!r}") + + # 3b. Check every mesh primitive carries baked COLOR_0 attributes (AO, Edge, Island, RestHeight) + meshes = gltf.get("meshes", []) + if not meshes: + raise AssertionError(f"{vid}: GLB contains no meshes") + prim_count = 0 + for m_idx, mesh in enumerate(meshes): + for p_idx, prim in enumerate(mesh.get("primitives", [])): + attrs = prim.get("attributes") or {} + if "COLOR_0" not in attrs: + raise AssertionError( + f"{vid}: mesh[{m_idx}] ({mesh.get('name', '?')}) primitive[{p_idx}] missing COLOR_0 attribute" + ) + prim_count += 1 + if prim_count == 0: + raise AssertionError(f"{vid}: GLB contains zero mesh primitives") + + # 4. Check GLB triangle count & grounded +Y-up / +Z-forward bounds + tri_total, g_min, g_max = compute_glb_stats(gltf, bin_blob) + max_tris = 50000 if vid in RETROFIT_MECHS else 35000 + min_tris = 15000 if vid in RETROFIT_MECHS else 1500 + if not (min_tris <= tri_total <= max_tris): + raise AssertionError(f"{vid}: tri count {tri_total} outside [{min_tris}, {max_tris}]") + if abs(tri_total - manifest["triCount"]) > 0: + raise AssertionError(f"{vid}: GLB tri count {tri_total} != manifest triCount {manifest['triCount']}") + if abs(float(g_min[1])) > 0.02: + raise AssertionError(f"{vid}: GLB not grounded at minY=0 (got minY={g_min[1]:.4f})") + size = g_max - g_min + if vid in RETROFIT_MECHS: + if not (2.5 <= size[0] <= 14.0 and 5.0 <= size[1] <= 12.5 and 2.5 <= size[2] <= 16.0): + raise AssertionError(f"{vid}: implausible mech bounds size {size.tolist()}") + elif not (1.2 <= size[0] <= 5.0 and 1.0 <= size[1] <= 3.5 and 2.5 <= size[2] <= 6.5): + raise AssertionError(f"{vid}: implausible bounds size {size.tolist()}") + + # 5. Flush-seating check: every hardpoint slot center and base vertices must sit <= 0.025m from hull geometry + hp_gaps = measure_hardpoint_gaps(gltf, bin_blob) + if len(hp_gaps) != len(manifest["hardpoints"]): + raise AssertionError(f"{vid}: measured {len(hp_gaps)} hardpoint slots != manifest {len(manifest['hardpoints'])}") + max_gap = 0.0 + for hp in manifest["hardpoints"]: + hid = hp["modelNodeId"] + d_center, d_vert = hp_gaps[hid] + if d_center > 0.025 or d_vert > 0.025: + raise AssertionError( + f"{vid}: floating/buried hardpoint {hid!r} (center_to_hull={d_center:.4f}m, base_to_hull={d_vert:.4f}m > 0.025m)" + ) + max_gap = max(max_gap, d_center, d_vert) + + return { + "id": vid, + "plane": plane, + "tris": tri_total, + "bytes": glb_path.stat().st_size, + "hardpoints": len(manifest["hardpoints"]), + "joints": len(manifest["joints"]), + "mechanisms": len((manifest.get("mechanisms") or {}).get("dofs", [])), + "minY": round(float(g_min[1]), 4), + "maxHpGap": round(max_gap, 4), + "size": [round(float(v), 3) for v in size], + } + + +def validate_gear(gid: str) -> dict[str, Any]: + glb_path = GEAR_DIR / f"{gid}.glb" + if not glb_path.is_file(): + raise AssertionError(f"Missing gear GLB: {glb_path}") + gltf, bin_blob = parse_glb(glb_path) + tri_total, g_min, g_max = compute_glb_stats(gltf, bin_blob) + if tri_total <= 0 or tri_total > 10000: + raise AssertionError(f"gear/{gid}: unexpected tri count {tri_total}") + if abs(float(g_min[1])) > 0.02: + raise AssertionError(f"gear/{gid}: not grounded at minY=0 (got {g_min[1]:.4f})") + return { + "id": gid, + "tris": tri_total, + "bytes": glb_path.stat().st_size, + "size": [round(float(v), 3) for v in (g_max - g_min)], + } + + +def validate_drop_pod() -> dict[str, Any]: + glb_path = VEHICLES_DIR / "drop_pod" / "drop_pod.glb" + if not glb_path.is_file(): + raise AssertionError(f"Missing drop_pod GLB: {glb_path}") + gltf, bin_blob = parse_glb(glb_path) + tri_total, g_min, g_max = compute_glb_stats(gltf, bin_blob) + if tri_total < 400 or tri_total > 12000: + raise AssertionError(f"drop_pod: unexpected tri count {tri_total}") + if abs(float(g_min[1])) > 0.02: + raise AssertionError(f"drop_pod: not grounded at minY=0 (got {g_min[1]:.4f})") + + size = g_max - g_min + if size[1] < 4.0 or size[1] > 5.2 or size[0] < 2.2 or size[0] > 3.4: + raise AssertionError(f"drop_pod: unexpected dimensions {size}") + + nodes = gltf.get("nodes", []) + meshes = gltf.get("meshes", []) + accessors = gltf.get("accessors", []) + buffer_views = gltf.get("bufferViews", []) + node_names = {n.get("name", ""): n for n in nodes} + + for req in ("DropPodRoot", "CoreBody", "RetroNozzle"): + if req not in node_names: + raise AssertionError(f"drop_pod: missing required node {req!r}") + + petal_centroids = [] + for i in range(4): + pname = f"Petal_{i}" + if pname not in node_names or "mesh" not in node_names[pname]: + raise AssertionError(f"drop_pod: missing mesh node {pname!r}") + p_mesh = meshes[node_names[pname]["mesh"]] + p_min = np.array([math.inf, math.inf, math.inf], dtype=np.float64) + p_max = np.array([-math.inf, -math.inf, -math.inf], dtype=np.float64) + for prim in p_mesh.get("primitives", []): + attrs = prim.get("attributes", {}) + if "COLOR_0" not in attrs: + raise AssertionError(f"drop_pod: {pname} primitive missing COLOR_0 weathering") + pts = _read_accessor(accessors, buffer_views, bin_blob, attrs["POSITION"]) + p_min = np.minimum(p_min, pts.min(axis=0)) + p_max = np.maximum(p_max, pts.max(axis=0)) + local_center = (p_min + p_max) * 0.5 + offset = float(np.linalg.norm(local_center)) + if offset > 0.03: + raise AssertionError(f"drop_pod: {pname} local origin not at centroid (offset={offset:.4f}m)") + petal_centroids.append(round(offset, 5)) + + for m_idx, mesh in enumerate(meshes): + for prim in mesh.get("primitives", []): + if "COLOR_0" not in prim.get("attributes", {}): + raise AssertionError(f"drop_pod: mesh[{m_idx}] missing COLOR_0 weathering") + + return { + "id": "drop_pod", + "tris": tri_total, + "bytes": glb_path.stat().st_size, + "minY": round(float(g_min[1]), 4), + "size": [round(float(v), 3) for v in size], + "petalOffsets": petal_centroids, + } + + +def validate_weapon_part(slot: str, pid: str) -> dict[str, Any]: + glb_path = WEAPON_PARTS_DIR / f"{pid}.glb" + if not glb_path.is_file(): + raise AssertionError(f"Missing weapon part GLB: {glb_path}") + gltf, bin_blob = parse_glb(glb_path) + nodes = gltf.get("nodes", []) + meshes = gltf.get("meshes", []) + if not meshes: + raise AssertionError(f"gear/parts/{pid}: GLB contains no meshes") + + for m_idx, mesh in enumerate(meshes): + for p_idx, prim in enumerate(mesh.get("primitives", [])): + attrs = prim.get("attributes") or {} + if "COLOR_0" not in attrs: + raise AssertionError(f"gear/parts/{pid}: mesh[{m_idx}] prim[{p_idx}] missing COLOR_0 weathering") + + tri_total, g_min, g_max = compute_glb_stats(gltf, bin_blob) + if tri_total < 24 or tri_total > 4000: + raise AssertionError(f"gear/parts/{pid}: unexpected tri count {tri_total}") + if not np.all(np.isfinite(g_min)) or not np.all(np.isfinite(g_max)): + raise AssertionError(f"gear/parts/{pid}: non-finite bounds") + size = g_max - g_min + if np.any(size <= 0.01): + raise AssertionError(f"gear/parts/{pid}: degenerate bounds size={size.tolist()}") + + # Compute world positions of rtd.socket nodes + scenes = gltf.get("scenes", []) + root_indices = scenes[gltf.get("scene", 0)]["nodes"] if scenes else list(range(len(nodes))) + sockets: dict[str, np.ndarray] = {} + found_slot: str | None = None + + def walk_sockets(idx: int, parent_mat: np.ndarray) -> None: + nonlocal found_slot + node = nodes[idx] + world = parent_mat @ _node_local_matrix(node) + extras = node.get("extras") or {} + if "rtd.part_slot" in extras: + found_slot = str(extras["rtd.part_slot"]) + if "rtd.socket" in extras: + sockets[str(extras["rtd.socket"])] = world[:3, 3] + for child_idx in node.get("children", []): + walk_sockets(child_idx, world) + + ident = np.eye(4, dtype=np.float64) + for r_idx in root_indices: + walk_sockets(r_idx, ident) + + if found_slot != slot: + raise AssertionError(f"gear/parts/{pid}: rtd.part_slot={found_slot!r} != expected {slot!r}") + + if slot == "receiver": + if abs(float(g_min[1])) > 0.02: + raise AssertionError(f"gear/parts/{pid}: receiver not grounded at minY=0 (got {g_min[1]:.4f})") + for req_sock in ("barrel", "feed"): + if req_sock not in sockets: + raise AssertionError(f"gear/parts/{pid}: missing socket {req_sock!r}") + if sockets["barrel"][2] <= 0.05: + raise AssertionError(f"gear/parts/{pid}: barrel socket not forward (+Z), got z={sockets['barrel'][2]:.4f}") + elif slot == "barrel": + if "muzzle" not in sockets: + raise AssertionError(f"gear/parts/{pid}: missing socket 'muzzle'") + if sockets["muzzle"][2] <= 0.25 or float(g_max[2]) < 0.25: + raise AssertionError(f"gear/parts/{pid}: barrel does not extend forward (+Z), maxZ={g_max[2]:.4f}, muzzle={sockets['muzzle'].tolist()}") + elif slot == "muzzle": + if "muzzle_tip" not in sockets: + raise AssertionError(f"gear/parts/{pid}: missing socket 'muzzle_tip'") + if sockets["muzzle_tip"][2] <= 0.05 or float(g_max[2]) < 0.08: + raise AssertionError(f"gear/parts/{pid}: muzzle does not extend forward (+Z), maxZ={g_max[2]:.4f}, tip={sockets['muzzle_tip'].tolist()}") + + return { + "id": pid, + "slot": slot, + "tris": tri_total, + "bytes": glb_path.stat().st_size, + "size": [round(float(v), 3) for v in size], + "sockets": sorted(sockets.keys()), + } + + +def main() -> int: + v_reports = [validate_vehicle(v) for v in EXPECTED_VEHICLES] + g_reports = [validate_gear(g) for g in EXPECTED_GEAR] + pod_report = validate_drop_pod() + part_reports = [ + validate_weapon_part(slot, pid) + for slot, pids in EXPECTED_WEAPON_PARTS.items() + for pid in pids + ] + print("=== VEHICLE GLB VALIDATION PASSED ===") + for r in v_reports: + mech_tag = f" | dofs={r['mechanisms']}" if r["mechanisms"] else "" + print(f" {r['id']:10s} | {r['plane']:7s} | tris={r['tris']:5d} | size={r['size']} | minY={r['minY']} | hpGap={r['maxHpGap']:.4f}m | hps={r['hardpoints']} | joints={r['joints']}{mech_tag} | {r['bytes']/1024:.1f} KiB") + print("=== GEAR GLB VALIDATION PASSED ===") + for r in g_reports: + print(f" {r['id']:14s} | tris={r['tris']:4d} | size={r['size']} | {r['bytes']/1024:.1f} KiB") + print("=== DROP POD GLB VALIDATION PASSED ===") + print(f" {pod_report['id']:10s} | tris={pod_report['tris']:5d} | size={pod_report['size']} | minY={pod_report['minY']} | petalPivotOffsets={pod_report['petalOffsets']} | {pod_report['bytes']/1024:.1f} KiB") + print(f"=== MODULAR WEAPON PARTS VALIDATION PASSED ({len(part_reports)} PARTS) ===") + for r in part_reports: + print(f" {r['slot']:8s} | {r['id']:20s} | tris={r['tris']:4d} | size={r['size']} | sockets={r['sockets']} | {r['bytes']/1024:.1f} KiB") + return 0 + + +if __name__ == "__main__": + sys.exit(main())