From ca6ce5a2e1f9d81b51cbd7f1edcd5340e4183455 Mon Sep 17 00:00:00 2001 From: Vorta <179685+Vorta@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:57:58 +0100 Subject: [PATCH] Add MW3 valve authoring and live testing --- CHANGELOG.md | 5 +- CLAUDE.md | 6 +- docs/agents/engine-evidence.md | 11 + docs/agents/pr-watch.md | 2 +- docs/agents/testing.md | 1 + docs/agents/workbench.md | 15 +- docs/map-editor.md | 2 +- docs/mcp-capabilities.json | 37 +- docs/mcp.md | 5 + docs/mw3-source-project.md | 33 +- .../Animation/AnimationPlayer.Events.cs | 1 + .../Animation/AnimationPlayer.Mission.cs | 12 + .../Animation/AnimationPlayer.Valves.cs | 107 +++ src/zStudio.Core/Animation/AnimationPlayer.cs | 3 +- .../Animation/AnimationPreviewContext.cs | 2 + src/zStudio.Core/MissionAiNetworks.cs | 13 +- src/zStudio.Core/MissionAiValves.cs | 128 ++-- .../MissionSceneContext.Transforms.cs | 7 +- .../MissionSceneContext.Valves.cs | 41 ++ src/zStudio.Core/MissionSceneLoader.Mw3.cs | 6 +- src/zStudio.Core/Mw3ValveMap.cs | 476 +++++++++++++ src/zStudio.Core/Mw3ValveProgram.cs | 159 +++++ src/zStudio.Core/Mw3ValveRoutes.cs | 48 ++ src/zStudio.Core/Mw3ValveRuntime.cs | 216 ++++++ src/zStudio.Core/Mw3ValveSimulation.cs | 266 +++++++ src/zStudio.Core/Sources/SourceValveEdits.cs | 426 +++++++++++ src/zStudio.Desktop/AnimationAudio.cs | 13 +- .../MainWindow.AnimationMode.cs | 1 + src/zStudio.Desktop/MainWindow.Mcp.cs | 2 + src/zStudio.Desktop/MainWindow.Properties.cs | 13 +- src/zStudio.Desktop/MainWindow.SceneTree.cs | 21 +- .../MainWindow.SceneTreeLayout.cs | 7 + .../MainWindow.SourceEditor.cs | 11 +- .../MainWindow.SourceSections.cs | 68 ++ .../MainWindow.ValveAuthoring.cs | 463 ++++++++++++ .../MainWindow.ValvePreview.cs | 664 ++++++++++++++++++ .../MainWindow.WorldAnimation.cs | 3 + src/zStudio.Desktop/MainWindow.xaml | 9 +- src/zStudio.Desktop/OutlinerKinds.cs | 16 +- src/zStudio.Desktop/PreviewIcon.cs | 7 + src/zStudio.Desktop/SceneTreeModel.cs | 64 +- src/zStudio.Desktop/SourceMapSections.cs | 8 + .../SourceSectionCard.Valves.cs | 543 ++++++++++++++ src/zStudio.Desktop/SourceSectionCard.cs | 18 +- src/zStudio.Mcp/CommandCatalog.json | 457 +++++++++++- .../SceneViewport.Framing.cs | 4 +- src/zStudio.Rendering/SceneViewport.Valves.cs | 38 +- .../AnimationAudioTests.cs | 13 + .../McpLazyConnectorTests.cs | 2 +- .../zStudio.Desktop.Tests/McpParityChecks.cs | 2 +- .../Mw3SourceAuthoringMcpChecks.cs | 146 +++- tests/zStudio.Tests/AiValveTests.cs | 2 +- tests/zStudio.Tests/Mw3PreviewParityTests.cs | 161 +++++ tests/zStudio.Tests/Mw3ValveMapTests.cs | 175 +++++ tests/zStudio.Tests/Mw3ValveRuntimeTests.cs | 127 ++++ .../Mw3SourceLiveCheck.cs | 33 +- 56 files changed, 4994 insertions(+), 125 deletions(-) create mode 100644 src/zStudio.Core/Animation/AnimationPlayer.Valves.cs create mode 100644 src/zStudio.Core/MissionSceneContext.Valves.cs create mode 100644 src/zStudio.Core/Mw3ValveMap.cs create mode 100644 src/zStudio.Core/Mw3ValveProgram.cs create mode 100644 src/zStudio.Core/Mw3ValveRoutes.cs create mode 100644 src/zStudio.Core/Mw3ValveRuntime.cs create mode 100644 src/zStudio.Core/Mw3ValveSimulation.cs create mode 100644 src/zStudio.Core/Sources/SourceValveEdits.cs create mode 100644 src/zStudio.Desktop/MainWindow.ValveAuthoring.cs create mode 100644 src/zStudio.Desktop/MainWindow.ValvePreview.cs create mode 100644 src/zStudio.Desktop/SourceSectionCard.Valves.cs create mode 100644 tests/zStudio.Tests/Mw3ValveMapTests.cs create mode 100644 tests/zStudio.Tests/Mw3ValveRuntimeTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 60b1f566..7b399b4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,9 +4,10 @@ Version numbers follow `MAJOR.MINOR.PATCH`; the 0.x series is under active devel ## 0.12.1 — Unreleased -- AI networks in RECOIL and MW3 use clickable circular node markers and directed triangles. - +- MW3 source maps list a mission's valves in the World tree, one per name, each with what it does. A valve's card shows what sets it, its reactions and what waits on it, with links to the vehicles, route nodes and valves involved, and edits its starting value, computed inputs and reactions with pickers; rename, delete and new valves are single undoable changes that keep the files' comments and layout. +- Test valves runs a mission's valves in memory: set a valve and watch its timers, sounds, animations, vehicle changes and route gates follow, with the test's time, values and activity shown in the view, the tree and the card. Nothing is saved. - zStudio is built on .NET 11 (included in `zStudio.exe`; nothing to install). +- AI networks in RECOIL and MW3 use clickable circular node markers and directed triangles. Valve-controlled routes remain visible with their simulated availability. ## 0.12.0 — 2026-11-08 diff --git a/CLAUDE.md b/CLAUDE.md index 0e7b8139..0921c182 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,5 +1,9 @@ # Claude Code guidance -Claude Code follows the same project guidance as Codex. `AGENTS.md` is the single source of truth; keep instructions there rather than duplicating or diverging from them here. +Claude Code follows the same project guidance as Codex. `AGENTS.md` is the single source of truth; keep instructions there rather than duplicating or diverging from them here. Only rules that apply to Claude Code alone are stated below. @AGENTS.md + +## Claude Code only + +- Before making any commit, run an adversarial Codex review (the `codex-review` skill) of all the uncommitted changes. Fix the issues Codex finds, then repeat the full review of all the uncommitted changes. Commit only when a review comes back with no issues found (owner decision). diff --git a/docs/agents/engine-evidence.md b/docs/agents/engine-evidence.md index 54612ef2..353e5bf3 100644 --- a/docs/agents/engine-evidence.md +++ b/docs/agents/engine-evidence.md @@ -306,6 +306,17 @@ Static association discovery follows bound recipients separately from load-time - `CALL_ANIMATION` binds `OPERAND_NODE` when its positive reference resolves; `AT_NODE`/`WITH_NODE` position rather than own. Runtime impact victims have no statically identified recipient. - Discovery includes all sequence branches and cleanup without evaluating conditions or advancing time; it describes known assignments, not proof that a branch runs. +## MW3 valves and route conditions + +- **Registry and loading** [U: [original 1.2 reconstruction](https://github.com/telltaleatheist/mw3-re/blob/715d6d6e24590ef54a83a257f67a965601795216/src/mech3/zrdrvalve.cpp), [registry](https://github.com/telltaleatheist/mw3-re/blob/715d6d6e24590ef54a83a257f67a965601795216/src/mech3/zai_valve.cpp)]: exact case-sensitive names create integer holders initially zero. Repeated records add reactions in file order. A record looks up tags recursively, builds sound, animation, scan_aim/scan_hit/scan_time/canleave, shutdown, destroy, setteam, attack_strategy, teleport, missionreset/abort/complete, update and delayupdate in that fixed order. The once tag overrides its ordinary counterpart. Initial value writes do not fire. A second compound holder conflicts and drops that record. Unknown tags are ignored, not removed from source. +- **Conditions and reactions** [U: same reader]: any_nonzero, any_zero, all_nonzero and all_zero compute from their namelist on every read; member changes fire the compound's reactions even when its computed value stays unchanged. Setting a holder fires only if the requested value differs from its current value; a compound ignores the write but still fires in that case. Actions compare against their own trigger integer; update fires its target regardless of value and delayupdate captures its source value on every firing. +- **Timers** [U: same registry]: native float due time is delay + current game time; a timer fires only when due is strictly less than now. Timer lists visit timers appended during their own tick. A composite slot keeps its identity when it shrinks to one timer, across later ticks; it is released only when empty. Each mission frame advances game time, updates the world, then ticks valve timers ([mission loop](https://github.com/telltaleatheist/mw3-re/blob/715d6d6e24590ef54a83a257f67a965601795216/src/mech3/mission.cpp)). When a lone timer creates more timers while completing, the retail dispatcher clears its replacement slot and loses those new timers. Upstream's optional repair is not original 1.2 behavior. Reentrant firing and recursive conditions require bounded diagnostic termination in an editor preview. +- **Route semantics** [U: [compiler](https://github.com/telltaleatheist/mw3-re/blob/715d6d6e24590ef54a83a257f67a965601795216/src/mech3/zainetedit.cpp), [reader](https://github.com/telltaleatheist/mw3-re/blob/715d6d6e24590ef54a83a257f67a965601795216/src/mech3/zrdrainet.cpp)]: node properties compile on each outgoing link in order. A valve tuple's first integer enables it; an omitted expected integer is one for the last nonnegative link, zero for the others. A union admits when any enabled term equals its expected integer (default one). Edge records have no XYZ, start with a from node followed by one or more target indices, and add their property chain to each matching authored link. valve_assign changes a value on traversal; it is not a passability test. +- **Animation binding** [U: [owner registry](https://github.com/telltaleatheist/mw3-re/blob/715d6d6e24590ef54a83a257f67a965601795216/src/mech3/zai_anim_owner.cpp)]: callback values 42 through 49 bind a node-name valve at zero through three uniquely parented ancestors. The binding is chosen while scanning the entry's normal sequences, excludes cleanup, and retains the first compatible valve. Even values set zero, odd values one. The callback handler uses the retained binding rather than resolving a new valve for each event. Native mission setup binds loaded definitions after vehicle/player placement and post-vehicle fixup, before starting the selected named entry; ON_STARTUP entries have already been marked running. Their first normal events share the post-placement world frontier ([setup](https://github.com/telltaleatheist/mw3-re/blob/715d6d6e24590ef54a83a257f67a965601795216/src/mech3/mission.cpp)). Mission startup can start range-gated callbacks. In c1, call_ramp attaches to the bramp healthy child at (-1850.06, -25.918423, -1606.5876), outside its 500-unit range of the initial player (-3200.9, -35.9, -1225.1); it starts held. Setting bramp to one wakes owens_01 and schedules truck/dialogue updates. +- **Vehicle triggers** [U: [vlist reader](https://github.com/telltaleatheist/mw3-re/blob/ffec5550795b5ec1b976b80ea5fc518611031fac/src/mech3/zrdraiv.cpp), [evaluation](https://github.com/telltaleatheist/mw3-re/blob/ffec5550795b5ec1b976b80ea5fc518611031fac/src/mech3/zai_brain.cpp)]: an `aiv.zrd` `vlist` entry has 16 or 17 items: the value flag (the valve is set to 1 or 0), ammo flag and threshold, hit flag, health flag and threshold, heat flag and threshold, inside-region flag, region name, in-sight flag and distance, near flag and distance, an unused flag, the valve name, and from 17 items the outside-region flag. Distances are stored in plain units (the reader squares them). Each frame an entry whose valve already is zero or nonzero as its value flag asks does nothing; otherwise the first condition that holds sets the valve, tested in this order: hit within the last second, heat at or above its threshold, health at or below, ammo at or below, the nearest enemy nearer than the near distance, the nearest enemy nearer than the in-sight distance with a clear line, then the region (inside, outside, or anywhere with both flags; no region or neither flag never holds). The player's record runs its list the same way. +- **Deploy and wait points** [U: [net compiler](https://github.com/telltaleatheist/mw3-re/blob/ffec5550795b5ec1b976b80ea5fc518611031fac/docs/ai.md)]: a node's `deploy` stores two valve names (items 1 and 3) and `mcbwait` one (item 1). zStudio lists them as places that name the valve and makes no further claim. +- **Action effects** [U: valve reader above]: shutdown's second operand is the power-down flag; zero wakes a mech. Teleport writes absolute position and yaw. Its get_vec3/get_float_value operands convert integer values to floats ([zReader](https://github.com/telltaleatheist/mw3-re/blob/715d6d6e24590ef54a83a257f67a965601795216/src/gamez/zreader/zreader.cpp)); value/trigger operands and delayupdate retain their raw words. Scans, canleave, team and strategy modify actor AI state. missionreset reports failure and creates nothing; missioncomplete has no effect in retail; missionabort calls the abort handler. Damage thresholds in targets.zrd retain raw float words (TargetRec::parse word_f in zrdraiv.cpp), and set their valves strictly below each threshold, highest first; death fires all remaining thresholds. Objective valve_change stores separate valve (name) and value (comparison word) fields. + ## GameZ world format - RECOIL worlds are GameZ version 15 in both releases and the September 1998 demo; version 13 in the demos built 21 July–12 August 1998 (read-only, read into the same model). Version 13 differs in two ways, established from every node of the ten version-13 demo worlds: node slots are 268 bytes (after the sphere, the cached box as eight corners in the parent's space — bottom face then top, each from minimum X and maximum Z — then model and child boxes and the activation pointer; the reader rebuilds the cached box from the flagged model/child boxes, otherwise maps the corners back through the matrix); Object3D records are 156 bytes (a translation after the scale, matrix and rest 12 bytes later; the matrix already carries the translation, so the reader drops it and shows it as `translate`). Version-28 animations bind to version 15 or 13. Version 200 and animation format 200 are zStudio's formats for reRECOIL v2, not the engine's: version 15 and format 28 with the fields that capped content widened ([version 200](../zbd-v200.md)). diff --git a/docs/agents/pr-watch.md b/docs/agents/pr-watch.md index 7975f66f..0555cd60 100644 --- a/docs/agents/pr-watch.md +++ b/docs/agents/pr-watch.md @@ -1,6 +1,6 @@ # PR watch -`tools/pr-watch.ps1` watches one GitHub PR and notifies the owning agent conversation of new review feedback and of a qualifying review-bot approval. It is development tooling, separate from zStudio and its MCP server. Requirements: Windows, the .NET 10 SDK, an authenticated `gh.exe`; the Codex channel also needs a native Codex with the experimental App Server queue API. It never changes agent permissions or zStudio's MCP opt-in, and never edits files outside its state, fixes code, pushes, merges, tags or publishes. +`tools/pr-watch.ps1` watches one GitHub PR and notifies the owning agent conversation of new review feedback and of a qualifying review-bot approval. It is development tooling, separate from zStudio and its MCP server. Requirements: Windows, the .NET 11 SDK, an authenticated `gh.exe`; the Codex channel also needs a native Codex with the experimental App Server queue API. It never changes agent permissions or zStudio's MCP opt-in, and never edits files outside its state, fixes code, pushes, merges, tags or publishes. ## Commands diff --git a/docs/agents/testing.md b/docs/agents/testing.md index 9df63323..16944297 100644 --- a/docs/agents/testing.md +++ b/docs/agents/testing.md @@ -36,6 +36,7 @@ Tests that need data return early unless their variable is set, so the plain sui | `ZSTUDIO_CORPUS` | absolute path of a RECOIL data folder (holding `interp.zbd`, `zrdr.zbd`, `m1\`); a relative path resolves against the test folder | archive, world, animation, keyframe, AI, resource and source-project corpus tests. `SourceProjectCorpusTests` reconstructs the release, checks every script is an SI script with its DKit messages and no `.zrd` holds animation definitions, exports, compares the archives with the shipped ones without their definitions, rebuilds every shipped animation entry and checks that unpacking the export is refused | | `ZSTUDIO_MW3_CORPUS` | a MechWarrior 3 `zbd` folder | MW3/AI valve inspection and complete source reconstruction/export preservation; originals are hashed and never written | | `ZSTUDIO_DEMO_CORPUS` | a RECOIL demo's `zbd` folder (July or August 1998, version-13 worlds) | every version-13 world reads without diagnostics and every rebuilt node box gives back the stored corners | +| `ZSTUDIO_MW3_SOURCE_PROJECT` | a reconstructed MW3 source project, read only | retail C1 valve startup/range, manual reaction and timer proof | | `ZSTUDIO_SOURCE_PROJECT` | a reconstructed project (read only; `data` and `gamegen` are copied to a temporary folder) | the terrain conversion corpus test without reconstructing first | | `ZSTUDIO_BLENDER` | Blender 5.2.x executable | `BlenderGraphTests`: installs the packaged extension in a factory-startup background Blender with a fresh user-resource folder, round-trips shared references, flags, zones and geometry, saves and reopens a `.blend` with its baseline cache missing; never touches the user's Blender preferences or windows | | `ZSTUDIO_BLENDER_HELPER` | the package's `zStudio.exe`, with `zStudio-Blender-extension-.zip` beside it (required with `ZSTUDIO_BLENDER`); locally an extracted copy, not `artifacts/zStudio-win-x64` | the helper the extension calls; run after packaging | diff --git a/docs/agents/workbench.md b/docs/agents/workbench.md index 94429554..a6e225e3 100644 --- a/docs/agents/workbench.md +++ b/docs/agents/workbench.md @@ -78,10 +78,23 @@ Rules for the WPF workbench. User-facing descriptions: [map editor](../map-edito - Under World, imported objects expose their complete authored child hierarchy, including hidden healthy/destroyed states, nested references, geometry and LOD nodes. Viewport hits keep whole-object ownership; tree rows select exact nodes for framing, inspection and supported edits. Selection never changes visibility or camera; presentation-only expansion never accepts drafts. Resource-placed actors retain their placement selection rules. - Child eyes share source-map part overrides: initialized flags supply the default, explicit gates can reveal initially hidden geometry, ancestors and LOD still apply. The eye shows the own gate, dimming also reflects effective visibility; tooltips explain a blocked visible gate. Overrides are session-only, independent for siblings and occurrences, and retained through compatible refreshes. Reset part visibility restores the owning object's initialized gates. The shared static refresh stops animation preview and keeps camera/selection; animation playback retains its own visibility behavior. - Rows are 32 DIP apart (the 28 DIP row template; a source map's `TreeViewItem` padding 4,2 and no margin); a row is never narrower than its fixed parts plus 96 DIP of name (a world object's) or 24 (a section row's), so only deeper rows scroll sideways. -- Fixed row order: World, Zones, AI Vehicles, AI Networks, Pickups, Animations. Animations holds the map's definition files (no map row; a file with one definition shows that definition), then Common ("shared by every map", collapsed), then Objects placed by animations (design/world-tree-animations.md). Section, folder, file, group, pass and note rows show counts, open or close on click and are never the selection. A definition row (`AnimationTreeSummary`, built once per shown map off the UI thread from the graph index, the object uses and the bound rows; until it arrives the plain definition icon and no target) shows its start glyph (Mission start, On startup, On damage, Called, Started by the game, No caller found, in Animation mode's palette), its name, the grey target text (what it acts on, trimming first; hidden below a 260 DIP pane, with the start detail from 400 DIP), ⧉ for a later definition with an earlier one's name, the kept-scenario dot, `×N` only for several bindings, Open (▷, pressed while Animation mode has it open) and Frame only when a bound object is a World tree row (hidden below 260 DIP), no eye; a definition bound to nothing has a tertiary name and its glyph at 55 %, never a dimmed row; with an object selected its definitions carry the amber bar (the Structure view's bound colour, where the selection bar sits) and a closed file, group or Common holding one an amber dot. Only a definition with several bindings has binding rows (the binding's name, its object as grey text, Open and Frame; the entry in the tooltip and accessible name); calls belong to Animation mode. Notices (⚠) are not shown on definitions: no build note carries a definition's file and position yet. The Animations row's Group by start toggle (Group by type's icon; its context menu too; MCP `scene_options animationsByStart`) lists the map's and Common's definitions in one row per start kind instead of by file, for the session; a definition keeps its row identity across it (its key and selection path pass through file, group and Common rows), a shown selection stays shown, and the keyboard follows Pickups' rule (the Animations row keeps it). Enter or a double-click on a definition or binding row opens it in Animation mode; its context menu adds Open in Animation mode, Frame bound objects, Select its one listed object, Copy animation name, Show source (a flyout with the definition's excerpt) and Properties (Alt+Enter: selects it and focuses its card); a binding's adds Open, Frame, Select and Copy. Frame on a definition or binding frames what it binds to without selecting. Search matches a definition's name, NAME, target, file, bindings and start words; results put an Objects and an Animations subheader when animations match, a definition's with Open, its search words underlined and, in place of its path, what matched when it is not the name or target. Selecting a zone, network or definition ends the object selection and opens its card in the Properties pane; Escape, Clear selection or a click on empty view space clears it. +- Fixed row order: World, Zones, AI Vehicles, AI Networks, Valves (MW3 maps only: [MW3 valves](#mw3-valves)), Pickups, Animations. Animations holds the map's definition files (no map row; a file with one definition shows that definition), then Common ("shared by every map", collapsed), then Objects placed by animations (design/world-tree-animations.md). Section, folder, file, group, pass and note rows show counts, open or close on click and are never the selection. A definition row (`AnimationTreeSummary`, built once per shown map off the UI thread from the graph index, the object uses and the bound rows; until it arrives the plain definition icon and no target) shows its start glyph (Mission start, On startup, On damage, Called, Started by the game, No caller found, in Animation mode's palette), its name, the grey target text (what it acts on, trimming first; hidden below a 260 DIP pane, with the start detail from 400 DIP), ⧉ for a later definition with an earlier one's name, the kept-scenario dot, `×N` only for several bindings, Open (▷, pressed while Animation mode has it open) and Frame only when a bound object is a World tree row (hidden below 260 DIP), no eye; a definition bound to nothing has a tertiary name and its glyph at 55 %, never a dimmed row; with an object selected its definitions carry the amber bar (the Structure view's bound colour, where the selection bar sits) and a closed file, group or Common holding one an amber dot. Only a definition with several bindings has binding rows (the binding's name, its object as grey text, Open and Frame; the entry in the tooltip and accessible name); calls belong to Animation mode. Notices (⚠) are not shown on definitions: no build note carries a definition's file and position yet. The Animations row's Group by start toggle (Group by type's icon; its context menu too; MCP `scene_options animationsByStart`) lists the map's and Common's definitions in one row per start kind instead of by file, for the session; a definition keeps its row identity across it (its key and selection path pass through file, group and Common rows), a shown selection stays shown, and the keyboard follows Pickups' rule (the Animations row keeps it). Enter or a double-click on a definition or binding row opens it in Animation mode; its context menu adds Open in Animation mode, Frame bound objects, Select its one listed object, Copy animation name, Show source (a flyout with the definition's excerpt) and Properties (Alt+Enter: selects it and focuses its card); a binding's adds Open, Frame, Select and Copy. Frame on a definition or binding frames what it binds to without selecting. Search matches a definition's name, NAME, target, file, bindings and start words; results put an Objects and an Animations subheader when animations match, a definition's with Open, its search words underlined and, in place of its path, what matched when it is not the name or target. Selecting a zone, network or definition ends the object selection and opens its card in the Properties pane; Escape, Clear selection or a click on empty view space clears it. - Keyboard: Up/Down, Home/End and Page Up/Down visit every shown row without stopping on buttons; a selectable row becomes the selection, other rows only take focus (outline) while the selection keeps its highlight and card. Left/Right step through the row's buttons (Zones switch, Pickups Group by type, Animations Group by start, Open, Frame, eye; Left from the first returns to the row) and show their tooltips; Space or Enter opens or closes a row or presses the button; Escape returns from a button to its row. - After a rebuild the tree that had the keyboard gives it to the selected row. After Group by start the Animations row keeps it when it, a file, group or Common row had it; otherwise the shown selected row takes it, else the Animations row. After Group by type: the Pickups row or group row that had the keyboard keeps it (a type row gives it to its group when the types go; pressing the toggle from the keyboard keeps it on Pickups); otherwise the selected row takes it, or Pickups when nothing is selected or the selection is inside a closed row. +## MW3 valves + +Design: `design/mw3-valves-ui.md` (owner request 2026-11-11: valves must be previewed and edited without zReader text). User guide: [MW3 source projects](../mw3-source-project.md#valves). + +- One valve per exact name (`Mw3ValveMap`, Core): its starting value and computed condition, its reactions, what sets it and what waits on it, gathered from the mission's `valves.zrd`, `aiv.zrd`, `targets.zrd`, networks, this mission's block of `objectives.zrd`, and the animations whose callbacks 42–49 bind the scene node of its name (`Mw3ValveSimulation.CallbackValves`, from the loaded entries' events and roots; nothing runs). A second computed definition's record is the game's dropped record: its reactions are not listed and the card refuses to change the valve's kind or inputs. The GUI and MCP `source_ai_valve` read the same map; source records stay authoritative. +- World tree: the Valves section lists them by name (ordinal, case-insensitive): switch or gate glyph in the valve colour, name, the summary as grey target text (hidden below 260 DIP), ⚠ with the problems in its tooltip, Frame when it has route nodes or placed vehicles. At rest the right-hand text is "starts n" only for a switch whose start is not 0; while the test runs it is the live value, accent and SemiBold while not 0. The section row carries the Test toggle (▷, pressed while testing). Context menu: Test valves, New valve…, and on a valve Rename valve…, Delete valve, Copy valve name. Search matches the name, the summary and every name it mentions. A valve row is a section item: selecting it ends the object selection and shows its card. +- Selecting a valve shows the networks its links name, sets the view's valve highlight to it (rings on its route nodes, dashed assignment links) and outlines its placed vehicles and targets; the highlight ends with the selection. Frame frames its vehicles and targets, else its ringed nodes. +- Valve card (`SourceSectionCard.Valves`): notices for its problems; Test; **Value** (Starts at: the stored starting value, also for a computed valve, which keeps it in the file but ignores it (the field is dimmed and says so); Kind: Switch or one of the four computed kinds, Inputs as rows of editable valve pickers with Show and Remove, Add input); **Set by** and **Used by** (icon by role, owner, what in secondary text, Go to for a vehicle, route node or valve; the first 24, then "and n more"); **Reactions** (one block per reaction: its kind, then that kind's fields: an editable picker of the mission's vehicles and targets, animations or valves, a choice or number, When it becomes, teleport X/Y/Z/Heading, Only the first time; ✕ strikes it out until Apply, again restores it; Add reaction); **Source** (collapsed: the records as stored, Rename…, Delete). Value and Reactions are one draft with the shared footer; Apply is one undoable `SourceValveEdits.PlanValve` change. The same valve with a draft keeps its fields when the card is shown again; only Test refreshes. A binary or unreadable `valves.zrd` shows why and disables editing. +- Rename and Delete act at once (their own prompt or confirmation), never through the draft; they and New valve resolve pending drafts first. Rename is refused, with the reason, for a valve an animation sets: its name is the scene node's. A new or renamed valve is selected in the rebuilt tree. +- Valve test (`MainWindow.ValvePreview`; MCP `ai_valve_preview`): one switch, no separate prepare. Starting resolves drafts, is refused in Animation mode and shows "Starting…" on the banner and the card; a failure to start is shown on the card. A banner over the view (Pick in view's chip, top centre): "Testing valves · 12.350 s · n timers", Play/Pause, Step, Skip to the next timer (disabled without one), Restart, End test. The card's Test section replaces the Test valves button: Off (0) / On (1) (the current one accent), another value with Set, Fire; a computed valve lists its inputs with their values as links instead; Waiting (up to six timers, this valve's first, each with Skip to); Activity (the latest 14 trace lines in words, in the order they happened: a valve's new value with its time, then indented what that did; this valve's sets SemiBold, unavailable targets in the caution colour). The section is one element for a valve and test: its buttons and the Other value box stay (and what is typed in it) while only the readouts are rebuilt. The banner, the rows and the cards show the test as its last finished step left it (`ValveTestView`); they never read the simulation, which a background step may be changing. Set by rows with a value gain Fire while the test runs and lose it when it ends (the rows are rebuilt on that change; the draft's fields are not). While playing, the banner's clock follows every frame; rows and cards follow when something happened and at most five times a second. +- The test ends on its switch, a source edit or draft, another mission or map, Animation mode and shutdown; ending restores the map at rest and the rows' resting text. +- An AI node's card ends with a Valves section: its gates, unions and assignments in words with a link to each valve, and Add (a kind, a valve picker, a value) for a gate or an assignment. Its fields keep what is typed while the test runs: only its "Test: drive through" part (each outgoing link open or closed with the reason, Drive through) follows the test. A vehicle's card shows a Valve test section with what the test did to it; both cards follow what happened in the test (its start and end, a valve changing), not its clock. + ## Title row - One title/menu row with full-height caption controls and a Windows maximize/Snap hit region; menu and caption hit regions reserved equally on both sides. diff --git a/docs/map-editor.md b/docs/map-editor.md index b3d7090d..b76a713f 100644 --- a/docs/map-editor.md +++ b/docs/map-editor.md @@ -34,7 +34,7 @@ MCP: `zstudio_source_world_list`, `zstudio_source_world_open`. ### World tree -Rows come in a fixed order: **World** (the authored glTF hierarchy, including groups the build removes), **Zones**, **AI Vehicles**, **AI Networks**, **Pickups**, **Animations** (the `.zad` definitions the mission lists, then Common and the objects placed by animations). Icons show each node's type; the info button beside **Show all** opens a legend. +Rows come in a fixed order: **World** (the authored glTF hierarchy, including groups the build removes), **Zones**, **AI Vehicles**, **AI Networks**, **Valves** (MechWarrior 3 missions: [valves](mw3-source-project.md#valves)), **Pickups**, **Animations** (the `.zad` definitions the mission lists, then Common and the objects placed by animations). Icons show each node's type; the info button beside **Show all** opens a legend. - Objects show their zone on the right (`Zone: 12`, `Zone: Any`). - Expand an imported object to browse its groups, nested references, geometry and LOD branches. Clicking a child selects that exact part; clicking geometry in the map still selects the whole object. Hidden parts remain in the tree and can be inspected. Deep branches scroll horizontally to keep names and eye buttons accessible. - Healthy and destroyed branches keep their initialized visibility: healthy normally has an open eye, destroyed a closed eye. Hide healthy and show destroyed with their separate eyes to inspect the destroyed geometry. These are preview overrides, independent of the stored Visible flag: no source edit or undo step is created. Changing or resetting these eyes keeps the tree at its current scroll position and retains keyboard focus. A child blocked by its parent, isolation or LOD is dimmed; its tooltip explains why. Right-click the object and choose **Reset part visibility** to restore its initialized defaults. Ending isolation preserves the chosen part states. Overrides last for the open map and compatible preview refreshes; changing them stops animation playback, whose own visibility applies when played again. diff --git a/docs/mcp-capabilities.json b/docs/mcp-capabilities.json index dde8f8ed..4d9b7499 100644 --- a/docs/mcp-capabilities.json +++ b/docs/mcp-capabilities.json @@ -135,7 +135,12 @@ "zstudio_ai_nodes", "zstudio_preview_state" ], - "note": "Authored node conditions and uniquely resolved edge assignments can be outlined, highlighted and framed; node cards navigate to source occurrences in Properties. Runtime valve evaluation is not simulated." + "note": "Authored node conditions and uniquely resolved edge assignments can be outlined, highlighted and framed. Circular node picking shares AI selection and Properties; simulated blocked routes remain dashed and dim." + }, + { + "gui": "MainWindow.ValvePreview:Controls", + "tools": ["zstudio_ai_valve_preview", "zstudio_source_ai_valve", "zstudio_scene_tree", "zstudio_scene_card", "zstudio_resolve_drafts", "zstudio_undo_redo", "zstudio_save_document"], + "note": "MW3 valves (design: one World tree row and one card per valve name). The valve card's Value (Starts at, Kind, Inputs) and Reactions (kind, target, on/off or team or strategy or seconds, When it becomes, teleport X/Y/Z/Heading, Only the first time, Add reaction, remove) are one draft: source_ai_valve draft stages the same changes, set applies them directly, Apply/Revert are the shared card's. Set by and Used by rows are source_ai_valve valve's setBy and usedBy links (their Go to selects the vehicle, route node, valve or animation definition: scene_tree select, ai_selection select). A valve row's Frame is scene_tree frame on that row. The Test section and the banner are ai_valve_preview: Test valves (start), Off/On/Set (set), Fire (update), a Set by row's Fire (set with that trigger's value), Skip to (advance), the banner's play, pause, step, next, reset, End test (stop); values, timers and activity are state, values, timers and trace. An AI node's Valves section lists its gates and assignments (ai_nodes, source_ai_valve records), Add is source_ai_valve attach, Drive through is ai_valve_preview traverse. Test state, timers, reactions and vehicle overrides stay in memory." }, { "gui": "SourceExportSelectionDialog:Controls", @@ -1281,6 +1286,36 @@ "tools": ["zstudio_animation_mode"], "note": "A definition row's Open (▷), or a binding row's under a definition with several bindings (also on their search results), is animation_mode open with that definition (and the binding's entry); Enter on the row or result and a double-click do the same. A click on the row only selects it and shows its card (scene_tree select). The opened definition's Open is pressed (sectionRow opened)." }, + { + "gui": "MainWindow.xaml:OutlinerValveTestClick", + "tools": ["zstudio_ai_valve_preview", "zstudio_scene_tree"], + "note": "The Valves row's Test toggle (MW3 source maps) is ai_valve_preview start and stop: the valve test runs in memory and scene_tree's valves row reports testing. The banner over the view (play, pause, step, next timer, restart, End test) is the same tool's play, pause, step, next, reset and stop." + }, + { + "gui": "MainWindow.xaml:SceneValveTestClick", + "tools": ["zstudio_ai_valve_preview"], + "note": "The Valves row's and a valve row's context menu Test valves is ai_valve_preview start and stop, as the row's toggle." + }, + { + "gui": "MainWindow.xaml:SceneNewValveClick", + "tools": ["zstudio_source_ai_valve"], + "note": "New valve… prompts for an unused name and is source_ai_valve new: a valves.zrd record that starts at 0 (the file is created when the mission has none), one undoable change; the new valve's row is selected." + }, + { + "gui": "MainWindow.xaml:SceneRenameValveClick", + "tools": ["zstudio_source_ai_valve"], + "note": "Rename valve… (also the card's Source section) is source_ai_valve rename: every file of the mission that names the valve changes in one undoable change (its records, other valves' inputs and timers, vehicle triggers, health thresholds, route gates, assignments and deploy points, this mission's objectives)." + }, + { + "gui": "MainWindow.xaml:SceneDeleteValveClick", + "tools": ["zstudio_source_ai_valve"], + "note": "Delete valve (also the card's Source section) confirms and is source_ai_valve remove: its valves.zrd records go as one undoable change; what other files say about it stays." + }, + { + "gui": "MainWindow.xaml:SceneCopyValveNameClick", + "tools": ["zstudio_source_ai_valve", "zstudio_scene_tree"], + "note": "Copies the valve's exact name; source_ai_valve valves and scene_tree's valve rows return it." + }, { "gui": "MainWindow.xaml:OutlinerGroupByStartClick", "tools": ["zstudio_scene_options"], diff --git a/docs/mcp.md b/docs/mcp.md index d090660f..e846cd74 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,5 +1,9 @@ # MCP +MW3 valves are one per exact name over every mission file that mentions them. `source_ai_valve` `valves` pages them and `valve` reads one as its card shows it: starting value, computed condition and inputs, reactions (each with its `occurrence`, stored kind and fields), `setBy` and `usedBy` links and its records. `set` applies changes to `valves.zrd` as one undoable change that keeps comments, layout and unknown tags: `initial`, `condition` with `inputs`, and `reactions` (an existing one by `occurrence` and `storedKind` with new `fields` or `remove`, a new one by `fields` alone). `new`, `rename` (every file of the mission that names it; refused for a valve an animation sets through the scene node of its name) and `remove` (its records) work by name; `draft` stages the same changes on the selected valve's card. Edits need the current document revision. The record-level actions (`sources`, `records`, `read`, `create`, `update`, `delete`, `attach`) edit one stored record or node attribute as zReader text. + +`ai_valve_preview` is the valve test of an MW3 source map. `start` (or `prepare`) and `reset` return a new simulation ID that the other actions need: `state`, `play`, `pause`, `step`, `advance` (absolute time), `next` (to the first tick on which the next waiting timer runs), `set`, `update`, `traverse` (AI node ID and physical slot), `trace`, `timers`, paged `values` and `actors`, and `stop`. A source edit, another mission or Animation mode ends the test; nothing it does is saved. Valve names are case sensitive; gameplay triggers and route traversal are manual, with no autonomous combat or path following. + Map preview problems retain their original severity and category. Unresolved animation calls are grouped by exact target name; `problems` returns their `Count` and bounded `ContextDetails` (entry, sequence, event and source definition or compiled offset), also shown by Diagnostics → Details. Queries include those details. Omitted call-site details are counted explicitly. zStudio lets local AI agents work in its visible workspace through the Model Context Protocol. An agent and you share the same documents, edits, undo history, drafts, previews and verified saves; there is no separate headless mode. The connection is a named pipe restricted to your Windows user, with no network port. @@ -148,6 +152,7 @@ All tools are named `zstudio_*`. "MCP only" marks tools without a GUI path. The | Adding groups and models | `source_group_add`, `source_world_placement`, `source_world_add_model`, `source_map_parts`, `source_map_parts_visibility` | World/group **Add group…** and **Add object…** context actions, model browser and click placement; unplaced model/definition additions remain MCP only | | Pickups and units | `pickups`, `pickup_move`, `source_pickup_add` | **Tools → Add pickup…**, scene card | | AI networks | `ai_networks`, `ai_nodes`, `ai_selection`, `source_ai_network`, `ai_path` | AI Networks section and network card (header fields and each node's links: `source_ai_network` `changes` and `links`); whole-path editing (`ai_path`) is MCP only | +| MW3 valves | `source_ai_valve`, `ai_valve_preview`, `ai_valves`, `ai_valve_selection` | Valves section and valve card (`valves`, `valve`, `set`, `new`, `rename`, `remove`, `draft`), the valve test (`start` to `stop`), an AI node's Valves section (`attach`, `traverse`) | | Animations | `animation_mode`, `animation_graph`, `animation_timing`, `animation_scenario`, `source_animation`, `animation_paths`, `animation_transport`, `animation_options`, `animation_runtime`, `animation_select` | Animation mode (command bar, animation panel, Inspector, Scenario tab, the 3D view's Paths chip, range tests and drop windows), the map layout's definition card | | Zones | `source_zones`, `source_zone_label`, `source_zone_tool`, `source_polygon_zones` | Zones section, **Tools → Paint polygon zones** / **Erase polygon zones** | | Terrain | `source_terrain`, `source_terrain_create`, `source_terrain_edit`, `source_terrain_convert` | **Tools → Create terrain…** / **Convert to editable terrain…**, terrain Properties | diff --git a/docs/mw3-source-project.md b/docs/mw3-source-project.md index 2d30c071..0dc28832 100644 --- a/docs/mw3-source-project.md +++ b/docs/mw3-source-project.md @@ -2,7 +2,7 @@ Repeated native `#N` animation bindings retain their separate source identities through navigation, scenario save/reload and automatic path reevaluation. Native execution ranges can exclude an inner region; the graph and range overlays show both bounds and use the same interval as playback. -The map shows the initialized starting state: animation resets hide destroyed alternatives before actors are copied, then startup events use the selected mission and its player spawn. Hidden parts remain available through the World tree eyes. Object animation links, bound-object selection and event highlighting use the same native bindings as playback, including repeated-name objects. These preview choices do not rewrite authored source flags. Mission progression, AI, combat and inventory are not simulated; native game callbacks remain trace markers in playback, graph descriptions and Inspector readouts. +The map shows the initialized starting state: animation resets hide destroyed alternatives before actors are copied, then startup events use the selected mission and its player spawn. Hidden parts remain available through the World tree eyes. Object animation links, bound-object selection and event highlighting use the same native bindings as playback, including repeated-name objects. These preview choices do not rewrite authored source flags. Mission progression, AI, combat and inventory are not simulated; ordinary animation playback keeps native game callbacks as trace markers; the valve simulator below evaluates its supported callbacks. New glTF files use `extras.zstudio`. Core and the Blender extension also read legacy `extras.recoil`; when both keys are present, `zstudio` wins without merging. Import does not rewrite source files. Blender operator IDs, property handles, saved-state names and the extension ID remain unchanged. @@ -10,6 +10,35 @@ Initialize reconstructs an original MechWarrior 3 ZBD folder into a separate `da Open a campaign world from the map picker to edit its source hierarchy, objects, placements, AI paths, zones, animations and terrain. The mission picker chooses the campaign, instant-action or multiplayer resource folder used for actors and AI networks. Every mission variant of a campaign shares its world and animation sources. Source files can also be edited on disk. Opening compiled game files remains inspection only. +### Valves + +A valve is a named switch of a mission: a whole number, in practice 0 (off) or 1 (on). Vehicle triggers, a target's health, objectives, routes and other valves' timers set it; when it changes it plays sounds, starts animations, wakes or destroys vehicles, starts timers, and opens or closes the route links that wait on it. The game keeps this in five kinds of file; the editor shows one valve per name. + +The **Valves** section of the World tree (after AI Networks) lists the selected mission's valves by name, each with what it does in a few words. A warning mark means a reaction names a vehicle, target or animation the mission does not have, or a record the game does not read. Search finds a valve by its name and by anything it names. Right-click the section or a valve for **New valve…**, **Rename valve…** (every file of the mission that names it changes, as one step; a valve an animation sets keeps its scene node's name and cannot be renamed), **Delete valve** (its `valves.zrd` records; other files keep naming it) and **Copy valve name**. + +Select a valve for its card. Selecting it also shows the networks it belongs to, rings the route nodes that set it or wait on it, and outlines its vehicles and targets; **Frame** on its row frames them. + +- **Value**: its starting value, and its kind. A *switch* is set by the rest of the mission. A *computed* valve is on while any or all of its **inputs** are on (or off): the game works it out each time and ignores attempts to set it. +- **Set by**: every place the mission's files set it: a vehicle's trigger (inside or outside a region, hit, health, heat, ammo, an enemy near or in sight), a target's health threshold, an objective, a route a vehicle drives through, another valve's timer, and an animation whose events 42–49 run on the scene node with the valve's name. The arrow selects that vehicle, node, valve or animation. The game's own code also sets valves; that is not listed. +- **Reactions**: what happens when it changes. Each reaction has a kind (play a sound, start an animation, wake or power down a mech, destroy, teleport, change team or attack strategy, an AI switch, set another valve later, fire another valve's reactions, abort the mission), what it acts on, and **When it becomes**: the value that triggers it. Timers and "fire another valve" run on every change. Names can be picked from the mission's vehicles, animations and valves, or typed. **Add reaction** adds one; the ✕ removes one. +- **Used by**: what waits on it: route gates, objectives and computed valves. +- **Source**: its records as stored, with **Rename…** and **Delete**. + +Value and Reactions are one draft: **Apply** accepts it as one undoable change and **Revert** discards it. Only the edited values change in `valves.zrd`; comments, layout and tags the editor does not know stay. A new reaction is written as its own record after the valve's last one, as the shipped files do, and a mission without `valves.zrd` gets the file with its first valve. A record the game does not read as written is listed with its problem and left alone: correct it in a text editor. The same goes for a valve with two computed definitions (the game keeps the first and drops the second record with its reactions): remove one in a text editor before changing its kind or inputs. A record that stores several reactions of one kind (a plain and a once-only sound, say) has only one the game uses: its fields can be edited, but changing its kind or removing it is refused until the unused one is removed in a text editor. Vehicle triggers, health thresholds and objectives are shown and linked but edited in their own files. + +An AI node selected in the view lists its gates and assignments in words, each with a link to its valve. Its **Add** adds a gate (pass only while a valve holds a value) or an assignment (set a valve when a vehicle drives through) to the node; change or remove an existing one in the network's file. + +#### Testing valves + +**Test valves** (▷ on the Valves row, the button on a valve's card, or the row's context menu) runs the mission's valves in memory, starting paused at 0 s. Nothing is saved, and a source edit, another mission or Animation mode ends the test. + +- A banner over the view shows the test's time, with Play/Pause, Step, **Skip to the next timer**, Restart and **End test**. +- Each valve's row shows its value while the test runs. +- The selected valve's card has a **Test** section: **Off (0)** and **On (1)** set it as a trigger would, **Fire** runs its reactions without changing it, the timers waiting are listed with **Skip to**, and **Activity** lists what happened in order: each valve's new value with its time, then what that did. A computed valve shows its inputs' values instead. Each **Set by** row gains **Fire**, which sets the valve as that trigger, threshold or route would. +- In the view, route links a valve closes are drawn dim and dashed. A selected AI node lists each outgoing link as open or closed (and why) with **Drive through**, which applies that link's assignments. A vehicle's card shows what the test did to it (awake, powered down, destroyed, team, strategy, teleported); a teleported vehicle moves. + +The test starts from the mission's starting state with its startup animations, runs conditions, once-only reactions and timers as the game does, plays the reactions' sounds and animations, and connects animation callbacks 42–49 to their valves. It does not play the game: no vehicle drives, fights or meets a trigger on its own, so set valves yourself to stand in for gameplay. A sound, animation or vehicle a reaction names and the mission lacks is reported in Activity. The test runs for at most one hour of mission time and keeps the latest 4,096 activity lines. + The map picker lists campaign worlds and the tutorial; native library folders such as `lab` remain model sources for Blender. **Tools → Compare worlds…** accepts original and rebuilt MW3 version-27 worlds, including their native corner colours, material switches and cycles, facade modes and node metadata. The Blender checkout/update workflow accepts native world, mech and lab source graphs. Use a fresh checkout with the matching v0.12 extension; older checkouts are refused. Game identity and mech-library member identity belong to the source file and cannot be changed by a Blender update. A base mech's named top-level root must remain available to its AIV actors; edit its parts below that root. Native retained groups, node words, corner colours and material cycles survive editing. A shared model or texture edit is validated against its world and library consumers before acceptance. @@ -76,4 +105,4 @@ Use `source_reconstruct`, `source_status`, `source_export_selection` and `source ## Evidence -The pinned reference is [`telltaleatheist/mw3-re` at dce9757b8b49d9a04a0bad8187741ca1bc12b62c](https://github.com/telltaleatheist/mw3-re/tree/dce9757b8b49d9a04a0bad8187741ca1bc12b62c), together with the read-only original game data. The external project is evidence only and is not a build or runtime dependency. Engine mechanisms are recorded in [engine evidence](agents/engine-evidence.md). +The source-pipeline reference is [`telltaleatheist/mw3-re` at dce9757b8b49d9a04a0bad8187741ca1bc12b62c](https://github.com/telltaleatheist/mw3-re/tree/dce9757b8b49d9a04a0bad8187741ca1bc12b62c); valve and route research uses [715d6d6e24590ef54a83a257f67a965601795216](https://github.com/telltaleatheist/mw3-re/tree/715d6d6e24590ef54a83a257f67a965601795216), together with the read-only original game data. The external project is evidence only and is not a build or runtime dependency. Engine mechanisms are recorded in [engine evidence](agents/engine-evidence.md). diff --git a/src/zStudio.Core/Animation/AnimationPlayer.Events.cs b/src/zStudio.Core/Animation/AnimationPlayer.Events.cs index 4ed8089a..af69fcbe 100644 --- a/src/zStudio.Core/Animation/AnimationPlayer.Events.cs +++ b/src/zStudio.Core/Animation/AnimationPlayer.Events.cs @@ -160,6 +160,7 @@ private int Execute(Instance instance, Sequence sequence, AnimationEvent ev, boo } case 34: case 39: case 40: return 2; case 35: + if (ev.Version == 39 && NativeValveCallback?.Invoke(instance.Entry.Index, instance.Root, ev.I32(12)) == true) return 2; vtolCallback?.Invoke(instance, sequence, ev); if (!initializingScene && ev.Version != 39 && ev.I32(12) is 10 or 11 or 17) PlayerCallback(instance, ev, ev.I32(12), Math.Max(0, Time - remaining)); else AddNote($"Game callback {ev.I32(12)} is a trace marker; game code is not executed.", "Support", "Information"); diff --git a/src/zStudio.Core/Animation/AnimationPlayer.Mission.cs b/src/zStudio.Core/Animation/AnimationPlayer.Mission.cs index 40b33fcc..339e6456 100644 --- a/src/zStudio.Core/Animation/AnimationPlayer.Mission.cs +++ b/src/zStudio.Core/Animation/AnimationPlayer.Mission.cs @@ -73,6 +73,7 @@ internal static HashSet ApplyInitialization(AnimationPreviewContext context operation.Reserve(1); // ActivateRuntime refuses the states 4-6, and the load starts no entry stored running (2). static bool Startable(AnimationEntry entry) => entry.Bytes[152] is not (2 or 4 or 5 or 6); + if (load && context.World.Game == GameVariant.MechWarrior3) context.ValveStartupBefore = []; var frame = new AnimationPlayer(context, operation) { dispatchBudget = 10000, rangeGated = true, playerStart = player }; if (load) { @@ -94,6 +95,11 @@ internal static HashSet ApplyInitialization(AnimationPreviewContext context } frame.RunInitialization(token); frame.PublishInitialization(positioned); + if (load && context.World.Game == GameVariant.MechWarrior3) + { + context.ValveLoadBefore = context.ValveStartupBefore; + context.ValveStartupBefore = null; + } if (load && running != null) foreach (var instance in frame.instances) if (instance.Shared) running.Add((instance.Entry.Index, instance.Root)); diagnostics.AddRange(frame.notes.Select(n => "Mission initialization: " + n)); @@ -271,6 +277,12 @@ private void Publish(IEnumerable nodes, HashSet positioned, bool admi if (!admitted) bindingOperation!.Reserve(64); var source = context.Scene.Nodes[node.Source]; if (source.Class is not ("object3d" or "lod")) continue; + if (context.ValveStartupBefore is { } before && !before.ContainsKey(node.Source)) + { + bindingOperation!.Reserve(64L + source.Data.Count * 64L); + before.Add(node.Source, source with { Data = (System.Text.Json.Nodes.JsonObject)source.Data.DeepClone(), + Metadata = new System.Text.Json.Nodes.JsonObject { ["flags"] = source.Metadata.UInt("flags") } }); + } source.Metadata["flags"] = node.Active ? source.Metadata.UInt("flags") | 4u : source.Metadata.UInt("flags") & ~4u; if (node.Changed && source.Class == "object3d") { diff --git a/src/zStudio.Core/Animation/AnimationPlayer.Valves.cs b/src/zStudio.Core/Animation/AnimationPlayer.Valves.cs new file mode 100644 index 00000000..b62a3731 --- /dev/null +++ b/src/zStudio.Core/Animation/AnimationPlayer.Valves.cs @@ -0,0 +1,107 @@ +namespace zStudio.Core.Animation; + +public sealed partial class AnimationPlayer +{ + /// A preview-owned callback sink, absent during ordinary animation analysis. + public Func? NativeValveCallback { get; set; } + internal Action? NativeValveStarted { get; set; } + internal double? ValveClock { get; set; } + internal void BeginValveOperation() => dispatchBudget = 10000; + internal int ValveParent(int node) + { + var authored = context.Scene.Nodes[node]; + if (sharedNodes.TryGetValue(node, out var owned) && owned.Parent != authored.Parents.FirstOrDefault(-1)) return owned.Parent; + return authored.Parents is [var parent] ? parent : -1; + } + internal IReadOnlySet ValveActorNodes(int root, CancellationToken token) + { + using var binding = BeginBinding(token); + Dictionary belongs = new() { [root] = true }; + HashSet result = []; + foreach (var source in context.Scene.Nodes) + { + if (source.ModelIndex == null) continue; + List chain = []; HashSet seen = []; int at = source.Index; + while (at >= 0 && at < context.Scene.Nodes.Count && !belongs.ContainsKey(at) && seen.Add(at)) + { + token.ThrowIfCancellationRequested(); bindingOperation!.Reserve(64); + chain.Add(at); at = sharedNodes.TryGetValue(at, out var node) ? node.Parent : context.Scene.Nodes[at].Parents.FirstOrDefault(-1); + } + bool owned = belongs.GetValueOrDefault(at); + foreach (int index in chain) belongs[index] = owned; + if (owned) result.Add(source.Index); + } + return result; + } + internal IReadOnlyList ValveActorPoses(int root, IReadOnlySet nodes, CancellationToken token) + { + using var binding = BeginBinding(token); + List result = []; + var ancestry = BeginFrameAncestry(bindingOperation!); + Instance owner = new() { Entry = context.Package.Entries[0], Root = root, Shared = true }; + foreach (int index in nodes) + { + token.ThrowIfCancellationRequested(); + if (context.Scene.Nodes[index].ModelIndex is not { } model) continue; + var node = SharedNode(index); var pose = ancestry.Get(owner, node); + result.Add(new(node.RenderId, index, model, pose.World, pose.Visible, pose.Opacity, node.Variant, node.Morph, Math.Max(0, Time - node.CycleStart))); + } + EndFrameAncestry(ancestry); + return result; + } + internal void StartValveLoadAnimations(CancellationToken token) + { + using var binding = BeginBinding(token); + dispatchBudget = 10000; rangeGated = true; playerStart = context.Mission?.PlayerStart; + // Native mission setup binds every loaded definition after vehicle placement, before any first-frame events. + foreach (var entry in context.Package.Entries) + if (entry.Index > 0 && bindingOperation!.Root(entry) is >= 0 and var root) NativeValveStarted?.Invoke(entry.Index, root); + foreach (var entry in context.Package.Entries) + if (entry.Index > 0 && entry.Bytes[153] == 4 && entry.Bytes[152] is not (2 or 4 or 5 or 6)) + StartInitialization(entry, false, null, [], token); + } + internal System.Numerics.Matrix4x4 ValveWorldTransform(int node, CancellationToken token) + { + using var binding = BeginBinding(token); + var instance = instances.FirstOrDefault(i => i.Shared && i.Nodes.ContainsKey(node)); + if (instance != null) return World(instance, instance.Nodes[node]); + var world = System.Numerics.Matrix4x4.Identity; + HashSet seen = []; + while (node >= 0 && node < context.Scene.Nodes.Count && seen.Add(node)) + { + token.ThrowIfCancellationRequested(); + var state = SharedNode(node); world *= state.Local; node = state.Parent; + } + return world; + } + internal void TeleportValveActor(int root, System.Numerics.Vector3 position, float yaw, CancellationToken token) + { + using var binding = BeginBinding(token); + var node = SharedNode(root); + var parent = node.Parent < 0 ? System.Numerics.Matrix4x4.Identity : ValveWorldTransform(node.Parent, token); + if (!System.Numerics.Matrix4x4.Invert(parent, out var inverse)) throw new InvalidDataException("The actor's parent transform is not invertible."); + var world = System.Numerics.Matrix4x4.CreateRotationY(yaw * (MathF.PI / 180)) * System.Numerics.Matrix4x4.CreateTranslation(position); + var local = world * inverse; + if (!System.Numerics.Matrix4x4.Decompose(local, out var scale, out var rotation, out var translation)) throw new InvalidDataException("The teleport pose is not representable."); + node.Exact = local; node.Position = translation; node.Scale = scale; node.Rotation = rotation; node.Euler = AnimationMath.ToEuler(rotation); node.Changed = true; + } + public AnimationFrame FlushValveFrontier(CancellationToken token = default) + { + using var binding = BeginBinding(token); + dispatchBudget = 10000; + playerStart = context.Mission?.PlayerStart; + RunInitialization(token); + return Frame(token); + } + public bool StartValveAnimation(int entry, CancellationToken token = default) + { + if (entry <= 0 || entry >= context.Package.Entries.Count) return false; + using var binding = BeginBinding(token); + return AddInstance(context.Package.Entries[entry], null, null, started: true) != null; + } + internal void StartValveMissionStartup(int entry, CancellationToken token) + { + using var binding = BeginBinding(token); + if (context.Package.Entries[entry].Bytes[152] is not (2 or 4 or 5 or 6)) StartInitialization(context.Package.Entries[entry], false, null, [], token); + } +} diff --git a/src/zStudio.Core/Animation/AnimationPlayer.cs b/src/zStudio.Core/Animation/AnimationPlayer.cs index 73cad9e2..9db5ee6e 100644 --- a/src/zStudio.Core/Animation/AnimationPlayer.cs +++ b/src/zStudio.Core/Animation/AnimationPlayer.cs @@ -210,7 +210,7 @@ public float PreviewHeight previewHeight = value; } } - public double Time => ticks * StepSeconds; + public double Time => ValveClock ?? ticks * StepSeconds; private bool PendingStarts => schedule != null && nextScheduled < schedule.Starts.Count; public bool IsComplete => !PendingStarts && instances.All(i => i.Finished) && effects.Count == 0; public bool HasExcludedCalls => hasExcludedCalls; @@ -671,6 +671,7 @@ private static string EventWords(Instance instance, Sequence sequence, Animation instance.SavedNodes = instance.Nodes.ToDictionary(p => p.Key, p => { operation.Reserve(1); return p.Value.Clone(); }); instance.Sequences = (primary ? new[] { entry.Primary } : entry.Sequences.ToArray()).Select(s => new Sequence(s) { WorkChanged = AdjustRetainedWork, Created = instance.StartedAt }).ToList(); if (activation) SetEntryState(entry, new(2, instance.Id, root, instance.SavedNodes, Time, "start", callPath)); + if (!primary) NativeValveStarted?.Invoke(entry.Index, root); InvalidateRetainedState(); return instance; } diff --git a/src/zStudio.Core/Animation/AnimationPreviewContext.cs b/src/zStudio.Core/Animation/AnimationPreviewContext.cs index 652e6d6a..4fbc02e5 100644 --- a/src/zStudio.Core/Animation/AnimationPreviewContext.cs +++ b/src/zStudio.Core/Animation/AnimationPreviewContext.cs @@ -33,6 +33,8 @@ public enum AnimationBinding public sealed partial class AnimationPreviewContext { internal MissionInitializationTransforms? InitializationTransforms { get; init; } + internal Dictionary? ValveStartupBefore { get; set; } + internal Dictionary? ValveLoadBefore { get; set; } public required AnimationPackage Package { get; init; } public required ISceneDocument World { get; init; } public AnimationTerrain? Terrain { get; private set; } diff --git a/src/zStudio.Core/MissionAiNetworks.cs b/src/zStudio.Core/MissionAiNetworks.cs index 0d55bf4f..cbd11175 100644 --- a/src/zStudio.Core/MissionAiNetworks.cs +++ b/src/zStudio.Core/MissionAiNetworks.cs @@ -121,7 +121,7 @@ internal static bool TryNodeIndex(string name, out int index) internal static bool IsConstraint(ZrdNode value, CancellationToken token) { var c = value.Children; - if (value.Kind != ZrdKind.Array || c.Count < 3 || c[0].Kind != ZrdKind.Array || c[0].Children.Count != 2 || c[0].Children.Any(n => n.Kind != ZrdKind.Int)) return false; + if (value.Kind != ZrdKind.Array || c.Count < 3 || c[0].Kind != ZrdKind.Array || c[0].Children.Count < 2 || c[0].Children.Any(n => n.Kind != ZrdKind.Int)) return false; return AttributePairs(c, 1, token); } /// Every field from is a string name followed by an array value, with none dangling. @@ -258,7 +258,7 @@ AiAttackStrategy ReadAttackStrategy() constraint = true; // Only fully validated v106 constraints are a separate identity kind. constraintCount += (c.Count - 1) / 2; for (int attribute = 1; attribute < c.Count; attribute += 2) - if (c[attribute].Text == "valve_assign") { valveEdges.Add(value); break; } + if (c[attribute].Text is "valve" or "valveunion" or "valve_assign") { valveEdges.Add(value); break; } for (int attribute = 1; attribute < c.Count && constraints.Count < 1024; attribute += 2) constraints.Add(new(index, from, to, c[attribute].Text, value.SourceOffset, c[attribute + 1].ToPreviewJson(token, 32, 512, 6, 256)) { AttributeIndex = (attribute - 1) / 2, SourceId = c[attribute].Id, Valve = c[attribute].Text == "valve_assign" ? new(c[attribute].Id, value.Id, attribute, c[attribute], c[attribute + 1], "edge", From: from, To: to) : null }); @@ -290,7 +290,7 @@ AiAttackStrategy ReadAttackStrategy() if (mw3) for (int a = 3; a + 1 < c.Count; a += 2) { token.ThrowIfCancellationRequested(); - if (c[a].Kind != ZrdKind.String || c[a].Text is not ("valve" or "valveunion")) continue; + if (c[a].Kind != ZrdKind.String || c[a].Text is not ("valve" or "valveunion" or "valve_assign")) continue; valveCount++; if (valves.Count < 16) valves.Add(new(c[a].Id, value.Id, a, c[a], c[a + 1], "node", index)); } nodes.Add(new(id + ":" + nodes.Count, index, Integer(c[0]), position, value.SourceOffset, links.AsReadOnly()) { AuthoredLinkCount = linkCount, Source = value, Valves = valves.AsReadOnly(), ValveCount = valveCount, Key = key }); @@ -323,11 +323,12 @@ AiAttackStrategy ReadAttackStrategy() Dictionary> edgeValves = []; List resolvedEdges = []; foreach (var edge in valveEdges) { - token.ThrowIfCancellationRequested(); int from = Integer(edge.Children[0].Children[0]), to = Integer(edge.Children[0].Children[1]); - if (!unique.Contains(from) || !unique.Contains(to)) continue; + token.ThrowIfCancellationRequested(); int from = Integer(edge.Children[0].Children[0]); + if (!unique.Contains(from) || !edge.Children[0].Children.Skip(1).Any(n => unique.Contains(Integer(n)))) continue; resolvedEdges.Add(edge); if (!edgeValves.TryGetValue(from, out var first)) edgeValves.Add(from, first = []); first.Add(edge); - if (to != from) { if (!edgeValves.TryGetValue(to, out var second)) edgeValves.Add(to, second = []); second.Add(edge); } + foreach (int to in edge.Children[0].Children.Skip(1).Select(Integer).Where(t => t != from && unique.Contains(t)).Distinct()) + { if (!edgeValves.TryGetValue(to, out var second)) edgeValves.Add(to, second = []); second.Add(edge); } } return new(id, archive, memberIndex, member, TextField("name", member), TextField("type", ""), width, Array.AsReadOnly(resolved), notes.AsReadOnly()) { AttackStrategy = attackStrategy, Constraints = constraints.AsReadOnly(), ConstraintCount = constraintCount, Source = root, IsMw3 = mw3, AmbiguousIndices = declared.Where(p => p.Value > 1).Select(p => p.Key).ToHashSet(), ResolvedIndices = unique, ValveEdgeSources = resolvedEdges.AsReadOnly(), ValveEdgesByNode = edgeValves.ToDictionary(p => p.Key, p => (IReadOnlyList)p.Value.AsReadOnly()) }; } diff --git a/src/zStudio.Core/MissionAiValves.cs b/src/zStudio.Core/MissionAiValves.cs index cffadd0f..dd289c9b 100644 --- a/src/zStudio.Core/MissionAiValves.cs +++ b/src/zStudio.Core/MissionAiValves.cs @@ -10,6 +10,8 @@ public sealed record AiValveRecord(Guid Id, Guid Parent, int ChildIndex, ZrdNode string Kind, int? NodeIndex = null, int? From = null, int? To = null) { public string Name => NameNode.Text; + public IReadOnlyList TargetNodes { get; init; } = []; + public int TargetNodeCount => Kind == "edge" ? TargetNodes.Count == 256 ? -1 : TargetNodes.Count : 0; public long SourceOffset => NameNode.SourceOffset; } public sealed record AiValveReference(Guid Record, Guid Operand, string Name, string Role); @@ -41,10 +43,12 @@ public static AiNetworkSnapshot Attach(AiNetworkSnapshot graph, IEnumerable name.Equals("valves.zrd", StringComparison.OrdinalIgnoreCase) || - name.Equals("objectives.zrd", StringComparison.OrdinalIgnoreCase) || MissionAiNetworks.IsCandidate(name, mw3: true); + name.Equals("objectives.zrd", StringComparison.OrdinalIgnoreCase) || name.Equals("aiv.zrd", StringComparison.OrdinalIgnoreCase) || + name.Equals("targets.zrd", StringComparison.OrdinalIgnoreCase) || MissionAiNetworks.IsCandidate(name, mw3: true); + private static bool ValveAttribute(string key) => key is "valve" or "valveunion" or "valve_assign"; public static string Short(string text, int maximum = 256) => text.Length <= maximum ? text : text[..maximum] + "…"; public static bool MatchesSearch(AiValveRecord record, string query) => record.Name.Contains(query, StringComparison.OrdinalIgnoreCase) || (record.NodeIndex?.ToString(CultureInfo.InvariantCulture)?.Contains(query, StringComparison.OrdinalIgnoreCase) ?? false) || @@ -81,7 +85,13 @@ private static bool HasAttribute(ZrdNode source, int first, string? name) for (int i = first; i + 1 < source.Children.Count; i += 2) { var key = source.Children[i]; - if (key.Kind == ZrdKind.String && (first == 3 ? key.Text is "valve" or "valveunion" : key.Text == "valve_assign") && Matches(key.Text, source.Children[i + 1], name)) return true; + if (key.Kind != ZrdKind.String) continue; + if (ValveAttribute(key.Text) && Matches(key.Text, source.Children[i + 1], name)) return true; + // A deploy point names two valves and a wait point one (Mw3ValveMap lists them): found when a valve is asked for by + // name. The overlay of every valve attribute (no name) keeps to gates, unions and assignments. + if (name != null && key.Text is "deploy" or "mcbwait" && source.Children[i + 1].Kind == ZrdKind.Array) + foreach (int at in key.Text == "deploy" ? new[] { 0, 2 } : [0]) + if (source.Children[i + 1].Children.ElementAtOrDefault(at) is { Kind: ZrdKind.String } named && named.Text == name) return true; } return false; } @@ -96,15 +106,16 @@ private static bool Matches(string attribute, ZrdNode value, string? name) return false; } public static IEnumerable EdgeAssignments(AiNetwork network, string? name = null) - { foreach (var edge in network.ValveEdgeSources) foreach (var record in Attributes(edge, null, name)) yield return record; } + { foreach (var edge in network.ValveEdgeSources) foreach (var record in Attributes(edge, null, name).Where(r => r.Name == "valve_assign")) yield return record; } private static IEnumerable Attributes(ZrdNode source, int? node, string? name = null) { var c = source.Children; for (int i = node != null ? 3 : 1; i + 1 < c.Count; i += 2) { - if (c[i].Kind != ZrdKind.String || (node != null ? c[i].Text is not ("valve" or "valveunion") : c[i].Text != "valve_assign") || !Matches(c[i].Text, c[i + 1], name)) continue; + if (c[i].Kind != ZrdKind.String || !ValveAttribute(c[i].Text) || !Matches(c[i].Text, c[i + 1], name)) continue; yield return new(c[i].Id, source.Id, i, c[i], c[i + 1], node != null ? "node" : "edge", node, - node == null ? unchecked((int)c[0].Children[0].Bits) : null, node == null ? unchecked((int)c[0].Children[1].Bits) : null); + node == null ? unchecked((int)c[0].Children[0].Bits) : null, node == null ? unchecked((int)c[0].Children[1].Bits) : null) + { TargetNodes = node == null ? c[0].Children.Skip(1).Take(256).Select(n => unchecked((int)n.Bits)).ToArray() : [] }; } } public static ZrdNode Fields(ZrdNode root) => root.Kind == ZrdKind.Array && root.Children.Count == 1 && root.Children[0].Kind == ZrdKind.Array ? root.Children[0] : root; @@ -142,9 +153,10 @@ public static IEnumerable Records(string member, ZrdNode root, Ca for (int j = spatial ? 3 : 1; j + 1 < c.Count; j += 2) { token.ThrowIfCancellationRequested(); - if (c[j].Kind != ZrdKind.String || (spatial ? c[j].Text is not ("valve" or "valveunion") : c[j].Text != "valve_assign")) continue; + if (c[j].Kind != ZrdKind.String || !ValveAttribute(c[j].Text)) continue; yield return new(c[j].Id, value.Id, j, c[j], c[j + 1], spatial ? "node" : "edge", spatial ? index : null, - edge ? unchecked((int)c[0].Children[0].Bits) : null, edge ? unchecked((int)c[0].Children[1].Bits) : null); + edge ? unchecked((int)c[0].Children[0].Bits) : null, edge ? unchecked((int)c[0].Children[1].Bits) : null) + { TargetNodes = edge ? c[0].Children.Skip(1).Take(256).Select(n => unchecked((int)n.Bits)).ToArray() : [] }; } } } @@ -163,6 +175,32 @@ IEnumerable Walk(ZrdNode node, int depth) } } } + else if (member.Equals("targets.zrd", StringComparison.OrdinalIgnoreCase) || member.Equals("aiv.zrd", StringComparison.OrdinalIgnoreCase)) + { + bool target = member.Equals("targets.zrd", StringComparison.OrdinalIgnoreCase); + for (int i = 0; i + 1 < fields.Children.Count; i += 2) + { + token.ThrowIfCancellationRequested(); + var owner = fields.Children[i + 1]; + if (fields.Children[i].Kind != ZrdKind.String || owner.Kind != ZrdKind.Array) continue; + if (target && Mw3ValveProgram.Find(owner, "health_below") is { } thresholds) + for (int j = 0; j + 2 < thresholds.Children.Count; j += 3) + if (thresholds.Children[j] is { Kind: ZrdKind.String } name) + yield return new(name.Id, thresholds.Id, j, name, thresholds, "target"); + if (!target) + { + if (Mw3ValveProgram.Find(owner, "vlist") is { } list) + foreach (var trigger in list.Children) + { + token.ThrowIfCancellationRequested(); + if (trigger.Children.Count >= 16 && trigger.Children[15] is { Kind: ZrdKind.String } name) + yield return new(name.Id, trigger.Id, 15, name, trigger, "actor"); + } + if (Mw3ValveProgram.Find(owner, "p4") is { Children.Count: >= 23 } old && old.Children[22] is { Kind: ZrdKind.String } n) + yield return new(n.Id, old.Id, 22, n, old, "actor"); + } + } + } } public static IEnumerable References(AiValveRecord record, CancellationToken token = default) @@ -172,21 +210,27 @@ public static IEnumerable References(AiValveRecord record, Can if (record.Kind == "definition") { yield return new(record.Id, record.NameNode.Id, record.Name, "action trigger / compound output"); - if (c.Count >= 3 && c[0].Kind == ZrdKind.String && Conditions.Contains(c[0].Text) && c[1].Text == "namelist") - { foreach (var n in c[2].Children) { token.ThrowIfCancellationRequested(); if (Reference(n, "compound input") is { } r) yield return r; } } - else for (int i = 0; i + 1 < c.Count; i += 2) - { token.ThrowIfCancellationRequested(); if (c[i].Text == "delayupdate" && Reference(c[i + 1].Children.FirstOrDefault(), "delayed update") is { } r) yield return r; } + if (Conditions.Any(k => Mw3ValveProgram.HasTag(record.Value, k)) && Mw3ValveProgram.Find(record.Value, "namelist") is { } names) + foreach (var n in names.Children) { token.ThrowIfCancellationRequested(); if (Reference(n, "compound input") is { } input) yield return input; } + foreach (string tag in new[] { "update", "delayupdate" }) + { + token.ThrowIfCancellationRequested(); + if (Mw3ValveProgram.Find(record.Value, tag) is { } update && Reference(update.Children.FirstOrDefault(), tag == "update" ? "update" : "delayed update") is { } target) + yield return target; + } } - else if (record.Name == "valve" && Reference(c.ElementAtOrDefault(1), "node condition") is { } condition) yield return condition; - else if (record.Name == "valve_assign" && Reference(c.FirstOrDefault(), "edge assignment") is { } assignment) yield return assignment; - else if (record is { Kind: "node", Name: "valveunion" }) + else if (record.Kind is "node" or "edge" && record.Name == "valve" && Reference(c.ElementAtOrDefault(1), "node condition") is { } condition) yield return condition; + else if (record.Kind is "node" or "edge" && record.Name == "valve_assign" && Reference(c.FirstOrDefault(), "edge assignment") is { } assignment) yield return assignment; + else if (record.Name == "valveunion" && record.Kind is "node" or "edge") { foreach (var term in c) { token.ThrowIfCancellationRequested(); if (Reference(term.Children.ElementAtOrDefault(1), "union term") is { } r) yield return r; } } - else if (record.Name == "set_valve" && Reference(c.FirstOrDefault(), "objective assignment") is { } objective) yield return objective; - else if (record.Name == "valve_change") + else if (record.Kind == "objective" && record.Name == "set_valve" && Reference(c.FirstOrDefault(), "objective assignment") is { } objective) yield return objective; + else if (record.Kind == "objective" && record.Name == "valve_change") { for (int i = 0; i + 1 < c.Count; i += 2) { token.ThrowIfCancellationRequested(); if (c[i].Text == "valve" && Reference(c[i + 1].Children.FirstOrDefault(), "objective condition") is { } r) yield return r; } } + else if (record.Kind is "actor" or "target") + yield return new(record.Id, record.NameNode.Id, record.Name, record.Kind == "actor" ? "actor trigger" : "health threshold"); } public static JsonObject Describe(AiValveRecord r, CancellationToken token = default) @@ -194,6 +238,7 @@ public static JsonObject Describe(AiValveRecord r, CancellationToken token = def var references = References(r, token).Take(9).ToArray(); return new() { ["record"] = r.Id.ToString(), ["parent"] = r.Parent.ToString(), ["valueNode"] = r.Value.Id.ToString(), ["name"] = Short(r.Name), ["nameCharacters"] = r.Name.Length, ["kind"] = r.Kind, ["nodeIndex"] = r.NodeIndex, ["from"] = r.From, ["to"] = r.To, ["sourceOffset"] = r.SourceOffset, + ["targetNodes"] = new JsonArray(r.TargetNodes.Select(n => JsonValue.Create(n)).ToArray()), ["targetNodesMayBeTruncated"] = r.TargetNodes.Count == 256, ["parameters"] = r.Value.ToPreviewJson(token, 24, 256, 5, 128), ["problem"] = Problem(r, token), ["references"] = new JsonArray(references.Take(8).Select(x => (JsonNode)new JsonObject { ["operand"] = x.Operand.ToString(), ["name"] = Short(x.Name, 128), ["nameCharacters"] = x.Name.Length, ["role"] = x.Role }).ToArray()), ["referencesTruncated"] = references.Length > 8 }; @@ -202,32 +247,33 @@ public static JsonObject Describe(AiValveRecord r, CancellationToken token = def { if (r.Value.Kind != ZrdKind.Array) return "Expected an ordered parameter array. Original data is retained."; var c = r.Value.Children; - bool Tuple(ZrdNode n) => n.Kind == ZrdKind.Array && n.Children.Count is 2 or 3 && n.Children[0].Kind == ZrdKind.Int && n.Children[1].Kind == ZrdKind.String && (n.Children.Count == 2 || n.Children[2].Kind == ZrdKind.Int); - if (r.Name == "valve" && r.Kind == "node" && !Tuple(r.Value)) return "Expected stored integer, valve name and optional stored integer."; - if (r.Kind == "node" && r.Name == "valveunion" && (c.Count == 0 || c.Any(n => !Tuple(n)))) return "Expected ordered valve tuples."; - if (r.Kind == "edge" && r.Name == "valve_assign" && (c.Count != 2 || c[0].Kind != ZrdKind.String || c[1].Kind != ZrdKind.Int)) return "Expected valve name and assigned integer."; + bool Word(ZrdNode n) => n.Kind is ZrdKind.Int or ZrdKind.Float; + bool Tuple(ZrdNode n) => n.Kind == ZrdKind.Array && n.Children.Count is 2 or 3 && Word(n.Children[0]) && n.Children[1].Kind == ZrdKind.String && (n.Children.Count == 2 || Word(n.Children[2])); + if (r.Name == "valve" && r.Kind is "node" or "edge" && !Tuple(r.Value)) return "Expected stored integer, valve name and optional stored integer."; + if (r.Kind is "node" or "edge" && r.Name == "valveunion" && (c.Count == 0 || c.Any(n => !Tuple(n)))) return "Expected ordered valve tuples."; + if (r.Kind is "node" or "edge" && r.Name == "valve_assign" && (c.Count != 2 || c[0].Kind != ZrdKind.String || !Word(c[1]))) return "Expected valve name and assigned integer."; if (r.Kind == "definition") { - if (c.Count >= 1 && Conditions.Contains(c[0].Text)) return c.Count == 3 && c[1].Text == "namelist" && c[2].Kind == ZrdKind.Array && c[2].Children.All(n => n.Kind == ZrdKind.String) ? null : "Expected compound kind, namelist and ordered valve names."; - if (c.Count % 2 != 0 || c.Count == 0) return "Unrecognized action block. Use source properties to preserve or repair it."; - for (int i = 0; i < c.Count; i += 2) if (c[i].Kind != ZrdKind.String || c[i + 1].Kind != ZrdKind.Array || !Actions.Contains(c[i].Text)) return "Unrecognized action or layout; stored fields remain accessible."; - for (int i = 0; i < c.Count; i += 2) - { - token.ThrowIfCancellationRequested(); - var p = c[i + 1].Children; - bool valid = c[i].Text switch - { - "attack_strategy" or "shutdown" => p.Count == 3 && p[0].Kind == ZrdKind.String && p[1].Kind == ZrdKind.Int && p[2].Kind == ZrdKind.Int, - "delayupdate" => p.Count == 2 && p[0].Kind == ZrdKind.String && p[1].Kind == ZrdKind.Float, - "destroy" or "sound" => p.Count == 2 && p[0].Kind == ZrdKind.String && p[1].Kind == ZrdKind.Int, - "sound_once" => p.Count == 2 && p[0].Kind == ZrdKind.String && p[1].Kind is ZrdKind.Int or ZrdKind.Float, - "teleport" => p.Count == 4 && p[0].Kind == ZrdKind.String && p[1].Kind == ZrdKind.Array && p[1].Children.Count == 3 && p[1].Children.All(n => n.Kind == ZrdKind.Float) && p[2].Kind == ZrdKind.Float && p[3].Kind == ZrdKind.Int, - _ => false - }; - if (!valid) return $"Action {i / 2} has an unrecognized operand layout; original typed fields are retained."; - } + if (Mw3ValveProgram.SourceProblem(r.Value) is { } problem) return problem; + var root = ZrdNode.Create(ZrdKind.Array) with { Children = [r.NameNode, r.Value] }; + var definition = Mw3ValveProgram.Read(root, token).Definitions[0]; + if (definition.Condition == null && definition.Initial == null && definition.Actions.Count == 0) + return "No recognized native property or action; stored fields remain accessible."; + return Mw3ValveProgram.Problem(definition); + } + if (r.Kind == "objective" && r.Name == "set_valve" && (c.Count != 2 || c[0].Kind != ZrdKind.String || !Word(c[1]))) return "Expected objective valve name and assigned integer."; + if (r.Kind == "objective" && r.Name == "valve_change") + { + if (Mw3ValveProgram.Find(r.Value, "valve") is not { Kind: ZrdKind.Array, Children.Count: 1 } v || v.Children[0].Kind != ZrdKind.String) + return "Expected valve (name) and optional value (comparison word)."; + if (Mw3ValveProgram.HasTag(r.Value, "value") && + (Mw3ValveProgram.Find(r.Value, "value") is not { Kind: ZrdKind.Array, Children.Count: 1 } comparison || !Word(comparison.Children[0]))) + return "Expected one objective comparison word."; } - if (r.Kind == "objective" && r.Name == "set_valve" && (c.Count != 2 || c[0].Kind != ZrdKind.String || c[1].Kind != ZrdKind.Int)) return "Expected objective valve name and assigned integer."; + if (r.Kind == "target" && (c.Count % 3 != 0 || Enumerable.Range(0, c.Count / 3).Any(i => + c[i * 3].Kind != ZrdKind.String || !Word(c[i * 3 + 1]) || !Word(c[i * 3 + 2]) || !float.IsFinite(Mw3ValveRuntime.Number(r.Value, i * 3 + 2))))) return "Expected health threshold triples: valve name, assigned word, finite fraction."; + if (r.Kind == "actor" && (r.ChildIndex >= c.Count || c[r.ChildIndex].Kind != ZrdKind.String || + c.Count < r.ChildIndex + 2 || !Word(c[r.ChildIndex + 1]))) return "Expected actor trigger name and assigned word."; return null; } } diff --git a/src/zStudio.Core/MissionSceneContext.Transforms.cs b/src/zStudio.Core/MissionSceneContext.Transforms.cs index d33fbf7c..d607f0a7 100644 --- a/src/zStudio.Core/MissionSceneContext.Transforms.cs +++ b/src/zStudio.Core/MissionSceneContext.Transforms.cs @@ -24,6 +24,9 @@ public sealed partial class MissionSceneContext public MissionSceneContext? WithSourceTransforms(GameScene beforeSource, GameScene afterSource, CancellationToken token = default) { token.ThrowIfCancellationRequested(); + // Retained native load/startup states include hydrated descendants, not just written channels. + // Rebuild after a transform edit rather than let a later simulation restore an old authored pose. + if (ValveLoadBefore != null || ValveStartupBefore != null) return null; if (InitializationTransforms is not { } dependencies || beforeSource.Nodes.Count != originalNodeCount || afterSource.Nodes.Count != originalNodeCount || Scene.Nodes.Count < originalNodeCount || SourceNodes.Count != Scene.Nodes.Count || !SameGeometry(beforeSource, afterSource)) return null; @@ -112,7 +115,7 @@ public sealed partial class MissionSceneContext if (lookup.First(query.Root, query.Name, query.Limit) != query.Result) return null; } return new(scene, SourceNodes.ToList(), Actors.ToList(), new(DormantRoots), Diagnostics, Layout, originalNodeCount, token, previewDiagnostics: PreviewDiagnostics) - { AiNetworks = AiNetworks, InitializationTransforms = dependencies, AnimationEntryRoots = AnimationEntryRoots, AnimationUses = AnimationUses, LocalPlayer = LocalPlayer, PlayerTank = PlayerTank, PlayerTankFailure = PlayerTankFailure, PlayerStartControl = PlayerStartControl, PlayerStart = PlayerStart, StartupAnimations = StartupAnimations, LoadGameAnimations = LoadGameAnimations }; +{ ValveStartupBefore = ValveStartupBefore, ValveLoadBefore = ValveLoadBefore, AiNetworks = AiNetworks, InitializationTransforms = dependencies, AnimationEntryRoots = AnimationEntryRoots, AnimationUses = AnimationUses, LocalPlayer = LocalPlayer, PlayerTank = PlayerTank, PlayerTankFailure = PlayerTankFailure, PlayerStartControl = PlayerStartControl, PlayerStart = PlayerStart, StartupAnimations = StartupAnimations, LoadGameAnimations = LoadGameAnimations }; } /// @@ -148,7 +151,7 @@ public sealed partial class MissionSceneContext { scene.Models[i] = copy with { Polygons = afterSource.Models[j].Polygons }; break; } } return new(scene, SourceNodes.ToList(), Actors.ToList(), new(DormantRoots), Diagnostics, Layout, originalNodeCount, token, previewDiagnostics: PreviewDiagnostics) - { AiNetworks = AiNetworks, InitializationTransforms = InitializationTransforms, AnimationEntryRoots = AnimationEntryRoots, AnimationUses = AnimationUses, LocalPlayer = LocalPlayer, PlayerTank = PlayerTank, PlayerTankFailure = PlayerTankFailure, PlayerStartControl = PlayerStartControl, PlayerStart = PlayerStart, StartupAnimations = StartupAnimations, LoadGameAnimations = LoadGameAnimations }; + { ValveStartupBefore = ValveStartupBefore, ValveLoadBefore = ValveLoadBefore, AiNetworks = AiNetworks, InitializationTransforms = InitializationTransforms, AnimationEntryRoots = AnimationEntryRoots, AnimationUses = AnimationUses, LocalPlayer = LocalPlayer, PlayerTank = PlayerTank, PlayerTankFailure = PlayerTankFailure, PlayerStartControl = PlayerStartControl, PlayerStart = PlayerStart, StartupAnimations = StartupAnimations, LoadGameAnimations = LoadGameAnimations }; } private static readonly string[] BoundsFields =["node_bbox", "model_bbox", "child_bbox", "area_partition", "update_flags"]; diff --git a/src/zStudio.Core/MissionSceneContext.Valves.cs b/src/zStudio.Core/MissionSceneContext.Valves.cs new file mode 100644 index 00000000..73e4c5d5 --- /dev/null +++ b/src/zStudio.Core/MissionSceneContext.Valves.cs @@ -0,0 +1,41 @@ +using System.Text.Json.Nodes; +using zStudio.Core.Worlds; + +namespace zStudio.Core; + +public sealed partial class MissionSceneContext +{ + internal IReadOnlyDictionary? ValveStartupBefore { get; init; } + internal IReadOnlyDictionary? ValveLoadBefore { get; init; } + /// Startup-only fields are restored on a private scene; placement, zones and authored fields remain current. + public MissionSceneContext ValveStartupBaseline(CancellationToken token = default) + { + GameScene scene = new(); scene.Models.AddRange(Scene.Models); scene.Materials.AddRange(Scene.Materials); scene.Textures.AddRange(Scene.Textures); + var placed = Actors.Select(a => a.Root).ToHashSet(); + foreach (var node in Scene.Nodes) + { + token.ThrowIfCancellationRequested(); + var startup = ValveStartupBefore?.GetValueOrDefault(node.Index); var load = ValveLoadBefore?.GetValueOrDefault(node.Index); + if (startup == null && load == null) { scene.Nodes.Add(node); continue; } + var data = (JsonObject)node.Data.DeepClone(); var metadata = (JsonObject)node.Metadata.DeepClone(); + int? model = node.ModelIndex; + Restore(startup, false); Restore(load, placed.Contains(node.Index)); + scene.Nodes.Add(node with { Data = data, Metadata = metadata, ModelIndex = model }); + void Restore(GameNode? before, bool keepPlacement) + { + if (before == null) return; + foreach (string field in new[] { "transform", "rotate", "scale", "translate", "opacity", "flags" }) + { + if (keepPlacement && field is "transform" or "rotate" or "scale" or "translate") continue; + if (keepPlacement && field == "flags") + { data[field] = (before.Data.UInt(field) & ~WorldGltf.ObjectTransformFlags) | (data.UInt(field) & WorldGltf.ObjectTransformFlags); continue; } + if (before.Data[field] is { } value) data[field] = value.DeepClone(); else data.Remove(field); + } + if (!keepPlacement) metadata["flags"] = (metadata.UInt("flags") & ~4u) | (before.Metadata.UInt("flags") & 4u); + model = before.ModelIndex; + } + } + return new(scene, SourceNodes.ToList(), Actors.ToList(), [.. DormantRoots], Diagnostics, Layout, originalNodeCount, token, previewDiagnostics: PreviewDiagnostics) + { ValveLoadBefore = ValveLoadBefore, AiNetworks = AiNetworks, StartupAnimations = StartupAnimations, AnimationEntryRoots = AnimationEntryRoots, PlayerStart = PlayerStart, LocalPlayer = LocalPlayer }; + } +} diff --git a/src/zStudio.Core/MissionSceneLoader.Mw3.cs b/src/zStudio.Core/MissionSceneLoader.Mw3.cs index de06ca81..85ab2c02 100644 --- a/src/zStudio.Core/MissionSceneLoader.Mw3.cs +++ b/src/zStudio.Core/MissionSceneLoader.Mw3.cs @@ -406,7 +406,7 @@ private static MissionSceneContext BuildMw3Scene(AssetDocument world, IReadOnlyL budget.Take(edges); budget.Storage(64L * edges); scene.Nodes[worldRoot] = scene.Nodes[worldRoot] with { Children = scene.Nodes[worldRoot].Children.Concat(attachedRoots).Distinct().ToArray() }; } - if (animation != null) Initialize(false); + if (animation != null) { animation.ValveStartupBefore = []; Initialize(false); } Dictionary entryRoots = []; if (package != null && binding != null) foreach (var entry in package.Entries) @@ -423,6 +423,8 @@ private static MissionSceneContext BuildMw3Scene(AssetDocument world, IReadOnlyL { InitializationTransforms = dependencies, AnimationEntryRoots = entryRoots, AnimationUses = uses, PlayerStart = playerStart, LocalPlayer = actors.FirstOrDefault(a => a.Name == "player"), StartupAnimations = startup + , ValveStartupBefore = animation?.ValveStartupBefore + , ValveLoadBefore = animation?.ValveLoadBefore }; context.AiNetworks = MissionAiNetworks.Read((missionSources ?? (selected == null ? [] : [selected])).SelectMany(d => d.Assets.Where(a => MissionAiNetworks.IsCandidate(a.Name, mw3: true)).Select(a => (d, a))), token); context.AiNetworks = MissionAiValves.Attach(context.AiNetworks, archives.Where(a => a == selected || !a.Assets.Any(v => v.Name.Equals("aiv.zrd", StringComparison.OrdinalIgnoreCase))), token); @@ -442,6 +444,8 @@ int Clone(GameScene source, int index, int parent, int depth, HashSet activ var metadata = (JsonObject)n.Metadata.DeepClone(); metadata["source_library"] = mech ? library!.Path : world.Path; metadata["source_node"] = index; scene.Nodes.Add(n with { Index = id, Parents = parent < 0 ? [] : [parent], Children = [], ModelIndex = n.ModelIndex is int m ? (mech ? modelBase : 0) + m : null, Metadata = metadata, Data = (JsonObject)n.Data.DeepClone() }); sources.Add(mech ? -1 : index); + if (!mech && animation?.ValveLoadBefore is { } captured && captured.TryGetValue(index, out var before)) + { budget.Storage(64); captured.TryAdd(id, before); } var children = n.Children.Select(c => Clone(source, c, id, depth + 1, active, mech)).ToArray(); scene.Nodes[id] = scene.Nodes[id] with { Children = children }; active.Remove(index); return id; } diff --git a/src/zStudio.Core/Mw3ValveMap.cs b/src/zStudio.Core/Mw3ValveMap.cs new file mode 100644 index 00000000..b2684ea3 --- /dev/null +++ b/src/zStudio.Core/Mw3ValveMap.cs @@ -0,0 +1,476 @@ +using System.Globalization; +using System.Text.Json; +using zStudio.Core.Formats; + +namespace zStudio.Core; + +/// A mission resource the valve map reads: its project path and parsed tree. +public sealed record Mw3ValveSource(string Path, ZrdNode Root); + +/// What the mission has for a reaction to name; null sets are unknown (nothing is reported against them). +public sealed record Mw3ValveCatalog(IReadOnlySet? Vehicles = null, IReadOnlySet? Sounds = null, IReadOnlySet? Animations = null); + +/// +/// A reaction's editable fields as text, so an untouched number keeps its stored form. is the stored tag +/// (sound, sound_once, shutdown, delayupdate…). Target: the sound, animation, vehicle or valve. Operand: on/off, the team, +/// the strategy, or a timer's seconds. When: the valve value that triggers it (update and delayupdate have none). +/// +public sealed record Mw3ValveReactionSpec(string Kind, string? Target = null, string? Operand = null, string? When = null, + string? X = null, string? Y = null, string? Z = null, string? Yaw = null); + +/// One action of one valves.zrd record: the record's occurrence in the file and the stored tag identify it. +public sealed record Mw3ValveReaction(string Source, Guid Record, int Occurrence, Mw3ValveReactionSpec Spec, string Text, string? Problem = null); + +/// +/// Something outside the valve's own records that sets it () or waits on it. Owner is the +/// vehicle, target, network node, objective group or other valve; Value the value set or expected. +/// +public sealed record Mw3ValveLink(string Role, string Source, Guid Record, string Owner, string Text, int? Value = null, + string? Network = null, int? Node = null, string? Actor = null, string? Valve = null, int? Entry = null); + +/// One valves.zrd record of a valve, as the Source section shows it. +public sealed record Mw3ValveRecord(string Source, Guid Record, int Occurrence, string? Problem); + +public sealed record Mw3ValveInfo(string Name) +{ + /// A valves.zrd record names it; otherwise only other files do (the game makes it on first mention, at zero). + public bool Defined => Records.Count > 0; + /// + /// The starting value as stored (the last record's that holds one; 0 without one). A computed valve keeps the word in + /// its file but ignores it; it is shown and edited as stored, so that making the valve a switch again starts where the file says. + /// + public int Initial { get; init; } + public string? Condition { get; init; } + public IReadOnlyList Inputs { get; init; } = []; + public IReadOnlyList Records { get; init; } = []; + public IReadOnlyList Reactions { get; init; } = []; + public IReadOnlyList SetBy { get; init; } = []; + public IReadOnlyList UsedBy { get; init; } = []; + public IReadOnlyList Problems { get; init; } = []; + /// What it does in a few words: its reactions, else what waits on it, else what sets it. + public string Summary { get; init; } = ""; + /// Every name it mentions (vehicles, sounds, animations, valves, regions), for search. + public IReadOnlyList Mentions { get; init; } = []; +} + +/// +/// The mission's valves by exact name, gathered from valves.zrd (definitions and reactions), aiv.zrd (vehicle triggers), +/// targets.zrd (health thresholds), the networks (route gates, assignments, deploy points) and the map's objectives. +/// A reading aid over the shared trees: source records stay authoritative and are never changed here. +/// +public sealed class Mw3ValveMap +{ + public const int MaximumValves = 4096, MaximumLinks = 65_536, ShownLinks = 256; + public static readonly string[] SetRoles = ["trigger", "health", "objective", "route", "timer", "fire", "deploy", "animation"]; + public static readonly Mw3ValveMap Empty = new([], null, false); + public IReadOnlyList Valves { get; } + /// The mission's valves.zrd path, when one was read. + public string? DefinitionSource { get; } + /// More names or links than the map keeps: the rest is in the source files. + public bool Truncated { get; } + private readonly Dictionary byName; + private Mw3ValveMap(IReadOnlyList valves, string? definitionSource, bool truncated) + { + Valves = valves; DefinitionSource = definitionSource; Truncated = truncated; + byName = valves.ToDictionary(v => v.Name, StringComparer.Ordinal); + } + public Mw3ValveInfo? Find(string name) => byName.GetValueOrDefault(name); + + private sealed class Builder(string name) + { + public readonly string Name = name; + public int Initial; public string? Condition; public string[] Inputs = []; + public readonly List Records = []; + public readonly List Reactions = []; + public readonly List SetBy = [], UsedBy = []; + public readonly List Problems = []; + public readonly HashSet Mentions = new(StringComparer.Ordinal); + } + + /// The mission's folder name (m1, ia2…): the objectives block that belongs to it. + /// The animations that set valves through callbacks 42–49 (); listed for the valves the files name. + public static Mw3ValveMap Build(IEnumerable sources, string? mission, Mw3ValveCatalog? catalog = null, CancellationToken token = default, + IEnumerable? callbacks = null) + { + Dictionary valves = new(StringComparer.Ordinal); + string? definitionSource = null; bool truncated = false; int links = 0; + Builder? Get(string name) + { + if (valves.TryGetValue(name, out var found)) return found; + if (valves.Count == MaximumValves || name.Length > 256) { truncated = true; return null; } + valves.Add(name, found = new(name)); return found; + } + void Link(bool sets, string name, Mw3ValveLink link, params string?[] mentions) + { + if (Get(name) is not { } valve) return; + if (++links > MaximumLinks) { truncated = true; return; } + (sets ? valve.SetBy : valve.UsedBy).Add(link); + foreach (string? mention in mentions) if (mention is { Length: > 0 and <= 256 } && valve.Mentions.Count < 64) valve.Mentions.Add(mention); + } + foreach (var source in sources.OrderBy(s => s.Path, StringComparer.OrdinalIgnoreCase)) + { + token.ThrowIfCancellationRequested(); + string member = System.IO.Path.GetFileName(source.Path); + if (member.Equals("valves.zrd", StringComparison.OrdinalIgnoreCase)) + { + definitionSource ??= source.Path; + int occurrence = -1; + foreach (var record in MissionAiValves.Records(member, source.Root, token)) + { + occurrence++; + if (Get(record.Name) is not { } valve) continue; + string? problem = Mw3ValveProgram.SourceProblem(record.Value); + valve.Records.Add(new(source.Path, record.Id, occurrence, problem)); + if (problem != null) { valve.Problems.Add($"Record {valve.Records.Count} is not as the game reads it ({problem.TrimEnd('.')}); it is kept as stored."); continue; } + string? condition = Mw3ValveProgram.Conditions.FirstOrDefault(k => Mw3ValveProgram.HasTag(record.Value, k)); + if (condition != null) + { + string[] inputs = [.. (Mw3ValveProgram.Find(record.Value, "namelist")?.Children ?? []).Where(n => n.Kind == ZrdKind.String).Select(n => n.Text).Take(256)]; + if (valve.Condition != null) + { + // The game keeps the first computed definition and drops this whole record: its value and reactions too. + const string dropped = "A second computed definition: the game keeps the first and drops this whole record, with its reactions."; + valve.Records[^1] = valve.Records[^1] with { Problem = dropped }; + valve.Problems.Add("A second computed definition: the game keeps the first and drops that whole record, with its reactions."); + continue; + } + valve.Condition = condition; valve.Inputs = inputs; + foreach (string input in inputs) + Link(false, input, new("computed", source.Path, record.Id, valve.Name, $"{ConditionText(condition)} ({inputs.Length} input{(inputs.Length == 1 ? "" : "s")})", Valve: valve.Name), valve.Name); + foreach (string input in inputs) valve.Mentions.Add(input); + } + if (Mw3ValveProgram.Find(record.Value, "value") is { Children: [{ Kind: ZrdKind.Int or ZrdKind.Float } word] }) valve.Initial = unchecked((int)word.Bits); + foreach (string kind in Mw3ValveProgram.ActionOrder) + { + string stored = kind is "sound" or "animation" && Mw3ValveProgram.HasTag(record.Value, kind + "_once") ? kind + "_once" : kind; + if (Mw3ValveProgram.Find(record.Value, stored) is not { Kind: ZrdKind.Array } arguments) continue; + var spec = Spec(stored, arguments); + string? missing = Missing(spec, catalog); + valve.Reactions.Add(new(source.Path, record.Id, occurrence, spec, ReactionText(spec), missing)); + if (missing != null) valve.Problems.Add(missing); + if (spec.Target is { Length: > 0 } target) valve.Mentions.Add(target); + if (kind is "update" or "delayupdate" && spec.Target is { } next) + Link(true, next, new(kind == "update" ? "fire" : "timer", source.Path, record.Id, valve.Name, + kind == "update" ? "fires its reactions whenever it changes" : $"sets it to its own value {Seconds(spec.Operand)} after it changes", Valve: valve.Name), valve.Name); + } + // A record with several reactions of one kind: the game builds one (the card edits that one's fields only). + if (record.Value.Children.Where(n => n.Kind == ZrdKind.String).Select(n => n.Text is "sound_once" ? "sound" : n.Text is "animation_once" ? "animation" : n.Text) + .Where(t => Mw3ValveProgram.ActionOrder.Contains(t)).GroupBy(t => t, StringComparer.Ordinal).FirstOrDefault(g => g.Count() > 1) is { } repeated) + valve.Problems.Add($"A record stores more than one {repeated.Key} reaction: the game uses only one of them (a once-only one before a plain one, else the first)."); + } + } + else if (member.Equals("aiv.zrd", StringComparison.OrdinalIgnoreCase)) Vehicles(source); + else if (member.Equals("targets.zrd", StringComparison.OrdinalIgnoreCase)) Targets(source); + else if (member.Equals("objectives.zrd", StringComparison.OrdinalIgnoreCase)) Objectives(source); + else if (MissionAiNetworks.IsCandidate(member, mw3: true) && MissionAiValves.IsNetwork(source.Root)) Network(source, member); + } + // An animation sets the valve named as the node it binds; only valves the files name are listed. + foreach (var callback in callbacks ?? []) + { + token.ThrowIfCancellationRequested(); + if (!valves.ContainsKey(callback.Valve)) continue; + Link(true, callback.Valve, new("animation", "", Guid.Empty, callback.Animation, callback.Values is [var only] ? $"its events set it to {only}" : "its events set it to 0 and to 1", + callback.Values is [var value] ? value : null, Entry: callback.Entry), callback.Animation); + } + List result = []; + foreach (var valve in valves.Values.OrderBy(v => v.Name, StringComparer.OrdinalIgnoreCase).ThenBy(v => v.Name, StringComparer.Ordinal)) + { + token.ThrowIfCancellationRequested(); + result.Add(new(valve.Name) + { + Initial = valve.Initial, Condition = valve.Condition, Inputs = valve.Inputs, Records = valve.Records, Reactions = valve.Reactions, + SetBy = valve.SetBy, UsedBy = valve.UsedBy, Problems = [.. valve.Problems.Distinct(StringComparer.Ordinal).Take(16)], + Summary = Summary(valve), Mentions = [.. valve.Mentions.Order(StringComparer.Ordinal)], + }); + } + return new(result, definitionSource, truncated); + + void Vehicles(Mw3ValveSource source) + { + var fields = MissionAiValves.Fields(source.Root).Children; + for (int i = 0; i + 1 < fields.Count; i += 2) + { + token.ThrowIfCancellationRequested(); + if (fields[i].Kind != ZrdKind.String || fields[i + 1].Kind != ZrdKind.Array) continue; + string vehicle = fields[i].Text; + if (Mw3ValveProgram.Find(fields[i + 1], "vlist") is not { Kind: ZrdKind.Array } list) continue; + foreach (var trigger in list.Children) + { + var c = trigger.Children; + if (trigger.Kind != ZrdKind.Array || c.Count < 16 || c[15].Kind != ZrdKind.String) continue; + int value = On(c, 0) ? 1 : 0; + string? region = c[9].Kind == ZrdKind.String ? c[9].Text : null; + Link(true, c[15].Text, new("trigger", source.Path, c[15].Id, vehicle, $"{TriggerText(c)} → {value}", value, Actor: vehicle), vehicle, region); + } + } + } + void Targets(Mw3ValveSource source) + { + var fields = MissionAiValves.Fields(source.Root).Children; + for (int i = 0; i + 1 < fields.Count; i += 2) + { + token.ThrowIfCancellationRequested(); + if (fields[i].Kind != ZrdKind.String || fields[i + 1].Kind != ZrdKind.Array) continue; + string target = fields[i].Text; + if (Mw3ValveProgram.Find(fields[i + 1], "health_below") is not { Kind: ZrdKind.Array } thresholds) continue; + for (int j = 0; j + 2 < thresholds.Children.Count; j += 3) + { + if (thresholds.Children[j] is not { Kind: ZrdKind.String } name) continue; + int value = Mw3ValveRuntime.Integer(thresholds, j + 1); float health = Mw3ValveRuntime.Number(thresholds, j + 2); + string when = health <= 0 ? "when destroyed" : $"health below {Number(health)}"; + Link(true, name.Text, new("health", source.Path, name.Id, target, $"{when} → {value}", value, Actor: target), target); + } + } + } + void Objectives(Mw3ValveSource source) + { + // objectives.zrd holds every mission of the map: only this mission's block names this mission's valves. + var fields = MissionAiValves.Fields(source.Root).Children; ZrdNode? block = null; + for (int i = 0; mission != null && i + 1 < fields.Count; i += 2) + if (fields[i].Kind == ZrdKind.String && fields[i].Text.Equals(mission, StringComparison.OrdinalIgnoreCase) && fields[i + 1].Kind == ZrdKind.Array) { block = fields[i + 1]; break; } + if (block != null) Walk(block, "objective", 0); + void Walk(ZrdNode node, string group, int depth) + { + token.ThrowIfCancellationRequested(); + if (node.Kind != ZrdKind.Array || depth > 64) return; + var c = node.Children; + for (int i = 0; i < c.Count; i++) + { + if (c[i].Kind != ZrdKind.String || i + 1 >= c.Count || c[i + 1].Kind != ZrdKind.Array) { Walk(c[i], group, depth + 1); continue; } + var value = c[i + 1]; + if (c[i].Text == "valve_change" && Mw3ValveProgram.Find(value, "valve") is { Children: [{ Kind: ZrdKind.String } watched] }) + { + int expected = Mw3ValveProgram.Find(value, "value") is { Children: [{ Kind: ZrdKind.Int or ZrdKind.Float } word] } ? unchecked((int)word.Bits) : 1; + Link(false, watched.Text, new("objective", source.Path, c[i].Id, group, group == "fail objective" ? $"fails the mission when it is {expected}" : $"is met when it is {expected}", expected)); + } + else if (c[i].Text == "set_valve" && value.Children is [{ Kind: ZrdKind.String } set, { Kind: ZrdKind.Int or ZrdKind.Float } assigned]) + Link(true, set.Text, new("objective", source.Path, c[i].Id, group, $"when its condition is met → {unchecked((int)assigned.Bits)}", unchecked((int)assigned.Bits))); + // The mission block's groups name their objectives: primary, secondary, final, fail. + Walk(value, depth == 0 && c[i].Text is "primary" or "secondary" or "final" or "fail" ? c[i].Text + " objective" : group, depth + 1); + i++; + } + } + } + void Network(Mw3ValveSource source, string member) + { + string network = System.IO.Path.GetFileNameWithoutExtension(member); + foreach (var record in MissionAiValves.Records(member, source.Root, token)) + { + var c = record.Value.Children; + string where = record.Kind == "node" ? $"{network} · node {record.NodeIndex}" : $"{network} · link {record.From} → {string.Join(", ", record.TargetNodes.Take(4))}"; + int? node = record.NodeIndex ?? record.From; + if (record.Name == "valve" && c.Count >= 2 && c[1].Kind == ZrdKind.String) + { + bool enabled = Mw3ValveRuntime.Integer(record.Value, 0) != 0; int? expected = c.Count > 2 ? Mw3ValveRuntime.Integer(record.Value, 2) : null; + Link(false, c[1].Text, new("gate", source.Path, record.Id, where, !enabled ? "gate switched off" : expected is int e ? $"passes while it is {e}" + : "the last link passes while it is 1, the others while it is 0", expected, source.Path, node)); + } + else if (record.Name == "valveunion") + foreach (var term in c) + if (term.Children.Count >= 2 && term.Children[1].Kind == ZrdKind.String) + { + int expected = term.Children.Count > 2 ? Mw3ValveRuntime.Integer(term, 2) : 1; + Link(false, term.Children[1].Text, new("union", source.Path, record.Id, where, Mw3ValveRuntime.Integer(term, 0) == 0 ? "term switched off" + : $"passes while it is {expected}, or another of its {c.Count} valves holds", expected, source.Path, node)); + } + if (record.Name == "valve_assign" && c.Count >= 2 && c[0].Kind == ZrdKind.String) + { + int value = Mw3ValveRuntime.Integer(record.Value, 1); + Link(true, c[0].Text, new("route", source.Path, record.Id, where, $"a vehicle driving through → {value}", value, source.Path, node)); + } + } + // Deploy points and waits name valves beside their route: listed so the valve is found, without guessing more. + var fields = MissionAiValves.Fields(source.Root).Children; + for (int i = 0; i + 1 < fields.Count; i += 2) + { + token.ThrowIfCancellationRequested(); + if (fields[i].Kind != ZrdKind.String || !MissionAiNetworks.TryNodeIndex(fields[i].Text, out int index) || !MissionAiNetworks.IsSpatial(fields[i + 1], true, token)) continue; + var c = fields[i + 1].Children; + for (int j = 3; j + 1 < c.Count; j += 2) + { + if (c[j].Kind != ZrdKind.String || c[j].Text is not ("deploy" or "mcbwait") || c[j + 1].Kind != ZrdKind.Array) continue; + foreach (int at in c[j].Text == "deploy" ? new[] { 0, 2 } : [0]) + if (c[j + 1].Children.ElementAtOrDefault(at) is { Kind: ZrdKind.String, Text.Length: > 0 } named) + Link(true, named.Text, new("deploy", source.Path, named.Id, $"{network} · node {index}", c[j].Text == "deploy" ? "named by this deploy point" : "named by this wait point", + Network: source.Path, Node: index)); + } + } + } + } + + private static bool On(IReadOnlyList c, int index) => index < c.Count && c[index].Kind is ZrdKind.Int or ZrdKind.Float && c[index].Bits != 0; + private static string Word(IReadOnlyList c, int index) => index < c.Count && c[index].Kind is ZrdKind.Int or ZrdKind.Float ? c[index].Value : "?"; + /// A vehicle trigger's conditions in the order the game tests them: the first that holds sets the valve. + public static string TriggerText(IReadOnlyList c) + { + List conditions = []; + if (On(c, 3)) conditions.Add("hit"); + if (On(c, 6)) conditions.Add($"heat at least {Word(c, 7)}"); + if (On(c, 4)) conditions.Add($"health at most {Word(c, 5)}"); + if (On(c, 1)) conditions.Add($"ammo at most {Word(c, 2)}"); + if (On(c, 12)) conditions.Add($"enemy within {Word(c, 13)}"); + if (On(c, 10)) conditions.Add($"enemy in sight within {Word(c, 11)}"); + bool inside = On(c, 8), outside = c.Count >= 17 && On(c, 16); + if (c.Count > 9 && c[9].Kind == ZrdKind.String && (inside || outside)) + conditions.Add(inside && outside ? $"anywhere ({MissionAiValves.Short(c[9].Text, 64)})" : $"{(inside ? "inside" : "outside")} {MissionAiValves.Short(c[9].Text, 64)}"); + return conditions.Count == 0 ? "no condition switched on" : string.Join(" or ", conditions); + } + + public static string ConditionText(string? condition) => condition switch + { + "any_nonzero" => "on while any input is on", "any_zero" => "on while any input is off", + "all_nonzero" => "on while all inputs are on", "all_zero" => "on while all inputs are off", _ => "switch", + }; + private static string Number(float value) => value.ToString("R", CultureInfo.InvariantCulture); + private static string Seconds(string? operand) => operand is { Length: > 0 } ? operand + " s" : "later"; + + /// A reaction's arguments as its editable fields. + public static Mw3ValveReactionSpec Spec(string kind, ZrdNode arguments) + { + var c = arguments.Children; + string? Name(int i) => i < c.Count && c[i].Kind == ZrdKind.String ? c[i].Text : null; + string? Raw(int i) => i < c.Count && c[i].Kind is ZrdKind.Int or ZrdKind.Float ? unchecked((int)c[i].Bits).ToString(CultureInfo.InvariantCulture) : null; + string? Decimal(IReadOnlyList list, int i) => i < list.Count && list[i].Kind is ZrdKind.Int or ZrdKind.Float ? list[i].Value : null; + return kind switch + { + "sound" or "sound_once" or "animation" or "animation_once" or "destroy" => new(kind, Name(0), When: Raw(1)), + "scan_aim" or "scan_hit" or "scan_time" or "canleave" or "shutdown" or "setteam" or "attack_strategy" => new(kind, Name(0), Raw(1), Raw(2)), + "teleport" => c.ElementAtOrDefault(1) is { Kind: ZrdKind.Array } xyz + ? new(kind, Name(0), When: Raw(3), X: Decimal(xyz.Children, 0), Y: Decimal(xyz.Children, 1), Z: Decimal(xyz.Children, 2), Yaw: Decimal(c, 2)) : new(kind, Name(0), When: Raw(3)), + "missionreset" or "missionabort" or "missioncomplete" => new(kind, When: Raw(0)), + "update" => new(kind, Name(0)), + // delayupdate keeps the raw word as its float seconds. + "delayupdate" => new(kind, Name(0), c.Count > 1 && c[1].Kind is ZrdKind.Int or ZrdKind.Float ? Number(Mw3ValveRuntime.Number(arguments, 1)) : null), + _ => new(kind), + }; + } + + /// A reaction's fields in stored order (a teleport's position flattened), by the layout its kind stores. + private static (int Layout, string?[] Fields) Flat(Mw3ValveReactionSpec spec) => spec.Kind switch + { + "sound" or "sound_once" or "animation" or "animation_once" or "destroy" => (1, [spec.Target, spec.When]), + "scan_aim" or "scan_hit" or "scan_time" or "canleave" or "shutdown" or "setteam" or "attack_strategy" => (2, [spec.Target, spec.Operand, spec.When]), + "teleport" => (3, [spec.Target, spec.X, spec.Y, spec.Z, spec.Yaw, spec.When]), + "missionreset" or "missionabort" or "missioncomplete" => (4, [spec.When]), + "update" => (5, [spec.Target]), + "delayupdate" => (6, [spec.Target, spec.Operand]), + _ => (0, []), + }; + private static ZrdNode[]? FlatNodes(int layout, ZrdNode arguments) + { + var c = arguments.Children; + if (layout == 3) return c.Count == 4 && c[1] is { Kind: ZrdKind.Array, Children.Count: 3 } xyz ? [c[0], xyz.Children[0], xyz.Children[1], xyz.Children[2], c[2], c[3]] : null; + return [.. c]; + } + /// + /// The arguments for an edited reaction: every field that still reads as it was stored keeps its original node, so an + /// untouched number keeps its kind, its text and its place (a teleport's whole-number coordinates stay whole numbers). + /// + public static ZrdNode Arguments(Mw3ValveReactionSpec spec, string storedKind, ZrdNode stored) + { + var fresh = Arguments(spec); + var (layout, fields) = Flat(spec); var (storedLayout, storedFields) = Flat(Spec(storedKind, stored)); + if (layout == 0 || layout != storedLayout || FlatNodes(layout, stored) is not { } old || FlatNodes(layout, fresh) is not { } created || old.Length != fields.Length || created.Length != fields.Length) + { + // Another kind's fields: the stored list stays the list and each value takes the place of the one stored there + // (its token changes in place; one that reads the same is kept), so the comments and layout around them stay. + return stored with { Children = [.. fresh.Children.Select((node, i) => i >= stored.Children.Count || node.Kind == ZrdKind.Array || stored.Children[i].Kind == ZrdKind.Array ? node + : node.Kind == stored.Children[i].Kind && node.Text == stored.Children[i].Text && node.Bits == stored.Children[i].Bits ? stored.Children[i] : node with { Id = stored.Children[i].Id })] }; + } + // A changed field replaces its token in place: it keeps the stored node's identity, also when a whole number becomes + // a fraction, so the comments and layout around it stay. + ZrdNode[] nodes = [.. created.Select((node, i) => fields[i] == storedFields[i] ? old[i] : node.Kind != ZrdKind.Array && old[i].Kind != ZrdKind.Array ? node with { Id = old[i].Id } : node)]; + if (layout != 3) return stored with { Children = nodes }; + var position = stored.Children[1]; + return stored with { Children = [nodes[0], nodes[1..4].SequenceEqual(position.Children) ? position : position with { Children = nodes[1..4] }, nodes[4], nodes[5]] }; + } + + /// The arguments a reaction stores, from its fields; a field the kind needs and cannot read is refused. + public static ZrdNode Arguments(Mw3ValveReactionSpec spec) + { + ZrdNode Name(string? text, string what) + { + if (string.IsNullOrWhiteSpace(text) || text.Length > 256) throw new InvalidDataException($"Enter {what} (at most 256 characters)."); + return ZrdNode.Create(ZrdKind.String, JsonSerializer.Serialize(text)); + } + ZrdNode Whole(string? text, string what) => int.TryParse(text?.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int number) + ? ZrdNode.Create(ZrdKind.Int, number.ToString(CultureInfo.InvariantCulture)) : throw new InvalidDataException($"Enter {what} as a whole number."); + ZrdNode Real(string? text, string what, bool positive = false) => float.TryParse(text?.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out float number) && float.IsFinite(number) && (!positive || number >= 0) + ? ZrdNode.Create(ZrdKind.Float, number.ToString("R", CultureInfo.InvariantCulture)) : throw new InvalidDataException($"Enter {what} as a {(positive ? "number of 0 or more" : "number")}."); + ZrdNode[] children = spec.Kind switch + { + "sound" or "sound_once" => [Name(spec.Target, "the sound's name"), Whole(spec.When, "the triggering value")], + "animation" or "animation_once" => [Name(spec.Target, "the animation's name"), Whole(spec.When, "the triggering value")], + "destroy" => [Name(spec.Target, "the vehicle or object to destroy"), Whole(spec.When, "the triggering value")], + "scan_aim" or "scan_hit" or "scan_time" or "canleave" or "shutdown" => [Name(spec.Target, "the vehicle's name"), Whole(spec.Operand, "on (1) or off (0)"), Whole(spec.When, "the triggering value")], + "setteam" => [Name(spec.Target, "the vehicle's name"), Whole(spec.Operand, "the team"), Whole(spec.When, "the triggering value")], + "attack_strategy" => [Name(spec.Target, "the vehicle's name"), Whole(spec.Operand, "the attack strategy"), Whole(spec.When, "the triggering value")], + "teleport" => [Name(spec.Target, "the vehicle's name"), ZrdNode.Create(ZrdKind.Array) with { Children = [Real(spec.X, "X"), Real(spec.Y, "Y"), Real(spec.Z, "Z")] }, + Real(spec.Yaw, "the heading"), Whole(spec.When, "the triggering value")], + "missionreset" or "missionabort" or "missioncomplete" => [Whole(spec.When, "the triggering value")], + "update" => [Name(spec.Target, "the valve to fire")], + "delayupdate" => [Name(spec.Target, "the valve to set"), Real(spec.Operand, "the delay in seconds", positive: true)], + _ => throw new InvalidDataException("Choose a reaction the game knows."), + }; + return ZrdNode.Create(ZrdKind.Array) with { Children = children }; + } + + /// What a reaction does, in words ("wakes owens_01", "plays com_mech once"). + public static string ReactionText(Mw3ValveReactionSpec spec) + { + string target = spec.Target is { Length: > 0 } name ? MissionAiValves.Short(name, 64) : "?"; + bool on = spec.Operand is not (null or "0"); + return spec.Kind switch + { + "sound" => $"plays {target}", "sound_once" => $"plays {target} once", + "animation" => $"starts animation {target}", "animation_once" => $"starts animation {target} once", + "shutdown" => on ? $"powers down {target}" : $"wakes {target}", + "destroy" => $"destroys {target}", "teleport" => $"teleports {target}", + "setteam" => $"moves {target} to team {spec.Operand ?? "?"}", "attack_strategy" => $"sets {target}'s attack strategy to {spec.Operand ?? "?"}", + "scan_aim" => $"turns {target}'s aim scan {(on ? "on" : "off")}", "scan_hit" => $"turns {target}'s hit scan {(on ? "on" : "off")}", + "scan_time" => $"turns {target}'s timed scan {(on ? "on" : "off")}", "canleave" => on ? $"lets {target} leave its network" : $"keeps {target} on its network", + "update" => $"fires {target}", "delayupdate" => $"sets {target} after {Seconds(spec.Operand)}", + "missionabort" => "aborts the mission", "missionreset" => "mission reset (no effect in the game)", "missioncomplete" => "mission complete (no effect in the game)", + _ => spec.Kind, + }; + } + + private static string? Missing(Mw3ValveReactionSpec spec, Mw3ValveCatalog? catalog) + { + if (catalog == null || spec.Target is not { Length: > 0 } target) return null; + string name = MissionAiValves.Short(target, 64); + return spec.Kind switch + { + "sound" or "sound_once" when catalog.Sounds is { } sounds && !sounds.Contains(target) => $"No sound is named {name}: the reaction does nothing.", + "animation" or "animation_once" when catalog.Animations is { } animations && !animations.Contains(target) => $"No animation is named {name}: the reaction does nothing.", + "shutdown" or "destroy" or "teleport" or "setteam" or "attack_strategy" or "scan_aim" or "scan_hit" or "scan_time" or "canleave" + when catalog.Vehicles is { } vehicles && !vehicles.Contains(target) && target != "player" => $"This mission has no vehicle or target named {name}: the reaction does nothing.", + _ => null, + }; + } + + private static string Summary(Builder valve) + { + if (valve.Reactions.Count > 0) + { + // Timers and sounds are counted; the reactions that change the mission are named. + int timers = valve.Reactions.Count(r => r.Spec.Kind == "delayupdate"), sounds = valve.Reactions.Count(r => r.Spec.Kind is "sound" or "sound_once"); + var named = valve.Reactions.Where(r => r.Spec.Kind is not ("delayupdate" or "sound" or "sound_once")).Select(r => r.Text).ToList(); + if (named.Count == 0 && sounds == 1) { named.Add(valve.Reactions.First(r => r.Spec.Kind is "sound" or "sound_once").Text); sounds = 0; } + if (named.Count == 0 && timers == 1) { named.Add(valve.Reactions.First(r => r.Spec.Kind == "delayupdate").Text); timers = 0; } + List parts = [.. named.Take(2)]; + if (named.Count > 2) parts.Add($"{named.Count - 2} more"); + if (timers > 0) parts.Add(timers == 1 ? "1 timer" : $"{timers} timers"); + if (sounds > 0) parts.Add(sounds == 1 ? "1 sound" : $"{sounds} sounds"); + return string.Join(" · ", parts); + } + if (valve.Condition != null) return valve.Inputs.Length == 1 ? ConditionText(valve.Condition).Replace("any input", "its input").Replace("all inputs are", "its input is") + : ConditionText(valve.Condition).Replace("any input", $"any of {valve.Inputs.Length}").Replace("all inputs", $"all {valve.Inputs.Length}"); + int gates = valve.UsedBy.Count(l => l.Role is "gate" or "union"); + if (gates > 0) return gates == 1 ? $"gates {valve.UsedBy.First(l => l.Role is "gate" or "union").Owner}" : $"gates {gates} route links"; + if (valve.UsedBy.FirstOrDefault(l => l.Role == "objective") is { } objective) return objective.Owner; + if (valve.UsedBy.FirstOrDefault(l => l.Role == "computed") is { } computed) return $"input of {MissionAiValves.Short(computed.Owner, 64)}"; + if (valve.SetBy.Count > 0) return $"set by {MissionAiValves.Short(valve.SetBy[0].Owner, 64)}" + (valve.SetBy.Count > 1 ? $" and {valve.SetBy.Count - 1} more" : ""); + return ""; + } +} diff --git a/src/zStudio.Core/Mw3ValveProgram.cs b/src/zStudio.Core/Mw3ValveProgram.cs new file mode 100644 index 00000000..519024fb --- /dev/null +++ b/src/zStudio.Core/Mw3ValveProgram.cs @@ -0,0 +1,159 @@ +using zStudio.Core.Formats; + +namespace zStudio.Core; + +public sealed record Mw3ValveAction(string Kind, ZrdNode Arguments); +public sealed record Mw3ValveDefinition(Guid Record, string Name, int? Initial, string? Condition, + IReadOnlyList Inputs, IReadOnlyList Actions); + +/// The native reader's semantic projection. Source trees remain authoritative and unmodified. +public sealed record Mw3ValveProgram(IReadOnlyList Definitions) +{ + public void ValidateForEditing() + { + foreach (var definition in Definitions) + if (Problem(definition) is { } problem) throw new InvalidDataException(problem); + _ = new Mw3ValveRuntime(this).Values(); + Dictionary> edges = new(StringComparer.Ordinal); + HashSet compound = new(StringComparer.Ordinal); + foreach (var definition in Definitions) + { + if (definition.Condition != null && definition.Inputs.Count > 0) + { + if (!compound.Add(definition.Name)) throw new InvalidDataException("A valve cannot have two compound definitions."); + foreach (string input in definition.Inputs) Edge(input, definition.Name); + } + foreach (var action in definition.Actions) + if (action.Kind == "update" && Mw3ValveRuntime.Text(action.Arguments, 0) is { } target) Edge(definition.Name, target); + } + Dictionary state = new(StringComparer.Ordinal); + foreach (string name in edges.Keys) Visit(name, 0); + void Edge(string from, string to) + { + if (!edges.TryGetValue(from, out var list)) edges.Add(from, list = []); + list.Add(to); + } + void Visit(string name, int depth) + { + if (state.TryGetValue(name, out byte s)) + { if (s == 1) throw new InvalidDataException("The edit creates an immediate valve reaction cycle."); return; } + if (depth >= 128) throw new InvalidDataException("Valve reaction nesting exceeds preview limits."); + state[name] = 1; + if (edges.TryGetValue(name, out var list)) foreach (string target in list) Visit(target, depth + 1); + state[name] = 2; + } + } + public static string? Problem(Mw3ValveDefinition definition) + { + if (definition.Condition != null && definition.Inputs.Count == 0) return "A compound valve requires a nonempty namelist."; + foreach (var action in definition.Actions) + { + var c = action.Arguments.Children; + bool Word(int i) => i < c.Count && c[i].Kind is ZrdKind.Int or ZrdKind.Float; + bool Name(int i) => i < c.Count && c[i].Kind == ZrdKind.String; + bool Number(int i) => Word(i) && float.IsFinite(Mw3ValveRuntime.Number(action.Arguments, i)); + bool valid = action.Kind switch + { + "sound" or "sound_once" or "animation" or "animation_once" or "destroy" => c.Count == 2 && Name(0) && Word(1), + "scan_aim" or "scan_hit" or "scan_time" or "canleave" or "shutdown" or "setteam" or "attack_strategy" => c.Count == 3 && Name(0) && Word(1) && Word(2), + "delayupdate" => c.Count == 2 && Name(0) && Number(1), + "update" => c.Count == 1 && Name(0), + "missionreset" or "missionabort" or "missioncomplete" => c.Count == 1 && Word(0), + "teleport" => c.Count == 4 && Name(0) && c[1].Kind == ZrdKind.Array && c[1].Children.Count == 3 && + c[1].Children.All(n => n.Kind == ZrdKind.Int || n.Kind == ZrdKind.Float && float.IsFinite(BitConverter.UInt32BitsToSingle(n.Bits))) && + Word(2) && float.IsFinite(Mw3ValveRuntime.Scalar(action.Arguments, 2)) && Word(3), + _ => true + }; + if (!valid) return $"Invalid {action.Kind} parameters in valve {MissionAiValves.Short(definition.Name)}."; + } + return null; + } + public const int MaximumValves = 16_384, MaximumReactions = 131_072; + public static readonly string[] Conditions = ["any_nonzero", "any_zero", "all_nonzero", "all_zero"]; + public static readonly string[] ActionOrder = ["sound", "animation", "scan_aim", "scan_hit", "scan_time", "canleave", + "shutdown", "destroy", "setteam", "attack_strategy", "teleport", "missionreset", "missionabort", "missioncomplete", "update", "delayupdate"]; + + public static string? SourceProblem(ZrdNode value) + { + if (value.Kind != ZrdKind.Array) return "Expected ordered valve properties."; + foreach (string tag in ActionOrder.Concat(["sound_once", "animation_once"])) + if (HasTag(value, tag) && (Find(value, tag) is not { Kind: ZrdKind.Array } args || + Problem(new(Guid.Empty, "source", null, null, [], [new(tag, args)])) is { })) + return $"Invalid {tag} parameters."; + if (HasTag(value, "value") && Find(value, "value") == null) return "Expected one initial value word."; + if (Find(value, "value") is { } initial && (initial.Kind != ZrdKind.Array || initial.Children.Count != 1 || + initial.Children[0].Kind is not (ZrdKind.Int or ZrdKind.Float))) return "Expected one initial value word."; + if (Conditions.Any(k => HasTag(value, k)) && (Find(value, "namelist") is not { Kind: ZrdKind.Array } names || + names.Children.Count == 0 || names.Children.Any(n => n.Kind != ZrdKind.String))) return "Expected a nonempty namelist of valve names."; + return null; + } + + /// + /// The definitions the game builds: a second computed definition of a valve is dropped with its whole record + /// (its value and reactions too), as does. + /// + public Mw3ValveProgram Effective() + { + HashSet computed = new(StringComparer.Ordinal); + return new([.. Definitions.Where(d => !(d.Condition != null && d.Inputs.Count > 0) || computed.Add(d.Name))]); + } + + /// Leave out records the game does not read as written instead of refusing the file (what an edit of another record is checked against). + public static Mw3ValveProgram Read(ZrdNode root, CancellationToken token = default, bool skipUnreadable = false) + { + var body = MissionAiValves.Fields(root); + List definitions = []; + if (body.Kind != ZrdKind.Array) throw new InvalidDataException("Valve definitions need an ordered array."); + int reactions = 0; + for (int i = 0; i + 1 < body.Children.Count; i += 2) + { + token.ThrowIfCancellationRequested(); + var key = body.Children[i]; var value = body.Children[i + 1]; + if (key.Kind != ZrdKind.String) continue; + if (SourceProblem(value) is { } problem) + { + if (skipUnreadable) continue; + throw new InvalidDataException($"Valve {MissionAiValves.Short(key.Text)}: {problem}"); + } + if (definitions.Count == MaximumReactions) throw new InvalidDataException("Too many valve definition occurrences for preview."); + string? condition = Conditions.FirstOrDefault(k => HasTag(value, k)); + var names = Find(value, "namelist"); + if (names?.Children.Count > MaximumValves) throw new InvalidDataException("Too many compound valve inputs."); + string[] inputs = names?.Kind == ZrdKind.Array + ? names.Children.Where(n => n.Kind == ZrdKind.String).Select(n => n.Text).ToArray() : []; + if (inputs.Length > MaximumValves) throw new InvalidDataException("Too many compound valve inputs."); + List actions = []; + foreach (string kind in ActionOrder) + { + var args = Find(value, kind); + string selected = kind; + if (kind is "sound" or "animation" && Find(value, kind + "_once") is { } once) { args = once; selected += "_once"; } + if (args == null || args.Kind != ZrdKind.Array) continue; + if (++reactions > MaximumReactions) throw new InvalidDataException("Too many valve reactions for preview."); + actions.Add(new(selected, args)); + } + var initial = Find(value, "value"); + definitions.Add(new(key.Id, key.Text, initial?.Children.FirstOrDefault() is { Kind: ZrdKind.Int or ZrdKind.Float } n ? unchecked((int)n.Bits) : null, + condition, inputs, actions)); + } + return new(definitions); + } + + // zReader's native tag search descends through ordered lists; it is not a dictionary. + public static bool HasTag(ZrdNode node, string key) => node.Kind == ZrdKind.Array && + node.Children.Any(c => c.Kind == ZrdKind.String && c.Text == key || c.Kind == ZrdKind.Array && HasTag(c, key)); + public static ZrdNode? Find(ZrdNode node, string key) => TryFind(node, key, out var value) ? value : null; + private static bool TryFind(ZrdNode node, string key, out ZrdNode? value) + { + value = null; + if (node.Kind != ZrdKind.Array) return false; + var c = node.Children; + for (int i = 0; i < c.Count; i++) + { + if (c[i].Kind == ZrdKind.String && c[i].Text == key) + { value = i + 1 < c.Count ? c[i + 1] : null; return true; } + if (c[i].Kind == ZrdKind.Array && TryFind(c[i], key, out value)) return true; + } + return false; + } +} diff --git a/src/zStudio.Core/Mw3ValveRoutes.cs b/src/zStudio.Core/Mw3ValveRoutes.cs new file mode 100644 index 00000000..024c6300 --- /dev/null +++ b/src/zStudio.Core/Mw3ValveRoutes.cs @@ -0,0 +1,48 @@ +using zStudio.Core.Formats; + +namespace zStudio.Core; + +public sealed record Mw3ValveRoute(bool Passable, IReadOnlyList Reasons, IReadOnlyList<(string Valve, int Value)> Assignments); + +public static class Mw3ValveRoutes +{ + /// One physical outgoing slot, never a deduplicated pair of node names. + public static Mw3ValveRoute Evaluate(AiNetwork network, AiNode node, int slot, Mw3ValveRuntime runtime) + { + if (!network.IsMw3 || node.Source is not { } source) return new(true, [], []); + var links = source.Children[2].Children; + if (slot < 0 || slot >= links.Count || unchecked((int)links[slot].Bits) < 0) throw new ArgumentException("Choose an outgoing link slot."); + int last = links.Count - 1; + while (last >= 0 && unchecked((int)links[last].Bits) < 0) last--; + int target = unchecked((int)links[slot].Bits); + List reasons = []; List<(string, int)> assignments = []; + Inspect(source, slot == last ? 1 : 0); + if (network.ValveEdgesByNode.TryGetValue(node.Index, out var edges)) foreach (var edge in edges) + { + var ends = edge.Children[0].Children; + if (unchecked((int)ends[0].Bits) != node.Index) continue; + for (int j = 1; j < ends.Count; j++) + if (unchecked((int)ends[j].Bits) == target) Inspect(edge, j == ends.Count - 1 ? 1 : 0); + } + return new(reasons.Count == 0, reasons.AsReadOnly(), assignments.AsReadOnly()); + void Inspect(ZrdNode record, int expectedDefault) + { + var condition = Mw3ValveProgram.Find(record, "valve"); + if (condition is { Children.Count: >= 2 } && Mw3ValveRuntime.Integer(condition, 0) != 0 && Mw3ValveRuntime.Text(condition, 1) is { } name) + { + int expected = condition.Children.Count > 2 ? Mw3ValveRuntime.Integer(condition, 2) : expectedDefault; + if (runtime.Value(name) != expected && reasons.Count < 64) reasons.Add($"{MissionAiValves.Short(name)} must equal {expected}."); + } + var union = Mw3ValveProgram.Find(record, "valveunion"); + if (union != null && !union.Children.Any(term => Mw3ValveRuntime.Integer(term, 0) != 0 + && Mw3ValveRuntime.Text(term, 1) is { } n && runtime.Value(n) == (term.Children.Count > 2 ? Mw3ValveRuntime.Integer(term, 2) : 1)) + && reasons.Count < 64) reasons.Add("No enabled valve-union term matches."); + var assignment = Mw3ValveProgram.Find(record, "valve_assign"); + if (assignment != null && Mw3ValveRuntime.Text(assignment, 0) is { } a) + { + if (assignments.Count == 1024) throw new InvalidDataException("Too many route assignments for preview."); + assignments.Add((a, Mw3ValveRuntime.Integer(assignment, 1))); + } + } + } +} diff --git a/src/zStudio.Core/Mw3ValveRuntime.cs b/src/zStudio.Core/Mw3ValveRuntime.cs new file mode 100644 index 00000000..45b8405e --- /dev/null +++ b/src/zStudio.Core/Mw3ValveRuntime.cs @@ -0,0 +1,216 @@ +using zStudio.Core.Formats; + +namespace zStudio.Core; + +public sealed record Mw3ValveTrace(long Sequence, float Time, string Valve, string Kind, int Value, string Detail, Guid? Record = null); +public sealed record Mw3ValveEffect(string Valve, string Kind, ZrdNode Arguments, Guid Record, float Time); +public sealed record Mw3ValveValue(string Name, int Value, string? Condition); +public sealed record Mw3ValveTimer(string Target, int Value, float Due); + +/// Owned, bounded mission state. It never writes source trees or the accepted mission scene. +public sealed class Mw3ValveRuntime +{ + private sealed class Holder(string name) + { + public readonly string Name = name; + public int Value; + public string? Condition; + public string[] Inputs = []; + public readonly List Reactions = []; + } + private sealed class Reaction(Guid record, string kind, ZrdNode args, string? target = null) + { + public readonly Guid Record = record; + public readonly string Kind = kind; + public readonly ZrdNode Args = args; + public readonly string? Target = target; + public bool Consumed; + } + private readonly Dictionary holders = new(StringComparer.Ordinal); + private readonly List timers = []; + private bool compositeTimers; + private readonly Queue trace = new(); + private readonly List effects = []; + private readonly HashSet reading = new(StringComparer.Ordinal); + private int work, reactionCount, callDepth, fireDepth; + private long sequence; + private readonly Func? available; + private readonly Action? immediate; + public const int MaximumTimers = 32_768, MaximumTrace = 4096, MaximumWork = 100_000; + public float Time { get; private set; } + public bool Halted { get; private set; } + public IReadOnlyList Timers => timers.AsReadOnly(); + public IReadOnlyList Trace => trace.ToArray(); + + public Mw3ValveRuntime(Mw3ValveProgram program, Func? available = null, Action? immediate = null) + { + this.available = available; + this.immediate = immediate; + work = MaximumWork; + foreach (var d in program.Definitions) + { + var holder = Get(d.Name); + if (d.Condition != null && d.Inputs.Count > 0) + { + if (holder.Condition != null) { Log(d.Name, "ignored", 0, "Conflicting compound definition; record ignored.", d.Record); continue; } + holder.Condition = d.Condition; holder.Inputs = [.. d.Inputs]; + foreach (string input in holder.Inputs) Add(Get(input), new(d.Record, "update", Empty, holder.Name)); + } + if (d.Initial is { } initial && holder.Condition == null) holder.Value = initial; + foreach (var action in d.Actions) + { + string? target = action.Kind is "update" or "delayupdate" ? Text(action.Arguments, 0) : null; + if (target != null) _ = Get(target); + Add(holder, new(d.Record, action.Kind, action.Arguments, target)); + } + } + foreach (var holder in holders.Values) _ = Read(holder); + } + private static readonly ZrdNode Empty = ZrdNode.Create(ZrdKind.Array); + private void Add(Holder holder, Reaction reaction) + { + if (++reactionCount > Mw3ValveProgram.MaximumReactions) throw new InvalidDataException("Valve preview reaction limit exceeded."); + holder.Reactions.Add(reaction); + } + private Holder Get(string name) + { + if (name.Length > 4096) throw new InvalidDataException("Valve name exceeds the preview's 4,096-character limit."); + if (holders.TryGetValue(name, out var holder)) return holder; + if (holders.Count == Mw3ValveProgram.MaximumValves) throw new InvalidDataException("Valve preview name limit exceeded."); + holder = new(name); holders.Add(name, holder); return holder; + } + public int Value(string name) => Run(() => Read(Get(name))); + public void Register(IEnumerable names) => Run(() => + { + int count = 0; + foreach (string name in names) + { + if (++count > Mw3ValveProgram.MaximumReactions) throw new InvalidDataException("Too many valve references for preview."); + _ = Get(name); + } + return 0; + }); + public IReadOnlyList Values() => Run(() => (IReadOnlyList)holders.Values.Select(h => new Mw3ValveValue(h.Name, Read(h), h.Condition)).ToArray()); + public void Set(string name, int value) => Run(() => { SetCore(Get(name), value); return 0; }); + public void Update(string name) => Run(() => { Fire(Get(name)); return 0; }); + internal void SetClock(float now) => Run(() => + { + if (!float.IsFinite(now) || now < Time) throw new ArgumentException("Advance valve time monotonically to a finite value."); + Time = now; return 0; + }); + public void Tick(float now) => Run(() => + { + if (!float.IsFinite(now) || now < Time) throw new ArgumentException("Advance valve time monotonically to a finite value."); + Time = now; + bool lone = timers.Count == 1 && !compositeTimers; + int visited = 0; + while (visited < timers.Count) + { + Spend(); + var timer = timers[visited]; + if (!(timer.Due < now)) { visited++; continue; } + timers.RemoveAt(visited); + SetCore(Get(timer.Target), timer.Value); + if (lone) + { + if (timers.Count > 0) Log(timer.Target, "timer quirk", timer.Value, "Retail lone-timer completion drops timers created by its reactions."); + timers.Clear(); compositeTimers = false; break; + } + } + if (timers.Count == 0) compositeTimers = false; + return 0; + }); + public IReadOnlyList DrainEffects() + { + var result = effects.ToArray(); effects.Clear(); return result; + } + private T Run(Func action) + { + if (Halted) throw new InvalidOperationException("Valve simulation halted; reset it before continuing."); + if (callDepth++ == 0) work = MaximumWork; + try { return action(); } + catch (InvalidDataException) + { + Halted = true; effects.Clear(); throw; + } + finally { --callDepth; } + } + private void Spend() + { + if (--work < 0) throw new InvalidDataException("Valve simulation work limit reached; check immediate reaction cycles."); + } + private int Read(Holder holder) + { + Spend(); + if (holder.Condition == null) return holder.Value; + if (reading.Count >= 128) throw new InvalidDataException("Compound valve depth limit exceeded."); + if (!reading.Add(holder.Name)) throw new InvalidDataException("Cyclic compound valve condition."); + try + { + bool zero = false, nonzero = false; + foreach (string input in holder.Inputs) { int value = Read(Get(input)); zero |= value == 0; nonzero |= value != 0; } + return holder.Condition switch { "any_nonzero" => nonzero ? 1 : 0, "any_zero" => zero ? 1 : 0, "all_nonzero" => zero ? 0 : 1, _ => nonzero ? 0 : 1 }; + } + finally { reading.Remove(holder.Name); } + } + private void SetCore(Holder holder, int value) + { + Spend(); int old = Read(holder); + if (old == value) return; + if (holder.Condition == null) holder.Value = value; + Log(holder.Name, "set", value, holder.Condition == null ? $"Previous value {old}." : "Computed holder ignores assignment; reactions still fire."); + Fire(holder); + } + private void Fire(Holder holder) + { + Spend(); + if (fireDepth >= 128) throw new InvalidDataException("Valve reaction depth limit exceeded; check immediate cycles."); + fireDepth++; + try + { + foreach (var reaction in holder.Reactions) + { + Spend(); + int value = Read(holder); + if (reaction.Kind == "update") { if (reaction.Target != null) Fire(Get(reaction.Target)); continue; } + if (reaction.Kind == "delayupdate") + { + if (reaction.Target == null) continue; + float due = Time + Number(reaction.Args, 1); + if (!float.IsFinite(due)) throw new InvalidDataException("Valve timer is not finite."); + if (timers.Count == MaximumTimers) throw new InvalidDataException("Valve timer limit reached."); + if (timers.Count > 0) compositeTimers = true; + timers.Add(new(reaction.Target, value, due)); + Log(holder.Name, "timer", value, FormattableString.Invariant($"sets {MissionAiValves.Short(reaction.Target)} to {value} at {due:0.###} s"), reaction.Record); continue; + } + int triggerIndex = reaction.Kind switch + { + "sound" or "sound_once" or "animation" or "animation_once" or "destroy" => 1, + "teleport" => 3, "missionreset" or "missionabort" or "missioncomplete" => 0, _ => 2 + }; + if (Integer(reaction.Args, triggerIndex) != value || reaction.Consumed) continue; + if (available?.Invoke(reaction.Kind, reaction.Args) == false) + { Log(holder.Name, "unavailable", value, reaction.Kind + ": target or resource was not found.", reaction.Record); continue; } + if (reaction.Kind.EndsWith("_once", StringComparison.Ordinal)) reaction.Consumed = true; + if (effects.Count == MaximumWork) throw new InvalidDataException("Valve effect limit reached."); + var effect = new Mw3ValveEffect(holder.Name, reaction.Kind, reaction.Args, reaction.Record, Time); + effects.Add(effect); + Log(holder.Name, reaction.Kind, value, reaction.Kind is "missionreset" or "missioncomplete" ? "No retail gameplay effect." : Text(reaction.Args, 0) ?? "", reaction.Record); + immediate?.Invoke(effect); + } + } + finally { fireDepth--; } + } + private void Log(string name, string kind, int value, string detail, Guid? record = null) + { + if (trace.Count == MaximumTrace) trace.Dequeue(); + trace.Enqueue(new(++sequence, Time, MissionAiValves.Short(name), kind, value, MissionAiValves.Short(detail, 512), record)); + } + public static string? Text(ZrdNode args, int index) => args.Children.ElementAtOrDefault(index) is { Kind: ZrdKind.String } n ? n.Text : null; + public static int Integer(ZrdNode args, int index) => args.Children.ElementAtOrDefault(index) is { Kind: ZrdKind.Int or ZrdKind.Float } n ? unchecked((int)n.Bits) : 0; + public static float Number(ZrdNode args, int index) => args.Children.ElementAtOrDefault(index) is { } n + ? n.Kind is ZrdKind.Float or ZrdKind.Int ? BitConverter.UInt32BitsToSingle(n.Bits) : 0 : 0; + // zReader get_vec3/get_float_value convert integer operands; delayupdate stores the raw word instead. + public static float Scalar(ZrdNode args, int index) => args.Children.ElementAtOrDefault(index) is { Kind: ZrdKind.Int } n + ? unchecked((int)n.Bits) : Number(args, index); +} diff --git a/src/zStudio.Core/Mw3ValveSimulation.cs b/src/zStudio.Core/Mw3ValveSimulation.cs new file mode 100644 index 00000000..d02b342c --- /dev/null +++ b/src/zStudio.Core/Mw3ValveSimulation.cs @@ -0,0 +1,266 @@ +using System.Numerics; +using zStudio.Core.Animation; +using zStudio.Core.Formats; + +namespace zStudio.Core; + +public sealed record Mw3ValveActorState(string Name, bool? PoweredDown = null, bool Destroyed = false, + int? Team = null, int? Strategy = null, Vector3? Position = null, float? Yaw = null) +{ + public IReadOnlyDictionary Switches { get; init; } = new Dictionary(); +} + +/// An animation that sets a valve through callbacks 42–49: the node-name valve its entry binds and the values its events set. +public sealed record Mw3ValveCallback(string Valve, int Entry, string Animation, IReadOnlyList Values); + +/// A single preview clock joins native reactions, animation callbacks and owned actor overrides. +public sealed class Mw3ValveSimulation +{ + public Guid Id { get; } = Guid.NewGuid(); + public Mw3ValveRuntime Runtime { get; } + public AnimationPreviewContext Context { get; } + private readonly AnimationPlayer player; + private readonly Dictionary<(int Entry, int Root), string?> bindings = []; + private readonly Dictionary actors = new(StringComparer.Ordinal); + private readonly Dictionary targets = new(StringComparer.Ordinal); + private readonly List sounds = []; + private bool animationFrontierPending; + private CancellationToken operationToken; + private long soundId; + public IReadOnlyDictionary Actors => actors; + public double Time => player.Time; + public bool Aborted { get; private set; } + public bool Faulted { get; private set; } + public AnimationFrame CurrentFrame { get; private set; } + + public Mw3ValveSimulation(AnimationPreviewContext context, Mw3ValveProgram program, CancellationToken token = default, int lod = 0) + { + token.ThrowIfCancellationRequested(); + operationToken = token; + Context = context; Runtime = new(program, Available, ApplyImmediateEffect); + player = new(context, 0, 1, false, token) { LodLevel = Math.Max(0, lod) }; + player.NativeValveCallback = Callback; + player.NativeValveStarted = Bind; + foreach (var actor in context.Mission?.Actors ?? []) actors.TryAdd(actor.Name, new(actor.Name)); + foreach (var resource in context.Mission?.AiNetworks.ValveSources ?? []) + { + token.ThrowIfCancellationRequested(); + Runtime.Register(MissionAiValves.Records(resource.Member, resource.Root, token).SelectMany(r => MissionAiValves.References(r, token)).Select(r => r.Name)); + if (!resource.Member.Equals("targets.zrd", StringComparison.OrdinalIgnoreCase)) continue; + var fields = MissionAiValves.Fields(resource.Root).Children; + for (int i = 0; i + 1 < fields.Count; i += 2) + { + if (fields[i].Kind != ZrdKind.String || fields[i + 1].Kind != ZrdKind.Array) continue; + string name = fields[i].Text; + if (!context.Scene.Nodes.Any(n => n.Name == name)) continue; + targets.TryAdd(name, fields[i + 1]); actors.TryAdd(name, new(name)); + } + } + player.StartValveLoadAnimations(token); + foreach (string name in context.Mission?.StartupAnimations ?? []) + if (context.Package.Entries.FirstOrDefault(e => e.Index > 0 && e.Name == name) is { } entry) player.StartValveMissionStartup(entry.Index, token); + CurrentFrame = player.FlushValveFrontier(token); + ApplyEffects(token); CurrentFrame = Frame(token); operationToken = default; + } + private bool Available(string kind, ZrdNode args) + { + string? name = Mw3ValveRuntime.Text(args, 0); + return kind switch + { + "sound" or "sound_once" => name != null && Context.Sounds.ContainsKey(name), + "animation" or "animation_once" => Context.Package.Entries.Any(e => e.Index > 0 && e.Name == name), + "missionreset" or "missionabort" or "missioncomplete" => true, + "teleport" => Context.Mission?.Actors.Any(a => a.Name == name) == true, + _ => name != null && actors.ContainsKey(name) + }; + } + private void Mutate(Action action, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + if (Faulted) throw new InvalidOperationException("Valve preview was interrupted; reset it before continuing."); + var previous = operationToken; operationToken = token; player.BeginValveOperation(); + try { action(); token.ThrowIfCancellationRequested(); } + catch { Faulted = true; throw; } + finally { operationToken = previous; } + } + public void Set(string name, int value, CancellationToken token = default) => Mutate(() => { Runtime.Set(name, value); ApplyEffects(token); CurrentFrame = Frame(token); }, token); + public void Update(string name, CancellationToken token = default) => Mutate(() => { Runtime.Update(name); ApplyEffects(token); CurrentFrame = Frame(token); }, token); + public void Traverse(AiNetwork network, AiNode node, int slot, CancellationToken token = default) + { + var link = node.PreviewLinks.FirstOrDefault(l => l.Slot == slot); + if (link?.Target == null) throw new InvalidDataException("This outgoing slot has no uniquely resolved target."); + var route = Mw3ValveRoutes.Evaluate(network, node, slot, Runtime); + if (!route.Passable) throw new InvalidDataException(string.Join(" ", route.Reasons)); + Mutate(() => + { + foreach (var assignment in route.Assignments) Runtime.Set(assignment.Valve, assignment.Value); + ApplyEffects(token); CurrentFrame = Frame(token); + }, token); + } + /// + /// The time of the first tick after on which a timer due at runs: the game + /// compares in single precision and runs a timer only once its time is strictly behind the clock. A timer due later + /// is still waiting then. + /// + public static double TimerTime(double now, float due) + { + const long last = 3600 * 60; + long tick = Math.Min(last, (long)Math.Round(now / AnimationPlayer.StepSeconds) + 1); + if (float.IsFinite(due)) tick = Math.Clamp((long)Math.Floor(due / AnimationPlayer.StepSeconds), tick, last); + while (tick < last && !(due < (float)(tick * AnimationPlayer.StepSeconds))) tick++; + return tick * AnimationPlayer.StepSeconds; + } + public AnimationFrame Advance(double seconds, CancellationToken token = default) + { + if (!double.IsFinite(seconds) || seconds < Time || seconds > 3600) throw new ArgumentException("Advance between the current time and one hour; Reset returns to zero."); + long target = (long)Math.Floor(seconds / AnimationPlayer.StepSeconds + 1e-7); + Mutate(() => + { + while (player.Time / AnimationPlayer.StepSeconds + .5 < target) + { + token.ThrowIfCancellationRequested(); + player.ValveClock = player.Time + AnimationPlayer.StepSeconds; + try + { + Runtime.SetClock((float)player.Time); + CurrentFrame = player.Step(token); + ApplyEffects(token); + Runtime.Tick((float)player.Time); + ApplyEffects(token); + } + finally { player.ValveClock = null; } + } + CurrentFrame = Frame(token); + }, token); + return CurrentFrame; + } + private bool Callback(int entryIndex, int root, int message) + { + if (message is < 42 or > 49) return false; + Bind(entryIndex, root); + string? name = bindings[(entryIndex, root)]; + if (name != null) Runtime.Set(name, message & 1); + return name != null; + } + private void Bind(int entryIndex, int root) + { + var key = (entryIndex, root); + if (!bindings.TryGetValue(key, out var name)) + { + name = entryIndex > 0 ? CallbackValve(Context.Package.Entries[entryIndex], Context.Scene, root, player.ValveParent) : null; + bindings.Add(key, name); + if (name != null) Runtime.Register([name]); + } + } + /// + /// The node-name valve an entry's callbacks 42–49 bind when it is loaded on : the first such event + /// of its normal sequences whose zero to three uniquely parented ancestors exist names it. Null without one. + /// + internal static string? CallbackValve(AnimationEntry entry, GameScene scene, int root, Func parent) + { + if (entry.Bytes[152] == 5 || (entry.U32(148) & 0x10) == 0) return null; + foreach (var ev in entry.Sequences.SelectMany(s => s.Events).Where(e => e.Type == 35 && e.I32(12) is >= 42 and <= 49)) + { + int node = root, up = (ev.I32(12) - 42) / 2; + while (up > 0 && node >= 0 && node < scene.Nodes.Count && parent(node) is >= 0 and var above) { node = above; up--; } + if (up == 0 && node >= 0 && node < scene.Nodes.Count) return scene.Nodes[node].Name; + } + return null; + } + /// + /// The valves the map's loaded animations set through callbacks 42–49, read from the entries' events and the roots they + /// bind to in the starting scene (no animation runs). The valve test binds the same way as each animation is loaded. + /// + public static IReadOnlyList CallbackValves(AnimationPackage package, MissionSceneContext mission, CancellationToken token = default) + { + List result = []; + var scene = mission.Scene; + foreach (var entry in package.Entries) + { + token.ThrowIfCancellationRequested(); + if (entry.Index <= 0 || !mission.AnimationEntryRoots.TryGetValue(entry.Index, out int root) || root < 0 || root >= scene.Nodes.Count) continue; + if (CallbackValve(entry, scene, root, node => scene.Nodes[node].Parents is [var parent] ? parent : -1) is not { } valve) continue; + int[] values = [.. entry.Sequences.SelectMany(s => s.Events).Where(e => e.Type == 35 && e.I32(12) is >= 42 and <= 49).Select(e => e.I32(12) & 1).Distinct().Order()]; + result.Add(new(valve, entry.Index, entry.Name, values)); + if (result.Count == Mw3ValveMap.MaximumLinks) break; + } + return result; + } + private void ApplyEffects(CancellationToken token) + { + int remaining = 10_000; + while (true) + { + var effects = Runtime.DrainEffects(); if (effects.Count == 0) break; + bool animation = animationFrontierPending; animationFrontierPending = false; + foreach (var effect in effects) + { + token.ThrowIfCancellationRequested(); + if (--remaining < 0) throw new InvalidDataException("Valve/animation reaction frontier limit exceeded."); + string? name = Mw3ValveRuntime.Text(effect.Arguments, 0); + if (effect.Kind is "animation" or "animation_once") + { + // Activation (and its synchronous cleanup) already ran in reaction order. + } + else if (effect.Kind is "sound" or "sound_once") + { + if (name != null && Context.Sounds.TryGetValue(name, out var sound) && sounds.Count < 1024) + sounds.Add(new(--soundId, name, false, sound.Loop, effect.Time, Vector3.Zero)); + } + else if (effect.Kind == "missionabort") Aborted = true; + } + if (animation) CurrentFrame = player.FlushValveFrontier(token); + } + } + // Actor reactions execute within the valve frontier: a death's valve writes precede later update reactions. + private void ApplyImmediateEffect(Mw3ValveEffect effect) + { + string? name = Mw3ValveRuntime.Text(effect.Arguments, 0); + if (effect.Kind is "animation" or "animation_once") { StartAnimation(name); return; } + if (name == null || !actors.TryGetValue(name, out var actor)) return; + switch (effect.Kind) + { + case "shutdown": actor = actor with { PoweredDown = Mw3ValveRuntime.Integer(effect.Arguments, 1) != 0 }; break; + case "destroy": + if (actor.Destroyed) return; + actors[name] = actor with { Destroyed = true }; + if (targets.TryGetValue(name, out var target) && Mw3ValveProgram.Find(target, "health_below") is { } thresholds) + foreach (int i in Enumerable.Range(0, thresholds.Children.Count / 3).Select(i => i * 3) + .OrderByDescending(i => Mw3ValveRuntime.Number(thresholds, i + 2))) + if (thresholds.Children[i].Kind == ZrdKind.String) Runtime.Set(thresholds.Children[i].Text, Mw3ValveRuntime.Integer(thresholds, i + 1)); + if (targets.TryGetValue(name, out var destruction) && Mw3ValveProgram.Find(destruction, "destroy_anim") is { } destroyArguments) + StartAnimation(Mw3ValveRuntime.Text(destroyArguments, 0)); + return; + case "setteam": actor = actor with { Team = Mw3ValveRuntime.Integer(effect.Arguments, 1) }; break; + case "attack_strategy": actor = actor with { Strategy = Mw3ValveRuntime.Integer(effect.Arguments, 1) }; break; + case "scan_aim": case "scan_hit": case "scan_time": case "canleave": + actor = actor with { Switches = new Dictionary(actor.Switches) { [effect.Kind] = Mw3ValveRuntime.Integer(effect.Arguments, 1) != 0 } }; break; + case "teleport": + if (effect.Arguments.Children.ElementAtOrDefault(1) is { Children.Count: 3 } xyz) + { + actor = actor with { Position = new(Mw3ValveRuntime.Scalar(xyz, 0), Mw3ValveRuntime.Scalar(xyz, 1), Mw3ValveRuntime.Scalar(xyz, 2)), Yaw = Mw3ValveRuntime.Scalar(effect.Arguments, 2) }; + if (Context.Mission?.Actors.FirstOrDefault(a => a.Name == name) is { } placed) player.TeleportValveActor(placed.Root, actor.Position.Value, actor.Yaw.Value, operationToken); + } + break; + } + actors[name] = actor; + } + private void StartAnimation(string? name) + { + if (Context.Package.Entries.FirstOrDefault(e => e.Index > 0 && e.Name == name) is { } entry) + animationFrontierPending |= player.StartValveAnimation(entry.Index, operationToken); + } + private AnimationFrame Frame(CancellationToken token) + { + var frame = player.Frame(token); + sounds.RemoveAll(s => !Context.Sounds.TryGetValue(s.Name, out var sound) || !s.Persistent && Time - s.StartedAt >= sound.Duration); + var poses = frame.Nodes.ToList(); var rendered = poses.Select(p => p.SourceNode).ToHashSet(); + foreach (var actor in Context.Mission?.Actors ?? []) + { + if (!actors.TryGetValue(actor.Name, out var state) || state.Position == null) continue; + var descendants = player.ValveActorNodes(actor.Root, token); + foreach (var pose in player.ValveActorPoses(actor.Root, descendants, token)) if (rendered.Add(pose.SourceNode)) poses.Add(pose); + } + return frame with { Nodes = poses, Sounds = frame.Sounds.Concat(sounds).ToArray(), ActiveSounds = frame.ActiveSounds.Concat(sounds).ToArray() }; + } +} diff --git a/src/zStudio.Core/Sources/SourceValveEdits.cs b/src/zStudio.Core/Sources/SourceValveEdits.cs new file mode 100644 index 00000000..0195043f --- /dev/null +++ b/src/zStudio.Core/Sources/SourceValveEdits.cs @@ -0,0 +1,426 @@ +using System.Text.Json; +using zStudio.Core.Formats; + +namespace zStudio.Core.Sources; + +/// Lossless occurrence-based valve edits over the shared text syntax. +public static class SourceValveEdits +{ + public sealed record Edit(byte[] Content, string Label); + public static Edit Attach(byte[] bytes, int nodeIndex, string attribute, string parameters, CancellationToken token = default) + { + if (attribute is not ("valve" or "valveunion" or "valve_assign")) throw new InvalidDataException("Choose valve, valveunion or valve_assign."); + var syntax = ZrdTextSyntax.Parse(bytes, token); + if (!MissionAiValves.IsNetwork(syntax.Root)) throw new InvalidDataException("Valve attributes require a native version-106 network."); + var network = MissionAiNetworks.Decode("edit", "", 0, "net_01.zrd", syntax.Root, token); + var node = network.Nodes.SingleOrDefault(n => n.Index == nodeIndex); + if (node?.Source == null || !network.ResolvedIndices.Contains(nodeIndex)) throw new InvalidDataException("Choose a uniquely resolved spatial node."); + if (Mw3ValveProgram.Find(node.Source, attribute) != null) throw new InvalidDataException("This node already stores that attribute. Edit its occurrence instead."); + var key = ZrdNode.Create(ZrdKind.String, JsonSerializer.Serialize(attribute)); var value = ParseParameters(parameters, token); + var record = new AiValveRecord(key.Id, node.Source.Id, node.Source.Children.Count, key, value, "node", nodeIndex); + if (MissionAiValves.Problem(record, token) is { } problem) throw new InvalidDataException(problem); + var updated = Replace(syntax.Root, node.Source.Id, node.Source with { Children = [.. node.Source.Children, key, value] }); + var (text, lossless) = syntax.Rewrite(updated, token); + if (!lossless) throw new InvalidDataException("Adding the attribute cannot preserve this source layout."); + return new(ZrdTextSyntax.Encode(text), "Add AI node valve attribute"); + } + public static Edit Plan(string member, byte[] bytes, string operation, int occurrence, string? name, string? parameters, + CancellationToken token = default) + { + if (!ZrdText.LooksLikeText(bytes)) throw new InvalidDataException("Valve editing requires a text source."); + var syntax = ZrdTextSyntax.Parse(bytes, token); + var records = MissionAiValves.Records(member, syntax.Root, token).ToArray(); + bool definition = member.Equals("valves.zrd", StringComparison.OrdinalIgnoreCase); + var body = MissionAiValves.Fields(syntax.Root); + var children = body.Children.ToList(); + ZrdNode updated; + if (operation == "create") + { + if (!definition) throw new InvalidDataException("Create definitions in valves.zrd; edit existing associations in their resource."); + if (string.IsNullOrWhiteSpace(name) || name.Length > 256) throw new InvalidDataException("Enter a valve name of at most 256 characters."); + children.Add(ZrdNode.Create(ZrdKind.String, JsonSerializer.Serialize(name))); + children.Add(ParseParameters(parameters, token)); + updated = Replace(syntax.Root, body.Id, body with { Children = children }); + } + else + { + if (occurrence < 0 || occurrence >= records.Length) throw new InvalidDataException("The valve occurrence is no longer available."); + var record = records[occurrence]; + if (operation == "delete") + { + if (!definition) throw new InvalidDataException("Remove an association by editing its owning record."); + children.RemoveRange(record.ChildIndex, 2); + updated = Replace(syntax.Root, body.Id, body with { Children = children }); + } + else if (operation == "update") + { + var value = ParseParameters(parameters, token); + updated = Replace(syntax.Root, record.Value.Id, Merge(record.Value, value)); + if (definition && name != null) + { + if (string.IsNullOrWhiteSpace(name) || name.Length > 256) throw new InvalidDataException("Enter a valve name of at most 256 characters."); + updated = Replace(updated, record.NameNode.Id, record.NameNode with { Text = name }); + } + } + else throw new InvalidDataException("Use create, update or delete."); + } + if (definition) + { + ValidateEdit(syntax.Root, updated, token); + } + else + { + var id = records[occurrence].Id; + var result = MissionAiValves.Records(member, updated, token).FirstOrDefault(r => r.Id == id) + ?? throw new InvalidDataException("The edit removes the association's recognized layout."); + if (MissionAiValves.Problem(result, token) is { } problem) throw new InvalidDataException(problem); + } + var (text, lossless) = syntax.Rewrite(updated, token); + if (!lossless) throw new InvalidDataException("This edit cannot preserve the surrounding source layout."); + return new(ZrdTextSyntax.Encode(text), operation + " valve occurrence"); + } + /// One reaction of a valve to change: an existing one by its record's occurrence and stored tag (a null spec removes it), or a new one. + public sealed record ReactionChange(int? Occurrence, string? Kind, Mw3ValveReactionSpec? Spec); + /// + /// What a valve's card changes: its starting value, whether it is computed (a condition tag, "" for a plain switch) with + /// its inputs, and its reactions. Null leaves a part as stored. + /// + public sealed record ValveChanges(string? Initial = null, string? Condition = null, IReadOnlyList? Inputs = null, IReadOnlyList? Reactions = null) + { + public bool IsEmpty => Initial == null && Condition == null && Inputs == null && Reactions is null or { Count: 0 }; + } + + /// + /// Changes one valve by name in valves.zrd, keeping every other token: a stored value is replaced in place, a new + /// reaction becomes its own record after the valve's last one (as the shipped files write them), a removed reaction + /// takes its record along once nothing is left in it. A valve without a record gets one. is + /// null when the mission has no valves.zrd yet. + /// + public static Edit PlanValve(byte[]? bytes, string name, ValveChanges changes, CancellationToken token = default) + { + if (string.IsNullOrWhiteSpace(name) || name.Length > 256) throw new InvalidDataException("Enter a valve name of at most 256 characters."); + bytes ??= System.Text.Encoding.Latin1.GetBytes("()\r\n"); + if (!ZrdText.LooksLikeText(bytes)) throw new InvalidDataException("valves.zrd is stored as binary zReader data, so its valves can be edited only in a text source."); + var syntax = ZrdTextSyntax.Parse(bytes, token); + var body = MissionAiValves.Fields(syntax.Root); + if (body.Kind != ZrdKind.Array) throw new InvalidDataException("valves.zrd does not hold a list of valves."); + var records = MissionAiValves.Records("valves.zrd", syntax.Root, token).ToList(); + // The records of this valve, by their place in the file; edits replace them here and the body is rebuilt at the end. + List children = [.. body.Children]; + List<(int Occurrence, int Key)> mine = [.. records.Select((r, i) => (i, r.ChildIndex)).Where(r => records[r.i].Name == name)]; + bool created = mine.Count == 0; + if (created) + { + if (changes.IsEmpty) changes = changes with { Initial = "0" }; + children.Add(ZrdNode.Create(ZrdKind.String, JsonSerializer.Serialize(name))); children.Add(ZrdNode.Create(ZrdKind.Array)); + mine.Add((-1, children.Count - 2)); + } + else if (changes.IsEmpty) throw new InvalidOperationException("Nothing changed."); + foreach (var (_, key) in mine) + if (Mw3ValveProgram.SourceProblem(children[key + 1]) is { } problem && Touches(key)) + throw new InvalidDataException($"A record of {MissionAiValves.Short(name, 64)} is not as the game reads it ({problem.TrimEnd('.')}). Correct it in a text editor first."); + bool Touches(int key) => changes.Initial != null || changes.Condition != null || changes.Inputs != null + || changes.Reactions?.Any(r => r.Occurrence is int occurrence && mine.Any(m => m.Occurrence == occurrence && m.Key == key)) == true; + ZrdNode Value(int key) => children[key + 1]; + // A tag the game reads at the record's top level: its index, or -1 (nested lists are left to a text editor). + static int Tag(ZrdNode record, string tag) + { + for (int i = 0; i < record.Children.Count; i++) if (record.Children[i].Kind == ZrdKind.String && record.Children[i].Text == tag) return i; + return -1; + } + static ZrdNode With(ZrdNode record, IEnumerable items) => record with { Children = [.. items] }; + static ZrdNode Word(string tag) => ZrdNode.Create(ZrdKind.String, JsonSerializer.Serialize(tag)); + + // What the draft asks for, checked at the end against what the game builds from the edited file. + int? wantedStart = null; bool wantedKind = false; string? wantedCondition = null; string[] wantedInputs = []; + List<(Guid Record, string Kind, ZrdNode? Arguments)> wantedReactions = []; + if (changes.Initial is { } initial) + { + if (!int.TryParse(initial.Trim(), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int start)) + throw new InvalidDataException("Enter the starting value as a whole number."); + wantedStart = start; + var number = ZrdNode.Create(ZrdKind.Int, start.ToString(System.Globalization.CultureInfo.InvariantCulture)); + // The game applies every record's value in order: the last one stored decides. + int holder = mine.Select(m => m.Key).LastOrDefault(k => Tag(Value(k), "value") is >= 0 and var at && at + 1 < Value(k).Children.Count && Value(k).Children[at + 1].Kind == ZrdKind.Array, -1); + if (holder >= 0) + { + var record = Value(holder); int at = Tag(record, "value"); var list = record.Children[at + 1]; + var word = list.Children.Count == 1 ? InPlace(list.Children[0], number) : number; + children[holder + 1] = With(record, record.Children.Select((n, i) => i == at + 1 ? list with { Children = [word] } : n)); + } + else + { + int first = mine[0].Key; var record = Value(first); + children[first + 1] = With(record, [Word("value"), ZrdNode.Create(ZrdKind.Array) with { Children = [number] }, .. record.Children]); + } + } + if (changes.Condition != null || changes.Inputs != null) + { + // The game keeps the first computed definition and drops a second one's whole record: changing or removing the first + // would silently promote the other, so the two are sorted out in the file first. + if (mine.Count(m => Mw3ValveProgram.Conditions.Any(c => Mw3ValveProgram.HasTag(Value(m.Key), c))) > 1) + throw new InvalidDataException($"{MissionAiValves.Short(name, 64)} has two computed definitions; the game keeps the first and drops the second record. Remove one of them in a text editor before changing its kind or inputs."); + int holder = mine.Select(m => m.Key).FirstOrDefault(k => Mw3ValveProgram.Conditions.Any(c => Tag(Value(k), c) >= 0), -1); + string? stored = holder < 0 ? null : Mw3ValveProgram.Conditions.First(c => Tag(Value(holder), c) >= 0); + string? condition = changes.Condition == null ? stored : changes.Condition.Length == 0 ? null : changes.Condition; + if (condition != null && !Mw3ValveProgram.Conditions.Contains(condition)) throw new InvalidDataException("Choose any_nonzero, any_zero, all_nonzero or all_zero, or a plain switch."); + wantedKind = true; wantedCondition = condition; + if (condition == null) + { + if (holder >= 0) + { + var record = Value(holder); int at = Tag(record, stored!), names = Tag(record, "namelist"); + HashSet removed = [at]; + // The shipped form is "all_nonzero namelist ( a b )": the tag's own value is the word namelist. + if (at + 1 < record.Children.Count && record.Children[at + 1].Kind == ZrdKind.Array) removed.Add(at + 1); + if (names >= 0) { removed.Add(names); if (names + 1 < record.Children.Count && record.Children[names + 1].Kind == ZrdKind.Array) removed.Add(names + 1); } + children[holder + 1] = With(record, record.Children.Where((_, i) => !removed.Contains(i))); + } + } + else + { + string[] inputs = [.. (changes.Inputs ?? (holder >= 0 && Mw3ValveProgram.Find(Value(holder), "namelist") is { } kept ? [.. kept.Children.Where(n => n.Kind == ZrdKind.String).Select(n => n.Text)] : [])).Select(i => i.Trim()).Where(i => i.Length > 0)]; + if (inputs.Length == 0) throw new InvalidDataException("A computed valve needs at least one input valve."); + if (inputs.Length > 256 || inputs.Any(i => i.Length > 256)) throw new InvalidDataException("A computed valve takes at most 256 inputs of at most 256 characters."); + if (inputs.Contains(name, StringComparer.Ordinal)) throw new InvalidDataException("A computed valve cannot be its own input."); + wantedInputs = inputs; + if (holder >= 0) + { + var record = Value(holder); int at = Tag(record, stored!), names = Tag(record, "namelist"); + if (names < 0 || names + 1 >= record.Children.Count || record.Children[names + 1].Kind != ZrdKind.Array) + throw new InvalidDataException("This computed valve stores its inputs in a form the card does not edit. Correct it in a text editor."); + var updated = Names(record.Children[names + 1], inputs); + children[holder + 1] = With(record, record.Children.Select((n, i) => i == at && condition != stored ? n with { Text = condition } : i == names + 1 ? updated : n)); + } + else + { + int first = mine[0].Key; var record = Value(first); int names = Tag(record, "namelist"); + if (names >= 0 && names + 1 < record.Children.Count && record.Children[names + 1].Kind == ZrdKind.Array) + { + // An input list the record still stores (without a condition the game ignores it) is the one the game + // will read: it becomes the valve's, with the condition before it as the shipped files write it. + var updated = Names(record.Children[names + 1], inputs); + children[first + 1] = With(record, record.Children.SelectMany((n, i) => i == names ? [Word(condition), n] : i == names + 1 ? [updated] : new[] { n })); + } + else children[first + 1] = With(record, [.. record.Children, Word(condition), Word("namelist"), ZrdNode.Create(ZrdKind.Array) with { Children = [.. inputs.Select(Word)] }]); + } + } + } + // Each existing reaction is found in its record as stored, removals apply first, and a record is checked as the draft + // leaves it: the order of the changes never matters (removing one reaction and giving another its kind is one draft). + List added = []; + List<(int Key, Guid Tag, ReactionChange Change)> existing = []; + foreach (var change in changes.Reactions ?? []) + { + token.ThrowIfCancellationRequested(); + if (change.Occurrence is not int occurrence) + { + var spec = change.Spec ?? throw new InvalidDataException("A new reaction needs its fields."); + var owner = Word(name); var fresh = Mw3ValveMap.Arguments(spec); + added.Add(owner); added.Add(ZrdNode.Create(ZrdKind.Array) with { Children = [Word(spec.Kind), fresh] }); + wantedReactions.Add((owner.Id, spec.Kind, fresh)); + continue; + } + int key = -1; foreach (var m in mine) if (m.Occurrence == occurrence) { key = m.Key; break; } + if (key < 0 || change.Kind == null) throw new InvalidDataException("The reaction is no longer in this valve. Read the valve again."); + var record = Value(key); int at = Tag(record, change.Kind); + if (at < 0 || at + 1 >= record.Children.Count || record.Children[at + 1].Kind != ZrdKind.Array) throw new InvalidDataException("The reaction is no longer in this valve. Read the valve again."); + if (existing.Any(e => e.Tag == record.Children[at].Id)) throw new InvalidDataException("One reaction is changed twice."); + // A record that stores several reactions of one kind has only one the game uses (a once-only sound or animation + // before its plain one, else the first). Its fields can change; giving it another kind or removing it would + // silently make a stored, unused reaction the active one. + string family = Family(change.Kind); + if (Kinds(body.Children[key + 1]).GetValueOrDefault(family) > 1 && (change.Spec == null || change.Spec.Kind != change.Kind)) + throw new InvalidDataException($"That record stores more than one {family} reaction and the game uses only one of them. Remove the unused one in a text editor before changing this reaction's kind or removing it."); + existing.Add((key, record.Children[at].Id, change)); + } + foreach (var (key, tag, change) in existing.OrderBy(e => e.Change.Spec == null ? 0 : 1)) + { + var record = Value(key); int at = -1; + for (int i = 0; i < record.Children.Count; i++) if (record.Children[i].Id == tag) { at = i; break; } + if (change.Spec == null) + { + children[key + 1] = With(record, record.Children.Where((_, i) => i != at && i != at + 1)); + wantedReactions.Add((children[key].Id, change.Kind!, null)); + continue; + } + var arguments = Mw3ValveMap.Arguments(change.Spec, change.Kind!, record.Children[at + 1]); + children[key + 1] = With(record, record.Children.Select((n, i) => i == at && change.Spec.Kind != change.Kind ? n with { Text = change.Spec.Kind } : i == at + 1 ? arguments : n)); + wantedReactions.Add((children[key].Id, change.Spec.Kind, arguments)); + } + // A record holds one reaction of a kind (a once-only sound or animation takes the plain one's place): the draft may + // not add a second, whatever a record stored before. + static string Family(string kind) => kind is "sound_once" ? "sound" : kind is "animation_once" ? "animation" : kind; + static Dictionary Kinds(ZrdNode record) => record.Children.Where(n => n.Kind == ZrdKind.String) + .Select(n => Family(n.Text)).Where(t => Mw3ValveProgram.ActionOrder.Contains(t)) + .GroupBy(t => t, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal); + foreach (int key in existing.Select(e => e.Key).Distinct()) + { + var before = Kinds(body.Children[key + 1]); + foreach (var (kind, count) in Kinds(Value(key))) + if (count > 1 && count > before.GetValueOrDefault(kind)) throw new InvalidDataException($"That record would hold two {kind} reactions; a record holds one of a kind."); + } + // New reactions follow the valve's last record; a record emptied by removals leaves the file (never the last one of a new valve). + int after = mine.Max(m => m.Key) + 2; + HashSet emptied = [.. mine.Where(m => m.Occurrence >= 0 && Value(m.Key).Children.Count == 0 && body.Children[m.Key + 1].Children.Count > 0).Select(m => m.Key)]; + List rebuilt = []; + for (int i = 0; i < children.Count; i++) + { + if (i == after) rebuilt.AddRange(added); + if (emptied.Contains(i) || emptied.Contains(i - 1)) continue; + rebuilt.Add(children[i]); + } + if (after >= children.Count) rebuilt.AddRange(added); + var updatedRoot = Replace(syntax.Root, body.Id, body with { Children = rebuilt }); + if (ZrdTextSyntax.StructurallyEqual(updatedRoot, syntax.Root)) throw new InvalidOperationException("Nothing changed."); + ValidateEdit(syntax.Root, updatedRoot, token); + // The edit is accepted only when the game would build what the draft shows: the game finds a tag by searching the + // record's lists in order, so a record written in an unusual form can make it read another value first. + { + var built = Mw3ValveProgram.Read(updatedRoot, token, skipUnreadable: true).Effective().Definitions; + var definitions = built.Where(d => d.Name == name).ToArray(); + var computed = definitions.FirstOrDefault(d => d.Condition != null && d.Inputs.Count > 0); + bool asShown = !wantedKind || (wantedCondition == null ? computed == null : computed != null && computed.Condition == wantedCondition && computed.Inputs.SequenceEqual(wantedInputs)); + asShown &= wantedStart == null || (definitions.LastOrDefault(d => d.Initial != null)?.Initial ?? 0) == wantedStart; + // One draft can remove a reaction and give another its kind: what a record ends with per kind is what counts. + Dictionary<(Guid Record, string Family), (string Kind, ZrdNode Arguments)?> expected = []; + foreach (var (owner, kind, arguments) in wantedReactions.Where(w => w.Arguments == null)) expected[(owner, Family(kind))] = null; + foreach (var (owner, kind, arguments) in wantedReactions.Where(w => w.Arguments != null)) expected[(owner, Family(kind))] = (kind, arguments!); + foreach (var (key, wanted) in expected) + { + var action = built.FirstOrDefault(d => d.Record == key.Record)?.Actions.FirstOrDefault(a => Family(a.Kind) == key.Family); + asShown &= wanted is not { } set ? action == null : action != null && action.Kind == set.Kind && ZrdTextSyntax.StructurallyEqual(action.Arguments, set.Arguments); + } + if (!asShown) throw new InvalidDataException($"valves.zrd stores {MissionAiValves.Short(name, 64)} in a form where this change would not take effect as shown (the game would read another value first). Edit it in a text editor."); + } + var (text, lossless) = syntax.Rewrite(updatedRoot, token); + if (!lossless) throw new InvalidDataException("This edit cannot preserve the surrounding source layout."); + return new(ZrdTextSyntax.Encode(text), created ? $"Add valve {MissionAiValves.Short(name, 48)}" : $"Edit valve {MissionAiValves.Short(name, 48)}"); + } + + /// Removes every valves.zrd record of a valve. What other files say about it stays (the game still makes it, at zero). + public static Edit PlanRemove(byte[] bytes, string name, CancellationToken token = default) + { + if (!ZrdText.LooksLikeText(bytes)) throw new InvalidDataException("valves.zrd is stored as binary zReader data, so its valves can be edited only in a text source."); + var syntax = ZrdTextSyntax.Parse(bytes, token); var body = MissionAiValves.Fields(syntax.Root); + HashSet keys = [.. MissionAiValves.Records("valves.zrd", syntax.Root, token).Where(r => r.Name == name).Select(r => r.ChildIndex)]; + if (keys.Count == 0) throw new InvalidDataException("valves.zrd has no record of this valve."); + var updated = Replace(syntax.Root, body.Id, body with { Children = [.. body.Children.Where((_, i) => !keys.Contains(i) && !keys.Contains(i - 1))] }); + var (text, lossless) = syntax.Rewrite(updated, token); + if (!lossless) throw new InvalidDataException("This edit cannot preserve the surrounding source layout."); + return new(ZrdTextSyntax.Encode(text), $"Delete valve {MissionAiValves.Short(name, 48)}"); + } + + /// + /// Renames a valve wherever one resource names it: its valves.zrd records, other valves' inputs and timers, vehicle + /// triggers, health thresholds, route gates and assignments, deploy points, and this mission's objectives. Null when the + /// file does not name it. + /// + public static Edit? PlanRename(string member, byte[] bytes, string name, string renamed, string? mission, CancellationToken token = default) + { + if (string.IsNullOrWhiteSpace(renamed) || renamed.Length > 256 || renamed != renamed.Trim()) throw new InvalidDataException("Enter a valve name of at most 256 characters, without spaces around it."); + if (!ZrdText.LooksLikeText(bytes)) return null; + var syntax = ZrdTextSyntax.Parse(bytes, token); + HashSet operands = []; + bool objectives = member.Equals("objectives.zrd", StringComparison.OrdinalIgnoreCase); + // objectives.zrd holds every mission of the map: only this mission's block is this mission's valve. + ZrdNode? scope = syntax.Root; + if (objectives) + { + var fields = MissionAiValves.Fields(syntax.Root).Children; scope = null; + for (int i = 0; mission != null && i + 1 < fields.Count; i += 2) + if (fields[i].Kind == ZrdKind.String && fields[i].Text.Equals(mission, StringComparison.OrdinalIgnoreCase)) { scope = fields[i + 1]; break; } + if (scope == null) return null; + } + foreach (var record in MissionAiValves.Records(member, syntax.Root, token)) + { + if (objectives && scope!.Find(record.Id) == null) continue; + foreach (var reference in MissionAiValves.References(record, token)) if (reference.Name == name) operands.Add(reference.Operand); + } + if (MissionAiNetworks.IsCandidate(member, mw3: true) && MissionAiValves.IsNetwork(syntax.Root)) + foreach (var node in MissionAiValves.Fields(syntax.Root).Children.Where(n => n.Kind == ZrdKind.Array)) + for (int j = 3; j + 1 < node.Children.Count; j += 2) + if (node.Children[j] is { Kind: ZrdKind.String, Text: "deploy" or "mcbwait" } key && node.Children[j + 1].Kind == ZrdKind.Array) + foreach (int at in key.Text == "deploy" ? new[] { 0, 2 } : [0]) + if (node.Children[j + 1].Children.ElementAtOrDefault(at) is { Kind: ZrdKind.String } named && named.Text == name) operands.Add(named.Id); + if (operands.Count == 0) return null; + var updated = Rename(syntax.Root); + if (member.Equals("valves.zrd", StringComparison.OrdinalIgnoreCase)) ValidateEdit(syntax.Root, updated, token); + var (text, lossless) = syntax.Rewrite(updated, token); + if (!lossless) throw new InvalidDataException($"Renaming cannot preserve the layout of {member}."); + return new(ZrdTextSyntax.Encode(text), $"Rename valve {MissionAiValves.Short(name, 48)}"); + ZrdNode Rename(ZrdNode node) => operands.Contains(node.Id) ? node with { Text = renamed } + : node.Kind != ZrdKind.Array ? node : node with { Children = [.. node.Children.Select(Rename)] }; + } + + /// + /// Checks valves.zrd as an edit leaves it. A record the game read before must still read as written, and the definitions + /// the game builds (unreadable records left out, a second computed definition dropped with its record) must have no + /// immediate reaction cycle and no cyclic condition. What the file already had wrong is not this edit's: the same + /// failure before the edit does not refuse it. + /// + private static void ValidateEdit(ZrdNode before, ZrdNode after, CancellationToken token) + { + HashSet unreadable = [.. MissionAiValves.Records("valves.zrd", before, token).Where(r => Mw3ValveProgram.SourceProblem(r.Value) != null).Select(r => r.Id)]; + foreach (var record in MissionAiValves.Records("valves.zrd", after, token)) + if (!unreadable.Contains(record.Id) && Mw3ValveProgram.SourceProblem(record.Value) is { } problem) + throw new InvalidDataException($"Valve {MissionAiValves.Short(record.Name, 64)}: {problem}"); + static string? Failure(ZrdNode root, CancellationToken token) + { + try { Mw3ValveProgram.Read(root, token, skipUnreadable: true).Effective().ValidateForEditing(); return null; } + catch (InvalidDataException ex) { return ex.Message; } + } + if (Failure(after, token) is { } failure && failure != Failure(before, token)) throw new InvalidDataException(failure); + } + /// A number that replaces a stored number keeps its node's identity, so its token changes in place whatever its kind. + /// + /// An input list with other names; every row keeps its own token, so only the words that change are rewritten and the + /// notes around them stay. As many names as before: row by row (a row given another name is that row). More or fewer: + /// the longest run of names that stay, in order, keeps its rows; between them a new name takes the place of one that + /// goes, the rest are added or removed. + /// + private static ZrdNode Names(ZrdNode list, IReadOnlyList inputs) + { + ZrdNode[] old = [.. list.Children.Where(n => n.Kind == ZrdKind.String)]; + static ZrdNode Word(string name) => ZrdNode.Create(ZrdKind.String, JsonSerializer.Serialize(name)); + static ZrdNode Row(ZrdNode stored, string name) => stored.Text == name ? stored : Word(name) with { Id = stored.Id }; + if (old.Length == inputs.Count) return list with { Children = [.. inputs.Select((name, at) => Row(old[at], name))] }; + // Longest common subsequence of the stored and the wanted names (at most 256 of each). + var run = new int[old.Length + 1, inputs.Count + 1]; + for (int i = old.Length - 1; i >= 0; i--) + for (int j = inputs.Count - 1; j >= 0; j--) + run[i, j] = old[i].Text == inputs[j] ? run[i + 1, j + 1] + 1 : Math.Max(run[i + 1, j], run[i, j + 1]); + List rows = []; + int a = 0, b = 0; + while (a < old.Length || b < inputs.Count) + { + if (a < old.Length && b < inputs.Count && old[a].Text == inputs[b]) { rows.Add(old[a]); a++; b++; continue; } + // Up to the next name that stays on both sides: what goes and what comes pair up in order. + int goes = a, comes = b; + while (a < old.Length && b < inputs.Count && old[a].Text != inputs[b]) { if (run[a + 1, b] >= run[a, b + 1]) a++; else b++; } + if (a == old.Length) b = inputs.Count; else if (b == inputs.Count) a = old.Length; + for (int k = 0; comes + k < b; k++) rows.Add(goes + k < a ? Row(old[goes + k], inputs[comes + k]) : Word(inputs[comes + k])); + } + return list with { Children = [.. rows] }; + } + + private static ZrdNode InPlace(ZrdNode stored, ZrdNode value) => stored.Kind == ZrdKind.Array || value.Kind == ZrdKind.Array ? value + : ZrdTextSyntax.StructurallyEqual(stored, value) ? stored : value with { Id = stored.Id }; + + private static ZrdNode ParseParameters(string? text, CancellationToken token) + { + if (text == null || text.Length > 65_536) throw new InvalidDataException("Enter at most 65,536 characters of valve parameters."); + var parsed = ZrdText.Parse(text, token); + return parsed.Children is [{ Kind: ZrdKind.Array } array] ? array : parsed; + } + private static ZrdNode Merge(ZrdNode before, ZrdNode after) + { + if (ZrdTextSyntax.StructurallyEqual(before, after)) return before; + // A scalar that changes kind still replaces its token in place (its comments and place stay). + if (before.Kind != after.Kind) return before.Kind != ZrdKind.Array && after.Kind != ZrdKind.Array ? after with { Id = before.Id } : after; + if (before.Kind != ZrdKind.Array) return after with { Id = before.Id }; + return before with { Children = after.Children.Select((n, i) => i < before.Children.Count ? Merge(before.Children[i], n) : n).ToArray() }; + } + private static ZrdNode Replace(ZrdNode node, Guid id, ZrdNode replacement) => node.Id == id ? replacement : + node.Kind != ZrdKind.Array ? node : node with { Children = node.Children.Select(c => Replace(c, id, replacement)).ToArray() }; +} diff --git a/src/zStudio.Desktop/AnimationAudio.cs b/src/zStudio.Desktop/AnimationAudio.cs index 17f1d9e1..51883208 100644 --- a/src/zStudio.Desktop/AnimationAudio.cs +++ b/src/zStudio.Desktop/AnimationAudio.cs @@ -49,7 +49,7 @@ public Task PrepareAsync(AnimationPreviewContext snapshot, int entryIndex, Cance /// Source world sessions defer device creation until explicit forward playback. public async Task PrepareAsync(AnimationPreviewContext snapshot, int entryIndex, AnimationExecutionPolicy? policy, - bool openOutput, CancellationToken token = default, AnimationSchedule? schedule = null) + bool openOutput, CancellationToken token = default, AnimationSchedule? schedule = null, IReadOnlyList? soundNames = null) { ObjectDisposedException.ThrowIf(disposed, this); Stop(); IsPrepared = false; bank.Clear(); @@ -60,7 +60,7 @@ public async Task PrepareAsync(AnimationPreviewContext snapshot, int entryIndex, Preparation? result = null; try { - result = await Task.Run(() => Prepare(snapshot, entryIndex, policy, openOutput, linked.Token, schedule), linked.Token); + result = await Task.Run(() => Prepare(snapshot, entryIndex, policy, openOutput, linked.Token, schedule, soundNames), linked.Token); linked.Token.ThrowIfCancellationRequested(); if (disposed || generation != preparationGeneration) return; bank = result.Bank; IsPrepared = result.Error == null; @@ -76,14 +76,15 @@ public async Task PrepareAsync(AnimationPreviewContext snapshot, int entryIndex, } private Preparation Prepare(AnimationPreviewContext snapshot, int entryIndex, AnimationExecutionPolicy? policy, - bool openOutput, CancellationToken token, AnimationSchedule? schedule) + bool openOutput, CancellationToken token, AnimationSchedule? schedule, IReadOnlyList? soundNames) { - var dependencies = AnimationAudioDependencies.Collect(snapshot.Package, entryIndex, policy, token, schedule); - List diagnostics = [.. dependencies.Diagnostics]; + if (soundNames?.Count > 16_384) throw new InvalidDataException("Audio name allowance exceeded."); + var dependencies = soundNames == null ? AnimationAudioDependencies.Collect(snapshot.Package, entryIndex, policy, token, schedule) : null; + List diagnostics = dependencies == null ? [] : [.. dependencies.Diagnostics]; Dictionary names = new(StringComparer.Ordinal); Dictionary, AnimationSound> requested = []; HashSet> unavailable = []; - foreach (string name in dependencies.Names.Order(StringComparer.Ordinal)) + foreach (string name in ((IEnumerable?)soundNames ?? dependencies!.Names).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)) { token.ThrowIfCancellationRequested(); if (!snapshot.Sounds.TryGetValue(name, out var sound)) diff --git a/src/zStudio.Desktop/MainWindow.AnimationMode.cs b/src/zStudio.Desktop/MainWindow.AnimationMode.cs index ccc80265..eb6bc1be 100644 --- a/src/zStudio.Desktop/MainWindow.AnimationMode.cs +++ b/src/zStudio.Desktop/MainWindow.AnimationMode.cs @@ -102,6 +102,7 @@ private async Task OpenAnimationModeAsync(DocumentModel document, int definition // The drop-window analysis and the shown guides belong to the opened definition: opening another one closes them // (selecting another definition's items in the graph or Timing, which shows their card, keeps them). if (!entering && animationMode!.Definition != definition) { ForgetAutomaticGuides(); EndDropMove(); CloseParachutes(); HideAllAnimationGuides(); } + EndValveTest(); DetachWorldAnimationRun(); if (!entering && animationMode!.Definition == definition) AutomaticBindingChanged(document, binding); animationMode = target; animationKept = null; animationFailure = null; previewId = Guid.NewGuid(); diff --git a/src/zStudio.Desktop/MainWindow.Mcp.cs b/src/zStudio.Desktop/MainWindow.Mcp.cs index 34506182..50877e2b 100644 --- a/src/zStudio.Desktop/MainWindow.Mcp.cs +++ b/src/zStudio.Desktop/MainWindow.Mcp.cs @@ -135,6 +135,7 @@ private void RequireNoSelectionDrafts(DocumentModel? doc = null) /// The refusal a pending section card draft gives, naming the card that holds it and how MCP resolves it. private string SectionDraftRefusal => sectionCard?.Entry is DefinitionEntry ? "Apply or revert the animation card's changes (source_animation apply or cancel, or drafts target section) before continuing." + : sectionCard?.Entry is ValveEntry ? "Apply or revert the valve card's changes (drafts target section) before continuing." : "Apply or revert the zone or AI network card's changes (drafts target section) before continuing."; /// Whether any draft a GUI action is refused for is pending (the drafts names). private bool HasGuiDraft => HasModelPlacementDraft || HasSectionDraft() || parachuteDraft != null || HasAiPathDraft || HasInspectionDraft @@ -222,6 +223,7 @@ private StudioCommands CreateCommands() RegisterSourceAnimationCommands(registry); RegisterWorldAnimationCommands(registry); RegisterValveCommands(registry); + RegisterValveAuthoringCommands(registry); RegisterInspectionCommands(registry); RegisterSceneTreeCommand(registry); RegisterSourceMapPartCommands(registry); diff --git a/src/zStudio.Desktop/MainWindow.Properties.cs b/src/zStudio.Desktop/MainWindow.Properties.cs index f0ffd4ea..4f7cb4f4 100644 --- a/src/zStudio.Desktop/MainWindow.Properties.cs +++ b/src/zStudio.Desktop/MainWindow.Properties.cs @@ -270,9 +270,20 @@ private void SceneContextOpening(object sender, RoutedEventArgs e) SceneGroupByStartMenu.Visibility = animationsRow ? Visibility.Visible : Visibility.Collapsed; SceneGroupByStartMenu.IsChecked = animationsByStart; SceneGroupByStartMenu.IsEnabled = animationsRow && sceneContextDocument!.SourceWorld is { IsRebuilding: false } && !sourceWorkspaceBusy; - if (!creation && !rename && !addPickup && !resetParts && !animationRow && !animationsRow && sender is ContextMenu menu) menu.IsOpen = false; + // The Valves row and its valves (MW3): Test valves, New valve; a valve also Rename, Delete (its records) and Copy name. + bool valvesRow = contextScene is { HasValveTest: true } && contextScene.Owner == sceneTree && sceneContextDocument == shownDocument; + bool valveRow = contextScene?.Section is ValveEntry && contextScene.Owner == sceneTree && sceneContextDocument == shownDocument; + bool valveEdits = sceneContextDocument.SourceWorld is { IsRebuilding: false } && !sourceWorkspaceBusy && !InAnimationMode && !HasGuiDraft; + SceneValveTestMenu.Visibility = SceneNewValveMenu.Visibility = valvesRow || valveRow ? Visibility.Visible : Visibility.Collapsed; + SceneValveTestMenu.IsChecked = ValveTesting; SceneValveTestMenu.IsEnabled = !InAnimationMode; + SceneNewValveMenu.IsEnabled = valveEdits; + SceneRenameValveMenu.Visibility = SceneDeleteValveMenu.Visibility = SceneCopyValveMenu.Visibility = valveRow ? Visibility.Visible : Visibility.Collapsed; + SceneRenameValveMenu.IsEnabled = valveEdits; + SceneDeleteValveMenu.IsEnabled = valveEdits && contextScene?.Section is ValveEntry { Valve.Defined: true }; + if (!creation && !rename && !addPickup && !resetParts && !animationRow && !animationsRow && !valvesRow && !valveRow && sender is ContextMenu menu) menu.IsOpen = false; e.Handled = true; return; } + SceneValveTestMenu.Visibility = SceneNewValveMenu.Visibility = SceneRenameValveMenu.Visibility = SceneDeleteValveMenu.Visibility = SceneCopyValveMenu.Visibility = Visibility.Collapsed; SceneAddGroupMenu.Visibility = SceneAddObjectMenu.Visibility = SceneRenameMenu.Visibility = SceneOpenAnimationMenu.Visibility = SceneCopyAnimationMenu.Visibility = SceneFrameAnimationMenu.Visibility = SceneAnimationSourceMenu.Visibility = SceneAnimationPropertiesMenu.Visibility = SceneSelectBoundMenu.Visibility = SceneGroupByStartMenu.Visibility = Visibility.Collapsed; ScenePropertiesMenu.Visibility = Visibility.Visible; diff --git a/src/zStudio.Desktop/MainWindow.SceneTree.cs b/src/zStudio.Desktop/MainWindow.SceneTree.cs index ecc810ad..641ae056 100644 --- a/src/zStudio.Desktop/MainWindow.SceneTree.cs +++ b/src/zStudio.Desktop/MainWindow.SceneTree.cs @@ -324,10 +324,10 @@ private void ScheduleSceneTreeReveal(SceneTreeItem? reveal = null) } private void RegisterSceneTreeCommand(StudioCommands commands) { - Register(commands, "scene_tree", "Read the Document scene hierarchy, including stable preview placements, shared/partition references and disconnected nodes. Source maps show the World tree: the authored glTF hierarchy, including groups removed by compilation, under the World root, then section rows (sectionRow.section) and pass rows in a fixed order: World, Zones, AI Vehicles (pass aiv: units the AIV resources place), AI Networks, Pickups (pass puppies) and Animations (section definitions: the map's definition files, then Common, then Objects placed by animations, pass anim: objects startup animations place or hide until placed). Zones lists the map's zones (sectionRow zoneId, label, polygons, placements, models, objects = ownObjects + inheritedObjects with emptyObjects among them, used) and polygons without a zone; AI Networks lists the mission's networks (sectionRow network = the file's project path, name, nodes, attackStrategy); Animations lists the .zad files the mission's anim.zad names directly (no map scope row; a file with one definition is that definition; sectionRow definitionFile, occurrence, listedBy, definitions, affectsSelection when closed over a definition bound to the selected object), then one Common row (sectionRow definitionScope Common: data/common, shared by every map) holding the common ones the same way, and listed files that are missing; with scene_options animationsByStart the definitions are in one row per start kind instead (category definitionGroup; sectionRow kind definitionGroup, scope map or Common, start opening, startup, damage, called, game or none, label, count; never selected; Common holds its own). Each definition (sectionRow definition, definitionFile, ordinal, occurrence, name, rootName, roots/bound: what it binds in this world, null when unknown; bindings: its entries) says how it starts (start: kind opening (NEW_GAME_START), load (LOAD_GAME_START), startup, damage, called (a call of the map reaches it), game (the game starts it on the map's units: pickups, vehicles, turrets, trails, weapon flyouts) or none (no caller found: the game may still play it by name), its detail, activation as compiled, health, callerCount, callers: up to 8 calling definitions with their calling bindings, known: false when the map's animations did not build), what it acts on (target: kind object, objects, template (bound only to nodes no World tree row lists), playerTank, units or none (not in this map), text as the row shows it, count), duplicateOf (the earlier definition of the same name that calls, stops and prerequisites reach), opened (Animation mode has it open), kept (its scenario is kept after Exit), affectsSelection (bound to the selected object) and frameable; the fields are null until the map's summary is built, which every scene_tree call awaits. A definition with several bindings lists them (sectionRow kind animationBinding, entry, name: the name calls use, its Label, rootName, opened, frameable). Zones and AI networks are shown one by one and start hidden (sectionRow shown); any shown zone turns the zone overlay on and any shown network the AI overlay (always drawn through geometry, at half strength where it hides them). The Zones, AI Networks, AI Vehicles and Pickups rows carry master (true: shown, so hide is what their eye does next; it follows when everything below comes to be shown or hidden one by one); Zones also reports its overlay kind (objects or polygons) and paused while Edit zones is on. The aiv and puppies passes list every difficulty's units and pickups with the difficulties placing each; those the shown difficulty does not place have otherDifficulty=true, node=null and a placement summary, and cannot be selected; placed rows matched to their records carry the placement summary too (including how often a resource lists that placement). Pickups always hold three group rows, Weapons, Ammo and Other (category pickupGroup; sectionRow kind, group weapons/ammo/other, count and shown = placed on the shown difficulty), which open and close, hide and show (master) and frame their pickups but are never selected; with scene_options pickupsByType each holds a row per catalog type (category pickupType; sectionRow group, pickupType, shortName, name, count, shown). Pickup rows expose pickupType (catalog name), pickupKind (ammo, weapon, health or technology), pickupGroup, pickupNumber (per catalog type in list order over every difficulty), pickupShortName, pickupName (the game manual's name; ammo adds the word ammo), instanceName (the game's name, null on other-difficulty rows) and pickupTemplate; their Label is the short name and number (ERFPG #1). These fields are null on non-pickup rows. The player tank's row (the first vehicle the shown difficulty's AIV layout spawns, identified by placement, not name) has playerTank true, null elsewhere; preview_state.bft describes how the view draws it. A unit or pickup every difficulty places shows All as its difficulty tag. animations lists resolved initial-root and indirect animation associations (at most eight names, then an ellipsis). animationUses supplies the first eight entryIndex/name/origin/reason records (origin initialRoot or indirect), animationUseCount how many there are and animationUsesTruncated whether more exist; action animationUses (row or node) pages every one of them, uncapped, as the object card's Animations affecting this object and the glyph flyout list them (with each one's definition for animation_mode open) and animationHasInitialRoot and animationHasIndirect retain both origin summaries even when details are capped. The original cyan icon marks any initial-root association; indirect-only recipients use the same glyph at half HSL saturation. Position references and unknown impact targets do not imply animation ownership. World objects expand into exact child objects, geometry and LOD branches, including initialized hidden healthy/destroyed states. select targets the exact row; map hits still select the whole object. Child hide/show uses session-only part gates and may rebuild the preview; use the returned context and preview afterwards. visibility reports DefaultVisible, Visible, Override, EffectiveVisible and Reason. sourceFile/gltfNode identify authored nodes, sourceOccurrence identifies a tree path, and compiledNode is an optional built slot. selectionOwner for source_map_parts is a signed current-preview identity; source-only authored groups have node=null and selectionOwner=null and support read-only row inspection. properties focuses the source-object card, or opens pinned Properties in other viewers. Read returns roots or a row's direct children, optionally filtered before paging; in a source map, search and/or types read the whole hierarchy as a flat list of matches with their parent paths, as the outliner's search box does (types narrows it by the legend's categories). A row's zone is null in the aiv and puppies passes. Source map rows carry category (world, group, geometry, empty: an Object3D without a model or children, which draws nothing and cannot be hidden or framed; object, node, zone, network, definition), zone and hidden. Expand/collapse/reveal only change tree presentation; hide/show hide a row's object (a removed group: what it holds) in the view only, like the outliner's eye, except that show, and an isolate that ends or moves an isolation (as scene_selection show_all and isolate), select in the view an object the card shows as hidden because it was selected in the tree while hidden (only with no draft open; after an AI path or drop-window draft ends this follows once the application is idle, after that command returned, so read scene_inspect or preview_state afterwards): the view selection, the card and scene_inspect selected change, and its placement can be edited; on the Zones, AI Networks, AI Vehicles (pass aiv) and Pickups (pass puppies) rows they hide or show everything below them, on a zone its colour and on a network its nodes and links (preview_state sections reports them); isolate works on world objects only (zones, networks, units and pickups are refused). select shares scene inspection and draft guards; selecting a zone, network or definition ends the object selection and opens its card in the Properties pane (a network is shown and emphasised, a definition's bound objects outlined; drafts target section), and properties also focuses the card's first field. Runtime parenting is not represented.", true, - [DocumentParameter, P("action", "string", "Tree action; default read. Properties focuses the source-object card; other viewers open the same pinned window as the row context menu. hide/show (source maps) change only what the view draws; isolate (source maps) shows only the row's object, or everything again on the isolated row, as a middle-click on its eye. frame (source maps: the Pickups section's Weapons, Ammo and Other rows and their type rows, and animation definition and binding rows) frames their pickups on the shown difficulty, or what a definition or binding binds to (the row's Frame bound objects), without selecting anything, as the row's Frame button; a definition bound only to templates (nodes no World tree row lists) or to nothing is refused (not_ready: nothing it binds to is drawn in the view).", false, "read", "expand", "collapse", "reveal", "select", "properties", "hide", "show", "isolate", "frame", "animationUses"), + Register(commands, "scene_tree", "Read the Document scene hierarchy, including stable preview placements, shared/partition references and disconnected nodes. Source maps show the World tree: the authored glTF hierarchy, including groups removed by compilation, under the World root, then section rows (sectionRow.section) and pass rows in a fixed order: World, Zones, AI Vehicles (pass aiv: units the AIV resources place), AI Networks, Valves (MW3 maps only), Pickups (pass puppies) and Animations (section definitions: the map's definition files, then Common, then Objects placed by animations, pass anim: objects startup animations place or hide until placed). Zones lists the map's zones (sectionRow zoneId, label, polygons, placements, models, objects = ownObjects + inheritedObjects with emptyObjects among them, used) and polygons without a zone; AI Networks lists the mission's networks (sectionRow network = the file's project path, name, nodes, attackStrategy); Valves (section valves: count, source, testing while ai_valve_preview runs) lists an MW3 mission's valves one per exact name (sectionRow kind valve, name, defined, computed, summary, setBy, reactions, usedBy and problems counts; select shows the valve's card, source_ai_valve reads and edits it, frame frames its vehicles and route nodes); Animations lists the .zad files the mission's anim.zad names directly (no map scope row; a file with one definition is that definition; sectionRow definitionFile, occurrence, listedBy, definitions, affectsSelection when closed over a definition bound to the selected object), then one Common row (sectionRow definitionScope Common: data/common, shared by every map) holding the common ones the same way, and listed files that are missing; with scene_options animationsByStart the definitions are in one row per start kind instead (category definitionGroup; sectionRow kind definitionGroup, scope map or Common, start opening, startup, damage, called, game or none, label, count; never selected; Common holds its own). Each definition (sectionRow definition, definitionFile, ordinal, occurrence, name, rootName, roots/bound: what it binds in this world, null when unknown; bindings: its entries) says how it starts (start: kind opening (NEW_GAME_START), load (LOAD_GAME_START), startup, damage, called (a call of the map reaches it), game (the game starts it on the map's units: pickups, vehicles, turrets, trails, weapon flyouts) or none (no caller found: the game may still play it by name), its detail, activation as compiled, health, callerCount, callers: up to 8 calling definitions with their calling bindings, known: false when the map's animations did not build), what it acts on (target: kind object, objects, template (bound only to nodes no World tree row lists), playerTank, units or none (not in this map), text as the row shows it, count), duplicateOf (the earlier definition of the same name that calls, stops and prerequisites reach), opened (Animation mode has it open), kept (its scenario is kept after Exit), affectsSelection (bound to the selected object) and frameable; the fields are null until the map's summary is built, which every scene_tree call awaits. A definition with several bindings lists them (sectionRow kind animationBinding, entry, name: the name calls use, its Label, rootName, opened, frameable). Zones and AI networks are shown one by one and start hidden (sectionRow shown); any shown zone turns the zone overlay on and any shown network the AI overlay (always drawn through geometry, at half strength where it hides them). The Zones, AI Networks, AI Vehicles and Pickups rows carry master (true: shown, so hide is what their eye does next; it follows when everything below comes to be shown or hidden one by one); Zones also reports its overlay kind (objects or polygons) and paused while Edit zones is on. The aiv and puppies passes list every difficulty's units and pickups with the difficulties placing each; those the shown difficulty does not place have otherDifficulty=true, node=null and a placement summary, and cannot be selected; placed rows matched to their records carry the placement summary too (including how often a resource lists that placement). Pickups always hold three group rows, Weapons, Ammo and Other (category pickupGroup; sectionRow kind, group weapons/ammo/other, count and shown = placed on the shown difficulty), which open and close, hide and show (master) and frame their pickups but are never selected; with scene_options pickupsByType each holds a row per catalog type (category pickupType; sectionRow group, pickupType, shortName, name, count, shown). Pickup rows expose pickupType (catalog name), pickupKind (ammo, weapon, health or technology), pickupGroup, pickupNumber (per catalog type in list order over every difficulty), pickupShortName, pickupName (the game manual's name; ammo adds the word ammo), instanceName (the game's name, null on other-difficulty rows) and pickupTemplate; their Label is the short name and number (ERFPG #1). These fields are null on non-pickup rows. The player tank's row (the first vehicle the shown difficulty's AIV layout spawns, identified by placement, not name) has playerTank true, null elsewhere; preview_state.bft describes how the view draws it. A unit or pickup every difficulty places shows All as its difficulty tag. animations lists resolved initial-root and indirect animation associations (at most eight names, then an ellipsis). animationUses supplies the first eight entryIndex/name/origin/reason records (origin initialRoot or indirect), animationUseCount how many there are and animationUsesTruncated whether more exist; action animationUses (row or node) pages every one of them, uncapped, as the object card's Animations affecting this object and the glyph flyout list them (with each one's definition for animation_mode open) and animationHasInitialRoot and animationHasIndirect retain both origin summaries even when details are capped. The original cyan icon marks any initial-root association; indirect-only recipients use the same glyph at half HSL saturation. Position references and unknown impact targets do not imply animation ownership. World objects expand into exact child objects, geometry and LOD branches, including initialized hidden healthy/destroyed states. select targets the exact row; map hits still select the whole object. Child hide/show uses session-only part gates and may rebuild the preview; use the returned context and preview afterwards. visibility reports DefaultVisible, Visible, Override, EffectiveVisible and Reason. sourceFile/gltfNode identify authored nodes, sourceOccurrence identifies a tree path, and compiledNode is an optional built slot. selectionOwner for source_map_parts is a signed current-preview identity; source-only authored groups have node=null and selectionOwner=null and support read-only row inspection. properties focuses the source-object card, or opens pinned Properties in other viewers. Read returns roots or a row's direct children, optionally filtered before paging; in a source map, search and/or types read the whole hierarchy as a flat list of matches with their parent paths, as the outliner's search box does (types narrows it by the legend's categories). A row's zone is null in the aiv and puppies passes. Source map rows carry category (world, group, geometry, empty: an Object3D without a model or children, which draws nothing and cannot be hidden or framed; object, node, zone, network, definition), zone and hidden. Expand/collapse/reveal only change tree presentation; hide/show hide a row's object (a removed group: what it holds) in the view only, like the outliner's eye, except that show, and an isolate that ends or moves an isolation (as scene_selection show_all and isolate), select in the view an object the card shows as hidden because it was selected in the tree while hidden (only with no draft open; after an AI path or drop-window draft ends this follows once the application is idle, after that command returned, so read scene_inspect or preview_state afterwards): the view selection, the card and scene_inspect selected change, and its placement can be edited; on the Zones, AI Networks, AI Vehicles (pass aiv) and Pickups (pass puppies) rows they hide or show everything below them, on a zone its colour and on a network its nodes and links (preview_state sections reports them); isolate works on world objects only (zones, networks, units and pickups are refused). select shares scene inspection and draft guards; selecting a zone, network or definition ends the object selection and opens its card in the Properties pane (a network is shown and emphasised, a definition's bound objects outlined; drafts target section), and properties also focuses the card's first field. Runtime parenting is not represented.", true, + [DocumentParameter, P("action", "string", "Tree action; default read. Properties focuses the source-object card; other viewers open the same pinned window as the row context menu. hide/show (source maps) change only what the view draws; isolate (source maps) shows only the row's object, or everything again on the isolated row, as a middle-click on its eye. frame (source maps: the Pickups section's Weapons, Ammo and Other rows and their type rows, and animation definition and binding rows) frames their pickups on the shown difficulty, or what a definition or binding binds to (the row's Frame bound objects), without selecting anything, as the row's Frame button; a definition bound only to templates (nodes no World tree row lists) or to nothing is refused (not_ready: nothing it binds to is drawn in the view). frame on a valve row selects the valve (its route nodes are ringed) and frames its placed vehicles and targets, else those nodes, as its Frame button.", false, "read", "expand", "collapse", "reveal", "select", "properties", "hide", "show", "isolate", "frame", "animationUses"), P("search", "string", "Source maps: search across the whole hierarchy (read without row): every word must appear, ignoring case, in a row's name (a pickup's also in its manual and catalog names, kind, template and game name; a definition's also in its NAME, target, file, bindings' names and objects, and how it starts: opening, load, startup, damage, hit, called, game, no caller); results are flat rows with path; a definition's say what matched (matchedBy: name, rootName, target, file, binding, start, in that order) and the note its result shows (what matched when not its name or target, else its file)."), - P("types", "string", "Source maps: comma-separated categories the flat read includes (group, geometry, empty, object, node, zone, network, definition); default all."), + P("types", "string", "Source maps: comma-separated categories the flat read includes (group, geometry, empty, object, node, zone, network, valve, definition); default all."), P("context", "string", "Current hierarchy context from read; required for all actions and row queries."), P("preview", "string", "Current preview ID from read; required for actions on a preview hierarchy."), P("row", "string", "Opaque row ID for child queries or actions."), new("node", "integer", "Scene node index or signed selectionOwner for reveal/select/properties instead of row, scoped to the current hierarchy.", Minimum: int.MinValue, Maximum: int.MaxValue), .. PageParameters], async (a, token) => @@ -398,7 +398,18 @@ private void RegisterSceneTreeCommand(StudioCommands commands) if (!TryFrameAnimationRow(row)) throw new StudioCommandException("not_ready", $"Nothing this {what} binds to is shown in the view to frame."); return Result(new { context = sceneTree.Context, document = doc.SessionId, revision = doc.Revision, row = DescribeTreeRow(row) }); } - if (row.PickupEntries == null) throw new StudioCommandException("invalid_argument", "frame works on the Pickups section's group and type rows and on animation definition and binding rows; select other rows and frame the selection with camera."); + if (row.Section is ValveEntry) + { + // A valve's Frame, as its row's button: the valve is selected (its route nodes are ringed), then its + // placed vehicles and targets are framed, else those nodes. + if (!row.CanFrame) throw new StudioCommandException("not_ready", "This valve has no route node, vehicle or target on the map to frame."); + if (TreeViewport is { } valveView && (valveView.IsPickupDragging || valveView.IsFlyActive)) throw new StudioCommandException("busy", "Finish the pickup drag or exit Fly before framing."); + // Selecting replaces the shown card: a pending draft is refused first, as for select. + if (sceneTree.Selected != row) { RequireNoSelectionDrafts(doc); SelectSectionRow(row); } + if (!TryFrameSection(row)) throw new StudioCommandException("not_ready", "None of this valve's route nodes, vehicles or targets is shown in the view to frame."); + return Result(new { context = sceneTree.Context, document = doc.SessionId, revision = doc.Revision, row = DescribeTreeRow(row) }); + } + if (row.PickupEntries == null) throw new StudioCommandException("invalid_argument", "frame works on the Pickups section's group and type rows, on animation definition and binding rows and on valve rows; select other rows and frame the selection with camera."); if (!row.CanFrame) throw new StudioCommandException("invalid_argument", row.PickupEntries.Count == 0 ? row.FrameToolTip + "." : "Its pickups are placed only on other difficulties; choose one of them (scene_options difficulty) to frame them."); if (TreeViewport is { } framing && (framing.IsPickupDragging || framing.IsFlyActive)) throw new StudioCommandException("busy", "Finish the pickup drag or exit Fly before framing."); if (!TryFrameSection(row)) throw new StudioCommandException("not_ready", "None of these pickups is shown in the view to frame: show them (hide/show) first."); @@ -472,7 +483,7 @@ private void RegisterSceneTreeCommand(StudioCommands commands) string search = Text(a, "search").Trim(); if (search.Length > 256) throw new StudioCommandException("invalid_argument", "Search text is limited to 256 characters."); var types = a["types"] == null ? OutlinerKinds.Categories.ToHashSet() : Text(a, "types").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToHashSet(); - if (types.Count == 0 || types.Any(t => !OutlinerKinds.Categories.Contains(t))) throw new StudioCommandException("invalid_argument", "types lists group, geometry, empty, object, node, zone, network and/or definition."); + if (types.Count == 0 || types.Any(t => !OutlinerKinds.Categories.Contains(t))) throw new StudioCommandException("invalid_argument", "types lists group, geometry, empty, object, node, zone, network, valve and/or definition."); var hits = OutlinerMatches(sceneTree, search, types, 10_000, out bool truncated); string[] words = SceneTreeItem.SearchWords(search); // A definition says which of its fields matched (name, rootName, target, file, binding, start), as its result's note does. diff --git a/src/zStudio.Desktop/MainWindow.SceneTreeLayout.cs b/src/zStudio.Desktop/MainWindow.SceneTreeLayout.cs index a99966e1..340c621e 100644 --- a/src/zStudio.Desktop/MainWindow.SceneTreeLayout.cs +++ b/src/zStudio.Desktop/MainWindow.SceneTreeLayout.cs @@ -103,6 +103,13 @@ void Level(IReadOnlyList rows, string parent) try { SelectSectionRow(section, restoring: true); } catch (zStudio.Automation.StudioCommandException) { } } + // A valve just added or renamed is selected in the tree that now lists it. + if (rememberedValve is { } named && tree.FindSection("valve:" + named) is { IsSectionItem: true } valveRow) + { + rememberedValve = null; + try { SelectSectionRow(valveRow); } + catch (zStudio.Automation.StudioCommandException) { } + } if (anchor != null && tree.Selected == null) ScheduleSceneTreeReveal(anchor); } } diff --git a/src/zStudio.Desktop/MainWindow.SourceEditor.cs b/src/zStudio.Desktop/MainWindow.SourceEditor.cs index 114731ef..70564265 100644 --- a/src/zStudio.Desktop/MainWindow.SourceEditor.cs +++ b/src/zStudio.Desktop/MainWindow.SourceEditor.cs @@ -351,7 +351,7 @@ private void ApplyCardDocking() // In Animation mode the opened definition's events naming the object come first (design §11); the player tank's // sections next; every object card, the tank's too, ends with the animations affecting it. card.LeadingSections = selected => EventsNamingObject(viewport, selected); - card.ExtraSections = selected => PlayerTankSections(viewport, selected); + card.ExtraSections = selected => ValveInspectionSections(viewport, selected) ?? PlayerTankSections(viewport, selected); card.TrailingSections = selected => AnimationObjectLinks(viewport, selected); card.PlayerTankSummary = PlayerTankRowSummary; card.PickPlayerTank = PickPlayerTank; @@ -672,6 +672,8 @@ internal bool TryFrameSection(SceneTreeItem row) return row.Section switch { NetworkEntry network => viewport.TryFrameAiNetwork(network.Network.Id), + // A valve: its placed vehicles and targets, else its route nodes (ringed while it is selected). + ValveEntry valve => FrameValve(viewport, valve.Valve), // What the World tree lists of what it binds to (a template the build loads but never places has no row to frame). DefinitionEntry definition => viewport.FrameAnimationPaths(definition.Definition.Index.ToString(CultureInfo.InvariantCulture)) || sceneTree?.Sections?.DefinitionRoots.GetValueOrDefault(definition.Definition.Index) is { } roots && roots.Where(r => sceneTree.Projection?.IsListed(r) != false).Take(4096).ToArray() is { Length: > 0 } listed && viewport.TryFrameNodes(listed), @@ -680,6 +682,13 @@ internal bool TryFrameSection(SceneTreeItem row) }; } + private bool FrameValve(SceneViewport viewport, zStudio.Core.Mw3ValveInfo valve) + { + int[] actors = [.. ValveActorNodes(viewport, valve).Take(4096)]; + if (actors.Length > 0 && viewport.TryFrameNodes(actors)) return true; + return viewport.ValveFilter == valve.Name && viewport.FrameValveAssociations(); + } + // Hide in viewport: presentation only, never a source edit. private async void OutlinerEyeClick(object sender, RoutedEventArgs e) { diff --git a/src/zStudio.Desktop/MainWindow.SourceSections.cs b/src/zStudio.Desktop/MainWindow.SourceSections.cs index 27bdc1f0..52a26cbb 100644 --- a/src/zStudio.Desktop/MainWindow.SourceSections.cs +++ b/src/zStudio.Desktop/MainWindow.SourceSections.cs @@ -129,9 +129,12 @@ private void RefreshAnimationTreeMarks() int[] rows = [.. definition.Entries.Select(e => bindingRows.TryGetValue(e, out int row) ? row : (int?)null).OfType().Distinct()]; if (rows.Length > 0) definitionRoots[definition.Index] = rows; } + // An MW3 mission's valves, one per name over every file that mentions it. + (Mw3ValveMap Map, Mw3ValveCatalog Catalog)? valves = snapshot.Game == GameVariant.MechWarrior3 ? BuildValveMap(snapshot, mission) : null; SourceMapSections sections = new() { Mission = session.Mission, Zones = zones, NoZonePolygons = none, Networks = mission?.AiNetworks.Networks ?? [], + ValveSource = valves != null ? ValveDefinitionSource(snapshot) : null, ValveMap = valves?.Map, ValveCatalog = valves?.Catalog, Definitions = snapshot.AnimationDefinitions, DefinitionRoots = definitionRoots, BindingRows = bindingRows, }; mapSections.AddOrUpdate(data, sections); @@ -313,6 +316,37 @@ private void ApplySectionPresentation() } finally { applyingSectionPresentation = sectionPresentationAgain = false; } } + /// The selected valve's highlight is on in the view (it ends with the selection). + private bool valveHighlightShown; + /// The placed vehicles and targets a valve names: those whose triggers or health set it and those its reactions act on. + private IEnumerable ValveActorNodes(SceneViewport viewport, Mw3ValveInfo valve) + { + if (viewport.Mission is not { } mission) return []; + // Found once per shown mission and valve: the presentation pass asks again at every refresh. + if (ReferenceEquals(valveNodes.Mission, mission) && ReferenceEquals(valveNodes.Valve, valve)) return valveNodes.Nodes; + HashSet names = new(valve.SetBy.Concat(valve.UsedBy).Select(l => l.Actor).OfType(), StringComparer.Ordinal); + foreach (var reaction in valve.Reactions) if (reaction.Spec.Kind is not ("sound" or "sound_once" or "animation" or "animation_once" or "update" or "delayupdate") && reaction.Spec.Target is { } target) names.Add(target); + int[] nodes = [.. ValveNamedNodes(mission, names)]; + valveNodes = (mission, valve, nodes); + return nodes; + } + private (MissionSceneContext? Mission, Mw3ValveInfo? Valve, int[] Nodes) valveNodes = (null, null, []); + /// + /// The scene nodes the mission's files name as vehicles and targets: a placed vehicle's root (aiv.zrd), and a target + /// (targets.zrd names a scene node, such as a dish) where exactly one node has that name. + /// + private static IEnumerable ValveNamedNodes(MissionSceneContext mission, IReadOnlySet names) + { + if (names.Count == 0) return []; + HashSet found = []; HashSet placed = new(StringComparer.Ordinal); + foreach (var actor in mission.Actors) if (names.Contains(actor.Name)) { found.Add(actor.Root); placed.Add(actor.Name); } + if (placed.Count == names.Count) return found; + Dictionary unique = new(StringComparer.Ordinal); + foreach (var node in mission.Scene.Nodes) + if (names.Contains(node.Name) && !placed.Contains(node.Name)) unique[node.Name] = unique.ContainsKey(node.Name) ? -1 : node.Index; + foreach (int node in unique.Values) if (node >= 0) found.Add(node); + return found; + } private void ApplySectionPresentationOnce() { { @@ -342,6 +376,15 @@ private void ApplySectionPresentationOnce() int[] outlined = InAnimationMode && animationGraphOutline is { } named ? [.. named.Take(SceneViewport.MaximumOutlinedNodes)] : SectionSelection?.Section is DefinitionEntry definition && sceneTree?.Sections?.DefinitionRoots.GetValueOrDefault(definition.Definition.Index) is { } roots ? [.. roots.Take(SceneViewport.MaximumOutlinedNodes)] : []; + // A selected valve: the route nodes that set it or wait on it are ringed, and its vehicles and targets outlined. + var selectedValve = (SectionSelection?.Section as ValveEntry)?.Valve; + if (selectedValve != null) + { + if (!viewport.ValveOverlayVisible || viewport.ValveFilter != selectedValve.Name) viewport.SetValveOptions(true, selectedValve.Name); + valveHighlightShown = true; + if (!InAnimationMode) outlined = [.. ValveActorNodes(viewport, selectedValve).Take(SceneViewport.MaximumOutlinedNodes)]; + } + else if (valveHighlightShown) { valveHighlightShown = false; viewport.SetValveOptions(AiValveOverlay.IsChecked == true, null); } if (!outlined.SequenceEqual(viewport.OutlinedNodes)) viewport.SetOutlinedNodes(outlined); RefreshRowEyes(); RefreshViewportChips(); RefreshAnimationOverlay(); } @@ -615,6 +658,14 @@ private void SelectSectionRow(SceneTreeItem row, bool restoring = false) case DefinitionEntry definition: ViewModel.Status = $"Selected animation definition {definition.Definition.Name}"; break; + // Selecting a valve shows the networks it gates or is set on, so its nodes can be seen. + case ValveEntry valve: + ResetSectionStateFor(shownDocument); + foreach (string network in valve.Valve.SetBy.Concat(valve.Valve.UsedBy).Select(l => l.Network).OfType().Distinct(StringComparer.OrdinalIgnoreCase).Take(64)) + if (scene?.AiNetworks.Networks.FirstOrDefault(n => n.Id.Equals(network, StringComparison.OrdinalIgnoreCase)) is { } shown) shownNetworks.Add(shown.Id); + ReconcileMasters(); + ViewModel.Status = $"Selected valve {JsonData.ShownText(valve.Valve.Name, 64)}"; + break; } ShowSectionCard(row); ApplySectionPresentation(); @@ -662,6 +713,19 @@ private SourceSectionCard SectionCard() if (sectionCard.Document is not { IsDisposed: false } doc) throw new StudioCommandException("stale_document", "The map was closed."); await EditNetworkAsync(LiveDocument(doc), network, changes, CancellationToken.None, committingSection: true, links: links); }; + sectionCard.ApplyValve = async (name, changes) => + { + if (sectionCard.Document is not { IsDisposed: false } doc) throw new StudioCommandException("stale_document", "The map was closed."); + await EditValveAsync(LiveDocument(doc), name, changes, CancellationToken.None, committingSection: true); + // Once the card has accepted its draft it shows the valve as stored now (its reactions are found by their place in + // the file, so a card kept from before the edit must not be edited again). + _ = Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, () => { if (SectionSelection is { Section: ValveEntry } row) ShowSectionCard(row); }); + }; + sectionCard.ValveLinkInvoked = FollowValveLink; + sectionCard.ValveInvoked = name => SelectValve(name); + sectionCard.ValveCommand = ValveCardCommand; + sectionCard.ValveTest = BuildValveTestPanel; + sectionCard.ValveFire = ValveFireFor; sectionCard.ApplyAnimation = async (definition, changes) => { if (sectionCard.Document is not { IsDisposed: false } doc) throw new StudioCommandException("stale_document", "The map was closed."); @@ -704,6 +768,8 @@ private void ShowSectionCard(SceneTreeItem row) var card = SectionCard(); switch (row.Section) { + case ValveEntry valve: + card.ShowValve(doc, valve, ValveCardContextOf(doc, valve.Valve)); break; case AnimationBindingEntry: _ = ReportUi(() => ShowWorldAnimationTreeCardAsync(doc, row)); break; @@ -845,11 +911,13 @@ private static JsonObject NetworkFields(zStudio.Core.Formats.ZrdNode? source) SectionHeader { Section: "zones" } => new { section = "zones", master = MasterShown("zones"), shown = shownZones.Count, overlay = new { visible = ZoneOverlayOn, kind = (ZoneOverlayOn ? worldHighlightMode : zoneOverlayKind) == WorldHighlightMode.PolygonZones ? "polygons" : "objects", paused = ZoneToolEngaged } }, SectionHeader { Section: "aiNetworks" } => new { section = "aiNetworks", master = MasterShown("aiNetworks"), shown = shownNetworks.Count, ai = new { visible = aiVisible } }, + SectionHeader { Section: "valves" } => new { section = "valves", count = row.Owner.Sections?.ValveMap?.Valves.Count ?? 0, source = row.Owner.Sections?.ValveSource, testing = ValveTesting }, SectionHeader header => new { section = header.Section }, ZoneEntry zone => new { zoneId = zone.Zone.Zone, label = zone.Zone.Label is { } text ? JsonData.ShownText(text, 256) : null, polygons = zone.Zone.Polygons, placements = zone.Zone.Placements, models = zone.Zone.Models, objects = zone.Zone.Objects, ownObjects = zone.Zone.OwnObjects, inheritedObjects = zone.Zone.InheritedObjects, emptyObjects = zone.Zone.EmptyObjects, used = zone.Zone.Used, shown = shownZones.Contains(zone.Zone.Zone) }, NoZonesEntry none => new { noZones = true, polygons = none.Polygons }, NetworkEntry network => new { network = network.Network.Id, name = JsonData.ShownText(network.Network.Name, 256), nodes = network.Network.Nodes.Count, attackStrategy = DescribeAiStrategy(network.Network), diagnosticCount = network.Network.Diagnostics.Count, shown = shownNetworks.Contains(network.Network.Id) }, + ValveEntry valve => DescribeValveRow(valve.Valve), DefinitionScopeEntry scope => new { definitionScope = scope.Name, folder = scope.Folder, definitions = scope.Count, affectsSelection = row.HoldsBoundMark ? true : (bool?)null }, DefinitionGroupEntry group => new { kind = "definitionGroup", scope = group.Scope, start = AnimationTreeSummary.Key(group.Start), label = AnimationTreeSummary.Label(group.Start), count = group.Definitions.Count, affectsSelection = row.HoldsBoundMark ? true : (bool?)null }, diff --git a/src/zStudio.Desktop/MainWindow.ValveAuthoring.cs b/src/zStudio.Desktop/MainWindow.ValveAuthoring.cs new file mode 100644 index 00000000..11d2c25e --- /dev/null +++ b/src/zStudio.Desktop/MainWindow.ValveAuthoring.cs @@ -0,0 +1,463 @@ +using System.IO; +using System.Text.Json.Nodes; +using System.Windows; +using zStudio.Automation; +using zStudio.Core; +using zStudio.Core.Formats; +using zStudio.Core.Sources; + +namespace zStudio.Desktop; + +/// +/// MW3 valves in a source map (design/mw3-valves-ui.md): the mission's valves by name, their card's edits and the tree's +/// commands, shared by the GUI and MCP source_ai_valve. +/// +public partial class MainWindow +{ + private static string ValveDefinitionSource(SourceSceneSnapshot source) => source.Resources.Values.FirstOrDefault(r => + Path.GetFileName(r.Path).Equals("valves.zrd", StringComparison.OrdinalIgnoreCase))?.Path ?? + (source.SourceMission ?? $"data/{source.Mission}/zrdr") + "/valves.zrd"; + private SourceSceneSnapshot ValveSource(DocumentModel document) + { + if (document != shownDocument || document.Document is not SourceSceneSnapshot { Game: GameVariant.MechWarrior3 } source || document.SourceWorld == null) + throw new StudioCommandException("unsupported", "Open an MW3 source map and select its mission first."); + return source; + } + /// The mission's valves by name and what its reactions can name: its vehicles and targets, and its animations. + private static (Mw3ValveMap Map, Mw3ValveCatalog Catalog) BuildValveMap(SourceSceneSnapshot snapshot, MissionSceneContext? mission, CancellationToken token = default) + { + var sources = snapshot.Resources.Values.Where(r => r.Root != null && MissionAiValves.IsResource(Path.GetFileName(r.Path))).Select(r => new Mw3ValveSource(r.Path, r.Root!)).ToArray(); + HashSet vehicles = new(StringComparer.Ordinal); + foreach (var actor in mission?.Actors ?? []) vehicles.Add(actor.Name); + // A target is named by targets.zrd; a vehicle the shown difficulty leaves out is still one of the mission's. + foreach (var source in sources.Where(s => Path.GetFileName(s.Path) is var name && (name.Equals("targets.zrd", StringComparison.OrdinalIgnoreCase) || name.Equals("aiv.zrd", StringComparison.OrdinalIgnoreCase)))) + { + var fields = MissionAiValves.Fields(source.Root).Children; + for (int i = 0; i + 1 < fields.Count; i += 2) if (fields[i].Kind == ZrdKind.String && fields[i + 1].Kind == ZrdKind.Array) vehicles.Add(fields[i].Text); + } + HashSet? animations = snapshot.Animations is { } package ? new(package.Entries.Where(e => e.Index > 0).Select(e => e.Name), StringComparer.Ordinal) : null; + Mw3ValveCatalog catalog = new(vehicles, null, animations); + string? folder = snapshot.SourceMission is { } path ? Path.GetFileName(path) : null; + // The animations that set a valve through callbacks 42–49, from the entries' events and the roots they bind to. + var callbacks = snapshot.Animations is { } loaded && mission != null ? Mw3ValveSimulation.CallbackValves(loaded, mission, token) : null; + return (Mw3ValveMap.Build(sources, folder, catalog, token, callbacks), catalog); + } + /// The shown map's valves (the World tree's, built once per shown mission). + private (Mw3ValveMap Map, Mw3ValveCatalog? Catalog) ValveMapOf(DocumentModel document) + { + var source = ValveSource(document); + if (sceneTreeDocument == document && sceneTree?.Sections is { ValveMap: { } map } sections) return (map, sections.ValveCatalog); + var built = BuildValveMap(source, scene?.Mission); + return (built.Map, built.Catalog); + } + private static string? ValveMissionFolder(SourceSceneSnapshot source) => source.SourceMission is { } path ? Path.GetFileName(path) : null; + + /// Applies a valve's changes to valves.zrd as one undoable change (the card's Apply and MCP set alike). + private async Task EditValveAsync(DocumentModel document, string name, SourceValveEdits.ValveChanges changes, CancellationToken token, bool committingSection = false) + { + RequireNoDrafts(document, committing: true, committingSection: committingSection); + var source = ValveSource(document); + string path = ValveDefinitionSource(source); + var resource = source.Resources.Values.SingleOrDefault(r => r.Path.Equals(path, StringComparison.OrdinalIgnoreCase)); + if (resource is { Root: null }) throw new StudioCommandException("invalid_argument", "valves.zrd could not be read; the map's notes say why. Correct it in a text editor first."); + EndValveTest(); + try + { + return await PrepareSourceWorldEditAsync(document, "Editing valve", (workspace, ct) => + { + byte[]? bytes = workspace.Read(path, ct); + if (bytes == null && resource != null) throw new StudioCommandException("stale_record", "valves.zrd is no longer in the project."); + if (bytes != null && resource == null) throw new SourceFileChangedException("valves.zrd appeared; reload the mission before editing valves.", [path]); + SourceValveEdits.Edit plan; + try { plan = SourceValveEdits.PlanValve(bytes, name, changes, ct); } + catch (InvalidDataException ex) { throw new StudioCommandException("invalid_argument", ex.Message); } + catch (InvalidOperationException) { throw new StudioCommandException("unchanged", "Nothing changed."); } + return workspace.Apply(plan.Label, [(path, (byte[]?)plan.Content)], ct); + }, token, committingSection: committingSection); + } + catch (StudioCommandException ex) when (ex.Code == "unchanged") { return document; } + } + /// Renames a valve in every file of the mission that names it: one undoable change. + private async Task RenameValveAsync(DocumentModel document, string name, string renamed, CancellationToken token) + { + RequireNoDrafts(document); + var source = ValveSource(document); + var (map, _) = ValveMapOf(document); + if (map.Find(name) is not { } renaming) throw new StudioCommandException("stale_record", "The mission has no valve of that name. Read its valves again."); + if (renamed == name) return document; + if (ValveRenameRefusal(renaming) is { } refusal) throw new StudioCommandException("unsupported", refusal); + if (map.Find(renamed) != null) throw new StudioCommandException("invalid_argument", $"The mission already has a valve named {JsonData.ShownText(renamed, 64)}."); + string? mission = ValveMissionFolder(source); + // Every file that names it must be a text source: a rename that skipped a binary one would split the valve in two. + if (source.Resources.Values.FirstOrDefault(r => r is { Root: not null, Syntax: null } && MissionAiValves.IsResource(Path.GetFileName(r.Path)) + && MissionAiValves.Records(Path.GetFileName(r.Path), r.Root, token).Any(record => MissionAiValves.References(record, token).Any(reference => reference.Name == name))) is { } binary) + throw new StudioCommandException("unsupported", $"{Path.GetFileName(binary.Path)} names this valve and is stored as binary zReader data, so the valve can be renamed only in text sources."); + string[] paths = [.. source.Resources.Values.Where(r => r.Syntax != null && MissionAiValves.IsResource(Path.GetFileName(r.Path))).Select(r => r.Path)]; + EndValveTest(); + rememberedValve = renamed; + try + { + return await PrepareSourceWorldEditAsync(document, "Renaming valve", (workspace, ct) => + { + List<(string, byte[]?)> files = []; + foreach (string path in paths) + { + if (workspace.Read(path, ct) is not { } bytes) continue; + try { if (SourceValveEdits.PlanRename(Path.GetFileName(path), bytes, name, renamed, mission, ct) is { } edit) files.Add((path, edit.Content)); } + catch (InvalidDataException ex) { throw new StudioCommandException("invalid_argument", ex.Message); } + } + if (files.Count == 0) throw new StudioCommandException("stale_record", "No text source of the mission names this valve."); + return workspace.Apply($"Rename valve {MissionAiValves.Short(name, 48)}", files, ct); + }, token); + } + catch { rememberedValve = null; throw; } + } + /// Deletes a valve's valves.zrd records: one undoable change. Other files keep naming it. + private async Task RemoveValveAsync(DocumentModel document, string name, CancellationToken token) + { + RequireNoDrafts(document); + var source = ValveSource(document); + string path = ValveDefinitionSource(source); + if (ValveMapOf(document).Map.Find(name) is not { Defined: true }) throw new StudioCommandException("stale_record", "valves.zrd has no record of that valve. Read the mission's valves again."); + EndValveTest(); + return await PrepareSourceWorldEditAsync(document, "Deleting valve", (workspace, ct) => + { + byte[] bytes = workspace.Read(path, ct) ?? throw new StudioCommandException("stale_record", "valves.zrd is no longer in the project."); + try { var plan = SourceValveEdits.PlanRemove(bytes, name, ct); return workspace.Apply(plan.Label, [(path, (byte[]?)plan.Content)], ct); } + catch (InvalidDataException ex) { throw new StudioCommandException("invalid_argument", ex.Message); } + }, token); + } + /// A new valve: a valves.zrd record that starts at 0 (a name other files already mention gets its first record). + private async Task NewValveAsync(DocumentModel document, string name, CancellationToken token) + { + if (ValveNameProblem(document, name, creating: true) is { } problem) throw new StudioCommandException("invalid_argument", problem); + rememberedValve = name; + try { return await EditValveAsync(document, name, new(Initial: "0"), token); } + catch { rememberedValve = null; throw; } + } + /// + /// An animation sets the valve named as the scene node it binds (callbacks 42–49): renaming the valve in the mission's + /// files would leave the animation setting the old name, so the rename is refused. + /// + private static string? ValveRenameRefusal(Mw3ValveInfo valve) => valve.SetBy.FirstOrDefault(l => l.Role == "animation") is { } animation + ? $"The animation {JsonData.ShownText(animation.Owner, 64)} sets this valve through the scene node named {JsonData.ShownText(valve.Name, 64)}, so the valve keeps that node's name. Renaming it would disconnect the animation." + : null; + private string? ValveNameProblem(DocumentModel document, string name, bool creating, string? current = null) + { + if (name.Length == 0) return "Enter a name."; + if (name.Length > 256) return "At most 256 characters."; + if (name != name.Trim()) return "No spaces around the name."; + if (name.Any(char.IsControl) || name.Contains('"')) return "No quotes or control characters."; + if (name == current) return null; + var existing = ValveMapOf(document).Map.Find(name); + if (creating ? existing is { Defined: true } : existing != null) return "The mission already has a valve of that name."; + return null; + } + /// A valve just added or renamed: the rebuilt map's tree selects it (). + private string? rememberedValve; + /// Selects a valve's row by name (a link on a card, a new or renamed valve); false when the mission has none. + private bool SelectValve(string name) + { + if (sceneTree?.FindSection("valve:" + name) is not { } row) { ViewModel.Status = $"This mission has no valve named {JsonData.ShownText(name, 64)}."; return false; } + if (sceneTree.Selected == row) return true; + if (!ResolveSelectionDrafts(sceneTreeDocument)) return false; + try { SelectSectionRow(row); return true; } + catch (StudioCommandException ex) { Report(ex); return false; } + } + /// A Set by or Used by link: the vehicle or target, the route node (its network shown), or the other valve. + private void FollowValveLink(Mw3ValveLink link) + { + if (link.Valve != null) { SelectValve(link.Valve); return; } + if (link.Entry is int entry) + { + // The animation's definition row (its card has Open in Animation mode). + var definition = sceneTree?.Sections?.Definitions.Definitions.FirstOrDefault(d => d.Entries.Contains(entry)); + var row = definition == null ? null : sceneTree!.FindSection($"definition:{definition.File}#{definition.Ordinal.ToString(System.Globalization.CultureInfo.InvariantCulture)}@0"); + if (row == null) { ViewModel.Status = $"The World tree does not list the animation {JsonData.ShownText(link.Owner, 64)}."; return; } + if (!ResolveSelectionDrafts(sceneTreeDocument)) return; + try { SelectSectionRow(row); } + catch (StudioCommandException ex) { Report(ex); } + return; + } + if (scene is not { } viewport || !ResolveSelectionDrafts(sceneTreeDocument)) return; + try + { + if (link.Actor != null) + { + // A placed vehicle, or a target's scene node (targets.zrd names one, such as a dish). + int[] named = viewport.Mission is { } mission ? [.. ValveNamedNodes(mission, new HashSet(StringComparer.Ordinal) { link.Actor })] : []; + if (named.Length != 1 || sceneTree?.Reveal(named[0]) is not { Selectable: true } row) + { ViewModel.Status = named.Length > 1 ? $"Several placed vehicles are named {JsonData.ShownText(link.Actor, 64)}; select one in the World tree." : $"{JsonData.ShownText(link.Actor, 64)} is not on the map at the shown difficulty."; return; } + SelectSceneTreeRow(row); RunCameraNavigation("frameSelected"); + } + else if (link is { Network: { } network, Node: int index } && viewport.AiNetworks.Networks.FirstOrDefault(n => n.Id.Equals(network, StringComparison.OrdinalIgnoreCase)) is { } found + && found.Nodes.FirstOrDefault(n => n.Index == index) is { } node) + { + ResetSectionStateFor(shownDocument); shownNetworks.Add(found.Id); ReconcileMasters(); ApplySectionPresentation(); + ClearSectionSelection(); + if (viewport.SelectAiNode(node.Id)) RunCameraNavigation("frameSelected"); + } + } + catch (StudioCommandException ex) { Report(ex); } + } + + // ---------------------------------------------------------------- the tree's commands + + private void SceneNewValveClick(object sender, RoutedEventArgs e) + { + if (sceneContextDocument is not { IsDisposed: false } doc || doc != shownDocument) return; + string? name = PromptName("New valve", "A valve is a named switch of this mission. It starts at 0; add what sets it and its reactions on its card.", "", "Add valve", n => ValveNameProblem(doc, n, creating: true)); + if (name != null) _ = ReportUi(() => NewValveAsync(LiveDocument(doc), name, CancellationToken.None)); + } + private void SceneRenameValveClick(object sender, RoutedEventArgs e) { if (contextScene?.Section is ValveEntry valve) ValveCardCommand("rename", valve.Valve.Name); } + private void SceneDeleteValveClick(object sender, RoutedEventArgs e) { if (contextScene?.Section is ValveEntry valve) ValveCardCommand("delete", valve.Valve.Name); } + private void SceneCopyValveNameClick(object sender, RoutedEventArgs e) + { + if (contextScene?.Section is not ValveEntry valve) return; + try { Clipboard.SetText(valve.Valve.Name); ViewModel.Status = "Copied the valve's name."; } + catch (System.Runtime.InteropServices.COMException) { ViewModel.Status = "The clipboard is busy; try again."; } + } + private void SceneValveTestClick(object sender, RoutedEventArgs e) => ToggleValveTest(); + private void OutlinerValveTestClick(object sender, RoutedEventArgs e) { e.Handled = true; ToggleValveTest(); } + /// Rename… and Delete from a valve's card or row. + private void ValveCardCommand(string command, string name) + { + if (shownDocument is not { IsDisposed: false } doc || doc.SourceWorld == null || !ResolveSelectionDrafts(doc)) return; + if (command == "rename") + { + if (sceneTree?.Sections?.ValveMap?.Find(name) is { } current && ValveRenameRefusal(current) is { } refusal) + { MessageBox.Show(this, refusal, "Rename valve", MessageBoxButton.OK, MessageBoxImage.Information); return; } + string? renamed = PromptName("Rename valve", $"Rename {JsonData.ShownText(name, 64)} in every file of the mission that names it: its records, vehicle triggers, routes, other valves and this mission's objectives.", + name, "Rename", n => ValveNameProblem(doc, n, creating: false, current: name)); + if (renamed != null && renamed != name) _ = ReportUi(() => RenameValveAsync(LiveDocument(doc), name, renamed, CancellationToken.None)); + } + else if (command == "delete") + { + var info = sceneTree?.Sections?.ValveMap?.Find(name); + int others = (info?.SetBy.Count ?? 0) + (info?.UsedBy.Count ?? 0); + var answer = MessageBox.Show(this, $"Delete the valves.zrd records of {JsonData.ShownText(name, 64)}?\n\nIts reactions and starting value go." + + (others > 0 ? $" {others} other place{(others == 1 ? " still names" : "s still name")} it; the game then makes it at 0 with no reactions." : ""), + "Delete valve", MessageBoxButton.OKCancel, MessageBoxImage.Warning, MessageBoxResult.Cancel); + if (answer == MessageBoxResult.OK) _ = ReportUi(() => RemoveValveAsync(LiveDocument(doc), name, CancellationToken.None)); + } + } + /// What the valve card shows beside the valve: the names for its pickers, its records as stored, and why it cannot edit. + private SourceSectionCard.ValveCardContext ValveCardContextOf(DocumentModel doc, Mw3ValveInfo valve) + { + var sections = sceneTree?.Sections; var snapshot = doc.Document as SourceSceneSnapshot; + var map = sections?.ValveMap ?? Mw3ValveMap.Empty; + List<(string, string?)> source = []; + foreach (var record in valve.Records.Take(16)) + { + var resource = snapshot?.Resources.Values.FirstOrDefault(r => r.Path.Equals(record.Source, StringComparison.OrdinalIgnoreCase)); + var body = resource?.Root != null ? MissionAiValves.Fields(resource.Root).Children : []; + int at = -1; + for (int i = 0; i + 1 < body.Count; i += 2) if (body[i].Id == record.Record) { at = i; break; } + if (at < 0) continue; + string text = resource!.Syntax is { } syntax && syntax.TryGetSpan(body[at].Id, out var key) && syntax.TryGetSpan(body[at + 1].Id, out var value) && value.End - key.Start <= 4096 + ? syntax.Text.Substring(key.Start, value.End - key.Start) : JsonData.ShownText(ZrdText.Write(body[at + 1], default, 4096), 4096); + source.Add((text, record.Problem)); + } + string path = snapshot != null ? ValveDefinitionSource(snapshot) : ""; + var definitions = snapshot?.Resources.Values.FirstOrDefault(r => r.Path.Equals(path, StringComparison.OrdinalIgnoreCase)); + string? readOnly = definitions is { Root: null } ? "valves.zrd could not be read, so valves are not edited here; the map's notes say why." + : definitions is { Syntax: null } ? "valves.zrd is stored as binary zReader data, so valves can be edited only in a text source." : null; + // The mission's sounds are not known without its sound banks: the picker offers the sounds its valves already play. + var catalog = sections?.ValveCatalog is { } known ? known with { Sounds = null } : null; + return new(map, catalog, source, readOnly); + } + + // ---------------------------------------------------------------- MCP + + private static object DescribeValveRow(Mw3ValveInfo valve) => new + { + kind = "valve", name = JsonData.ShownText(valve.Name, 256), nameCharacters = valve.Name.Length, defined = valve.Defined, computed = valve.Condition != null, + summary = JsonData.ShownText(valve.Summary, 256), setBy = valve.SetBy.Count, reactions = valve.Reactions.Count, usedBy = valve.UsedBy.Count, problems = valve.Problems.Count, + }; + private static JsonObject DescribeValveLink(Mw3ValveLink link) => new() + { + ["role"] = link.Role, ["source"] = link.Source, ["record"] = link.Record.ToString(), ["owner"] = JsonData.ShownText(link.Owner, 256), ["text"] = JsonData.ShownText(link.Text, 256), ["value"] = link.Value, + ["network"] = link.Network, ["node"] = link.Node, ["vehicle"] = link.Actor is { } actor ? JsonData.ShownText(actor, 256) : null, ["valve"] = link.Valve is { } other ? JsonData.ShownText(other, 256) : null, + ["animationEntry"] = link.Entry, + }; + private static JsonObject DescribeValveSpec(Mw3ValveReactionSpec spec) => new() + { + ["kind"] = spec.Kind, ["target"] = spec.Target is { } target ? JsonData.ShownText(target, 256) : null, ["operand"] = spec.Operand, ["when"] = spec.When, + ["x"] = spec.X, ["y"] = spec.Y, ["z"] = spec.Z, ["yaw"] = spec.Yaw, + }; + private static object DescribeValve(Mw3ValveInfo valve) => new + { + name = JsonData.ShownText(valve.Name, 256), nameCharacters = valve.Name.Length, defined = valve.Defined, initial = valve.Initial, condition = valve.Condition, + inputs = valve.Inputs.Take(64).Select(i => JsonData.ShownText(i, 256)).ToArray(), inputCount = valve.Inputs.Count, summary = JsonData.ShownText(valve.Summary, 256), + problems = valve.Problems.Select(p => JsonData.ShownText(p, 400)).ToArray(), + records = valve.Records.Take(64).Select(r => new { source = r.Source, record = r.Record, occurrence = r.Occurrence, problem = r.Problem }).ToArray(), recordCount = valve.Records.Count, + reactions = valve.Reactions.Take(64).Select(r => new JsonObject { ["occurrence"] = r.Occurrence, ["record"] = r.Record.ToString(), ["text"] = JsonData.ShownText(r.Text, 256), ["problem"] = r.Problem, ["fields"] = DescribeValveSpec(r.Spec) }).ToArray(), + reactionCount = valve.Reactions.Count, + setBy = valve.SetBy.Take(64).Select(DescribeValveLink).ToArray(), setByCount = valve.SetBy.Count, + usedBy = valve.UsedBy.Take(64).Select(DescribeValveLink).ToArray(), usedByCount = valve.UsedBy.Count, + }; + private static Mw3ValveReactionSpec ValveSpecArgument(JsonObject fields) => new(Text(fields, "kind"), fields["target"]?.GetValue(), Scalar(fields["operand"]), Scalar(fields["when"]), + Scalar(fields["x"]), Scalar(fields["y"]), Scalar(fields["z"]), Scalar(fields["yaw"])); + private static string? Scalar(JsonNode? node) => node is JsonValue value ? value.TryGetValue(out string? text) ? text : value.ToJsonString() : null; + private static SourceValveEdits.ValveChanges ValveChangesArgument(JsonObject args) + { + if (args["changes"] is not JsonObject changes) throw new StudioCommandException("invalid_argument", "Give the changes: initial, condition, inputs or reactions."); + var reactions = (changes["reactions"] as JsonArray ?? []).OfType().Select(r => new SourceValveEdits.ReactionChange(r["occurrence"]?.GetValue(), r["storedKind"]?.GetValue(), + r["remove"]?.GetValue() == true ? null : r["fields"] is JsonObject fields ? ValveSpecArgument(fields) : throw new StudioCommandException("invalid_argument", "A reaction needs fields, or remove: true."))).ToArray(); + if (reactions.Any(r => r.Occurrence != null && r.Kind == null)) throw new StudioCommandException("invalid_argument", "An existing reaction is named by occurrence and storedKind."); + return new(Scalar(changes["initial"]), changes["condition"]?.GetValue(), changes["inputs"] is JsonArray inputs ? [.. inputs.Select(i => i?.GetValue() ?? "")] : null, reactions); + } + + private void RegisterValveAuthoringCommands(StudioCommands registry) + { + StudioParameter reactionFields = new("fields", "object", "The reaction as the card shows it.", Properties: + [ + P("kind", "string", "The stored tag.", true, "sound", "sound_once", "animation", "animation_once", "shutdown", "destroy", "teleport", "setteam", "attack_strategy", "scan_aim", "scan_hit", "scan_time", "canleave", + "delayupdate", "update", "missionabort", "missionreset", "missioncomplete"), + P("target", "string", "The sound, animation, vehicle or valve it names (none for the mission reactions)."), + P("operand", "string", "shutdown: 0 wake, 1 power down; scans and canleave: 1 on, 0 off; setteam: the team; attack_strategy: the strategy; delayupdate: seconds."), + P("when", "string", "The valve value that triggers it, a whole number (not for update and delayupdate, which run on every change)."), + P("x", "string", "teleport: X."), P("y", "string", "teleport: Y."), P("z", "string", "teleport: Z."), P("yaw", "string", "teleport: heading."), + ]); + RegisterJob(registry, "source_ai_valve", "Read or edit the valves of the shown MW3 source mission. A valve is a named whole-number switch; the World tree's Valves section and its card show one per exact name, gathered from valves.zrd (starting value, computed condition, reactions), aiv.zrd vehicle triggers, targets.zrd health thresholds, the networks' route gates, assignments and deploy points, and this mission's objectives. valves pages them (name, summary, counts, problems); valve reads one (initial: the stored starting value, which a computed valve keeps but ignores; condition and inputs, reactions with their fields, setBy and usedBy links, records; setBy also lists the animations that set it through callbacks 42–49 on the scene node of its name, role animation with animationEntry). set applies the card's changes as one undoable change of valves.zrd that keeps comments, layout and unknown tags: initial; condition (any_nonzero, any_zero, all_nonzero, all_zero, or empty for a plain switch) with inputs; reactions, each an existing one by occurrence and storedKind (fields to change it, remove: true to remove it) or a new one (fields only; written as its own record after the valve's last). new adds a valve starting at 0; rename renames it in every file of the mission that names it (one change; refused for a valve an animation sets, which keeps its scene node's name); remove deletes its valves.zrd records. draft stages the same changes on the selected valve's card (Apply, Revert and resolve_drafts as for any card). Record level: sources, records, read, create, update, delete and attach edit one stored record or node attribute as zReader text. Test state is ai_valve_preview's and is never saved.", + [DocumentParameter, RevisionParameter with { Required = false }, P("action", "string", "Operation.", true, "valves", "valve", "set", "new", "rename", "remove", "draft", "sources", "records", "read", "create", "update", "delete", "attach"), + P("name", "string", "valve, set, new, rename, remove, draft: the exact case-sensitive valve name. create, update: the record's name."), P("newName", "string", "rename: the new name."), + new("changes", "object", "set, draft: what changes; omitted parts stay.", Properties: + [ + P("initial", "string", "The starting value, a whole number."), P("condition", "string", "Computed kind, or empty for a plain switch.", false, "", "any_nonzero", "any_zero", "all_nonzero", "all_zero"), + new("inputs", "array", "A computed valve's input valves, in order.", Items: new("", "string", "A valve name."), MaxItems: 256), + new("reactions", "array", "Reactions to change, remove or add.", Items: new("", "object", "One reaction.", Properties: + [ + new("occurrence", "integer", "An existing reaction's record occurrence (from valve); omit for a new one.", Minimum: 0, Maximum: int.MaxValue), + P("storedKind", "string", "An existing reaction's stored tag (from valve)."), P("remove", "boolean", "Remove this existing reaction."), reactionFields, + ]), MaxItems: 64), + ]), + P("source", "string", "Record level: exact relative source path from sources."), P("record", "string", "Record level: occurrence ID from records."), + P("nodeIndex", "integer", "attach: uniquely resolved spatial node number."), P("attribute", "string", "attach: node attribute.", false, "valve", "valveunion", "valve_assign"), + P("parameters", "string", "Record level: ordered zReader parameter array, at most 65,536 characters."), + P("draft", "string", "draft: the current card draft token when a draft is already open."), ..PageParameters], false, async (args, token) => + { + var document = TargetDocument(args); var source = ValveSource(document); string action = Text(args, "action"); + if (action is "valves" or "valve" or "set" or "new" or "rename" or "remove" or "draft") + { + var (map, _) = ValveMapOf(document); + if (action == "valves") return Page(map.Valves, args, v => v.Name, v => DescribeValveRow(v), matches: (v, query) => v.Name.Contains(query, StringComparison.OrdinalIgnoreCase) + || v.Summary.Contains(query, StringComparison.OrdinalIgnoreCase) || v.Mentions.Any(m => m.Contains(query, StringComparison.OrdinalIgnoreCase))); + string name = Text(args, "name"); + if (action == "valve") + return Result(new { document = DocumentState(document), source = ValveDefinitionSource(source), valve = DescribeValve(map.Find(name) ?? throw new StudioCommandException("stale_record", "The mission has no valve of that name.")), truncated = map.Truncated }); + if (args["revision"]?.GetValue() != document.Revision) throw new StudioCommandException("revision_conflict", "Read the current document revision."); + if (action == "draft") + { + if (sectionCard is not { ShownValve: { } shown } card || shown.Name != name || card.Document != document) throw new StudioCommandException("not_ready", "Select this valve's World tree row first."); + if (card.HasDraft) card.RequireDraft(Text(args, "draft")); + card.SetValveDraft(ValveChangesArgument(args)); + return Result(card.Describe()); + } + var next = action switch + { + "set" => await EditValveAsync(document, map.Find(name)?.Name ?? throw new StudioCommandException("stale_record", "The mission has no valve of that name; new adds one."), ValveChangesArgument(args), token), + "new" => await NewValveAsync(document, name, token), + "rename" => ValveNameProblem(document, Text(args, "newName"), creating: false, current: name) is { } problem ? throw new StudioCommandException("invalid_argument", problem) + : await RenameValveAsync(document, name, Text(args, "newName"), token), + _ => await RemoveValveAsync(document, name, token), + }; + return Result(new { document = DocumentState(next), name = action == "rename" ? Text(args, "newName") : name }); + } + if (action == "sources") + { + string proposed = ValveDefinitionSource(source); + var sources = source.Resources.Values.Where(r => MissionAiValves.IsResource(Path.GetFileName(r.Path))) + .Select(r => (Path: r.Path, Exists: true)); + if (!source.Resources.Values.Any(r => r.Path.Equals(proposed, StringComparison.OrdinalIgnoreCase))) sources = sources.Append((proposed, false)); + return Page(sources, args, r => r.Path, r => new { source = r.Path, member = Path.GetFileName(r.Path), exists = r.Exists }); + } + string path = Text(args, "source"); + var resource = source.Resources.Values.SingleOrDefault(r => r.Path.Equals(path, StringComparison.OrdinalIgnoreCase)); + if (resource == null && !path.Equals(ValveDefinitionSource(source), StringComparison.OrdinalIgnoreCase)) throw new StudioCommandException("stale_record", "Read the current valve sources."); + if (resource is { Root: null }) throw new StudioCommandException("invalid_argument", "The source resource could not be read."); + var records = resource?.Root == null ? [] : MissionAiValves.Records(Path.GetFileName(path), resource.Root, token).ToArray(); + if (action == "records") return Page(records, args, r => r.Name, r => MissionAiValves.Describe(r, token)); + Guid id = args.ContainsKey("record") ? GuidArg(args, "record") : Guid.Empty; + var record = records.FirstOrDefault(r => r.Id == id); + if (action == "read") + { + if (record == null) throw new StudioCommandException("stale_record", "Read the current valve occurrence."); + return Result(new { document = DocumentState(document), source = path, record = MissionAiValves.Describe(record, token), + parameters = ZrdText.Write(record.Value, token, 65_536) }); + } + if (args["revision"]?.GetValue() != document.Revision) throw new StudioCommandException("revision_conflict", "Read the current document revision."); + if (action == "attach") + { + var attached = await AttachValveAsync(document, path, Int(args, "nodeIndex", -1), Text(args, "attribute"), Text(args, "parameters"), token); + return Result(new { document = DocumentState(attached), source = path }); + } + if (action is not ("create" or "update" or "delete")) throw new StudioCommandException("invalid_argument", "Unknown valve operation."); + var edited = await EditValveRecordAsync(document, path, id, action, args.ContainsKey("name") ? Text(args, "name") : null, + args.ContainsKey("parameters") ? Text(args, "parameters") : null, token); + return Result(new { document = DocumentState(edited), source = path }); + }); + RegisterJob(registry, "ai_valve_preview", "The valve test of the shown MW3 source mission (the Valves row's Test, the banner over the view and the valve card's Test section): the mission's valves run in memory from 0 s with their conditions, reactions and timers, animation callbacks 42–49, vehicle state and route gates. start (or prepare) begins it paused and returns its simulation ID, which the other actions need; state reads it (time, playing, the first 64 values, timers, vehicles and the latest activity). set gives a valve a value (as a trigger, threshold or route would), update fires its reactions without changing it, traverse drives a vehicle through a node's outgoing link slot (refused while its valves close it; its assignments apply). play, pause, step (one tick), advance (to an absolute time, at most one hour), next (to the first tick on which the next pending timer runs), reset (back to 0 s, a new ID) and stop. trace, timers, values and vehicles page the whole state. Nothing is saved; a source edit, another mission or Animation mode ends it. Gameplay is manual: no AI drives, fights or triggers on its own.", + [PreviewParameter, P("action", "string", "Operation.", true, "state", "start", "prepare", "play", "pause", "step", "advance", "next", "reset", "stop", "set", "update", "traverse", "trace", "timers", "values", "actors"), + P("simulation", "string", "Current simulation ID; required except start, prepare and state."), P("name", "string", "set, update: exact valve name."), + P("value", "integer", "set: the value."), P("seconds", "number", "advance: absolute test time, the current time through 3600 seconds."), + P("node", "string", "traverse: snapshot-scoped AI node ID."), P("slot", "integer", "traverse: physical outgoing link slot."), ..PageParameters], true, async (args, token) => + { + _ = TargetAiGraph(args, false); string action = Text(args, "action"); + if (action == "start") action = "prepare"; + if (action is not ("prepare" or "state") && (valveSimulation == null || Text(args, "simulation") != valveSimulation.Id.ToString())) + throw new StudioCommandException("stale_record", "Read the current valve simulation ID."); + if (action == "trace") return Page(CurrentValveSimulation().Runtime.Trace, args, t => t.Valve, t => t); + if (action == "values") return Page(CurrentValveSimulation().Runtime.Values(), args, v => v.Name, + v => new { name = MissionAiValves.Short(v.Name), nameCharacters = v.Name.Length, v.Value, v.Condition }); + if (action == "actors") return Page(CurrentValveSimulation().Actors.Values, args, a => a.Name, + a => new { name = MissionAiValves.Short(a.Name), nameCharacters = a.Name.Length, a.PoweredDown, a.Destroyed, a.Team, a.Strategy, + position = a.Position is { } p ? JsonData.Vector(p) : null, a.Yaw, a.Switches }); + if (action == "timers") return Page(CurrentValveSimulation().Runtime.Timers, args, t => t.Target, + t => new { target = MissionAiValves.Short(t.Target), targetCharacters = t.Target.Length, t.Value, t.Due }); + await ValvePreviewActionAsync(action, Text(args, "name"), Int(args, "value"), args["seconds"]?.GetValue(), + Text(args, "node"), Int(args, "slot", -1), token); + return Result(ValvePreviewState()); + }); + } + /// Record level (MCP create, update, delete): one stored record as zReader text. + private async Task EditValveRecordAsync(DocumentModel document, string path, Guid record, string action, string? name, string? parameters, CancellationToken token) + { + RequireNoDrafts(document); + var source = ValveSource(document); + var resource = source.Resources.Values.SingleOrDefault(r => r.Path.Equals(path, StringComparison.OrdinalIgnoreCase)); + bool creatingResource = resource == null && action == "create" && path.Equals(ValveDefinitionSource(source), StringComparison.OrdinalIgnoreCase); + if (resource == null && !creatingResource) throw new StudioCommandException("stale_record", "Read the current mission's valve sources."); + if (resource is { Root: null }) throw new StudioCommandException("invalid_argument", "The source resource could not be read."); + var records = resource?.Root == null ? [] : MissionAiValves.Records(Path.GetFileName(path), resource.Root, token).ToArray(); + int index = Array.FindIndex(records, r => r.Id == record); + if (action != "create" && index < 0) throw new StudioCommandException("stale_record", "Read the current valve occurrence."); + EndValveTest(); + return await PrepareSourceWorldEditAsync(document, "Editing MW3 valve", (workspace, ct) => + { + var stored = workspace.Read(path, ct); + if (creatingResource && stored != null) throw new SourceFileChangedException("The valve source appeared; reload the mission before creating a definition.", [path]); + var bytes = stored ?? (creatingResource ? System.Text.Encoding.Latin1.GetBytes("()\r\n") : + throw new StudioCommandException("stale_record", "The valve source no longer exists.")); + SourceValveEdits.Edit edit; + try { edit = SourceValveEdits.Plan(Path.GetFileName(path), bytes, action, index, name, parameters, ct); } + catch (InvalidDataException ex) { throw new StudioCommandException("invalid_argument", ex.Message); } + return workspace.Apply(edit.Label, [(path, (byte[]?)edit.Content)], ct); + }, token); + } + private async Task AttachValveAsync(DocumentModel document, string path, int nodeIndex, string attribute, string parameters, CancellationToken token) + { + RequireNoDrafts(document); var source = ValveSource(document); + if (!source.Resources.Values.Any(r => r.Path.Equals(path, StringComparison.OrdinalIgnoreCase)) || !MissionAiNetworks.IsCandidate(Path.GetFileName(path), mw3: true)) + throw new StudioCommandException("stale_record", "Choose a current mission network."); + EndValveTest(); + return await PrepareSourceWorldEditAsync(document, "Adding valve association", (workspace, ct) => + { + var bytes = workspace.Read(path, ct) ?? throw new StudioCommandException("stale_record", "The network source no longer exists."); + SourceValveEdits.Edit edit; + try { edit = SourceValveEdits.Attach(bytes, nodeIndex, attribute, parameters, ct); } + catch (InvalidDataException ex) { throw new StudioCommandException("invalid_argument", ex.Message); } + return workspace.Apply(edit.Label, [(path, (byte[]?)edit.Content)], ct); + }, token); + } +} diff --git a/src/zStudio.Desktop/MainWindow.ValvePreview.cs b/src/zStudio.Desktop/MainWindow.ValvePreview.cs new file mode 100644 index 00000000..180dff12 --- /dev/null +++ b/src/zStudio.Desktop/MainWindow.ValvePreview.cs @@ -0,0 +1,664 @@ +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Windows; +using System.Windows.Automation; +using System.Windows.Controls; +using System.Windows.Documents; +using System.Windows.Threading; +using zStudio.Automation; +using zStudio.Core; +using zStudio.Core.Animation; +using zStudio.Core.Formats; +using zStudio.Core.Sources; +using zStudio.Rendering; + +namespace zStudio.Desktop; + +/// +/// The valve test (design/mw3-valves-ui.md §3): the mission's valves run in memory from 0 s. One switch starts and ends it +/// (the Valves row, the valve card, MCP ai_valve_preview); a banner over the view carries its clock and transport, valve rows +/// show live values and the selected valve's card its value, timers and the test's activity. Nothing is saved. +/// +public partial class MainWindow +{ + private Mw3ValveSimulation? valveSimulation; + private DocumentModel? valveDocument; + private SourceSceneSnapshot? valveMap; + private SceneViewport? valveViewport; + private Guid? valveAttachment; + private AnimationAudio? valveAudio; + private DispatcherTimer? valveTimer; + private bool valveBusy, valveStarting; + private long valveGeneration; + private CancellationTokenSource? valveLifetime; + private string[] valvePreparedSounds = []; + private string? valveAudioProblem, valveFailure; + private readonly Stopwatch valveClock = new(); + private double valvePlayOrigin; + /// + /// The test as its last finished step left it: everything the banner, the rows and the cards show. They never read the + /// simulation itself, which a background step may be changing (its reads count work and guard recursion in shared state). + /// + private sealed record ValveTestView(Guid Simulation, double Time, bool Halted, bool Aborted, IReadOnlyDictionary Values, Mw3ValveTimer[] Timers, + Mw3ValveTrace[] Trace, IReadOnlyDictionary Actors, IReadOnlyDictionary Routes); + private ValveTestView? valveView; + /// The selected valve's Test section while the test runs: its controls stay (and what is typed in them) while its readouts follow the test. + private sealed class ValveTestPanel(string valve, Guid simulation) + { + internal readonly string Valve = valve; + internal readonly Guid Simulation = simulation; + internal readonly CardSection Section = new("Test"); + internal readonly WrapPanel Controls = new() { Margin = new(0, 0, 0, 4) }; + internal readonly StackPanel Inputs = new(), Live = new(); + internal readonly List + + @@ -133,6 +135,11 @@ + + + + + @@ -317,7 +324,7 @@ - + diff --git a/src/zStudio.Desktop/OutlinerKinds.cs b/src/zStudio.Desktop/OutlinerKinds.cs index 0273591f..aa6fcec7 100644 --- a/src/zStudio.Desktop/OutlinerKinds.cs +++ b/src/zStudio.Desktop/OutlinerKinds.cs @@ -6,7 +6,7 @@ namespace zStudio.Desktop; /// The source map outliner's node types: each has an icon and a colour, shared by the tree, its legend and Properties. internal static class OutlinerKinds { - internal static readonly string[] Categories = ["group", "geometry", "empty", "object", "node", "zone", "network", "definition"]; + internal static readonly string[] Categories = ["group", "geometry", "empty", "object", "node", "zone", "network", "valve", "definition"]; /// What an empty node is, for its row's tooltip and its Properties subtitle. internal const string EmptyNote = "No geometry and no children: it draws nothing, but keeps its flags and zone."; private static Brush Frozen(byte r, byte g, byte b) { SolidColorBrush brush = new(Color.FromRgb(r, g, b)); brush.Freeze(); return brush; } @@ -15,17 +15,20 @@ internal static class OutlinerKinds /// The labels of the World tree's sections (the later passes keep their kinds aiv, puppies and anim). internal static string SectionLabel(string section) => section switch { - "zones" => "Zones", "aiNetworks" => "AI Networks", "definitions" => "Animations", + "zones" => "Zones", "aiNetworks" => "AI Networks", "valves" => "Valves", "definitions" => "Animations", "aiv" => "AI Vehicles", "puppies" => "Pickups", "anim" => "Objects placed by animations", _ => section, }; internal static string SectionIcon(SectionEntry section) => section switch { - SectionHeader { Section: "zones" } => "Zones", SectionHeader { Section: "aiNetworks" } => "AiNodes", SectionHeader => "Definition", + SectionHeader { Section: "zones" } => "Zones", SectionHeader { Section: "aiNetworks" } => "AiNodes", SectionHeader { Section: "valves" } => "Valve", SectionHeader => "Definition", + // A valve is a switch; one computed from others is a gate. + ValveEntry { Valve.Condition: not null } => "ValveComputed", ValveEntry => "Valve", DefinitionScopeEntry or PickupGroupEntry => "Folder", DefinitionFileEntry or MissingFileEntry => "DefinitionFile", DefinitionEntry => "Definition", _ => "", }; internal static Brush SectionBrush(SectionEntry section) => section switch { SectionHeader { Section: "zones" } => ZonesBrush, SectionHeader { Section: "aiNetworks" } => VehicleBrush, + SectionHeader { Section: "valves" } or ValveEntry => ValveBrush, SectionHeader or DefinitionEntry => AnimationBrush, // Pickups' groups only sort: a tertiary folder, not the gold of world groups. PickupGroupEntry => Application.Current?.TryFindResource("TextFillColorTertiaryBrush") as Brush ?? Brushes.Gray, @@ -38,11 +41,14 @@ internal static class OutlinerKinds zStudio.Core.AiAttackStrategyKind.FOL => "Follow network", zStudio.Core.AiAttackStrategyKind.ZIG => "Zigzag", zStudio.Core.AiAttackStrategyKind.SIT => "Sit", _ => "Unknown", }; private static readonly Brush GroupBrush = Frozen(0xE8, 0xC2, 0x6B), GeometryBrush = Frozen(0x7F, 0xB8, 0xE8), NodeBrush = Frozen(0xC9, 0xA2, 0xFF); - internal static string Icon(string category) => category switch { "world" => "World", "group" => "Folder", "geometry" => "Geometry", "empty" => "Empty", "object" => "Cube", "zone" => "Zones", "network" => "AiNodes", "definition" => "Definition", _ => "Node" }; + internal static string Icon(string category) => category switch { "world" => "World", "group" => "Folder", "geometry" => "Geometry", "empty" => "Empty", "object" => "Cube", "zone" => "Zones", "network" => "AiNodes", "valve" => "Valve", "definition" => "Definition", _ => "Node" }; /// A later pass's own icon and colour: AI vehicles (aiv), pickups (puppies) and map animations (anim). internal static string PassIcon(string kind) => kind switch { "aiv" => "Tank", "puppies" => "Pickup", "anim" => "Animation", _ => "Folder" }; internal static Brush PassBrush(string kind) => kind switch { "aiv" => VehicleBrush, "puppies" => PickupBrush, "anim" => AnimationBrush, _ => GroupBrush }; private static readonly Brush VehicleBrush = Frozen(0xE8, 0x90, 0x7F), PickupBrush = Frozen(0x8F, 0xD1, 0x8B), AnimationDarkBrush = Frozen(0x6F, 0xC8, 0xD6), AnimationLightBrush = Frozen(0x1F, 0x7F, 0x8C); + // Valves are lime: lighter on the dark theme, darker on the light one. + private static readonly Brush ValveDarkBrush = Frozen(0xC9, 0xD9, 0x5C), ValveLightBrush = Frozen(0x66, 0x7A, 0x12); + internal static Brush ValveBrush => LightTheme ? ValveLightBrush : ValveDarkBrush; // Animation teal: lighter on the dark theme, darker on the light one (the design's motion family). private static Brush AnimationBrush => LightTheme ? AnimationLightBrush : AnimationDarkBrush; // Empty nodes are slate: lighter on the dark theme, darker on the light one. @@ -52,7 +58,7 @@ internal static class OutlinerKinds internal static bool LightTheme => Application.Current?.TryFindResource("TextFillColorPrimaryBrush") is SolidColorBrush { Color: var text } && text.R + text.G + text.B < 384; internal static Brush Brush(string category) => category switch { - "group" => GroupBrush, "geometry" => GeometryBrush, "empty" => EmptyBrush, "node" => NodeBrush, "zone" => ZonesBrush, "network" => VehicleBrush, "definition" => AnimationBrush, + "group" => GroupBrush, "geometry" => GeometryBrush, "empty" => EmptyBrush, "node" => NodeBrush, "zone" => ZonesBrush, "network" => VehicleBrush, "valve" => ValveBrush, "definition" => AnimationBrush, "object" => Application.Current?.TryFindResource("AccentFillColorDefaultBrush") as Brush ?? Brushes.Orange, _ => Application.Current?.TryFindResource("TextFillColorPrimaryBrush") as Brush ?? Brushes.Gray, }; diff --git a/src/zStudio.Desktop/PreviewIcon.cs b/src/zStudio.Desktop/PreviewIcon.cs index 029a0d26..e49f9f61 100644 --- a/src/zStudio.Desktop/PreviewIcon.cs +++ b/src/zStudio.Desktop/PreviewIcon.cs @@ -117,6 +117,13 @@ public sealed class PreviewIcon : FrameworkElement ["Scenario"] = "M2.5,4 H8 M11,4 H13.5 M2.5,8 H4.5 M7.5,8 H13.5 M2.5,12 H9 M12,12 H13.5 M9.5,2.5 V5.5 M6,6.5 V9.5 M10.5,10.5 V13.5", ["Pin"] = "M8,14.5 C8,14.5 3.5,9.6 3.5,6.2 A4.5,4.5 0 0 1 12.5,6.2 C12.5,9.6 8,14.5 8,14.5 Z M6.5,6.2 A1.5,1.5 0 1 0 9.5,6.2 A1.5,1.5 0 1 0 6.5,6.2", ["More"] = "M3,8 A0.6,0.6 0 1 0 4.2,8 A0.6,0.6 0 1 0 3,8 M7.4,8 A0.6,0.6 0 1 0 8.6,8 A0.6,0.6 0 1 0 7.4,8 M11.8,8 A0.6,0.6 0 1 0 13,8 A0.6,0.6 0 1 0 11.8,8", + // Valves: a switch, a valve computed from others (a gate), a timer, a link to what a row names, add, and skip to the next timer. + ["Valve"] = "M8,2 V8 M4.7,4.3 A5,5 0 1 0 11.3,4.3", + ["ValveComputed"] = "M4,3.5 H8 A4.5,4.5 0 0 1 8,12.5 H4 Z M1.5,6 H4 M1.5,10 H4 M12.5,8 H14.5", + ["Timer"] = "M2.5,9 A5.5,5.5 0 1 0 13.5,9 A5.5,5.5 0 1 0 2.5,9 M8,6 V9 L10,10.5 M6.5,1.5 H9.5", + ["GoTo"] = "M5,11 L11,5 M6,5 H11 V10", + ["Add"] = "M8,3 V13 M3,8 H13", + ["SkipForward"] = "M3,3.5 L8,8 L3,12.5 Z M8.5,3.5 L13.5,8 L8.5,12.5 Z", ["Paths"] = "M2,13 C5,13 4,3 8,3 C12,3 11,13 14,13" }.ToDictionary(p => p.Key, p => { Geometry g = Geometry.Parse(p.Value); g.Freeze(); return g; }); diff --git a/src/zStudio.Desktop/SceneTreeModel.cs b/src/zStudio.Desktop/SceneTreeModel.cs index 3b8a44cc..456808f3 100644 --- a/src/zStudio.Desktop/SceneTreeModel.cs +++ b/src/zStudio.Desktop/SceneTreeModel.cs @@ -51,6 +51,10 @@ internal interface ISourceSectionState (int Definition, int Entry)? OpenedAnimation => null; /// After Exit, the definition whose scenario is kept and the scenario's starts (its row's dot); null otherwise. (int Definition, int Starts)? KeptAnimation => null; + /// The valve test runs: valve rows show their live values and the Valves row's Test is pressed. + bool ValveTesting => false; + /// A valve's value in the running test; null outside one. + int? ValveValue(string name) => null; } internal sealed class SceneTreeModel @@ -101,7 +105,7 @@ internal void SetPaneWidth(double width) { bool narrow = Narrow, wide = Wide; PaneWidth = width; - if (narrow != Narrow || wide != Wide) RefreshAnimationRows(); + if (narrow != Narrow || wide != Wide) { RefreshAnimationRows(); RefreshValveRows(); } } /// /// The Animations rows show again what the summary, the selection, Animation mode and the kept scenario say (their glyph, @@ -111,6 +115,11 @@ internal void RefreshAnimationRows() { foreach (var row in rows.Values) if (row.IsAnimationRow) row.NotifyAnimation(); } + /// The valve test started, ended or changed values, or the pane crossed a width band: the Valves row and its valves show it (only their properties change). + internal void RefreshValveRows() + { + foreach (var row in rows.Values) if (row.Section is ValveEntry or SectionHeader { Section: "valves" }) row.NotifyValve(); + } internal SceneTreeModel(GameScene scene, string source, bool isPreview, SceneTreeState state, Func? identity = null, IReadOnlySet? included = null, SourceMapSelection? projection = null, SourceMapSections? sections = null, bool pickupsByType = false, ISourceSectionState? sectionState = null, bool animationsByStart = false, double paneWidth = 0) { @@ -128,7 +137,8 @@ internal SceneTreeModel(GameScene scene, string source, bool isPreview, SceneTre { void Pass(string kind) { if (projection.Passes.Any(p => p.Kind == kind)) roots.Add(New(null, null, "pass:" + kind, 0)); } void Section(string section) { if (Sections != null) roots.Add(New(null, null, "section:" + section, 0, section: new SectionHeader(section))); } - Section("zones"); Pass("aiv"); Section("aiNetworks"); Pass("puppies"); Section("definitions"); + // An MW3 mission's valves follow the networks they gate (RECOIL has none). + Section("zones"); Pass("aiv"); Section("aiNetworks"); if (Sections?.ValveMap != null) Section("valves"); Pass("puppies"); Section("definitions"); } Roots = roots; var retainedPath = state.SelectionPath; @@ -283,7 +293,7 @@ public sealed class SceneTreeItem : INotifyPropertyChanged public bool Synthetic => SourceGroup || Index is int i && Owner.Projection?.Boundaries.GetValueOrDefault(i)?.Synthetic == true; public bool Selectable => Problem == null && (IsSectionItem || Section == null && (Node != null || Synthetic)); /// A zone, an AI network or a definition: selected for its own card, not a scene object. - public bool IsSectionItem => Section is ZoneEntry or NetworkEntry or DefinitionEntry or AnimationBindingEntry; + public bool IsSectionItem => Section is ZoneEntry or NetworkEntry or DefinitionEntry or AnimationBindingEntry or ValveEntry; /// A definition or binding row: its Open (▷) enters Animation mode on it. public bool CanOpenAnimation => IsSourceMap && Section is DefinitionEntry { BindingKnown: true } or AnimationBindingEntry; public string OpenAnimationToolTip => IsOpenedAnimation ? "Opened in Animation mode" @@ -357,7 +367,8 @@ public sealed class SceneTreeItem : INotifyPropertyChanged /// The Frame button's tooltip and name. public string FrameToolTip => PickupEntries is { } pickups ? pickups.Count == 0 ? $"No {PickupNoun(2)} in this mission" : $"Frame every {PickupNoun(1)} on {ShownDifficulty}" - : Section is DefinitionEntry ? "Frame bound objects" : Section is AnimationBindingEntry binding ? "Frame " + Short(binding.Binding.Root, 64) : "Frame selection"; + : Section is DefinitionEntry ? "Frame bound objects" : Section is AnimationBindingEntry binding ? "Frame " + Short(binding.Binding.Root, 64) + : Section is ValveEntry ? "Frame its route nodes and vehicles" : "Frame selection"; /// What a screen reader names the row. public string AccessibleName => PickupEntries is { } pickups ? $"{SectionLabel}, {PickupCount(pickups.Count)}" + (Section is PickupTypeEntry && Pickup is { } type ? ", " + type.ManualName : "") : PickupName is { } name && Pickup is { } pickup ? $"{pickup.ShortName} {Placement!.Number}, {pickup.Kind} pickup, {pickup.ManualName}, " @@ -452,7 +463,10 @@ private static System.Windows.Media.Brush AnimationColor(byte r, byte g, byte b) /// The row's Frame selection button: a selectable object, piece of geometry or node (not a group the build removes), an AI /// network, a definition or binding bound to an object the World tree lists (never only a template), or a Pickups group or type. /// - public bool CanFrame => IsSourceMap && (Section != null ? Section is NetworkEntry || CanFrameAnimation || PickupShown : Index is int && Selectable && !SourceGroup && !IsEmptyNode); + public bool CanFrame => IsSourceMap && (Section != null ? Section is NetworkEntry || CanFrameAnimation || PickupShown || Section is ValveEntry valve && OnMap(valve.Valve) : Index is int && Selectable && !SourceGroup && !IsEmptyNode); + /// A valve with something on the map: a route node that sets or waits on it, or a vehicle that triggers it or that it acts on. + internal static bool OnMap(Mw3ValveInfo valve) => valve.SetBy.Concat(valve.UsedBy).Any(l => l.Node != null || l.Actor != null) + || valve.Reactions.Any(r => r.Spec.Kind is not ("sound" or "sound_once" or "animation" or "animation_once" or "update" or "delayupdate" or "missionabort" or "missionreset" or "missioncomplete")); internal SourceMapNodeVisibility? VisibilityState => Index is int i ? Owner.PartVisibility?.Invoke(i) : null; public bool IsHidden => MasterKey is { } master ? State?.MasterShown(master) != true : Section != null ? SectionHidden : VisibilityState is { } part ? !part.Visible : Index is int i && Owner.IsHiddenNode?.Invoke(i) == true; @@ -606,6 +620,8 @@ private SceneTreeItem[] PickupChildren() : [.. s.Zones.Select(z => (SectionEntry)new ZoneEntry(z)), .. s.NoZonePolygons > 0 ? [new NoZonesEntry(s.NoZonePolygons)] : Array.Empty()], SectionHeader { Section: "aiNetworks" } when Owner.Sections is { } s => s.Networks.Count == 0 ? [new NoteEntry("No AI networks in this mission.")] : [.. s.Networks.OrderBy(SourceMapSections.NetworkNumber).ThenBy(n => n.Id, StringComparer.Ordinal).Select(n => new NetworkEntry(n))], + SectionHeader { Section: "valves" } when Owner.Sections?.ValveMap is { } map => map.Valves.Count == 0 ? [new NoteEntry("No valves in this mission yet. Right-click Valves to add one.")] + : [.. map.Valves.Select(v => (SectionEntry)new ValveEntry(v))], SectionHeader { Section: "definitions" } when Owner.Sections is { } s => s.DefinitionScopes(Owner.AnimationsByStart) is { Count: > 0 } scopes ? scopes : [new NoteEntry("This map lists no animation definitions.")], DefinitionScopeEntry scope => scope.Items, DefinitionFileEntry file => file.Definitions, @@ -615,7 +631,7 @@ private SceneTreeItem[] PickupChildren() }; private static string KindOf(SectionEntry entry) => entry switch { - ZoneEntry => "zone", NoZonesEntry => "noZones", NetworkEntry => "network", DefinitionScopeEntry => "definitionScope", DefinitionGroupEntry => "definitionGroup", + ValveEntry => "valve", ZoneEntry => "zone", NoZonesEntry => "noZones", NetworkEntry => "network", DefinitionScopeEntry => "definitionScope", DefinitionGroupEntry => "definitionGroup", DefinitionFileEntry => "definitionFile", DefinitionEntry => "definition", AnimationBindingEntry => "animationBinding", AnimationPageEntry => "animationPage", MissingFileEntry => "missingFile", _ => "note", }; private static string PassEmpty(string kind) => kind switch @@ -625,7 +641,7 @@ private SceneTreeItem[] PickupChildren() private ISourceSectionState? State => Owner.SectionState; private string SectionCategory => Section switch { - SectionHeader => "section", ZoneEntry => "zone", NoZonesEntry => "noZones", NetworkEntry => "network", DefinitionScopeEntry => "definitionScope", DefinitionGroupEntry => "definitionGroup", + ValveEntry => "valve", SectionHeader => "section", ZoneEntry => "zone", NoZonesEntry => "noZones", NetworkEntry => "network", DefinitionScopeEntry => "definitionScope", DefinitionGroupEntry => "definitionGroup", DefinitionFileEntry => "definitionFile", DefinitionEntry or AnimationBindingEntry => "definition", AnimationPageEntry => "definitionScope", MissingFileEntry => "missingFile", PickupGroupEntry => "pickupGroup", PickupTypeEntry => "pickupType", _ => "note", }; private string SectionLabel => Section switch @@ -636,6 +652,7 @@ private SceneTreeItem[] PickupChildren() ZoneEntry zone => ZoneName(zone.Zone.Zone), NoZonesEntry => "No zones", NetworkEntry network => SourceMapSections.NetworkStem(network.Network), + ValveEntry valve => JsonData.ShownText(valve.Valve.Name, 96), DefinitionScopeEntry scope => scope.Name, DefinitionGroupEntry group => AnimationTreeSummary.Label(group.Start), DefinitionFileEntry file => System.IO.Path.GetFileName(file.Listing.File), @@ -670,6 +687,10 @@ private SceneTreeItem[] PickupChildren() SectionHeader { Section: "zones" } => Count(Owner.Sections?.Zones.Count ?? 0), SectionHeader { Section: "aiNetworks" } => Count(Owner.Sections?.Networks.Count ?? 0), SectionHeader { Section: "definitions" } => Count(Owner.Sections?.Definitions.Definitions.Count ?? 0), + SectionHeader { Section: "valves" } => Count(Owner.Sections?.ValveMap?.Valves.Count ?? 0), + // While the test runs a valve's row shows its value; at rest only a start other than zero. + ValveEntry valve => State?.ValveTesting == true ? State.ValveValue(valve.Valve.Name) is int live ? live.ToString(System.Globalization.CultureInfo.InvariantCulture) : "" + : valve.Valve is { Initial: not 0, Condition: null } ? "starts " + valve.Valve.Initial.ToString(System.Globalization.CultureInfo.InvariantCulture) : "", ZoneEntry zone => zone.Zone.Polygons > 0 ? Count(zone.Zone.Polygons) : zone.Zone.Objects > 0 ? "objects only" : "Not used", NoZonesEntry none => Count(none.Polygons), NetworkEntry network => network.Network.Nodes.Count == 1 ? "1 node" : Count(network.Network.Nodes.Count) + " nodes", @@ -697,9 +718,10 @@ private SceneTreeItem[] PickupChildren() public bool IsNote => Section is NoteEntry; /// A Pickups group or type placed only on other difficulties (dimmed). public bool IsDimmed => IsOtherDifficultyGroup; - public bool HasWarning => Section is NetworkEntry { Network.Diagnostics.Count: > 0 } || Section is MissingFileEntry; + public bool HasWarning => Section is NetworkEntry { Network.Diagnostics.Count: > 0 } || Section is MissingFileEntry || Section is ValveEntry { Valve.Problems.Count: > 0 }; public string? WarningToolTip => Section switch { + ValveEntry valve => string.Join("\n", valve.Valve.Problems.Take(3).Select(p => Short(p, 200))) + (valve.Valve.Problems.Count > 3 ? $"\n{valve.Valve.Problems.Count - 3} more" : ""), NetworkEntry network => string.Join("\n", network.Network.Diagnostics.Take(3).Select(d => Short(d.Message, 200))) + (network.Network.Diagnostics.Count > 3 ? $"\n{network.Network.Diagnostics.Count - 3} more" : ""), MissingFileEntry missing => $"Listed by {missing.Listing.ListedBy} but not in the project: the build skips it.", _ => null, @@ -755,6 +777,12 @@ private SceneTreeItem[] PickupChildren() SectionHeader { Section: "zones" } => "The map's zones: the zones its polygons carry and the zones of its objects. Click a zone for its details and label.", SectionHeader { Section: "aiNetworks" } => "The mission's AI networks (aipath/net_.zrd), each in its attack-strategy colour. Click one to show it and edit its settings.", SectionHeader { Section: "definitions" } => AnimationsToolTipText, + SectionHeader { Section: "valves" } => "The mission's valves: named switches. Vehicle triggers, health thresholds, timers and routes set them; they play sounds, wake vehicles and open or close routes.\n" + + "Click one for what sets it and what it does. Test (▷) flips them in memory to show what follows.", + ValveEntry { Valve: var valve } => $"{Short(valve.Name, 128)} · {(valve.Condition != null ? "computed: " + Mw3ValveMap.ConditionText(valve.Condition) : "switch")}" + + (valve.Summary.Length > 0 ? "\n" + Short(valve.Summary, 256) : "") + + $"\nSet by {Count(valve.SetBy.Count)} · {Count(valve.Reactions.Count)} reaction{(valve.Reactions.Count == 1 ? "" : "s")} · used by {Count(valve.UsedBy.Count)}" + + (valve.Defined ? "" : "\nNo valves.zrd record: the game makes it at 0 when a file first names it."), DefinitionScopeEntry scope => $"Definitions from {scope.Folder} that every map lists. {Owner.Sections?.Mission ?? "This map"} lists {Count(scope.Count)} of them: " + "effects, enemy vehicles and turrets, pickups, the player tank's trails.\nEditing one changes every map that lists it (its card's Source names them).", DefinitionGroupEntry group => $"{AnimationTreeSummary.Label(group.Start)} · {Count(group.Definitions.Count)}\n{AnimationTreeSummary.Rule(group.Start)}", @@ -805,6 +833,8 @@ private string PickupGroupToolTip NetworkEntry network => $"{SectionLabel} {network.Network.Name} {network.Network.AttackStrategy.Value} {OutlinerKinds.StrategyName(network.Network.AttackStrategy.Kind)} {network.Network.Type}", DefinitionEntry definition => DefinitionSummary?.SearchText ?? $"{SectionLabel} {definition.Definition.RootName} {System.IO.Path.GetFileName(definition.Definition.File)}", AnimationBindingEntry binding => $"{binding.Binding.Name} {binding.Binding.Root}", + // A valve by its name, what it does and everything it names (vehicles, sounds, other valves, regions). + ValveEntry valve => $"{valve.Valve.Name} {valve.Valve.Summary} {string.Join(' ', valve.Valve.Mentions)}", // A pickup by its name, the manual's name, its kind, catalog type, template and (placed) game name. _ when PickupName is { } name && Pickup is { } pickup => $"{name} {pickup.ManualName} {pickup.Kind} pickup {PickupPresentation.GroupLabel(pickup.Group)} {pickup.Type} {pickup.TemplateName}" + (IsOtherDifficulty ? "" : " " + Placement!.Name), _ => DisplayName + (Pass is { } pass ? " " + pass.Label : ""), @@ -846,6 +876,8 @@ private string TargetText(bool quiet) switch (Section) { case AnimationBindingEntry binding: text = binding.Binding.Root; break; + // A valve: what it does, in a few words. + case ValveEntry valve: text = valve.Valve.Summary; break; case DefinitionEntry definition when DefinitionSummary is { } summary: text = summary.Target?.Text ?? ""; if (text == definition.Definition.Name) text = ""; @@ -997,6 +1029,22 @@ private string AnimationsToolTipText _ => AnimationTreeSummary.Label(DefinitionSummary!.Start.Kind), }; } + // ---------------------------------------------------------------- Valves rows (design/mw3-valves-ui.md) + + /// The Valves row: its Test toggle (▷) starts and ends the valve test. + public bool HasValveTest => IsSourceMap && Section is SectionHeader { Section: "valves" }; + public bool ValveTestOn => HasValveTest && State?.ValveTesting == true; + public string ValveTestIcon => ValveTestOn ? "Stop" : "Play"; + public string ValveTestToolTip => ValveTestOn ? "End the valve test" : "Test valves: flip them in memory and watch timers, routes and vehicles react. Nothing is saved."; + /// A valve whose live value is not zero: its value shows in the accent colour. + public bool ValveIsOn => Section is ValveEntry valve && State?.ValveTesting == true && State.ValveValue(valve.Valve.Name) is not (null or 0); + /// A valve with nothing on the map: no Frame, but its space stays so the live values line up. + public bool KeepsFrameSpace => Section is ValveEntry && !CanFrame; + internal void NotifyValve() + { + foreach (string name in new[] { nameof(Meta), nameof(ValveIsOn), nameof(ValveTestOn), nameof(ValveTestIcon), nameof(ValveTestToolTip), nameof(AccessibleName), + nameof(TargetRunText), nameof(TargetQuietRunText) }) Changed(name); + } internal void NotifyAnimation() { foreach (string name in new[] { nameof(OutlinerIcon), nameof(OutlinerBrush), nameof(TargetRunText), nameof(TargetQuietRunText), nameof(SecondaryRunText), nameof(Meta), diff --git a/src/zStudio.Desktop/SourceMapSections.cs b/src/zStudio.Desktop/SourceMapSections.cs index 699c971c..18325825 100644 --- a/src/zStudio.Desktop/SourceMapSections.cs +++ b/src/zStudio.Desktop/SourceMapSections.cs @@ -25,6 +25,12 @@ internal sealed class SourceMapSections /// Polygons with no zone (not a zone: the overlay leaves them untinted). internal long NoZonePolygons { get; init; } internal required IReadOnlyList Networks { get; init; } + /// An MW3 mission's valves by name (null in RECOIL maps, which have none). + internal Mw3ValveMap? ValveMap { get; init; } + /// Where a new valve's first record goes: the mission's valves.zrd, also before it exists. + internal string? ValveSource { get; init; } + /// What a reaction can name in this mission, for the card's pickers: vehicles and targets, animations, sounds (null: unknown). + internal Mw3ValveCatalog? ValveCatalog { get; init; } internal required SourceAnimationDefinitions Definitions { get; init; } /// The tree rows each definition binds to in this world, by definition index (none when it binds to nothing). internal required IReadOnlyDictionary DefinitionRoots { get; init; } @@ -101,6 +107,8 @@ internal sealed record ZoneEntry(SourceZoneRow Zone) : SectionEntry("zone:" + Zo /// Polygons without a zone: listed for information (not a zone, not selectable). internal sealed record NoZonesEntry(long Polygons) : SectionEntry("zone:none"); internal sealed record NetworkEntry(AiNetwork Network) : SectionEntry("network:" + Network.Id); +/// A valve of the MW3 mission: one row per exact name, whatever files mention it. +internal sealed record ValveEntry(Mw3ValveInfo Valve) : SectionEntry("valve:" + Valve.Name); /// Common: the definitions from data/common that every map lists, after the map's own (§3). internal sealed record DefinitionScopeEntry(string Name, string Folder, IReadOnlyList Items, int Count) : SectionEntry("scope:" + Name); /// With Group by start: the map's (or Common's) definitions that start one way, in compile order. diff --git a/src/zStudio.Desktop/SourceSectionCard.Valves.cs b/src/zStudio.Desktop/SourceSectionCard.Valves.cs new file mode 100644 index 00000000..11903b2a --- /dev/null +++ b/src/zStudio.Desktop/SourceSectionCard.Valves.cs @@ -0,0 +1,543 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Automation; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Documents; +using System.Windows.Media; +using zStudio.Automation; +using zStudio.Core; +using zStudio.Core.Sources; + +namespace zStudio.Desktop; + +/// +/// The valve card (design/mw3-valves-ui.md): one MW3 valve by name. Value, Kind, Inputs and Reactions are one draft that +/// Apply accepts as one undoable change of valves.zrd; Set by and Used by list what other files say, as links. +/// +internal sealed partial class SourceSectionCard +{ + /// What the card needs beside the valve: the mission's names for its pickers, the records as stored, and why it cannot edit (or null). + internal sealed record ValveCardContext(Mw3ValveMap Map, Mw3ValveCatalog? Catalog, IReadOnlyList<(string Text, string? Problem)> Source, string? ReadOnly); + /// Applies the draft: the valve's name and its changes. + internal Func? ApplyValve { get; set; } + /// A Set by or Used by row's link: its vehicle, route node or valve is selected. + internal Action? ValveLinkInvoked { get; set; } + /// Another valve of the mission is selected by name (an input, a timer's or update's target). + internal Action? ValveInvoked { get; set; } + /// Rename… and Delete (the row's context menu has the same). + internal Action? ValveCommand { get; set; } + /// The Test section's content for a valve: the Test valves button, or while testing its value, timers and activity. + internal Func? ValveTest { get; set; } + /// A Set by row's Fire while testing: the valve takes the value that trigger would give it. Null outside a test. + internal Func? ValveFire { get; set; } + + private Mw3ValveInfo? valve; + private ValveCardContext? valveContext; + private TextBox? valveInitial; + private ComboBox? valveKind; + private StackPanel? valveInputs, valveReactions; + private readonly List valveInputBoxes = []; + private readonly List valveRows = []; + private Border? valveTestHost; + private CardSection? valveReactionSection, valveValueSection; + private Button? valveAddInput; + + internal Mw3ValveInfo? ShownValve => Entry is ValveEntry ? valve : null; + private string ValveKindValue => (valveKind?.SelectedItem as ComboBoxItem)?.Tag as string ?? ""; + private string[] ValveInputValues => [.. valveInputBoxes.Select(b => b.Text.Trim()).Where(t => t.Length > 0)]; + /// The draft was accepted: the card waits for the rebuilt map (or is shown again) and holds no draft. + private bool valveApplied; + private bool ValveHasDraft => !valveApplied && Entry is ValveEntry && valve != null && valveInitial != null && (valveInitial.Text.Trim() != valve.Initial.ToString(CultureInfo.InvariantCulture) + || ValveKindValue != (valve.Condition ?? "") || ValveKindValue.Length > 0 && !ValveInputValues.SequenceEqual(valve.Inputs) || valveRows.Any(r => r.Changed)); + private string ValveDraftFingerprint => Entry is ValveEntry && valveInitial != null + ? string.Join("\u0001", [valveInitial.Text, ValveKindValue, .. ValveInputValues, .. valveRows.Select(r => r.Fingerprint)]) : ""; + /// The draft as the changes Apply sends (throws what a field refuses). + internal SourceValveEdits.ValveChanges ValveChanges + { + get + { + if (valve == null || valveInitial == null) return new(); + string initial = valveInitial.Text.Trim(), kind = ValveKindValue; + bool kindChanged = kind != (valve.Condition ?? ""), inputsChanged = kind.Length > 0 && !ValveInputValues.SequenceEqual(valve.Inputs); + return new(initial != valve.Initial.ToString(CultureInfo.InvariantCulture) ? initial : null, kindChanged ? kind : null, kindChanged && kind.Length > 0 || inputsChanged ? ValveInputValues : null, + [.. valveRows.Where(r => r.Changed).Select(r => new SourceValveEdits.ReactionChange(r.Original?.Occurrence, r.Original?.Spec.Kind, r.Removed ? null : r.Spec))]); + } + } + private object? ValveDraft => Entry is ValveEntry && valve != null && valveInitial != null ? new + { + name = JsonData.ShownText(valve.Name, 256), initial = valveInitial.Text, condition = ValveKindValue.Length == 0 ? null : ValveKindValue, + inputs = ValveInputValues.Take(64).Select(i => JsonData.ShownText(i, 256)).ToArray(), + reactions = valveRows.Take(64).Select(r => new + { + occurrence = r.Original?.Occurrence, storedKind = r.Original?.Spec.Kind, kind = r.Spec.Kind, target = r.Spec.Target is { } target ? JsonData.ShownText(target, 256) : null, + operand = r.Spec.Operand, when = r.Spec.When, x = r.Spec.X, y = r.Spec.Y, z = r.Spec.Z, yaw = r.Spec.Yaw, added = r.Original == null ? true : (bool?)null, + removed = r.Removed ? true : (bool?)null, changed = r.Changed, + }).ToArray(), + editable = valveContext?.ReadOnly == null, + } : null; + + /// A valve: its value, what sets it, its reactions and what waits on it. The same valve with a draft keeps the draft; only Test refreshes. + internal void ShowValve(DocumentModel document, ValveEntry entry, ValveCardContext context) + { + if (Entry?.Key == entry.Key && ReferenceEquals(Document, document) && Applying) { valveContext = context; RefreshValveTest(); return; } + string? lost = null; + if (Entry?.Key == entry.Key && ReferenceEquals(Document, document) && HasDraft) + { + // The draft names reactions by their place in the file: it stays only while the valve is stored as it was. + if (valve != null && SameStored(valve, entry.Valve)) { valve = entry.Valve; valveContext = context; RefreshValveTest(); return; } + lost = "This valve changed in its file, so the unapplied changes on this card were dropped."; + } + Begin(entry, document); + if (lost != null) Error(lost); + valve = entry.Valve; valveContext = context; + var info = entry.Valve; bool editable = context.ReadOnly == null; + heading.Text = info.Name; heading.ToolTip = info.Name; + subtitle.Text = "Valve · " + (info.Condition != null ? "computed" : "switch") + (info.Defined ? "" : " · no record yet"); + subtitle.ToolTip = info.Defined ? string.Join("\n", info.Records.Select(r => r.Source).Distinct(StringComparer.OrdinalIgnoreCase)) : "No valves.zrd record names it: the game makes it at 0 when a file first mentions it."; + tile.Child = new PreviewIcon { Kind = info.Condition != null ? "ValveComputed" : "Valve", Width = 17, Height = 17, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; + ((PreviewIcon)tile.Child).SetValue(TextElement.ForegroundProperty, OutlinerKinds.ValveBrush); + if (context.ReadOnly != null) Error(lost == null ? context.ReadOnly : lost + " " + context.ReadOnly); + foreach (string problem in info.Problems.Take(4)) body.Children.Add(ValveNotice(problem)); + + valveTestHost = new Border { Margin = new(0, 0, 0, 8) }; + body.Children.Add(valveTestHost); + + // ---- Value + var value = valveValueSection = Section("Value", info: "A valve holds a whole number; the game's files use 0 (off) and 1 (on). A computed valve has no value of its own: the game works it out from its inputs each time it is read."); + valveInitial = new TextBox { Text = info.Initial.ToString(CultureInfo.InvariantCulture), Height = 30, Width = 84, MaxLength = 11, HorizontalAlignment = HorizontalAlignment.Left, IsEnabled = editable }; + AutomationProperties.SetName(valveInitial, "Starting value"); + valveInitial.TextChanged += (_, _) => { RefreshValveKind(); Changed(); }; + value.Body.Children.Add(Row("Starts at", valveInitial)); + valveKind = new ComboBox { Height = 30, HorizontalAlignment = HorizontalAlignment.Stretch, IsEnabled = editable }; + AutomationProperties.SetName(valveKind, "Kind"); + foreach (var (tag, text) in new[] { ("", "Switch"), ("any_nonzero", "On while any input is on"), ("any_zero", "On while any input is off"), ("all_nonzero", "On while all inputs are on"), ("all_zero", "On while all inputs are off") }) + { + ComboBoxItem item = new() { Content = text, Tag = tag, ToolTip = tag.Length == 0 ? "A plain valve: triggers, timers and routes set it." : $"Stored as {tag} with a namelist." }; + valveKind.Items.Add(item); + if (tag == (info.Condition ?? "")) valveKind.SelectedItem = item; + } + value.Body.Children.Add(Row("Kind", valveKind)); + valveInputs = new StackPanel(); + value.Body.Children.Add(valveInputs); + valveInputBoxes.Clear(); + foreach (string input in info.Inputs) AddValveInput(input, editable); + valveAddInput = ValveTextButton("Add", "Add input", "Add an input valve", () => { AddValveInput("", true).Focus(); Changed(); }); + valveAddInput.Margin = new(76, 2, 0, 2); valveAddInput.IsEnabled = editable; + value.Body.Children.Add(valveAddInput); + valveKind.SelectionChanged += (_, _) => { RefreshValveKind(); Changed(); }; + RefreshValveKind(); + + // ---- Set by + var setBy = Section("Set by", info: "What gives this valve a value: vehicle triggers (aiv.zrd), a target's health (targets.zrd), objectives, routes, other valves' timers, " + + "and animations whose events 42–49 run on the scene node of this name. The game's own code can set a valve too; that is not listed."); + setBy.Summary = info.SetBy.Count.ToString(CultureInfo.CurrentCulture); + valveSetBy = setBy.Body; + BuildValveSetBy(); + + // ---- Reactions + var reactions = valveReactionSection = Section("Reactions", info: "What happens when the valve changes. Each reaction waits for one value (\"when it becomes\"); timers and updates run on every change. " + + "Reactions run in the game's fixed order: sounds, animations, scans, power, destroy, team, strategy, teleport, mission, updates, timers."); + valveReactions = new StackPanel(); valveRows.Clear(); + reactions.Body.Children.Add(valveReactions); + foreach (var reaction in info.Reactions.Take(64)) AddValveReaction(reaction, null, editable); + if (info.Reactions.Count > 64) HelpLine(reactions).Text = $"and {info.Reactions.Count - 64:N0} more: edit those in a text editor"; + var add = ValveTextButton("Add", "Add reaction", "Add a reaction to this valve", () => + { + AddValveReaction(null, new("sound", "", When: "1"), true).FocusFirst(); + Changed(); + }); + add.IsEnabled = editable; add.Margin = new(0, 4, 0, 0); + reactions.Body.Children.Add(add); + RefreshValveReactionSummary(); + + // ---- Used by + var usedBy = Section("Used by", info: "What waits on this valve: route gates (a vehicle passes only while the valve holds the value), objectives, and computed valves that read it."); + usedBy.Summary = info.UsedBy.Count.ToString(CultureInfo.CurrentCulture); + if (info.UsedBy.Count == 0) HelpLine(usedBy).Text = info.Reactions.Count == 0 ? "Nothing waits on it and it has no reactions: it changes nothing in play." : "No route, objective or computed valve waits on it."; + foreach (var link in info.UsedBy.Take(24)) usedBy.Body.Children.Add(ValveLinkRow(info, link, sets: false)); + if (info.UsedBy.Count > 24) HelpLine(usedBy).Text = $"and {info.UsedBy.Count - 24:N0} more (source_ai_valve lists them all)"; + + // ---- Source + var source = Section("Source", expanded: false); + source.Summary = info.Records.Count == 0 ? "no record" : info.Records.Count == 1 ? "1 record" : $"{info.Records.Count:N0} records"; + if (info.Records.Count == 0) HelpLine(source).Text = "No valves.zrd record yet. Apply a change, or a reaction, to write one."; + foreach (var (text, problem) in context.Source.Take(16)) + { + if (problem != null) source.Body.Children.Add(ValveNotice(problem)); + var block = Mono(text); block.Margin = new(0, 2, 0, 6); block.TextWrapping = TextWrapping.Wrap; + source.Body.Children.Add(block); + } + if (info.Records.Count > 16) HelpLine(source).Text = $"and {info.Records.Count - 16:N0} more"; + StackPanel commands = new() { Orientation = Orientation.Horizontal, Margin = new(0, 4, 0, 0) }; + var rename = ValveTextButton("Edit", "Rename…", "Rename the valve in every file of the mission that names it", () => ValveCommand?.Invoke("rename", info.Name)); + var delete = ValveTextButton("Delete", "Delete", "Delete its valves.zrd records", () => ValveCommand?.Invoke("delete", info.Name)); + rename.IsEnabled = editable; delete.IsEnabled = editable && info.Defined; delete.Margin = new(8, 0, 0, 0); + commands.Children.Add(rename); commands.Children.Add(delete); + source.Body.Children.Add(commands); + HelpLine(source).Text = "Unknown tags and comments are kept: the card changes only the values it shows."; + + RefreshValveTest(); + Finish(editable); + } + + private static bool SameStored(Mw3ValveInfo a, Mw3ValveInfo b) => a.Initial == b.Initial && a.Condition == b.Condition && a.Inputs.SequenceEqual(b.Inputs) + && a.Reactions.Select(r => (r.Occurrence, r.Spec)).SequenceEqual(b.Reactions.Select(r => (r.Occurrence, r.Spec))); + + /// The Test section and the Set by rows' Fire follow the test (started, ended, a value changed, time passed) without touching the draft's fields. + internal void RefreshValveTest() + { + if (valveTestHost == null || valve == null || Entry is not ValveEntry) return; + // While the test runs the same section comes back for the same valve: it moves here from the host of an earlier + // showing of the card (an element has one parent). + var content = ValveTest?.Invoke(valve); + if (!ReferenceEquals(valveTestHost.Child, content)) + { + if (content?.Parent is Border previous && !ReferenceEquals(previous, valveTestHost)) previous.Child = null; + valveTestHost.Child = content; + } + valveTestHost.Visibility = valveTestHost.Child == null ? Visibility.Collapsed : Visibility.Visible; + // A row offers Fire only while the test runs. + bool firing = valve.SetBy.Any(link => ValveFire?.Invoke(valve, link) != null); + if (firing != valveSetByFiring) BuildValveSetBy(); + } + private StackPanel? valveSetBy; + private bool valveSetByFiring; + private void BuildValveSetBy() + { + if (valveSetBy == null || valve == null) return; + valveSetBy.Children.Clear(); + valveSetByFiring = valve.SetBy.Any(link => ValveFire?.Invoke(valve, link) != null); + if (valve.SetBy.Count == 0) valveSetBy.Children.Add(ValveHelp("Nothing in the mission's files or animations sets it. The game itself may.")); + foreach (var link in valve.SetBy.Take(24)) valveSetBy.Children.Add(ValveLinkRow(valve, link, sets: true)); + if (valve.SetBy.Count > 24) valveSetBy.Children.Add(ValveHelp($"and {valve.SetBy.Count - 24:N0} more (source_ai_valve lists them all)")); + } + private static TextBlock ValveHelp(string text) { var help = Help(text); help.Margin = new(0, 1, 0, 4); return help; } + + private void RefreshValveKind() + { + if (valveInputs == null || valveInitial == null || valveAddInput == null) return; + bool computed = ValveKindValue.Length > 0; + valveInputs.Visibility = valveAddInput.Visibility = computed ? Visibility.Visible : Visibility.Collapsed; + // A computed valve ignores its stored start. + valveInitial.Opacity = computed ? .55 : 1; + valveInitial.ToolTip = computed ? "A computed valve ignores its starting value." : null; + if (computed && valveInputBoxes.Count == 0) AddValveInput("", valveContext?.ReadOnly == null); + if (valveValueSection != null) valveValueSection.Summary = computed ? Mw3ValveMap.ConditionText(ValveKindValue) : "starts at " + valveInitial.Text.Trim(); + } + private ComboBox AddValveInput(string name, bool editable) + { + var box = ValveNameBox(name, valveContext?.Map.Valves.Select(v => v.Name).Where(n => n != valve?.Name), "Input valve"); + box.IsEnabled = editable; + // Typing or choosing another input is a change of the draft, as any field's. + box.AddHandler(TextBoxBase.TextChangedEvent, new TextChangedEventHandler((_, _) => Changed())); + box.SelectionChanged += (_, _) => Changed(); + valveInputBoxes.Add(box); + DockPanel line = new() { Margin = new(76, 2, 0, 2) }; + var remove = ValveIconButton("Close", "Remove this input", () => { valveInputBoxes.Remove(box); valveInputs!.Children.Remove(line); Changed(); }); + remove.IsEnabled = editable; + DockPanel.SetDock(remove, Dock.Right); line.Children.Add(remove); + var open = ValveIconButton("GoTo", "Show this valve", () => { if (box.Text.Trim() is { Length: > 0 } target) ValveInvoked?.Invoke(target); }); + DockPanel.SetDock(open, Dock.Right); line.Children.Add(open); + line.Children.Add(box); + valveInputs!.Children.Add(line); + return box; + } + private ValveReactionRow AddValveReaction(Mw3ValveReaction? original, Mw3ValveReactionSpec? spec, bool editable) + { + ValveReactionRow row = new(this, original, spec ?? original!.Spec, editable); + valveRows.Add(row); valveReactions!.Children.Add(row.Panel); + return row; + } + private void RefreshValveReactionSummary() + { + if (valveReactionSection == null) return; + int count = valveRows.Count(r => !r.Removed); + valveReactionSection.Summary = count.ToString(CultureInfo.CurrentCulture); + } + private void RestoreValve() + { + if (valve == null || valveInitial == null || valveKind == null || valveInputs == null || valveReactions == null) return; + bool editable = valveContext?.ReadOnly == null; + valveInitial.Text = valve.Initial.ToString(CultureInfo.InvariantCulture); + valveInputBoxes.Clear(); valveInputs.Children.Clear(); + foreach (string input in valve.Inputs) AddValveInput(input, editable); + valveKind.SelectedItem = valveKind.Items.Cast().First(i => (string)i.Tag == (valve.Condition ?? "")); + valveRows.Clear(); valveReactions.Children.Clear(); + foreach (var reaction in valve.Reactions.Take(64)) AddValveReaction(reaction, null, editable); + RefreshValveKind(); RefreshValveReactionSummary(); + } + + /// Stages changes on the open valve card as its draft (MCP source_ai_valve draft): the fields the card shows. + internal void SetValveDraft(SourceValveEdits.ValveChanges changes) + { + if (Applying || !IsEnabled) throw new StudioCommandException("busy", "Finish the current source edit before changing the valve draft."); + if (Entry is not ValveEntry || valve == null || valveInitial == null || valveKind == null) throw new StudioCommandException("not_ready", "Select the valve's World tree row first."); + if (valveContext?.ReadOnly is { } reason) throw new StudioCommandException("unsupported", reason); + if (changes.Initial != null) valveInitial.Text = changes.Initial; + if (changes.Condition != null) + valveKind.SelectedItem = valveKind.Items.Cast().FirstOrDefault(i => (string)i.Tag == changes.Condition) ?? throw new StudioCommandException("invalid_argument", "condition is any_nonzero, any_zero, all_nonzero, all_zero or empty for a switch."); + if (changes.Inputs != null) + { + valveInputBoxes.Clear(); valveInputs!.Children.Clear(); + foreach (string input in changes.Inputs.Take(256)) AddValveInput(input, true); + } + foreach (var change in changes.Reactions ?? []) + { + if (change.Occurrence is int occurrence) + { + var row = valveRows.FirstOrDefault(r => r.Original?.Occurrence == occurrence && r.Original.Spec.Kind == change.Kind) ?? throw new StudioCommandException("stale_record", "The valve has no such reaction. Read the valve again."); + if (change.Spec == null) row.SetRemoved(true); else { row.SetRemoved(false); row.Show(change.Spec); } + } + else AddValveReaction(null, change.Spec ?? throw new StudioCommandException("invalid_argument", "A new reaction needs its fields."), true); + } + RefreshValveKind(); RefreshValveReactionSummary(); Changed(); + } + + // ---------------------------------------------------------------- rows and small controls + + private static Border ValveNotice(string text) + { + DockPanel content = new(); + var icon = new PreviewIcon { Kind = "Warning", Width = 13, Height = 13, Margin = new(0, 2, 8, 0), VerticalAlignment = VerticalAlignment.Top }; + icon.SetValue(TextElement.ForegroundProperty, OutlinerKinds.Frozen(OutlinerKinds.LightTheme ? "#8A6A00" : "#FCE100")); + DockPanel.SetDock(icon, Dock.Left); content.Children.Add(icon); + content.Children.Add(new TextBlock { Text = text, FontSize = 12, TextWrapping = TextWrapping.Wrap }); + Border notice = new() { Child = content, Padding = new(10, 7, 10, 7), CornerRadius = new(6), Margin = new(0, 0, 0, 8), BorderThickness = new(1) }; + notice.SetResourceReference(BackgroundProperty, "SubtleFillColorSecondaryBrush"); + notice.SetResourceReference(BorderBrushProperty, "CardStrokeColorDefaultBrush"); + return notice; + } + private static string ValveLinkIcon(Mw3ValveLink link) => link.Role switch + { + "trigger" or "health" => "Tank", "timer" => "Timer", "fire" => "Valve", "computed" => "ValveComputed", "objective" => "Pin", "animation" => "Animation", _ => "AiNodes", + }; + /// A Set by or Used by row: its kind's icon, who (the vehicle, node, objective or valve), what in secondary text, and its link. + private FrameworkElement ValveLinkRow(Mw3ValveInfo info, Mw3ValveLink link, bool sets) + { + DockPanel row = new() { Margin = new(0, 2, 0, 2), MinHeight = 28 }; + bool linked = link.Node != null || link.Actor != null || link.Valve != null || link.Entry != null; + if (linked) + { + string what = link.Valve != null ? "Show valve " + JsonData.ShownText(link.Valve, 64) : link.Entry != null ? "Show animation " + JsonData.ShownText(link.Owner, 64) + : link.Actor != null ? "Select " + JsonData.ShownText(link.Actor, 64) : "Select " + link.Owner; + var open = ValveIconButton("GoTo", what, () => ValveLinkInvoked?.Invoke(link)); + DockPanel.SetDock(open, Dock.Right); row.Children.Add(open); + } + if (sets && ValveFire?.Invoke(info, link) is { } fire) + { + Button button = new() { Content = "Fire", Height = 26, Padding = new(10, 0, 10, 0), Margin = new(6, 0, 0, 0), FontSize = 12, VerticalAlignment = VerticalAlignment.Center, + ToolTip = $"Test: set {JsonData.ShownText(info.Name, 64)} to {link.Value}, as this would" }; + AutomationProperties.SetName(button, $"Fire {link.Owner}"); + button.Click += (_, _) => fire(); + DockPanel.SetDock(button, Dock.Right); row.Children.Add(button); + } + var icon = new PreviewIcon { Kind = ValveLinkIcon(link), Width = 14, Height = 14, Margin = new(0, 4, 8, 0), VerticalAlignment = VerticalAlignment.Top }; + icon.SetResourceReference(TextElement.ForegroundProperty, "TextFillColorSecondaryBrush"); + DockPanel.SetDock(icon, Dock.Left); row.Children.Add(icon); + TextBlock text = new() { FontSize = 12.5, TextWrapping = TextWrapping.Wrap, VerticalAlignment = VerticalAlignment.Center }; + text.Inlines.Add(new Run(JsonData.ShownText(link.Owner, 96))); + Run rest = new(" " + JsonData.ShownText(link.Text, 200)) { FontSize = 12 }; + rest.SetResourceReference(TextElement.ForegroundProperty, "TextFillColorSecondaryBrush"); + text.Inlines.Add(rest); + text.ToolTip = link.Source.Length > 0 ? link.Source : null; + row.Children.Add(text); + return row; + } + private static Button ValveIconButton(string kind, string name, Action action) + { + Button button = new() { Content = new PreviewIcon { Kind = kind, Width = 13, Height = 13 }, Width = 28, Height = 28, Padding = new(0), Margin = new(4, 0, 0, 0), ToolTip = name, VerticalAlignment = VerticalAlignment.Center }; + button.SetResourceReference(StyleProperty, "CommandButton"); + ToolTipService.SetInitialShowDelay(button, 0); + AutomationProperties.SetName(button, name); + button.Click += (_, _) => action(); + return button; + } + internal static Button ValveTextButton(string icon, string text, string name, Action action, bool accent = false) + { + StackPanel content = new() { Orientation = Orientation.Horizontal }; + content.Children.Add(new PreviewIcon { Kind = icon, Width = 13, Height = 13, Margin = new(0, 0, 7, 0), VerticalAlignment = VerticalAlignment.Center }); + content.Children.Add(new TextBlock { Text = text, VerticalAlignment = VerticalAlignment.Center }); + Button button = new() { Content = content, Height = 30, Padding = new(10, 0, 12, 0), HorizontalAlignment = HorizontalAlignment.Left, ToolTip = name }; + if (accent) button.SetResourceReference(StyleProperty, "AccentButtonStyle"); + AutomationProperties.SetName(button, text.TrimEnd('…')); + button.Click += (_, _) => action(); + return button; + } + /// An editable name with the mission's own names to choose from; typed names are accepted (a file may be edited later). + private static ComboBox ValveNameBox(string value, IEnumerable? names, string name) + { + ComboBox box = new() { IsEditable = true, IsTextSearchEnabled = false, Height = 30, HorizontalAlignment = HorizontalAlignment.Stretch, MaxDropDownHeight = 320, + ItemsSource = names?.Order(StringComparer.OrdinalIgnoreCase).Take(4096).ToArray() ?? [], Text = value }; + AutomationProperties.SetName(box, name); + return box; + } + + /// What a reaction can be, by what it does; the stored tag is in each item's tooltip. + private static readonly (string Tag, string Text)[] ValveReactionKinds = + [ + ("sound", "Play a sound"), ("animation", "Start an animation"), ("shutdown", "Wake or power down a mech"), ("destroy", "Destroy"), ("teleport", "Teleport"), + ("setteam", "Change team"), ("attack_strategy", "Change attack strategy"), ("scan_aim", "AI switch: aim scan"), ("scan_hit", "AI switch: hit scan"), + ("scan_time", "AI switch: timed scan"), ("canleave", "AI switch: may leave its network"), ("delayupdate", "Set another valve later"), + ("update", "Fire another valve's reactions"), ("missionabort", "Abort the mission"), ("missionreset", "Mission reset (no effect in the game)"), ("missioncomplete", "Mission complete (no effect in the game)"), + ]; + + /// One reaction's block: its kind, then the fields that kind stores. A new one has no original; a removed one stays, struck out, until Apply. + private sealed class ValveReactionRow + { + private readonly SourceSectionCard card; + private readonly ComboBox kind = new() { Height = 30, HorizontalAlignment = HorizontalAlignment.Stretch }; + private readonly StackPanel fields = new(); + private readonly Button remove; + private ComboBox? target, choice; + private TextBox? operand, when, x, y, z, yaw; + private CheckBox? once; + private bool showing; + internal Mw3ValveReaction? Original { get; } + internal Border Panel { get; } + internal bool Removed { get; private set; } + internal bool Changed => Original == null ? !Removed : Removed || Spec != Original.Spec; + internal string Fingerprint => $"{Original?.Occurrence}|{Original?.Spec.Kind}|{Removed}|{Spec}"; + private string BaseKind => (kind.SelectedItem as ComboBoxItem)?.Tag as string ?? "sound"; + + internal ValveReactionRow(SourceSectionCard card, Mw3ValveReaction? original, Mw3ValveReactionSpec spec, bool editable) + { + this.card = card; Original = original; + foreach (var (tag, text) in ValveReactionKinds) + { + // The two reactions without an effect are offered only where a file already stores them. + if (tag is "missionreset" or "missioncomplete" && spec.Kind != tag) continue; + kind.Items.Add(new ComboBoxItem { Content = text, Tag = tag, ToolTip = "Stored as " + tag + (tag is "sound" or "animation" ? $" (or {tag}_once)" : "") }); + } + AutomationProperties.SetName(kind, "Reaction"); + remove = ValveIconButton("Close", "Remove this reaction", () => { SetRemoved(!Removed); card.RefreshValveReactionSummary(); card.Changed(); }); + DockPanel top = new(); + DockPanel.SetDock(remove, Dock.Right); top.Children.Add(remove); top.Children.Add(kind); + StackPanel content = new(); content.Children.Add(top); content.Children.Add(fields); + Panel = new Border { Child = content, Padding = new(8, 8, 6, 6), Margin = new(0, 0, 0, 6), CornerRadius = new(5), BorderThickness = new(1) }; + Panel.SetResourceReference(Border.BorderBrushProperty, "CardStrokeColorDefaultBrush"); + Panel.SetResourceReference(Border.BackgroundProperty, "SubtleFillColorSecondaryBrush"); + if (original?.Problem != null) Panel.ToolTip = original.Problem; + kind.IsEnabled = remove.IsEnabled = editable; + Show(spec, editable); + kind.SelectionChanged += (_, _) => { if (showing) return; Build(new(BaseKind, Spec.Target, null, BaseKind is "update" or "delayupdate" ? null : Spec.When ?? "1"), true); card.Changed(); }; + } + internal void FocusFirst() => kind.Focus(); + internal void SetRemoved(bool removed) + { + Removed = removed; + fields.Opacity = kind.Opacity = removed ? .4 : 1; + fields.IsEnabled = kind.IsEnabled = !removed; + remove.ToolTip = removed ? "Keep this reaction" : "Remove this reaction"; + AutomationProperties.SetName(remove, (string)remove.ToolTip); + ((PreviewIcon)remove.Content).Kind = removed ? "Undo" : "Close"; + // A new reaction that is removed again simply goes. + if (removed && Original == null) { card.valveRows.Remove(this); card.valveReactions?.Children.Remove(Panel); } + } + internal void Show(Mw3ValveReactionSpec spec, bool editable = true) + { + showing = true; + try + { + string tag = spec.Kind is "sound_once" ? "sound" : spec.Kind is "animation_once" ? "animation" : spec.Kind; + kind.SelectedItem = kind.Items.Cast().FirstOrDefault(i => (string)i.Tag == tag); + Build(spec, editable); + } + finally { showing = false; } + } + /// The fields as the reaction they describe. + internal Mw3ValveReactionSpec Spec + { + get + { + string tag = BaseKind; + if (tag is "sound" or "animation" && once?.IsChecked == true) tag += "_once"; + string? Text(TextBox? box) => box?.Text.Trim(); + return new(tag, target?.Text.Trim(), choice != null ? (choice.SelectedItem as ComboBoxItem)?.Tag as string : Text(operand), Text(when), Text(x), Text(y), Text(z), Text(yaw)); + } + } + private void Build(Mw3ValveReactionSpec spec, bool editable) + { + fields.Children.Clear(); fields.IsEnabled = editable && !Removed; + target = null; choice = null; operand = when = x = y = z = yaw = null; once = null; + var catalog = card.valveContext?.Catalog; var valves = card.valveContext?.Map.Valves.Select(v => v.Name); + string tag = BaseKind; + void Target(string caption, IEnumerable? names, bool isValve = false) + { + target = ValveNameBox(spec.Target ?? "", names, caption); + target.AddHandler(TextBoxBase.TextChangedEvent, new TextChangedEventHandler((_, _) => card.Changed())); + FrameworkElement value = target; + if (isValve) + { + DockPanel line = new(); + var box = target; + var open = ValveIconButton("GoTo", "Show this valve", () => { if (box.Text.Trim() is { Length: > 0 } name) card.ValveInvoked?.Invoke(name); }); + DockPanel.SetDock(open, Dock.Right); line.Children.Add(open); line.Children.Add(target); + value = line; + } + fields.Children.Add(Field(caption, value)); + } + TextBox Number(string caption, string? text, string name, string? suffix = null, double width = 84) + { + TextBox box = new() { Text = text ?? "", Height = 30, Width = width, MaxLength = 24, HorizontalAlignment = HorizontalAlignment.Left }; + AutomationProperties.SetName(box, name); + box.TextChanged += (_, _) => card.Changed(); + FrameworkElement value = box; + if (suffix != null) + { + StackPanel line = new() { Orientation = Orientation.Horizontal }; line.Children.Add(box); + TextBlock unit = new() { Text = suffix, FontSize = 12, Margin = new(6, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center }; + unit.SetResourceReference(TextBlock.ForegroundProperty, "TextFillColorSecondaryBrush"); + line.Children.Add(unit); value = line; + } + fields.Children.Add(Field(caption, value)); + return box; + } + void Choice(string caption, (string Value, string Text)[] options) + { + choice = new ComboBox { Height = 30, HorizontalAlignment = HorizontalAlignment.Stretch }; + AutomationProperties.SetName(choice, caption); + foreach (var (value, text) in options) choice.Items.Add(new ComboBoxItem { Content = text, Tag = value }); + // A stored value the choice does not name (2, say) is kept and shown as it is. + if (spec.Operand != null && options.All(o => o.Value != spec.Operand)) choice.Items.Add(new ComboBoxItem { Content = "Stored: " + spec.Operand, Tag = spec.Operand }); + choice.SelectedItem = choice.Items.Cast().FirstOrDefault(i => (string)i.Tag == (spec.Operand ?? options[0].Value)); + choice.SelectionChanged += (_, _) => card.Changed(); + fields.Children.Add(Field(caption, choice)); + } + void When() => when = Number("When it becomes", spec.When ?? "1", "Triggering value"); + switch (tag) + { + case "sound" or "animation": + // The mission's sound banks are not read for the card: the picker offers the sounds its valves already play. + Target(tag == "sound" ? "Sound" : "Animation", tag == "sound" ? catalog?.Sounds ?? card.valveContext?.Map.Valves.SelectMany(v => v.Reactions) + .Where(r => r.Spec.Kind is "sound" or "sound_once" && r.Spec.Target is { Length: > 0 }).Select(r => r.Spec.Target!).Distinct(StringComparer.Ordinal) : catalog?.Animations); + When(); + once = new CheckBox { Content = "Only the first time", IsChecked = spec.Kind.EndsWith("_once", StringComparison.Ordinal), Margin = new(108, 2, 0, 0), FontSize = 12.5 }; + once.Checked += (_, _) => card.Changed(); once.Unchecked += (_, _) => card.Changed(); + fields.Children.Add(once); + break; + case "shutdown": Target("Mech", catalog?.Vehicles); Choice("Do", [("0", "Wake (power up)"), ("1", "Power down")]); When(); break; + case "destroy": Target("Vehicle or target", catalog?.Vehicles); When(); break; + case "teleport": + Target("Vehicle", catalog?.Vehicles); + x = Number("X", spec.X ?? "0", "X"); y = Number("Y", spec.Y ?? "0", "Y"); z = Number("Z", spec.Z ?? "0", "Z"); + yaw = Number("Heading", spec.Yaw ?? "0", "Heading"); When(); + break; + case "setteam": Target("Vehicle or target", catalog?.Vehicles); operand = Number("Team", spec.Operand ?? "0", "Team"); When(); break; + case "attack_strategy": Target("Vehicle", catalog?.Vehicles); operand = Number("Strategy", spec.Operand ?? "0", "Attack strategy"); When(); break; + case "scan_aim" or "scan_hit" or "scan_time" or "canleave": Target("Vehicle", catalog?.Vehicles); Choice("Switch", [("1", "On"), ("0", "Off")]); When(); break; + case "delayupdate": + Target("Valve", valves, isValve: true); operand = Number("After", spec.Operand ?? "1", "Delay in seconds", "s"); + operand.ToolTip = "Seconds after this valve changes. The other valve then takes the value this one had."; + break; + case "update": Target("Valve", valves, isValve: true); break; + default: When(); break; + } + } + private static Grid Field(string caption, FrameworkElement value) + { + Grid row = Row(caption, value, 108); row.Margin = new(0, 4, 0, 0); + return row; + } + } +} diff --git a/src/zStudio.Desktop/SourceSectionCard.cs b/src/zStudio.Desktop/SourceSectionCard.cs index 9174b354..cf9afeb0 100644 --- a/src/zStudio.Desktop/SourceSectionCard.cs +++ b/src/zStudio.Desktop/SourceSectionCard.cs @@ -362,18 +362,19 @@ internal void ShowDefinition(DocumentModel document, DefinitionEntry entry, IRea // ---------------------------------------------------------------- the draft /// The zone's label, a network's field or a node's links differ from what is stored. - internal bool HasDraft => !Accepting && (Entry is ZoneEntry && label != null && label.Text.Trim() != labelInitial || Entry is NetworkEntry && (inputs.Any(i => i.Changed) || linkInputs.Any(l => l.Changed)) || Entry is DefinitionEntry && animationChanges.Count > 0); - internal string DraftToken => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes($"{draftId}|{Document?.SessionId}|{Document?.Revision}|{Entry?.Key}|{(label?.Text ?? "")}|{string.Join("\u0001", inputs.Select(i => string.Join("\u0002", i.Values)))}|{string.Join("\u0001", linkInputs.Select(l => l.Changed ? l.Value + "\u0002" : l.Value))}|{System.Text.Json.JsonSerializer.Serialize(animationChanges)}"))); + internal bool HasDraft => !Accepting && (ValveHasDraft || Entry is ZoneEntry && label != null && label.Text.Trim() != labelInitial || Entry is NetworkEntry && (inputs.Any(i => i.Changed) || linkInputs.Any(l => l.Changed)) || Entry is DefinitionEntry && animationChanges.Count > 0); + internal string DraftToken => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes($"{ValveDraftFingerprint}|{draftId}|{Document?.SessionId}|{Document?.Revision}|{Entry?.Key}|{(label?.Text ?? "")}|{string.Join("\u0001", inputs.Select(i => string.Join("\u0002", i.Values)))}|{string.Join("\u0001", linkInputs.Select(l => l.Changed ? l.Value + "\u0002" : l.Value))}|{System.Text.Json.JsonSerializer.Serialize(animationChanges)}"))); /// The changes a network's draft makes, as requested values. internal IReadOnlyList NetworkChanges => [.. inputs.Where(i => i.Changed).Select(i => new SourceAiNetworkEdits.Change(i.Field.Key, i.Values))]; /// The links a network's draft changes, as requested node numbers (a value the edit refuses throws its message). internal IReadOnlyList LinkChanges => [.. linkInputs.Where(l => l.Changed).Select(l => new SourceAiNetworkEdits.LinkChange(l.Index, SourceAiNetworkEdits.ParseLinks(l.Value)))]; internal object Describe() => new { - token = DraftToken, pending = HasDraft, kind = Entry switch { ZoneEntry => "zone", NetworkEntry => "network", DefinitionEntry => "definition", _ => null }, + token = DraftToken, pending = HasDraft, kind = Entry switch { ZoneEntry => "zone", NetworkEntry => "network", DefinitionEntry => "definition", ValveEntry => "valve", _ => null }, target = Entry?.Key, revision = Document?.Revision, applying = Applying, // Why the last Apply was refused, or why the card cannot edit (a binary source); the card shows it above its sections. error = error.Visibility == Visibility.Visible ? error.Text : null, + valve = ValveDraft, label = Entry is ZoneEntry ? label?.Text : null, animation = AnimationDraft, fields = Entry is NetworkEntry ? inputs.Select(i => new { key = i.Field.Key, values = i.Values, stored = i.Initial, changed = i.Changed }).ToArray() : null, @@ -401,6 +402,7 @@ internal void Discard() if (Applying) return; animationChanges.Clear(); typedFrom.Clear(); RerenderAnimation(); if (label != null) label.Text = labelInitial; + RestoreValve(); foreach (var input in inputs) for (int i = 0; i < input.Boxes.Length; i++) Restore(input.Boxes[i], input.Initial[i]); foreach (var link in linkInputs) link.Restore(); @@ -417,6 +419,7 @@ internal async Task ApplyAsync() if (Entry is ZoneEntry zone && ApplyLabel != null) await ApplyLabel(zone.Zone.Zone, label!.Text.Trim()); else if (Entry is NetworkEntry network && ApplyNetwork != null) await ApplyNetwork(network.Network.Id, NetworkChanges, LinkChanges); else if (Entry is DefinitionEntry definition && ApplyAnimation != null) await ApplyAnimation(definition.Definition.Index, animationChanges.Values.ToArray()); + else if (Entry is ValveEntry valveEntry && ApplyValve != null) await ApplyValve(valveEntry.Valve.Name, ValveChanges); // Accepted: what was applied is now stored (until the rebuilt map shows the card again with its own values). if (ReferenceEquals(Entry, applied)) Adopt(); } @@ -429,6 +432,8 @@ private void Adopt() { animationChanges.Clear(); typedFrom.Clear(); if (label != null) labelInitial = label.Text.Trim(); + // The rebuilt map shows the valve again with what is now stored. + if (Entry is ValveEntry) valveApplied = true; // The edit stored Buddies Activate when it was checked, or when Buddies Attack was turned on (Plan adds it then). var attack = inputs.FirstOrDefault(i => i.Field.Key == "attack_buddy"); if (inputs.FirstOrDefault(i => i.Field.Key == "activate_buddy") is { Stored: null } activate && (activate.Changed || attack is { Changed: true } && attack.Values[0] == "1")) @@ -450,8 +455,8 @@ internal async Task ResolvePendingAsync() { if (Applying) return Accepting; if (!HasDraft) return true; - string subject = Entry switch { ZoneEntry => "zone label", DefinitionEntry => "animation changes", _ => "network changes" }; - string title = Entry switch { ZoneEntry => "Zone label draft", DefinitionEntry => "Animation draft", _ => "AI network draft" }; + string subject = Entry switch { ZoneEntry => "zone label", DefinitionEntry => "animation changes", ValveEntry => "valve changes", _ => "network changes" }; + string title = Entry switch { ZoneEntry => "Zone label draft", DefinitionEntry => "Animation draft", ValveEntry => "Valve draft", _ => "AI network draft" }; var answer = MessageBox.Show(Window.GetWindow(this), $"Apply the pending {subject}?\nYes: apply · No: discard · Cancel: keep editing", title, MessageBoxButton.YesNoCancel, MessageBoxImage.Question); if (answer == MessageBoxResult.Cancel) return false; @@ -462,6 +467,7 @@ internal async Task ResolvePendingAsync() internal void FocusFirst() { if (label != null) { label.Focus(); label.SelectAll(); } + else if (Entry is ValveEntry && valveInitial != null) { valveInitial.Focus(); valveInitial.SelectAll(); } else if (Entry is DefinitionEntry) body.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); else if (inputs.FirstOrDefault()?.Boxes[0] is { } first) first.Focus(); } @@ -474,6 +480,8 @@ private void Begin(SectionEntry entry, DocumentModel document) if (Entry?.Key != entry.Key || !ReferenceEquals(Document, document)) draftId = Guid.NewGuid(); Entry = entry; Document = document; body.Children.Clear(); inputs.Clear(); networkRows.Clear(); linkInputs.Clear(); linkTargets = []; buddiesBar = null; activateWritten = false; label = null; labelInitial = ""; + valve = null; valveContext = null; valveInitial = null; valveKind = null; valveInputs = null; valveReactions = null; valveTestHost = null; valveReactionSection = valveValueSection = null; + valveAddInput = null; valveInputBoxes.Clear(); valveRows.Clear(); valveApplied = false; valveSetBy = null; valveSetByFiring = false; if (!Applying) Error(null); } private void Finish(bool editable) diff --git a/src/zStudio.Mcp/CommandCatalog.json b/src/zStudio.Mcp/CommandCatalog.json index 3faf8037..aaf26cd5 100644 --- a/src/zStudio.Mcp/CommandCatalog.json +++ b/src/zStudio.Mcp/CommandCatalog.json @@ -3879,6 +3879,457 @@ } ] }, + { + "Name": "zstudio_source_ai_valve", + "Description": "Read or edit the valves of the shown MW3 source mission. A valve is a named whole-number switch; the World tree\u0027s Valves section and its card show one per exact name, gathered from valves.zrd (starting value, computed condition, reactions), aiv.zrd vehicle triggers, targets.zrd health thresholds, the networks\u0027 route gates, assignments and deploy points, and this mission\u0027s objectives. valves pages them (name, summary, counts, problems); valve reads one (initial: the stored starting value, which a computed valve keeps but ignores; condition and inputs, reactions with their fields, setBy and usedBy links, records; setBy also lists the animations that set it through callbacks 42\u201349 on the scene node of its name, role animation with animationEntry). set applies the card\u0027s changes as one undoable change of valves.zrd that keeps comments, layout and unknown tags: initial; condition (any_nonzero, any_zero, all_nonzero, all_zero, or empty for a plain switch) with inputs; reactions, each an existing one by occurrence and storedKind (fields to change it, remove: true to remove it) or a new one (fields only; written as its own record after the valve\u0027s last). new adds a valve starting at 0; rename renames it in every file of the mission that names it (one change; refused for a valve an animation sets, which keeps its scene node\u0027s name); remove deletes its valves.zrd records. draft stages the same changes on the selected valve\u0027s card (Apply, Revert and resolve_drafts as for any card). Record level: sources, records, read, create, update, delete and attach edit one stored record or node attribute as zReader text. Test state is ai_valve_preview\u0027s and is never saved. Returns an operation ID; use zstudio_operation to await/read the result.", + "Mutates": true, + "Parameters": [ + { + "Name": "document", + "Type": "string", + "Description": "Document lifetime ID from zstudio_state.", + "Required": true, + "Choices": null, + "Properties": null + }, + { + "Name": "revision", + "Type": "integer", + "Description": "Expected current document revision. Read before editing.", + "Required": false, + "Choices": null, + "Properties": null, + "Minimum": 0, + "Maximum": 9223372036854775807 + }, + { + "Name": "action", + "Type": "string", + "Description": "Operation.", + "Required": true, + "Choices": [ + "valves", + "valve", + "set", + "new", + "rename", + "remove", + "draft", + "sources", + "records", + "read", + "create", + "update", + "delete", + "attach" + ], + "Properties": null + }, + { + "Name": "name", + "Type": "string", + "Description": "valve, set, new, rename, remove, draft: the exact case-sensitive valve name. create, update: the record\u0027s name.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "newName", + "Type": "string", + "Description": "rename: the new name.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "changes", + "Type": "object", + "Description": "set, draft: what changes; omitted parts stay.", + "Required": false, + "Choices": null, + "Properties": [ + { + "Name": "initial", + "Type": "string", + "Description": "The starting value, a whole number.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "condition", + "Type": "string", + "Description": "Computed kind, or empty for a plain switch.", + "Required": false, + "Choices": [ + "", + "any_nonzero", + "any_zero", + "all_nonzero", + "all_zero" + ], + "Properties": null + }, + { + "Name": "inputs", + "Type": "array", + "Description": "A computed valve\u0027s input valves, in order.", + "Required": false, + "Choices": null, + "Properties": null, + "Items": { + "Name": "", + "Type": "string", + "Description": "A valve name.", + "Required": false, + "Choices": null, + "Properties": null + }, + "MaxItems": 256 + }, + { + "Name": "reactions", + "Type": "array", + "Description": "Reactions to change, remove or add.", + "Required": false, + "Choices": null, + "Properties": null, + "Items": { + "Name": "", + "Type": "object", + "Description": "One reaction.", + "Required": false, + "Choices": null, + "Properties": [ + { + "Name": "occurrence", + "Type": "integer", + "Description": "An existing reaction\u0027s record occurrence (from valve); omit for a new one.", + "Required": false, + "Choices": null, + "Properties": null, + "Minimum": 0, + "Maximum": 2147483647 + }, + { + "Name": "storedKind", + "Type": "string", + "Description": "An existing reaction\u0027s stored tag (from valve).", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "remove", + "Type": "boolean", + "Description": "Remove this existing reaction.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "fields", + "Type": "object", + "Description": "The reaction as the card shows it.", + "Required": false, + "Choices": null, + "Properties": [ + { + "Name": "kind", + "Type": "string", + "Description": "The stored tag.", + "Required": true, + "Choices": [ + "sound", + "sound_once", + "animation", + "animation_once", + "shutdown", + "destroy", + "teleport", + "setteam", + "attack_strategy", + "scan_aim", + "scan_hit", + "scan_time", + "canleave", + "delayupdate", + "update", + "missionabort", + "missionreset", + "missioncomplete" + ], + "Properties": null + }, + { + "Name": "target", + "Type": "string", + "Description": "The sound, animation, vehicle or valve it names (none for the mission reactions).", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "operand", + "Type": "string", + "Description": "shutdown: 0 wake, 1 power down; scans and canleave: 1 on, 0 off; setteam: the team; attack_strategy: the strategy; delayupdate: seconds.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "when", + "Type": "string", + "Description": "The valve value that triggers it, a whole number (not for update and delayupdate, which run on every change).", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "x", + "Type": "string", + "Description": "teleport: X.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "y", + "Type": "string", + "Description": "teleport: Y.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "z", + "Type": "string", + "Description": "teleport: Z.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "yaw", + "Type": "string", + "Description": "teleport: heading.", + "Required": false, + "Choices": null, + "Properties": null + } + ] + } + ] + }, + "MaxItems": 64 + } + ] + }, + { + "Name": "source", + "Type": "string", + "Description": "Record level: exact relative source path from sources.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "record", + "Type": "string", + "Description": "Record level: occurrence ID from records.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "nodeIndex", + "Type": "integer", + "Description": "attach: uniquely resolved spatial node number.", + "Required": false, + "Choices": null, + "Properties": null, + "Minimum": -2147483648, + "Maximum": 2147483647 + }, + { + "Name": "attribute", + "Type": "string", + "Description": "attach: node attribute.", + "Required": false, + "Choices": [ + "valve", + "valveunion", + "valve_assign" + ], + "Properties": null + }, + { + "Name": "parameters", + "Type": "string", + "Description": "Record level: ordered zReader parameter array, at most 65,536 characters.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "draft", + "Type": "string", + "Description": "draft: the current card draft token when a draft is already open.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "offset", + "Type": "integer", + "Description": "Zero-based result offset.", + "Required": false, + "Choices": null, + "Properties": null, + "Minimum": -2147483648, + "Maximum": 2147483647 + }, + { + "Name": "limit", + "Type": "integer", + "Description": "Page size, 1\u2013200; default 100.", + "Required": false, + "Choices": null, + "Properties": null, + "Minimum": -2147483648, + "Maximum": 2147483647 + }, + { + "Name": "query", + "Type": "string", + "Description": "Case-insensitive name/path or displayed-text filter, applied before pagination.", + "Required": false, + "Choices": null, + "Properties": null + } + ] + }, + { + "Name": "zstudio_ai_valve_preview", + "Description": "The valve test of the shown MW3 source mission (the Valves row\u0027s Test, the banner over the view and the valve card\u0027s Test section): the mission\u0027s valves run in memory from 0 s with their conditions, reactions and timers, animation callbacks 42\u201349, vehicle state and route gates. start (or prepare) begins it paused and returns its simulation ID, which the other actions need; state reads it (time, playing, the first 64 values, timers, vehicles and the latest activity). set gives a valve a value (as a trigger, threshold or route would), update fires its reactions without changing it, traverse drives a vehicle through a node\u0027s outgoing link slot (refused while its valves close it; its assignments apply). play, pause, step (one tick), advance (to an absolute time, at most one hour), next (to the first tick on which the next pending timer runs), reset (back to 0 s, a new ID) and stop. trace, timers, values and vehicles page the whole state. Nothing is saved; a source edit, another mission or Animation mode ends it. Gameplay is manual: no AI drives, fights or triggers on its own. Returns an operation ID; use zstudio_operation to await/read the result.", + "Mutates": true, + "Parameters": [ + { + "Name": "preview", + "Type": "string", + "Description": "Current preview lifetime ID from zstudio_state.", + "Required": true, + "Choices": null, + "Properties": null + }, + { + "Name": "action", + "Type": "string", + "Description": "Operation.", + "Required": true, + "Choices": [ + "state", + "start", + "prepare", + "play", + "pause", + "step", + "advance", + "next", + "reset", + "stop", + "set", + "update", + "traverse", + "trace", + "timers", + "values", + "actors" + ], + "Properties": null + }, + { + "Name": "simulation", + "Type": "string", + "Description": "Current simulation ID; required except start, prepare and state.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "name", + "Type": "string", + "Description": "set, update: exact valve name.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "value", + "Type": "integer", + "Description": "set: the value.", + "Required": false, + "Choices": null, + "Properties": null, + "Minimum": -2147483648, + "Maximum": 2147483647 + }, + { + "Name": "seconds", + "Type": "number", + "Description": "advance: absolute test time, the current time through 3600 seconds.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "node", + "Type": "string", + "Description": "traverse: snapshot-scoped AI node ID.", + "Required": false, + "Choices": null, + "Properties": null + }, + { + "Name": "slot", + "Type": "integer", + "Description": "traverse: physical outgoing link slot.", + "Required": false, + "Choices": null, + "Properties": null, + "Minimum": -2147483648, + "Maximum": 2147483647 + }, + { + "Name": "offset", + "Type": "integer", + "Description": "Zero-based result offset.", + "Required": false, + "Choices": null, + "Properties": null, + "Minimum": -2147483648, + "Maximum": 2147483647 + }, + { + "Name": "limit", + "Type": "integer", + "Description": "Page size, 1\u2013200; default 100.", + "Required": false, + "Choices": null, + "Properties": null, + "Minimum": -2147483648, + "Maximum": 2147483647 + }, + { + "Name": "query", + "Type": "string", + "Description": "Case-insensitive name/path or displayed-text filter, applied before pagination.", + "Required": false, + "Choices": null, + "Properties": null + } + ] + }, { "Name": "zstudio_scene_inspect", "Description": "Read independent hover/selection information from the fixed top-right inspection panel (a source map docks it as the Properties pane, with the hover readout as the surface chip over the view), or query an explicit viewport point/target without moving the mouse. Parent(s) describes the selected object or authored source-tree occurrence; Surface node and Surface parent(s) separately describe a clicked internal mesh. glTF node indices and compiled source slots are distinct. The permanent hover readout clears its coordinates over empty space. Coordinates distinguish triangle hits, object origins and authored placement positions. Zone is the selected object\u0027s built zone ID (Any is 255), as Inherit (ID) when its source node inherits it, with its altitude zone check; Surface zone and Polygon zones separately describe a clicked internal mesh and its polygon (an empty polygon set has no zones); Object polygon zones (the selection only) counts the zone sets of the object\u0027s polygons and those below it: rows of zones (255 is Any, empty none) or moreSets or unknown, each with polygons, then total and truncated. In source worlds, Zone source names the glTF node, reference placement, ancestor or load root that supplied it. AI results include attackStrategy/hoverAttackStrategy with stored value, status, key, character count, truncation and network RGB hex color. Panel state includes preferred/effective heights, viewport limits, expanded state and whether a source map docks it as the Properties pane. In a source map, animations lists what the object card ends with: Animations affecting this object (affecting: the first 8 with their definition and entry for animation_mode open, total; scene_tree animationUses pages them all) and, in Animation mode, eventsNaming: the opened definition\u0027s graph rows whose events name it (animation_graph select). recentSelections lists the empty pane\u0027s Recently selected objects (newest first) with the node scene_tree select takes for each (null when it is no longer in the world).", @@ -4121,7 +4572,7 @@ }, { "Name": "zstudio_scene_tree", - "Description": "Read the Document scene hierarchy, including stable preview placements, shared/partition references and disconnected nodes. Source maps show the World tree: the authored glTF hierarchy, including groups removed by compilation, under the World root, then section rows (sectionRow.section) and pass rows in a fixed order: World, Zones, AI Vehicles (pass aiv: units the AIV resources place), AI Networks, Pickups (pass puppies) and Animations (section definitions: the map\u0027s definition files, then Common, then Objects placed by animations, pass anim: objects startup animations place or hide until placed). Zones lists the map\u0027s zones (sectionRow zoneId, label, polygons, placements, models, objects = ownObjects \u002B inheritedObjects with emptyObjects among them, used) and polygons without a zone; AI Networks lists the mission\u0027s networks (sectionRow network = the file\u0027s project path, name, nodes, attackStrategy); Animations lists the .zad files the mission\u0027s anim.zad names directly (no map scope row; a file with one definition is that definition; sectionRow definitionFile, occurrence, listedBy, definitions, affectsSelection when closed over a definition bound to the selected object), then one Common row (sectionRow definitionScope Common: data/common, shared by every map) holding the common ones the same way, and listed files that are missing; with scene_options animationsByStart the definitions are in one row per start kind instead (category definitionGroup; sectionRow kind definitionGroup, scope map or Common, start opening, startup, damage, called, game or none, label, count; never selected; Common holds its own). Each definition (sectionRow definition, definitionFile, ordinal, occurrence, name, rootName, roots/bound: what it binds in this world, null when unknown; bindings: its entries) says how it starts (start: kind opening (NEW_GAME_START), load (LOAD_GAME_START), startup, damage, called (a call of the map reaches it), game (the game starts it on the map\u0027s units: pickups, vehicles, turrets, trails, weapon flyouts) or none (no caller found: the game may still play it by name), its detail, activation as compiled, health, callerCount, callers: up to 8 calling definitions with their calling bindings, known: false when the map\u0027s animations did not build), what it acts on (target: kind object, objects, template (bound only to nodes no World tree row lists), playerTank, units or none (not in this map), text as the row shows it, count), duplicateOf (the earlier definition of the same name that calls, stops and prerequisites reach), opened (Animation mode has it open), kept (its scenario is kept after Exit), affectsSelection (bound to the selected object) and frameable; the fields are null until the map\u0027s summary is built, which every scene_tree call awaits. A definition with several bindings lists them (sectionRow kind animationBinding, entry, name: the name calls use, its Label, rootName, opened, frameable). Zones and AI networks are shown one by one and start hidden (sectionRow shown); any shown zone turns the zone overlay on and any shown network the AI overlay (always drawn through geometry, at half strength where it hides them). The Zones, AI Networks, AI Vehicles and Pickups rows carry master (true: shown, so hide is what their eye does next; it follows when everything below comes to be shown or hidden one by one); Zones also reports its overlay kind (objects or polygons) and paused while Edit zones is on. The aiv and puppies passes list every difficulty\u0027s units and pickups with the difficulties placing each; those the shown difficulty does not place have otherDifficulty=true, node=null and a placement summary, and cannot be selected; placed rows matched to their records carry the placement summary too (including how often a resource lists that placement). Pickups always hold three group rows, Weapons, Ammo and Other (category pickupGroup; sectionRow kind, group weapons/ammo/other, count and shown = placed on the shown difficulty), which open and close, hide and show (master) and frame their pickups but are never selected; with scene_options pickupsByType each holds a row per catalog type (category pickupType; sectionRow group, pickupType, shortName, name, count, shown). Pickup rows expose pickupType (catalog name), pickupKind (ammo, weapon, health or technology), pickupGroup, pickupNumber (per catalog type in list order over every difficulty), pickupShortName, pickupName (the game manual\u0027s name; ammo adds the word ammo), instanceName (the game\u0027s name, null on other-difficulty rows) and pickupTemplate; their Label is the short name and number (ERFPG #1). These fields are null on non-pickup rows. The player tank\u0027s row (the first vehicle the shown difficulty\u0027s AIV layout spawns, identified by placement, not name) has playerTank true, null elsewhere; preview_state.bft describes how the view draws it. A unit or pickup every difficulty places shows All as its difficulty tag. animations lists resolved initial-root and indirect animation associations (at most eight names, then an ellipsis). animationUses supplies the first eight entryIndex/name/origin/reason records (origin initialRoot or indirect), animationUseCount how many there are and animationUsesTruncated whether more exist; action animationUses (row or node) pages every one of them, uncapped, as the object card\u0027s Animations affecting this object and the glyph flyout list them (with each one\u0027s definition for animation_mode open) and animationHasInitialRoot and animationHasIndirect retain both origin summaries even when details are capped. The original cyan icon marks any initial-root association; indirect-only recipients use the same glyph at half HSL saturation. Position references and unknown impact targets do not imply animation ownership. World objects expand into exact child objects, geometry and LOD branches, including initialized hidden healthy/destroyed states. select targets the exact row; map hits still select the whole object. Child hide/show uses session-only part gates and may rebuild the preview; use the returned context and preview afterwards. visibility reports DefaultVisible, Visible, Override, EffectiveVisible and Reason. sourceFile/gltfNode identify authored nodes, sourceOccurrence identifies a tree path, and compiledNode is an optional built slot. selectionOwner for source_map_parts is a signed current-preview identity; source-only authored groups have node=null and selectionOwner=null and support read-only row inspection. properties focuses the source-object card, or opens pinned Properties in other viewers. Read returns roots or a row\u0027s direct children, optionally filtered before paging; in a source map, search and/or types read the whole hierarchy as a flat list of matches with their parent paths, as the outliner\u0027s search box does (types narrows it by the legend\u0027s categories). A row\u0027s zone is null in the aiv and puppies passes. Source map rows carry category (world, group, geometry, empty: an Object3D without a model or children, which draws nothing and cannot be hidden or framed; object, node, zone, network, definition), zone and hidden. Expand/collapse/reveal only change tree presentation; hide/show hide a row\u0027s object (a removed group: what it holds) in the view only, like the outliner\u0027s eye, except that show, and an isolate that ends or moves an isolation (as scene_selection show_all and isolate), select in the view an object the card shows as hidden because it was selected in the tree while hidden (only with no draft open; after an AI path or drop-window draft ends this follows once the application is idle, after that command returned, so read scene_inspect or preview_state afterwards): the view selection, the card and scene_inspect selected change, and its placement can be edited; on the Zones, AI Networks, AI Vehicles (pass aiv) and Pickups (pass puppies) rows they hide or show everything below them, on a zone its colour and on a network its nodes and links (preview_state sections reports them); isolate works on world objects only (zones, networks, units and pickups are refused). select shares scene inspection and draft guards; selecting a zone, network or definition ends the object selection and opens its card in the Properties pane (a network is shown and emphasised, a definition\u0027s bound objects outlined; drafts target section), and properties also focuses the card\u0027s first field. Runtime parenting is not represented.", + "Description": "Read the Document scene hierarchy, including stable preview placements, shared/partition references and disconnected nodes. Source maps show the World tree: the authored glTF hierarchy, including groups removed by compilation, under the World root, then section rows (sectionRow.section) and pass rows in a fixed order: World, Zones, AI Vehicles (pass aiv: units the AIV resources place), AI Networks, Valves (MW3 maps only), Pickups (pass puppies) and Animations (section definitions: the map\u0027s definition files, then Common, then Objects placed by animations, pass anim: objects startup animations place or hide until placed). Zones lists the map\u0027s zones (sectionRow zoneId, label, polygons, placements, models, objects = ownObjects \u002B inheritedObjects with emptyObjects among them, used) and polygons without a zone; AI Networks lists the mission\u0027s networks (sectionRow network = the file\u0027s project path, name, nodes, attackStrategy); Valves (section valves: count, source, testing while ai_valve_preview runs) lists an MW3 mission\u0027s valves one per exact name (sectionRow kind valve, name, defined, computed, summary, setBy, reactions, usedBy and problems counts; select shows the valve\u0027s card, source_ai_valve reads and edits it, frame frames its vehicles and route nodes); Animations lists the .zad files the mission\u0027s anim.zad names directly (no map scope row; a file with one definition is that definition; sectionRow definitionFile, occurrence, listedBy, definitions, affectsSelection when closed over a definition bound to the selected object), then one Common row (sectionRow definitionScope Common: data/common, shared by every map) holding the common ones the same way, and listed files that are missing; with scene_options animationsByStart the definitions are in one row per start kind instead (category definitionGroup; sectionRow kind definitionGroup, scope map or Common, start opening, startup, damage, called, game or none, label, count; never selected; Common holds its own). Each definition (sectionRow definition, definitionFile, ordinal, occurrence, name, rootName, roots/bound: what it binds in this world, null when unknown; bindings: its entries) says how it starts (start: kind opening (NEW_GAME_START), load (LOAD_GAME_START), startup, damage, called (a call of the map reaches it), game (the game starts it on the map\u0027s units: pickups, vehicles, turrets, trails, weapon flyouts) or none (no caller found: the game may still play it by name), its detail, activation as compiled, health, callerCount, callers: up to 8 calling definitions with their calling bindings, known: false when the map\u0027s animations did not build), what it acts on (target: kind object, objects, template (bound only to nodes no World tree row lists), playerTank, units or none (not in this map), text as the row shows it, count), duplicateOf (the earlier definition of the same name that calls, stops and prerequisites reach), opened (Animation mode has it open), kept (its scenario is kept after Exit), affectsSelection (bound to the selected object) and frameable; the fields are null until the map\u0027s summary is built, which every scene_tree call awaits. A definition with several bindings lists them (sectionRow kind animationBinding, entry, name: the name calls use, its Label, rootName, opened, frameable). Zones and AI networks are shown one by one and start hidden (sectionRow shown); any shown zone turns the zone overlay on and any shown network the AI overlay (always drawn through geometry, at half strength where it hides them). The Zones, AI Networks, AI Vehicles and Pickups rows carry master (true: shown, so hide is what their eye does next; it follows when everything below comes to be shown or hidden one by one); Zones also reports its overlay kind (objects or polygons) and paused while Edit zones is on. The aiv and puppies passes list every difficulty\u0027s units and pickups with the difficulties placing each; those the shown difficulty does not place have otherDifficulty=true, node=null and a placement summary, and cannot be selected; placed rows matched to their records carry the placement summary too (including how often a resource lists that placement). Pickups always hold three group rows, Weapons, Ammo and Other (category pickupGroup; sectionRow kind, group weapons/ammo/other, count and shown = placed on the shown difficulty), which open and close, hide and show (master) and frame their pickups but are never selected; with scene_options pickupsByType each holds a row per catalog type (category pickupType; sectionRow group, pickupType, shortName, name, count, shown). Pickup rows expose pickupType (catalog name), pickupKind (ammo, weapon, health or technology), pickupGroup, pickupNumber (per catalog type in list order over every difficulty), pickupShortName, pickupName (the game manual\u0027s name; ammo adds the word ammo), instanceName (the game\u0027s name, null on other-difficulty rows) and pickupTemplate; their Label is the short name and number (ERFPG #1). These fields are null on non-pickup rows. The player tank\u0027s row (the first vehicle the shown difficulty\u0027s AIV layout spawns, identified by placement, not name) has playerTank true, null elsewhere; preview_state.bft describes how the view draws it. A unit or pickup every difficulty places shows All as its difficulty tag. animations lists resolved initial-root and indirect animation associations (at most eight names, then an ellipsis). animationUses supplies the first eight entryIndex/name/origin/reason records (origin initialRoot or indirect), animationUseCount how many there are and animationUsesTruncated whether more exist; action animationUses (row or node) pages every one of them, uncapped, as the object card\u0027s Animations affecting this object and the glyph flyout list them (with each one\u0027s definition for animation_mode open) and animationHasInitialRoot and animationHasIndirect retain both origin summaries even when details are capped. The original cyan icon marks any initial-root association; indirect-only recipients use the same glyph at half HSL saturation. Position references and unknown impact targets do not imply animation ownership. World objects expand into exact child objects, geometry and LOD branches, including initialized hidden healthy/destroyed states. select targets the exact row; map hits still select the whole object. Child hide/show uses session-only part gates and may rebuild the preview; use the returned context and preview afterwards. visibility reports DefaultVisible, Visible, Override, EffectiveVisible and Reason. sourceFile/gltfNode identify authored nodes, sourceOccurrence identifies a tree path, and compiledNode is an optional built slot. selectionOwner for source_map_parts is a signed current-preview identity; source-only authored groups have node=null and selectionOwner=null and support read-only row inspection. properties focuses the source-object card, or opens pinned Properties in other viewers. Read returns roots or a row\u0027s direct children, optionally filtered before paging; in a source map, search and/or types read the whole hierarchy as a flat list of matches with their parent paths, as the outliner\u0027s search box does (types narrows it by the legend\u0027s categories). A row\u0027s zone is null in the aiv and puppies passes. Source map rows carry category (world, group, geometry, empty: an Object3D without a model or children, which draws nothing and cannot be hidden or framed; object, node, zone, network, definition), zone and hidden. Expand/collapse/reveal only change tree presentation; hide/show hide a row\u0027s object (a removed group: what it holds) in the view only, like the outliner\u0027s eye, except that show, and an isolate that ends or moves an isolation (as scene_selection show_all and isolate), select in the view an object the card shows as hidden because it was selected in the tree while hidden (only with no draft open; after an AI path or drop-window draft ends this follows once the application is idle, after that command returned, so read scene_inspect or preview_state afterwards): the view selection, the card and scene_inspect selected change, and its placement can be edited; on the Zones, AI Networks, AI Vehicles (pass aiv) and Pickups (pass puppies) rows they hide or show everything below them, on a zone its colour and on a network its nodes and links (preview_state sections reports them); isolate works on world objects only (zones, networks, units and pickups are refused). select shares scene inspection and draft guards; selecting a zone, network or definition ends the object selection and opens its card in the Properties pane (a network is shown and emphasised, a definition\u0027s bound objects outlined; drafts target section), and properties also focuses the card\u0027s first field. Runtime parenting is not represented.", "Mutates": true, "Parameters": [ { @@ -4135,7 +4586,7 @@ { "Name": "action", "Type": "string", - "Description": "Tree action; default read. Properties focuses the source-object card; other viewers open the same pinned window as the row context menu. hide/show (source maps) change only what the view draws; isolate (source maps) shows only the row\u0027s object, or everything again on the isolated row, as a middle-click on its eye. frame (source maps: the Pickups section\u0027s Weapons, Ammo and Other rows and their type rows, and animation definition and binding rows) frames their pickups on the shown difficulty, or what a definition or binding binds to (the row\u0027s Frame bound objects), without selecting anything, as the row\u0027s Frame button; a definition bound only to templates (nodes no World tree row lists) or to nothing is refused (not_ready: nothing it binds to is drawn in the view).", + "Description": "Tree action; default read. Properties focuses the source-object card; other viewers open the same pinned window as the row context menu. hide/show (source maps) change only what the view draws; isolate (source maps) shows only the row\u0027s object, or everything again on the isolated row, as a middle-click on its eye. frame (source maps: the Pickups section\u0027s Weapons, Ammo and Other rows and their type rows, and animation definition and binding rows) frames their pickups on the shown difficulty, or what a definition or binding binds to (the row\u0027s Frame bound objects), without selecting anything, as the row\u0027s Frame button; a definition bound only to templates (nodes no World tree row lists) or to nothing is refused (not_ready: nothing it binds to is drawn in the view). frame on a valve row selects the valve (its route nodes are ringed) and frames its placed vehicles and targets, else those nodes, as its Frame button.", "Required": false, "Choices": [ "read", @@ -4163,7 +4614,7 @@ { "Name": "types", "Type": "string", - "Description": "Source maps: comma-separated categories the flat read includes (group, geometry, empty, object, node, zone, network, definition); default all.", + "Description": "Source maps: comma-separated categories the flat read includes (group, geometry, empty, object, node, zone, network, valve, definition); default all.", "Required": false, "Choices": null, "Properties": null diff --git a/src/zStudio.Rendering/SceneViewport.Framing.cs b/src/zStudio.Rendering/SceneViewport.Framing.cs index 38800270..9e75121b 100644 --- a/src/zStudio.Rendering/SceneViewport.Framing.cs +++ b/src/zStudio.Rendering/SceneViewport.Framing.cs @@ -52,7 +52,9 @@ private bool TryFrame(string target, int? node, bool manual, IReadOnlyCollection if (!CanInspectNode(root)) return false; selected = []; Subtree(root, selected); } - bool assetOnly = animationFrame != null && node == null && target != "all"; + // With an animation attached, "selected" and "asset" without a node frame what it animates. Named roots are framed + // whole: their parked geometry and their animated poses (a vehicle the valve test has not moved is static). + bool assetOnly = animationFrame != null && node == null && roots == null && target != "all"; Rect3D bounds = Rect3D.Empty; long staticCorners = 0; if (!assetOnly && selectedRuntime == null) diff --git a/src/zStudio.Rendering/SceneViewport.Valves.cs b/src/zStudio.Rendering/SceneViewport.Valves.cs index cd9b7163..f1d68c4a 100644 --- a/src/zStudio.Rendering/SceneViewport.Valves.cs +++ b/src/zStudio.Rendering/SceneViewport.Valves.cs @@ -20,7 +20,10 @@ public bool FrameValveAssociations() Rect3D bounds = Rect3D.Empty; foreach (var network in VisibleAiNetworks) foreach (var node in network.Nodes.Where(n => MissionAiValves.HasAssociation(network, n, ValveFilter))) - bounds.Union(new Rect3D(node.Position.X - 2, node.Position.Y - 2, node.Position.Z - 2, 4, 4, 4)); + { + var point = AiPosition(node); + bounds.Union(new Rect3D(point.X - 2, point.Y - 2, point.Z - 2, 4, 4, 4)); + } return FrameBounds(bounds, true); } private void BuildValveOverlay() @@ -35,12 +38,13 @@ private void BuildValveOverlay() if (nodes.Length > 0) aiMarkers.Add((AiMesh(ValveCage(), color), nodes, 8)); // Select the capped edges first, then resolve only their endpoints: toggling or filtering valves must // not index every node. ValveEdgeSources retain only edges whose endpoint indices are unique. - var assignments = MissionAiValves.EdgeAssignments(network, ValveFilter).Take(remainingEdges).Select(c => (From: c.From!.Value, To: c.To!.Value)).ToArray(); - Dictionary endpoints = new(Math.Min(assignments.Length * 2, 2048)); + var assignments = MissionAiValves.EdgeAssignments(network, ValveFilter) + .SelectMany(c => (c.TargetNodes.Count == 0 ? [c.To!.Value] : c.TargetNodes).Select(t => (From: c.From!.Value, To: t))).Take(remainingEdges).ToArray(); + Dictionary endpoints = new(Math.Min(assignments.Length * 2, 2048)); foreach (var (from, to) in assignments) { endpoints.TryAdd(from, default); endpoints.TryAdd(to, default); } if (endpoints.Count > 0) foreach (var node in network.Nodes) - if (endpoints.ContainsKey(node.Index) && network.ResolvedIndices.Contains(node.Index)) endpoints[node.Index] = node.Position; + if (endpoints.ContainsKey(node.Index) && network.ResolvedIndices.Contains(node.Index)) endpoints[node.Index] = node; var edges = assignments.Where(e => network.ResolvedIndices.Contains(e.From) && network.ResolvedIndices.Contains(e.To)) .Select(e => (From: endpoints[e.From], To: endpoints[e.To])).ToArray(); remainingEdges -= edges.Length; @@ -51,13 +55,15 @@ MeshData Links() var pose = CaptureView(); var forward = Vector3.Normalize(new Vector3((float)pose.LookDirection.X, (float)pose.LookDirection.Y, (float)pose.LookDirection.Z)); foreach (var edge in edges) { - var delta = edge.To - edge.From; if (delta.LengthSquared() < 1e-8f) continue; + if (edge.From == null || edge.To == null) continue; + var from = AiPosition(edge.From); var to = AiPosition(edge.To); + var delta = to - from; if (delta.LengthSquared() < 1e-8f) continue; var direction = Vector3.Normalize(delta); var cross = Vector3.Cross(direction, forward); if (cross.LengthSquared() < 1e-8f) cross = Vector3.Cross(direction, Math.Abs(direction.Y) < .9 ? Vector3.UnitY : Vector3.UnitX); - var side = Vector3.Normalize(cross) * AiScale(Vector3.Lerp(edge.From, edge.To, .5f), 1.5); + var side = Vector3.Normalize(cross) * AiScale(Vector3.Lerp(from, to, .5f), 1.5); for (int step = 0; step < 12; step += 2) { - var a = Vector3.Lerp(edge.From, edge.To, step / 12f); var b = Vector3.Lerp(edge.From, edge.To, (step + 1) / 12f); + var a = Vector3.Lerp(from, to, step / 12f); var b = Vector3.Lerp(from, to, (step + 1) / 12f); int i = positions.Count; positions.AddRange([a - side, a + side, b + side, b - side]); indices.AddRange([i, i + 1, i + 2, i, i + 2, i + 3]); } } @@ -65,21 +71,5 @@ MeshData Links() } } } - private static MeshData ValveCage() - { - var source = AiOctahedron(); List positions = []; List indices = []; - var sourceIndices = source.Indices; var sourcePositions = source.Positions; - for (int i = 0; i < sourceIndices.Length; i += 3) - { - Vector3[] p = [sourcePositions[sourceIndices[i]], sourcePositions[sourceIndices[i + 1]], sourcePositions[sourceIndices[i + 2]]]; - var center = (p[0] + p[1] + p[2]) / 3; - for (int j = 0; j < 3; j++) - { - var a = p[j]; var b = p[(j + 1) % 3]; int at = positions.Count; - positions.AddRange([a, b, Vector3.Lerp(b, center, .15f), Vector3.Lerp(a, center, .15f)]); - indices.AddRange([at, at + 1, at + 2, at, at + 2, at + 3]); - } - } - return new([.. positions], [.. indices], [.. positions.Select(p => Vector3.Normalize(p))]); - } + private static MeshData ValveCage() => AiCircle(); } diff --git a/tests/zStudio.Desktop.Tests/AnimationAudioTests.cs b/tests/zStudio.Desktop.Tests/AnimationAudioTests.cs index 9d829bb0..91f3ea3d 100644 --- a/tests/zStudio.Desktop.Tests/AnimationAudioTests.cs +++ b/tests/zStudio.Desktop.Tests/AnimationAudioTests.cs @@ -11,6 +11,19 @@ namespace zStudio.Desktop.Tests; public sealed class AnimationAudioTests { + [Fact] + public async Task ManualSoundAdmissionEvictsInactivePcmInsteadOfPreparingTheMissionBank() + { + var context = Context(); + context.Sounds.Add("other", new("other", "other.wav", false, Wave())); + int decoded = 0; FakeOutput output = new(); + await using AnimationAudio audio = new(() => output, (bytes, token) => { decoded++; return PreparedSound.Decode(bytes, token); }, maximumPreparedBytes: 400_000); + await audio.PrepareAsync(context, 0, null, true, Token, soundNames: ["tone"]); + Assert.True(audio.IsPrepared); Assert.Equal(1, decoded); + await audio.PrepareAsync(context, 0, null, true, Token, soundNames: ["other"]); + Assert.True(audio.IsPrepared); Assert.Equal(2, decoded); Assert.Equal(1, audio.PreparedSoundCount); + Assert.Equal(1, output.Starts); + } private static CancellationToken Token => TestContext.Current.CancellationToken; [Fact] diff --git a/tests/zStudio.Desktop.Tests/McpLazyConnectorTests.cs b/tests/zStudio.Desktop.Tests/McpLazyConnectorTests.cs index 064387bc..4a4ba61b 100644 --- a/tests/zStudio.Desktop.Tests/McpLazyConnectorTests.cs +++ b/tests/zStudio.Desktop.Tests/McpLazyConnectorTests.cs @@ -16,7 +16,7 @@ public async Task DiscoveryAndInvalidRequestsNeverOpenTheWorkspace() int connections = 0; await WithConnector(_ => { connections++; throw new Exception("Must not connect"); }, () => false, async client => { - Assert.Equal(110, (await client.ListToolsAsync()).Count); + Assert.Equal(112, (await client.ListToolsAsync()).Count); Assert.Equal(2, (await client.ListResourcesAsync()).Count); Assert.False((await client.CallToolAsync("zstudio_capabilities")).IsError); Assert.Single((await client.ReadResourceAsync("zstudio://capabilities")).Contents); diff --git a/tests/zStudio.Desktop.Tests/McpParityChecks.cs b/tests/zStudio.Desktop.Tests/McpParityChecks.cs index 3fa9dfd5..56118a58 100644 --- a/tests/zStudio.Desktop.Tests/McpParityChecks.cs +++ b/tests/zStudio.Desktop.Tests/McpParityChecks.cs @@ -17,7 +17,7 @@ internal static void Run(StudioCommands commands) var capabilityMap = JsonNode.Parse(File.ReadAllText(Path.Combine(root, "docs", "mcp-capabilities.json")))!; var inventory = capabilityMap["handlers"]!.AsArray(); var interactions = capabilityMap["interactions"]!.AsArray(); - Assert.Equal(new[] { "MainWindow.Navigation:CameraNavigationClick", "MainWindow.Navigation:CameraKeyboard", "SceneViewport.Navigation:ConfigureNavigation", "SceneViewport.NavigationCube:NavigateCubeAt", "MainWindow.Resources:ArchiveMembers", "MainWindow.Resources:ZrdNodes", "MainWindow.Content:Scripts", "SceneViewport.Ai:HandleAiPointerDown", "SceneViewport.Inspection:Pointer", "SceneInspectionCard:Resize", "SceneInspectionCard:Actions", "DocumentSceneTree:Hierarchy", "MotionEditor:Controls", "SceneViewport:Valves", "SourceExportSelectionDialog:Controls", "SourceExportSelectionDialog:Target", "SourceObjectCardEditor:Fields", "SourceSectionCard:Fields", "SourceSectionCard:Inspector", "MainWindow.SourceAnimations:Controls", "MainWindow.AnimationPaths:PathsChip", "AnimationViewOverlay:RangeTests", "AnimationTimingView:DropWindows", "MainWindow.Parachutes:MoveAlongPathBanner", "AnimationTimingView:Controls", "AnimationThresholdEditor:ValueProposed", "AnimationPanel:Controls", "AnimationGraphView:Controls", "AnimationScenarioPanel:Controls", "MainWindow.AnimationMode:Chrome", "MainWindow.AnimationMode:AnimationModeKey", "MainWindow.AnimationScenario:PickInView", "TerrainPropertiesEditor:Fields", "SceneViewport.TerrainBrush:Strokes", "ZonePicker:Controls", "SceneViewport.Zones:Strokes", "MainWindow.SourceZones:Notices", "MainWindow.SourceZones:ZoneToolKey", "SourceObjectBrowser:Controls", "SourcePickupDialog:Controls", "BlenderUpdateDialog:Controls", "SourceExportDialog:Controls", "SourceInitializeDialog:Controls", "WorldCompareWindow:Controls", "TerrainCreateDialog:Controls", "MainWindow.AiPath:AiPathKeyboard", "SceneViewport.AiEditing:HandleAiPathDown", "MainWindow.Parachutes:ParachuteKeyboard", "SceneViewport.Parachutes:HandleParachuteDown", "MainWindow.Presentation:PresentationKey", "MainWindow.MapWorkspace:MapPicker", +Assert.Equal(new[] { "MainWindow.Navigation:CameraNavigationClick", "MainWindow.Navigation:CameraKeyboard", "SceneViewport.Navigation:ConfigureNavigation", "SceneViewport.NavigationCube:NavigateCubeAt", "MainWindow.Resources:ArchiveMembers", "MainWindow.Resources:ZrdNodes", "MainWindow.Content:Scripts", "SceneViewport.Ai:HandleAiPointerDown", "SceneViewport.Inspection:Pointer", "SceneInspectionCard:Resize", "SceneInspectionCard:Actions", "DocumentSceneTree:Hierarchy", "MotionEditor:Controls", "SceneViewport:Valves", "MainWindow.ValvePreview:Controls", "SourceExportSelectionDialog:Controls", "SourceExportSelectionDialog:Target", "SourceObjectCardEditor:Fields", "SourceSectionCard:Fields", "SourceSectionCard:Inspector", "MainWindow.SourceAnimations:Controls", "MainWindow.AnimationPaths:PathsChip", "AnimationViewOverlay:RangeTests", "AnimationTimingView:DropWindows", "MainWindow.Parachutes:MoveAlongPathBanner", "AnimationTimingView:Controls", "AnimationThresholdEditor:ValueProposed", "AnimationPanel:Controls", "AnimationGraphView:Controls", "AnimationScenarioPanel:Controls", "MainWindow.AnimationMode:Chrome", "MainWindow.AnimationMode:AnimationModeKey", "MainWindow.AnimationScenario:PickInView", "TerrainPropertiesEditor:Fields", "SceneViewport.TerrainBrush:Strokes", "ZonePicker:Controls", "SceneViewport.Zones:Strokes", "MainWindow.SourceZones:Notices", "MainWindow.SourceZones:ZoneToolKey", "SourceObjectBrowser:Controls", "SourcePickupDialog:Controls", "BlenderUpdateDialog:Controls", "SourceExportDialog:Controls", "SourceInitializeDialog:Controls", "WorldCompareWindow:Controls", "TerrainCreateDialog:Controls", "MainWindow.AiPath:AiPathKeyboard", "SceneViewport.AiEditing:HandleAiPathDown", "MainWindow.Parachutes:ParachuteKeyboard", "SceneViewport.Parachutes:HandleParachuteDown", "MainWindow.Presentation:PresentationKey", "MainWindow.MapWorkspace:MapPicker", "PlayerTankPanel:Radios", "SceneInspectionCard:PlayerTankRow", "MainWindow.SourceEditor:StatusPlayerTank", "MainWindow.CompiledAnimation:Chrome", "MainWindow.CompiledAnimation:Panel", "MainWindow.CompiledAnimation:Inspector", "MainWindow.CompiledAnimation:Scenario", "MainWindow.CompiledDrops:DropWindowsChip", "MainWindow.ModelPlacement:Controls" }, interactions.Select(row => row!["gui"]!.GetValue())); diff --git a/tests/zStudio.Desktop.Tests/Mw3SourceAuthoringMcpChecks.cs b/tests/zStudio.Desktop.Tests/Mw3SourceAuthoringMcpChecks.cs index 7465b4b5..e20edae3 100644 --- a/tests/zStudio.Desktop.Tests/Mw3SourceAuthoringMcpChecks.cs +++ b/tests/zStudio.Desktop.Tests/Mw3SourceAuthoringMcpChecks.cs @@ -37,7 +37,8 @@ internal static async Task Run(MainWindow main, string project, { string folder = Directory.CreateDirectory(Path.Combine(project, $"data/c1/zrdr/aipath/{mission}")).FullName; File.WriteAllText(Path.Combine(folder, "aiv.zrd"), $"( fixture_01 ( 0 ( {(mission == "m1" ? "1.0" : "7.0")} 2.0 3.0 ) 0.0 ) )\r\n"); - File.WriteAllText(Path.Combine(folder, "net_01.zrd"), "( version ( 106 ) node_00 ( 12 ( 1.0 2.0 3.0 ) ( 1 ) wait_interval ( 1 2.0 ) ) node_01 ( 12 ( 4.0 5.0 6.0 ) ( 0 ) ) )\r\n"); + File.WriteAllText(Path.Combine(folder, "net_01.zrd"), "( version ( 106 ) node_00 ( 12 ( 1.0 2.0 3.0 ) ( 1 ) wait_interval ( 1 2.0 ) valve (1 go 1) ) node_01 ( 12 ( 4.0 5.0 6.0 ) ( 0 ) ) )\r\n"); + if (mission == "m1") File.WriteAllText(Path.Combine(folder, "valves.zrd"), "( go ( shutdown ( fixture_01 0 1 ) delayupdate ( later 1.0 ) ) )\r\n"); } const string nestedDefinition = "data/c1/zrdr/native-definitions/ground.zad"; Directory.CreateDirectory(Path.Combine(project, "data/c1/zrdr/native-definitions")); @@ -71,11 +72,136 @@ internal static async Task Run(MainWindow main, string project, var refused = await job("source_group_add", new() { ["document"] = document.SessionId, ["revision"] = document.Revision, ["name"] = "fixture_01" }, "failed"); Assert.Equal("invalid_argument", refused["code"]!.GetValue()); Assert.False(main.ViewModel.SelectedDocument!.IsDirty); + document = main.ViewModel.SelectedDocument!; + preview = (await call("state", new()))["preview"]!.GetValue(); + var simulation = await job("ai_valve_preview", new() { ["preview"] = preview, ["action"] = "prepare" }, "completed"); + string simulationId = simulation["simulation"]!.GetValue(); + simulation = await job("ai_valve_preview", new() { ["preview"] = preview, ["simulation"] = simulationId, ["action"] = "set", ["name"] = "go", ["value"] = 1 }, "completed"); + Assert.Equal(1, simulation["timerCount"]!.GetValue()); + Assert.False(document.IsDirty); + const BindingFlags hidden = BindingFlags.Instance | BindingFlags.NonPublic; + var viewport = (zStudio.Rendering.SceneViewport)typeof(MainWindow).GetField("scene", hidden)!.GetValue(main)!; + var aiNetwork = viewport.AiNetworks.Networks.First(); var ai = aiNetwork.Nodes[0]; + var aiTree = (SceneTreeModel)typeof(MainWindow).GetField("sceneTree", hidden)!.GetValue(main)!; + typeof(MainWindow).GetMethod("SelectSectionRow", hidden)!.Invoke(main, [aiTree.FindSection("network:" + aiNetwork.Id)!, false]); + await job("ai_valve_preview", new() { ["preview"] = preview, ["simulation"] = simulationId, ["action"] = "set", ["name"] = "go", ["value"] = 0 }, "completed"); + await job("ai_valve_preview", new() { ["preview"] = preview, ["simulation"] = simulationId, ["action"] = "traverse", ["node"] = ai.Id, ["slot"] = 0 }, "failed"); + var preserved = await job("ai_valve_preview", new() { ["preview"] = preview, ["action"] = "state" }, "completed"); + Assert.Equal(simulationId, preserved["simulation"]!.GetValue()); + await job("ai_valve_preview", new() { ["preview"] = preview, ["simulation"] = simulationId, ["action"] = "set", ["name"] = "go", ["value"] = 1 }, "completed"); + simulation = await job("ai_valve_preview", new() { ["preview"] = preview, ["simulation"] = simulationId, ["action"] = "traverse", ["node"] = ai.Id, ["slot"] = 0 }, "completed"); + Assert.True(viewport.SelectAiNode(ai.Id)); + var inspection = Assert.IsType(viewport.SelectedInspection); + var extra = typeof(MainWindow).GetMethod("ValveInspectionSections", hidden)!; + var controls = (System.Windows.FrameworkElement)extra.Invoke(main, [viewport, inspection])!; + // The node's Add fields keep what is typed while the test steps: only its Test part follows the test. + var typed = VisualChildren(controls).OfType().First(); + typed.Text = "7"; + await job("ai_valve_preview", new() { ["preview"] = preview, ["simulation"] = simulationId, ["action"] = "step" }, "completed"); + Assert.Same(controls, extra.Invoke(main, [viewport, inspection])); + Assert.Equal("7", typed.Text); + Assert.Contains(VisualChildren(controls).OfType(), b => b.Content as string == "Drive through" && b.IsEnabled); + // The Valves rows show the test's values; next runs the waiting timers. + var goRow = aiTree.FindSection("valve:go")!; + Assert.Equal("1", goRow.Meta); Assert.True(goRow.ValveIsOn); + Assert.True(aiTree.Roots.Single(r => r.HasValveTest).ValveTestOn); + simulation = await job("ai_valve_preview", new() { ["preview"] = preview, ["simulation"] = simulationId, ["action"] = "next" }, "completed"); + Assert.Equal(0, simulation["timerCount"]!.GetValue()); + Assert.Equal("1", aiTree.FindSection("valve:later")!.Meta); + // The valve card while the test runs: selecting the valve shows its Test section (the retained one, moved to the card + // as shown now), and what is typed in it stays through the test's refreshes. + var selectRow = typeof(MainWindow).GetMethod("SelectSectionRow", hidden)!; + selectRow.Invoke(main, [goRow, false]); + var testCard = (SourceSectionCard)typeof(MainWindow).GetField("sectionCard", hidden)!.GetValue(main)!; + System.Windows.Controls.TextBox Other() => VisualChildren(testCard).OfType().Single(t => System.Windows.Automation.AutomationProperties.GetName(t) == "Other value"); + Other().Text = "17"; + selectRow.Invoke(main, [goRow, false]); + await job("ai_valve_preview", new() { ["preview"] = preview, ["simulation"] = simulationId, ["action"] = "step" }, "completed"); + Assert.Equal("17", Other().Text); + simulation = await job("ai_valve_preview", new() { ["preview"] = preview, ["simulation"] = simulationId, ["action"] = "reset" }, "completed"); + Assert.NotEqual(simulationId, simulation["simulation"]!.GetValue()); Assert.Equal(0, simulation["timerCount"]!.GetValue()); + simulationId = simulation["simulation"]!.GetValue(); + // Stop must retire attachment and lifetime even while an evaluator owns the busy flag. + var lifetime = (CancellationTokenSource)typeof(MainWindow).GetField("valveLifetime", hidden)!.GetValue(main)!; + var lifetimeToken = lifetime.Token; + typeof(MainWindow).GetField("valveBusy", hidden)!.SetValue(main, true); + try { typeof(MainWindow).GetMethod("StopValveSimulation", hidden)!.Invoke(main, null); } + finally { typeof(MainWindow).GetField("valveBusy", hidden)!.SetValue(main, false); } + Assert.True(lifetimeToken.IsCancellationRequested); + Assert.Null(typeof(MainWindow).GetField("valveSimulation", hidden)!.GetValue(main)); + Assert.Null(typeof(MainWindow).GetField("valveAttachment", hidden)!.GetValue(main)); + simulation = await job("ai_valve_preview", new() { ["preview"] = preview, ["action"] = "start" }, "completed"); + simulationId = simulation["simulation"]!.GetValue(); + await job("ai_valve_preview", new() { ["preview"] = preview, ["simulation"] = simulationId, ["action"] = "stop" }, "completed"); + Assert.Equal("", goRow.Meta); + string valveSource = ((SourceSceneSnapshot)document.Document).SourceMission + "/valves.zrd"; + string Stored(string path) => System.Text.Encoding.Latin1.GetString(main.ViewModel.SelectedDocument!.SourceWorld!.Workspace.Read(path, token)!); + // The mission's valves by name, and one read as its card shows it. + var valves = (await job("source_ai_valve", new() { ["document"] = document.SessionId, ["action"] = "valves" }, "completed"))["items"]!.AsArray(); + Assert.Equal(["go", "later"], valves.Select(v => v!["name"]!.GetValue())); + var read = (await job("source_ai_valve", new() { ["document"] = document.SessionId, ["action"] = "valve", ["name"] = "go" }, "completed"))["valve"]!; + Assert.Equal("sets later after 1 s", read["reactions"]!.AsArray().Single(r => r!["fields"]!["kind"]!.GetValue() == "delayupdate")!["text"]!.GetValue()); + Assert.Contains(read["usedBy"]!.AsArray(), l => l!["role"]!.GetValue() == "gate" && l["node"]!.GetValue() == 0); + // set changes the delay in place: one undoable change that keeps the rest of the record. + await job("source_ai_valve", new() { ["document"] = document.SessionId, ["revision"] = document.Revision, ["action"] = "set", ["name"] = "go", + ["changes"] = new { reactions = new[] { new { occurrence = 0, storedKind = "delayupdate", fields = new { kind = "delayupdate", target = "later", operand = "2.5" } } } } }, "completed"); + document = main.ViewModel.SelectedDocument!; + Assert.True(document.IsDirty); + Assert.Equal("( go ( shutdown ( fixture_01 0 1 ) delayupdate ( later 2.5 ) ) )\r\n", Stored(valveSource)); + await call("undo_redo", new() { ["document"] = document.SessionId, ["revision"] = document.Revision, ["action"] = "undo" }); + Assert.False(main.ViewModel.SelectedDocument!.IsDirty); + document = main.ViewModel.SelectedDocument!; + // The valve's card: its draft through MCP, then Apply; a draft change is refused while Apply prepares. + var worldTree = (SceneTreeModel)typeof(MainWindow).GetField("sceneTree", hidden)!.GetValue(main)!; + var valveRow = worldTree.FindSection("valve:go")!; + Assert.True(valveRow.Selectable); + typeof(MainWindow).GetMethod("SelectSectionRow", hidden)!.Invoke(main, [valveRow, false]); + var valveCard = (SourceSectionCard)typeof(MainWindow).GetField("sectionCard", hidden)!.GetValue(main)!; + Assert.Equal("go", valveCard.ShownValve!.Name); Assert.False(valveCard.HasDraft); + await job("source_ai_valve", new() { ["document"] = document.SessionId, ["revision"] = document.Revision, ["action"] = "draft", ["name"] = "go", + ["changes"] = new { initial = "1", reactions = new[] { new { fields = new { kind = "sound_once", target = "alarm", when = "1" } } } } }, "completed"); + Assert.True(valveCard.HasDraft); + // Framing another valve selects it, which would replace this card: with its draft pending the selection is refused. + var refusal = Assert.IsType(Assert.Throws(() => + typeof(MainWindow).GetMethod("RequireNoSelectionDrafts", hidden)!.Invoke(main, [document])).InnerException); + Assert.Equal("pending_drafts", refusal.Code); + { + TaskCompletionSource valveDraftEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + using ManualResetEventSlim valveDraftRelease = new(false); + main.SourceEditPreparing = ct => { valveDraftEntered.TrySetResult(); Assert.True(valveDraftRelease.Wait(TimeSpan.FromSeconds(15), ct)); }; + var valveApply = valveCard.ApplyAsync(); + try + { + await valveDraftEntered.Task.WaitAsync(TimeSpan.FromSeconds(10), token); + document = main.ViewModel.SelectedDocument!; + var duringApply = await job("source_ai_valve", new() { ["document"] = document.SessionId, ["revision"] = document.Revision, + ["action"] = "draft", ["name"] = "go", ["changes"] = new { initial = "5" }, ["draft"] = valveCard.DraftToken }, "failed"); + Assert.Equal("busy", duringApply["code"]!.GetValue()); + } + finally { valveDraftRelease.Set(); main.SourceEditPreparing = null; } + await valveApply; + } + document = main.ViewModel.SelectedDocument!; + Assert.Contains("value ( 1 )", Stored(valveSource)); Assert.Contains("sound_once ( alarm 1 )", Stored(valveSource)); Assert.DoesNotContain("( 5 )", Stored(valveSource)); + await call("undo_redo", new() { ["document"] = document.SessionId, ["revision"] = document.Revision, ["action"] = "undo" }); + Assert.False(main.ViewModel.SelectedDocument!.IsDirty); + // rename follows every file of the mission that names the valve, as one change. + document = main.ViewModel.SelectedDocument!; + await job("source_ai_valve", new() { ["document"] = document.SessionId, ["revision"] = document.Revision, ["action"] = "rename", ["name"] = "go", ["newName"] = "open_gate" }, "completed"); + document = main.ViewModel.SelectedDocument!; + Assert.StartsWith("( open_gate ( shutdown", Stored(valveSource)); Assert.Contains("valve (1 open_gate 1)", Stored("data/c1/zrdr/aipath/m1/net_01.zrd")); + await call("undo_redo", new() { ["document"] = document.SessionId, ["revision"] = document.Revision, ["action"] = "undo" }); + Assert.False(main.ViewModel.SelectedDocument!.IsDirty); + document = main.ViewModel.SelectedDocument!; + source = Assert.IsType(document.Document); + preview = (await call("state", new()))["preview"]!.GetValue(); var placedRefusal = await job("source_world_add_model", new() { ["document"] = document.SessionId, ["revision"] = document.Revision, ["model"] = model, ["name"] = "fixture_01", ["position"] = new { x = 5, y = 0, z = 0 }, ["definitionFiles"] = Array.Empty() }, "failed"); Assert.True(placedRefusal["code"]!.GetValue() == "invalid_argument", placedRefusal.ToJsonString()); Assert.False(main.ViewModel.SelectedDocument!.IsDirty); + await job("ai_valve_preview", new() { ["preview"] = preview, ["action"] = "prepare" }, "completed"); await job("animation_mode", new() { ["preview"] = preview, ["document"] = document.SessionId, ["revision"] = document.Revision, ["action"] = "open", ["entry"] = 1 }, "completed"); + Assert.Null(typeof(MainWindow).GetField("valveSimulation", hidden)!.GetValue(main)); preview = (await call("state", new()))["preview"]!.GetValue(); var rangeState = await job("animation_paths", new() { ["preview"] = preview, ["document"] = document.SessionId, ["revision"] = document.Revision, ["action"] = "ranges" }, "completed"); var gate = rangeState["ranges"]!["ranges"]!.AsArray().Single(r => r!["kind"]!.GetValue() == "gate")!; @@ -146,6 +272,16 @@ internal static async Task Run(MainWindow main, string project, source = Assert.IsType(document.Document); Assert.Equal("data/c1/zrdr/aipath/mp1", source.SourceMission); Assert.Equal(7, Assert.Single(source.MissionScene(MissionDifficulty.Medium, token).Actors).PlacementPosition!.Value.X); + string firstValveSource = source.SourceMission + "/valves.zrd"; + var valveSources = (await job("source_ai_valve", new() { ["document"] = document.SessionId, ["action"] = "sources" }, "completed"))["items"]!.AsArray(); + Assert.Contains(valveSources, v => v!["source"]!.GetValue() == firstValveSource && !v["exists"]!.GetValue()); + // A mission without valves.zrd gets the file with its first valve. + await job("source_ai_valve", new() { ["document"] = document.SessionId, ["revision"] = document.Revision, ["action"] = "new", ["name"] = "first_valve" }, "completed"); + document = main.ViewModel.SelectedDocument!; + Assert.Contains("first_valve", System.Text.Encoding.Latin1.GetString(document.SourceWorld!.Workspace.Read(firstValveSource, token)!)); + await call("undo_redo", new() { ["document"] = document.SessionId, ["revision"] = document.Revision, ["action"] = "undo" }); + document = main.ViewModel.SelectedDocument!; Assert.False(document.IsDirty); + Assert.Null(document.SourceWorld!.Workspace.Read(firstValveSource, token)); const string network = "data/c1/zrdr/aipath/mp1/net_01.zrd"; await job("source_ai_network", new() { @@ -158,4 +294,12 @@ internal static async Task Run(MainWindow main, string project, await call("undo_redo", new() { ["document"] = document.SessionId, ["revision"] = document.Revision, ["action"] = "undo" }); Assert.False(main.ViewModel.SelectedDocument!.IsDirty); } + private static IEnumerable VisualChildren(System.Windows.DependencyObject parent) + { + for (int i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(parent); i++) + { + var child = System.Windows.Media.VisualTreeHelper.GetChild(parent, i); yield return child; + foreach (var nested in VisualChildren(child)) yield return nested; + } + } } diff --git a/tests/zStudio.Tests/AiValveTests.cs b/tests/zStudio.Tests/AiValveTests.cs index 1a37239f..3dc5d676 100644 --- a/tests/zStudio.Tests/AiValveTests.cs +++ b/tests/zStudio.Tests/AiValveTests.cs @@ -69,7 +69,7 @@ public async Task OptionalMw3ValveCorpusKeepsCompleteResourcesAndRecognizesAutho } } Assert.True(definitions > 1000); Assert.True(networks > 100); - Assert.Equal(new[] { "definition", "edge", "node", "objective" }, kinds.Order()); + Assert.Equal(new[] { "actor", "definition", "edge", "node", "objective", "target" }, kinds.Order()); } [Theory] [InlineData("valveunion")] diff --git a/tests/zStudio.Tests/Mw3PreviewParityTests.cs b/tests/zStudio.Tests/Mw3PreviewParityTests.cs index 53d064ee..e7f81240 100644 --- a/tests/zStudio.Tests/Mw3PreviewParityTests.cs +++ b/tests/zStudio.Tests/Mw3PreviewParityTests.cs @@ -8,6 +8,167 @@ namespace zStudio.Tests; public sealed class Mw3PreviewParityTests { + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task AnimationRestartCleanupFiresBeforeLaterValveUpdates(bool sameTrigger) + { + string gate = sameTrigger ? "go" : "actor_01"; + using var fixture = new Mw3MissionFixture(gate); var package = Package(); + fixture.World.Scene!.Nodes[1] = fixture.World.Scene.Nodes[1] with { Name = gate }; + var entry = Entry(package, "restart", gate); entry.SetInt(148, 0x10030); + var sequence = new AnimationSequence(new byte[64]); entry.Sequences.Add(sequence); + var on = AnimationCatalog.Create(35, 39); on.SetInt(12, 43); sequence.Events.Add(on); + var off = AnimationCatalog.Create(35, 39); off.SetInt(12, 42); entry.Primary.Events.Add(off); + var mission = await MissionSceneLoader.LoadAsync(fixture.World, fixture.Resolver, package, TestContext.Current.CancellationToken); + var context = new AnimationPreviewContext { World = fixture.World, Package = package, Mission = mission }; + context.Sounds.Add("sample", new("sample", "sample.wav", false, SourceFixture.Tone(new(22050, 16, 1), 48, null))); + string definitions = sameTrigger ? "(go (animation (restart 1)))" : "(go (animation (restart 1) update (actor_01)) actor_01 (sound (sample 1)))"; + var simulation = new Mw3ValveSimulation(context, Mw3ValveProgram.Read(zStudio.Core.Sources.ZrdText.Parse(definitions, TestContext.Current.CancellationToken), TestContext.Current.CancellationToken), TestContext.Current.CancellationToken); + simulation.Set("go", 1, TestContext.Current.CancellationToken); simulation.Advance(.05, TestContext.Current.CancellationToken); + simulation.Update("go", TestContext.Current.CancellationToken); + Assert.False(simulation.Faulted); Assert.Equal(1, simulation.Runtime.Value(gate)); + if (!sameTrigger) Assert.Single(simulation.CurrentFrame.ActiveSounds, s => s.Name == "sample"); + } + [Fact] + public async Task AnimationCallbackPrecedesDueValveTimersAtTheSameFrameClock() + { + using var fixture = new Mw3MissionFixture("actor_01"); var package = Package(); + var entry = Entry(package, "load", "actor"); entry.Bytes[153] = 4; entry.SetInt(148, 0x10030); + var sequence = new AnimationSequence(new byte[64]); entry.Sequences.Add(sequence); + var callback = AnimationCatalog.Create(35, 39); callback.SetInt(12, 43); callback.Threshold = .01f; sequence.Events.Add(callback); + var mission = await MissionSceneLoader.LoadAsync(fixture.World, fixture.Resolver, package, TestContext.Current.CancellationToken); + var context = new AnimationPreviewContext { World = fixture.World, Package = package, Mission = mission.ValveStartupBaseline(TestContext.Current.CancellationToken) }; + var simulation = new Mw3ValveSimulation(context, Mw3ValveProgram.Read(zStudio.Core.Sources.ZrdText.Parse("(go (delayupdate (actor 0.0)))", TestContext.Current.CancellationToken), TestContext.Current.CancellationToken), TestContext.Current.CancellationToken); + simulation.Update("go", TestContext.Current.CancellationToken); + simulation.Advance(AnimationPlayer.StepSeconds, TestContext.Current.CancellationToken); + Assert.Equal(new[] { 1, 0 }, simulation.Runtime.Trace.Where(t => t.Valve == "actor" && t.Kind == "set").Select(t => t.Value)); + } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task TeleportFollowsOwnedParentingAfterAnimationAttachOrDetach(bool attach) + { + using var fixture = new Mw3MissionFixture("actor_01"); var package = Package(); _ = Context(fixture, package); var scene = fixture.World.Scene!; + scene.Nodes[0] = scene.Nodes[0] with { Children = attach ? [1, 2] : [1] }; + scene.Nodes[1] = scene.Nodes[1] with { Name = "actor_01", Children = attach ? [] : [2] }; + scene.Nodes.Add(new(2, "child", "object3d", 0, attach ? [0] : [1], [], new() { ["flags"] = 4 }, new() { ["flags"] = 8 })); + var entry = Entry(package, "reparent", "actor_01"); var reference = new AnimationRecord(new byte[40]); reference.SetText(0, "child", 36); entry.References[1].Add(reference); + var sequence = new AnimationSequence(new byte[64]); entry.Sequences.Add(sequence); + var parenting = AnimationCatalog.Create((byte)(attach ? 15 : 16), 39); parenting.SetShort(12, -100); parenting.SetShort(14, 1); sequence.Events.Add(parenting); + var active = AnimationCatalog.Create(6, 39); active.SetShort(16, 1); active.SetInt(12, 1); sequence.Events.Add(active); + var mission = await MissionSceneLoader.LoadAsync(fixture.World, fixture.Resolver, package, TestContext.Current.CancellationToken); + var context = new AnimationPreviewContext { World = fixture.World, Package = package, Mission = mission }; + var simulation = new Mw3ValveSimulation(context, Mw3ValveProgram.Read(zStudio.Core.Sources.ZrdText.Parse("(go (animation (reparent 1)) warp (teleport (actor_01 (100 0 0) 0 1)))", TestContext.Current.CancellationToken), TestContext.Current.CancellationToken), TestContext.Current.CancellationToken); + simulation.Set("go", 1, TestContext.Current.CancellationToken); simulation.Set("warp", 1, TestContext.Current.CancellationToken); + Assert.Equal(attach ? 100 : 0, Assert.Single(simulation.CurrentFrame.Nodes, n => n.SourceNode == 2).Transform.Translation.X); + } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task LoadCallbacksBindPostPlacementAndRejectUnchangedSharedAncestors(bool ambiguous) + { + using var fixture = new Mw3MissionFixture("actor_01"); var package = Package(); var scene = fixture.World.Scene!; + scene.Nodes[0] = scene.Nodes[0] with { Children = ambiguous ? [1, 2] : [2] }; + scene.Nodes[1] = scene.Nodes[1] with { Name = ambiguous ? "actor" : "actor_01", Parents = ambiguous ? [2, 0] : [2] }; + scene.Nodes.Add(new(2, "formation", "object3d", null, [0], [1], new() { ["flags"] = 4 }, new() { ["flags"] = 8 })); + var entry = Entry(package, "load", scene.Nodes[1].Name); entry.Bytes[153] = 4; entry.SetInt(148, 0x10030); + var sequence = new AnimationSequence(new byte[64]); entry.Sequences.Add(sequence); + var callback = AnimationCatalog.Create(35, 39); callback.SetInt(12, 45); callback.Threshold = .1f; sequence.Events.Add(callback); + var mission = await MissionSceneLoader.LoadAsync(fixture.World, fixture.Resolver, package, TestContext.Current.CancellationToken); + var context = new AnimationPreviewContext { World = fixture.World, Package = package, Mission = mission.ValveStartupBaseline(TestContext.Current.CancellationToken) }; + var simulation = new Mw3ValveSimulation(context, new([]), TestContext.Current.CancellationToken); + simulation.Advance(.2, TestContext.Current.CancellationToken); + Assert.Equal(0, simulation.Runtime.Value("formation")); + Assert.Equal(ambiguous ? 0 : 1, simulation.Runtime.Value("world")); + } + [Fact] + public async Task ValveSimulationRetainsLoadCallbacksContinuationsAndLoopingSounds() + { + using var fixture = new Mw3MissionFixture("actor_01"); var package = Package(); _ = Context(fixture, package); + fixture.World.Scene!.Nodes[1] = fixture.World.Scene.Nodes[1] with { Name = "actor_01" }; + var entry = Entry(package, "load_valve", "actor_01"); entry.Bytes[153] = 4; entry.SetInt(148, 0x10030); + var sequence = new AnimationSequence(new byte[64]); entry.Sequences.Add(sequence); + var cycle = AnimationCatalog.Create(17, 39); cycle.SetShort(16, -100); cycle.SetShort(18, 3); sequence.Events.Add(cycle); + var first = AnimationCatalog.Create(35, 39); first.SetInt(12, 43); sequence.Events.Add(first); + var startupSound = AnimationCatalog.Create(2, 39); startupSound.SetText(12, "startup_tone"); startupSound.SetInt(52, 1); sequence.Events.Add(startupSound); + var later = AnimationCatalog.Create(35, 39); later.SetInt(12, 42); later.Threshold = .1f; sequence.Events.Add(later); + var mission = await MissionSceneLoader.LoadAsync(fixture.World, fixture.Resolver, package, TestContext.Current.CancellationToken); + var context = new AnimationPreviewContext { World = fixture.World, Package = package, Mission = mission.ValveStartupBaseline(TestContext.Current.CancellationToken) }; + context.Sounds.Add("loop", new("loop", "loop.wav", true, SourceFixture.Tone(new(22050, 16, 1), 48, null))); + context.Sounds.Add("startup_tone", context.Sounds["loop"] with { Name = "startup_tone", Loop = false }); + var simulation = new Mw3ValveSimulation(context, Mw3ValveProgram.Read(zStudio.Core.Sources.ZrdText.Parse("(actor_01 (sound_once (loop 1)))", TestContext.Current.CancellationToken), TestContext.Current.CancellationToken), TestContext.Current.CancellationToken); + Assert.Equal(1, simulation.Runtime.Value("actor_01")); + Assert.Equal(3, Assert.Single(simulation.CurrentFrame.Nodes, n => n.SourceNode == mission.Actors[0].Root).Variant); + Assert.Contains(simulation.CurrentFrame.Sounds, s => s.Name == "startup_tone"); + using var canceled = new CancellationTokenSource(); canceled.Cancel(); + Assert.Throws(() => simulation.Set("actor_01", 0, canceled.Token)); + Assert.Equal(1, simulation.Runtime.Value("actor_01")); + simulation.Advance(.2, TestContext.Current.CancellationToken); + Assert.Equal(0, simulation.Runtime.Value("actor_01")); + Assert.True(Assert.Single(simulation.CurrentFrame.ActiveSounds, s => s.Name == "loop").Persistent); + Assert.False(simulation.Faulted); + } + [Fact] + public async Task ValveActionsRespectAnimationActivationPrerequisites() + { + using var fixture = new Mw3MissionFixture("actor_01"); var package = Package(); + var entry = Entry(package, "guarded", "actor"); + var prerequisite = new AnimationRecord(new byte[48]); prerequisite.Bytes[4] = 2; + prerequisite.SetInt(0, 1); prerequisite.SetInt(8, 1); prerequisite.SetText(12, "missing_required_node", 28); + entry.References[6].Add(prerequisite); entry.Bytes[273] = 1; + var mission = await MissionSceneLoader.LoadAsync(fixture.World, fixture.Resolver, package, TestContext.Current.CancellationToken); + var context = new AnimationPreviewContext { World = fixture.World, Package = package, Mission = mission }; + var simulation = new Mw3ValveSimulation(context, Mw3ValveProgram.Read(zStudio.Core.Sources.ZrdText.Parse("(go (animation (guarded 1)))", TestContext.Current.CancellationToken), TestContext.Current.CancellationToken), TestContext.Current.CancellationToken); + simulation.Set("go", 1, TestContext.Current.CancellationToken); + Assert.DoesNotContain(simulation.CurrentFrame.Instances, i => i.Name == "guarded"); + Assert.Contains(simulation.CurrentFrame.Refusals, r => r.Reason == "prerequisites"); + } + [Fact] + public async Task ValveTeleportReplacesTheCurrentAnimatedRootWithAnAbsoluteNumericPose() + { + using var fixture = new Mw3MissionFixture("actor_01"); var package = Package(); _ = Context(fixture, package); + fixture.World.Scene!.Nodes[1] = fixture.World.Scene.Nodes[1] with { Name = "actor_01" }; + var entry = Entry(package, "move", "actor_01"); + var sequence = new AnimationSequence(new byte[64]); entry.Sequences.Add(sequence); + var move = AnimationCatalog.Create(7, 39); move.SetShort(28, -100); move.SetVector(16, new(10, 0, 0)); sequence.Events.Add(move); + var laterMove = AnimationCatalog.Create(7, 39); laterMove.SetShort(28, -100); laterMove.SetVector(16, new(20, 0, 0)); laterMove.Threshold = .1f; sequence.Events.Add(laterMove); + var mission = await MissionSceneLoader.LoadAsync(fixture.World, fixture.Resolver, package, TestContext.Current.CancellationToken); + var context = new AnimationPreviewContext { World = fixture.World, Package = package, Mission = mission }; + var program = Mw3ValveProgram.Read(zStudio.Core.Sources.ZrdText.Parse("(go (animation (move 1)) warp (teleport (actor_01 (100 0 0) 90 1)))", TestContext.Current.CancellationToken), TestContext.Current.CancellationToken); + program.ValidateForEditing(); var simulation = new Mw3ValveSimulation(context, program, TestContext.Current.CancellationToken); + simulation.Set("go", 1, TestContext.Current.CancellationToken); + int root = Assert.Single(mission.Actors).Root; + Assert.Equal(10, Assert.Single(simulation.CurrentFrame.Nodes, n => n.SourceNode == root).Transform.Translation.X); + simulation.Set("warp", 1, TestContext.Current.CancellationToken); + Assert.Equal(new Vector3(100, 0, 0), Assert.Single(simulation.CurrentFrame.Nodes, n => n.SourceNode == root).Transform.Translation); + Assert.Equal(90, simulation.Actors["actor_01"].Yaw); + simulation.Advance(.2, TestContext.Current.CancellationToken); + Assert.Equal(20, Assert.Single(simulation.CurrentFrame.Nodes, n => n.SourceNode == root).Transform.Translation.X); + var parked = new Mw3ValveSimulation(context, program, TestContext.Current.CancellationToken); + parked.Set("warp", 1, TestContext.Current.CancellationToken); + Assert.Equal(new Vector3(100, 0, 0), Assert.Single(parked.CurrentFrame.Nodes, n => n.SourceNode == root).Transform.Translation); + } + [Fact] + public async Task ValveTargetDeathWritesDescendingRemainingThresholdsBeforeLaterUpdates() + { + using var fixture = new Mw3MissionFixture("actor_01"); var package = Package(); + var mission = await MissionSceneLoader.LoadAsync(fixture.World, fixture.Resolver, package, TestContext.Current.CancellationToken); + var target = zStudio.Core.Sources.ZrdText.Parse("(actor_01 (health_below (gate 2 0.2 gate 1 0.8)))", TestContext.Current.CancellationToken); + mission.AiNetworks = mission.AiNetworks with { ValveSources = [new("fixture", 0, "targets.zrd", target, ReadOnlyMemory.Empty)] }; + var context = new AnimationPreviewContext { World = fixture.World, Package = package, Mission = mission }; + context.Sounds.Add("loop", new("loop", "loop.wav", true, SourceFixture.Tone(new(22050, 16, 1), 48, null))); + context.Sounds.Add("short", context.Sounds["loop"] with { Name = "short", Loop = false }); + var simulation = new Mw3ValveSimulation(context, Mw3ValveProgram.Read(zStudio.Core.Sources.ZrdText.Parse("(go (destroy (actor_01 1) update (gate)) gate (sound (loop 0)) clock (delayupdate (click 0.0)) click (sound (short 1)))", TestContext.Current.CancellationToken), TestContext.Current.CancellationToken), TestContext.Current.CancellationToken); + simulation.Set("go", 1, TestContext.Current.CancellationToken); + Assert.Equal(2, simulation.Runtime.Value("gate")); Assert.True(simulation.Actors["actor_01"].Destroyed); + Assert.Empty(simulation.CurrentFrame.ActiveSounds); + simulation.Set("gate", 9, TestContext.Current.CancellationToken); simulation.Update("go", TestContext.Current.CancellationToken); + Assert.Equal(9, simulation.Runtime.Value("gate")); Assert.Empty(simulation.CurrentFrame.ActiveSounds); + simulation.Set("clock", 1, TestContext.Current.CancellationToken); + simulation.Advance(AnimationPlayer.StepSeconds, TestContext.Current.CancellationToken); + Assert.InRange(Math.Abs(Assert.Single(simulation.CurrentFrame.ActiveSounds).StartedAt - simulation.Time), 0, 0.000001); + } // Map diagnostics must preserve preview limitations and group call sites instead of flooding the workspace. [Fact] public async Task MissionDiagnosticsKeepSeverityAndBoundGroupedCallDetails() diff --git a/tests/zStudio.Tests/Mw3ValveMapTests.cs b/tests/zStudio.Tests/Mw3ValveMapTests.cs new file mode 100644 index 00000000..128e686f --- /dev/null +++ b/tests/zStudio.Tests/Mw3ValveMapTests.cs @@ -0,0 +1,175 @@ +using System.Text; +using zStudio.Core; +using zStudio.Core.Formats; +using zStudio.Core.Sources; +using Xunit; + +namespace zStudio.Tests; + +/// The valve card's model and edits: one valve per name over every mission file, and edits that keep the source's layout. +public sealed class Mw3ValveMapTests +{ + private static CancellationToken Token => TestContext.Current.CancellationToken; + private static Mw3ValveSource Source(string path, string text) => new(path, ZrdText.Parse(text, Token)); + private const string Valves = "(\r\n # the ramp\r\n bramp (\r\n shutdown ( owens_01 0 1 )\r\n )\r\n bramp (\r\n delayupdate ( truck_go 18.0 ) # later\r\n )\r\n ready (\r\n all_nonzero\r\n namelist ( bramp gate )\r\n )\r\n)\r\n"; + + [Fact] + public void OneValvePerNameGathersReactionsTriggersGatesAndThisMissionsObjectives() + { + // Must-have: the tree and card show this model; a use attributed to the wrong valve or mission misleads every edit. + var map = Mw3ValveMap.Build( + [ + Source("data/c1/zrdr/aipath/m1/valves.zrd", Valves), + Source("data/c1/zrdr/aipath/m1/aiv.zrd", "(player (0 vlist ((1 0 0.25 0 0 0.999 0 0.8 1 reg_ramp 0 0.0 0 60.0 1 bramp 0) (0 0 0.25 1 0 0.5 0 0.8 0 0 0 0.0 1 60.0 1 gate 1))))"), + Source("data/c1/zrdr/aipath/m1/targets.zrd", "(satdish (2 health (35.0) health_below (gate 1 35.0 truck_go 1 0.0)))"), + Source("data/c1/zrdr/aipath/m1/net_02.zrd", "(version (106) node_00 (12 (0.0 0.0 0.0) (1) valve (1 gate 1) valve_assign (ready 1) deploy (mobilehq_01 1 \"MFB Baker\" 0 0)) node_01 (12 (1.0 0.0 0.0) ()))"), + Source("data/c1/zrdr/objectives.zrd", "(m1 (primary (valve_change (valve (ready) value (1)))) m2 (fail (valve_change (valve (other_mission) value (1)))))"), + ], "m1", new(Vehicles: new HashSet { "player" }), Token, + // An animation sets the valve named as the node it binds; one bound to a node no file names as a valve adds none. + [new("bramp", 5, "call_ramp", [1]), new("rbrgtwr6", 6, "tower_fall", [0, 1])]); + Assert.Equal(["bramp", "gate", "MFB Baker", "mobilehq_01", "ready", "truck_go"], map.Valves.Select(v => v.Name)); + var bramp = map.Find("bramp")!; + Assert.Contains(bramp.SetBy, l => l is { Role: "animation", Owner: "call_ramp", Entry: 5, Value: 1 }); + Assert.Equal(["wakes owens_01", "sets truck_go after 18 s"], bramp.Reactions.Select(r => r.Text)); + Assert.Equal([0, 1], bramp.Reactions.Select(r => r.Occurrence)); + Assert.Equal("wakes owens_01 · 1 timer", bramp.Summary); + Assert.Equal("inside reg_ramp → 1", bramp.SetBy.Single(l => l.Role == "trigger").Text); + // A reaction naming a vehicle the mission lacks is the one definite problem the row marks. + Assert.Contains(bramp.Problems, p => p.Contains("owens_01")); + var gate = map.Find("gate")!; + Assert.Equal(["trigger", "health"], gate.SetBy.Select(l => l.Role)); + Assert.Equal("hit or enemy within 60 → 0", gate.SetBy[0].Text); + Assert.Equal("health below 35 → 1", gate.SetBy[1].Text); + Assert.Contains(gate.UsedBy, l => l is { Role: "gate", Node: 0, Value: 1 } && l.Owner == "net_02 · node 0"); + Assert.Contains(gate.UsedBy, l => l is { Role: "computed", Valve: "ready" }); + var ready = map.Find("ready")!; + Assert.Equal("all_nonzero", ready.Condition); Assert.Equal(["bramp", "gate"], ready.Inputs); + Assert.Contains(ready.UsedBy, l => l.Role == "objective" && l.Owner == "primary objective"); + Assert.Contains(ready.SetBy, l => l.Role == "route"); + Assert.Equal("when destroyed → 1", map.Find("truck_go")!.SetBy.Single(l => l.Role == "health").Text); + Assert.Contains(map.Find("truck_go")!.SetBy, l => l is { Role: "timer", Valve: "bramp" }); + // The view rings and frames a valve's nodes by the same links: a deploy point's valves are found by name. + var net = MissionAiNetworks.Decode("test", "", 0, "net_02.zrd", ZrdText.Parse("(version (106) node_00 (12 (0.0 0.0 0.0) (1) deploy (mobilehq_01 1 \"MFB Baker\" 0 0)) node_01 (12 (1.0 0.0 0.0) () mcbwait (hold 1 2.0)))", Token), Token); + Assert.True(MissionAiValves.HasAssociation(net, net.Nodes[0], "MFB Baker")); Assert.True(MissionAiValves.HasAssociation(net, net.Nodes[0], "mobilehq_01")); + Assert.True(MissionAiValves.HasAssociation(net, net.Nodes[1], "hold")); Assert.False(MissionAiValves.HasAssociation(net, net.Nodes[1], "MFB Baker")); + Assert.False(MissionAiValves.HasAssociation(net, net.Nodes[0], null)); + // A second computed definition is dropped by the game with its whole record: its reactions are not the valve's. + var twice = Mw3ValveMap.Build([Source("data/c1/zrdr/aipath/m1/valves.zrd", "(done (all_nonzero namelist (a b)) done (any_zero namelist (c) sound (alarm 1)))")], "m1", token: Token).Find("done")!; + Assert.Equal(("all_nonzero", 0), (twice.Condition, twice.Reactions.Count)); Assert.Equal(["a", "b"], twice.Inputs); + Assert.NotNull(twice.Records[1].Problem); Assert.Single(twice.Problems); + } + + [Fact] + public void CardEditsChangeOnlyTheirTokensAndRenameFollowsEveryFile() + { + // Must-have: source files are authoritative; an edit that reflows comments or drops unknown text loses authored data. + byte[] bytes = Encoding.Latin1.GetBytes(Valves); + string Edit(SourceValveEdits.ValveChanges changes, string name = "bramp") => Encoding.Latin1.GetString(SourceValveEdits.PlanValve(bytes, name, changes, Token).Content); + // A changed delay replaces one token; the comments and the other record stay byte for byte. + Assert.Equal(Valves.Replace("18.0", "20.5"), Edit(new(Reactions: [new(1, "delayupdate", new("delayupdate", "truck_go", "20.5"))]))); + // Wake becomes a once-only sound in place: the tag and its arguments change, nothing else. + Assert.Equal(Valves.Replace("shutdown ( owens_01 0 1 )", "sound_once ( com_mech 1 )"), Edit(new(Reactions: [new(0, "shutdown", new("sound_once", "com_mech", When: "1"))]))); + // A new reaction is its own record after the valve's last one; removing the only reaction of a record removes that record. + string added = Edit(new(Reactions: [new(null, null, new("sound", "alarm", When: "1")), new(0, "shutdown", null)])); + // (The comment directly above the removed record goes with it, as the rewriter documents.) + Assert.DoesNotContain("shutdown", added); Assert.Contains("# later", added); + var program = Mw3ValveProgram.Read(ZrdText.Parse(added, Token), Token); + Assert.Equal(["bramp:delayupdate", "bramp:sound", "ready:"], program.Definitions.Select(d => d.Name + ":" + string.Join(",", d.Actions.Select(a => a.Kind)))); + // The starting value and a computed valve's inputs. + Assert.Contains("value ( 1 )", Edit(new(Initial: "1"))); + Assert.Equal(Valves.Replace("all_nonzero", "any_zero").Replace("( bramp gate )", "( bramp truck_go )"), Edit(new(Condition: "any_zero", Inputs: ["bramp", "truck_go"]), "ready")); + Assert.DoesNotContain("namelist", Edit(new(Condition: ""), "ready")); + // A computed valve keeps its stored start (the game ignores it): the card shows what is stored, so switch → computed → + // switch never applies a start other than the one shown. + string computed = Encoding.Latin1.GetString(SourceValveEdits.PlanValve(Encoding.Latin1.GetBytes("(armed (value (1)) other (value (0)))"), "armed", new(Condition: "any_nonzero", Inputs: ["other"]), Token).Content); + Assert.Contains("value (1)", computed); + var armed = Mw3ValveMap.Build([Source("data/c1/zrdr/aipath/m1/valves.zrd", computed)], "m1", token: Token).Find("armed")!; + Assert.Equal(("any_nonzero", 1), (armed.Condition, armed.Initial)); + Assert.Throws(() => Edit(new(Condition: "all_zero", Inputs: ["ready"]), "ready")); + // Two computed definitions: changing or removing the first would promote the one the game drops, so it is refused. + byte[] twice = Encoding.Latin1.GetBytes("(done (all_nonzero namelist (a b)) done (any_zero namelist (c)))"); + Assert.Throws(() => SourceValveEdits.PlanValve(twice, "done", new(Condition: ""), Token)); + Assert.Throws(() => SourceValveEdits.PlanValve(twice, "done", new(Inputs: ["a"]), Token)); + // Editing one field of a reaction leaves the others as stored: whole-number coordinates stay whole numbers. + Assert.Equal("(go (teleport (other (1 2 3) 0 1)))", Encoding.Latin1.GetString(SourceValveEdits.PlanValve(Encoding.Latin1.GetBytes("(go (teleport (mech (1 2 3) 0 1)))"), "go", + new(Reactions: [new(0, "teleport", new("teleport", "other", When: "1", X: "1", Y: "2", Z: "3", Yaw: "0"))]), Token).Content)); + Assert.Equal("(go (teleport (mech (1 2.5 3) 0 1)))", Encoding.Latin1.GetString(SourceValveEdits.PlanValve(Encoding.Latin1.GetBytes("(go (teleport (mech (1 2 3) 0 1)))"), "go", + new(Reactions: [new(0, "teleport", new("teleport", "mech", When: "1", X: "1", Y: "2.5", Z: "3", Yaw: "0"))]), Token).Content)); + // A whole number that becomes a fraction still changes in place: the comment after it and the lines around it stay. + const string commented = "(go (teleport (mech (1 # keep Y\r\n 2 3) 0 1)))"; + Assert.Equal(commented.Replace("(1 #", "(1.5 #"), Encoding.Latin1.GetString(SourceValveEdits.PlanValve(Encoding.Latin1.GetBytes(commented), "go", + new(Reactions: [new(0, "teleport", new("teleport", "mech", When: "1", X: "1.5", Y: "2", Z: "3", Yaw: "0"))]), Token).Content)); + Assert.Equal("(go (value (1) # start\r\n))", Encoding.Latin1.GetString(SourceValveEdits.PlanValve(Encoding.Latin1.GetBytes("(go (value (0.0) # start\r\n))"), "go", new(Initial: "1"), Token).Content)); + // One draft that removes a reaction and gives another its kind is valid whatever order its changes come in. + byte[] both = Encoding.Latin1.GetBytes("(scream (sound (yell 1) delayupdate (later 2.0)))"); + SourceValveEdits.ReactionChange retime = new(0, "sound", new("delayupdate", "after", "5")), drop = new(0, "delayupdate", null); + string forward = Encoding.Latin1.GetString(SourceValveEdits.PlanValve(both, "scream", new(Reactions: [retime, drop]), Token).Content); + Assert.Equal("(scream (delayupdate (after 5.0)))", forward); + Assert.Equal(forward, Encoding.Latin1.GetString(SourceValveEdits.PlanValve(both, "scream", new(Reactions: [drop, retime]), Token).Content)); + Assert.Throws(() => SourceValveEdits.PlanValve(both, "scream", new(Reactions: [retime]), Token)); + // Replacing one input changes only its word: the notes around it stay. + string noted = "(all_up (all_nonzero namelist (\r\n alpha\r\n # the second gate\r\n beta # opens late\r\n gamma)))"; + Assert.Equal(noted.Replace("beta #", "delta #"), Encoding.Latin1.GetString(SourceValveEdits.PlanValve(Encoding.Latin1.GetBytes(noted), "all_up", new(Inputs: ["alpha", "delta", "gamma"]), Token).Content)); + // Two rows given other names are those rows: nothing moves, each note stays on its line. + Assert.Equal(noted.Replace("beta #", "gamma #").Replace("gamma)))", "delta)))"), Encoding.Latin1.GetString(SourceValveEdits.PlanValve(Encoding.Latin1.GetBytes(noted), "all_up", new(Inputs: ["alpha", "gamma", "delta"]), Token).Content)); + // A removed row goes with its notes; the rows that stay keep theirs; an added one is new. + string shorter = Encoding.Latin1.GetString(SourceValveEdits.PlanValve(Encoding.Latin1.GetBytes(noted), "all_up", new(Inputs: ["alpha", "gamma"]), Token).Content); + Assert.True(!shorter.Contains("beta") && !shorter.Contains("opens late") && shorter.Contains(" alpha\r\n") && shorter.EndsWith("gamma)))", StringComparison.Ordinal), shorter); + Assert.Equal(noted.Replace("gamma)))", "gamma\r\n omega\r\n)))"), Encoding.Latin1.GetString(SourceValveEdits.PlanValve(Encoding.Latin1.GetBytes(noted), "all_up", new(Inputs: ["alpha", "beta", "gamma", "omega"]), Token).Content)); + // Skipping to a timer stops on the first tick that runs it (strictly after its time): one due a moment later still waits. + double first = Mw3ValveSimulation.TimerTime(0, 1f); + Assert.Equal(61, Math.Round(first * 60)); Assert.True(1f < (float)first && !(1.02f < (float)first)); + Assert.Equal(1, Math.Round(Mw3ValveSimulation.TimerTime(0, 0f) * 60)); Assert.Equal(31, Math.Round(Mw3ValveSimulation.TimerTime(.5, .25f) * 60)); + // A switch that still stores an input list (its condition commented out, say): making it computed uses that list, the + // one the game reads, instead of adding a second one it would never reach. + Assert.Equal("(gate ( all_nonzero namelist (new_input) sound (alarm 1)))", Encoding.Latin1.GetString(SourceValveEdits.PlanValve( + Encoding.Latin1.GetBytes("(gate (namelist (old_input) sound (alarm 1)))"), "gate", new(Condition: "all_nonzero", Inputs: ["new_input"]), Token).Content)); + // An edit the game would not read as shown is refused: here the list is nested where the card does not reach it. + Assert.Throws(() => SourceValveEdits.PlanValve(Encoding.Latin1.GetBytes("(gate ((namelist (old_input)) sound (alarm 1)))"), "gate", new(Condition: "all_nonzero", Inputs: ["new_input"]), Token)); + // A record that stores a plain and a once-only sound: the game uses the once-only one. Its fields can change, but + // making it plain or removing it would make the other one the active sound, so that is refused. + byte[] shadowed = Encoding.Latin1.GetBytes("(alarm (sound (old 1) sound_once (new 1)))"); + Assert.Equal("(alarm (sound (old 1) sound_once (newer 1)))", Encoding.Latin1.GetString(SourceValveEdits.PlanValve(shadowed, "alarm", new(Reactions: [new(0, "sound_once", new("sound_once", "newer", When: "1"))]), Token).Content)); + Assert.Throws(() => SourceValveEdits.PlanValve(shadowed, "alarm", new(Reactions: [new(0, "sound_once", new("sound", "new", When: "1"))]), Token)); + Assert.Throws(() => SourceValveEdits.PlanValve(shadowed, "alarm", new(Reactions: [new(0, "sound_once", null)]), Token)); + // What a file already has wrong (two computed definitions, as a shipped mission has) neither blocks another valve's + // edit nor lets it add a reaction that can never finish. + byte[] conflicted = Encoding.Latin1.GetBytes("(done (all_nonzero namelist (a b)) done (any_zero namelist (c)) start (sound (go 1)))"); + Assert.Contains("sound_once", Encoding.Latin1.GetString(SourceValveEdits.PlanValve(conflicted, "start", new(Reactions: [new(2, "sound", new("sound_once", "go", When: "1"))]), Token).Content)); + Assert.Throws(() => SourceValveEdits.PlanValve(conflicted, "start", new(Reactions: [new(null, null, new("update", "start"))]), Token)); + Assert.Contains("(go 2)", Encoding.Latin1.GetString(SourceValveEdits.Plan("valves.zrd", conflicted, "update", 2, "start", "(sound (go 2))", Token).Content)); + Assert.Throws(() => Edit(new(Reactions: [new(null, null, new("update", "bramp"))]))); + // A valve no record names yet gets one; a mission without valves.zrd gets the file. + string fresh = Edit(new(), "fresh"); + Assert.StartsWith(Valves[..^3], fresh); + Assert.Contains(Mw3ValveProgram.Read(ZrdText.Parse(fresh, Token), Token).Definitions, d => d is { Name: "fresh", Initial: 0 }); + Assert.Contains("fresh", Encoding.Latin1.GetString(SourceValveEdits.PlanValve(null, "fresh", new(), Token).Content)); + // Rename: records, another valve's inputs, a trigger, a gate, a deploy point and only this mission's objective. + Assert.Equal(Valves.Replace("bramp", "ramp"), Encoding.Latin1.GetString(SourceValveEdits.PlanRename("valves.zrd", bytes, "bramp", "ramp", "m1", Token)!.Content)); + string Rename(string member, string text, string name) => Encoding.Latin1.GetString(SourceValveEdits.PlanRename(member, Encoding.Latin1.GetBytes(text), name, "renamed", "m1", Token)!.Content); + Assert.Equal("(player (0 vlist ((1 0 0.25 0 0 0.999 0 0.8 1 bramp 0 0.0 0 60.0 1 renamed 0))))", Rename("aiv.zrd", "(player (0 vlist ((1 0 0.25 0 0 0.999 0 0.8 1 bramp 0 0.0 0 60.0 1 bramp 0))))", "bramp")); + Assert.Equal("(version (106) node_00 (12 (0.0 0.0 0.0) () valve (1 renamed 1) deploy (renamed 1 other 0 0)))", Rename("net_02.zrd", "(version (106) node_00 (12 (0.0 0.0 0.0) () valve (1 bramp 1) deploy (bramp 1 other 0 0)))", "bramp")); + Assert.Equal("(m1 (primary (valve_change (valve (renamed)))) m2 (primary (valve_change (valve (bramp)))))", Rename("objectives.zrd", "(m1 (primary (valve_change (valve (bramp)))) m2 (primary (valve_change (valve (bramp)))))", "bramp")); + Assert.Null(SourceValveEdits.PlanRename("targets.zrd", Encoding.Latin1.GetBytes("(satdish (2 health_below (other 1 0.0)))"), "bramp", "renamed", "m1", Token)); + Assert.DoesNotContain("bramp", Encoding.Latin1.GetString(SourceValveEdits.PlanRemove(bytes, "bramp", Token).Content).Replace("namelist ( bramp", "")); + } + + [Fact] + public async Task OptionalRetailC1MissionReadsAsTheShippedFilesSay() + { + string? root = Environment.GetEnvironmentVariable("ZSTUDIO_MW3_SOURCE_PROJECT"); + if (root == null || SourceProject.Game(root, Token) != GameVariant.MechWarrior3) return; + var source = await SourceWorlds.LoadSceneAsync(root, "c1", token: Token); + var callbacks = Mw3ValveSimulation.CallbackValves(source.Animations!, source.MissionScene(MissionDifficulty.Medium, Token), Token); + var map = Mw3ValveMap.Build(source.Resources.Values.Where(r => r.Root != null).Select(r => new Mw3ValveSource(r.Path, r.Root!)), Path.GetFileName(source.SourceMission), token: Token, callbacks: callbacks); + var bramp = map.Find("bramp")!; + Assert.Equal(4, bramp.Records.Count); + // The ramp's animation sets bramp through the scene node of that name (the test binds it the same way). + Assert.Contains(bramp.SetBy, l => l is { Role: "animation", Owner: "call_ramp" }); + Assert.Equal("wakes owens_01 · 2 timers · 1 sound", bramp.Summary); + Assert.Contains(map.Find("comcntr_down")!.SetBy, l => l is { Role: "health", Actor: "satdish" }); + Assert.Contains(map.Find("comcntr_down")!.UsedBy, l => l.Role == "objective"); + Assert.Contains(map.Find("mcbdeploy")!.UsedBy, l => l.Role == "gate"); + Assert.DoesNotContain(map.Valves, v => v.Name == "outside_c1m2"); + } +} diff --git a/tests/zStudio.Tests/Mw3ValveRuntimeTests.cs b/tests/zStudio.Tests/Mw3ValveRuntimeTests.cs new file mode 100644 index 00000000..66b9b8cd --- /dev/null +++ b/tests/zStudio.Tests/Mw3ValveRuntimeTests.cs @@ -0,0 +1,127 @@ +using System.Text; +using zStudio.Core; +using zStudio.Core.Formats; +using zStudio.Core.Sources; +using Xunit; + +namespace zStudio.Tests; + +public sealed class Mw3ValveRuntimeTests +{ + [Fact] + public async Task OptionalRetailC1StartupConnectsAnimationCallbacksAndValveReactions() + { + string? root = Environment.GetEnvironmentVariable("ZSTUDIO_MW3_SOURCE_PROJECT"); + if (root == null || SourceProject.Game(root, TestContext.Current.CancellationToken) != GameVariant.MechWarrior3) return; + var token = TestContext.Current.CancellationToken; + var source = await SourceWorlds.LoadSceneAsync(root, "c1", token: token); + var baseline = source.MissionScene(MissionDifficulty.Medium, token); + var resource = source.Resources.Values.Single(r => Path.GetFileName(r.Path) == "valves.zrd"); + byte[] before = File.ReadAllBytes(Path.Combine(root, resource.Path)); + var context = zStudio.Core.Animation.AnimationPreviewContext.FromSourceBaseline(source, baseline.ValveStartupBaseline(token), token); + var simulation = new Mw3ValveSimulation(context, Mw3ValveProgram.Read(resource.Root!, token), token); + // Startup starts call_ramp; its attach is outside the authored 500-unit range. + Assert.Equal(0, simulation.Runtime.Value("bramp")); + Assert.Contains(simulation.CurrentFrame.Instances, i => i.Name == "call_ramp"); + simulation.Set("bramp", 1, token); + Assert.False(simulation.Actors["owens_01"].PoweredDown); + Assert.Contains(simulation.Runtime.Timers, t => t.Target == "truck_go" && t.Due == 18); + simulation.Advance(18, token); Assert.Equal(0, simulation.Runtime.Value("truck_go")); + simulation.Advance(18 + zStudio.Core.Animation.AnimationPlayer.StepSeconds, token); Assert.Equal(1, simulation.Runtime.Value("truck_go")); + Assert.Equal(before, File.ReadAllBytes(Path.Combine(root, resource.Path))); + } + private static ZrdNode Parse(string text) => ZrdText.Parse(text, TestContext.Current.CancellationToken); + private static Mw3ValveRuntime Runtime(string text) => new(Mw3ValveProgram.Read(Parse(text), TestContext.Current.CancellationToken)); + + [Theory] + [InlineData("(sound alarm)")] + [InlineData("(value (1 2))")] + [InlineData("(all_nonzero namelist (go 1))")] + [InlineData("(sound)")] + [InlineData("(value)")] + [InlineData("(all_zero namelist (sound) sound (tone 1))")] + public void SourceEditsRefuseMalformedRecognizedProperties(string parameters) + { + Assert.Throws(() => SourceValveEdits.Plan("valves.zrd", Encoding.Latin1.GetBytes("(go (value (0)))"), "update", 0, "go", parameters, TestContext.Current.CancellationToken)); + } + [Fact] + public void SourceAssociationValidationAndRawInitialWordsSurviveEditing() + { + byte[] network = Encoding.Latin1.GetBytes("(version (106) node_00 (12 (0.0 0.0 0.0) (0) valve (1 gate) valve_assign (passed 1)))"); + Assert.Throws(() => SourceValveEdits.Plan("net_01.zrd", network, "update", 0, null, "(1)", TestContext.Current.CancellationToken)); + Assert.Throws(() => SourceValveEdits.Plan("net_01.zrd", network, "update", 1, null, "(passed)", TestContext.Current.CancellationToken)); + Assert.Equal(BitConverter.SingleToInt32Bits(1), Runtime("(go (value (1.0)))").Value("go")); + Assert.Equal(1, Runtime("(go (namelist (other) all_zero))").Value("go")); + var terminal = MissionAiValves.Records("valves.zrd", Parse("(go (namelist (other) all_zero))"), TestContext.Current.CancellationToken).Single(); + Assert.Contains(MissionAiValves.References(terminal, TestContext.Current.CancellationToken), r => r.Name == "other" && r.Role == "compound input"); + var objective = MissionAiValves.Records("objectives.zrd", Parse("(objective (valve_change (valve (gate) value (1))))"), TestContext.Current.CancellationToken).Single(); + Assert.Null(MissionAiValves.Problem(objective, TestContext.Current.CancellationToken)); + var health = MissionAiValves.Records("targets.zrd", Parse("(actor (health_below (normal 1 35.0 set_valve 1 0.0)))"), TestContext.Current.CancellationToken).ToArray(); + Assert.Equal("set_valve", Assert.Single(MissionAiValves.References(health[1], TestContext.Current.CancellationToken)).Name); + } + + // The native change notifications and timer frontier drive ordinary shipped dialogue and activation chains. + [Fact] + public void RepeatedDefinitionsConditionsOnceAndRetailTimerFrontier() + { + var runtime = Runtime(""" + (go (sound_once (first 1) sound (ignored 1)) + go (shutdown (actor 0 1) delayupdate (later 2.0)) + any (any_nonzero namelist (go other) sound (compound 1)) + later (delayupdate (last 1.0)) + last (sound (final 1))) + """); + runtime.Set("go", 1); + Assert.Equal(new[] { "sound_once", "shutdown", "sound" }, runtime.DrainEffects().Select(e => e.Kind)); + Assert.Equal(1, runtime.Value("any")); + runtime.Set("go", 1); Assert.Empty(runtime.DrainEffects()); + runtime.Tick(2); Assert.Equal(0, runtime.Value("later")); + runtime.Tick(2.01f); Assert.Equal(1, runtime.Value("later")); + Assert.Empty(runtime.Timers); // Retail lone-timer replacement drops the newly made timer. + Assert.Contains(runtime.Trace, t => t.Kind == "timer quirk"); + runtime.Set("other", 1); Assert.Single(runtime.DrainEffects()); // Compound value stayed one; its reactions still fire. + runtime.Set("go", 0); runtime.Set("go", 1); + Assert.DoesNotContain(runtime.DrainEffects(), e => e.Kind == "sound_once"); + Assert.Equal(0, runtime.Value("GO")); // Names are exact. + } + + [Fact] + public void CompositeTimersVisitNewTimersAndComputedWritesKeepTheirValue() + { + var runtime = Runtime("(a (delayupdate (b 1.0)) a (delayupdate (hold 10.0)) b (delayupdate (c 1.0)) test (all_zero namelist (a b) sound (sample 1)))"); + Assert.Equal(1, runtime.Value("test")); + runtime.Set("test", 0); Assert.Equal(1, runtime.Value("test")); Assert.Single(runtime.DrainEffects()); + runtime.Set("a", 1); runtime.Tick(1.1f); + Assert.Equal(2, runtime.Timers.Count); + runtime.Tick(2.2f); Assert.Equal(1, runtime.Value("c")); + var retained = Runtime("(go (delayupdate (early 1.0)) go (delayupdate (later 10.0)) later (delayupdate (last 1.0)))"); + retained.Set("go", 1); retained.Tick(1.1f); Assert.Single(retained.Timers); + retained.Tick(10.1f); Assert.Single(retained.Timers); // Native slot remains a composite across ticks. + retained.Tick(11.2f); Assert.Equal(1, retained.Value("last")); + } + + [Fact] + public void SourceChangesKeepCommentsOccurrencesAndRejectImmediateCycles() + { + const string text = "(\n# header\ngo (sound (\"old\" 1)) # retained\n\ngo (delayupdate (later 2.0))\n)"; + var edited = SourceValveEdits.Plan("valves.zrd", Encoding.Latin1.GetBytes(text), "update", 0, "go", "(sound (\"new\" 1))", TestContext.Current.CancellationToken); + string changed = Encoding.Latin1.GetString(edited.Content); + Assert.Equal(text.Replace("\"old\"", "new"), changed); + Assert.Throws(() => SourceValveEdits.Plan("valves.zrd", edited.Content, "update", 0, "go", "(update (go))", TestContext.Current.CancellationToken)); + var removed = SourceValveEdits.Plan("valves.zrd", edited.Content, "delete", 1, null, null, TestContext.Current.CancellationToken); + Assert.Single(MissionAiValves.Records("valves.zrd", Parse(Encoding.Latin1.GetString(removed.Content)), TestContext.Current.CancellationToken)); + } + + [Fact] + public void OutgoingDefaultsUsePhysicalNonnegativeSlotsAndAssignmentsDoNotGate() + { + var root = Parse("(version (106) node_00 (12 (0.0 0.0 0.0) (1 -1 2) valve (1 go)) node_01 (12 (1.0 0.0 0.0) ()) node_02 (12 (2.0 0.0 0.0) ()) node_03 ((0 1 2) valve_assign (passed 7)))"); + var net = MissionAiNetworks.Decode("test", "", 0, "net_01.zrd", root, TestContext.Current.CancellationToken); + var runtime = Runtime("()"); + Assert.True(Mw3ValveRoutes.Evaluate(net, net.Nodes[0], 0, runtime).Passable); + Assert.False(Mw3ValveRoutes.Evaluate(net, net.Nodes[0], 2, runtime).Passable); + Assert.Single(Mw3ValveRoutes.Evaluate(net, net.Nodes[0], 0, runtime).Assignments); + runtime.Set("go", 1); + Assert.True(Mw3ValveRoutes.Evaluate(net, net.Nodes[0], 2, runtime).Passable); + } +} diff --git a/tools/zStudio.PreviewCheck/Mw3SourceLiveCheck.cs b/tools/zStudio.PreviewCheck/Mw3SourceLiveCheck.cs index d2f64daf..967cbf0a 100644 --- a/tools/zStudio.PreviewCheck/Mw3SourceLiveCheck.cs +++ b/tools/zStudio.PreviewCheck/Mw3SourceLiveCheck.cs @@ -31,7 +31,10 @@ internal static async Task Run(McpClient client, string original) await Call("open_root", new { path = root, project = true }); var maps = (await Call("source_world_list", new { }))["items"]!.AsArray(); if (maps.Any(m => m!["mission"]!.GetValue() == "lab")) throw new InvalidDataException("The library was listed as a campaign map."); - foreach (string map in new[] { "c1", "c2", "c3", "c4", "c4b", "t1" }) + // ZSTUDIO_MW3_MAPS narrows the check to some maps (c1 alone covers valves and diagnostics); the default is all six. + string[] chosen = Environment.GetEnvironmentVariable("ZSTUDIO_MW3_MAPS")?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) is { Length: > 0 } some + ? some : ["c1", "c2", "c3", "c4", "c4b", "t1"]; + foreach (string map in chosen) { await Call("source_world_open", new { mission = map }); var state = await Call("state", new { }); string preview = state["preview"]!.GetValue(); @@ -80,6 +83,27 @@ internal static async Task Run(McpClient client, string original) var tree = await Call("scene_tree", new { document = documentId }); var uses = await Call("scene_tree", new { document = documentId, preview, context = tree["context"]!.GetValue(), action = "animationUses", node = tower.Index }); if (uses["total"]!.GetValue() == 0) throw new InvalidDataException("The bridge tower has no animation navigation."); + // Valves: the mission's valves by name, a valve's card, and the test from a trigger to its timer. + var valves = (await Call("source_ai_valve", new { document = documentId, action = "valves", limit = 200 }))["items"]!.AsArray(); + if (!valves.Any(v => v!["name"]!.GetValue() == "bramp" && v["summary"]!.GetValue() == "wakes owens_01 · 2 timers · 1 sound")) + throw new InvalidDataException("Retail c1 m1 valves are not listed by name with what they do."); + var valveRow = (await Call("scene_tree", new { document = documentId, search = "bramp", types = "valve" }))["matches"]!["items"]!.AsArray() + .Select(m => m!["item"]!).First(i => i["sectionRow"]?["name"]?.GetValue() == "bramp"); + tree = await Call("scene_tree", new { document = documentId }); + await Call("scene_tree", new { document = documentId, preview, context = tree["context"]!.GetValue(), action = "select", row = valveRow["row"]!.GetValue() }); + await WindowCapture("c1-valve-card"); + preview = (await Call("state", new { }))["preview"]!.GetValue(); + var test = await Call("ai_valve_preview", new { preview, action = "start" }); + string simulation = test["simulation"]!.GetValue(); + test = await Call("ai_valve_preview", new { preview, simulation, action = "set", name = "bramp", value = 1 }); + if (test["timerCount"]!.GetValue() != 2 || !test["actors"]!.AsArray().Any(a => a!["name"]!.GetValue() == "owens_01" && a["PoweredDown"]?.GetValue() == false)) + throw new InvalidDataException("Setting bramp did not wake owens_01 and start its two timers."); + test = await Call("ai_valve_preview", new { preview, simulation, action = "next" }); + if (!test["values"]!.AsArray().Any(v => v!["name"]!.GetValue() == "truck_go" && v["Value"]!.GetValue() == 1)) + throw new InvalidDataException("The next timer did not set truck_go."); + await WindowCapture("c1-valve-test"); + await Call("ai_valve_preview", new { preview, simulation, action = "stop" }); + tree = await Call("scene_tree", new { document = documentId }); int repeated = source.Animations!.Entries.Single(e => e.Name == "dest_shrubgrp#17").Index; int bridge = source.Animations.Entries.First(e => e.RootName == "rbrgtwr6").Index; long revision = Document(state)["Revision"]!.GetValue(); @@ -113,6 +137,13 @@ internal static async Task Run(McpClient client, string original) throw new InvalidDataException("The native source check changed " + relative); Console.WriteLine($"PASS: {hashes.Count} native source inputs and copied files unchanged."); + async Task WindowCapture(string name) + { + await Task.Delay(500); + var capture = await client.CallToolAsync("zstudio_capture", new Dictionary { ["target"] = "window" }); + if (capture.IsError == true) throw new InvalidDataException("Cannot capture " + name + "."); + File.WriteAllBytes(Path.Combine(output, name + ".png"), capture.Content.OfType().First().DecodedData.ToArray()); + } static string Hash(string path) { using var stream = File.OpenRead(path); return Convert.ToHexString(SHA256.HashData(stream)); } static JsonNode Document(JsonNode state) => state["documents"]!.AsArray().Single(d => d!["id"]!.GetValue() == state["activeDocument"]!.GetValue())!; async Task Call(string name, object values)