From 13f501eb68c384a5bfd76241060aa5ae14fd03e4 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:28:01 +0100 Subject: [PATCH 01/72] =?UTF-8?q?=F0=9F=9A=80=20Version=20v0.9.5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 12 ++++++------ Cargo.toml | 2 +- dispel-encodings/Cargo.toml | 2 +- dispel-gui/Cargo.toml | 2 +- dispel-macros/Cargo.toml | 2 +- gui-widgets/Cargo.toml | 2 +- hexedit/Cargo.toml | 2 +- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e973f40f..0cfd17c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1316,7 +1316,7 @@ dependencies = [ [[package]] name = "dispel-encodings" -version = "0.9.4" +version = "0.9.5" dependencies = [ "encoding_rs", "serde", @@ -1324,7 +1324,7 @@ dependencies = [ [[package]] name = "dispel-extractor" -version = "0.9.4" +version = "0.9.5" dependencies = [ "byteorder", "clap", @@ -1346,7 +1346,7 @@ dependencies = [ [[package]] name = "dispel-gui" -version = "0.9.4" +version = "0.9.5" dependencies = [ "bincode 1.3.3", "chrono", @@ -1382,7 +1382,7 @@ dependencies = [ [[package]] name = "dispel-macros" -version = "0.9.4" +version = "0.9.5" dependencies = [ "dispel-encodings", "proc-macro2", @@ -2012,7 +2012,7 @@ dependencies = [ [[package]] name = "gui-widgets" -version = "0.9.4" +version = "0.9.5" dependencies = [ "iced", "iced_renderer", @@ -2122,7 +2122,7 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "hexedit" -version = "0.9.4" +version = "0.9.5" dependencies = [ "dirs", "encoding_rs", diff --git a/Cargo.toml b/Cargo.toml index d94bb6ea..78bf6107 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,7 +24,7 @@ path = "src/lib.rs" [package] name = "dispel-extractor" -version = "0.9.4" +version = "0.9.5" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/dispel-encodings/Cargo.toml b/dispel-encodings/Cargo.toml index 5df00030..543917aa 100644 --- a/dispel-encodings/Cargo.toml +++ b/dispel-encodings/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dispel-encodings" -version = "0.9.4" +version = "0.9.5" edition = "2024" [dependencies] diff --git a/dispel-gui/Cargo.toml b/dispel-gui/Cargo.toml index 3d631ae4..56cbbba8 100644 --- a/dispel-gui/Cargo.toml +++ b/dispel-gui/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dispel-gui" -version = "0.9.4" +version = "0.9.5" edition = "2024" [dependencies] diff --git a/dispel-macros/Cargo.toml b/dispel-macros/Cargo.toml index 049b4a52..1f523348 100644 --- a/dispel-macros/Cargo.toml +++ b/dispel-macros/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dispel-macros" -version = "0.9.4" +version = "0.9.5" edition = "2024" [lib] diff --git a/gui-widgets/Cargo.toml b/gui-widgets/Cargo.toml index 6d8febcb..c29700fc 100644 --- a/gui-widgets/Cargo.toml +++ b/gui-widgets/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "gui-widgets" -version = "0.9.4" +version = "0.9.5" edition = "2024" [features] diff --git a/hexedit/Cargo.toml b/hexedit/Cargo.toml index f90a71a6..5db9ef4b 100644 --- a/hexedit/Cargo.toml +++ b/hexedit/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hexedit" -version = "0.9.4" +version = "0.9.5" edition = "2024" [[bin]] From 459f37ba97a15e53e013b70a644bf28e80f9b48c Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:29:23 +0100 Subject: [PATCH 02/72] docs: rewrite seven documents in plain English with observable facts --- README.md | 87 +++++------- docs/database_and_references.md | 98 +++++++------- docs/file_formats.md | 211 ++++++++++++++---------------- docs/iced-fork-config.md | 92 ++++--------- docs/overview.md | 67 +++++----- docs/rendering.md | 53 ++++---- gui-widgets/src/sweeten/README.md | 2 +- 7 files changed, 268 insertions(+), 342 deletions(-) diff --git a/README.md b/README.md index 401362a8..b6992d5c 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,18 @@ # DISPEL® Game File Extractor -A modding toolkit for the **DISPEL®** RPG game. Reads and writes game files in native binary, INI, and DB formats. Includes a CLI, a desktop GUI with 46 editor types, a hex editor, and a full mod packaging pipeline. All edits are persisted directly to game files — no intermediate database. +This toolkit reads and writes DISPEL® game files in binary, INI and DB formats. It includes a CLI, a desktop GUI with 46 editor types, a hex editor and a mod packaging pipeline. The tools write each edit into the game file. They do not keep a separate database. -**Not affiliated with, endorsed by, or sponsored by the trademark owner.** +## Scope and notice ---- +This project reads and writes data files for DISPEL®. It ships no game content. You provide the files you edit. + +DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark owner. + +The source code is licensed under the MIT License (LICENSE). Game content is not covered by this license. ## What's in this repository -This is a 6-crate Cargo workspace (Rust 2024, version `0.9.3`): +This Cargo workspace has six crates. The workspace uses Rust 2024 and version `0.9.3`. | Crate | Type | Role | | ------------------------- | ---------- | --------------------------------------------------------------- | @@ -23,18 +27,16 @@ This is a 6-crate Cargo workspace (Rust 2024, version `0.9.3`): | Directory | Contents | | --------------------- | ------------------------------------------------------------------- | -| `src/references/` | 30+ parsers for `.db`, `.ini`, `.ref` game data files | +| `src/references/` | 51 source files with parsers for `.db`, `.ini` and `.ref` files | | `src/map/` | `.map` parser + isometric tile/sprite/event renderer | | `src/sprite.rs` | `.spr` sprite and animation parser (RGB 565) | -| `src/snf.rs` | `.snf` audio parser (PCM → WAV conversion) | +| `src/snf.rs` | `.snf` audio parser (PCM to WAV conversion) | | `src/modding/` | Mod authoring pipeline (apply, patch, package, conflict resolution) | | `src/commands/` | CLI command implementations (11 subcommands) | | `src/queries/` | 118 SQL files (59 schema DDL + 59 parameterized INSERTs) | -| `src/localization.rs` | Text export/import for translations | +| `src/localization.rs` | Text export and import for translations | | `src/database.rs` | SQLite schema bootstrap | ---- - ## Supported file formats ### Binary DB files (`.db`) @@ -53,7 +55,7 @@ This is a 6-crate Cargo workspace (Rust 2024, version `0.9.3`): | `DrawItem.db` | Draw items | | `PartyLevelNpc.db` | Party level NPC data | -### INI / text files +### INI and text files | File | Description | | ------------- | -------------------------- | @@ -79,15 +81,13 @@ This is a 6-crate Cargo workspace (Rust 2024, version `0.9.3`): | Extension | Description | | --------------- | ---------------------------------------------- | | `.map` | Map geometry (tiles, sprites, events) | -| `.gtl` / `.btl` | Tilesets (ground / roof, RGB 565, 32×32 tiles) | +| `.gtl` / `.btl` | Tilesets (ground / roof, RGB 565, 32x32 tiles) | | `.spr` | Character sprites and animations (RGB 565) | -| `.snf` | Sound effects (custom PCM → WAV) | +| `.snf` | Sound effects (custom PCM to WAV) | | `.dlg` / `.pgp` | Dialogue scripts and text (EUC-KR / 1250) | | `.scr` | Event scripts (1250) | -Full format specs are in `docs/files/` (36 per-format documents plus `CROSS_REFERENCES.md`). - ---- +Format specifications are in `docs/files/`. That directory holds 36 per-format documents and `CROSS_REFERENCES.md`. ## CLI usage @@ -131,17 +131,18 @@ cargo run -- schema --type weapons cargo run -- template --type weapons --pretty ``` -### Sprite and animation extraction +### Extract sprites and animations ```bash cargo run -- sprite fixtures/Dispel/CharacterInGame/M_BODY1.SPR --mode sprite cargo run -- sprite fixtures/Dispel/CharacterInGame/M_BODY1.SPR --mode animation ``` -### Sound conversion +### Convert sound files ```bash -cargo run -- sound --input fixtures/Dispel/Sound/sample.snf --output output.wav +cargo run -- sound to-wav fixtures/Dispel/Sound/sample.snf output.wav +cargo run -- sound from-wav output.wav sample.snf ``` ### Map operations @@ -171,6 +172,8 @@ cargo run -- database import fixtures/Dispel/ db.sqlite ### Mod packaging +The CLI `mod-pack` command reads `Event*.scr` files from the game `Ref/` folder and writes JSON. + ```bash cargo run -- mod-pack --help ``` @@ -181,8 +184,6 @@ cargo run -- mod-pack --help cargo run -- --help ``` ---- - ## GUI Launch the desktop editor: @@ -191,28 +192,26 @@ Launch the desktop editor: cargo run -p dispel-gui ``` -The GUI provides: - -- **46 editor types** — spreadsheet views for every supported game data format -- **3-pane layout** — sidebar (file tree), main content (editors), history panel (undo/redo) -- **Undo/redo** with full edit history per editor -- **Mod recording** — tracks every field change for mod changelog generation -- **Full-text search** — nucleo-matcher fuzzy search across all loaded files -- **Hex editor** — built-in hex editor (from `hexedit` crate) -- **Map viewer** — isometric rendering with viewport + LRU cache -- **SNF audio playback** — rodio-based sound preview -- **Audio viewer** — read-only OGG/WAV playback with timeline and volume -- **BMP viewer** — read-only image preview with zoom and fit-to-viewport -- **Mod packager** — package changes into `dispel-mod` archives +The GUI has these features: ---- +- 46 editor types with spreadsheet views for supported game data formats +- A three-pane layout with a sidebar for the file tree, main content for editors and a history panel for undo and redo +- Undo and redo with an edit history for each editor +- Mod recording that tracks every field change for the mod changelog +- Full-text search with nucleo-matcher fuzzy search across loaded files +- A hex editor from the `hexedit` crate +- A map viewer with isometric rendering, a viewport and an LRU cache +- SNF audio playback with rodio +- An audio viewer for read-only OGG and WAV playback with timeline and volume +- A BMP viewer for read-only image preview with zoom and fit to viewport +- A mod packager that stores work in `.dispel-mods`. It writes a zip with `manifest.json`, `changes.json`, `patches/` and `files/`. ## Project structure ``` dispel-extractor/ ├── src/ # dispel-core library + CLI binary -│ ├── references/ # 30+ game data file parsers +│ ├── references/ # 51 game data file parsers │ ├── map/ # .map parser + isometric renderer │ ├── modding/ # Mod authoring pipeline │ ├── commands/ # CLI command implementations @@ -236,13 +235,9 @@ dispel-extractor/ └── release.sh # Automated release script ``` ---- - ## Development -The canonical build, format, lint and test commands live in -`scripts/ci-commands.sh` (11 commands). CI and the Makefile delegate to that -script, so use it or the matching `make` target rather than an inline command: +The canonical build, format, lint and test commands live in `scripts/ci-commands.sh`. The script has 11 commands. CI and the Makefile call that script. Use the script or the matching `make` target. ```bash bash scripts/ci-commands.sh --list # show all canonical commands @@ -282,15 +277,3 @@ cargo run -p dispel-gui | `make sprite-animation` | Extract animations | | `make mod-pack` | Package a mod | | `make help` | Show all Makefile targets | - ---- - -## Legal - -This project is **not affiliated with, endorsed by, or sponsored by** the DISPEL® trademark owner. - -This tool is for **independent file-format interoperability research based on observable program behavior** only. It does not redistribute copyrighted game files and does not circumvent technological protection measures. - -### License - -The source code is licensed under the **[MIT License](LICENSE)**. Game content, assets, and proprietary formats are not covered by this license. diff --git a/docs/database_and_references.md b/docs/database_and_references.md index 441a2064..2b0b11ff 100644 --- a/docs/database_and_references.md +++ b/docs/database_and_references.md @@ -1,57 +1,63 @@ -# Database & Entities +# Database and entities -The extractor populates a SQLite database (`database.sqlite`) using `database.rs`. +The tool populates a SQLite database (`database.sqlite`) through `database.rs`. -## Schema Overview -Tables are created on the fly using SQL files found in `src/queries/`. +## Schema overview -### Core Entities +Tables come from SQL files in `src/queries/`. The tool creates the tables when it imports data. + +### Core entities #### Maps (`save_maps`) -- **Table**: `create_table_maps.sql` -- **Fields**: ID, Filename, Name, PGP Filename, DLG Filename, Is Light. -#### Map Tiles (`save_map_tiles`) -- Stored per coordinate (X, Y). -- **Fields**: MapID, X, Y, GTL_ID (Ground), BTL_ID (Building), Collision (Bool), EventID. +- Table: `create_table_maps.sql` +- Fields: ID, Filename, Name, PGP Filename, DLG Filename, Is Light. + +#### Map tiles (`save_map_tiles`) + +- The tool stores one row per coordinate (X, Y). +- Fields: MapID, X, Y, GTL_ID (ground), BTL_ID (building), Collision (Bool), EventID. + +#### Events and dialogs -#### Events & Dialogs -- **Events**: ID, Previous ID, Type, Filename, Counter. -- **Dialogs**: ID, Prev Event ID, Next Dialog, Type, Owner, DLG ID, Event ID. +- Events: ID, Previous ID, Type, Filename, Counter. +- Dialogs: ID, Prev Event ID, Next Dialog, Type, Owner, DLG ID, Event ID. #### Items -Separate tables for different item categories: -- **Weapons**: Stats (Str, Agi, Wis, Atk, Def), Price, Requirements. -- **HealItems**: HP/MP/Status recovery effects. -- **MiscItems**: Basic description/price. -- **EventItems**: Name/Description. -- **DrawItems**: Map items (MapID, X, Y, ItemID). -- **Store**: Shop definitions and product lists. - -#### Characters & Monsters -- **Monsters**: Huge stat block (HP/MP min/max, Atk/Def/Hit/Dodge min/max, XP/Gold, Spells, AI type). - - **Monster Refs**: Placed monster instances on maps (Pos X, Y, Loot). - - **Monster Inis**: Visual/Sprite references. -- **NPCs**: - - **NPC Refs**: Placed NPCs (Pos, Scripts, Dialog IDs). - - **NPC Inis**: Visual/Sprite references. -- **Party**: - - **Party Refs**: Joinable components, Job names. + +The tool uses separate tables for item categories: + +- Weapons: Stats (Str, Agi, Wis, Atk, Def), Price, Requirements. +- HealItems: HP, MP and status recovery effects. +- MiscItems: Basic description and price. +- EventItems: Name and description. +- DrawItems: Map items with MapID, X, Y and ItemID. +- Store: Shop definitions and product lists. + +#### Characters and monsters + +- Monsters: HP, MP, Atk, Def, Hit and Dodge minimum and maximum values, plus XP, Gold, Spells and AI type. +- Monster refs: Placed monster instances on maps with Pos X, Y and Loot. +- Monster inis: Visual and sprite references. +- NPCs: + - NPC refs: Placed NPCs with Pos, Scripts and Dialog IDs. + - NPC inis: Visual and sprite references. +- Party: + - Party refs: Joinable components and Job names. #### Other -- **Extras**: Interactive objects? (Sprite file, Description). -- **Waves**: SNF filenames (Sound/Music triggers?). - -## Data Injection Logic -The `save_all` function in `main.rs` reads from hardcoded paths (e.g., `fixtures/Dispel/Ref/Map.ini`) using parsers in the `references` module, then calls the corresponding `save_*` function in `database.rs`. - -Each `save_*` function: -1. Executes a `create_table_*.sql`. -2. Iterates over the parsed data vector. -3. Executes an `insert_*.sql` for each record. - -**Exception:** the inserts for `chest_spawns`, `monster_spawns`, `map_info_multi` and -`tile_grids` live inline in `src/references/chest_spawn.rs`, `monster_spawn.rs`, -`map_info_multi.rs` and `tile_grid.rs` respectively (they use `conn.execute` -directly rather than a prepared `include_str!` statement). There are deliberately -no `insert_*.sql` files for those four tables — do not re-add them. + +- Extras: Sprite file and description. +- Waves: SNF filenames. + +## Data import + +The CLI imports game data with `cargo run -- database import `. The command reads files from the given directory with the parsers in `src/references/`. It calls the matching `save_*` function in `database.rs`. + +Each `save_*` function does three things: + +1. It runs a `create_table_*.sql` file. +2. It iterates over the parsed records. +3. It runs an `insert_*.sql` file for each record. + +The inserts for `chest_spawns`, `monster_spawns`, `map_info_multi` and `tile_grids` live inline in `src/references/chest_spawn.rs`, `src/references/monster_spawn.rs`, `src/references/map_info_multi.rs` and `src/references/tile_grid.rs`. They call `conn.execute` directly instead of a prepared `include_str!` statement. No `insert_*.sql` files exist for those four tables. Do not re-add them. diff --git a/docs/file_formats.md b/docs/file_formats.md index 2861b453..e391bf17 100644 --- a/docs/file_formats.md +++ b/docs/file_formats.md @@ -1,29 +1,24 @@ -# File Formats & Parsing +# File formats and parsing -## Legal Notice +This document records the binary layouts that the extractor reads. -This documentation describes the file formats parsed by the extractor, based on observable data behavior, for interoperability and re-implementation. +## Common data types -**DISPEL®** is a registered trademark. This documentation is **not affiliated with, endorsed by, or sponsored by** the trademark owner. +The tool reads all integers as little-endian values. -This document details the binary formats parsed by the extractor. This information is critical for re-implementation or generating parsers. +Colors use a 16-bit RGB 565 value: -## Common Data Types -- **LittleEndian Integers**: Checking `read_i32::()` or `read_i16` confirms data is stored in Little Endian. -- **Color Format (RGB 565)**: - - 16-bit integer. - - **Red**: 5 bits (Mask `0xF800` >> 11) - - **Green**: 6 bits (Mask `0x07E0` >> 5) - - **Blue**: 5 bits (Mask `0x001F`) - - Expansion to 8-bit: `val << 3` (for R/B) or `val << 2` (for G). +- Red takes 5 bits from mask `0xF800` after a shift of 11 places. +- Green takes 6 bits from mask `0x07E0` after a shift of 5 places. +- Blue takes 5 bits from mask `0x001F`. +- Expansion to 8-bit values uses `val << 3` for red and blue, and `val << 2` for green. ---- +## 1. SNF audio (`snf.rs`) -## 1. SNF Audio (`snf.rs`) +The tool reads SNF files as PCM data with a 22-byte header. -The SNF format appears to be a raw PCM container very similar to WAV but with a custom header. +### Header structure -### Header Structure | Byte Offset | Type | Description | |---|---|---| | 0 | i32 | Data Size | @@ -33,121 +28,107 @@ The SNF format appears to be a raw PCM container very similar to WAV but with a | 12 | i32 | Byte Rate | | 16 | i16 | Block Align | | 18 | i16 | Bits Per Sample | -| 20 | i16 | *Unknown / Padding* (skipped) | +| 20 | i16 | Unknown value that the tool skips | ### Conversion -The extractor writes a standard RIFF WAVE header followed by the raw PCM data read from the SNF file. ---- +The tool writes a standard RIFF WAVE header. It then appends the raw PCM data from the SNF file. -## 2. Map Format (`map.rs`) +## 2. Map format (`map.rs`) -Map files are complex binary structures containing multiple blocks of data. +Map files hold several blocks of binary data. + +### 2.1 Header and model -### 2.1 Header / Model - `Width` (i32) - `Height` (i32) -- Derived "Tiled Map Size": `Width * 25 - 1` by `Height * 25 - 1` (implying 25x25 chunks). +- The tool derives the tiled map size as `Width * 25 - 1` by `Height * 25 - 1`. The formula uses 25x25 chunks. + +### 2.2 Data blocks + +The tool reads these blocks in sequence. -### 2.2 Data Blocks -The file is read sequentially. +#### Block 1 -#### Block 1 (Unknown) - `Multiplier` (i32) - `Size` (i32) -- Skips 8 bytes. -- Skips `Multiplier * Size * 4` bytes. +- The tool skips 8 bytes. +- The tool skips `Multiplier * Size * 4` bytes. + +#### Block 2 -#### Block 2 (Unknown) - `Size` (i32) -- Skips `Size * 2` bytes. +- The tool skips `Size * 2` bytes. + +#### Internal sprites block -#### Internal Sprites Block - `Count` (i32) -- For each sprite: - - `Image Stamp` (i32): Determines a static offset (1904 if 6, 2996 if 9). - - Skip 264 bytes. - - **Sequence Info**: Parsed (see Sprite Format). - - Seek past image data based on the static offset logic. +- For each sprite, the tool reads `Image Stamp` (i32). It uses a static offset of 1904 for stamp 6 and 2996 for stamp 9. +- The tool skips 264 bytes. +- The tool parses the sequence information (see Sprite format). +- The tool seeks past the image data using that static offset. + +#### Sprite position block -#### Sprite Position Block - `Count` (i32) -- For each entry: - - `Sprite ID` (i32): Index into internal sprites. - - Skip 2x i32. - - Skip 2x i32 (bottom-right coords?). - - `Sprite X` (i32) - - `Sprite Y` (i32) - - Skip calculated based on frames in the referenced sprite sequence. - -#### Tiled Objects Block +- `Sprite ID` (i32) indexes the internal sprites. +- The tool skips two `i32` values, then two more `i32` values. +- `Sprite X` (i32) +- `Sprite Y` (i32) +- The tool skips a length based on the frame count in the referenced sprite sequence. + +#### Tiled objects block + - `Count` (i32) - `Number1` (i32) -- For each object: - - Skip 264 bytes. - - Read 4x i32 (s8, s0_1, s1, s0_2) - - Read 4x i32 (v1..v4) - - `X`, `Y` (i32) - - Read 2x i32 (v7, v8) - - `C1`, `C2`, `C3` (i32) - - Read `C3` count of `i16` (IDs). - - Skip 84 bytes. - - Skip `(C1 + C2 + C3) * 4` bytes. -- **Correction Logic**: Contains a specific seek-back-and-scan logic to handle a variable length footer or padding (looking for byte `1`). - -### 2.3 Tile & Event Layers -The file reading jumps to the END of the file and seeks backwards to find tile data. - -- **Seek**: `-(TiledHeight * TiledWidth * 4 * 3)` from End. -- **Event Block**: `TiledWidth * TiledHeight` entries of: - - `Event ID` (i16) - - `Unknown` (i16) -- **GTL (Ground Tile Layer) / Collision**: `TiledWidth * TiledHeight` entries of: - - `Value` (i32) - - `ID` = `Value >> 10` - - `Collision` = `(Value & 1) == 1` -- **BTL (Building/Roof Tile Layer)**: `TiledWidth * TiledHeight` entries of: - - `Tile ID` (i16) - - `Flag` (i16) - ---- - -## 3. Tileset Format (`tileset.rs`) - -Simple contiguous array of raw pixels. -- **File Length** is used to determine tile count. -- **Tile Size**: 32x32 pixels. -- **Pixel Format**: u16 (RGB 565). -- Loop until EOF: Read 32*32*2 bytes. - -### Isometry Mask -The code procedurally generates a diamond-shape mask (`decode::tile_mask()` in `src/decode.rs`) to render the 32x32 square tile into a 62x32 isometric projection. - ---- - -## 4. Sprite / Animation Format (`sprite.rs`) - -Starts at byte **268**. - -### Sequence Loop -- Checks if file has enough bytes left. -- **Validation**: Reads 15x `i32`. Checks specific values to determine if it's a valid sequence header (e.g., `ints[11] * ints[12] == ints[13]`). -- If valid: - - Read `Stamp` (i32). - - If Stamp == 0, read `FrameCount` (i32). - - **Frame Loop**: - - Skip 24 bytes (6 * 4). - - Read `Origin X`, `Origin Y`, `Width`, `Height` (i32). - - Read `Size` (u32). - - Actual Data Size = `Size * 2`. - - **Image Data**: u16 pixels (RGB 565). `Width * Height`. - -## Legal Compliance - -This documentation: -- Describes **file format specifications only** -- Does **not** distribute any proprietary algorithms or game content -- Focuses on **technical organization and data structures** -- Provides information for **independent interoperability research based on observable behavior** only, without circumvention of technological protection measures -- Maintains **nominative use** for trademark references -- **No copyrighted content** is reproduced or distributed +- For each object, the tool skips 264 bytes. +- It reads four `i32` values: `s8`, `s0_1`, `s1` and `s0_2`. +- It reads four `i32` values: `v1` through `v4`. +- It reads `X` and `Y` (i32). +- It reads two `i32` values: `v7` and `v8`. +- It reads `C1`, `C2` and `C3` (i32). +- It reads `C3` values of type `i16` as IDs. +- It skips 84 bytes. +- It skips `(C1 + C2 + C3) * 4` bytes. +- The tool seeks back and scans for byte `1` to handle a variable-length footer or padding. + +### 2.3 Tile and event layers + +The tool jumps to the end of the file. It seeks backwards to find the tile data. + +- Seek: `-(TiledHeight * TiledWidth * 4 * 3)` from End. +- Event block: `TiledWidth * TiledHeight` entries, each with `Event ID` (i16) and `Unknown` (i16). +- GTL (ground tile layer) and collision: `TiledWidth * TiledHeight` entries, each with `Value` (i32). The tool computes `ID = Value >> 10` and `Collision = (Value & 1) == 1`. +- BTL (building and roof tile layer): `TiledWidth * TiledHeight` entries, each with `Tile ID` (i16) and `Flag` (i16). + +## 3. Tileset format (`tileset.rs`) + +A tileset file holds a contiguous array of raw pixels. + +- The file length determines the tile count. +- Each tile is 32x32 pixels. +- Each pixel is a u16 RGB 565 value. +- The tool reads 32*32*2 bytes at a time until it reaches EOF. + +### Isometry mask + +The tool generates a diamond-shape mask with `decode::tile_mask()` in `src/decode.rs`. The mask draws the 32x32 square tile as a 62x32 isometric projection. + +## 4. Sprite and animation format (`sprite.rs`) + +Sprite data starts at byte 268. + +### Sequence loop + +- The tool checks that enough bytes remain in the file. +- The tool reads 15 `i32` values. It treats the header as a valid sequence when `ints[11] * ints[12] == ints[13]`. +- For a valid sequence, the tool reads `Stamp` (i32). +- When `Stamp` is 0, the tool reads `FrameCount` (i32). + +### Frame loop + +- The tool skips 24 bytes (6 * 4). +- It reads `Origin X`, `Origin Y`, `Width` and `Height` (i32). +- It reads `Size` (u32). +- The actual data size is `Size * 2`. +- The tool reads `Width * Height` pixels of type u16 in RGB 565 format. diff --git a/docs/iced-fork-config.md b/docs/iced-fork-config.md index 57a8d906..b7cc087d 100644 --- a/docs/iced-fork-config.md +++ b/docs/iced-fork-config.md @@ -1,14 +1,10 @@ -# Forked-Iced Configuration (single pin set & feature matrix) +# Forked Iced configuration: single pin set and feature matrix -The GUI stack builds against a git fork of Iced, `dimspell/iced`. This document -is the authoritative description of how that fork is pinned, which features -each workspace crate enables, and how headless tests select their renderer. -`scripts/check-iced-config.sh` (also `make check_iced_config`) enforces the -invariants below and runs in CI. +The GUI builds against a git fork of Iced, `dimspell/iced`. This document records the pins, the features each crate enables and the renderer that headless tests select. `scripts/check-iced-config.sh` (also `make check_iced_config`) enforces these rules in CI. -## 1. Single pin set +## Single pin set -All iced-family git dependencies must resolve to the **same** commit: +All iced-family git dependencies must resolve to the same commit: | Dependency | Source | Rev | |---|---|---| @@ -17,66 +13,37 @@ All iced-family git dependencies must resolve to the **same** commit: | `iced_renderer` (hexedit **dev**-dep) | `https://github.com/dimspell/iced` | `c0ffdd8e7352df9283496f3db334731c00ef6d0d` | | `winit` (`[patch.crates-io]`) | `https://github.com/iced-rs/winit.git` | `05b8ff17a06562f0a10bb46e6eaacbe2a95cb5ed` | -Historically `hexedit`'s `iced_renderer` dev-dependency was pinned to a -different commit (`48fb8fe…`). That produced two parallel copies of every -iced crate in `Cargo.lock` with incompatible internal types. It is now aligned -to the workspace pin; `Cargo.lock` contains a single `iced_renderer` entry. -**Do not reintroduce a second iced rev** — enable the needed feature through -the workspace pin instead. +hexedit's `iced_renderer` dev-dependency uses the same commit as the workspace. A different commit (`48fb8fe...`) gave `Cargo.lock` two copies of each iced crate. The copies had incompatible internal types. `Cargo.lock` now has one `iced_renderer` entry. Do not add a second iced rev. Enable any needed feature through the workspace pin. -## 2. Feature matrix +## Feature matrix -Cargo features are additive and unify across the dependency graph. The table -lists the features each workspace crate turns on directly (everything uses -`default-features = false` on `iced`): +Cargo features are additive and unify across the dependency graph. The table lists the features each workspace crate turns on directly. Every crate sets `default-features = false` on `iced`. | Crate | `iced` features (direct) | Own features | Forces on `gui-widgets` | |---|---|---|---| -| `gui-widgets` | `advanced`, `thread-pool`, `wgpu` | `default = [accessibility]`, `accessibility = [iced/accessibility]` | — | -| `hexedit` | `advanced`, `tokio`, `wgpu`, `canvas`, `lazy` | — | `accessibility` | +| `gui-widgets` | `advanced`, `thread-pool`, `wgpu` | `default = [accessibility]`, `accessibility = [iced/accessibility]` | none | +| `hexedit` | `advanced`, `tokio`, `wgpu`, `canvas`, `lazy` | none | `accessibility` | | `dispel-gui` | `tokio`, `wgpu`, `image`, `canvas`, `advanced`, `lazy`, `x11`, `wayland`, `accessibility` | `default = []`, `iced_test`, `debug` | `accessibility` | -| `dispel-extractor` (root) | — (no iced dependency) | — | — | +| `dispel-extractor` (root) | none (no iced dependency) | none | none | Notes: -- **Accessibility is default-on and force-enabled by both GUI consumers**, so - the shared `table_widget` compiles with one shape workspace-wide. Turning it - off in one crate only would not work: feature unification would turn it back - on for everyone, producing unexpected build differences. Only `table_widget` - implements full accesskit nodes today; the other custom widgets use iced's - no-op defaults. -- `dispel-gui/debug = ["iced/hot"]` enables the fork's experimental hot - reload. `cargo test --workspace --all-features` therefore compiles hot - reload *and* `iced_test` together. -- `dispel-gui/iced_test = ["dep:iced_test", "iced/tiny-skia"]`, hexedit's - `iced_renderer` dev-dep (`features = ["tiny-skia"]`) and the identical - `gui-widgets` dev-dep all make the software renderer available; any one path - is enough for feature unification, but each is kept so the crate's tests work - standalone. -- `gui-widgets` also enables `iced_test/accessibility` as a dev-dependency so - its widget tests can inspect accessibility trees and dispatch accesskit - actions. It matches the crate's default-on `accessibility` feature. - -## 3. Test backend - -`iced_test` reads the **`ICED_TEST_BACKEND`** environment variable at runtime -(iced fork `test/src/simulator.rs` and `test/src/emulator.rs`). The value -`software` selects the `tiny-skia` renderer; an unset value falls back to the -`wgpu` renderer, which needs a GPU/window server and fails in headless CI. - -Consequences: - -- Every iced UI-simulation test target sets `ICED_TEST_BACKEND=software` in the - Makefile (`iced_test`, `hexedit_test`). Use those targets, or export the - variable yourself when running `cargo test -p dispel-gui -p hexedit -p - gui-widgets`. -- `tiny-skia` must also be compiled in (see the feature matrix above); the env - variable alone is not enough. -- `cargo test --workspace --all-features` enables `iced_test` and hot reload - together. It compiles, but GPU-less environments must still export - `ICED_TEST_BACKEND=software` for the UI-simulation tests to run. - -## 4. Validation +- Accessibility is on by default, and both GUI consumers force it on. The shared `table_widget` then compiles with one shape across the workspace. A single crate cannot turn accessibility off. Feature unification turns it back on for all crates and changes the build. Only `table_widget` implements full accesskit nodes. The other custom widgets use iced's no-op defaults. +- `dispel-gui/debug = ["iced/hot"]` enables the fork's experimental hot reload. So `cargo test --workspace --all-features` compiles hot reload and `iced_test` together. +- Three paths make the software renderer available. The first is `dispel-gui/iced_test = ["dep:iced_test", "iced/tiny-skia"]`. The second is hexedit's `iced_renderer` dev-dep (`features = ["tiny-skia"]`). The third is the same `gui-widgets` dev-dep. One path is enough for feature unification. Each path stays so the crate's tests work on their own. +- `gui-widgets` also enables `iced_test/accessibility` as a dev-dependency. Its widget tests can inspect accessibility trees and dispatch accesskit actions. This matches the crate's default-on `accessibility` feature. + +## Test backend + +`iced_test` reads the `ICED_TEST_BACKEND` environment variable at runtime. The fork handles this in `test/src/simulator.rs` and `test/src/emulator.rs`. The value `software` selects the `tiny-skia` renderer. An unset value falls back to the `wgpu` renderer. That renderer needs a GPU and a window server. It fails in headless CI. + +Rules: + +- Every iced UI-simulation test target sets `ICED_TEST_BACKEND=software` in the Makefile (`iced_test`, `hexedit_test`). Use those targets, or export the variable yourself when you run `cargo test -p dispel-gui -p hexedit -p gui-widgets`. +- You must also compile `tiny-skia` (see the feature matrix above). The env variable alone is not enough. +- `cargo test --workspace --all-features` enables `iced_test` and hot reload together. The command compiles. On a machine with no GPU, export `ICED_TEST_BACKEND=software` before the UI-simulation tests. + +## Validation Run locally: @@ -84,9 +51,4 @@ Run locally: make check_iced_config # or: bash scripts/check-iced-config.sh ``` -The script checks: one iced rev in all manifests and in `Cargo.lock`; the -expected winit patch rev; the `ICED_TEST_BACKEND=software` settings in the -Makefile; `tiny-skia` compiled in on both iced_test paths; and consistent -accessibility configuration. It runs as a CI step in both `pr.yml` (verify job) -and `test.yml` (master push), in addition to the existing build/test/clippy -steps — it does not replace or weaken them. +The script checks for one iced rev in all manifests and in `Cargo.lock`. It checks the expected winit patch rev, the `ICED_TEST_BACKEND=software` settings in the Makefile, `tiny-skia` on both `iced_test` paths, and consistent accessibility configuration. It runs as a CI step in both `pr.yml` (the `verify` job) and `test.yml` (master push). Those steps do not replace the build, test or clippy steps. diff --git a/docs/overview.md b/docs/overview.md index 9dedebca..0f8ff860 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -1,41 +1,35 @@ -# Dispel Extractor Overview +# Dispel Extractor overview -A modding toolkit for **DISPEL®** game files. Written in Rust as a 6-crate Cargo workspace, this project provides a CLI for extraction/patching, a desktop GUI for editing game data, and a hex editor. All edits are persisted directly to game files — no intermediate database. +This toolkit reads and writes DISPEL® game files. It is a Rust workspace with six crates. The workspace has a CLI for extraction and patching, a desktop GUI for editing game data and a hex editor. The tools write edits into the game files. They do not keep a separate database. -**Not affiliated with, endorsed by, or sponsored by the trademark owner.** +## Project structure ---- - -## Project Structure - -The workspace consists of six crates: +The workspace has six crates: | Crate | Type | Role | |---|---|---| | `dispel-extractor` (root) | lib + bin | Core library (`dispel_core`) + CLI binary | -| `dispel-encodings` | lib | Single source of truth for text-encoding spellings/labels | -| `dispel-gui` | bin | Iced 0.15 desktop GUI | +| `dispel-encodings` | lib | Single source of truth for text-encoding spellings and labels | +| `dispel-gui` | bin | Iced 0.15 desktop GUI with 46 editor types, built on the `dimspell/iced` fork pinned at rev `c0ffdd8e7352df9283496f3db334731c00ef6d0d` | | `dispel-macros` | proc-macro | 7 derive macros (Extractor, Localizable, RecordPatcher, etc.) | | `gui-widgets` | lib | Reusable Iced widgets (ContextMenu, modal, ParagraphCache) | | `hexedit` | lib + bin | Hex editor | ### Key source directories (`src/`) -- **`src/main.rs`** — CLI entry point via `clap` -- **`src/cli.rs`** — Subcommand definitions -- **`src/database.rs`** — SQLite schema bootstrap -- **`src/localization.rs`** — Text export/import for translations -- **`src/references/`** — 51 game data file parsers (`.db`, `.ini`, `.ref`) -- **`src/map/`** — `.map` parser + isometric renderer (tiles, sprites, events) -- **`src/modding/`** — Mod authoring pipeline (apply, patch, package, resolve conflicts) -- **`src/commands/`** — CLI command implementations -- **`src/queries/`** — 118 SQL files (59 schema DDL + 59 INSERTs) -- **`src/sprite.rs`** — `.spr` sprite/animation parser -- **`src/snf.rs`** — `.snf` audio parser +- `src/main.rs`: CLI entry point with `clap` +- `src/cli.rs`: subcommand definitions +- `src/database.rs`: SQLite schema bootstrap +- `src/localization.rs`: text export and import for translations +- `src/references/`: 51 game data file parsers (`.db`, `.ini`, `.ref`) +- `src/map/`: `.map` parser and isometric renderer for tiles, sprites and events +- `src/modding/`: mod authoring pipeline (apply, patch, package, resolve conflicts) +- `src/commands/`: CLI command implementations +- `src/queries/`: 118 SQL files (59 schema DDL + 59 INSERTs) +- `src/sprite.rs`: `.spr` sprite and animation parser +- `src/snf.rs`: `.snf` audio parser ---- - -## CLI Commands +## CLI commands ``` # Extract game data to JSON @@ -44,13 +38,13 @@ cargo run -- extract -i "Monster.db" # Patch game files from JSON cargo run -- patch -i changes.json -t "Monster.db" --in-place -# Validate JSON against expected schema +# Validate JSON against an expected schema cargo run -- validate -i weapons.json --type weapons # List supported file types cargo run -- list -# Generate JSON schema for a file type +# Generate a JSON schema for a file type cargo run -- schema --type weapons # Generate a minimal JSON template @@ -59,8 +53,9 @@ cargo run -- template --type weapons --pretty # Extract sprites or animations cargo run -- sprite "M_BODY1.SPR" --mode sprite -# Convert SNF audio to WAV -cargo run -- sound --input sample.snf --output output.wav +# Convert SNF audio to WAV and WAV audio to SNF +cargo run -- sound to-wav sample.snf output.wav +cargo run -- sound from-wav output.wav sample.snf # Map operations (tiles, atlas, render) cargo run -- map tiles "cat1.gtl" --output out/tiles/ @@ -70,18 +65,16 @@ cargo run -- map render --map cat1.map --btl cat1.btl --gtl cat1.gtl --output ma # SQLite database import cargo run -- database import "path/to/Dispel/" db.sqlite -# Mod packaging -cargo run -- mod-pack ... +# Batch-export event scripts to JSON +cargo run -- mod-pack --game-path "path/to/Dispel" --output mod-pack/ ``` Full subcommand reference: `cargo run -- --help`. ---- - ## Workflow -1. **Parsing** — Binary/INI formats are read using `byteorder` and encoding-aware text readers (`WINDOWS-1250` or `EUC-KR`). -2. **Processing** — Raw data (RGB 565 colors, PCM audio, tile indexes) is converted to usable representations. -3. **Editing** — The GUI provides 44 editor types for viewing and modifying records, plus a fallback for unknown file types, with undo/redo and mod recording. -4. **Modding** — Changes can be packaged into `.dispel-mod` archives for distribution, with conflict detection and binary patching. -5. **Output** — Images (PNG), audio (WAV), JSON (extraction), or direct in-place file patching. +1. Parsing: The tools read binary and INI files with `byteorder` and encoding-aware text readers. The readers use `WINDOWS-1250` or `EUC-KR`. +2. Conversion: The tools convert RGB 565 colors, PCM audio and tile indexes to other representations. +3. GUI editing: The GUI has 46 editor types and a fallback for unknown file types. It supports undo, redo and mod recording. +4. Mod packaging: The CLI `mod-pack` command exports event scripts to JSON. The GUI mod packager writes a zip with `manifest.json`, `changes.json`, `patches/` and `files/`. It stores work in `.dispel-mods`. +5. Output: The tools write PNG images, WAV audio and extracted JSON. They can also patch files in place. diff --git a/docs/rendering.md b/docs/rendering.md index ec126c2b..a82fc465 100644 --- a/docs/rendering.md +++ b/docs/rendering.md @@ -1,31 +1,32 @@ -# Rendering Logic +# Rendering logic -## Map Rendering (`src/map/`) -The tool can render a full map into a single image (`render_map`). +## Map rendering (`src/map/`) -### Isometric Projection -The map logic handles conversion between "Map Coords" (grid) and "Image Coords" (pixel). +The tool can render a full map into one image with `render_map`. -- **Tile Dimensions**: 62x32 pixels. -- **Formula**: - ```rust - start_x = (x + y) * 32; // TILE_HORIZONTAL_OFFSET_HALF - start_y = (-x + y) * 16 + (diagonal / 2 * 16); // TILE_HEIGHT_HALF - ``` +### Isometric projection + +The map code converts map coordinates on a grid to image coordinates in pixels. + +- Tile dimensions: 62x32 pixels. +- The tool uses this formula: + +```rust +start_x = (x + y) * 32; // TILE_HORIZONTAL_OFFSET_HALF +start_y = (-x + y) * 16 + (diagonal / 2 * 16); // TILE_HEIGHT_HALF +``` ### Layers -1. **Base (Ground)**: Iterates diagonally. Renders `gtl_tiles`. - - Applies color mixing for Event tiles (Blue tint) or Collision tiles (optional). - - Uses a mask to draw the diamond tile shape. -2. **Objects**: Sprites and Tiled Objects. - - Sorted by `ground_y` coordinate to handle depth/occlusion correctly (painter's algorithm). - - **Sprites**: Rendered from `internal_sprites` extracted from the map file. - - **Tiled Objects**: Collections of tiles designated by `tiled_infos` (multi-tile structures). -3. **Roofs (BTL)**: Renders `btl_tiles`. - -## Sprite Rendering (`src/sprite.rs`) -- **Transparency**: Pixels with value `0` are skipped/transparent. -- **Positioning**: Uses `origin_x`, `origin_y` relative to a calculated bounding box for animations. - -## Tile Rendering (`src/map/tileset.rs`) -- **Masking**: Since the source data is a 32x32 square but the output is isometric, `decode::tile_mask()` (in `src/decode.rs`, shared with the GUI) generates an offset array (`mask[0]` for start x, `mask[1]` for width) per line `y` to draw a diamond shape. + +1. Base ground: The tool iterates diagonally and renders `gtl_tiles`. It applies a blue tint to event tiles and an optional tint to collision tiles. It uses a mask to draw the diamond tile shape. +2. Objects: The tool renders sprites and tiled objects. It sorts them by `ground_y` and draws them in that order. This order follows the painter's algorithm. Sprites come from `internal_sprites` in the map file. Tiled objects group tiles through `tiled_infos`. +3. Roofs: The tool renders `btl_tiles`. + +## Sprite rendering (`src/sprite.rs`) + +- The tool skips pixels with value `0`. +- Sprite position uses `origin_x` and `origin_y` relative to a calculated bounding box for animations. + +## Tile rendering (`src/map/tileset.rs`) + +`decode::tile_mask()` in `src/decode.rs` generates an offset array for each line `y`. The GUI also uses this mask. `mask[0]` gives the start x position. `mask[1]` gives the width. The array draws the diamond shape from the 32x32 source square. diff --git a/gui-widgets/src/sweeten/README.md b/gui-widgets/src/sweeten/README.md index 33f5b705..1463ed6f 100644 --- a/gui-widgets/src/sweeten/README.md +++ b/gui-widgets/src/sweeten/README.md @@ -1,3 +1,3 @@ # sweeten -The code from this module comes from the https://github.com/airstrike/sweeten repository. +The code in this module comes from https://github.com/airstrike/sweeten. From cf17570dbdf95a0b6f65b08a15c9eadd1f50a137 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:35:32 +0100 Subject: [PATCH 03/72] docs: rewrite hexedit README in plain English and fix version --- README.md | 2 +- hexedit/README.md | 769 ++++++++++++++++++++++------------------------ 2 files changed, 370 insertions(+), 401 deletions(-) diff --git a/README.md b/README.md index b6992d5c..dfc95c9b 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ The source code is licensed under the MIT License (LICENSE). Game content is not ## What's in this repository -This Cargo workspace has six crates. The workspace uses Rust 2024 and version `0.9.3`. +This Cargo workspace has six crates. The workspace uses Rust 2024 and version `0.9.5`. | Crate | Type | Role | | ------------------------- | ---------- | --------------------------------------------------------------- | diff --git a/hexedit/README.md b/hexedit/README.md index ebc1f549..71cd3322 100644 --- a/hexedit/README.md +++ b/hexedit/README.md @@ -1,120 +1,96 @@ -# hexedit — A standalone, embeddable hex editor widget for Iced +# hexedit: a standalone, embeddable hex editor widget for Iced -**hexedit** is a full-featured hex editor library built on [Iced 0.15](https://iced.rs/). -It ships as a reusable Rust library (`hexedit` crate) and one standalone binary -(`hexedit`). - -Designed for the [Dispel RPG modding toolkit](https://github.com/piotr/dispel-extractor), -it is embeddable inside any Iced application and powers the hex-editing tab in `dispel-gui`. - ---- +hexedit is a hex editor library built on [Iced 0.15](https://iced.rs/). It ships as a reusable Rust library, the `hexedit` crate, and one binary, `hexedit`. The [Dispel RPG modding toolkit](https://github.com/piotr/dispel-extractor) uses the library for the hex editing tab in `dispel-gui`. You can also embed the library in any Iced application. ## Table of Contents 1. [Features](#features) -2. [Architecture Overview](#architecture-overview) -3. [Domain Layer (Pure Data Model)](#domain-layer-pure-data-model) -4. [UI Layer (Iced-specific)](#ui-layer-iced-specific) -5. [HexEditorState (Aggregate State)](#hexeditorstate-aggregate-state) -6. [HexEditorConfig (Host Injection)](#hexeditorconfig-host-injection) -7. [HexEditorMessage (Enum Reference)](#hexeditormessage-enum-reference) -8. [HexMatrix Custom Widget](#hexmatrix-custom-widget) -9. [Coloring System](#coloring-system) -10. [Inspector Decoder System](#inspector-decoder-system) -11. [Pattern System](#pattern-system) -12. [Writing / Inline Editing](#writing--inline-editing) -13. [Search & Navigation](#search--navigation) -14. [Write Modes & Text Encoding](#write-modes--text-encoding) -15. [Byte Statistics & Entropy Panel](#byte-statistics--entropy-panel) -16. [Pane Grid Layout](#pane-grid-layout) +2. [Architecture overview](#architecture-overview) +3. [Domain layer (pure data model)](#domain-layer-pure-data-model) +4. [UI layer (Iced-specific)](#ui-layer-iced-specific) +5. [HexEditorState (aggregate state)](#hexeditorstate-aggregate-state) +6. [HexEditorConfig (host injection)](#hexeditorconfig-host-injection) +7. [HexEditorMessage (enum reference)](#hexeditormessage-enum-reference) +8. [HexMatrix custom widget](#hexmatrix-custom-widget) +9. [Cell colours](#the-coloring-system) +10. [Inspector decoder system](#inspector-decoder-system) +11. [Pattern system](#pattern-system) +12. [Inline editing](#inline-editing-and-writing) +13. [Search and navigation](#search-and-navigation) +14. [Write modes and text encoding](#write-modes-and-text-encoding) +15. [Byte statistics and entropy panel](#byte-statistics-and-entropy-panel) +16. [Pane grid layout](#pane-grid-layout) 17. [Minimap](#minimap) -18. [Theme System](#theme-system) -19. [Test Structure](#test-structure) +18. [Theme system](#theme-system) +19. [Test structure](#test-structure) 20. [Usage (library)](#usage-library) 21. [Usage (standalone binaries)](#usage-standalone-binaries) 22. [Build](#build) 23. [Feature flags](#feature-flags) 24. [Keybindings](#keybindings) 25. [Dependencies](#dependencies) -26. [LLM Guidance — Conventions & Invariants](#llm-guidance--conventions--invariants) - ---- +26. [LLM guidance: conventions and invariants](#llm-guidance-conventions-and-invariants) ## Features ### Core editing -- **Virtualized hex matrix** — Address gutter, hex bytes (grouped 8+8), ASCII column, and - annotation column. Only rows in the viewport are rendered (virtualized scrolling). -- **Inline overwrite editing** — Double-click or `F2` to begin editing a byte; type two hex - digits to auto-commit and advance to the next byte. `Tab`/`Enter` to commit and advance, - `Esc` to cancel. -- **Selection** — Click, drag, or Shift+arrow to select byte ranges. Arrow keys, `Home`/`End`, - `Page Up`/`Page Down`, `Ctrl+Home`/`Ctrl+End` for keyboard navigation. -- **Copy / Paste** — `Ctrl+C` copies the selected range as hex text (`DE AD BE EF`); - `Ctrl+V` pastes hex text from the clipboard back into the buffer. -- **Write bytes** — `WriteBytes` message for programmatic inspector edits and other - host-driven changes. - -### Search & navigation -- **Search** (`Ctrl+F`) — Hex byte-sequence search (`DE AD BE EF` or `DEADBEEF`) and - ASCII substring search. Next/prev match navigation with match highlighting in the matrix. -- **Goto** (`Ctrl+G`) — Navigate to a specific address. Accepts hex (`0xFF`, `FF`), - decimal (`255`), and relative offsets (`+10`, `-5`). -- **Bytes-per-row toggle** — Set any row width from 1 to 64 bytes: preset buttons - (8/16/32) plus a custom numeric input in the settings modal. + +- **Virtualized hex matrix:** The address gutter, hex bytes grouped 8+8, the ASCII column and the annotation column appear on screen. The widget draws only rows in the viewport. +- **Inline overwrite editing:** Double-click or press `F2` to edit a byte. Type two hex digits to commit the byte and move to the next one. Press `Tab` or `Enter` to commit and advance. Press `Esc` to cancel. +- **Selection:** Click, drag or press Shift with an arrow key to select a byte range. Arrow keys, `Home`, `End`, `Page Up`, `Page Down`, `Ctrl+Home` and `Ctrl+End` move the cursor. +- **Copy and paste:** `Ctrl+C` copies the selected range as hex text (`DE AD BE EF`). `Ctrl+V` pastes hex text from the clipboard into the buffer. +- **Write bytes:** The `WriteBytes` message supports inspector edits and other host changes. + +### Search and navigation + +- **Search (`Ctrl+F`):** The tool finds hex byte sequences (`DE AD BE EF` or `DEADBEEF`) and ASCII substrings. It highlights matches in the matrix. It moves to the next or previous match. +- **Goto (`Ctrl+G`):** The tool moves to an address. The input accepts hex (`0xFF`, `FF`), decimal (`255`) and relative offsets (`+10`, `-5`). +- **Bytes-per-row toggle:** The settings modal sets any row width from 1 to 64 bytes. Preset buttons cover 8, 16 and 32. A custom numeric input accepts other widths. ### Data inspector -- **Built-in decoders** — `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `f32`, `f64`, - ASCII char, UTF-8 char, RGB565 pixel, null-terminated C string, and raw hex dump. -- **Editable values** — All numeric decoders support inline editing via a modal: type a - decimal or `0x`-prefixed hex value and it's written back in the correct endianness. + +- **Built-in decoders:** `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `f32`, `f64`, ASCII char, UTF-8 char, RGB565 pixel, null-terminated C string and raw hex dump. +- **Editable values:** Each numeric decoder has an inline edit modal. Type a decimal value or a `0x` hex value. The tool writes the bytes in the matching endianness. ### Pattern highlighting -- **Named byte ranges** — Select a range, right-click → "Create Pattern" (or `Ctrl+E`). - Patterns are rendered with a distinct background/foreground colour in the matrix. -- **Repeated (zebra) patterns** — Create multi-instance repeating patterns with automatic - annotation labels (e.g. `Monster[0]`, `Monster[1]`...). -- **Pattern groups** — Organize related patterns into collapsible groups with rename, colour - cycling, and bulk delete. -- **Annotations** — Text annotations per pattern shown in the annotation column to the right - of the ASCII area. Annotations of patterns under the cursor are highlighted. -- **Import / Export** — Patterns and groups can be exported to and imported from a - JSON file. + +- **Named byte ranges:** Select a range, right-click and choose `Create Pattern`. You can also press `Ctrl+E`. Patterns use a distinct background and foreground colour in the matrix. +- **Repeated (zebra) patterns:** Create a repeating pattern with several instances. The tool adds annotation labels such as `Monster[0]` and `Monster[1]`. +- **Pattern groups:** Group related patterns. Groups support rename, colour cycling and bulk delete. +- **Annotations:** Each pattern can carry text in the annotation column to the right of the ASCII area. The tool highlights annotations for patterns under the cursor. +- **Import and export:** The tool exports patterns and groups to a JSON file and imports them from a JSON file. ### Visual colouring -- 5 colour schemes via the settings modal: - - **Monochrome** — Single colour for all bytes (the classic hex editor look). - - **Nybble** — 18 colour groups by high nibble (one per nybble + special `0x00`/`0xFF`). - - **Categories** — 6 semantic groups (NULL, whitespace, printable, DEL, control, non-ASCII). - - **Rainbow** — Continuous hue gradient across the full `0x00–0xFF` range. - - **Heatmap** — Cold-to-hot heatmap (blue → cyan → green → yellow → red). -- **Dim nulls** — Optionally render `0x00` bytes in a dim colour regardless of the active scheme. -- **Dirty vs vanilla-diff colouring** — Bytes dirtied this session use one colour; bytes that - differ cumulatively from the on-disk snapshot use another. - -### Layout & panels -- **Pane grid** — Halloy-style movable, splittable, resizable panels. The default layout is a - vertical split: hex matrix on the left, data inspector on the right. The pattern list opens - as an additional split pane. -- **Toolbar** — Save button, Goto, Patterns toggle, text export, settings, bytes-per-row toggle, - and status message. -- **Minimap** — Overview strip showing file structure at a glance, with cursor position marker - and dirty/diff pixel indicators. - -### Save & integration -- **Host-configurable save** — The host app provides a `SavePort` callback, a save label, - and a `can_save` flag. The editor surfaces these in the toolbar. -- **Dirty tracking** — `BufferProvider` tracks which addresses have been modified since load. -- **Text export** — Export the file as a formatted hex dump text file (configurable: address - gutter, decimal/hex addresses, ASCII column). + +The settings modal offers five colour schemes: + +- **Monochrome:** One colour for all bytes. +- **Nybble:** 18 colour groups by high nibble, one per nybble plus special `0x00` and `0xFF`. +- **Categories:** Six semantic groups, NULL, whitespace, printable, DEL, control and non-ASCII. +- **Rainbow:** A continuous hue gradient across the full `0x00` to `0xFF` range. +- **Heatmap:** Cold to hot, blue, cyan, green, yellow and red. + +- **Dim nulls:** The tool can draw `0x00` bytes in a dim colour under any scheme. +- **Dirty and vanilla diff colouring:** Bytes changed in this session use one colour. Bytes that differ from the on-disk snapshot use another. + +### Layout and panels + +- **Pane grid:** Movable, splittable, resizable panels follow the Halloy style. The default layout splits the hex matrix on the left from the inspector on the right. The pattern list opens as another split pane. +- **Toolbar:** The toolbar holds Save, Goto, Patterns toggle, text export, settings, bytes-per-row toggle and the status message. +- **Minimap:** An overview strip shows file structure, the cursor position marker and dirty or diff pixels. + +### Save and integration + +- **Host-configurable save:** The host app supplies a `SavePort` callback, a save label and a `can_save` flag. The editor shows them in the toolbar. +- **Dirty tracking:** `BufferProvider` tracks addresses that changed since load. +- **Text export:** The tool exports a formatted hex dump text file. The address gutter, decimal or hex addresses and the ASCII column are configurable. ### File support -- Library: `hexedit::HexEditorState::load_from_path(&path)` loads any file into memory. -- Binaries: Open files via command-line argument (`hexedit path/to/file.bin`) or file dialog. ---- +- **Library:** `hexedit::HexEditorState::load_from_path(&path)` loads any file into memory. +- **Binaries:** Open a file with a command-line argument (`hexedit path/to/file.bin`) or a file dialog. -## Architecture Overview +## Architecture overview ``` hexedit/ @@ -171,88 +147,95 @@ hexedit/ └── Cargo.toml ``` -**Design principle:** `domain/` is pure Rust — no Iced types, no widget dependencies. -`ui/` contains all Iced-specific code. This lets the data model be tested and reused -without a running UI. +The `domain/` directory holds pure Rust data types. It imports no Iced widget types. The `ui/` directory holds all Iced code. This split lets you test and reuse the data model without a UI. + +## Domain layer (pure data model) ---- +Every file in `src/domain/` is free of Iced widget types. Unit tests cover them without a running UI. -## Domain Layer (Pure Data Model) +### `provider.rs`: Byte source abstraction -All files in `src/domain/` are free of Iced widget types. They can be unit-tested -without a running UI. +- **`HexProvider` trait** (`read()`, `write()`, `len()`, `is_writable()`): A common interface for byte sources. It lets a vanilla snapshot and the live editing buffer coexist. +- **`BufferProvider`**: An in-memory `Vec` with a `BTreeSet` of dirty addresses. It tracks bytes that changed since load. Key methods: `from_bytes()`, `dirty()`, `dirty_count()`, `clear_dirty()`, `as_slice()`. +- **Rule:** `write()` marks an address dirty only when the new byte differs from the old one. -### `provider.rs` — Byte source abstraction -- **`HexProvider` trait** (`read()`, `write()`, `len()`, `is_writable()`): Abstraction over byte sources so vanilla snapshots and the live editing buffer can coexist. -- **`BufferProvider`**: In-memory `Vec` with a `BTreeSet` of dirty addresses. Tracks which bytes have been modified since load. Key methods: `from_bytes()`, `dirty()`, `dirty_count()`, `clear_dirty()`, `as_slice()`. -- **Rule:** `write()` only marks an address dirty if the new byte differs from the old one. +### `selection.rs`: Cursor and selection model -### `selection.rs` — Cursor & selection model - **`Selection`**: `{ anchor: u64, cursor: u64 }`. The selected range is `min(anchor,cursor)..=max(anchor,cursor)`. Methods: `single()`, `range()`, `start()`, `end()`, `len()`, `is_single()`, `contains()`, `select()`, `extend()`. - **`NavDir` enum**: Left, Right, Up, Down, LineStart, LineEnd, PageUp, PageDown, DocumentStart, DocumentEnd. -- **`nav_target(cursor, dir, bytes_per_row, page_rows, max_addr) -> u64`**: Pure function computing the new cursor after navigation. All edge cases (saturating at 0, clamping to max_addr) are unit-tested. +- **`nav_target(cursor, dir, bytes_per_row, page_rows, max_addr) -> u64`**: A pure function that computes the new cursor. Unit tests cover the edge cases. These include saturation at 0 and clamping to `max_addr`. + +### `pattern.rs`: Pattern highlighting -### `pattern.rs` — Pattern highlighting -- **`Pattern`**: `{ id, start, end, color_idx, group_id, annotation }`. Serializable via serde. -- **`RepeatedPatternGroup`**: `{ id, label, color_idx }`. Groups related patterns together. -- **`RepeatPatternDialog`**: Transient modal state for creating repeated patterns from a selection. -- **`PatternExport`**: Versioned JSON envelope (`{ version, groups, patterns }`) for import/export. -- **`pattern_bg(idx)` / `pattern_fg(idx)`**: Return palette colours (16-colour cyclic palette from `DARK_THEME`). +- **`Pattern`**: `{ id, start, end, color_idx, group_id, annotation }`. Serde serializes it. +- **`RepeatedPatternGroup`**: `{ id, label, color_idx }`. It groups related patterns. +- **`RepeatPatternDialog`**: Transient modal state for repeated patterns created from a selection. +- **`PatternExport`**: A versioned JSON envelope (`{ version, groups, patterns }`) for import and export. +- **`pattern_bg(idx)` / `pattern_fg(idx)`**: Palette colours from the 16-colour cyclic palette in `DARK_THEME`. + +### `search.rs`: Search engine -### `search.rs` — Search engine - **`SearchMode`**: `Hex` or `Ascii`. -- **`SearchState`**: `{ visible, query, mode, results: Vec, query_len, current_match, match_set: BTreeSet }`. The `match_set` is a precomputed O(log n) lookup table for the renderer. -- **`parse_hex_query(s)`**: Parse `"DE AD BE EF"` or `"DEADBEEF"` into `Vec`. Requires even number of hex digits. -- **`SearchMatchProvider`**: Implements `CellColorProvider` for search match highlighting in the matrix. +- **`SearchState`**: `{ visible, query, mode, results: Vec, query_len, current_match, match_set: BTreeSet }`. The `match_set` holds a precomputed O(log n) lookup table for the renderer. +- **`parse_hex_query(s)`**: Parses `"DE AD BE EF"` or `"DEADBEEF"` into `Vec`. The parser needs an even digit count. +- **`SearchMatchProvider`**: Implements `CellColorProvider` for search matches in the matrix. + +### `goto.rs`: Goto address parsing -### `goto.rs` — Goto address parsing - **`GotoState`**: `{ draft, error }`. -- **`parse(cursor, max_addr)`**: Accepts hex (`0xFF`, `FF`), decimal (`255`), relative (`+10`, `-5`). Clamps to `[0, max_addr]`. Pure function, fully unit-tested. +- **`parse(cursor, max_addr)`**: Accepts hex (`0xFF`, `FF`), decimal (`255`) and relative values (`+10`, `-5`). It clamps the result to `[0, max_addr]`. Unit tests cover the function. + +### `editing.rs`: Inline edit state -### `editing.rs` — Inline edit state -- **`EditState`**: `{ addr, draft: String }`. Draft holds 0–2 uppercase hex characters. `push_char()`, `pop_char()`, `is_complete()`, `staged_byte()` (single-digit draft treated as low nibble, e.g., `"A"` → `0x0A`). -- **`InspectorEditState`**: `{ entry_idx, addr, draft, error }`. Modal state for the inspector inline-edit flow. +- **`EditState`**: `{ addr, draft: String }`. The draft holds 0 to 2 uppercase hex characters. Methods: `push_char()`, `pop_char()`, `is_complete()`, `staged_byte()`. A single-digit draft becomes the low nibble, so `"A"` gives `0x0A`. +- **`InspectorEditState`**: `{ entry_idx, addr, draft, error }`. Modal state for inspector inline edits. + +### `write_mode.rs`: Text encoding modes -### `write_mode.rs` — Text encoding modes - **`WriteMode`**: `Hex`, `Ascii`, `Utf8`, `Windows1250`, `EucKr`, `Custom(usize)`. -- **`EncodingEntry`**: `{ label, encoding_name }` for user-added encodings (persisted by host). -- **`encode_text(text, mode, custom) -> Vec`**: Encode a single string character into bytes. Used by the inline text-typing path. -- **`is_text_mode(mode) -> bool`**: `true` for any mode except `Hex`. -- **`COMMON_ENCODINGS`**: Static list of 30+ `(label, encoding_rs_name)` pairs available for custom encoding entries. -- **`remap_write_mode()`**: Re-indexes `WriteMode::Custom(i)` when items are removed from the custom list. +- **`EncodingEntry`**: `{ label, encoding_name }` for user-added encodings. The host persists them. +- **`encode_text(text, mode, custom) -> Vec`**: Converts one string character to bytes. The inline text typing path calls it. +- **`is_text_mode(mode) -> bool`**: Returns `true` for every mode except `Hex`. +- **`COMMON_ENCODINGS`**: A static list of 30+ `(label, encoding_rs_name)` pairs for custom encoding entries. +- **`remap_write_mode()`**: Re-indexes `WriteMode::Custom(i)` when items leave the custom list. + +### `panel.rs`: Pane grid types -### `panel.rs` — Pane grid types - **`HexPanelContent`**: `Matrix`, `Inspector`, `PatternList`, `Statistics`. -- **`HexPanel`**: Wrapper around `HexPanelContent`. -- **`default_pane_grid() -> pane_grid::State`**: Creates the default vertical split (75/25 matrix/inspector). +- **`HexPanel`**: A wrapper around `HexPanelContent`. +- **`default_pane_grid() -> pane_grid::State`**: Creates the default vertical split, 75/25 matrix to inspector. + +### `layout.rs`: Structure overlay registry (future) -### `layout.rs` — Structure overlay registry (future) - **`BinaryLayout` trait**: `layout(bytes) -> Vec`. - **`FieldSpan`**: `{ range, name, ty }`. -- **`LayoutRegistry`**: Extension-keyed lookup table. Empty in v1 — reserved for future auto-derived structure overlays from `dispel_core`'s `#[extractor]` attributes. +- **`LayoutRegistry`**: An extension-keyed lookup table. It is empty in v1. A future version may derive structure overlays from `dispel_core` `#[extractor]` attributes. + +### `byte_stats.rs`: Byte statistics and entropy -### `byte_stats.rs` — Byte statistics & entropy -- **`ByteStatistics`**: Counts, frequencies, min/max, Shannon entropy, structure heuristics. +- **`ByteStatistics`**: Counts, frequencies, min/max, Shannon entropy and structure heuristics. - **`RowEntropyCache`**: Per-row entropy values for the gutter colour band. -- **`compute_statistics(bytes) -> ByteStatistics`**: Full analysis (async, via `Task::perform`). +- **`compute_statistics(bytes) -> ByteStatistics`**: Full analysis. It runs asynchronously through `Task::perform`. - **`compute_row_entropies(bytes, bpr) -> RowEntropyCache`**: Per-row entropy values. -- **`entropy_to_color()`**: Maps entropy value to a colour for the gutter band. -- **`StructureHeuristic`**: Detects uniform runs, high/low entropy patterns, mixed content. +- **`entropy_to_color()`**: Maps an entropy value to a colour for the gutter band. +- **`StructureHeuristic`**: Detects uniform runs, high and low entropy patterns and mixed content. + +### `vanilla_diff.rs`: Change tracking -### `vanilla_diff.rs` — Change tracking -- **`compute_diff(vanilla, current) -> BTreeSet`**: Linear scan comparing two byte slices, returning addresses where they differ. +- **`compute_diff(vanilla, current) -> BTreeSet`**: Compares two byte slices in a linear scan. It returns the addresses that differ. -### `fill_dialog.rs` — Fill selection -- **`FillDialog`**: `{ draft, error }`. Parses a hex byte pattern string to repeat across the selected range. +### `fill_dialog.rs`: Fill selection -### `pattern_layout.rs` — Branch connectors -- Types for rendering Git-log-style branch connectors in the pattern list panel for grouped patterns. +- **`FillDialog`**: `{ draft, error }`. It parses a hex byte pattern string to repeat across the selected range. ---- +### `pattern_layout.rs`: Branch connectors -## UI Layer (Iced-specific) +- Types that draw Git-log-style branch connectors in the pattern list panel for grouped patterns. + +## UI layer (Iced-specific) + +### `update.rs`: Message handler -### `update.rs` — Message handler ```rust pub fn update( state: &mut HexEditorState, @@ -260,30 +243,33 @@ pub fn update( message: HexEditorMessage, ) -> Task ``` -Pure update function (~1300 lines). Dispatches all message variants. Returns `Task::none()` for synchronous mutations, or an async `Task` for file I/O, clipboard, and analysis operations. - -Key handler sections: -- Pane grid operations (click, resize, drag, split, close) -- Cursor movement & selection (SelectAt, ExtendTo, Nav) -- Inline editing (BeginEdit, EditTypeChar, EditBackspace, EditCancel, EditCommit) -- Inspector (copy, begin edit, commit edit) -- Save (delegates to config's `SavePort`) -- Search (open, execute, toggle mode, next/prev, close) + +The `update()` function is pure and about 1300 lines long. It dispatches every message variant. Synchronous changes return `Task::none()`. File I/O, clipboard and analysis return an async `Task`. + +Handler sections: + +- Pane grid operations: click, resize, drag, split and close +- Cursor movement and selection: `SelectAt`, `ExtendTo` and `Nav` +- Inline editing: `BeginEdit`, `EditTypeChar`, `EditBackspace`, `EditCancel` and `EditCommit` +- Inspector: copy, begin edit and commit edit +- Save through the config `SavePort` +- Search: open, execute, toggle mode, next, previous and close - Goto dialog flow -- Pattern CRUD (create, remove, clear, right-click) +- Pattern create, remove, clear and right-click actions - Repeated pattern dialog -- Pattern list & group operations -- Pattern import/export (async file dialogs) -- Settings (theme, colour scheme, dim nulls, entropy band, minimap) -- Write mode & encoding settings -- Copy/Paste (clipboard) +- Pattern list and group operations +- Pattern import and export through async file dialogs +- Settings: theme, colour scheme, dim nulls, entropy band and minimap +- Write mode and encoding settings +- Copy and paste through the clipboard - Fill selection -- Extend file (insert bytes at the cursor) -- Text export (async file dialog + write) -- Byte statistics analysis (async) -- Navigation centering via `pending_center_on` +- Extend file: insert bytes at the cursor +- Text export through an async file dialog and write +- Byte statistics analysis through async work +- Navigation centering through `pending_center_on` + +### `inspector.rs`: Decoder registry -### `inspector.rs` — Decoder registry ```rust pub struct InspectorEntry { pub name: String, @@ -296,11 +282,13 @@ pub struct InspectorEntry { pub static ENTRIES: Lazy>; ``` -15 built-in entries: u8, i8, u16, i16, u32, i32, u64, i64, f32, f64, ascii, utf8, rgb565, cstr, hex. -Numeric entries are editable (have `encode`). The host can inject additional entries via `config.extra_entries`. -### `coloring.rs` — Cell colouring system -Layered provider chain pattern. Each provider implements `CellColorProvider`: +The 15 built-in entries are u8, i8, u16, i16, u32, i32, u64 and i64. The tool also ships f32, f64, ascii, utf8, rgb565, cstr and hex. Numeric entries have `encode`, so you can edit them. The host can add entries through `config.extra_entries`. + +### `coloring.rs`: Cell colouring system + +The providers form a layered chain. Each one implements `CellColorProvider`: + ```rust pub trait CellColorProvider { fn color(&self, addr: u64, byte: u8) -> (Option, Option); @@ -308,29 +296,30 @@ pub trait CellColorProvider { pub fn fold_color(providers, addr, byte) -> (Option, Option); ``` + Later providers in the chain override earlier ones when they return `Some`. -Built-in providers (in application order): -1. **`SearchMatchProvider`** — highlights search matches and current match -2. **`DiffVsVanillaProvider`** — highlights bytes differing from vanilla snapshot -3. **`DirtyProvider`** — highlights bytes modified this session -4. **`PatternBgProvider`** — applies pattern background colours -5. **`AnnotationProvider`** — applies annotation foreground for active patterns -6. **`SchemeProvider`** — applies the active `ColorScheme` (Monochrome/Nybble/Categories/Rainbow/Heatmap) -7. **`DimNullsProvider`** — optionally dims `0x00` bytes -8. **`SelectionProvider`** — highlights selection range and cursor cell +Built-in providers in application order: + +1. **`SearchMatchProvider`**: highlights search matches and the current match +2. **`DiffVsVanillaProvider`**: highlights bytes that differ from the vanilla snapshot +3. **`DirtyProvider`**: highlights bytes changed in this session +4. **`PatternBgProvider`**: applies pattern background colours +5. **`AnnotationProvider`**: applies annotation foreground for active patterns +6. **`SchemeProvider`**: applies the active `ColorScheme` (Monochrome, Nybble, Categories, Rainbow, Heatmap) +7. **`DimNullsProvider`**: dims `0x00` bytes when enabled +8. **`SelectionProvider`**: highlights the selection range and cursor cell -### `theme/` — Theme system -- **`HexEditorTheme`**: Flat struct with ~90+ colour fields covering matrix, header, selection, edit/dirty/diff, search matches, annotations, scrollbar, modals, minimap, pattern panel, statistics panel, byte-colouring schemes, pattern palettes, and Iced application palette. -- **`DARK_THEME`**: Near-black background with warm amber/brown tones (original). -- **`LIGHT_THEME`**: Warm parchment background for accessibility (WCAG AA). -- Both are `const` values compiled at compile time using `const fn hex()`. -- `ThemeVariant` enum: `Dark` / `Light` (with `Default` on `Dark`). -- Theme includes HSL saturation/lightness params for gradient schemes (0.70 for dark, 0.35 for light). +### `theme/`: Theme system ---- +- **`HexEditorTheme`**: A flat struct with 90+ colour fields. It covers the matrix, header, selection, edit, dirty and diff states. It also covers search matches, annotations, scrollbar, modals and minimap. Other groups are the pattern panel, statistics panel, byte-colouring schemes, pattern palettes and the Iced application palette. +- **`DARK_THEME`**: Near-black background with warm amber and brown tones. +- **`LIGHT_THEME`**: Warm parchment background for accessibility, WCAG AA. +- Both are `const` values. They compile at build time through `const fn hex()`. +- The `ThemeVariant` enum has `Dark` and `Light`, with `Default` on `Dark`. +- The theme holds HSL saturation and lightness parameters for gradient schemes: 0.70 for dark and 0.35 for light. -## HexEditorState (Aggregate State) +## HexEditorState (aggregate state) ```rust pub struct HexEditorState { @@ -386,20 +375,19 @@ pub struct HexEditorState { ``` Key methods: -- `load_from_path(path)` — constructs state from file (reads bytes, computes initial entropies, sets default pane layout) -- `max_addr()` — `provider.len().saturating_sub(1)` -- `recompute_vanilla_diff()` — linear scan, call after every write -- `add_pattern(start, end) -> usize` — creates pattern, rebuilds lookups -- `remove_pattern(id)` — removes pattern + orphan groups -- `clear_patterns()` — wipes all patterns and groups -- `rebuild_pattern_lookup()` — rebuilds `pattern_by_addr` BTreeMap -- `recompute_row_annotations()` — rebuilds annotation map + refreshes active patterns -- `refresh_active_patterns()` — recomputes which patterns contain the cursor -- `invalidate_stats()` — clears cached byte statistics when content changes ---- +- `load_from_path(path)`: builds state from a file. It reads bytes, computes initial entropies and sets the default pane layout. +- `max_addr()`: `provider.len().saturating_sub(1)` +- `recompute_vanilla_diff()`: linear scan. Call it after every write. +- `add_pattern(start, end) -> usize`: creates a pattern and rebuilds lookups +- `remove_pattern(id)`: removes a pattern and orphan groups +- `clear_patterns()`: removes all patterns and groups +- `rebuild_pattern_lookup()`: rebuilds the `pattern_by_addr` BTreeMap +- `recompute_row_annotations()`: rebuilds the annotation map and refreshes active patterns +- `refresh_active_patterns()`: recomputes which patterns contain the cursor +- `invalidate_stats()`: clears cached byte statistics when content changes -## HexEditorConfig (Host Injection) +## HexEditorConfig (host injection) ```rust // domain/save.rs — plain data, no iced message types cross this boundary. @@ -432,21 +420,16 @@ pub struct HexEditorConfig { } ``` -Assemble the config with `HexEditorConfig::new()` and its chainable setters -(`pane_gap`, `on_save`, `save_label`, `can_save`, `save_hint`, `extra_entries`, -`custom_encodings`, `on_write_mode_changed`). Both embedders use this one -builder; the standalone binary additionally uses the shared -`standalone_config(...)` helper so its defaults cannot drift from the GUI's. +Build the config with `HexEditorConfig::new()` and its chainable setters: `pane_gap`, `on_save`, `save_label`, `can_save`, `save_hint`, `extra_entries`, `custom_encodings` and `on_write_mode_changed`. Both embedders use this builder. The standalone binary also uses the shared `standalone_config(...)` helper to keep its defaults aligned with the GUI. -Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can_save && on_save.is_some() && dirty_count > 0`). +Helper methods: `save_label()`, `has_save()` and `can_save_now(state)`. The last one checks `can_save && on_save.is_some() && dirty_count > 0`. ---- +## HexEditorMessage (enum reference) -## HexEditorMessage (Enum Reference) - -~48 variant categories, ~200+ total variants. All variants are `#[derive(Debug, Clone)]` and produce `iced::Task`. +There are ~48 variant categories and ~200+ total variants. Every variant uses `#[derive(Debug, Clone)]` and produces `iced::Task`. ### Pane grid + | Variant | Purpose | |---------|---------| | `PaneClicked(pane)` | Set keyboard focus to pane | @@ -455,17 +438,19 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `SplitPane(Axis)` | Split focused pane (max 8 panes) | | `ClosePane` | Close focused pane | -### Cursor & selection +### Cursor and selection + | Variant | Purpose | |---------|---------| | `SetBytesPerRow(u8)` | Set row width (any value 1–64) | | `BytesPerRowInputChanged(String)` | Draft text of the custom bytes-per-row input | | `BytesPerRowInputInvalid` | Custom BPR submitted with an out-of-range/non-numeric value | -| `SelectAt(u64)` | Single click — set anchor=cursor=addr | -| `ExtendTo(u64)` | Shift-click/drag — move cursor only | +| `SelectAt(u64)` | Single click: set anchor=cursor=addr | +| `ExtendTo(u64)` | Shift-click/drag: move cursor only | | `Nav { dir, extend }` | Keyboard navigation | ### Inline editing + | Variant | Purpose | |---------|---------| | `BeginEdit(u64)` | Enter edit mode at addr | @@ -477,6 +462,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `WriteBytes { addr, bytes }` | Programmatic write (inspector/injection) | ### Inspector + | Variant | Purpose | |---------|---------| | `CopyInspectorValue(usize)` | Copy decoded value to clipboard | @@ -486,6 +472,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `CommitInspectorEdit` | Encode and write | ### Save + | Variant | Purpose | |---------|---------| | `SaveIntoRecording` | Trigger save (delegates to `SavePort`) | @@ -493,6 +480,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `ClearStatus` | Clear status message | ### Pattern highlighting + | Variant | Purpose | |---------|---------| | `CreatePattern` | From selection range | @@ -502,6 +490,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `RightClickAt(u64)` | For context menu targeting | ### Repeated pattern dialog + | Variant | Purpose | |---------|---------| | `BeginRepeatedPattern` | Open dialog from selection | @@ -511,6 +500,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `CloseRepeatedPattern` | Dismiss | ### Goto + | Variant | Purpose | |---------|---------| | `OpenGotoDialog` | Opens modal, focuses input | @@ -519,6 +509,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `CloseGotoDialog` | Dismiss | ### Search + | Variant | Purpose | |---------|---------| | `OpenSearch` | Show overlay | @@ -527,7 +518,8 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `SearchNext` / `SearchPrev` | Navigate matches | | `CloseSearch` | Hide overlay | -### Pattern list & groups +### Pattern list and groups + | Variant | Purpose | |---------|---------| | `TogglePatternList` / `ToggleInspector` | Show/hide panels | @@ -542,12 +534,14 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `PatternsExported` / `PatternsImported` | Async results | ### Address format + | Variant | Purpose | |---------|---------| | `ToggleAddrFormat` | Hex ↔ decimal | | `SetAddrFormat(bool)` | Explicit | ### Settings modal + | Variant | Purpose | |---------|---------| | `OpenSettings` / `CloseSettings` | Modal visibility | @@ -558,7 +552,8 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `SetShowMinimapEnabled(bool)` | Minimap toggle | | `ResetSettings` | All defaults | -### Write mode & encoding +### Write mode and encoding + | Variant | Purpose | |---------|---------| | `SetWriteMode(WriteMode)` | Switch mode | @@ -567,7 +562,8 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `RemoveCustomEncoding(usize)` | Remove entry | | `SetCustomEncodings(Vec)` | Bulk replace (deserialize) | -### Copy / Paste +### Copy and paste + | Variant | Purpose | |---------|---------| | `CopySelection` | Copy as hex text | @@ -575,6 +571,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `PasteContent(String)` | Parse and write | ### Fill selection + | Variant | Purpose | |---------|---------| | `BeginFill` | Open dialog | @@ -583,6 +580,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `CloseFill` | Dismiss | ### Extend file + | Variant | Purpose | |---------|---------| | `BeginExtend` | Open dialog (context menu at cursor) | @@ -592,6 +590,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `CloseExtend` | Dismiss | ### Byte statistics + | Variant | Purpose | |---------|---------| | `ToggleStats` | Show/hide panel | @@ -601,6 +600,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `SelectionAnalyzed(ByteStatistics)` | Async result | ### Text export + | Variant | Purpose | |---------|---------| | `OpenExportConfig` / `CloseExportConfig` | Modal visibility | @@ -610,68 +610,69 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can | `CommitExport` | File dialog + write | | `TextExportCompleted(Result<...>)` | Async result | ---- - -## HexMatrix Custom Widget +## HexMatrix custom widget -Located in `src/ui/view/matrix/` (5 files): +The widget lives in `src/ui/view/matrix/` (5 files). ### `mod.rs` -Public API: `HexMatrix` widget struct, `hex_matrix()` constructor function. Wraps `layout`, `state`, `draw`, and `event` modules. + +Public API: the `HexMatrix` widget struct and the `hex_matrix()` constructor. It wraps the `layout`, `state`, `draw` and `event` modules. ### `layout.rs` -Computes the visual layout: column widths (address gutter, hex bytes grouped 8+8, ASCII column, annotation column), row height, total content height for scrolling. Returns sizing metrics consumed by the draw and event handlers. + +It computes column widths for the address gutter, hex bytes grouped 8+8, ASCII column and annotation column. It also computes row height and total content height for scrolling. It returns sizing metrics for the draw and event handlers. ### `state.rs` -Internal mutable state cached between frames: scroll offset, selection/cursor visual positions, hot/cold state for click handling. + +Internal mutable state cached between frames: scroll offset, selection and cursor visual positions, and hot or cold state for click handling. ### `draw.rs` (~984 lines) -The rendering core. Paints via Iced's `Renderer` (wgpu backend): + +The rendering core paints through Iced's `Renderer` on the wgpu backend: + - Address gutter with hex or decimal labels -- Hex byte columns with 8+8 grouping and group separator lines -- ASCII column with printable characters (0x20–0x7E), dots for non-printable +- Hex byte columns grouped 8+8 with group separator lines +- ASCII column with printable characters (0x20 to 0x7E) and dots for other values - Annotation column with pattern text -- Colour resolution via the provider chain (CellColorProvider) -- Selection highlight, cursor cell +- Colour resolution through the `CellColorProvider` chain +- Selection highlight and cursor cell - Edit-in-progress highlight -- Scrollbar with search match dots and cursor dot +- Scrollbar with search match dots and a cursor dot ### `event.rs` (~605 lines) + Mouse and keyboard event handling: -- Click/drag selection -- Double-click → `BeginEdit` -- Keyboard navigation (arrows, Home/End, PageUp/Down, Ctrl+Home/End) -- Hex digit typing → auto-starts edit -- Shift+arrows → extend selection -- Scroll wheel -- All event handling defers to `HexEditorMessage` for state mutation -**Virtualization:** Only rows in the viewport are drawn. The widget computes which rows are visible based on scroll offset and viewport height, then iterates byte addresses in that range. +- Click and drag selection +- Double-click to begin an edit +- Keyboard navigation with arrows, `Home`, `End`, `PageUp`, `PageDown`, `Ctrl+Home` and `Ctrl+End` +- Hex digit typing to start an edit +- Shift with arrows to extend the selection +- Scroll wheel +- Every event defers state mutation to `HexEditorMessage` ---- +**Virtualization:** The widget draws only rows in the viewport. It computes visible rows from the scroll offset and viewport height. It then iterates byte addresses in that range. -## Coloring System +## The coloring system The hex matrix resolves cell colours through a layered provider chain. The application order in `draw.rs` is: -1. **Search match** — `SearchMatchProvider` highlights all bytes in search results (green tones) -2. **Diff vs vanilla** — `DiffVsVanillaProvider` shows cumulative changes from on-disk snapshot -3. **Dirty bytes** — `DirtyProvider` shows bytes modified this session -4. **Pattern background** — `PatternBgProvider` applies pattern background colours -5. **Pattern annotation** — `AnnotationProvider` adjusts foreground for active pattern annotations -6. **Colour scheme** — `SchemeProvider` applies the base font colour (Monochrome/Nybble/Categories/Rainbow/Heatmap) -7. **Dim nulls** — `DimNullsProvider` optionally dims `0x00` bytes -8. **Selection** — `SelectionProvider` paints selection range and cursor cell +1. **Search match:** `SearchMatchProvider` highlights all bytes in search results with green tones +2. **Diff vs vanilla:** `DiffVsVanillaProvider` shows cumulative changes from the on-disk snapshot +3. **Dirty bytes:** `DirtyProvider` shows bytes changed in this session +4. **Pattern background:** `PatternBgProvider` applies pattern background colours +5. **Pattern annotation:** `AnnotationProvider` adjusts foreground for active pattern annotations +6. **Colour scheme:** `SchemeProvider` applies the base font colour (Monochrome, Nybble, Categories, Rainbow, Heatmap) +7. **Dim nulls:** `DimNullsProvider` dims `0x00` bytes when enabled +8. **Selection:** `SelectionProvider` paints the selection range and cursor cell -Each provider returns `(Option, Option)`. `fold_color()` merges them: later providers override earlier ones. This means search highlights take priority over dirty/diff, which take priority over patterns, which take priority over the base scheme. +Each provider returns `(Option, Option)`. `fold_color()` merges the results. Later providers override earlier ones. Search highlights take priority over dirty and diff colours. Those take priority over patterns. Patterns take priority over the base scheme. -**`default_byte_colors(scheme, byte, dim_nulls)`** is the convenience function used by both the matrix widget and the settings-modal palette preview to ensure consistency. +`default_byte_colors(scheme, byte, dim_nulls)` is the shared convenience function. The matrix widget and the settings modal palette preview both call it. ---- +## Inspector decoder system -## Inspector Decoder System - -15 built-in `InspectorEntry` values in `ENTRIES` lazy static: +15 built-in `InspectorEntry` values live in the `ENTRIES` lazy static: | Name | Size | Editable | Category | |------|------|----------|----------| @@ -691,82 +692,84 @@ Each provider returns `(Option, Option)`. `fold_color()` merges them: la | cstr | 1 | No | Text | | hex | 1 | No | Binary | -Each entry has a `decode` function that converts bytes to a display string, and optionally an `encode` function that parses user input and produces bytes. - -The host can add entries via `config.extra_entries`. The update handler selects between built-in and extra entries based on index: indices below `ENTRIES.len()` are built-in; higher indices index into `config.extra_entries`. +Each entry has a `decode` function that converts bytes to a display string. Entries with an `encode` function also parse user input into bytes. ---- +The host can add entries through `config.extra_entries`. The update handler picks between built-in and extra entries by index. Indices below `ENTRIES.len()` refer to built-in entries. Higher indices refer to `config.extra_entries`. -## Pattern System +## Pattern system ### Data model -- **`Pattern`**: Serializable struct with id, byte range, colour index (0–15, cyclic palette), optional group id, optional annotation string. -- **`RepeatedPatternGroup`**: Named group with shared colour. All child patterns inherit the group's colour. + +- **`Pattern`**: A serializable struct with id, byte range, colour index (0 to 15, cyclic palette), optional group id and optional annotation string. +- **`RepeatedPatternGroup`**: A named group with a shared colour. Child patterns inherit the group colour. ### Lookup structures -- **`pattern_by_addr: BTreeMap`**: Maps every byte address to the pattern id and colour index that covers it. Rebuilt on every pattern mutation. -- **`row_annotations: BTreeMap>`**: Maps row start addresses to annotation segments for the annotation column. Rebuilt on every pattern mutation. -- **`active_patterns: BTreeSet`**: Pattern ids whose span includes the cursor. Refreshed on cursor movement. + +- **`pattern_by_addr: BTreeMap`**: Maps every byte address to its pattern id and colour index. A pattern mutation triggers a rebuild. +- **`row_annotations: BTreeMap>`**: Maps row start addresses to annotation segments for the annotation column. A pattern mutation triggers a rebuild. +- **`active_patterns: BTreeSet`**: Pattern ids whose span includes the cursor. Cursor movement refreshes this set. ### Creation flow -1. User selects a byte range -2. Right-click → "Create Pattern" or `Ctrl+E` -3. `add_pattern(start, end)` creates `Pattern { id, start, end, color_idx }`, rebuilds lookups + +1. The user selects a byte range. +2. The user right-clicks and chooses `Create Pattern`, or presses `Ctrl+E`. +3. `add_pattern(start, end)` creates `Pattern { id, start, end, color_idx }` and rebuilds lookups. ### Repeated pattern flow -1. User selects a block -2. Right-click → "Add Repeated Pattern" -3. Modal: enter repeat count and group label -4. `CommitRepeatedPattern` creates alternating-colour `Pattern` entries, auto-fills annotations as `"GroupName[0]"`, `"GroupName[1]"`, etc. -5. Group rename updates child annotations matching `"{old_label}[{digits}]"` pattern -### Import/Export -Patterns export as JSON via `PatternExport` struct (versioned, currently v1). Async file dialog flow. +1. The user selects a block. +2. The user right-clicks and chooses `Add Repeated Pattern`. +3. The modal asks for a repeat count and a group label. +4. `CommitRepeatedPattern` creates alternating-colour `Pattern` entries. It fills annotations such as `"GroupName[0]"` and `"GroupName[1]"`. +5. A group rename updates child annotations that match `"{old_label}[{digits}]"`. + +### Import and export ---- +Patterns export as JSON through the `PatternExport` struct, currently v1. The flow uses an async file dialog. -## Writing / Inline Editing +## Inline editing and writing ### Hex mode (default) -1. User presses a hex digit → auto-creates `EditState{ addr: cursor, draft: "" }` and appends the digit -2. Second digit appended → auto-commits: `provider.write(addr, byte)`, advances cursor +1, creates new `EditState` at next address -3. `Tab`/`Enter` → `EditCommit { advance: true }`: commit current draft (or nothing if empty), advance cursor -4. `Esc` → `EditCancel`: discard draft + +1. A hex digit starts `EditState{ addr: cursor, draft: "" }` and appends the digit. +2. A second digit commits the byte through `provider.write(addr, byte)`. The cursor advances by one. A new `EditState` starts at the next address. +3. `Tab` or `Enter` sends `EditCommit { advance: true }`. It commits a nonempty draft and advances the cursor. +4. `Esc` sends `EditCancel` and discards the draft. ### Text mode (ASCII, UTF-8, Windows-1250, EUC-KR, Custom) -1. User types any printable character → immediately encoded via `encode_text()`, written to buffer, cursor advanced by encoded byte count -2. No draft — each character is written atomically -3. `Backspace` moves cursor left by one byte (no delete) -4. `Delete` key writes 0x00 at cursor and advances + +1. A printable character goes through `encode_text()`. The tool writes the bytes and advances the cursor by the encoded byte count. +2. There is no draft. The tool writes each character atomically. +3. `Backspace` moves the cursor left by one byte. It does not delete. +4. `Delete` writes 0x00 at the cursor and advances. ### Inspector edit -1. User clicks "Edit" on an inspector entry → `BeginInspectorEdit(idx)` opens modal with pre-filled current value -2. User edits draft → `SetInspectorDraft(String)` -3. User confirms → `CommitInspectorEdit`: calls entry's `encode(&draft)`, writes bytes, closes modal ---- +1. The user clicks `Edit` on an inspector entry. `BeginInspectorEdit(idx)` opens a modal with the current value. +2. `SetInspectorDraft(String)` updates the draft. +3. `CommitInspectorEdit` calls the entry's `encode(&draft)`, writes bytes and closes the modal. -## Search & Navigation +## Search and navigation ### Search + - Two modes: Hex (`"DE AD BE EF"` or `"DEADBEEF"`) and ASCII (`"hello"`) -- Results are `Vec` of match start addresses, pre-computed on every query change -- `match_set: BTreeSet` for O(log n) lookup during rendering -- Current match highlighted differently from other matches -- Next/prev wrap around -- Search overlay appears below toolbar, rendered in `search_overlay.rs` +- Results are `Vec` of match start addresses. The tool precomputes them on every query change. +- `match_set: BTreeSet` supports O(log n) lookup during rendering +- The current match uses a different highlight +- Next and previous wrap around +- The search overlay sits below the toolbar and lives in `search_overlay.rs` ### Goto -- Modal dialog activated by `Ctrl+G` -- Input parsing: `0xFF` (hex prefix), `FF` (hex-detected if contains a-f), `255` (decimal), `+10` (relative forward), `-5` (relative backward) -- On commit: selection jumps to target address, viewport centers on it via `pending_center_on` -- Backed by `GotoState.parse(cursor, max_addr)`, fully unit-tested ---- +- The modal dialog opens with `Ctrl+G`. +- Input parsing: `0xFF` has a hex prefix. The tool treats `FF` as hex when it contains a-f. `255` is decimal. `+10` moves forward. `-5` moves backward. +- On commit, the selection jumps to the target address. The viewport centers on it through `pending_center_on`. +- The flow uses `GotoState.parse(cursor, max_addr)`, which has full unit tests. -## Write Modes & Text Encoding +## Write modes and text encoding -The `WriteMode` enum controls how keyboard input is interpreted: +The `WriteMode` enum controls how keyboard input becomes bytes: | Mode | Input → Bytes | Use case | |------|--------------|----------| @@ -777,71 +780,66 @@ The `WriteMode` enum controls how keyboard input is interpreted: | `EucKr` | Each char → 1–2 bytes via encoding_rs | Korean text | | `Custom(idx)` | Via `encoding_rs` for user-added encoding | Any encoding_rs-supported encoding | -Users can add custom encodings from a list of 30+ `COMMON_ENCODINGS` via the encoding settings modal. +Users can add custom encodings from a list of 30+ `COMMON_ENCODINGS` through the encoding settings modal. -**Serde:** `WriteMode` serializes as string label. `Custom` stores its label, not index — index is resolved at deserialization through the custom encoding list. +`WriteMode` serializes as a string label through Serde. `Custom` stores its label rather than its index. Deserialization resolves the index through the custom encoding list. ---- +## Byte statistics and entropy panel -## Byte Statistics & Entropy Panel +A toggleable panel shows: -Toggleable panel showing: -- **Byte distribution histogram** (bar chart of byte value frequencies) -- **Shannon entropy** (file-level and per-row) -- **Structure heuristics** (uniform runs, high/low entropy regions, mixed content) -- **Entropy colour band** in the address gutter (visual entropy fingerprint) +- **Byte distribution histogram:** a bar chart of byte value frequencies +- **Shannon entropy:** file level and per row +- **Structure heuristics:** uniform runs, high and low entropy regions, mixed content +- **Entropy colour band** in the address gutter, a visual entropy fingerprint -All analysis runs async via `Task::perform`. Selection-only analysis available. Statistics are cached and invalidated on content change or row-width change. +All analysis runs asynchronously through `Task::perform`. The tool also analyzes the selection only. It caches statistics and invalidates them when content or row width changes. ---- +## Pane grid layout -## Pane Grid Layout +The editor uses the Halloy pattern for panes: `pane_grid::State` with movable, splittable, resizable panels. -Hex editor uses the **Halloy pattern** for pane management: `pane_grid::State` with movable, splittable, resizable panels. - -**Default layout:** Vertical split — 75% hex matrix (left), 25% inspector (right). +**Default layout:** a vertical split with 75% hex matrix on the left and 25% inspector on the right. **Panel types** (`HexPanelContent`): -- `Matrix` — The main hex byte display (always present) -- `Inspector` — Decoded value inspector (shown by default) -- `PatternList` — Pattern management panel (toggled via toolbar) -- `Statistics` — Byte statistics & entropy panel (toggled via toolbar) + +- `Matrix`: the main hex byte display, always present +- `Inspector`: decoded value inspector, shown by default +- `PatternList`: pattern management panel, opened from the toolbar +- `Statistics`: byte statistics and entropy panel, opened from the toolbar **Operations:** -- Panels can be split (`SplitPane`) up to 8 total -- Panels can be reordered via drag (`PaneDragged`) -- Panels can be closed (`ClosePane`, minimum 1 panel) -- Focused panel receives keyboard input -- Divider resize with configurable gap (`config.pane_gap`) ---- +- Split a panel with `SplitPane`, up to 8 total +- Reorder panels by drag with `PaneDragged` +- Close panels with `ClosePane`, with at least 1 left +- The focused panel receives keyboard input +- Resize dividers with the configurable `config.pane_gap` ## Minimap -Overview strip at the bottom of the matrix panel shows: -- **File structure** — each row of the minimap represents many file rows (pixel-per-row mapping) -- **Cursor marker** — shows current position in the file -- **Dirty/diff pixels** — shows which regions have been modified -- Cached as `RefCell>` to avoid recomputing every frame +An overview strip at the bottom of the matrix panel shows: ---- +- **File structure:** each minimap row represents many file rows through a pixel-per-row mapping +- **Cursor marker:** the current position in the file +- **Dirty and diff pixels:** the regions that changed -## Theme System +The tool caches the strip as `RefCell>` to avoid recomputing every frame. -All colours consolidated into `HexEditorTheme` — a flat struct with ~90+ fields. Two built-in compile-time constants: +## Theme system -- **`DARK_THEME`**: Leather/amber (original). Near-black background `#14110f`, warm text `#d4cabd`, amber accents. -- **`LIGHT_THEME`**: Warm parchment. Background `#F5EDE0`, dark text `#3A3228`, blue selection. +All colours live in `HexEditorTheme`, a flat struct with 90+ fields. Two constants compile at build time: -Both themes meet WCAG AA contrast ratio (4.5:1) for normal-size text across all byte colouring schemes (with the intentional exception of `dim_nulls` for `0x00`). +- **`DARK_THEME`:** leather and amber, the original theme. Near-black background `#14110f`, warm text `#d4cabd` and amber accents. +- **`LIGHT_THEME`:** warm parchment. Background `#F5EDE0`, dark text `#3A3228` and blue selection. -The theme is stored as `&'static HexEditorTheme` on state (a reference to the static constant), so switching themes is just changing the pointer. The `ThemeVariant` enum tracks which is active for the settings UI. +Both themes meet WCAG AA contrast ratio (4.5:1) for normal-size text across all byte colouring schemes. `dim_nulls` for `0x00` is the exception. ---- +State holds the theme as `&'static HexEditorTheme`, a reference to the static constant. A theme change only updates the pointer. The `ThemeVariant` enum tracks the active theme for the settings UI. -## Test Structure +## Test structure -Located in `src/tests/`, using `iced_test::Simulator` for end-to-end view→update→view pipeline tests: +Files in `src/tests/` use `iced_test::Simulator` for end-to-end view-update-view pipeline tests: | File | Tests | |------|-------| @@ -860,8 +858,6 @@ Located in `src/tests/`, using `iced_test::Simulator` for end-to-end view→upda | `toolbar.rs` | Toolbar buttons visibility | | `pane_grid.rs` | Pane split, close, focus | ---- - ## Usage (library) ```rust @@ -889,12 +885,7 @@ fn view(&self) -> iced::Element<'_, HexEditorMessage> { } ``` -The host app provides a `SavePort` callback in `HexEditorConfig` if persistence -should be wired to mod recording or direct file saves. It receives a -domain-level `SaveRequest` (path + current bytes) and returns a task producing -a `SaveOutcome`; it never constructs or matches on `HexEditorMessage`. - ---- +The host provides a `SavePort` callback in `HexEditorConfig` when persistence should connect to mod recording or direct file saves. The callback receives a domain-level `SaveRequest` with the path and current bytes. It returns a task producing a `SaveOutcome`. It never constructs or matches on `HexEditorMessage`. ## Usage (standalone binaries) @@ -906,8 +897,6 @@ cargo run -p hexedit cargo run -p hexedit -- path/to/file.bin ``` ---- - ## Build ```bash @@ -916,14 +905,10 @@ cargo test -p hexedit # Unit + integration tests cargo test -p hexedit --test '' -- --ignored # All tests (including slow ones) ``` ---- - ## Feature flags `hexedit` declares no crate-specific Cargo features. ---- - ## Keybindings | Key | Action | @@ -943,79 +928,63 @@ cargo test -p hexedit --test '' -- --ignored # All tests (including slow one | `Ctrl+E` | Create pattern from selection | | Hex digit (`0-9 A-F`) | Auto-start editing at cursor | ---- - ## Dependencies -- **Iced 0.15** — UI framework (wgpu, advanced, canvas, lazy features) -- **gui-widgets** — Reusable Iced widgets (context menu, modal, paragraph cache) -- **lru 0.12** — LRU cache for inspector / internal use -- **tokio 1** — Async file I/O -- **rfd 0.17** — File dialogs (standalone binaries) -- **encoding_rs** — Text encoding for write modes and custom encodings -- **serde** + **serde_json** — Pattern import/export serialization -- **once_cell** — Lazy static for inspector entries +- **Iced 0.15:** UI framework with wgpu, advanced, canvas and lazy features +- **gui-widgets:** reusable Iced widgets, context menu, modal and paragraph cache +- **lru 0.12:** LRU cache for the inspector and internal use +- **tokio 1:** async file I/O +- **rfd 0.17:** file dialogs for the standalone binaries +- **encoding_rs:** text encoding for write modes and custom encodings +- **serde** and **serde_json:** pattern import and export serialization +- **once_cell:** lazy static for inspector entries ---- +## LLM guidance: conventions and invariants -## LLM Guidance — Conventions & Invariants +Keep these invariants when you change the code: -### When modifying this code, preserve these invariants: +1. **Domain and UI separation:** Never import Iced widget types into `src/domain/`. Domain types hold pure data with no widget dependencies. Put UI code in `src/ui/`. -1. **Domain/UI separation:** Never import Iced widget types into `src/domain/`. Domain types should be pure data structures with no widget dependencies. UI-specific code always goes in `src/ui/`. +2. **State mutation discipline:** All state mutation happens in `update()`. `view()` stays pure. It never mutates state, apart from reading `Cell>` through `Cell::take()` for one-frame events. -2. **State mutation discipline:** All state mutation happens in the `update()` function. The `view()` function is pure — it never mutates state (except reading `Cell>` via `Cell::take()` for one-frame events). +3. **Provider chain order:** The `fold_color()` chain in the matrix renderer has a fixed order: search, diff, dirty, pattern, scheme, dim and selection. A new provider must go in the right position. The order sets priority. -3. **Provider chain order:** The `fold_color()` provider chain in the matrix rendering has a specific layered order (search → diff → dirty → pattern → scheme → dim → selection). Adding a new provider means inserting it at the correct position. The order determines priority. +4. **Pattern lookup consistency:** After any pattern mutation (create, remove, colour change or annotation change), call `rebuild_pattern_lookup()` and `recompute_row_annotations()`. These keep address lookups and annotation rendering in sync. -4. **Pattern lookup consistency:** After any pattern mutation (create, remove, update colour, update annotation), you MUST call `rebuild_pattern_lookup()` + `recompute_row_annotations()` to keep address-based lookups and annotation rendering in sync. +5. **Vanilla diff freshness:** Call `recompute_vanilla_diff()` after every `provider.write()` call. The linear scan is cheap. If you skip it, the diff highlighting becomes stale. -5. **Vanilla diff freshness:** Call `recompute_vanilla_diff()` after every `provider.write()` call. It's a linear scan so it's cheap, but forgetting it will cause stale diff highlighting. +6. **Statistics invalidation:** Call `invalidate_stats()` when file content or `bytes_per_row` changes. The tool caches statistics and computes them through async work. -6. **Statistics invalidation:** Call `invalidate_stats()` whenever file content changes or `bytes_per_row` changes. Statistics are cached and computed async. +7. **Error string handling:** Do not use `"."` or empty strings for errors. The host shows `status_msg` to the user. `error` records load-time failures. Both should be informative. -7. **Error string handling:** Never use `"."` or empty strings for error cases. The host uses `status_msg` for user-facing messages and `error` for load-time failures. Both should be informative. +8. **Message return discipline:** `update()` returns `Task`. Synchronous mutations return `Task::none()`. Async work (file I/O, clipboard, analysis) returns `Task::perform(...)`. Do not return `Task::none()` from an update that should produce follow-up messages. -8. **Message return discipline:** The `update()` function returns `Task`. Synchronous mutations return `Task::none()`. Async operations (file I/O, clipboard, analysis) return a `Task::perform(...)`. Never return `Task::none()` from an update that should produce follow-up messages. +9. **Pane count limit:** The maximum is 8 panes. Before a split, the `SplitPane` handler checks `state.panes.len() < 8`. -9. **Pane count limit:** Maximum 8 panes (`state.panes.len() < 8` check before split). Enforced in the `SplitPane` handler. +10. **Bytes-per-row validation:** Any value in `MIN_BYTES_PER_ROW..=MAX_BYTES_PER_ROW` (1 to 64) is valid. The `SetBytesPerRow` handler enforces the range. The settings modal custom input goes through `parse_bpr()` and shows a status message for invalid values. A BPR change also re-lays out pattern annotations through `recompute_row_annotations()`. The tool keys annotations by `row * bpr`. -10. **Bytes-per-row validation:** Any value in `MIN_BYTES_PER_ROW..=MAX_BYTES_PER_ROW` - (1–64) is valid. The `SetBytesPerRow` handler enforces this range; the settings - modal's custom input goes through `parse_bpr()` and surfaces a status message - for invalid submissions. Note that a BPR change also re-lays-out pattern - annotations (`recompute_row_annotations()`) since they're keyed by `row * bpr`. +11. **ParagraphCache:** The app shares `state.cache` across frames. The widget gets a cheap clone each frame. Use it for shaped text that survives between frames. -11. **ParagraphCache:** The `state.cache` is shared across frames. It's cheaply cloned into the widget each frame. Always use it for shaped text that survives between frames. +12. **Test pattern:** Integration tests use `iced_test::Simulator`. Construct state, call `view()`, assert the widget tree with `ui.find()`, send messages through `update()` and check the view again. See `tests/` for examples. -12. **Test pattern:** Integration tests use `iced_test::Simulator`: construct state, call `view()`, assert widget tree with `ui.find()`, send messages via `update()`, re-check view. See `tests/` for examples. +13. **New decoder:** -13. **Adding a new decoder:** - - Add a `dec_*` function and optional `enc_*` function in `ui/inspector.rs` + - Add a `dec_*` function and an optional `enc_*` function in `ui/inspector.rs` - Add an `entry()` call in the `ENTRIES` lazy static - Add a `call_decode` test in the `#[cfg(test)]` block - - The host can also add entries via `config.extra_entries` (no code change needed) + - The host can also add entries through `config.extra_entries` without a code change -14. **When adding a new message variant:** - - Add the variant to `HexEditorMessage` in `message.rs` - - Add a handler arm in the `match` in `update.rs` - - Wire the update handler to any async returns or state mutations - - If the message changes the view, write an iced_test for it +14. **New message variant:** ---- + - Add the variant to `HexEditorMessage` in `message.rs` + - Add a handler arm to the `match` in `update.rs` + - Connect async returns and state mutations to the handler + - Write an iced_test for the message if it changes the view ## Project context -hexedit is part of the [Dispel RPG modding toolkit](https://github.com/piotr/dispel-extractor), -a 5-crate Rust workspace. It powers the hex editor tab inside `dispel-gui` and can also -be used standalone for general-purpose binary editing. - -**DISPEL®** is a registered trademark. This project is **not affiliated with, endorsed by, -or sponsored by** the trademark owner. - ---- +hexedit is part of the [Dispel RPG modding toolkit](https://github.com/piotr/dispel-extractor), a 6-crate Rust workspace: root `dispel-extractor`, `dispel-encodings`, `dispel-gui`, `dispel-macros`, `gui-widgets` and `hexedit`. It powers the hex editor tab inside `dispel-gui`. You can also use it standalone for general binary editing. ## License -Like the rest of the Dispel Extractor workspace, this crate is distributed under -the terms of the project license. +The MIT License (LICENSE) covers `hexedit`. From 958cf5280678a6a48061e7888527912827d18e63 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:41:34 +0100 Subject: [PATCH 04/72] docs: rewrite nine format documents in plain English --- docs/files/AllMap.ini.md | 38 ++++------ docs/files/CROSS_REFERENCES.md | 45 +++++------- docs/files/Event.ini.md | 106 +++++++++++++--------------- docs/files/Extra.ini.md | 84 ++++++++++------------ docs/files/Npc.ini.md | 68 +++++++++--------- docs/files/Save.ifo.md | 18 ++--- docs/files/SaveFile.md | 123 ++++++++++----------------------- docs/files/Sprites.spr.md | 9 +-- docs/files/Wave.ini.md | 19 ++--- 9 files changed, 195 insertions(+), 315 deletions(-) diff --git a/docs/files/AllMap.ini.md b/docs/files/AllMap.ini.md index 70b38088..5f2f2e06 100644 --- a/docs/files/AllMap.ini.md +++ b/docs/files/AllMap.ini.md @@ -1,27 +1,23 @@ -# AllMap.ini Documentation +# AllMap.ini documentation -> **DISPEL®** is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - -## File Information +## File information - **Location**: `Dispel/AllMap.ini` (relative to game installation directory) - **Encoding**: WINDOWS-1250 - **Format**: CSV (Comma-Separated Values) -- **Comment lines**: Lines starting with `;` are ignored +- **Comment lines**: The parser ignores lines starting with `;` -`AllMap.ini` is a master map list file used by the game engine to index all available maps and their associated -resources. +The tool reads `AllMap.ini` as a master map list. Each row links a map ID to a map file name, two dialogue file names and a lighting value. ## Structure -Each line represents one map with the following fields: +Each non-comment line holds six comma-separated fields: ``` id,map_file,name,pgp,dlg,lit ``` -### Field Definitions +### Field definitions | Field | Type | Description | |------------|-------------|---------------------------------------------------------------| @@ -32,7 +28,7 @@ id,map_file,name,pgp,dlg,lit | `dlg` | String/Null | Dialog text filename or "null" if absent | | `lit` | Integer | Lighting indicator: `0` = dark/dungeon, `1` = lit/outdoor | -### Example Entries +### Example entries ``` 1,cat1,Forest,Pgpcat1.pgp,Dlgcat1.dlg,1 @@ -40,26 +36,20 @@ id,map_file,name,pgp,dlg,lit 3,cat3,Village,null,null,1 ``` -### Special Values - -- **"null"**: Used for `pgp` and `dlg` fields when the file is absent -- **Lighting**: `0` indicates dark/dungeon maps, `1` indicates lit/outdoor maps +### Special values -## Purpose +- **"null"**: The tool reads this string when a `pgp` or `dlg` value is absent. +- **Light values**: `0` marks dark or dungeon maps. `1` marks lit or outdoor maps. -This file serves as the master index for all game maps, linking map IDs to their respective filenames and metadata. The -game engine uses this file to: +## Tool use -1. Load the correct map files -2. Associate party (PGP) and dialog (DLG) files with maps -3. Determine lighting conditions for rendering +The tool links each map ID to a map file name. It also stores the dialogue file names and the lighting value. ## Parser -The file is parsed by the `Map` struct in `src/references/all_map_ini.rs`, which implements the `Extractor` and -`Localizable` traits. +The `Map` struct in `src/references/all_map_ini.rs` parses the file. It implements the `Extractor` and `Localizable` traits. -### How to Run +### How to run ```bash # Extract AllMap.ini to JSON diff --git a/docs/files/CROSS_REFERENCES.md b/docs/files/CROSS_REFERENCES.md index cf84d032..2a821570 100644 --- a/docs/files/CROSS_REFERENCES.md +++ b/docs/files/CROSS_REFERENCES.md @@ -1,9 +1,8 @@ -# Dispel Game File System - Cross References +# Dispel game file system: cross references ## Overview -This document maps the relationships and cross-references between all game data files in the Dispel game system. The -files form a complex interconnected database that drives the game's mechanics, visuals, and interactions. +This document maps the cross references between game data files. The tool reads and writes data files that you supply. Each row below links a field in one file to a file name or a field in another file. ## File Dependency Map @@ -333,16 +332,16 @@ Message.scr (UI messages) ## Data Flow Summary -1. **Map Loading**: AllMap.ini → Map.ini → Load map geometry (.map), place monsters (.ref), NPCs (.ref), objects (.ref) -2. **Map Rendering**: Map.map → Map.gtl (ground tiles) + Map.btl (building tiles) + Sprites.spr (objects/NPCs) -3. **NPC Interaction**: NpcMapFiles.ref → Npc.ini → Sprites.spr + DlgMapFiles.dlg → PgpMapFiles.pgp -4. **Monster Combat**: MondunMonmap.ref → Monster.ini → Sprites.spr + Monster.db → Magic.db -5. **Object Interaction**: Extra.ref → Extra.ini → Sprites.spr + Event.ini + Message.scr -6. **Quest Progression**: Event.ini → Script files → Quest.scr -7. **Character Development**: PartyRef.ref → PrtLevel.db → WeaponItem.db + Magic.db -8. **Commerce**: Store.db → Item databases (WeaponItem.db, HealItem.db, etc.) -9. **Audio**: Wave.ini → .snf files (referenced during events/dialogue) -10. **Monster Loot**: MondunMonmap.ref → Item databases (loot drops) +1. Map data: AllMap.ini → Map.ini → Map.map, MondunMonmap.ref, NpcMapFiles.ref and Extra.ref +2. Map rendering: Map.map → Map.gtl (ground tiles), Map.btl (building tiles) and Sprites.spr (objects and NPCs) +3. NPC data: NpcMapFiles.ref → Npc.ini → Sprites.spr, and DlgMapFiles.dlg → PgpMapFiles.pgp +4. Monster data: MondunMonmap.ref → Monster.ini → Sprites.spr, and Monster.db → Magic.db +5. Object data: Extra.ref → Extra.ini → Sprites.spr, Event.ini and Message.scr +6. Quest data: Event.ini → script files → Quest.scr +7. Character data: PartyRef.ref → PrtLevel.db → WeaponItem.db and Magic.db +8. Commerce data: Store.db → item databases such as WeaponItem.db and HealItem.db +9. Audio data: Wave.ini → .snf files +10. Monster loot: MondunMonmap.ref → item databases ## Item Database Relationships @@ -393,20 +392,13 @@ MiscItem.db (generic utility items) | WINDOWS-1250 | AllMap.ini, Monster.ini, Store.db, WeaponItem.db, HealItem.db (names), MiscItem.db, EditItem.db, EventItem.db, Message.scr, Quest.scr, PgpMapFiles.pgp, Extra.ref, NpcMapFiles.ref, PartyRef.ref, Eventnpc.ref | | Binary | Monster.db, WeaponItem.db, HealItem.db, MiscItem.db, EditItem.db, EventItem.db, Store.db, ChData.db, PrtLevel.db, Magic.db, DrawItem.db, Map.map, Map.gtl, Map.btl, Sprites.spr | -## Legal Compliance +## Scope -This cross-reference documentation: +The tool reads and writes data files that you supply. This document lists the field links between those files. -- Describes **technical relationships between file formats only** -- Does **not distribute any copyrighted game content** -- Focuses on **data structure organization and system design** -- Uses **generic descriptions** of game mechanics -- Maintains **nominative use** for trademark references -- Is intended for **independent interoperability research based on observable behavior** only, without circumvention of technological protection measures +## Extractor commands -## Extractor Commands - -The extractor tool (`src/`) provides commands to parse and extract data from all game files. +The tool in `src/` parses and extracts data from game files. Run these commands from the repository root. ### Quick Reference @@ -464,8 +456,3 @@ cargo run -- sound "path/to/file.snf" "output.wav" # Import to SQLite database cargo run -- database import "path/to/Dispel/" "database.sqlite" ``` - ---- - -**DISPEL®** is a registered trademark. This documentation is **not affiliated with, endorsed by, or sponsored by** the -trademark owner. diff --git a/docs/files/Event.ini.md b/docs/files/Event.ini.md index b4fa1d63..27821598 100644 --- a/docs/files/Event.ini.md +++ b/docs/files/Event.ini.md @@ -1,22 +1,18 @@ -# Event.ini Documentation +# Event.ini documentation -> **DISPEL®** is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - -## File Information +## File information ### Overview -Text file that defines event scripts with execution conditions, prerequisites, and repetition limits for the game's -event system. +The tool reads `Event.ini` as a CSV file with comments. Each row holds an event ID, a prerequisite ID, a type code, a script filename and a counter. -### File Structure +### File structure -**Location**: `Event.ini` -**Encoding**: EUC-KR (Korean character encoding) -**Format**: CSV (Comma-Separated Values) with comments +- **Location**: `Event.ini` +- **Encoding**: EUC-KR (Korean character encoding) +- **Format**: CSV (Comma-Separated Values) with comments -### Format Specification +### Format specification ```ini ; Comment line explaining event types and execution conditions @@ -27,7 +23,7 @@ event_id,required_event_id,event_type,script_filename,counter ... ``` -### Field Definitions +### Field definitions | Field | Type | Description | |-------------------|--------|-----------------------------------------------------| @@ -37,9 +33,9 @@ event_id,required_event_id,event_type,script_filename,counter | script_filename | string | Script filename or "null" for no script | | counter | i32 | Execution limit (0 = unlimited, N = max executions) | -### Event Type System +### Event type system -The file includes a detailed comment header explaining the event type system: +The file carries a comment header that defines the type codes: ```ini ; Event number, preceding event identifier, type: @@ -55,31 +51,29 @@ The file includes a detailed comment header explaining the event type system: ; Script filename, number of times to execute (N) ``` -### Event Type Details +### Event type details -**Unconditional Execution (Types 0, 1, 2):** +**Unconditional execution (types 0, 1 and 2):** -- Execute regardless of previous event status -- Type 0: Execute once -- Type 1: Execute N times (uses counter) -- Type 2: Execute unconditionally +- Type 0 uses one execution and ignores the prerequisite. +- Type 1 uses `N` executions through the counter and ignores the prerequisite. +- Type 2 has no counter and ignores the prerequisite. -**Conditional Execution (Types 3-8):** +**Conditional execution (types 3 to 8):** -- Execution depends on previous event status -- Types 3-5: Execute when previous event unsatisfied -- Types 6-8: Execute when previous event satisfied -- Types 4, 7, 8: Use counter for repetition limits +- Types 3 to 5 use an unsatisfied prerequisite. +- Types 6 to 8 use a satisfied prerequisite. +- Types 4, 7 and 8 use the counter for repetition limits. -### Special Values +### Special values -- **"null"**: Literal string indicating no script filename -- **counter = 0**: No execution limit (infinite) -- **counter = N**: Maximum execution count -- **;**: Lines starting with semicolon are comments -- **Empty lines**: Ignored during processing +- **"null"**: The tool reads this string when no script filename is present. +- **counter = 0**: No execution limit. +- **counter = N**: Maximum execution count. +- **`;`**: Lines starting with this mark are comments. +- **Empty lines**: The parser ignores them. -### Example Format +### Example format ```ini ; Default data @@ -94,48 +88,42 @@ The file includes a detailed comment header explaining the event type system: 11,10,7,transition.scr,3 ``` -### Technical Details +### Technical details **Encoding**: EUC-KR (Extended Unix Code Korea) -- Supports Korean characters in comments -- Requires proper encoding handling for reading/writing - -**File Processing**: +- The encoding covers Korean characters in comments. +- The reader and writer must use this encoding. -- Comments (lines starting with ";") are ignored -- Empty lines are skipped -- CSV format with comma delimiter -- "null" literal used for missing script filenames +**File processing:** -### Database Integration +- The parser ignores comment lines that start with `;`. +- It skips empty lines. +- It splits rows on commas. +- It reads `null` as a missing script filename. -- Processed by the `Event` struct in `src/references/event_ini.rs` -- Uses the `EventType` enum from `src/references/enums.rs` for type-safe event types -- Stored in database with all field mappings -- Referenced by other game systems (NPC, Extra objects) +### Database integration -### Event Chaining +The `Event` struct in `src/references/event_ini.rs` parses the file. The `EventType` enum in `src/references/enums.rs` holds the type value. The tool stores every field in the database. Other file formats reference event IDs. -The system supports complex event sequences: +### Event chains -- **Linear Progression**: Event A → Event B → Event C -- **Conditional Branching**: Different paths based on success/failure -- **Parallel Events**: Multiple independent event chains -- **Repeating Events**: Limited or unlimited execution cycles +- Linear progression: Event A → Event B → Event C +- Conditional branching: paths based on a prerequisite state +- Parallel events: independent event chains +- Repeated events: limited or unlimited execution cycles ### Notes -- File uses Windows-style line endings (`\r\n`) -- Comments provide detailed explanations -- Event system forms core of game progression mechanics -- Integrated with multiple game subsystems +- The file uses Windows-style line endings (`\r\n`). +- The comment header defines the type codes. +- Event IDs link to other file formats. ## Extractor -The file is parsed by the `Event` struct in `src/references/event_ini.rs`, which implements the `Extractor` trait. +The `Event` struct in `src/references/event_ini.rs` parses the file. It implements the `Extractor` trait. -### How to Run +### How to run ```bash # Extract Event.ini to JSON diff --git a/docs/files/Extra.ini.md b/docs/files/Extra.ini.md index 5685a319..0d51ef41 100644 --- a/docs/files/Extra.ini.md +++ b/docs/files/Extra.ini.md @@ -1,21 +1,18 @@ -# Extra.ini Documentation +# Extra.ini documentation -> **DISPEL®** is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - -## File Information +## File information ### Overview -Text file that defines interactive-object definitions with visual assets, activation-frame settings, and descriptions. +The tool reads `Extra.ini` as a CSV file with comments. Each row defines an interactive object with a sprite filename, an activation-frame mode and a description. -### File Structure +### File structure -**Location**: `Extra.ini` -**Encoding**: EUC-KR (Korean character encoding) -**Format**: CSV (Comma-Separated Values) with comments +- **Location**: `Extra.ini` +- **Encoding**: EUC-KR (Korean character encoding) +- **Format**: CSV (Comma-Separated Values) with comments -### Format Specification +### Format specification ```ini ; Comment line explaining field structure @@ -26,7 +23,7 @@ id,sprite_filename,activation_sprite_frame_mode,description ... ``` -### Field Definitions +### Field definitions | Field | Type | Description | |------------------------------|--------|---------------------------------------------------------------------------------------------------------------| @@ -35,19 +32,17 @@ id,sprite_filename,activation_sprite_frame_mode,description | activation_sprite_frame_mode | i32 | Selects the sprite frame used after activation for the object handlers that use this setting. | | description | string | Editor-facing description or "null". This column is not loaded by the game into its runtime definition table. | -### Activation-Frame Mode -Every placed instance using the definition carries a copy of this field. For -object handlers 5, 6, and 8, values greater than `1` choose activated sprite -frame `1`; values `0` and `1` choose frame `0`. Observed files contain `0`, -`1`, and `2`, so this field is not a boolean or a quest flag. +### Activation-frame mode + +The placement records in `Ext*.ref` carry a copy of this value. For object handlers 5, 6 and 8, values greater than `1` select sprite frame `1`. Values `0` and `1` select frame `0`. Observed files contain `0`, `1` and `2`. -### Text-Format Details +### Text-format details -- **"null"**: Literal string indicating no sprite or description -- **;**: Lines starting with semicolon are comments -- **Empty lines**: Ignored during processing +- **"null"**: The tool reads this string when no sprite or description is present. +- **`;`**: Lines starting with this mark are comments. +- **Empty lines**: The parser ignores them. -### Example Format +### Example format ```ini ; Default entry @@ -62,28 +57,25 @@ frame `1`; values `0` and `1` choose frame `0`. Observed files contain `0`, 11,unique.spr,1,Interactive object ``` -### Technical Details +### Technical details **Encoding**: EUC-KR (Extended Unix Code Korea) -- Supports Korean characters in descriptions -- Requires proper encoding handling for reading/writing +- The encoding covers Korean characters in descriptions. +- The reader and writer must use this encoding. -**File Processing**: +**File processing:** -- Comments (lines starting with ";") are ignored -- Empty lines are skipped -- CSV format with comma delimiter -- "null" literal used for missing fields +- The parser ignores comment lines that start with `;`. +- It skips empty lines. +- It splits rows on commas. +- It reads `null` as a missing field. -### Database Integration +### Database integration -- Processed by the `Extra` struct in `src/references/extra_ini.rs` -- Stored in database with all field mappings -- Linked to object placement files (Ext*.ref) -- Referenced by interaction and puzzle systems +The `Extra` struct in `src/references/extra_ini.rs` parses the file. The tool stores every field in the database. Object placement files (`Ext*.ref`) reference these IDs. -### Object Type System +### Object type system The codebase defines the structure for interactive objects: @@ -98,23 +90,23 @@ pub struct Extra { ### Usage -1. **Environment Interaction**: Defines objects players can interact with -2. **Visual Mapping**: Links object IDs to sprite files -3. **Activation visuals**: Selects an activated sprite frame for supported object handlers -4. **Puzzle Systems**: Objects used in environmental puzzles -5. **Map Placement**: Referenced by Ext*.ref placement files +1. The tool defines objects with an ID and a sprite filename. +2. It links object IDs to sprite files. +3. It selects an activated sprite frame for supported handlers. +4. Environmental puzzles can use these objects. +5. `Ext*.ref` placement files reference the IDs. ### Notes -- File uses Windows-style line endings (`\r\n`) -- Descriptions use EUC-KR encoding for international characters -- Integrated with map placement and interaction systems +- The file uses Windows-style line endings (`\r\n`). +- Descriptions use EUC-KR encoding for international characters. +- The tool links these definitions to map placement files. ## Extractor -The file is parsed by the `Extra` struct in `src/references/extra_ini.rs`, which implements the `Extractor` trait. +The `Extra` struct in `src/references/extra_ini.rs` parses the file. It implements the `Extractor` trait. -### How to Run +### How to run ```bash # Extract Extra.ini to JSON diff --git a/docs/files/Npc.ini.md b/docs/files/Npc.ini.md index 920337e1..6bc2d78e 100644 --- a/docs/files/Npc.ini.md +++ b/docs/files/Npc.ini.md @@ -1,21 +1,18 @@ -# Npc.ini Documentation +# Npc.ini documentation -> **DISPEL®** is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - -## File Information +## File information ### Overview -Text file that defines visual appearances and descriptions for NPC (Non-Player Character) types in the game. +The tool reads `Npc.ini` as a CSV file with comments. Each row holds a visual type ID, a sprite filename and a description. -### File Structure +### File structure -**Location**: `Npc.ini` -**Encoding**: EUC-KR (Korean character encoding) -**Format**: CSV (Comma-Separated Values) with comments +- **Location**: `Npc.ini` +- **Encoding**: EUC-KR (Korean character encoding) +- **Format**: CSV (Comma-Separated Values) with comments -### Format Specification +### Format specification ```ini ; Comment line @@ -25,7 +22,7 @@ id,sprite_filename,description ... ``` -### Field Definitions +### Field definitions | Field | Type | Description | |-----------------|--------|--------------------------------------------------| @@ -33,13 +30,13 @@ id,sprite_filename,description | sprite_filename | string | SPR filename or "null" for no sprite | | description | string | NPC role/appearance description (EUC-KR encoded) | -### Special Values +### Special values -- `null`: Literal string indicating no sprite filename -- `;`: Lines starting with semicolon are comments -- Empty lines are ignored +- `null`: The tool reads this string when no sprite filename is present. +- `;`: Lines starting with a semicolon are comments. +- Empty lines: The parser ignores them. -### Example Entries +### Example entries ```ini ; Party members @@ -55,40 +52,39 @@ id,sprite_filename,description 17,King2.spr,Royal Guard ``` -### Technical Details +### Technical details **Encoding**: EUC-KR (Extended Unix Code Korea) -- Supports Korean characters used in descriptions -- Requires proper encoding handling for reading/writing +- The encoding covers Korean characters in descriptions. +- The reader and writer must use this encoding. -**File Processing**: +**File processing:** -- Comments (lines starting with ";") are ignored -- Empty lines are skipped -- CSV format with comma delimiter -- "null" literal used for missing sprite filenames +- The parser ignores comment lines that start with `;`. +- It skips empty lines. +- It splits rows on commas. +- It reads `null` as a missing sprite filename. ### Usage -1. Game loads NPC definitions from Npc.ini -2. Links NPC visual types to behavior scripts -3. Renders NPCs using specified sprite files -4. Displays descriptions in appropriate contexts -5. Manages NPC interactions based on type +1. The tool reads NPC definitions from `Npc.ini`. +2. It links visual type IDs to sprite files. +3. It stores each description with its ID. +4. Other file formats reference these IDs. ### Notes -- Some entries have "null" sprite filenames when no visual is needed -- Descriptions are in Korean (EUC-KR encoding) -- File uses Windows-style line endings (`\r\n`) -- IDs may have gaps in the sequence +- Some entries have a `null` sprite filename. +- Descriptions are in Korean and use EUC-KR encoding. +- The file uses Windows-style line endings (`\r\n`). +- IDs may have gaps in the sequence. ## Extractor -The file is parsed by the `NpcIni` struct in `src/references/npc_ini.rs`, which implements the `Extractor` trait. +The `NpcIni` struct in `src/references/npc_ini.rs` parses the file. It implements the `Extractor` trait. -### How to Run +### How to run ```bash # Extract Npc.ini to JSON diff --git a/docs/files/Save.ifo.md b/docs/files/Save.ifo.md index 7348c421..8fed629d 100644 --- a/docs/files/Save.ifo.md +++ b/docs/files/Save.ifo.md @@ -1,20 +1,14 @@ # Save.ifo -> **DISPEL®** is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - ## Purpose -`Save.ifo` is the save-slot metadata index. It describes the six save slots (`0.sav` … `5.sav`): whether each slot is -occupied and when it was last written. It also snapshots a small amount of global state needed to resume the session -from the `game.tmp` append-log. +`Save.ifo` is the save-slot metadata index. It describes six save slots (`0.sav` … `5.sav`). It records a timestamp and an occupied flag for each slot. It also holds a small global tail. -## File Structure +## File structure - **Location**: `Save.ifo` (game root directory) - **Encoding**: binary, little-endian -- **Format**: fixed size of 224 bytes — six 32-byte slot records followed by a 32-byte global tail, addressed as two - blocks: bytes 0–191 (slots) and 192–223 (tail). +- **Format**: fixed size of 224 bytes with six 32-byte slot records followed by a 32-byte global tail. The tool addresses two blocks: bytes 0–191 for slots and 192–223 for the tail. ### Slot records (offsets 0–191, record *p* at *p* × 32) @@ -42,10 +36,8 @@ from the `game.tmp` append-log. ## Usage -Written on every save alongside the `%d.sav` payload file. The save/load menu reads it at startup and lists each -occupied slot as `MM / DD HH : MM`. The tail snapshots the state needed to traverse the current session's payloads -inside the `game.tmp` append-log. +The tool reads and writes this file alongside the `%d.sav` payload files. Each occupied slot carries month, day, hour and minute values. The documented display format is `MM / DD HH : MM`. The tool preserves the tail values. ## Parser -The Rust parser is in `src/references/save_ifo.rs` (`SaveIfo` / `SaveSlotInfo` structs, `Extractor` trait). +The Rust parser is in `src/references/save_ifo.rs`. It defines the `SaveIfo` and `SaveSlotInfo` structs and implements the `Extractor` trait. diff --git a/docs/files/SaveFile.md b/docs/files/SaveFile.md index eb9a4a36..1324204c 100644 --- a/docs/files/SaveFile.md +++ b/docs/files/SaveFile.md @@ -1,8 +1,5 @@ # Save File Documentation -> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - ## File Information - **Location**: `Dispel/Save/` directory (relative to game installation directory) @@ -10,13 +7,11 @@ - **Format**: Binary (little-endian) - **Extension**: `.sav` (or similar save file extension) -The save file is a binary serialization of the player's game state, including character stats, inventory, party members, -journal entries, and map-specific data. +The tool reads and writes data files that you supply. This file holds character stats, inventory, party members, journal entries and map-specific data. All integers use little-endian byte order. ## Structure -The save file is parsed sequentially from start to end. The top-level structure is defined by the `SaveFile` struct in -`src/references/save_file/mod.rs`. +The tool reads the file from start to end. The `SaveFile` struct in `src/references/save_file/mod.rs` defines the top-level layout. ### Top-Level Layout @@ -43,15 +38,11 @@ The save file is parsed sequentially from start to end. The top-level structure ### Header -The first 8 bytes contain: - -1. `game_tmp_blob_size` (4 bytes, `u32`): A jump address pointing to the byte offset after all map data. The reader uses - this to seek past the map sections if needed. -2. `number_of_visited_maps` (4 bytes, `u32`): The number of `MapSectionData` records that follow. +The first 8 bytes hold two values. `game_tmp_blob_size` is a 4-byte `u32`. It gives the byte offset after all map data. The reader can seek to that offset. `number_of_visited_maps` is a 4-byte `u32`. It gives the count of `MapSectionData` records that follow. ### Map Sections (`maps`) -Each visited map is serialized as a `MapSectionData` record containing: +Each visited map uses a `MapSectionData` record with these fields: | Field | Type | Description | |-------------------------|---------------------------|-------------------------------------------------------------| @@ -66,14 +57,13 @@ Each visited map is serialized as a `MapSectionData` record containing: | `draw_items_misc` | `Vec` | Ground items — Misc type (268 bytes each) | | `draw_items_event` | `Vec` | Ground items — Event type (252 bytes each) | -Each collection is prefixed with a count (`u32` for monsters/NPCs/extra objects, `u16` for ground items). +A count precedes each collection. It uses `u32` for monsters, NPCs and extra objects. It uses `u16` for ground items. -Each ground-item record ends with a one-based `u16` ground-object ID and two preserved padding bytes. The item category -determines the ID range used by the game. +Each ground-item record ends with a one-based `u16` ground-object ID and two preserved padding bytes. The item category sets the ID range. An NPC record stores an active path-step direction at byte 161 and its animation frame at byte 162. The direction values are `0=(0,+32)`, `1=(-32,+16)`, `2=(-64,0)`, `3=(-32,-16)`, -`4=(0,-32)`, `5=(+32,-16)`, `6=(+64,0)`, `7=(+32,+16)`, and `255=inactive`. The pairs are screen-space offsets from the +`4=(0,-32)`, `5=(+32,-16)`, `6=(+64,0)`, `7=(+32,+16)`, and `255=inactive`. The pairs give screen-space offsets from the destination cell. Monster runtime data includes the current combat target, timed status-effect type and duration, movement-animation frame @@ -81,9 +71,7 @@ and offsets, path-buffer length and index, and temporary visual effects. Tempora and duration fields for status, ground, special-attack, guard, blood, and timed-overlay effects. Blood-effect directions use values `0..=7`. -The monster status-effect type uses `0=none`; observed active values are `1`, -`2`, `3`, `4`, `7`, and `12`. Its parameter is `-1` when unused. Type `3` -stores a monster identifier in the parameter field. +The monster status-effect type uses `0=none`. Observed active values are `1`, `2`, `3`, `4`, `7` and `12`. Its parameter is `-1` when unused. Type `3` stores a monster identifier in the parameter field. NPC runtime flags use these values: @@ -94,17 +82,13 @@ NPC runtime flags use these values: - `player_interaction_latched`: `0=not interacting`, `1=interaction started`. - `start_dialogue_on_arrival`: `0=normal arrival`, `1=start arrival dialogue`. -The arrival dialogue ID follows the arrival-action flag. Two intervening runtime words are reserved, initialized to -zero, and preserved without interpretation. +The arrival dialogue ID follows the arrival-action flag. The tool reserves two intervening runtime words. They are zero in known files. It preserves them. -An extra-object record begins with its selected render state, render variant, and current sprite frame. It ends with the -activation effect ID, one reserved byte, two padding bytes, the overlay flag, the map-active flag, and the pending -interaction latch. Boolean controls use `0=disabled` and non-zero `enabled`; the pending latch uses `0=no request` and -`1=activation requested`. +An extra-object record starts with its selected render state, render variant and current sprite frame. It ends with the activation effect ID, one reserved byte, two padding bytes, the overlay flag, the map-active flag and the pending interaction latch. Boolean controls use `0=disabled` and non-zero `enabled`. The pending latch uses `0=no request` and `1=activation requested`. ### Post-Maps Data (`post_maps`) -Contains save-world header values and the list of visited map IDs: +The section holds save-world header values and a list of visited map IDs: | Field | Type | Description | |--------------------------------|------------|--------------------------------------------------------------------------------------------------| @@ -120,13 +104,11 @@ Contains save-world header values and the list of visited map IDs: | `number_of_visited_maps` | `u32` | Number of visited maps (must match the map section count) | | `map_ids` | `Vec` | IDs of the visited maps | -The two map identifiers address different tables. `all_map_ini_id` selects the map itself. `ref_map_ini_id` selects the -route or entrance used to initialize that map. Multiple `Ref/Map.ini` records can target the same `AllMap.ini` map while -providing different spawn coordinates. +The two map identifiers address different tables. `all_map_ini_id` refers to the map entry in `AllMap.ini`. `ref_map_ini_id` refers to an entrance record in `Ref/Map.ini`. Several `Ref/Map.ini` records can share one `AllMap.ini` ID with different spawn coordinates. ### Map Viewport State (`map_viewport_state`) -A fixed-size (10,148 bytes) serialized state of the game's isometric map viewport: +A fixed-size block of 10,148 bytes with these fields: | Field | Type | Description | |--------------------------------|-------------------------|-------------------------------------------------------------------------------------------------------------------------------------| @@ -240,9 +222,7 @@ Four fixed-size (60-byte) null-terminated WINDOWS-1250 strings representing char | `player_class_name` | String (20 bytes) | Player class name (WINDOWS-1250, null-terminated) | | `selected_spell_ui_index` | `u16` | UI index of selected spell | -**Note**: The full identity block in the save file is larger than 35 bytes. The `CharacterIdentity::read_from` method -skips over many runtime fields (inventory serial counters, waypoint data, movement state, pathfinding scratch, etc.) and -only retains the trailing 35 bytes. +**Note**: The full identity block in the save file is larger than 35 bytes. The `CharacterIdentity::read_from` method skips many runtime fields. These include inventory serial counters, waypoint data, movement state and pathfinding scratch. It keeps the trailing 35 bytes. ### Inventory Data (`inventory`) @@ -256,9 +236,7 @@ Raw inventory data for 5 item categories, each prefixed with a `u16` count: | Weapon items | 292 bytes | Weapon-type items | | Heal items | 256 bytes | Heal-type items | -Each item record contains a copy of its database definition followed by save-runtime fields. The runtime category is -zero-based: `0`=weapon, `1`=heal, `2`=edit, -`3`=misc, and `4`=event. This numbering differs from the one-based item type used by some map and object files. +Each item record holds a copy of its database definition followed by save-runtime fields. The runtime category uses zero-based values: `0` for weapon, `1` for heal, `2` for edit, `3` for misc and `4` for event. Other map and object files use one-based item types. | Category | Runtime fields after/copied into the definition | |----------|--------------------------------------------------------------------------------------------| @@ -268,9 +246,7 @@ zero-based: `0`=weapon, `1`=heal, `2`=edit, | Weapon | Category, global inventory-instance ID | | Heal | Reserved definition byte, category, category-local record index, two runtime scratch bytes | -The global inventory-instance ID connects a weapon to equipped slots and connects weapon or miscellaneous items to -inventory placement cells. Heal runtime scratch bytes are normally zero, but saved games show that they are not -initialized consistently. +The global inventory-instance ID links a weapon to equipped slots. It links weapon and miscellaneous items to inventory placement cells. Heal runtime scratch bytes are usually zero. Some saved games store other values. ### Inventory Slots (`inventory_slots`) @@ -284,7 +260,7 @@ initialized consistently. ### Learned Spells (`learned_spells`) -41 bytes, one byte per spell, indicating whether each spell has been learned. +The block holds 41 bytes, one byte per spell. A byte holds the learned state of one spell. ### Party Members (`party_members`) @@ -295,11 +271,7 @@ Variable-length records, each consisting of: - An optional 52-byte combat snapshot (48 bytes + 4-byte terminator), present when the companion has an active combat object -The 300-byte payload is a serialized stream of overlapping four-byte runtime snapshots. Adjacent snapshots frequently -begin one or two bytes apart. As a result, the stream repeats parts of health, mana, class, level, spell IDs, animation -flags, coordinates, and other fields. The parser exposes the primary values and preserves each repeated snapshot tail or -overlap under an explicit -`*_snapshot_tail` or `*_snapshot_overlap` name. +The 300-byte payload holds overlapping four-byte runtime snapshots. Adjacent snapshots often start one or two bytes apart. The stream repeats parts of health, mana, class, level, spell IDs, animation flags, coordinates and other fields. The parser exposes the primary values. It preserves each repeated snapshot tail or overlap under a `*_snapshot_tail` or `*_snapshot_overlap` name. ### Events (`events`) @@ -336,8 +308,7 @@ Each dismissed-companion progression record contains three bytes: | `companion_level` | `u8` | Companion level when the progression was retained | | `player_level` | `u8` | Player level when the progression was retained | -Milestone records are written at walk animation milestones (walk progress reaching `path_length - 2`, or the walk frame -counter reaching 4). Completion records are written when a walk cycle finishes. +The tool writes milestone records at walk animation milestones. These occur when walk progress reaches `path_length - 2` or the walk frame counter reaches 4. It writes completion records when a walk cycle finishes. #### Walk Milestone Record (24 bytes) @@ -404,8 +375,7 @@ counter reaching 4). Completion records are written when a walk cycle finishes. ## Binary Record Macro -Several structs in this module use the `#[derive(BinaryRecord)]` macro from `dispel-macros`, which generates `parse` and -`write` methods for binary serialization. The `#[binary_record(...)]` attribute controls field encoding, including: +Several structs in this module use the `#[derive(BinaryRecord)]` macro from `dispel-macros`. The macro generates `parse` and `write` methods for binary serialization. The `#[binary_record(...)]` attribute controls field encoding: - `string(encoding = "WINDOWS-1250", size = N)`: Fixed-size null-terminated string - `size = N`: Fixed-size byte array @@ -413,19 +383,16 @@ Several structs in this module use the `#[derive(BinaryRecord)]` macro from `dis ## Validation -The writer performs preflight validation before serializing: +The writer runs preflight validation before it writes bytes. It checks these rules: -1. **Count limits**: All collection counts must fit in their wire types (`u16` or `u32`) -2. **Fixed collection lengths**: Sprite paths (4), learned spells (41), events (2,251), journal entries (100 per - section), map viewport cells (500) -3. **Cross-field consistency**: Visited-map count must match map section count and map ID count; party member count must - match the stored count -4. **Trailer size validation**: Map extra-object trailer size must match the computed expected size +1. Count limits: Each collection count must fit its wire type (`u16` or `u32`). +2. Fixed collection lengths: Sprite paths use 4 entries, learned spells 41, events 2,251, journal entries 100 per section and map viewport cells 500. +3. Cross-field consistency: The visited-map count must match the map section count and map ID count. The party member count must match the stored count. +4. Trailer size: The map extra-object trailer size must match the computed expected size. ## Extractor -The save file format is parsed by the `SaveFile` struct in `src/references/save_file/mod.rs`, which implements the -`Extractor` trait. +The `SaveFile` struct in `src/references/save_file/mod.rs` parses the file. It implements the `Extractor` trait. ### How to Run @@ -439,7 +406,7 @@ cargo run -- database import "fixtures/Dispel/" "database.sqlite" ## Purpose -This file stores the complete player game state, including: +The file holds these values: 1. Character progression (stats, level, XP, gold) 2. Inventory and equipment @@ -449,34 +416,16 @@ This file stores the complete player game state, including: 6. Event script flags 7. Isometric viewport state -## Legal Notice - -⚠️ **DISCLAIMER**: This documentation describes technical file format specifications only. It does not distribute any -copyrighted game content, save data, or proprietary assets. All references to save file structures are for **independent -interoperability research based on observable behavior** to document file organization and data structures, without -circumvention of technological protection measures. - -**DISPEL®** is a registered trademark. This documentation is **not affiliated with, endorsed by, or sponsored by** the -trademark owner. - -### Legal Compliance - -This documentation: +## Scope -- Describes **file format specifications only** -- Does **not** distribute any save data or game content -- Focuses on **technical organization**, not creative content -- Uses **generic descriptions** of file purposes -- Maintains **nominative use** for trademark references +The tool reads and writes data files that you supply. This document lists the file layout and field values. ## Notes -- All integers are little-endian -- Text fields use WINDOWS-1250 encoding -- The `game_tmp_blob_size` field in the header acts as a jump address; the reader seeks to this offset after parsing map - sections -- The `CharacterIdentity` struct only retains the trailing 35 bytes of the full identity block, skipping many runtime - fields -- Party member records have an optional combat snapshot that is conditionally present based on a marker value -- Reserved runtime and header fields are preserved verbatim for round-trip fidelity. -- The writer validates all fixed-size constraints before serialization to prevent corrupt output +- All integers are little-endian. +- Text fields use WINDOWS-1250 encoding. +- The `game_tmp_blob_size` field holds a jump address. The reader seeks to this offset after it parses the map sections. +- The `CharacterIdentity` struct retains the trailing 35 bytes of the identity block. It skips many runtime fields. +- Party member records can include a combat snapshot. A marker value controls its presence. +- The tool preserves reserved runtime and header fields for round-trip fidelity. +- The writer validates all fixed-size constraints before it writes output. diff --git a/docs/files/Sprites.spr.md b/docs/files/Sprites.spr.md index 3d0bc8bb..7be8f3ae 100644 --- a/docs/files/Sprites.spr.md +++ b/docs/files/Sprites.spr.md @@ -1,12 +1,9 @@ -# *.spr — Sprite File Format - -> **DISPEL®** is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. +# *.spr: sprite file format ## Scope -This document describes the `.spr` layout that this project reads and writes. -All integer values use little-endian byte order. +The tool reads and writes `.spr` files with this layout. All integer values use +little-endian byte order. ## File Summary diff --git a/docs/files/Wave.ini.md b/docs/files/Wave.ini.md index 0db73cad..a68e6d84 100644 --- a/docs/files/Wave.ini.md +++ b/docs/files/Wave.ini.md @@ -1,13 +1,10 @@ # Wave.ini -> **DISPEL®** is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - ## Purpose `Wave.ini` maps a sound identifier to an SNF filename and a simultaneous-playback limit. -## File Structure +## File structure - **Location**: `Wave.ini` - **Encoding**: EUC-KR @@ -25,18 +22,10 @@ | `snf_filename` | string or `null` | Referenced SNF filename. | | `max_simultaneous_plays` | `i32` | Maximum concurrent instances of this sound. | -## Runtime Behavior - -The loader creates `max_simultaneous_plays` audio-buffer copies for each entry. Playback uses a free copy. - -A limit of one prevents a sound from overlapping with itself. Larger limits allow concurrent playback. +## Field values -This value is not a priority, channel, or loop flag. +A value of `1` records one concurrent instance. Larger values record more concurrent instances. The field is not a priority, channel or loop flag. ## Parser -The Rust parser is in `src/references/wave_ini.rs` (`WaveIni` struct, `Extractor` trait). - -## Legal Notice - -This document describes a file format. It contains no game records, asset names, or other game-content data. +The Rust parser is in `src/references/wave_ini.rs`. It defines the `WaveIni` struct and implements the `Extractor` trait. From a98ad5a47b2b249a13100f85a7e5fb042f07d1d7 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:45:28 +0100 Subject: [PATCH 05/72] docs: rewrite fourteen format documents in plain English --- docs/files/CROSS_REFERENCES.md | 2 +- docs/files/CharacterInGame/ChData.db.md | 29 ++++++-------- docs/files/CharacterInGame/EditItem.db.md | 13 +------ docs/files/CharacterInGame/EventItem.db.md | 18 ++++----- docs/files/CharacterInGame/HealItem.db.md | 11 ++---- docs/files/CharacterInGame/MiscItem.db.md | 17 ++++---- docs/files/CharacterInGame/Monster.ini.md | 35 ++++++++--------- docs/files/CharacterInGame/Store.db.md | 41 +++++++++----------- docs/files/CharacterInGame/WeaponItem.db.md | 11 +----- docs/files/MagicInGame/Magic.db.md | 22 +++++------ docs/files/MonsterInGame/MondunMonmap.ref.md | 32 +++++++-------- docs/files/MonsterInGame/Monster.db.md | 38 ++++++++---------- docs/files/Ref/DrawItem.db.md | 5 --- docs/files/Ref/Map.ini.md | 28 ++++++------- docs/files/Ref/PartyRef.ref.md | 40 +++++++++---------- 15 files changed, 138 insertions(+), 204 deletions(-) diff --git a/docs/files/CROSS_REFERENCES.md b/docs/files/CROSS_REFERENCES.md index 2a821570..4bbfd287 100644 --- a/docs/files/CROSS_REFERENCES.md +++ b/docs/files/CROSS_REFERENCES.md @@ -451,7 +451,7 @@ cargo run -- map render --map "file.map" --btl "file.btl" --gtl "file.gtl" --out cargo run -- map sprites "path/to/file.map" # Convert audio -cargo run -- sound "path/to/file.snf" "output.wav" +cargo run -- sound to-wav "path/to/file.snf" "output.wav" # Import to SQLite database cargo run -- database import "path/to/Dispel/" "database.sqlite" diff --git a/docs/files/CharacterInGame/ChData.db.md b/docs/files/CharacterInGame/ChData.db.md index 64ea3d15..236cbcb5 100644 --- a/docs/files/CharacterInGame/ChData.db.md +++ b/docs/files/CharacterInGame/ChData.db.md @@ -1,7 +1,4 @@ -# ChData.db - Character Initial Attributes - -> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. +# ChData.db: character initial attributes ## File Information @@ -18,7 +15,7 @@ ### Class Base Attributes (32 bytes) -16 × `i16` — Base attributes (STR, CON, WIS, AGI) for each of 4 classes: +The tool reads 16 `i16` base attributes: STR, CON, WIS and AGI for each of 4 classes. | Offset | Class | Fields (each i16) | |--------|---------|--------------------| @@ -29,12 +26,11 @@ ### Reserved (2 bytes) -- `reserved_stat`: i16 — Separator between base stats and extra points (purpose unknown) +- `reserved_stat`: i16 between the base stats and the extra points. Purpose unknown. ### Derived Stat Bonuses (20 bytes) -5 × `i32` — per-class derived-stat bonuses applied at character creation. Only the low byte of each is significant -(values are small, e.g. 5). Each bonus is added to a derived combat stat: +The tool reads 5 `i32` derived-stat bonuses, one per class. Known files store small values such as 5. Only the low byte of each value carries meaning. | Offset | Class | Field | Derived stat | Base attr | |--------|---------|------------------------|--------------|-----------| @@ -44,7 +40,7 @@ | 76 | Archer | archer_hit_bonus | hit_rate | CON | | 80 | Mage | mage_magic_power_bonus | magic_power | WIS | -> Points-per-level is hardcoded to 5 in the game and is NOT read from this file. +> The tool does not read a points-per-level value from this file. The documented value is 5. ## Field Details @@ -52,7 +48,7 @@ - 30-byte WINDOWS-1250 encoded string - Starts with "Item" magic signature -- Otherwise unused by the game +- The tool treats this field as unused. ### Class Attributes (warrior_strength through mage_agility) @@ -63,16 +59,15 @@ ### reserved_stat - i16 between class attributes and extra points -- Value in the game appears to be ignored +- Known files store zero at this offset. ### Derived Stat Bonuses (warrior_offense_bonus through mage_magic_power_bonus) -- 5 × i32 — per-class derived-stat bonuses. Each is added to a derived combat stat (offense, defense, dodge_rate, - hit_rate, magic_power) for the corresponding class. +- The tool reads 5 `i32` derived-stat bonuses. Each maps to a derived combat stat: offense, defense, dodge_rate, hit_rate or magic_power. ### mage_magic_power_bonus -- i32 — Mage class bonus added to magic_power (WIS-derived). +- i32 value for the Mage bonus to magic_power, which uses WIS. ## Example Usage @@ -139,10 +134,10 @@ Bytes 80-83: mage_magic_power_bonus (i32) ### Data Types -- `unused_name`: [u8; 30] WINDOWS-1250 -- Class attributes: [i16; 16] +- `unused_name`: `[u8; 30]` WINDOWS-1250 +- Class attributes: `[i16; 16]` - `reserved_stat`: i16 -- Derived stat bonuses: [i32; 4] +- Derived stat bonuses: `[i32; 4]` - Mage magic power bonus: i32 ### Endianness diff --git a/docs/files/CharacterInGame/EditItem.db.md b/docs/files/CharacterInGame/EditItem.db.md index 8f7da5d7..3f67359c 100644 --- a/docs/files/CharacterInGame/EditItem.db.md +++ b/docs/files/CharacterInGame/EditItem.db.md @@ -1,10 +1,6 @@ # EditItem.db -> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - -`CharacterInGame/EditItem.db` defines consumable item-modification materials. It is a little-endian binary file with a -four-byte record count followed by fixed-size 268-byte records. Text is encoded as WINDOWS-1250. +`CharacterInGame/EditItem.db` holds consumable item-modification materials. The file is little-endian. It has a four-byte record count followed by fixed-size 268-byte records. Text uses WINDOWS-1250. ## Record layout @@ -32,12 +28,7 @@ four-byte record count followed by fixed-size 268-byte records. Text is encoded ## Runtime item ID -The four bytes at byte offset 236 are not two independent padding fields. The on-disk database stores zero there, then -the game loader overwrites the word with the zero-based record index. Inventory and ground-item records preserve that -value as `edit_item_id` to link an instance back to its database definition. - -When writing the original database, retain the stored value (normally zero). The game will assign the runtime ID when it -loads the file. +Known files store zero at byte offset 236. The tool reads those four bytes as `runtime_item_id` and writes them back unchanged. Other records keep the same value in `edit_item_id`. Keep the stored value when you write the database. ## Notes diff --git a/docs/files/CharacterInGame/EventItem.db.md b/docs/files/CharacterInGame/EventItem.db.md index a69bef0a..d8cae94b 100644 --- a/docs/files/CharacterInGame/EventItem.db.md +++ b/docs/files/CharacterInGame/EventItem.db.md @@ -1,21 +1,19 @@ # EventItem.db -> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - ## File Information ### Overview -Binary database file that defines quest and event items with names and descriptions for the game's quest progression and -event triggering system. +The tool reads `EventItem.db` as name and description records for quest and event items. ### File Structure -**Location**: `CharacterInGame/EventItem.db` -**Encoding**: Binary (Little-Endian) -**Text Encoding**: WINDOWS-1250 (Central European) -**Header**: 4-byte record count **Record Size**: 240 bytes **Total Records**: Variable (determined by header) +- **Location**: `CharacterInGame/EventItem.db` +- **Encoding**: Binary (Little-Endian) +- **Text Encoding**: WINDOWS-1250 (Central European) +- **Header**: 4-byte record count +- **Record Size**: 240 bytes +- **Total Records**: Variable (determined by header) ### Binary Format @@ -91,7 +89,7 @@ Offset | Size | Field | Description - File uses binary format with WINDOWS-1250 text encoding - Simple name/description/price structure for quest items - Fixed record size enables efficient parsing -- Integrated with quest progression systems +- Other files reference these item IDs. ## Extractor diff --git a/docs/files/CharacterInGame/HealItem.db.md b/docs/files/CharacterInGame/HealItem.db.md index cc7319ac..387115a0 100644 --- a/docs/files/CharacterInGame/HealItem.db.md +++ b/docs/files/CharacterInGame/HealItem.db.md @@ -1,11 +1,8 @@ # HealItem.db -> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - ## Purpose -`HealItem.db` stores fixed-size definitions for consumable items that restore health or mana and cure status effects. +The tool reads `HealItem.db` as fixed-size definitions for items that restore health or mana and cure status effects. ## File Structure @@ -31,9 +28,9 @@ | 248 | 1 | `cures_polymorph` | flag | Polymorph cure. | | 249 | 3 | `reserved_trailer` | bytes | Preserved opaque data. Unused. | -## Runtime Behavior +## Field values -The loader replaces `runtime_item_index_slot` with the sequential record index. Do not use this field as item data. +Known files store zero in `runtime_item_index_slot`. The tool reads the word and writes it back unchanged. Do not use this field as item data. Each effect flag uses `HealItemFlag`. `0` disables the effect. `1` enables the effect. @@ -41,6 +38,4 @@ Each effect flag uses `HealItemFlag`. `0` disables the effect. `1` enables the e The Rust parser is [heal_item_db.rs](../../../src/references/heal_item_db.rs). -## Legal Notice -This document describes a file format. It contains no game records, asset names, or other game-content data. diff --git a/docs/files/CharacterInGame/MiscItem.db.md b/docs/files/CharacterInGame/MiscItem.db.md index 4857f0ad..703980c2 100644 --- a/docs/files/CharacterInGame/MiscItem.db.md +++ b/docs/files/CharacterInGame/MiscItem.db.md @@ -1,22 +1,19 @@ # MiscItem.db -> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - ## File Information ### Overview -Binary database file that defines generic miscellaneous items with names, descriptions, and economic values for the -game's crafting, inventory, and utility systems. +The tool reads `MiscItem.db` as name, description and price records for miscellaneous items. ### File Structure -**Location**: `CharacterInGame/MiscItem.db` -**Encoding**: Binary (Little-Endian) -**Text Encodings**: Mixed (WINDOWS-1250 and EUC-KR) -**Header**: 4-byte record count **Record Size**: 256 bytes (64 × 4-byte fields) -**Total Records**: Variable (determined by header) +- **Location**: `CharacterInGame/MiscItem.db` +- **Encoding**: Binary (Little-Endian) +- **Text Encodings**: Mixed (WINDOWS-1250 and EUC-KR) +- **Header**: 4-byte record count +- **Record Size**: 256 bytes (64 × 4-byte fields) +- **Total Records**: Variable (determined by header) ### Binary Format diff --git a/docs/files/CharacterInGame/Monster.ini.md b/docs/files/CharacterInGame/Monster.ini.md index 3ce0545d..e5dab941 100644 --- a/docs/files/CharacterInGame/Monster.ini.md +++ b/docs/files/CharacterInGame/Monster.ini.md @@ -1,13 +1,10 @@ # Monster.ini -> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - ## File Information ### Overview -Text file that defines monster visual appearances and animation sequences for the game's monster rendering system. +The tool reads `Monster.ini` as a CSV file with comments. Each row holds a visual type ID, a name, a sprite filename and five animation sequence IDs. ### File Structure @@ -67,21 +64,21 @@ The file organizes monsters into logical groups based on the comment header: **Combat Animations:** -- `attack_seq`: Attacking/offensive animations +- `attack_seq`: attack animations - `hit_seq`: Damage/taking hit animations - `death_seq`: Death/dying animations **Movement Animations:** -- `walk_seq`: Walking/movement animations -- `cast_seq`: Spellcasting/magic animations +- `walk_seq`: movement animations +- `cast_seq`: magic animations ### Special Values - **"null"**: Literal string indicating no name or sprite - **0**: Unused animation sequence (no animation) - **-1**: Special or alternative animation sequence -- **;**: Lines starting with semicolon are comments +- **`;`**: Lines starting with this mark are comments. - **Empty lines**: Ignored during processing ### Example Format @@ -107,8 +104,8 @@ The file organizes monsters into logical groups based on the comment header: **File Processing**: -- Comments (lines starting with ";") are ignored -- Empty lines are skipped +- The parser ignores comments that start with `;`. +- The parser skips empty lines. - CSV format with comma delimiter - "null" literal used for missing name/sprite fields @@ -116,8 +113,8 @@ The file organizes monsters into logical groups based on the comment header: - Processed by `MonsterIni` struct in the codebase - Stored in database with all field mappings -- Linked to monster placement files (mondun*.ref, monmap*.ref) -- Referenced by combat and rendering systems +- Monster placement files (`mondun*.ref`, `monmap*.ref`) use these IDs. +- Other file formats reference these IDs. ### Animation Sequence System @@ -136,20 +133,20 @@ pub struct MonsterIni { } ``` -### Usage in Game +### File use -1. **Monster Rendering**: Game loads visual definitions from Monster.ini -2. **Animation Mapping**: Links monster IDs to animation sequences -3. **Combat System**: Uses attack/hit/death animations during battles -4. **Movement System**: Applies walking animations during navigation -5. **Magic System**: Triggers casting animations for spellcasters +1. The tool reads visual definitions from `Monster.ini`. +2. It links monster IDs to animation sequence IDs. +3. It stores the attack, hit and death sequence IDs. +4. It stores the walking sequence ID. +5. It stores the casting sequence ID. ### Notes - File uses Windows-style line endings (\r\n) - Comments are in Polish (WINDOWS-1250 encoding) - Animation sequences link to SPR file frame indices -- Integrated with monster placement and combat systems +- Other file formats link to these IDs. ## Extractor diff --git a/docs/files/CharacterInGame/Store.db.md b/docs/files/CharacterInGame/Store.db.md index 26b74a51..814cc842 100644 --- a/docs/files/CharacterInGame/Store.db.md +++ b/docs/files/CharacterInGame/Store.db.md @@ -1,21 +1,19 @@ # Store.db -> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - ## File Information ### Overview -Binary database file that defines shops and inns with inventories, prices, merchant dialogue, and economic behavior for -the game's commerce system. +The tool reads `Store.db` as shop and inn records. Each record holds a name, a cost, product slots and text fields. ### File Structure -**Location**: `CharacterInGame/STORE.DB` -**Encoding**: Binary (Little-Endian) -**Text Encoding**: WINDOWS-1250 **Header**: 4-byte record count **Record Size**: 948 bytes **Total Records**: Variable -(determined by header) +- **Location**: `CharacterInGame/STORE.DB` +- **Encoding**: Binary (Little-Endian) +- **Text Encoding**: WINDOWS-1250 +- **Header**: 4-byte record count +- **Record Size**: 948 bytes +- **Total Records**: Variable (determined by header) ### Binary Format @@ -55,24 +53,22 @@ the game's commerce system. **Inn (inn_night_cost > 0):** -- No products (144 bytes padding) -- Provides rest/healing services -- Nightly accommodation cost -- Dialogue for innkeeper +- No products, 144 bytes of padding +- A nightly cost value +- Text fields **Shop (inn_night_cost = 0):** -- Product inventory (up to 15 items) -- Sells goods and equipment -- Price modifier affects economy -- Merchant dialogue and haggling +- Up to 15 product slots +- A price modifier +- Text fields ### Product Structure **ProductType Enum:** - **1**: Weapon - Weapons and armor -- **2**: Healing - Healing items (potions, etc.) +- **2**: potions and other healing items - **3**: EditItem - Editable/modifiable equipment - **4**: MiscItem - Miscellaneous items @@ -85,17 +81,16 @@ the game's commerce system. ### Price Modifier & Pricing Formulas -The `price_modifier` field is a signed percentage applied to an item's base price: +The tool reads `price_modifier` as a signed percentage. The documented pricing equations are: ``` buy_price = base_price + (price_modifier * base_price) / 100 sell_price = base_price/2 + (price_modifier * (base_price/2)) / 100 ``` -- **Buy price**: the player pays `base_price * (1 + price_modifier/100)`. -- **Sell price**: the shop pays the player `(base_price/2) * (1 + price_modifier/100)` - (items sell at half their base price, then the modifier is applied). -- A positive modifier raises prices (e.g. `10` → +10%); a negative modifier lowers them. +- Buy price: `base_price * (1 + price_modifier/100)`. +- Sell price: `(base_price/2) * (1 + price_modifier/100)`. The tool halves the base price before it applies the modifier. +- A positive modifier raises prices, for example `10` for +10%. A negative modifier lowers them. - A value of `0` means the shop sells at the item's unmodified base price. ### Data Structure diff --git a/docs/files/CharacterInGame/WeaponItem.db.md b/docs/files/CharacterInGame/WeaponItem.db.md index d5e92caa..f64b0e9a 100644 --- a/docs/files/CharacterInGame/WeaponItem.db.md +++ b/docs/files/CharacterInGame/WeaponItem.db.md @@ -1,8 +1,5 @@ # WeaponItem.db -> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -> owner. - `CharacterInGame/WeaponItem.db` defines weapons and armour. ## Format @@ -11,9 +8,7 @@ - Records: `record_count` fixed-size records of 284 bytes. - Text: `name` and `description` are null-padded WINDOWS-1250 strings. -The game loader reads the complete record block, then overwrites each record's -`weapon_item_id` word with its zero-based record index. The file's stored value at that offset is therefore not a stable -persistent ID. +Known files store zero at offset 236. The tool reads this word as `weapon_item_id` and writes it back unchanged. The stored value is not a stable ID. | Offset | Size | Type | Field | Meaning | |-------:|-----:|--------|--------------------|------------------------------------------------| @@ -44,6 +39,4 @@ persistent ID. | 280 | 2 | i16 | `reserved_0x118` | Reserved; zero by default | | 282 | 2 | i16 | `reserved_0x11a` | Reserved; zero by default | -The seven reserved words are serialized and copied into save-game inventory records. No observed reader touches -them, and all known records contain zero at those offsets. Preserve their values when editing; their purpose is -unknown. +The tool writes the seven reserved words into save-game inventory records. All known records contain zero at those offsets. Keep their values when you edit them. Their purpose is unknown. diff --git a/docs/files/MagicInGame/Magic.db.md b/docs/files/MagicInGame/Magic.db.md index 0889dbd7..5707d26b 100644 --- a/docs/files/MagicInGame/Magic.db.md +++ b/docs/files/MagicInGame/Magic.db.md @@ -1,7 +1,4 @@ -# Magic.db — Spell Database - -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. +# Magic.db: spell database ## File Information @@ -12,7 +9,7 @@ ## Record Structure (88 bytes) -All fields are little-endian `u32`; the record ID is its zero-based position. +All fields are little-endian `u32` values. The record ID is its zero-based position. | Offset | Field | Meaning | |-------:|--------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------| @@ -38,25 +35,24 @@ All fields are little-endian `u32`; the record ID is its zero-based position. ## Field semantics -- Effective mana cost is derived from `mana_cost` and the caster's magic type skill, clamped to a minimum of 5. -- Effective success chance is derived from `base_success_rate` and that same skill category. +- The documented mana cost combines `mana_cost` with the magic type skill. The minimum is 5. +- The documented success chance combines `base_success_rate` with the same skill category. - `cast_duration` controls the progress limit used by the casting/action state. - `effect_visual_id` selects the mapping used to create the spell visual or projectile. -- The flags at offsets 4 and 68 select the renderer's palette-blending path; clear values use direct pixel copies. +- The flags at offsets 4 and 68 select the renderer's palette-blending path. Clear values use direct pixel copies. - `effect_animation_repeats` keeps the target-effect animation alive after its last frame. -- `animation_data_index` (offset 44) is resolved to a pointer after the file is loaded. +- `animation_data_index` at offset 44 is an index into the animation data table. ## File Purpose -Defines spell combat parameters, cast timing, and visual configuration. Effect-configuration words at offsets 48–56 -retain offset-based names because their purpose has not been established. +The file holds spell parameters, cast timing and visual fields. The tool keeps offset-based names for the words at offsets 48 to 56. ## Implementation - **Rust Module**: `src/references/magic_db.rs` - **Extractor**: `MagicSpell` struct implementing `Extractor` trait -- **Data Structure**: `MagicSpell` with comprehensive spell attributes -- **Database**: Saved to SQLite via `save_magic_spells` function +- **Data Structure**: `MagicSpell` with spell attributes +- **Database**: saved to SQLite by the `save_magic_spells` function ## Example Usage diff --git a/docs/files/MonsterInGame/MondunMonmap.ref.md b/docs/files/MonsterInGame/MondunMonmap.ref.md index 952a0473..32756d43 100644 --- a/docs/files/MonsterInGame/MondunMonmap.ref.md +++ b/docs/files/MonsterInGame/MondunMonmap.ref.md @@ -1,7 +1,4 @@ -# Mondun/Monmap Files - Monster Placement References - -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. +# Mondun and Monmap files: monster placement references ## File Information @@ -9,7 +6,7 @@ - **Encoding**: Binary (Little-Endian) - **Record Size**: 56 bytes per monster entry -Binary files that define monster placements, coordinates, event triggers, and loot configurations for game maps. +The tool reads these files as monster placements. Each record holds coordinates, an event ID and loot slots. ## File Types @@ -56,7 +53,7 @@ Binary files that define monster placements, coordinates, event triggers, and lo ## Map.ini Integration -These files are referenced in `Ref/Map.ini` to associate monster placements with specific maps: +`Ref/Map.ini` names these files for each map: ``` ; Map ID, X, Y, Width, Height, MonsterFile, NPCFile, ExitFile, MapType @@ -68,14 +65,13 @@ These files are referenced in `Ref/Map.ini` to associate monster placements with ## Field Details -**monster_db_id**: Links to monster definitions in `Monster.db`. Determines monster type, stats, and appearance. +**monster_db_id**: refers to a record in `Monster.db`. **map_x, map_y**: Tile coordinates where the monster spawns on the map. **event_id_on_kill**: Links to the event triggered when the monster dies. -**loot_item_1..3**: Packed 32-bit `InventoryItem` values. The low bytes contain the item ID and type; the upper bits are -preserved when writing. +**loot_item_1..3**: packed 32-bit `InventoryItem` values. The low bytes hold the item ID and type. The tool preserves the upper bits. ## Loot System @@ -83,7 +79,7 @@ preserved when writing. - 3 loot slots per monster - Each slot has item ID and type -- Items dropped when monster is defeated +- The slots hold item IDs and types. ### Item Types @@ -92,7 +88,7 @@ preserved when writing. - `Edit` (3): Modifiable equipment - `Event` (4): Quest-related objects - `Misc` (5): Various utility items -- `NoItem` (-1, `0xFF` on disk; SQL/GUI numeric keys use 255): No item +- `NoItem` (-1, `0xFF` on disk. SQL and GUI numeric keys use 255): No item ## Related Files @@ -108,7 +104,7 @@ preserved when writing. - **Editor**: `src/references/monster_ref_editor.rs` (EditableRecord impl) - **Extractor**: `MonsterRef` struct implementing `Extractor` trait - **Data Structure**: `MonsterRef` with position, event, and loot data -- **Database**: Saved to SQLite via `save_monster_refs` function +- **Database**: saved to SQLite by the `save_monster_refs` function ## Example Usage @@ -137,10 +133,10 @@ cargo run -- database import "fixtures/Dispel/" ## Technical Notes -- Both file types use identical binary format +- Both file types use the same binary format. - Distinction is organizational (dungeon vs overworld) -- Padding fields have constrained value ranges (see Binary Format above) -- Files are processed by `MonsterRef` struct in the codebase +- The padding fields use constrained value ranges. See Binary Format above. +- The `MonsterRef` struct processes these files. ## Extractor @@ -163,8 +159,8 @@ cargo run -- validate -i monsteref.json --type monster_ref The MonsterRef editor provides a 3-panel interface: -1. **File list** — discovered Mondun*/Monmap*.ref files -2. **Record list** — monster placements in the selected file -3. **Record editor** — editable fields with monster name dropdown (loaded from Monster.ini) +1. File list: Mondun* and Monmap* `.ref` files found by the tool +2. Record list: monster placements in the selected file +3. Record editor: editable fields with a monster name dropdown loaded from `Monster.ini` All saves create a timestamped `.bak` backup automatically. diff --git a/docs/files/MonsterInGame/Monster.db.md b/docs/files/MonsterInGame/Monster.db.md index 24fea0fd..bc44cf55 100644 --- a/docs/files/MonsterInGame/Monster.db.md +++ b/docs/files/MonsterInGame/Monster.db.md @@ -1,22 +1,19 @@ # Monster.db Documentation -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. - ## File Information ### Overview -Binary database file that defines all monster types with complete combat statistics, behavior patterns, and reward -systems for the game's monster spawning and combat AI. +The tool reads `Monster.db` as fixed-size monster records. Each record holds a name and 34 numeric fields. ### File Structure -**Location**: `MonsterInGame/Monster.db` -**Encoding**: Binary (Little-Endian) -**Text Encoding**: EUC-KR **Record Size**: 160 bytes (24-byte name + 34 × i32 fields) -**Header**: None (count derived from file size) -**Total Records**: Variable (file_size / 160) +- **Location**: `MonsterInGame/Monster.db` +- **Encoding**: Binary (Little-Endian) +- **Text Encoding**: EUC-KR +- **Record Size**: 160 bytes (24-byte name + 34 × i32 fields) +- **Header**: None (count derived from file size) +- **Total Records**: Variable (file_size / 160) ### Binary Format @@ -111,13 +108,13 @@ systems for the game's monster spawning and combat AI. **MonsterAiType (ai_type):** -- **0**: Aggressor — Actively seeks and engages the player -- **1**: HitAndFlee — Attacks then retreats (hit-and-run) -- **2**: FleeWhenApproached — Runs away when player approaches -- **3**: AttackWhenOutnumbered — Engages only when it has numerical advantage -- **4**: TeleportTactic — Uses teleportation during combat -- **5**: AttackWhenProvoked — Only attacks when attacked first -- **6**: RunAwayWhenAttacked — Flees upon taking damage +- **0**: Aggressor +- **1**: HitAndFlee +- **2**: FleeWhenApproached +- **3**: AttackWhenOutnumbered +- **4**: TeleportTactic +- **5**: AttackWhenProvoked +- **6**: RunAwayWhenAttacked ### Data Structure @@ -214,14 +211,11 @@ Offset | Size | Field | Description - **is_undead = 1**: Holy weakness, no bleed - **has_blood = 0**: No blood effects (golems) - **is_oversize = 1**: Large monsters (dragons, etc.) -- **special_attack != 0**: The attack carries a poison (1) or paralysis (2) - status rider — see the *Special-attack rider* section under Field - Definitions. `special_attack_chance` is a percent roll against the victim, - `special_attack_duration` counts 55 ms scheduler ticks. +- **special_attack != 0**: the record carries a poison (1) or paralysis (2) status rider. See the *Special-attack rider* section under Field Definitions. `special_attack_chance` is a percentage value. `special_attack_duration` counts 55 ms scheduler ticks. ### File Purpose -Defines all monster types with combat statistics, AI behavior patterns, and reward systems. +The file holds 160-byte records with the fields listed above. ## Extractor diff --git a/docs/files/Ref/DrawItem.db.md b/docs/files/Ref/DrawItem.db.md index 89fae264..104764cb 100644 --- a/docs/files/Ref/DrawItem.db.md +++ b/docs/files/Ref/DrawItem.db.md @@ -1,8 +1,5 @@ # DRAWITEM.ref -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. - ## Purpose `DRAWITEM.ref` stores item placements for maps. @@ -45,6 +42,4 @@ normalized CRLF line endings. The Rust parser is [draw_item.rs](../../../src/references/draw_item.rs). -## Legal Notice -This document describes a file format. It contains no game records, asset names, or other game-content data. diff --git a/docs/files/Ref/Map.ini.md b/docs/files/Ref/Map.ini.md index e51e33f9..f16a945e 100644 --- a/docs/files/Ref/Map.ini.md +++ b/docs/files/Ref/Map.ini.md @@ -1,17 +1,13 @@ # Map.ini Documentation -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. - ## File Information - **Location**: `Dispel/Ref/Map.ini` (relative to game installation directory) - **Encoding**: EUC-KR - **Format**: CSV (Comma-Separated Values) -- **Comment lines**: Lines starting with `;` are ignored +- **Comment lines**: The parser ignores lines starting with `;`. -`Map.ini` is a map initialization data file used by the game engine to configure individual map properties, starting -positions, and associated resources. +The tool reads `Map.ini` as a map initialization list. Each row holds a map ID, coordinates, an event ID and resource file names. ## Structure @@ -51,7 +47,7 @@ id,camera_event,start_x,start_y,map_id,monsters,npcs,extras,cd_track ## Special Values - **"null"**: Used for `monsters`, `npcs`, and `extras` fields when the file is absent -- **Comments**: Lines starting with `;` are ignored +- **Comments**: The parser ignores lines starting with `;`. - **Coordinates**: Use isometric tile coordinate system - **Event IDs**: Special event numbers that trigger when camera moves @@ -59,24 +55,24 @@ id,camera_event,start_x,start_y,map_id,monsters,npcs,extras,cd_track This file defines initialization parameters for each map including: -1. Starting player positions (X,Y coordinates) +1. Start positions (X,Y coordinates) 2. Linked resource files (monsters, NPCs, extra objects) 3. Background music track selection 4. Map transition and linking information 5. Camera movement event triggers -The game engine uses this data during map loading to: +The tool stores these values: -- Position the player correctly -- Load appropriate monster/NPC placements -- Set up interactive objects -- Play the correct background music -- Handle map transitions and camera events +- Start coordinates +- Monster and NPC placement file names +- Extra object file names +- Music track number +- Camera event and target map IDs ## Notes -- The file is parsed by the `MapIni` struct in `src/references/map_ini.rs` -- Map initialization records are stored in a database using the `save_map_inis` function +- The `MapIni` struct in `src/references/map_ini.rs` parses the file. +- The `save_map_inis` function stores the records in a database. - The file format uses EUC-KR encoding - Coordinate system uses isometric tiles, not pixel coordinates diff --git a/docs/files/Ref/PartyRef.ref.md b/docs/files/Ref/PartyRef.ref.md index 9c9b6104..f0639b39 100644 --- a/docs/files/Ref/PartyRef.ref.md +++ b/docs/files/Ref/PartyRef.ref.md @@ -1,7 +1,4 @@ -# PartyRef.ref — Party Characters - -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. +# PartyRef.ref: party characters ## File Information @@ -16,7 +13,7 @@ - Lines starting with `;` are comments - CSV format with comma delimiter -- Empty lines are ignored +- The parser ignores empty lines. ### Record Structure @@ -35,7 +32,7 @@ - Unique character identifier - Party member index -- Used for character selection and management +- The tool uses this ID for character selection. ### name @@ -49,7 +46,7 @@ - Origin map identifier - Where character is initially found - Links to map files and locations -- Determines recruitment location +- Records the origin map ID. ### npc_id @@ -61,21 +58,21 @@ ### dlg_out - Dialog ID when not in party -- Conversation when character is roaming +- Conversation text outside the party - Recruitment dialogue - Initial interaction text ### dlg_in - Dialog ID when in party -- Conversation when character is recruited +- Conversation text inside the party - Party member dialogue -- Ongoing interaction text +- Later interaction text ### in_party - Boolean flag (0/1) marking the character as currently in the party -- A single byte; non-zero marks the character's name as highlighted in the party member list +- A single byte. Non-zero marks the name as highlighted in the party member list. - `0`: character not in the party (default) - `1`: character is in the party (name shown highlighted) @@ -88,21 +85,20 @@ ## File Purpose -Defines all party characters with their names, classes, origin locations, dialog references, and visual representations. -Used for: +The tool reads each row as a character record with a name, a job, an origin map and dialogue IDs. The data supports: -- Party management system -- Character recruitment -- Dialogue interactions -- UI display and portraits -- Character progression tracking +- Party membership flags +- Character origin records +- Dialogue references +- UI text and portraits +- Character progression records ## Implementation - **Rust Module**: `src/references/party_ref.rs` - **Extractor**: `PartyRef` struct implementing `Extractor` trait - **Data Structure**: `PartyRef` with character attributes -- **Database**: Saved to SQLite via `save_party_refs` function +- **Database**: saved to SQLite by the `save_party_refs` function ## Example Usage @@ -125,9 +121,9 @@ cargo run -- extract -i "fixtures/Dispel/Ref/PartyRef.ref" ## Related Files -- `Npc.ini` — NPC definitions -- `PrtIni.db` — Party initialization data -- `PrtLevel.db` — Character progression data +- `Npc.ini`: NPC definitions +- `PrtIni.db`: party initialization data +- `PrtLevel.db`: character progression data - Dialogue files (`.dlg`) - Map files (`.map`) From a9b493cb4941199a6ece7f35c4ebdd74a9ba0f4b Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:51:36 +0100 Subject: [PATCH 06/72] docs: rewrite fourteen map and entity format documents --- docs/files/ExtraInGame/Extra.ref.md | 42 +++++--------- docs/files/ExtraInGame/Message.scr.md | 13 ++--- docs/files/ExtraInGame/Quest.scr.md | 13 ++--- docs/files/ExtraInGame/fogdata.dat.md | 46 +++++---------- docs/files/Map/Map.btl.md | 24 +++----- docs/files/Map/Map.gtl.md | 13 +---- docs/files/Map/Map.map.md | 74 ++++++++----------------- docs/files/Map/MapModule.md | 53 ++++++++---------- docs/files/NpcInGame/DlgMapFiles.dlg.md | 17 +++--- docs/files/NpcInGame/Eventnpc.ref.md | 20 ++----- docs/files/NpcInGame/NpcMapFiles.ref.md | 9 +-- docs/files/NpcInGame/PgpMapFiles.pgp.md | 16 ++---- docs/files/NpcInGame/PrtIni.db.md | 10 +--- docs/files/NpcInGame/PrtLevel.db.md | 15 ++--- 14 files changed, 124 insertions(+), 241 deletions(-) diff --git a/docs/files/ExtraInGame/Extra.ref.md b/docs/files/ExtraInGame/Extra.ref.md index 45b4b2a9..a8f53723 100644 --- a/docs/files/ExtraInGame/Extra.ref.md +++ b/docs/files/ExtraInGame/Extra.ref.md @@ -1,8 +1,5 @@ # ExtraInGame/Ext*.ref Documentation -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. - ## File Information ### Overview @@ -87,18 +84,13 @@ items) on specific maps. Each map has its own `Ext*.ref` file containing all int ### Field semantics -- `map_object_id` is exposed to the tile/object system as `700 + map_object_id`. -- `interaction_state` is preserved across reloads; it selects the closed/open sprite sequence for chest-type objects. -- `requires_key` enables validation of the three inclusive requirement ranges. A range starting with `9999` is disabled. -- `gold_amount` awards gold, and three `(item, count)` loot pairs are processed: `loot_item`/`loot_item_count`, then the - two - `additional_loot_*` pairs. -- `footprint_width`, `footprint_height`, and `footprint_orientation` determine which map cells the object occupies. - `interaction_range` limits activation distance. +- The tool exposes `map_object_id` to the tile and object system as `700 + map_object_id`. +- The tool preserves `interaction_state` across reloads. It selects the closed or open sprite sequence for chest-type objects. +- `requires_key` enables validation of three inclusive requirement ranges. The tool disables a range that starts with `9999`. +- `gold_amount` holds the gold value. The tool reads three `(item, count)` loot pairs: `loot_item` with `loot_item_count`, then the two `additional_loot_*` pairs. +- `footprint_width`, `footprint_height` and `footprint_orientation` describe the map cells the object occupies. `interaction_range` limits activation distance. -The seven words from `additional_loot_2_count` through `use_counter` were formerly exported as one opaque -28-byte `additional_loot_2_count_and_config` BLOB. Two of those words are the trap flag and trap spell -index; both are zero in every shipped placement. They are **not** the same as `open_sfx_id`. +The seven words from `additional_loot_2_count` through `use_counter` hold the trap flag, trap spell index and related configuration. Both trap fields are zero in every sample placement. They are separate from `open_sfx_id`. #### Core Identification @@ -185,13 +177,9 @@ index; both are zero in every shipped placement. They are **not** the same as `o #### Trap fields and open sound -`is_trapped` and `trap_spell_id` are the trap arming flag and `Magic.db` spell index. All 1,039 -shipped placements carry zero in both, so no shipped placement uses a trap. +`is_trapped` and `trap_spell_id` hold the trap arming flag and `Magic.db` spell index. The 1,039 sample placements carry zero in both fields. -`open_sfx_id` is a **Wave.ini sound index** played when a door, lever, chest, key, or subtype-8 object -is activated successfully. It was previously exported as `activation_effect_id` with the bogus values -`None`/`Effect10`; that mapping also rewrote any index other than 0 or 10 to 255 on save. It is a -plain `u8` now. +`open_sfx_id` holds a `Wave.ini` sound index for a door, lever, chest, key or subtype-8 object. Zero means no sound. The field is a `u8`. #### Item Type ID (required_item_type_id, loot_item_type_id) @@ -218,9 +206,7 @@ SQL columns and GUI numeric keys keep the on-disk byte value, so no item reads a ### File Purpose -These files define interactive object placements with exact coordinates, requirements, contents, and behaviors. Used for -populating maps with chests, doors, signs, and other interactive elements. Each map in the game has a corresponding -`Ext*.ref` file. +The tool reads these files as interactive object placements. Each placement holds coordinates, requirements, contents and state values. Each map has its own `Ext*.ref` file. ### Cross-References @@ -234,10 +220,12 @@ populating maps with chests, doors, signs, and other interactive elements. Each ### Technical Details -**Endianness**: Little-Endian throughout **Record Count**: Stored as first 4 bytes (i32) -**Record Size**: Fixed 184 bytes (46 × i32 equivalent) -**File Size**: 4 + (record_count × 184) bytes **Text Encoding**: WINDOWS-1250 for name fields **Padding**: Extensive -padding with known patterns (zeros, 205 bytes) +- **Endianness**: little-endian throughout +- **Record count**: the first 4 bytes, as i32 +- **Record size**: 184 bytes, or 46 i32 words +- **File size**: 4 + (record_count × 184) bytes +- **Text encoding**: WINDOWS-1250 for name fields +- **Padding**: zeros and 205 bytes ### File Processing diff --git a/docs/files/ExtraInGame/Message.scr.md b/docs/files/ExtraInGame/Message.scr.md index f84d493a..2d40034b 100644 --- a/docs/files/ExtraInGame/Message.scr.md +++ b/docs/files/ExtraInGame/Message.scr.md @@ -1,7 +1,4 @@ -# Message.scr — UI Text Messages - -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. +# Message.scr: UI text messages ## File Information @@ -16,7 +13,7 @@ - Lines starting with `;` are comments - Pipe-delimited format: `field1|field2|field3|field4` -- Empty lines are ignored +- The parser ignores empty lines. ### Record Structure @@ -37,7 +34,7 @@ - Three lines of text for UI display - Each line can be up to 255 characters -- Lines are displayed vertically stacked +- The three lines appear in vertical order. - Empty lines use "null" literal ## Special Values @@ -69,7 +66,7 @@ Stores multi-line text messages for UI elements such as: - **Rust Module**: `src/references/message_scr.rs` - **Extractor**: `Message` struct implementing `Extractor` trait - **Data Structure**: `Message` with ID and three text lines -- **Database**: Saved to SQLite via `save_messages` function +- **Database**: saved to SQLite by the `save_messages` function ## Example Usage @@ -94,7 +91,7 @@ cargo run -- extract -i "Dispel/ExtraInGame/Message.scr" ## Display System -- Messages are displayed in UI panels +- The tool shows messages in UI panels. - Three-line vertical layout - Centered or aligned based on context - WINDOWS-1250 character encoding support diff --git a/docs/files/ExtraInGame/Quest.scr.md b/docs/files/ExtraInGame/Quest.scr.md index b5e7ede1..bf62860f 100644 --- a/docs/files/ExtraInGame/Quest.scr.md +++ b/docs/files/ExtraInGame/Quest.scr.md @@ -1,7 +1,4 @@ -# Quest.scr — Quest Journal Entries - -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. +# Quest.scr: quest journal entries ## File Information @@ -16,7 +13,7 @@ - Lines starting with `;` are comments - Pipe-delimited format: `field1|field2|field3|field4` -- Empty lines are ignored +- The parser ignores empty lines. ### Record Structure @@ -76,7 +73,7 @@ ### Traders Journal (type=2) - Commerce-related quests -- Trading missions +- Trade missions - Economic activities - Merchant interactions - Supply chain quests @@ -97,14 +94,14 @@ Defines all quests with categories, titles, and descriptions. Used for: - Player objectives - Story advancement - Reward distribution -- Linked to event system for completion +- Event IDs link to the event system. ## Implementation - **Rust Module**: `src/references/quest_scr.rs` - **Extractor**: `Quest` struct implementing `Extractor` trait - **Data Structure**: `Quest` with ID, type, title, and description -- **Database**: Saved to SQLite via `save_quests` function +- **Database**: saved to SQLite by the `save_quests` function ## Example Usage diff --git a/docs/files/ExtraInGame/fogdata.dat.md b/docs/files/ExtraInGame/fogdata.dat.md index b1002bcf..44fa5e70 100644 --- a/docs/files/ExtraInGame/fogdata.dat.md +++ b/docs/files/ExtraInGame/fogdata.dat.md @@ -1,19 +1,12 @@ # ExtraInGame/fogdata.dat Documentation -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. - ## File Information ### Overview -Map-lighting fade tables. The file is a flat array of brightness factors used -to shade tiles that carry a shadow (darkness) level. Each row of the table is one -animated flicker pattern for a single light level; the renderer walks the row per rendered frame -to make torch-lit darkness shimmer. +The file holds brightness factors in a flat array. Each row covers one light level and has 512 bytes. The renderer reads a row for each shadowed tile. -This file feeds the map lighting pass, which only runs on maps flagged **Dark** in `AllMap.ini` -(see `docs/rendering.md` and `src/map/render.rs::plot_shadows`). +The map lighting pass reads this file on maps flagged **Dark** in `AllMap.ini` (see `docs/rendering.md` and `src/map/render.rs::plot_shadows`). ### File Structure @@ -49,38 +42,28 @@ Row `L-1` serves light level `L`. A consumer indexes the file as: byte[(level - 1) * 512 + pair] ``` -where `pair` is the pixel-pair index (`0..512`) within a shadowed tile — each factor byte covers -two horizontally adjacent pixels. +Here `pair` is the pixel-pair index (`0..512`) within a shadowed tile. Each factor byte covers two horizontally adjacent pixels. -**Range nuance:** light levels `1..=199` occur in the map's access-ref grid (levels ≥ 200 are -skipped by the lighting pass entirely), but the file only covers levels `1..=123`. -Levels above 123 would read past the table; tooling must clamp or skip. +**Range:** light levels `1..=199` occur in the map's access-ref grid. The lighting pass skips levels of 200 or more. The file covers levels `1..=123`. Levels above 123 read past the table. Tooling must clamp or skip them. ### Factor Semantics -Each byte is a brightness factor `f` in `0..=31` — a 5-bit fixed-point value: +Each byte is a brightness factor `f` in `0..=31`. This is a 5-bit fixed-point value: - Effective multiplier on shadowed pixels: `f / 32`. - Applied to **all three colour channels**. -- `f = 0` → pixel pair blacked out; `f = 31` → nearly full brightness. -- Values are **not monotonic in level**: each row is an animated flicker pattern, so adjacent - levels can have very different brightness at the same pair index. +- `f = 0` blacks out the pixel pair. `f = 31` gives nearly full brightness. +- Values do not rise with level. Adjacent levels can have very different brightness at the same pair index. ### File Purpose -Provides the per-level darkness fade/flicker patterns that the map lighting pass applies to -shadowed tiles on Dark maps, producing an animated torch-light falloff. +The tool reads per-level brightness patterns. It applies them to shadowed tiles on Dark maps. ### Rendering Dark Maps -The `.map` file's own light-level bits (access-ref word bits 15–29) are not used for -rendering: a fixed 500-byte viewport template is applied per visible slot instead. A -static render that uses the file's bits therefore shows every dark map as pitch black. +The tool does not use the `.map` light-level bits (access-ref word bits 15 to 29) for rendering. It applies a fixed 500-byte viewport template per visible slot. A static render that uses the file's bits shows every dark map as black. -`map render --light-template [--camera x,y]` applies that template before the fog -pass and reproduces the lighting the game draws (the template is the 500×1 grayscale PNG the -Godot remake's `tools/convert_lighting.py` writes). `make map-render-lit map_id=dun01` -wraps it. +`map render --light-template [--camera x,y]` applies that template before the fog pass. The template is a 500×1 grayscale PNG. `tools/convert_lighting.py` writes it. `make map-render-lit map_id=dun01` wraps the command. ### Cross-References @@ -95,8 +78,8 @@ See also `docs/rendering.md` (isometric rendering pipeline) and ### Technical Details -- No header, no padding — exactly 62,976 raw bytes. -- Byte order is irrelevant (single-byte fields). +- No header and no padding. The file holds exactly 62,976 raw bytes. +- Byte order does not apply because fields are single bytes. - Parsed by `dispel_core::map::fogdata::FogData` (re-exported as `dispel_core::map::render::FogData`), which validates the length and provides bounds-checked accessors plus an editor-safe `set_factor` that rejects values > 31 @@ -104,6 +87,5 @@ See also `docs/rendering.md` (isometric rendering pipeline) and ### Notes -- Level 0 tiles are not looked up here: on Dark maps they are blacked out outright. -- When editing, keep every byte in `0..=31`; larger values are invalid in this table even though - they wrap silently when consumed. +- The tool does not look up level 0 tiles. It draws them black on Dark maps. +- When you edit the file, keep every byte in `0..=31`. Larger values are invalid in this table. diff --git a/docs/files/Map/Map.btl.md b/docs/files/Map/Map.btl.md index 04af760c..6f2d0870 100644 --- a/docs/files/Map/Map.btl.md +++ b/docs/files/Map/Map.btl.md @@ -1,10 +1,6 @@ # DISPEL® Building Tile Layer (`.btl`) -Raw tileset binary used for structures, roofs, and architectural elements. The format is identical to `.gtl`; only the -semantic role differs. - -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. +The tool reads `.btl` files as raw tilesets for structures and roofs. The binary format matches `.gtl`. ## Quick Facts @@ -47,24 +43,20 @@ blue = bits 0–4 of pixel → scale 0–31 to 0–255 ## Isometric Rendering -Tiles are projected as isometric diamonds (62×32 px). A diamond-shaped mask clips each tile so that corners blend -seamlessly. +The renderer projects tiles as isometric diamonds of 62×32 pixels. A diamond-shaped mask clips each tile. + +The renderer picks a blit mode from the building overlay entry. Transparency 0 selects an opaque copy. A non-zero value selects a skip-zero blit, which copies only non-zero pixels. The draw-enable byte must be set before the renderer draws the cell. Only shadowed cells use this pass. -The blit mode is chosen **per ref**, from the transparency and draw-enable bytes of the -building overlay's map entry: transparency 0 means opaque copy, non-zero means a skip-zero blit -that copies only the non-zero source pixels; the draw-enable byte must be set for the cell to be -drawn at all. Only the shadowed cells are drawn by this pass. An atlas therefore bakes in one mode — -`map atlas` uses the skip-zero blit for `.BTL` files, which matches the shadow art but drops the -black pixels of the opaque-mode refs (764 of 1419 in `dun01`). +An atlas bakes in one mode. `map atlas` uses the skip-zero blit for `.btl` files. In `dun01`, 764 of 1419 references use opaque mode. ## Relationship to `.map` Files A `.map` file references BTL tile IDs in two places: -- **Tiled Objects block** — building stacks drawn from anchor points -- **Access-Ref block** — occlusion/access lookup per tile +- **Tiled Objects block**: building stacks drawn from anchor points +- **Access-Ref block**: occlusion and access lookup per tile -BTL tile IDs inside the Tiled Objects block are stacked bottom-to-top; negative IDs are skipped during rendering. +The tool stacks BTL tile IDs bottom-to-top. It skips negative IDs when rendering. ## Related Files diff --git a/docs/files/Map/Map.gtl.md b/docs/files/Map/Map.gtl.md index 1ceed937..40d7131a 100644 --- a/docs/files/Map/Map.gtl.md +++ b/docs/files/Map/Map.gtl.md @@ -1,10 +1,6 @@ # DISPEL® Ground Tile Layer (`.gtl`) -Raw tileset binary used for terrain, paths, and natural features. The format is identical to `.btl`; only the semantic -role differs. - -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. +The tool reads `.gtl` files as raw tilesets for terrain, paths and natural features. The binary format matches `.btl`. ## Quick Facts @@ -47,12 +43,9 @@ blue = bits 0–4 of pixel → scale 0–31 to 0–255 ## Isometric Rendering -Tiles are projected as isometric diamonds (62×32 px). A diamond-shaped mask clips each tile so that corners blend -seamlessly. +The renderer projects tiles as isometric diamonds of 62×32 pixels. A diamond-shaped mask clips each tile. -**The ground pass is an opaque row-copy**: the 32 rows are copied verbatim, so the -tile's RGB(0,0,0) pixels are drawn like any other. An atlas that treats black as transparent punches holes in the -floor — `map atlas` therefore defaults to the opaque mode for `.GTL` files. +The ground pass copies 32 rows without filtering. The tool draws RGB(0,0,0) pixels like any other pixel. `map atlas` defaults to opaque mode for `.gtl` files. ## Relationship to `.map` Files diff --git a/docs/files/Map/Map.map.md b/docs/files/Map/Map.map.md index 4eff1f71..be5cbdb0 100644 --- a/docs/files/Map/Map.map.md +++ b/docs/files/Map/Map.map.md @@ -1,12 +1,6 @@ # DISPEL® Map File Format (`.map`) -All game maps — overworld (`map1.map`…), catacombs (`cat1.map`…, `catp.map`), and dungeons (`dun01.map`…, `final.map`) — -share this binary format. A `.map` -file contains everything needed to render a map: dimensions, embedded sprites (thrones, statues, decor), building -stacks, and three per-tile grids (events, ground tiles, occlusion). - -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. +The tool reads overworld, catacomb and dungeon maps with one binary format. Sample names include `map1.map`, `cat1.map`, `catp.map`, `dun01.map` and `final.map`. A `.map` file holds dimensions, embedded sprites, building stacks and three per-tile grids for events, ground tiles and occlusion. ## Quick Facts @@ -59,9 +53,7 @@ count: i32 records: (count − 1) × 8 bytes -- each record: word0: i32, word1: i32 ``` -Skipping `(count − 1) × 8` lands exactly on the next block's size field, verified against the cat1/cat3/dun01/map1/catp -fixtures. Both words are **constant across all shipped maps** — `word0 == 0` and `word1 == 1` in all 99,104 records -probed — so their purpose is unknown. The earlier "linear tile index into the end grids" interpretation was wrong. +The tool skips `(count − 1) × 8` bytes and lands on the next block's size field. The cat1, cat3, dun01, map1 and catp samples contain 99,104 records. In those records `word0 == 0` and `word1 == 1`. The supplied data shows no use for these fields. ### Second Block *(u16 lookup table)* @@ -87,8 +79,7 @@ for each sprite: 6 → 1904 bytes, 9 → 2996 bytes ``` -Any other `image_stamp` is a parse error. Sprites here are thrones, statues, decor — anything placed by pixel coordinate -rather than tile grid. +Any other `image_stamp` is a parse error. These sprites use pixel coordinates rather than tile grid coordinates. ### Sprite Info Block *(placements)* @@ -105,16 +96,11 @@ for each placement: frame_skip: (frame_count − 1) × 6 × 4 bytes ``` -The seven i32s after `sprite_id` are actually **frame 0 of a per-frame record** -(24 bytes each: `{left, top, right, bottom}` box + duplicated `{x, y}` anchor; -the game stores them in separate per-frame arrays so they can diverge). -Verified against cat1/map1: `right − left` and `bottom − top` equal the frame's -pixel `width × height` exactly. Placements Y-sort by `bottom`. +The seven i32 values after `sprite_id` hold frame 0 of a per-frame record. Each record has 24 bytes: a `{left, top, right, bottom}` box and a duplicated `{x, y}` anchor. The format stores these values in separate per-frame arrays. In the cat1 and map1 samples, `right − left` and `bottom − top` equal the frame pixel `width × height`. Placements sort by `bottom` on the Y axis. -### Tiled Objects Block *(buildings)* — fully typed +### Tiled Objects Block *(buildings)*: fully typed -This block is a three-level tree: bundle, record, item, and entry. The -structure below is based on the on-disk data. +This block is a three-level tree: bundle, record, item and entry. The structure below follows the on-disk data. ``` bundle_count: i32 @@ -148,26 +134,16 @@ for each bundle: -- stack level; their meaning is unknown ``` -There is **no end-of-block sentinel**: the three end grids follow the last -bundle's level flags immediately. The previously described "empirically fitted" -layout (`264-byte blob`, `control words`, `84-byte trailer`, -`sentinel alignment scan`) was an approximation that happened to consume the -same byte stream; it has been deleted. - -Discovered semantics (verified over all 33 fixture maps, 43,554 entries): -- `anchor_x`/`anchor_y` are the stack anchor `(x, y)` in map-local pixels; - the entry's `ids` u16 array is its BTL tile stack. The renderer-facing - `TiledObjectInfo` is derived from the bundle's *first* entry - (first record → first item → first entry). -- The bbox relations above hold exactly on every shipped entry. +There is no end-of-block sentinel. The three end grids follow the last bundle's level flags immediately. + +The 33 sample maps contain 43,554 entries. Those entries use this layout: +- `anchor_x` and `anchor_y` give the stack anchor `(x, y)` in map-local pixels. The entry's `ids` u16 array is its BTL tile stack. The renderer-facing `TiledObjectInfo` comes from the bundle's first entry (first record, first item, first entry). +- The 43,554 entries follow the bounding-box relations above. - An entry's `grid_height` sizes the per-bundle flag arrays that follow. -Shipped data is degenerate: exactly one record per bundle, eight items per -record, at most one entry per item; `type_flag ≡ 0` and `field_14 ≡ 0` -everywhere. +The sample maps contain one record per bundle, eight items per record and at most one entry per item. `type_flag` and `field_14` are zero in those files. -Each bundle's first-entry tile stack is drawn downward from the anchor, one 62×32 diamond per id. -Negative ids occur and are skipped when drawing. +The tool draws each bundle's first-entry tile stack downward from the anchor. It draws one 62×32 diamond per id. Negative ids occur. The tool skips them when it draws. ### Event Block @@ -182,7 +158,7 @@ flags: i16 -- high half: parameter/flag bits In the packed u32, bit 22 sets `EventBlock::is_tile_marked`. -Two game systems use the following exact event-word predicate: +Two documented checks use this exact event-word predicate: ```text (word & 0x0FC00000) == 0x00400000 @@ -198,7 +174,7 @@ remaining high bits have no documented meaning. ### Tile & Access Block -One packed u32 per tile, row-major (bit layout verified against shipped map data): +One packed u32 per tile, row-major: | Bits | Meaning | |-------|--------------------------------------------------------------| @@ -211,8 +187,7 @@ The index points straight into the `.gtl` pixel data: the renderer blits from `gtl_base + index × 2048` (one 32×32 RGB565 tile). Across observed maps the maximum index matches the `.gtl` tile capacity minus one. -Bits 0–9 together form one access field that can be rewritten without touching the tile index. Maps only ever -use bit 0; bits 1–9 are written at runtime. +Bits 0 to 9 form one access field. The tool can rewrite that field without changing the tile index. The sample maps use bit 0 only. No sample value sets bits 1 to 9. ### Access-Ref Block *(a.k.a. "roof" block)* @@ -226,12 +201,10 @@ shadow_and_flags: i16 -- bits 15–29 of the u32: shadow level 0–19 This grid packs **two layers** in one u32: -1. **BTL overlay ref** (bits 0–14): when the referenced Second Block entry has - its *high* byte set, the game blits BTL pixels from +1. BTL overlay ref (bits 0 to 14): when the referenced Second Block entry has its high byte set, the renderer blits BTL pixels from `btl_base + ref_id × 2048` (entry *low* byte selects transparent vs opaque blit). So the Second Block is `{transparency, draw_enable}` per overlay id. -2. **Shadow/fog level** (bits 15–29): 0–199 darkness applied per tile via a - fade table; entities carrying light raise the value (max wins). +2. Shadow and fog level (bits 15 to 29): the value spans 0 to 199. The documented rule raises the value for light sources. The highest value wins. On a dark map, a BTL overlay must have a non-zero reference and at least one bit in positions 15–31. The extractor exposes this condition as @@ -239,8 +212,7 @@ bit in positions 15–31. The extractor exposes this condition as the referenced Second Block entry must also have its draw-enable byte set. Light maps use a different roof pass and do not apply this extra condition. -Bit 15 overlaps the signed-i16 view of `ref_id`; readers must mask the low 15 -bits instead of treating a negative i16 value as an absent reference. +Bit 15 overlaps the signed-i16 view of `ref_id`. Readers must mask the low 15 bits. A negative i16 value does not mean the reference is absent. --- @@ -253,11 +225,9 @@ pixel_x = (x + y) × 32 pixel_y = (y − x) × 16 + (map_diagonal / 2) × 16 ``` -where `map_diagonal = tiled_width + tiled_height`. Moving `+1` in `x` steps up-left on screen (−32, −16); moving `+1` in -`y` steps down-right (+32, +16). +Here `map_diagonal = tiled_width + tiled_height`. A step of +1 in `x` moves the tile by (−32, −16) on screen. A step of +1 in `y` moves it by (+32, +16). -Sprite and building placements inside the file are **map-local**: subtract -`map_non_occluded_start_x/y` (computed in `src/map/model.rs`) to convert to world pixels. +Sprite and building placements in the file use map-local coordinates. Subtract `map_non_occluded_start_x/y`, computed in `src/map/model.rs`, to convert them to world pixels. ## File Size Calculation @@ -278,7 +248,7 @@ total = header + variable blocks + fixed_tail ## Implementation & Usage - Parser: `read_map_data()` in `src/map/mod.rs`, block readers in `src/map/reader.rs` -- Renderer: `render_map()` in `src/map/render.rs`; GUI canvas in +- Renderer: `render_map()` in `src/map/render.rs`. The GUI canvas is in `dispel-gui/src/components/map_render/` ```bash diff --git a/docs/files/Map/MapModule.md b/docs/files/Map/MapModule.md index 21f441ff..cfd04d2d 100644 --- a/docs/files/Map/MapModule.md +++ b/docs/files/Map/MapModule.md @@ -1,19 +1,15 @@ # Map Module Specification -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. - --- ## Overview -The `src/map/` module handles parsing, rendering, and database operations for the Dispel game's `.MAP`, `.GTL`, and -`.BTL` binary file formats. It provides: +The `src/map/` module parses and renders `.MAP`, `.GTL` and `.BTL` files. It also writes data to SQLite. It provides: - **Binary parsing** of `.MAP` files (geometry, sprites, tiles, events, collisions) - **Tileset extraction** from `.GTL` (ground) and `.BTL` (building) files - **Isometric rendering** to PNG images -- **Database import/export** via SQLite +- **Database import and export** with SQLite - **Sprite loading** from `.SPR` files for entity rendering ### Module Files @@ -36,10 +32,9 @@ The `src/map/` module handles parsing, rendering, and database operations for th ## File Formats -### `.MAP` — Map File +### `.MAP`: map file -Binary file containing the complete map definition: geometry, embedded sprites, tiled objects, event triggers, ground -tiles, collision data, and optional roof tiles. +The file holds geometry, embedded sprites, tiled objects, event triggers, ground tiles, collision data and optional roof tiles. #### Structure @@ -162,7 +157,7 @@ start_y = (-x + y) × 16 + (diagonal / 2 × 16) #### Event Block Location -The event block and tile blocks are located at the **end of the file**. The parser seeks backwards from EOF: +The event block and tile blocks sit at the end of the file. The parser seeks backwards from EOF: ``` seek_offset = -(tiled_map_width × tiled_map_height × 4 × 3) @@ -173,9 +168,9 @@ bytes/tile). --- -### `.GTL` / `.BTL` — Tileset Files +### `.GTL` and `.BTL`: tileset files -Simple binary format with **no header**. Direct sequence of 32×32 pixel tiles in RGB565. +The format has no header. It holds a sequence of 32×32 RGB565 tiles. #### Structure @@ -213,14 +208,14 @@ blue = bits 0–4 of pixel → scale 0-31 to 0-255 **File types:** -- `.GTL` — Ground Tile Layer (terrain, paths, natural features) -- `.BTL` — Building Tile Layer (structures, roofs, man-made objects) +- `.GTL`: ground tile layer for terrain, paths and natural features +- `.BTL`: building tile layer for structures, roofs and man-made objects --- -### `.SPR` — Sprite Files (referenced, not owned by map module) +### `.SPR`: sprite files (referenced, not owned by map module) -Sprite files are parsed by the parent `sprite` module but loaded by `sprite_loader.rs` for entity rendering. +The parent `sprite` module parses `.spr` files. `sprite_loader.rs` loads them for entity rendering. #### Structure (per sequence) @@ -345,8 +340,7 @@ struct LoadedSpriteFrame { ### Database -Owned by `src/database/map_persistence.rs`; re-exported from `map` so existing -`dispel_core::map::save_to_db` paths keep working. +These functions live in `src/database/map_persistence.rs`. The `map` module re-exports them. Existing `dispel_core::map::save_to_db` paths keep working. | Function | Description | |-------------------------------------------------|------------------------------------| @@ -378,12 +372,12 @@ Owned by `src/database/map_persistence.rs`; re-exported from `map` so existing ### Depth Sorting -Sprites and tiled objects are sorted by `ground_y` before rendering: +The renderer sorts sprites and tiled objects by `ground_y`. - **Sprites**: `ground_y = sprite_y + frame_height` - **Tiled objects**: `ground_y = tile_y + (stack_height × 32)` -This ensures proper isometric depth ordering (painter's algorithm). +This gives isometric depth order through the painter's algorithm. --- @@ -415,7 +409,7 @@ This ensures proper isometric depth ordering (painter's algorithm). ## JSON Schema for Map Data Export -The following JSON schema describes the structure for exporting `.MAP` file data: +This JSON schema describes exported `.MAP` data: ```json { @@ -865,7 +859,7 @@ Where `w = tiled_map_width`, `h = tiled_map_height`. ## External Entity Rendering Colors -When `game_path` is not provided or sprite files are missing, entities are rendered as colored diamond markers: +The tool draws entities as colored diamond markers when `game_path` is absent or sprite files are missing. | Entity Type | Color (RGBA) | Sprite Directory | |-------------|----------------------------------|------------------| @@ -877,11 +871,10 @@ When `game_path` is not provided or sprite files are missing, entities are rende ## Notes -1. **Two unknown blocks** at the start of `.MAP` files are skipped — their purpose is not yet understood -2. **Image stamps** (6 or 9) determine the padding size after sprite sequence data (1904 or 2996 bytes respectively) -3. **Tiled object sentinel** — the end of the tiled objects block is detected by scanning 20 bytes backwards for the - byte value 1 -4. **Roof block is optional** — only parsed if remaining file size is sufficient -5. **Collision flag** is extracted from bit 0 of the packed tile value; tile index is bits 10–24 -6. **All integers are little-endian** -7. **Sprite sequences** in the map file are self-contained — pixel data is embedded directly, not referenced externally +1. The tool skips the first two blocks. The supplied data shows no use for these fields. +2. Image stamp 6 uses 1904 bytes of padding after sprite sequence data. Image stamp 9 uses 2996 bytes. +3. The tool finds the end of the tiled objects block with a 20-byte backwards scan for byte value 1. +4. The tool parses the roof block only when enough bytes remain. +5. The collision flag comes from bit 0 of the packed tile value. The tile index uses bits 10 to 24. +6. All integers are little-endian. +7. Sprite sequences in the map file hold embedded pixel data. The file does not reference external sprite data. diff --git a/docs/files/NpcInGame/DlgMapFiles.dlg.md b/docs/files/NpcInGame/DlgMapFiles.dlg.md index 0aa804b6..5b80d794 100644 --- a/docs/files/NpcInGame/DlgMapFiles.dlg.md +++ b/docs/files/NpcInGame/DlgMapFiles.dlg.md @@ -1,7 +1,4 @@ -# Dlgcat1.dlg - Dialogue/Conversation Scripts - -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. +# Dlgcat1.dlg: dialogue scripts ## File Information @@ -16,7 +13,7 @@ - Lines starting with `;` are comments - CSV format with comma delimiter -- Empty lines are ignored +- The parser ignores empty lines. ### Record Structure @@ -29,8 +26,8 @@ Each line has exactly 10 comma-separated fields: - `owner`: i32 - 0=player, 1=NPC - `dlg_id`: i32 - Reference to PGP text content - `opt0`: i32 - Next dialogue option 1 (choice dialogs) or next dialog in linear type -- `opt1`: i32 - Next dialogue option 2 (choice dialogs); 0 = absent -- `opt2`: i32 - Next dialogue option 3 (choice dialogs); 0 = absent +- `opt1`: i32 - next dialogue option 2 for choice dialogs. Zero means absent. +- `opt2`: i32 - next dialogue option 3 for choice dialogs. Zero means absent. - `event_id`: i32 - Event triggered by dialogue ## Field Definitions @@ -41,7 +38,7 @@ Each line has exactly 10 comma-separated fields: - `type`: 0=normal, 1=choice dialog - `owner`: 0=player, 1=NPC - `dlg_id`: Reference to PGP text content -- `opt0`–`opt2`: Choice-dialog branching targets; unused options are 0 +- `opt0` to `opt2`: choice-dialog targets. Unused options are 0. - `event_id`: Event triggered by dialogue ## Dialogue Types @@ -59,7 +56,7 @@ Each line has exactly 10 comma-separated fields: - Optional fields are `0` when absent (not `"null"`) - Lines starting with `;` are comments - CSV format with comma delimiter -- Empty lines are ignored +- The parser ignores empty lines. ## File Purpose @@ -77,7 +74,7 @@ quest dialogues, and story progression systems. - **Rust Module**: `src/references/dialogue_script.rs` - **Extractor**: `DialogueScript` struct implementing `Extractor` trait -- **Database**: Saved to SQLite via `save_dialogs` function +- **Database**: saved to SQLite by the `save_dialogs` function ## Extractor diff --git a/docs/files/NpcInGame/Eventnpc.ref.md b/docs/files/NpcInGame/Eventnpc.ref.md index 198d8cdb..b8df7f9c 100644 --- a/docs/files/NpcInGame/Eventnpc.ref.md +++ b/docs/files/NpcInGame/Eventnpc.ref.md @@ -1,7 +1,4 @@ -# Eventnpc.ref - Event NPC Definitions - -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. +# Eventnpc.ref: event NPC definitions ## File Information @@ -17,8 +14,8 @@ - Lines starting with `;` are comments - Rows are comma-separated, 40 columns each -- Rows are terminated by CRLF -- Empty lines are ignored +- Each row ends with CRLF +- The parser ignores empty lines. ### Record Structure @@ -124,22 +121,17 @@ id, the high 16 bits the parameter - the same split the `Npccat*.ref` records us - Lines starting with `;` are comments - Empty lines ignored -- The `id` column is the row index. The game itself ignores the value and - selects rows by position. +- The `id` column holds the row index. The tool selects rows by position. ## Known Data Defect -The shipped `Eventnpc.ref` holds one row whose comma between the -`npc_ini_id` and the `name` column is missing: +The sample `Eventnpc.ref` holds one row with a missing comma between the `npc_ini_id` and `name` columns: ```text 2,69Character Name,guard,0,0,1,1,301,251,0,4,0,...,0,6 ``` -The row therefore carries 39 columns. The game reads the leading digits of -`69Character Name` as the archetype id and loses the name. The extractor splits -the glued column back apart, so the record keeps the id `69` and the name -`Character Name`. Saving the file writes the repaired 40-column row. +That row carries 39 columns. The tool splits the glued column apart. The record keeps id `69` and name `Character Name`. When you save the file, the tool writes a repaired 40-column row. ## Extractor diff --git a/docs/files/NpcInGame/NpcMapFiles.ref.md b/docs/files/NpcInGame/NpcMapFiles.ref.md index 61cfde5c..30f04097 100644 --- a/docs/files/NpcInGame/NpcMapFiles.ref.md +++ b/docs/files/NpcInGame/NpcMapFiles.ref.md @@ -1,7 +1,4 @@ -# Npccat1.ref - NPC Placement Data - -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. +# Npccat1.ref: NPC placement data ## File Information @@ -41,7 +38,7 @@ | 664 | dialog_id | Dialogue node ID. | | 668 | dialogue_face_sprite_id | Face sprite ID. | -## Looking Directions +## Direction values - `0`: Up (North) - `1`: Up-Right (Northeast) @@ -82,7 +79,7 @@ characters. - **Rust Module**: `src/references/npc_ref.rs` - **Extractor**: `NPC` struct implementing `Extractor` trait -- **Database**: Saved to SQLite via `save_npc_refs` function +- **Database**: saved to SQLite by the `save_npc_refs` function ## Extractor diff --git a/docs/files/NpcInGame/PgpMapFiles.pgp.md b/docs/files/NpcInGame/PgpMapFiles.pgp.md index 2db957cb..a52cc18b 100644 --- a/docs/files/NpcInGame/PgpMapFiles.pgp.md +++ b/docs/files/NpcInGame/PgpMapFiles.pgp.md @@ -1,7 +1,4 @@ -# Pgpcat1.pgp - Dialogue Text - -> DISPEL® is a registered trademark. This project is not affiliated with, -> endorsed by, or sponsored by the trademark owner. +# Pgpcat1.pgp: dialogue text ## File Information @@ -16,7 +13,7 @@ - Lines starting with `;` are comments - Pipe-delimited format -- Empty lines are ignored +- The parser ignores empty lines. ### Record Structure @@ -37,14 +34,14 @@ ## Parameter Usage - `param1`: Dialogue branch conditions -- `wave_ini_entry_id`: Sound effect played at dialogue start; 0 = none +- `wave_ini_entry_id`: sound effect at dialogue start. Zero means none. ## Text Formatting - "null" literal for empty text - "$" literal interpreted as a line-break in game - Pipe (|) delimiter between fields -- Semicolon (;) for comment lines +- Semicolon (`;`) for comment lines - Multi-line comments supported ## Special Values @@ -56,8 +53,7 @@ ## File Purpose -Stores dialogue text content with developer comments and logical parameters. Used for displaying conversation text, -branching dialogue, and triggering game events. +The tool stores dialogue text with developer comments and parameters. Each row holds an ID, text and a sound reference. ## Related Files @@ -70,7 +66,7 @@ branching dialogue, and triggering game events. - **Rust Module**: `src/references/dialogue_paragraph.rs` - **Extractor**: `DialogueParagraph` struct implementing `Extractor` trait -- **Database**: Saved to SQLite via `save_dialogue_paragraphs` function +- **Database**: saved to SQLite by the `save_dialogue_paragraphs` function ## Extractor diff --git a/docs/files/NpcInGame/PrtIni.db.md b/docs/files/NpcInGame/PrtIni.db.md index e6f09570..8a7b1ef0 100644 --- a/docs/files/NpcInGame/PrtIni.db.md +++ b/docs/files/NpcInGame/PrtIni.db.md @@ -6,7 +6,7 @@ - No header. - Exactly eight 28-byte records. -- Records are addressed as `party_slot * 28`. +- The parser addresses records as `party_slot * 28`. - `name` is a 20-byte, null-padded string. Names are ASCII-compatible. | Offset | Size | Type | Field | Meaning | @@ -18,10 +18,6 @@ | `23` | 1 | u8 | `pathfinding_mode` | Map/path-query mode; observed value 7 | | `24` | 4 | u32 | `character_variant` | Variant selector; observed values 0 and 1 | -The loader copies `class_id`, `starting_level`, `pathfinding_mode`, and -`character_variant` into runtime character state. It uses `class_id` for class-specific behavior and titles, and uses -`character_variant` to choose one of two class variants. The binary does not establish whether that variant is a gender, -portrait, or another presentation choice, so the parser uses the neutral name `character_variant`. +The tool reads `class_id`, `starting_level`, `pathfinding_mode` and `character_variant` into character state. The supplied data does not establish what `character_variant` represents. The parser uses that neutral name. + -DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -owner. diff --git a/docs/files/NpcInGame/PrtLevel.db.md b/docs/files/NpcInGame/PrtLevel.db.md index b3f48685..56a4adcb 100644 --- a/docs/files/NpcInGame/PrtLevel.db.md +++ b/docs/files/NpcInGame/PrtLevel.db.md @@ -1,8 +1,6 @@ # PrtLevel.db -`NpcInGame/PrtLevel.db` contains eight party-member progression tables, each with 20 levels. It has no header: the game -reads level `n` of party slot `s` -at `s * 720 + (n - 1) * 36`. +`NpcInGame/PrtLevel.db` contains eight party-member progression tables, each with 20 levels. It has no header. The tool reads level `n` of party slot `s` at `s * 720 + (n - 1) * 36`. Each entry is 36 bytes. @@ -24,13 +22,8 @@ Each entry is 36 bytes. | `28` | 4 | u32 | `weapon_skill_level` | Party member's shared weapon proficiency | | `32` | 4 | u32 | `tactical_action_chance` | Percentage threshold for a level-10+ tactical action | -The first three bytes were previously misidentified as a sentinel. They are magic-spell references copied into runtime -state. All reserved bytes are preserved verbatim by the parser. +The first three bytes hold magic-spell IDs. The tool preserves all reserved bytes. + +`weapon_skill_level` holds a shared weapon proficiency value. `tactical_action_chance` holds a percentage threshold from 0 to 99. -`weapon_skill_level` is not MP recharge: the game uses it in the same generic weapon calculations that select one of the -player's weapon-skill levels. -`tactical_action_chance` is not defence: it is compared to a random value from 0 to 99 before changing the party -member's tactical action state. -DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark -owner. From 348da02dfb6c55bbfe882e04d15ebaf561badfb1 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:57:50 +0100 Subject: [PATCH 07/72] docs: rewrite AGENTS.md in plain English --- AGENTS.md | 226 +++++++++++++++++++++++++++--------------------------- 1 file changed, 112 insertions(+), 114 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3b7872c6..e1f909f7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,12 +1,12 @@ -# AGENTS.md — Dispel Game File Extractor +# AGENTS.md: Dispel Game File Extractor -**A game modding toolkit for Dispel RPG.** Reads/writes game files in native binary, INI, and DB formats — including save games. All edits are persisted directly — no intermediate database. Includes a full desktop GUI for editing game data with undo/redo, mod packaging, and a hex editor. +This toolkit reads and writes game files in binary, INI and DB formats. It also handles save games. Edits go directly into game files. The repository includes a desktop GUI, a hex editor and a mod packaging pipeline. --- ## Project Overview -This workspace is a **6-crate Cargo workspace** (Rust edition 2024) versioned `0.9.3`: +The workspace is a **6-crate Cargo workspace** with Rust edition 2024 and version `0.9.3`. | Crate | Type | Role | |---|---|---| @@ -17,7 +17,7 @@ This workspace is a **6-crate Cargo workspace** (Rust edition 2024) versioned `0 | `gui-widgets` | lib | Reusable custom Iced widgets (ContextMenu, modal, popover, toast, ParagraphCache…). | | `hexedit` | lib + bin | Full hex editor — used by `dispel-gui` as a tab type. Single binary: `hexedit`. | -**Separation of concerns:** +Separation of concerns: - `dispel-core` + `dispel-macros` + `dispel-encodings`: game logic only. Zero GUI/presentation code. - `dispel-gui` + `gui-widgets` + `hexedit`: UI only. Zero game logic (they consume `dispel-core`). - `dispel-extractor` (root `main.rs`): thin CLI wrapper around the library. @@ -53,7 +53,7 @@ dispel-extractor/ │ ├── app.rs # App (transient UI state; embeds AppState) │ ├── state.rs # AppState (persistent model) + RecordingSession │ ├── workspace.rs # Tabs; re-exports EditorType from editor_catalog/ -│ ├── editor_catalog/ # define_editor_catalog! — 45 named variants + Unknown (EDITOR_COUNT = 46) +│ ├── editor_catalog/ # define_editor_catalog! — 45 named variants + `Unknown` (EDITOR_COUNT = 46) │ ├── editor_registry.rs # All 47 editor state fields │ ├── platform.rs # OS-specific ops │ ├── style.rs + style/ # Iced style functions ("Medieval" theme), split per component @@ -96,7 +96,7 @@ dispel-extractor/ | `.snf` | Audio | PCM | Sound effects | | `.ifo` / save file | Save game | Binary | Player saves (`Save.ifo`, parsed by `save_ifo` / `save_file`) | -**Encoding is critical:** `Event.ini`, `Npc.ini`, `Monster.db` (desc) → **EUC-KR**. `Monster.ini`, `Store.db`, `WeaponItem.db` → **WINDOWS-1250**. Per-file encoding documented in `docs/files/CROSS_REFERENCES.md`. +Check the encoding before you read a file. `Event.ini`, `Npc.ini` and `Monster.db` descriptions use EUC-KR. `Monster.ini`, `Store.db` and `WeaponItem.db` use WINDOWS-1250. `docs/files/CROSS_REFERENCES.md` lists the encoding of each file. ### Item Type Enum | Value | Type | Database | @@ -131,16 +131,18 @@ dispel-extractor/ ## Binary Format Essentials -- **All integers**: little-endian -- **Colors**: RGB 565 (16-bit). Helpers: `sprite::Color::from_rgb565()` / `to_rgb565()` -- **Map tiles**: seeked from EOF (event/GTL/BTL layers) -- **Sprites**: start at byte 268; validation: `ints[11] * ints[12] == ints[13]` -- **Tilesets**: contiguous 32×32 tiles, RGB 565 (2 bytes/pixel) -- **Map rendering**: isometric projection, 62×32 display size; Y-sorted draw order for walls/objects. **Warning:** full map ≈ 300MB; GUI uses viewport + LRU cache (≤50MB via `lru` 0.12). -- **TMX export**: `map::tmx::export_tmx()` converts `.map` + tilesets to Tiled TMX XML (isometric, CSV tile data) -- **SNF audio**: custom PCM header; prepend RIFF WAVE header for conversion (`SnfFile::to_wav_bytes()`) -- **DB record sizes** (all fixed): WeaponItem 284B, Monster 160B, Magic 88B, HealItem 252B, EditItem 268B, EventItem 240B, MiscItem 256B, ChData 84B, Store 948B (variable product list), PartyIniNpc 28B, PartyLevelNpc 5760B (8×20 grid), NPC 672B, MonsterRef 56B, ExtraRef 184B. Save records (`SaveFile`, `SaveIfo`) are variable-layout — see `docs/files/`. -- **Static layout metadata**: `references/layout.rs` defines `FieldDef` / `FixedRecordLayout` and the `RecordLayout` derive trait — generated byte-offset metadata for fixed-size records. +- All integers use little-endian byte order. +- Colors use 16-bit RGB 565. Helpers: `sprite::Color::from_rgb565()` and `to_rgb565()`. +- The parser seeks map tiles from EOF for the event, GTL and BTL layers. +- Sprite data starts at byte 268. Validation uses `ints[11] * ints[12] == ints[13]`. +- Tilesets hold contiguous 32×32 tiles in RGB 565, with 2 bytes per pixel. +- Map rendering uses an isometric projection at 62×32 pixels. The tool draws walls and objects in Y-sorted order. A full map takes about 300MB. The GUI uses a viewport and an LRU cache of at most 50MB from `lru` 0.12. +- `map::tmx::export_tmx()` converts a `.map` file and tilesets to Tiled TMX XML. The XML uses isometric projection and CSV tile data. +- SNF audio has a custom PCM header. `SnfFile::to_wav_bytes()` prepends a RIFF WAVE header. +- Fixed DB record sizes: WeaponItem 284B, Monster 160B, Magic 88B, HealItem 252B, EditItem 268B, EventItem 240B, MiscItem 256B, ChData 84B and Store 948B with a variable product list. +- Other fixed sizes: PartyIniNpc 28B, PartyLevelNpc 5760B for an 8×20 grid, NPC 672B, MonsterRef 56B and ExtraRef 184B. +- `SaveFile` and `SaveIfo` use variable layouts. See `docs/files/`. +- `references/layout.rs` defines `FieldDef`, `FixedRecordLayout` and the `RecordLayout` derive trait. They generate byte-offset metadata for fixed-size records. See `docs/file_formats.md` and per-file `docs/files/*.md` for detailed specs. @@ -158,7 +160,7 @@ See `docs/file_formats.md` and per-file `docs/files/*.md` for detailed specs. | `RecordPatcher` | `modding/patcher.rs` | Applies mod patches to individual records. Two derive variants (binary + text). | | `Command` | `commands/mod.rs` | CLI command trait: `fn execute(&self) -> Result<(), Box>` | -### Modding pipeline (`src/modding/`) +### Mod pipeline (`src/modding/`) Core modules: `apply`, `bsdiff`, `change`, `changelog`, `conflicts`, `manifest`, `package`, `patcher`, `registry`, `resolution`, `value`, `vanilla`, `workspace` (+ `error.rs`). Per-format record patchers live in `modding/patchers/`: `derived`, `dialogue`, `draw_item`, `event_script`, `misc_item`, `party_level`, `quest`, `save_ifo`, `store`. @@ -167,21 +169,21 @@ Core modules: `apply`, `bsdiff`, `change`, `changelog`, `conflicts`, `manifest`, - Other modules use `std::io::Result` / `rusqlite::Result` directly (plus thiserror errors in `dispel-gui`'s indexation/file-tree modules). ### Encoding helpers -- `dispel-encodings` crate — single source of truth for accepted spellings (`WINDOWS-1250`/`WINDOWS_1250`, `EUC-KR`/`EUC_KR`, `UTF-8`/`UTF_8`, case-insensitive), CSV/PO labels and the `encoding_rs` mapping. Both `dispel-macros` (compile time) and `dispel-core` (runtime) consume it. -- `TextEncoding` — re-exported from `localization.rs` (defined in `dispel-encodings`); `encoding_rs_for()`, `encoded_len()` in `localization.rs` -- `read_null_terminated(bytes, &TextEncoding)` — in `references/extractor.rs`; `read_null_terminated_windows_1250()` is its backward-compatible wrapper -- `WINDOWS_1250` / `EUC_KR` still used directly in a few hand-written parsers/patchers (not yet routed through the registry) -- Enum wire-value fallback (`from_X(v).unwrap_or_default()`) lives once in `references/enums.rs::WireValue::from_wire`; the derive macros call it so parse and patch agree +- The `dispel-encodings` crate holds accepted spellings (`WINDOWS-1250`/`WINDOWS_1250`, `EUC-KR`/`EUC_KR`, `UTF-8`/`UTF_8`, case-insensitive). It also holds CSV/PO labels and the `encoding_rs` mapping. `dispel-macros` reads it at compile time. `dispel-core` reads it at runtime. +- `localization.rs` re-exports `TextEncoding` from `dispel-encodings`. The same file defines `encoding_rs_for()` and `encoded_len()`. +- `references/extractor.rs` defines `read_null_terminated(bytes, &TextEncoding)`. It also defines the wrapper `read_null_terminated_windows_1250()`. +- A few hand-written parsers and patchers use `WINDOWS_1250` and `EUC_KR` directly. +- `references/enums.rs::WireValue::from_wire` holds the enum wire-value fallback `from_X(v).unwrap_or_default()`. The derive macros call it. Parse and patch then agree. ### SQLite schema (`src/queries/`) -118 SQL files: 59 `create_table_*.sql` (schema DDL) + 59 parameterized `insert_*.sql`. Run by `database.rs` to drop and recreate the schema. **No foreign keys** — relationships are enforced in code, not SQL constraints. +The directory holds 118 SQL files: 59 `create_table_*.sql` files for schema DDL and 59 parameterized `insert_*.sql` files. `database.rs` runs them to drop and recreate the schema. The schema has no foreign keys. Code enforces relationships. ### Tests -**95 `#[cfg(test)]` blocks across 87 `.rs` files** in the root crate. Parsers have hardcoded-byte-slice unit tests; save-file round-trip checking lives in `examples/check_save_roundtrip.rs`. +The root crate has **95 `#[cfg(test)]` blocks across 87 `.rs` files**. Parsers use hardcoded byte-slice unit tests. Save-file round-trip checking lives in `examples/check_save_roundtrip.rs`. --- -## dispel-macros — Proc-Macro Crate +## dispel-macros: proc-macro crate 7 derive macros using `syn 2` + `quote 1`: @@ -195,13 +197,13 @@ Core modules: `apply`, `bsdiff`, `change`, `changelog`, `conflicts`, `manifest`, | `#[derive(TextRecordPatcher)]` | `RecordPatcher` impl (text) + unit struct | Modding for text formats | | `#[derive(Localizable)]` | `Localizable` impl | Translation extraction | -**Attributes:** `#[extractor(id, string, primitive, enum_from_*, padding, array, skip, ...)]` on binary; `#[extractor(field=N, parse_null, enum_from_i32)]` + struct-level `encoding, delimiter, comment_char` on text; `#[patcher(filename=...)]` or `#[patcher(extension=..., stem_prefix=...)]`; `#[translatable(encoding=..., max_bytes=N)]`. +Attributes: `#[extractor(id, string, primitive, enum_from_*, padding, array, skip, ...)]` on binary records. Text records use `#[extractor(field=N, parse_null, enum_from_i32)]` and struct-level `encoding, delimiter, comment_char`. Patchers use `#[patcher(filename=...)]` or `#[patcher(extension=..., stem_prefix=...)]`. Translatable fields use `#[translatable(encoding=..., max_bytes=N)]`. -**Used by 26+ structs in `src/references/`.** No direct unit tests — verified indirectly via dependent crate's tests. +26+ structs in `src/references/` use these macros. There are no direct unit tests. Dependent crates test them indirectly. --- -## gui-widgets — Reusable Iced Widgets +## gui-widgets: reusable Iced widgets | Widget | Location | Purpose | |---|---|---| @@ -220,24 +222,24 @@ Also: `sweeten/` (builder-style helpers) and `lucide.rs` (icon set). --- -## hexedit — Hex Editor Crate +## hexedit: hex editor crate Standalone library + single binary (`hexedit`, `src/main.rs`). Rust edition 2024. Iced (fork) with no features of its own. Structure: - Top level: `app.rs`, `config.rs`, `state.rs`, `message.rs`, `main.rs` -- `domain/` (~16 files): editing, goto, pattern, provider, search, selection, vanilla_diff, … -- `ui/`: coloring, inspector, update, view/, theme -- `tests/`: 16 dedicated test files (**26 `.rs` files with `#[cfg(test)]` total**) +- `domain/` holds about 16 files: edit, goto, pattern, provider, search, selection and vanilla_diff. +- `ui/` holds the inspector, update, view/, theme and colouring modules. +- `tests/` holds 16 dedicated test files (**26 `.rs` files with `#[cfg(test)]` total**). -**Used by `dispel-gui`:** stored as `HashMap` in `EditorRegistry`, rendered in tabs, with save wired to mod packager via the domain-level `SavePort` (`SaveRequest` → `SaveOutcome`) in `hex_save.rs`. +`dispel-gui` stores hexedit state as `HashMap` in `EditorRegistry`. Tabs render it. `hex_save.rs` wires saves to the mod packager through the domain-level `SavePort` (`SaveRequest` → `SaveOutcome`). --- ## dispel-gui Architecture ### Tech Stack -- **UI**: Iced from git fork `dimspell/iced` (rev `c0ffdd8`; GPU via wgpu, Elm/MVU, advanced + lazy features) +- UI: Iced from the git fork `dimspell/iced`, rev `c0ffdd8`. It uses wgpu, Elm/MVU, advanced and lazy features. - **Async**: Tokio multi-thread runtime + `iced::Task::perform` - **Core**: `dispel_core` (sibling crate) - **Search**: nucleo-matcher 0.3 (fuzzy full-text) @@ -245,8 +247,11 @@ Structure: - **File dialogs**: rfd 0.16 - **Window**: 1100×800, custom "Medieval" theme (dark leather/gold) - **macOS native**: objc2 + objc2-app-kit + objc2-foundation (context menus, file manager reveal) -- **Accessibility**: forked iced `accessibility` feature with vendored accesskit; enabled on `dispel-gui` only. The workspace `[patch.crates-io]` pins `winit` to an iced-rs fork for version alignment. Only `table_widget` implements full accesskit nodes (`accessibility()` + `accessibility_action()`). Custom widgets (context menu, modal, hex matrix) use the default no-op methods. -- **Tests**: `iced_test` (same git fork, optional feature), `proptest`, `syn` +- Accessibility: the forked iced `accessibility` feature uses vendored accesskit. Only `dispel-gui` enables it. +- The workspace `[patch.crates-io]` pins `winit` to an iced-rs fork for version alignment. +- Only `table_widget` implements full accesskit nodes with `accessibility()` and `accessibility_action()`. +- Custom widgets such as the context menu, modal and hex matrix use the default no-op methods. +- Tests: `iced_test` from the same fork as an optional feature, `proptest` and `syn`. ### Flow `user action → Message → update/ handler (mutates App + AppState) → view/ (pure render)` @@ -281,27 +286,27 @@ Top-level `Message` enum (`message/mod.rs`) has 5 variants: **`MessageExt` trait** (`message/ext.rs`, generated by `define_message_ext!` macro) provides shorthand constructors like `Message::weapon(WeaponEditorMessage::LoadCatalog)`. -### Editor System — 46 editor types / 47 registry state fields +### Editor system: 46 editor types and 47 registry state fields -`EditorType` is generated by `define_editor_catalog!` in `editor_catalog/mod.rs` (re-exported from `workspace.rs`); it has 45 named variants + `Unknown` (with `#[serde(other)]`), and `EDITOR_COUNT` is 46. Variants are suffixed `Editor` (e.g. `WeaponEditor`, `SaveIfoEditor`); new since v0.7: `SaveFileViewer`, `SaveIfoEditor`, `HexEditor`, `DialogueTextEditor`, `AudioViewer`, `BmpViewer`. +`editor_catalog/mod.rs` defines `EditorType` through `define_editor_catalog!`. `workspace.rs` re-exports the type. It has 45 named variants plus `Unknown`, which uses `#[serde(other)]`. `EDITOR_COUNT` is 46. Variants end in `Editor`, for example `WeaponEditor` and `SaveIfoEditor`. Version 0.7 added `SaveFileViewer`, `SaveIfoEditor`, `HexEditor`, `DialogueTextEditor`, `AudioViewer` and `BmpViewer`. -**Standard editors (20)** — macro-generated via `define_standard_editor!`, invoked in each editor's own `editors//mod.rs`: +Twenty standard editors use `define_standard_editor!` in their own `editors//mod.rs`: `weapon`, `monster`, `heal_item`, `misc_item`, `edit_item`, `event_item`, `party_ref`, `all_map_ini`, `event_ini`, `draw_item`, `chdata`, `event_npc_ref`, `map_ini`, `npc_ini`, `message_scr`, `extra_ini`, `magic`, `quest_scr`, `monster_ini`, `party_ini` -**Custom boxed editors** — custom state in `Box<...>` (all listed in `EditorRegistry`): +Custom boxed editors keep state in `Box<...>`. All appear in `EditorRegistry`: `save_ifo_editor`, `event_scr`, `wave_ini`, `store`, `party_level_db`, `localization_manager`, … -**Tabbed editors (5)** — `TabbedEditor` (HashMap>): +Five tabbed editors use `TabbedEditor`, a HashMap from tab IDs to `MultiFileEditorState`: `monster_ref`, `dialogue_script`, `dialogue_paragraph`, `extra_ref`, `npc_ref` **Single-instance special editors:** mod_packager_editor (ModPackagerState) -**Per-tab HashMap editors (8)** — one state per open tab: +Eight per-tab HashMap editors keep one state per open tab: `sprite_viewers`, `map_editors`, `tileset_editors`, `snf_editors`, `audio_viewers`, `bmp_viewers`, `hex_editors`, `save_file_viewers` ### `define_standard_editor!` macro -Generates from a single declaration (now placed in each editor's `editors//mod.rs`): +The macro generates code from one declaration in each `editors//mod.rs`: ```rust define_standard_editor! { name: weapon, @@ -317,7 +322,7 @@ Produces: `pub type WeaponEditorState = StandardEditor`, `pub type W ### `EditorRegistry` (`editor_registry.rs`) -Aggregates all editor state fields. Provides consolidated lifecycle: +This struct holds all editor state fields and provides the lifecycle methods: | Method | Role | |---|---| @@ -331,7 +336,7 @@ Aggregates all editor state fields. Provides consolidated lifecycle: | `stop_snf_playback()` | Stops any playing SNF audio | | `stop_audio_playback()` | Stops any playing audio-viewer audio | -**Principle:** `AppState` exposes only pass-through methods — all real work lives in `EditorRegistry`. +Principle: `AppState` exposes pass-through methods only. `EditorRegistry` does the work. ### Workspace & Tab Management (`workspace.rs`) @@ -352,8 +357,8 @@ pub struct Workspace { 3-pane layout (sidebar | main content | history panel) using `pane_grid::State`. `PaneContent` enum: `Sidebar | MainContent | HistoryPanel`. `PaneState` tracks focus and maximized. ### Subscriptions (`subscriptions.rs`) -- Keyboard handling via a single `keyboard::listen()` filter (shortcuts live in the filter logic, not a literal key list) -- Separate global-search subscription; Event Script Editor ESC-shortcut subscription +- Keyboard handling uses one `keyboard::listen()` filter. Shortcuts live in the filter logic, not a literal key list. +- A separate subscription handles global search. Another handles the Event Script Editor ESC shortcut. - Sprite animation tick (16ms) - SNF and audio-viewer playback poll (250ms) - Event script indexing poll (100ms) @@ -373,30 +378,30 @@ pub struct Workspace { ### Mod Recording -`RecordingSession` is defined in `state.rs`. Every `FieldChanged` handler calls `observe_field_change()` in `editors/mod_packager/recording.rs`. Records are debounced via `PendingEdit` / `RecordingKey` per field edit, then flushed to the mod changelog on save. 38 integration tests in `recording_tests.rs` cover macro-generated, custom-wrapper, fully-custom, and tab-based editor types. +`state.rs` defines `RecordingSession`. Each `FieldChanged` handler calls `observe_field_change()` in `editors/mod_packager/recording.rs`. The tool debounces records through `PendingEdit` and `RecordingKey` for each field edit. It flushes them to the mod changelog on save. `recording_tests.rs` holds 38 integration tests. They cover macro-generated, custom-wrapper, fully custom and tab-based editor types. ### Indexation & Search `indexation/` module: -- `file_index_cache.rs` — `FileIndexCache` + `FileIndexCacheManager` (persistent bincode on disk) -- `indexation_service.rs` — `IndexationService` background file scanning -- `search_index.rs` — `SearchIndex` nucleo-matcher full-text search with persistence -- `tests.rs` — Indexation tests +- `file_index_cache.rs`: `FileIndexCache` and `FileIndexCacheManager`, stored as bincode on disk +- `indexation_service.rs`: `IndexationService` scans files in the background +- `search_index.rs`: `SearchIndex` uses nucleo-matcher and persists its index +- `tests.rs`: indexation tests -### Adding a New Editor +### Add a new editor -1. Implement `Extractor` (derive via `dispel-macros`) in `dispel-core/src/references/` +1. Implement `Extractor` with `dispel-macros` in `dispel-core/src/references/` 2. If single-file spreadsheet: invoke `define_standard_editor!` in `dispel-gui/src/editors//mod.rs` 3. Otherwise: create `editors/my_editor/{mod,state,message,update,view}.rs` -4. Add field to `EditorRegistry` (not `AppState` — editors are consolidated) +4. Add a field to `EditorRegistry`, not `AppState`. The registry holds all editor state. 5. Add `EditorMessage` variant in `message/editor/mod.rs` (use `define_message_ext!` macro for shorthand) -6. Add handler in `update/editor/` and route via `dispatch_table.rs` / `update/editor/mod.rs` +6. Add a handler in `update/editor/`. Route it through `dispatch_table.rs` and `update/editor/mod.rs`. 7. Wire `EditorType::from_path()` for file extension detection (in `workspace.rs`) 8. Wire `view/mod.rs` dispatch (the `view_editor` match) 9. Wire `EditorRegistry` lifecycle methods (`remove_tab`, `undo_active`, etc.) -10. Delete old editor code — never keep both +10. Delete old editor code. Never keep both. -### Naming Glossary +### Glossary | Term | Meaning | |------|---------| @@ -414,7 +419,7 @@ pub struct Workspace { - **State mutation**: `update/` only. Views are pure. - **Views**: defined as `impl App` blocks in `view/*.rs`, not `app.rs`. - **Messages**: use `define_message_ext!` macro for shorthand constructors. -- **Scan vs Browse**: "Scan" = load from `shared_game_path`; "Browse" = file picker. +- Scan and Browse: Scan loads from `shared_game_path`. Browse opens a file picker. - **Game files**: editors read/write game files directly. - **Enums over booleans**: e.g. `LoadingState { Idle, Loading, Loaded(T), Failed(String) }` - **Editor state lives on `EditorRegistry`, not `AppState`**. @@ -433,34 +438,41 @@ pub struct Workspace { | `docs/iced-fork-config.md` | Single iced fork pin set, feature matrix, headless test backend, consistency check | | `docs/files/*.md` | **36 per-format docs** (in subdirectories `CharacterInGame/`, `MonsterInGame/`, `NpcInGame/`, `Ref/`, `Map/`, `ExtraInGame/`, `MagicInGame/` and at the top level) + `CROSS_REFERENCES.md` — 37 files total | -Always read the relevant `docs/files/*.md` before modifying a parser. +Read the relevant `docs/files/*.md` before you change a parser. ## Build System & CI ### Makefile targets (95 total) - Basic dev: `fmt`, `check`, `build`, `cargo_test`, `clippy`, `run`, `help`, `check_iced_config`, `check_metadata`, `check_metadata_test` -- Build, fmt, clippy and test recipes delegate to **`scripts/ci-commands.sh`** — the one canonical command set shared with CI. Set `ICED_TEST_BACKEND=software` where Iced simulations need the CPU renderer. -- `iced_test`, `hexedit_test` — headless GUI/hexedit test suites -- `hexedit` — launch the hex editor -- Extraction/render: `sound`, `sprite-*`, `map-render` (+ 13 `map-render-*` flavors), `map-atlas-gtl/btl`, `map-to-db` / `map-from-db` - - Every `map-render*` flavor is generated from **one** recipe plus a flag table (`MAP_RENDER_ARGS`, per-flavor `MAP_RENDER_EXTRA`) and the `MAP_RENDER_TARGETS` list. A common flag change touches `MAP_RENDER_ARGS` only. - - `light_template` is configurable (`make map-render-lit light_template=/path/to/light_template.png`); the default is `$(game_path)/Map/light_template.png` and assumes no sibling repo. -- `extract-*` (~24 targets) — extract individual game files to JSON -- `database-*` — SQLite import (maps, databases, refs, rest, dialog-texts) -- `template*`, `patch-*`, `list-json`, `sprite-info`, `mod-pack-*` — misc pipelines - -`make help` lists CLI subcommands; the Makefile's `.PHONY` list is kept in sync with real recipes by `scripts/check-project-metadata.sh`. +- Build, fmt, clippy and test recipes call `scripts/ci-commands.sh`. This is the single canonical command set shared with CI. Set `ICED_TEST_BACKEND=software` where Iced simulations need the CPU renderer. +- `iced_test` and `hexedit_test` run headless GUI and hexedit suites. +- `hexedit` launches the hex editor. +- Extraction and render targets: `sound`, `sprite-*`, `map-render` plus 13 `map-render-*` flavors, `map-atlas-gtl/btl`, `map-to-db` and `map-from-db`. + - One recipe and a flag table generate every `map-render*` flavor. The table holds `MAP_RENDER_ARGS` and per-flavor `MAP_RENDER_EXTRA`. The `MAP_RENDER_TARGETS` list names the flavors. A common flag change touches `MAP_RENDER_ARGS` only. + - `light_template` is configurable with `make map-render-lit light_template=/path/to/light_template.png`. The default is `$(game_path)/Map/light_template.png`. It assumes no sibling repo. +- `extract-*` has about 24 targets. They extract individual game files to JSON. +- `database-*` imports maps, databases, refs, rest and dialog texts to SQLite. +- `template*`, `patch-*`, `list-json`, `sprite-info` and `mod-pack-*` run miscellaneous pipelines. + +`make help` lists CLI subcommands. `scripts/check-project-metadata.sh` keeps the Makefile `.PHONY` list in sync with real recipes. ### GitHub Actions -- `.github/workflows/test.yml` — CI on push to `master`: fmt, iced-config + metadata checks, clippy, full test suite, build on ubuntu-latest -- `.github/workflows/pr.yml` — same verify job, then a 5-build release-binary matrix -- `.github/workflows/release.yml` — Release on tag `v*.*.*`: the same 5 builds, archives with SHA256, uploads to GitHub release (draft) -- Both matrix workflows read the **single** matrix definition in `.github/build-matrix.json` via a `build-matrix` job and `fromJSON(needs.build-matrix.outputs.matrix)` — target lists cannot drift between PR and release. -- All three workflows use `dtolnay/rust-toolchain@stable`. The test.yml and pr.yml verify jobs call `scripts/ci-commands.sh` for fmt/clippy/test; test.yml also routes its workspace build through the script. Release matrix builds invoke Cargo directly with each target's flags. -- `scripts/check-project-metadata.sh` (also run by the Makefile) validates AGENTS.md counts, `.PHONY` ↔ recipe parity, canonical command parity, and matrix parity. `scripts/test-check-project-metadata.sh` injects eight independent drifts into a scratch tree to test that validator; both run in `test.yml` and `pr.yml`. +- `.github/workflows/test.yml`: CI on push to `master` runs fmt, iced-config and metadata checks, clippy, the full test suite and a build on ubuntu-latest. +- `.github/workflows/pr.yml`: the same `verify` job, then a 5-build release-binary matrix. +- `.github/workflows/release.yml`: Release on tag `v*.*.*` runs the same 5 builds. It archives with SHA256 and uploads to a draft GitHub release. +- Both matrix workflows read one definition in `.github/build-matrix.json`. A `build-matrix` job reads it with `fromJSON(needs.build-matrix.outputs.matrix)`. Target lists cannot drift between PR and release. +- All three workflows use `dtolnay/rust-toolchain@stable`. The `verify` jobs in test.yml and pr.yml call `scripts/ci-commands.sh` for fmt, clippy and test. test.yml also routes its workspace build through the script. Release matrix builds invoke Cargo directly with each target's flags. +- `scripts/check-project-metadata.sh` (also run by the Makefile) validates AGENTS.md counts, `.PHONY` ↔ recipe parity, canonical command parity, and matrix parity. `scripts/test-check-project-metadata.sh` injects eight independent drifts into a scratch tree to test that validator. Both scripts run in `test.yml` and `pr.yml`. ### Release script -`scripts/release.sh` automates: validate semver → `bash scripts/ci-commands.sh fmt-check` + `bash scripts/ci-commands.sh test` → bump version in all workspace `Cargo.toml` (discovered via `cargo metadata`) → regen `Cargo.lock` via `bash scripts/ci-commands.sh check` → commit + tag `v{major}.{minor}.{patch}` → print push instructions. +`scripts/release.sh` automates these steps: + +1. Validate the semver value. +2. Run `bash scripts/ci-commands.sh fmt-check` and `bash scripts/ci-commands.sh test`. +3. Bump the version in every workspace `Cargo.toml` found through `cargo metadata`. +4. Regenerate `Cargo.lock` with `bash scripts/ci-commands.sh check`. +5. Commit and tag `v{major}.{minor}.{patch}`. +6. Print push instructions. --- @@ -469,22 +481,22 @@ Always read the relevant `docs/files/*.md` before modifying a parser. ### Error Handling - `dispel-core`: `thiserror` for enumerable error types (see `ModdingError`) - GUI/CLI: `anyhow` for contextual bubbling -- Never `.unwrap()` on file I/O — show errors in `status_msg` -- **Never swallow I/O or serialization errors** with `let _ =` or `.unwrap_or_default()` — log them via `eprintln!` or propagate with `?` +- Never call `.unwrap()` on file I/O. Show errors in `status_msg`. +- Never swallow I/O or serialization errors with `let _ =` or `.unwrap_or_default()`. Log them with `eprintln!` or propagate them with `?`. ### State & Async - Use **enums over booleans**: `LoadingState { Idle, Loading, Loaded(T), Failed(String) }` -- Always use `Task::perform` for async work — never block +- Always use `Task::perform` for async work. Never block. ### Code Quality -- Clippy: zero warnings; format before commit; validate all binary bounds before indexing -- Compiler warnings: use the `cargo test … --no-run` command in [Quick Commands](#quick-commands) to compile all crates (including tests) and surface compiler warnings without waiting for tests to execute — useful as a fast pre-commit check +- Clippy: keep zero warnings. Format code before you commit. Validate binary bounds before you index data. +- Compiler warnings: run the `cargo test … --no-run` command in [Quick Commands](#quick-commands). It compiles all crates and their tests. It surfaces compiler warnings without running the tests. Use it as a fast pre-commit check. ### Testing -**Writing effective tests:** The goal is finding real bugs, not just confirming compilation. Prefer integration tests (iced_test) that simulate real user flows — they catch behavioral regressions, state corruption, and edge cases that unit tests miss. +Effective tests: find real bugs. Compilation alone is not enough. Prefer `iced_test` integration tests that simulate user flows. They catch behavioural regressions, state corruption and edge cases. - **dispel-core**: unit test every new parser with hardcoded byte slices (95 `#[cfg(test)]` blocks across 87 `.rs` files) -- **dispel-gui**: write iced_test integration tests that simulate real user flows (open tabs, edit data, undo/redo, save). Test state transitions and behaviors, not visuals. Dedicated suite in `dispel-gui/src/tests/` (28 files) plus co-located `#[cfg(test)]` blocks. +- dispel-gui: write iced_test integration tests that simulate user flows, such as tab opens, data edits, undo, redo and saves. Test state transitions and behaviour, not visuals. The dedicated suite is in `dispel-gui/src/tests/` (30 files), with co-located `#[cfg(test)]` blocks. - **Round-trip checks**: `examples/check_save_roundtrip.rs` (parse → write → compare) - **Test naming**: `test_${scenario}_${condition}` e.g. `test_undo_weapon_editor_empty_history` - **Test helpers**: tests in `$module/tests.rs` (co-located), separate `recording_tests.rs` for recording @@ -528,33 +540,20 @@ Subcommands defined in `src/cli.rs`: extract, patch, validate, list, schema, tem --- -## Legal Compliance - -**✅ Permitted:** -- Analyzing file formats, documenting specs -- Creating modding/interoperability tools -- Using "Dispel" for identification only - -**❌ Prohibited:** -- Extracting/distributing copyrighted content -- Bypassing copy protection -- Commercial exploitation -- Using DISPEL® trademark beyond identification - -**When mentioning Dispel:** Use **DISPEL®** with ® symbol on first mention. Include disclaimer: "not affiliated with, endorsed by, or sponsored by the trademark owner." +Scope and legal notice: see README.md. --- ## Common Pitfalls -- **Circular imports**: GUI ↔ core must never share presentation code -- **Blocking UI**: All file I/O is async via Task -- **Unsafe parsing**: Validate all bounds before indexing +- Circular imports: GUI and core must never share presentation code. +- UI blocking: run all file I/O asynchronously through Task. +- Unsafe parsing: validate all bounds before you index data. - **Hardcoded paths**: Use `dirs` crate for config/cache (`~/.config/dispel-gui/`) -- **Text encoding**: Check encoding table before reading — wrong codec = corruption -- **Map memory**: Never load full rendered map (~300MB); use viewport + LRU cache -- **Macros have no unit tests**: `dispel-macros` is verified only via dependent crate's tests -- **Editor count drifts**: Verify editor count against `EditorRegistry` and `EditorType` if unsure +- Text encoding: check the encoding table before you read. The wrong codec corrupts text. +- Map memory: never load a full rendered map of about 300MB. Use a viewport and an LRU cache. +- Macro tests: `dispel-macros` has no direct unit tests. Dependent crates test it. +- Editor count drift: check the count against `EditorRegistry` and `EditorType` when unsure. --- @@ -576,14 +575,14 @@ make iced_test # Iced UI simulation tests `make build`, `make fmt`, `make clippy`, `make cargo_test`, `make check`, `make iced_test` and `make hexedit_test` are thin wrappers around -`scripts/ci-commands.sh`; CI calls the same subcommands. Never introduce a +`scripts/ci-commands.sh`. CI calls the same subcommands. Never introduce a second inline spelling of these commands. ### rtk (Rust Token Killer) -**Always use `rtk` instead of the bare command** when running these operations. It compresses output by 60-90%, saving significant context window for real work. +Always use `rtk` instead of the bare command for these operations. It compresses output by 60 to 90%. This saves context for real work. -Note: the rtk hook only applies to Bash tool calls — built-in tools like `Read`, `Grep`, and `Glob` bypass it. For token-efficient file access, prefer shell commands through `rtk read`, `rtk grep`, `rtk ls` instead of the built-in tools. +The rtk hook applies only to Bash tool calls. Built-in tools such as `Read`, `Grep` and `Glob` bypass it. For token-efficient file access, use `rtk read`, `rtk grep` and `rtk ls`. ```bash rtk cargo test -v [cargo test args...] # Tests with compact output (failures only, ~-90%) @@ -599,15 +598,15 @@ rtk read file.rs # Smart file reading ## iced GUI patterns -This project uses iced from a git fork: `https://github.com/dimspell/iced` (pinned rev `c0ffdd8`). It is a nightly version (v0.15-dev) with modifications to handle accessibility features (like a VoiceOver screen reader). A local clone may exist at `../iced` for development. +The project uses iced from a git fork at `https://github.com/dimspell/iced`, pinned at rev `c0ffdd8`. The fork is a nightly version, v0.15-dev. It includes accessibility changes such as VoiceOver support. A local clone may exist at `../iced` for development. ### Custom patterns -Custom patterns are in the `gui-widgets` crate - `./gui-widgets/src`. +Custom patterns are in the `gui-widgets` crate at `./gui-widgets/src`. ### `min` and `max` methods for `Length` -There are `min` and `max` methods to the `Length` type, allowing to define minimum and maximum constraints for any widget: +The `Length` type has `min` and `max` methods. They set minimum and maximum constraints for any widget: ```rs row![ @@ -618,10 +617,9 @@ row![ ### Notification on `scale_factor` change -`window::Event::Resized` is notified when `scale_factor` changes. +The tool receives `window::Event::Resized` when `scale_factor` changes. --- *Last updated: 2026-11-19* -**DISPEL®** is a registered trademark. This project is **not affiliated with, endorsed by, or sponsored by** the trademark owner. From dae2c4a79be8f8a71a9fe9a0c04e3cb2fc186a47 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:00:03 +0100 Subject: [PATCH 08/72] docs: align agent guide version and sound example --- AGENTS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e1f909f7..ef5086ac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ This toolkit reads and writes game files in binary, INI and DB formats. It also ## Project Overview -The workspace is a **6-crate Cargo workspace** with Rust edition 2024 and version `0.9.3`. +The workspace is a **6-crate Cargo workspace** with Rust edition 2024 and version `0.9.5`. | Crate | Type | Role | |---|---|---| @@ -527,7 +527,7 @@ cargo run -- map tiles "file.gtl" --output dir/ cargo run -- map render --map file.map --btl file.btl --gtl file.gtl --output out.png # Audio -cargo run -- sound "file.snf" output.wav +cargo run -- sound to-wav "file.snf" output.wav # SQLite (optional) cargo run -- database import "path/to/Dispel/" db.sqlite From 404c11e0bf58ac3db55cc48887959a85cd3b5bda Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:05:13 +0100 Subject: [PATCH 09/72] docs: keep the shared notice unique in the root readme --- README.md | 4 ++-- hexedit/README.md | 4 ---- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index dfc95c9b..e50e6280 100644 --- a/README.md +++ b/README.md @@ -4,11 +4,11 @@ This toolkit reads and writes DISPEL® game files in binary, INI and DB formats. ## Scope and notice -This project reads and writes data files for DISPEL®. It ships no game content. You provide the files you edit. +This project reads and writes data files for DISPEL®. It ships no game content. You choose the files you edit. DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark owner. -The source code is licensed under the MIT License (LICENSE). Game content is not covered by this license. +The MIT License (LICENSE) covers the source code. It does not cover game content. ## What's in this repository diff --git a/hexedit/README.md b/hexedit/README.md index 71cd3322..6d697528 100644 --- a/hexedit/README.md +++ b/hexedit/README.md @@ -984,7 +984,3 @@ Keep these invariants when you change the code: ## Project context hexedit is part of the [Dispel RPG modding toolkit](https://github.com/piotr/dispel-extractor), a 6-crate Rust workspace: root `dispel-extractor`, `dispel-encodings`, `dispel-gui`, `dispel-macros`, `gui-widgets` and `hexedit`. It powers the hex editor tab inside `dispel-gui`. You can also use it standalone for general binary editing. - -## License - -The MIT License (LICENSE) covers `hexedit`. From 95a8df8de45541a198091211231b6612f7440e9a Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:25:43 +0100 Subject: [PATCH 10/72] docs: correct file cross references from code --- docs/files/CROSS_REFERENCES.md | 633 ++++++++++++++------------------- 1 file changed, 272 insertions(+), 361 deletions(-) diff --git a/docs/files/CROSS_REFERENCES.md b/docs/files/CROSS_REFERENCES.md index 4bbfd287..2c0544c4 100644 --- a/docs/files/CROSS_REFERENCES.md +++ b/docs/files/CROSS_REFERENCES.md @@ -1,406 +1,316 @@ -# Dispel game file system: cross references +# Dispel game files: cross references ## Overview -This document maps the cross references between game data files. The tool reads and writes data files that you supply. Each row below links a field in one file to a file name or a field in another file. +This document lists the links between game data files. The tool reads and writes the files that you supply. Each link connects a field in one file with a field in another file. Some links point to a file name instead of a field. -## File Dependency Map +## File dependency map -### Core Configuration Files (INI) +This section groups files by role. A family name such as `DlgMapFiles.dlg` stands for a set of real files. A real file name such as `Dlgcat1.dlg` names one file on disk. -- **AllMap.ini**: Master map index linking maps to resources -- **Map.ini** (Ref/): Map initialization with positions and resource links -- **Monster.ini** (CharacterInGame/): Monster visual definitions and animations -- **Npc.ini**: NPC visual definitions and sprite references -- **Extra.ini**: Interactive object definitions -- **Event.ini**: Event scripts with conditions and triggers -- **Wave.ini**: Sound effect mappings +### Core configuration files (INI) -### Database Files (DB) +- `AllMap.ini`: Master map index. It lists each map and its resources. +- `Ref/Map.ini`: Map setup with spawn coordinates and file links. Each row holds one entrance. +- `CharacterInGame/Monster.ini`: Monster visuals and animation sequences. +- `Npc.ini`: NPC visuals and sprite file names. +- `Extra.ini`: Interactive object definitions. +- `Event.ini`: Event conditions and script file names. +- `Wave.ini`: Sound effect names that point to `.snf` files. -- **Monster.db** (MonsterInGame/): Monster combat statistics and AI -- **WeaponItem.db** (CharacterInGame/): Weapons and armor with stats -- **HealItem.db** (CharacterInGame/): Consumable healing items -- **MiscItem.db** (CharacterInGame/): Generic utility items -- **EditItem.db** (CharacterInGame/): Modifiable equipment items -- **EventItem.db** (CharacterInGame/): Quest and event items -- **Store.db** (CharacterInGame/): Shops and inns with inventories -- **ChData.db** (CharacterInGame/): Character statistics tracking -- **PrtLevel.db** (NpcInGame/): Character progression (levels 1-20) -- **Magic.db** (Ref/): Spell database with effects -- **DrawItem.db** (Ref/): Object placements on maps +### Database files (DB) -### Reference Files (REF) +- `CharacterInGame/WeaponItem.db`: Weapons and armor with combat stats. +- `CharacterInGame/HealItem.db`: Consumable healing items. +- `CharacterInGame/EditItem.db`: Editable items that the player can change. +- `CharacterInGame/EventItem.db`: Quest and event items. +- `CharacterInGame/MiscItem.db`: Utility items. +- `CharacterInGame/STORE.DB`: Shops and inns with product lists. +- `CharacterInGame/ChData.db`: One record of initial class statistics. +- `MagicInGame/Magic.db`: Spell definitions and effects. +- `NpcInGame/PrtLevel.db`: Party growth records for eight slots and twenty levels. +- `MonsterInGame/Monster.db`: Monster combat statistics. -- **PartyRef.ref** (Ref/): Party character definitions -- **Eventnpc.ref** (NpcInGame/): Event-triggered NPC definitions -- **NpcMapFiles.ref** (NpcInGame/): NPC placements with waypoints -- **Extra.ref** (ExtraInGame/): Interactive object placements -- **fogdata.dat** (ExtraInGame/): Map lighting fade tables, consumed by the map renderer/editor (see [ExtraInGame/fogdata.dat.md](ExtraInGame/fogdata.dat.md)) -- **MondunMonmap.ref** (MonsterInGame/): Monster placements on maps +### Reference files (REF) -### Script Files (SCR/DLG/PGP) +- `Ref/PartyRef.ref`: Party member definitions and dialogue links. +- `MonsterInGame/Mondun01.ref`: Monster placements. `MondunMonmap.ref` is the family name. +- `NpcInGame/Npccat1.ref`: NPC placements. `NpcMapFiles.ref` is the family name. +- `ExtraInGame/Extdun01.ref`: Interactive object placements. `Extra.ref` is the family name. +- `NpcInGame/Eventnpc.ref`: NPCs that appear during events. +- `Ref/DRAWITEM.ref`: Map item drops. This is a parenthesized CSV file with EUC-KR text. +- `ExtraInGame/fogdata.dat`: Fade tables for map lighting. See [ExtraInGame/fogdata.dat.md](ExtraInGame/fogdata.dat.md). -- **Message.scr** (ExtraInGame/): UI text messages -- **Quest.scr** (ExtraInGame/): Quest journal entries -- **DlgMapFiles.dlg** (NpcInGame/): Dialogue conversation scripts -- **PgpMapFiles.pgp** (NpcInGame/): Dialogue text content +### Script files (SCR/DLG/PGP) -### Visual/Audio Assets +- `ExtraInGame/Message.scr`: UI text messages. +- `ExtraInGame/Quest.scr`: Quest journal entries. +- `NpcInGame/Dlgcat1.dlg`: Dialogue scripts. `DlgMapFiles.dlg` is the family name. +- `NpcInGame/Pgpcat1.pgp`: Dialogue text and parameters. `PgpMapFiles.pgp` is the family name. -- **Sprites.spr** (Map/): Sprite files for characters, monsters, objects -- **SNF files** (referenced by Wave.ini): Sound effect files -- **Map.map** (Map/): Map geometry and tile data -- **Map.gtl** (Map/): Ground tileset files -- **Map.btl** (Map/): Building/roof tileset files +### Visual, audio and map assets -### Map Tileset Relationships +- Map.map: Map geometry, tile layers and embedded sprites. +- Tileset files: Ground and roof tiles. Each map stem names its own pair of `.gtl` and `.btl` files. +- `.spr` files: Sprite art. File names come from `Monster.ini`, `Npc.ini` and `Extra.ini`. +- `.snf` files: Audio data. `Wave.ini` names these files. -``` -Map.map files - ├── gtl_tile_id → Map.gtl (ground tiles) - ├── btl_tile_id → Map.btl (building tiles) - └── event_id → Event.ini (tile events) - -Map.gtl (ground tiles) - └── Referenced by Map.map for terrain - -Map.btl (building tiles) - └── Referenced by Map.map for structures -``` - -## Cross-Reference Relationships +## Relationship diagrams -### 1. Map System Relationships +### 1. Map system ``` -AllMap.ini (master index) - ├── map_file → Map.map files - ├── pgp → PgpMapFiles.pgp (dialogue text) - └── dlg → DlgMapFiles.dlg (dialogue scripts) - -Map.ini (Ref/) - ├── id → AllMap.ini.id - ├── monsters → MondunMonmap.ref (monster placements) - ├── npcs → NpcMapFiles.ref (NPC placements) - ├── extras → Extra.ref (object placements) - ├── camera_event → Event.ini.event_id - └── cd_track → Audio track number - -Map.map (map geometry) - ├── gtl_tile_id → Map.gtl (ground tiles) - ├── btl_tile_id → Map.btl (building tiles) - ├── event_id → Event.ini (tile events) - └── Contains embedded sprites - -Map.gtl (ground tiles) - └── Referenced by Map.map for terrain - -Map.btl (building tiles) - └── Referenced by Map.map for structures +AllMap.ini + ├── id → row key + ├── map_filename → Map.map stem + ├── pgp_filename → Pgpcat1.pgp (dialogue text) + ├── dlg_filename → Dlgcat1.dlg (dialogue scripts) + └── lighting → MapLighting code + +Ref/Map.ini + ├── id → entrance row key + ├── map_id → AllMap.ini.id + ├── event_id_on_camera_move → event index + ├── start_pos_x / start_pos_y → spawn point + ├── monsters_filename → Mondun01.ref + ├── npc_filename → Npccat1.ref + ├── extra_filename → Extdun01.ref + └── cd_music_track_number → audio track ``` -### 2. Character System Relationships +### 2. Map.map layers ``` -PartyRef.ref (Ref/) - ├── npc_id → Npc.ini.id (visual appearance) - ├── map_id → AllMap.ini.id (recruitment location) - ├── dlg_out → DlgMapFiles.dlg.id (dialogue when not in party) - └── dlg_in → DlgMapFiles.dlg.id (dialogue when in party) - -Npc.ini (visual definitions) - └── sprite_filename → Sprites.spr files - -PrtLevel.db (character progression) - └── 8 NPC slots × 20 levels = character stat growth - -ChData.db (character statistics) - └── Tracks overall game/player statistics - -Character System Cross-References: - ├── PartyRef.ref → PrtLevel.db (character progression) - ├── PrtLevel.db → WeaponItem.db (equipment requirements) - ├── PrtLevel.db → Magic.db (spell access) - └── ChData.db → Overall game statistics +Map.map + ├── ground GTL index = (word >> 10) & 0x7FFF (Tile and Access words) + ├── BTL IDs → u16 array in the Tiled Objects block + ├── roof BTL index → bits 0..14 of the Access-Ref grid + ├── event IDs → bits 0..13 of a u32 (resolved via Map.ini and AllMap.ini) + └── sprites → embedded sprite block ``` -### 3. Monster System Relationships +### 3. Character data ``` -Monster.ini (visual definitions) - ├── sprite_filename → Sprites.spr files - ├── attack_seq → Sprite animation sequence - ├── hit_seq → Sprite animation sequence - ├── death_seq → Sprite animation sequence - ├── walk_seq → Sprite animation sequence - └── cast_seq → Sprite animation sequence - -Monster.db (combat statistics) - ├── known_spell_slot1 → Magic.db.id - ├── known_spell_slot2 → Magic.db.id - ├── known_spell_slot3 → Magic.db.id - └── AI type determines combat behavior - -MondunMonmap.ref (monster placements) - ├── mon_id → Monster.db.id (monster type) - ├── loot1/2/3_item_id → Item databases (loot drops) - └── Places monsters from Monster.db/ini on specific maps -``` +Ref/PartyRef.ref + ├── npc_id → Npc.ini.id (visual type) + ├── root_map_id → AllMap.ini.id + ├── dlg_when_not_in_party → PartyDlg.dlg paragraph + └── dlg_when_in_party → PartyDlg.dlg paragraph -### 4. NPC System Relationships +NpcInGame/PrtLevel.db + ├── 8 slots × 20 levels, with 36-byte records + ├── magic_spell_id_1 / 2 / 3 → spell indices + └── weapon_skill_level → skill level -``` -NpcMapFiles.ref (NPC placements) - ├── npc_id → Npc.ini.id (visual type) - ├── dialog_id → DlgMapFiles.dlg.id (dialogue script) - ├── show_on_event → Event.ini.event_id (visibility trigger) - └── Waypoints for patrol routes - -Eventnpc.ref (event NPCs) - ├── npc_ini_id → Npc.ini.id (visual type) - ├── show_on_event → Event.ini.event_id (trigger condition) - ├── dialog_id → DlgMapFiles.dlg.id (dialogue script) - └── Temporary NPCs appearing during specific events - -DlgMapFiles.dlg (dialogue scripts) - ├── prev_event → Event.ini.event_id (prerequisite) - ├── next_dlg → DlgMapFiles.dlg.id (conversation chain) - ├── dlg_id → PgpMapFiles.pgp.id (text content) - ├── event_id → Event.ini.event_id (triggered by dialogue) - └── Referenced by NpcMapFiles.ref and PartyRef.ref - -PgpMapFiles.pgp (dialogue text) - └── Contains actual dialogue text and parameters +CharacterInGame/ChData.db + └── one 84-byte record of initial class statistics ``` -### 5. Interactive Object System Relationships +### 4. Monster data ``` -Extra.ini (object definitions) - ├── sprite_filename → Sprites.spr files - └── flag (0=standard, 1=special/quest) - -Extra.ref (object placements) - ├── ext_id → Extra.ini.id (object type) - ├── event_id → Event.ini.event_id (interaction trigger) - ├── message_id → Message.scr.id (sign text) - ├── required_item_id → Item database - ├── required_item_type_id → Item type enum - ├── item_id → Item database (contents) - └── item_type_id → Item type enum - -DrawItem.db (object placements) - ├── map_id → AllMap.ini.id - └── item_id → Extra.ini.id or object database -``` +CharacterInGame/Monster.ini + └── sprite_filename → .spr file under CharacterInGame/ -### 6. Event System Relationships +MonsterInGame/Monster.db + ├── known_spell_slot1 / 2 / 3 → spell indices (-1 = SQL NULL) + └── combat statistics -``` -Event.ini (event definitions) - ├── required_event_id → Event.ini.id (prerequisite) - ├── script_filename → Script files (.scr) - └── event_type (0-8) determines execution logic - -Events are referenced by: - ├── Map.ini.camera_event - ├── NpcMapFiles.ref.show_on_event - ├── DlgMapFiles.dlg.event_id - ├── DlgMapFiles.dlg.prev_event - ├── Extra.ref.event_id - └── Eventnpc.ref.show_on_event +MonsterInGame/Mondun01.ref + ├── monster_db_id → Monster.db.id + ├── loot_item_1 / 2 / 3 → items lookup (type:ID) + └── event_id_on_kill → event index ``` -### 7. Item/Equipment System Relationships +### 5. NPC and dialogue data ``` -WeaponItem.db (weapons/armor) - ├── Referenced by Store.db products (type=0,1) - ├── Referenced by Extra.ref contents (item_type_id=0,1) - └── Referenced by MondunMonmap.ref loot (loot*_item_type) - -HealItem.db (consumable healing) - ├── Referenced by Store.db products (type=2) - ├── Referenced by Extra.ref contents (item_type_id=2) - └── Referenced by MondunMonmap.ref loot (loot*_item_type) - -MiscItem.db (generic utility items) - ├── Referenced by Store.db products (type=3) - ├── Referenced by Extra.ref contents (item_type_id=3) - └── Referenced by MondunMonmap.ref loot (loot*_item_type) - -EditItem.db (modifiable equipment) - ├── Referenced by Store.db products (type=4) - ├── Referenced by Extra.ref contents (item_type_id=4) - └── Referenced by MondunMonmap.ref loot (loot*_item_type) - -EventItem.db (quest items) - ├── Referenced by Extra.ref contents (item_type_id=5) - └── Quest progression tracking - -Store.db (shops/inns) - ├── products reference item databases - └── Commerce system with haggling and dialogue - -Item Type Enum (used in Extra.ref and Store.db): - ├── 1: Weapon → WeaponItem.db - ├── 2: Healing → HealItem.db - ├── 3: Edit → EditItem.db - ├── 4: Event → EventItem.db - ├── 5: Misc → MiscItem.db - └── -1: NoItem → no item (0xFF on disk; SQL/GUI keys use 255) +NpcInGame/Npccat1.ref + ├── npc_ini_id → Npc.ini.id + ├── dialog_id → Dlgcat1.dlg script + └── show_on_event → event index + +NpcInGame/Eventnpc.ref + ├── npc_ini_id → Npc.ini.id + ├── show_on_event → event index + └── dialog_id → Dlgcat1.dlg script + +NpcInGame/Dlgcat1.dlg (on-disk labels in parentheses) + ├── required_event_id (prev_event) → event index + ├── next_dialog_to_check (next_dlg) → Dlg script + ├── dialog_id (dlg_id) → Pgpcat1.pgp paragraph + └── triggered_event_id (event_id) → event index + +NpcInGame/Pgpcat1.pgp + └── dialogue text and parameters ``` -### 8. Audio System Relationships +### 6. Interactive object data ``` -Wave.ini (sound mappings) - └── snf_filename → .snf audio files - -Sound IDs referenced by: - ├── dialogue_paragraph.rs (wave_ini_entry_id) - └── Game events and interactions +ExtraInGame/Extra.ini + └── sprite_filename → .spr file under ExtraInGame/ + +ExtraInGame/Extdun01.ref + ├── extra_definition_id → Extra.ini.id + ├── map_object_id → map object number + ├── interaction_event_id → event index + ├── interaction_message_id → Message.scr.id + ├── required_item / required_item2 → items lookup (type:ID) + ├── loot_item → items lookup (type:ID) + ├── additional_loot_1 / additional_loot_2 → item IDs + ├── trap_spell_id → spell index + └── open_sfx_id → Wave.ini index + +Ref/DRAWITEM.ref + ├── map_id → AllMap.ini.id + ├── x_coord / y_coord → map position + └── item → items lookup (type:ID) ``` -### 9. Quest System Relationships +### 7. Events and audio ``` -Quest.scr (quest definitions) - ├── type (0=main, 1=side, 2=traders journal) - └── Referenced by event system +Event.ini + ├── required_event_id → event prerequisite + ├── event_filename → event script file + └── event_type → 0, 2, 5 or 6 -Message.scr (UI messages) - └── Referenced by Extra.ref.message_id for signs -``` - -## Complete Cross-Reference Table - -| Source File | Source Field | Target File | Target Field | Relationship | -|------------------|-----------------------|------------------|--------------|--------------------| -| AllMap.ini | map_file | Map.map | filename | Map geometry | -| AllMap.ini | pgp | PgpMapFiles.pgp | filename | Dialogue text | -| AllMap.ini | dlg | DlgMapFiles.dlg | filename | Dialogue scripts | -| Map.ini | monsters | MondunMonmap.ref | filename | Monster placements | -| Map.ini | npcs | NpcMapFiles.ref | filename | NPC placements | -| Map.ini | extras | Extra.ref | filename | Object placements | -| Map.ini | camera_event | Event.ini | event_id | Camera trigger | -| Monster.ini | sprite_filename | Sprites.spr | filename | Visual assets | -| Npc.ini | sprite_filename | Sprites.spr | filename | Visual assets | -| Extra.ini | sprite_filename | Sprites.spr | filename | Visual assets | -| PartyRef.ref | npc_id | Npc.ini | id | Visual appearance | -| PartyRef.ref | map_id | AllMap.ini | id | Location | -| PartyRef.ref | dlg_out | DlgMapFiles.dlg | id | Dialogue | -| PartyRef.ref | dlg_in | DlgMapFiles.dlg | id | Dialogue | -| NpcMapFiles.ref | npc_id | Npc.ini | id | NPC type | -| NpcMapFiles.ref | dialog_id | DlgMapFiles.dlg | id | Dialogue | -| NpcMapFiles.ref | show_on_event | Event.ini | event_id | Visibility | -| Eventnpc.ref | show_on_event | Event.ini | event_id | Trigger | -| Eventnpc.ref | npc_ini_id | Npc.ini | id | NPC type | -| Eventnpc.ref | dialog_id | DlgMapFiles.dlg | id | Dialogue | -| DlgMapFiles.dlg | prev_event | Event.ini | event_id | Prerequisite | -| DlgMapFiles.dlg | next_dlg | DlgMapFiles.dlg | id | Chain | -| DlgMapFiles.dlg | dlg_id | PgpMapFiles.pgp | id | Text | -| DlgMapFiles.dlg | event_id | Event.ini | event_id | Trigger | -| Extra.ref | ext_id | Extra.ini | id | Object type | -| Extra.ref | event_id | Event.ini | event_id | Interaction | -| Extra.ref | message_id | Message.scr | id | Sign text | -| Extra.ref | required_item_type_id | Item type enum | - | Key type | -| Extra.ref | item_type_id | Item type enum | - | Content type | -| Monster.db | known_spell_slot1-3 | Magic.db | id | Spells | -| DrawItem.db | map_id | AllMap.ini | id | Map location | -| DrawItem.db | item_id | Extra.ini | id | Object type | -| Map.map | gtl_tile_id | Map.gtl | id | Ground tiles | -| Map.map | btl_tile_id | Map.btl | id | Building tiles | -| Map.map | event_id | Event.ini | event_id | Tile events | -| Store.db | products | Item databases | id | Inventory | -| Store.db | products (type=0,1) | WeaponItem.db | id | Weapons/Armor | -| Store.db | products (type=2) | HealItem.db | id | Healing items | -| Store.db | products (type=3) | MiscItem.db | id | Misc items | -| Store.db | products (type=4) | EditItem.db | id | Modifiable items | -| Extra.ref | item_type_id=1 | WeaponItem.db | id | Weapons/Armor | -| Extra.ref | item_type_id=2 | HealItem.db | id | Healing items | -| Extra.ref | item_type_id=3 | EditItem.db | id | Modifiable items | -| Extra.ref | item_type_id=4 | EventItem.db | id | Quest items | -| Extra.ref | item_type_id=5 | MiscItem.db | id | Misc items | -| MondunMonmap.ref | loot*_item_type=1 | WeaponItem.db | id | Weapon loot | -| MondunMonmap.ref | loot*_item_type=2 | HealItem.db | id | Healing loot | -| MondunMonmap.ref | loot*_item_type=3 | EditItem.db | id | Editable loot | -| MondunMonmap.ref | loot*_item_type=4 | EventItem.db | id | Event loot | -| MondunMonmap.ref | loot*_item_type=5 | MiscItem.db | id | Misc loot | -| Wave.ini | snf_filename | .snf files | filename | Audio | - -## Data Flow Summary - -1. Map data: AllMap.ini → Map.ini → Map.map, MondunMonmap.ref, NpcMapFiles.ref and Extra.ref -2. Map rendering: Map.map → Map.gtl (ground tiles), Map.btl (building tiles) and Sprites.spr (objects and NPCs) -3. NPC data: NpcMapFiles.ref → Npc.ini → Sprites.spr, and DlgMapFiles.dlg → PgpMapFiles.pgp -4. Monster data: MondunMonmap.ref → Monster.ini → Sprites.spr, and Monster.db → Magic.db -5. Object data: Extra.ref → Extra.ini → Sprites.spr, Event.ini and Message.scr -6. Quest data: Event.ini → script files → Quest.scr -7. Character data: PartyRef.ref → PrtLevel.db → WeaponItem.db and Magic.db -8. Commerce data: Store.db → item databases such as WeaponItem.db and HealItem.db -9. Audio data: Wave.ini → .snf files -10. Monster loot: MondunMonmap.ref → item databases - -## Item Database Relationships - -### Item Type Enum (ItemTypeId) +Wave.ini + └── snf_filename → .snf audio file -``` -1: Weapon → WeaponItem.db -2: Healing → HealItem.db -3: Edit → EditItem.db -4: Event → EventItem.db -5: Misc → MiscItem.db --1: NoItem → no item (0xFF on disk; SQL/GUI numeric keys use 255) +NpcInGame/Pgpcat1.pgp + └── wave_ini_entry_id (column 3) → Wave.ini index ``` -### Item Database Cross-References +### 8. Item keys and store products ``` -WeaponItem.db (weapons/armor) - ├── Referenced by Store.db products (type=1) - ├── Referenced by Extra.ref contents (item_type_id=1) - └── Referenced by MondunMonmap.ref loot (loot*_item_type=1) - -HealItem.db (consumable healing) - ├── Referenced by Store.db products (type=2) - ├── Referenced by Extra.ref contents (item_type_id=2) - └── Referenced by MondunMonmap.ref loot (loot*_item_type=2) - -EditItem.db (modifiable equipment) - ├── Referenced by Store.db products (type=4) - ├── Referenced by Extra.ref contents (item_type_id=3) - └── Referenced by MondunMonmap.ref loot (loot*_item_type=3) - -EventItem.db (quest items) - ├── Referenced by Extra.ref contents (item_type_id=4) - └── Quest progression tracking - -MiscItem.db (generic utility items) - ├── Referenced by Store.db products (type=3) - ├── Referenced by Extra.ref contents (item_type_id=5) - └── Referenced by MondunMonmap.ref loot (loot*_item_type=5) +ItemTypeId (composite key type:ID) + ├── 1 Weapon → WeaponItem.db + ├── 2 Healing → HealItem.db + ├── 3 Edit → EditItem.db + ├── 4 Event → EventItem.db + ├── 5 Misc → MiscItem.db + └── -1 NoItem → 0xFF on disk, 255 in SQL and GUI keys + +ProductType (Store.db slots) + ├── 1 Weapon → WeaponItem.db + ├── 2 Healing → HealItem.db + ├── 3 EditItem → EditItem.db + ├── 4 MiscItem → MiscItem.db + └── 0 ends the list, with at most 15 products ``` -## File Encoding Summary - -| Encoding | Files | -|--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| EUC-KR | Event.ini, Extra.ini, Npc.ini, Wave.ini, Map.ini, Monster.db, DlgMapFiles.dlg, HealItem.db (descriptions) | -| WINDOWS-1250 | AllMap.ini, Monster.ini, Store.db, WeaponItem.db, HealItem.db (names), MiscItem.db, EditItem.db, EventItem.db, Message.scr, Quest.scr, PgpMapFiles.pgp, Extra.ref, NpcMapFiles.ref, PartyRef.ref, Eventnpc.ref | -| Binary | Monster.db, WeaponItem.db, HealItem.db, MiscItem.db, EditItem.db, EventItem.db, Store.db, ChData.db, PrtLevel.db, Magic.db, DrawItem.db, Map.map, Map.gtl, Map.btl, Sprites.spr | +## Complete cross-reference table + +| Source file | Source field | Target file | Target field | Relationship | +|---|---|---|---|---| +| AllMap.ini | map_filename | Map.map | stem | Map geometry | +| AllMap.ini | pgp_filename | Pgpcat1.pgp | file name | Dialogue text | +| AllMap.ini | dlg_filename | Dlgcat1.dlg | file name | Dialogue scripts | +| Ref/Map.ini | map_id | AllMap.ini | id | Map link | +| Ref/Map.ini | monsters_filename | Mondun01.ref | file name | Monster placements | +| Ref/Map.ini | npc_filename | Npccat1.ref | file name | NPC placements | +| Ref/Map.ini | extra_filename | Extdun01.ref | file name | Object placements | +| Ref/Map.ini | cd_music_track_number | Wave.ini | index | Music track | +| Mondun01.ref | monster_db_id | Monster.db | id | Monster type | +| Mondun01.ref | loot_item_1 / 2 / 3 | items lookup | type:ID | Loot | +| Mondun01.ref | event_id_on_kill | event index | - | Kill trigger | +| Monster.db | known_spell_slot1 / 2 / 3 | spell index | - | Spells (NULL for -1) | +| Npccat1.ref | npc_ini_id | Npc.ini | id | NPC type | +| Npccat1.ref | dialog_id | Dlgcat1.dlg | id | Dialogue | +| Npccat1.ref | show_on_event | event index | - | Visibility | +| Eventnpc.ref | npc_ini_id | Npc.ini | id | NPC type | +| Eventnpc.ref | show_on_event | event index | - | Trigger | +| Eventnpc.ref | dialog_id | Dlgcat1.dlg | id | Dialogue | +| Dlgcat1.dlg | required_event_id | event index | - | Prerequisite | +| Dlgcat1.dlg | next_dialog_to_check | Dlgcat1.dlg | id | Chain | +| Dlgcat1.dlg | dialog_id | Pgpcat1.pgp | paragraph | Text | +| Dlgcat1.dlg | triggered_event_id | event index | - | Trigger | +| Pgpcat1.pgp | wave_ini_entry_id | Wave.ini | index | Voice audio | +| PartyRef.ref | npc_id | Npc.ini | id | Visual type | +| PartyRef.ref | root_map_id | AllMap.ini | id | Location | +| PartyRef.ref | dlg_when_not_in_party | PartyDlg.dlg | paragraph | Dialogue | +| PartyRef.ref | dlg_when_in_party | PartyDlg.dlg | paragraph | Dialogue | +| Extdun01.ref | extra_definition_id | Extra.ini | id | Object type | +| Extdun01.ref | interaction_event_id | event index | - | Interaction | +| Extdun01.ref | interaction_message_id | Message.scr | id | Sign text | +| Extdun01.ref | required_item / required_item2 | items lookup | type:ID | Required item | +| Extdun01.ref | loot_item | items lookup | type:ID | Loot | +| Extdun01.ref | trap_spell_id | spell index | - | Trap spell | +| Extdun01.ref | open_sfx_id | Wave.ini | index | Open sound | +| DRAWITEM.ref | map_id | AllMap.ini | id | Map location | +| DRAWITEM.ref | item | items lookup | type:ID | Dropped item | +| Map.map | ground GTL index | Map.gtl | tile index | Ground tiles | +| Map.map | BTL IDs | Map.btl | tile index | Roof tiles | +| Map.map | event ID bits | event index | - | Tile event | +| STORE.DB | product | items lookup | type:ID | Product | +| PrtLevel.db | magic_spell_id_1 / 2 / 3 | spell index | - | Spells | +| Monster.ini / Npc.ini / Extra.ini | sprite_filename | .spr | file name | Sprites | +| Event.ini | event_filename | event script | file name | Event logic | +| Wave.ini | snf_filename | .snf | file name | Audio | + +## Data flow summary + +1. Map data: `AllMap.ini` → `Ref/Map.ini` → `Map.map`, `Mondun01.ref`, `Npccat1.ref` and `Extdun01.ref`. +2. Map rendering: `Map.map` → ground `.gtl` tiles, roof `.btl` tiles and the embedded sprite block. +3. NPC data: `Npccat1.ref` → `Npc.ini` → `.spr` files, and `Dlgcat1.dlg` → `Pgpcat1.pgp`. +4. Monster data: `Mondun01.ref` → `Monster.db` and `Monster.ini`, plus spell indices in `Monster.db`. +5. Object data: `Extdun01.ref` → `Extra.ini`, `Event.ini` and `Message.scr`. +6. Item drops: `DRAWITEM.ref` → item databases through the items lookup. +7. Party data: `PartyRef.ref` → `Npc.ini` and `PartyDlg.dlg`, with growth in `PrtLevel.db`. +8. Commerce data: `STORE.DB` → item databases through product types. +9. Audio data: `Wave.ini` → `.snf` files, with indices from `Pgpcat1.pgp`. +10. Event data: `Event.ini` → event scripts, with indices in placements and dialogue. + +## Item type section + +### Item type enum + +The tool uses `ItemTypeId` for composite item keys. A key holds a type code and an item ID. + +- 1 Weapon → `WeaponItem.db` +- 2 Healing → `HealItem.db` +- 3 Edit → `EditItem.db` +- 4 Event → `EventItem.db` +- 5 Misc → `MiscItem.db` +- -1 NoItem → empty slot (`0xFF` on disk, `255` in SQL and GUI keys) + +There is no item type 0. + +### Product types in stores + +`STORE.DB` uses a different enum named `ProductType`. Each product slot holds a type code and an item ID. + +- 1 Weapon → `WeaponItem.db` +- 2 Healing → `HealItem.db` +- 3 EditItem → `EditItem.db` +- 4 MiscItem → `MiscItem.db` +- 0 ends the product list, with at most 15 products per store + +Unknown type codes fall back to MiscItem. EventItem has no product type. NoItem and 255 do not appear in `STORE.DB`. + +## File encoding summary + +Some files mix text and binary data. `Monster.db` is binary, and its 24-byte name field is EUC-KR. `MiscItem.db` has a WINDOWS-1250 name and an EUC-KR description. + +| Encoding | Files | +|---|---| +| EUC-KR | `Event.ini`, `Extra.ini`, `Npc.ini`, `Wave.ini`, `Map.ini`, DLG files, `HealItem.db` descriptions, `MiscItem.db` description, `Monster.db` name field, `DRAWITEM.ref` | +| WINDOWS-1250 | `AllMap.ini`, `Monster.ini`, `WeaponItem.db`, `EditItem.db`, `EventItem.db`, `Message.scr`, `Quest.scr`, PGP files, `MiscItem.db` name, `STORE.DB` text fields, `Extra.ref` names, NPC refs, `PartyRef.ref`, `Eventnpc.ref` | +| Binary | `WeaponItem.db`, `HealItem.db`, `MiscItem.db`, `EditItem.db`, `EventItem.db`, `STORE.DB`, `Monster.db`, `ChData.db`, `PrtLevel.db`, `Magic.db`, `Map.map`, `.gtl`, `.btl`, `.spr`, `.snf` | ## Scope -The tool reads and writes data files that you supply. This document lists the field links between those files. +The tool reads and writes the game files that you supply. This document lists the field links between those files. The extractor commands below use sample paths. ## Extractor commands The tool in `src/` parses and extracts data from game files. Run these commands from the repository root. -### Quick Reference +### Quick reference ```bash # Build the extractor @@ -408,37 +318,38 @@ cargo build --release # Extract INI files to JSON cargo run -- extract -i "path/to/AllMap.ini" +cargo run -- extract -i "path/to/Ref/Map.ini" cargo run -- extract -i "path/to/Event.ini" cargo run -- extract -i "path/to/Extra.ini" -cargo run -- extract -i "path/to/Monster.ini" +cargo run -- extract -i "path/to/CharacterInGame/Monster.ini" cargo run -- extract -i "path/to/Npc.ini" cargo run -- extract -i "path/to/Wave.ini" -cargo run -- extract -i "path/to/Map.ini" # Extract database files to JSON -cargo run -- extract -i "path/to/weaponItem.db" -cargo run -- extract -i "path/to/Monster.db" -cargo run -- extract -i "path/to/HealItem.db" -cargo run -- extract -i "path/to/MiscItem.db" -cargo run -- extract -i "path/to/EditItem.db" -cargo run -- extract -i "path/to/EventItem.db" -cargo run -- extract -i "path/to/STORE.DB" -cargo run -- extract -i "path/to/Magic.db" -cargo run -- extract -i "path/to/PrtLevel.db" -cargo run -- extract -i "path/to/ChData.db" +cargo run -- extract -i "path/to/CharacterInGame/weaponItem.db" +cargo run -- extract -i "path/to/MonsterInGame/Monster.db" +cargo run -- extract -i "path/to/CharacterInGame/HealItem.db" +cargo run -- extract -i "path/to/CharacterInGame/MiscItem.db" +cargo run -- extract -i "path/to/CharacterInGame/EditItem.db" +cargo run -- extract -i "path/to/CharacterInGame/EventItem.db" +cargo run -- extract -i "path/to/CharacterInGame/STORE.DB" +cargo run -- extract -i "path/to/MagicInGame/Magic.db" +cargo run -- extract -i "path/to/NpcInGame/PrtLevel.db" +cargo run -- extract -i "path/to/CharacterInGame/ChData.db" # Extract reference files to JSON -cargo run -- extract -i "path/to/PartyRef.ref" -cargo run -- extract -i "path/to/DrawItem.ref" -cargo run -- extract -i "path/to/Npccat1.ref" -cargo run -- extract -i "path/to/Mondun01.ref" -cargo run -- extract -i "path/to/Extdun01.ref" -cargo run -- extract -i "path/to/Eventnpc.ref" +cargo run -- extract -i "path/to/Ref/PartyRef.ref" +cargo run -- extract -i "path/to/Ref/DRAWITEM.ref" +cargo run -- extract -i "path/to/NpcInGame/Npccat1.ref" +cargo run -- extract -i "path/to/MonsterInGame/Mondun01.ref" +cargo run -- extract -i "path/to/ExtraInGame/Extdun01.ref" +cargo run -- extract -i "path/to/NpcInGame/Eventnpc.ref" # Extract script files to JSON -cargo run -- extract -i "path/to/Dlgcat1.dlg" -cargo run -- extract -i "path/to/Message.scr" -cargo run -- extract -i "path/to/Quest.scr" +cargo run -- extract -i "path/to/NpcInGame/Dlgcat1.dlg" +cargo run -- extract -i "path/to/NpcInGame/Pgpcat1.pgp" +cargo run -- extract -i "path/to/ExtraInGame/Message.scr" +cargo run -- extract -i "path/to/ExtraInGame/Quest.scr" # Extract sprites cargo run -- sprite "path/to/file.spr" "output_name" From 0a539df720b8d41141542af142974be8cfdce2b9 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:31:12 +0100 Subject: [PATCH 11/72] docs: fix five cross reference details --- docs/files/CROSS_REFERENCES.md | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/files/CROSS_REFERENCES.md b/docs/files/CROSS_REFERENCES.md index 2c0544c4..b1d668cc 100644 --- a/docs/files/CROSS_REFERENCES.md +++ b/docs/files/CROSS_REFERENCES.md @@ -12,7 +12,7 @@ This section groups files by role. A family name such as `DlgMapFiles.dlg` stand - `AllMap.ini`: Master map index. It lists each map and its resources. - `Ref/Map.ini`: Map setup with spawn coordinates and file links. Each row holds one entrance. -- `CharacterInGame/Monster.ini`: Monster visuals and animation sequences. +- `Monster.ini`: Monster visuals and animation sequences. - `Npc.ini`: NPC visuals and sprite file names. - `Extra.ini`: Interactive object definitions. - `Event.ini`: Event conditions and script file names. @@ -110,8 +110,8 @@ CharacterInGame/ChData.db ### 4. Monster data ``` -CharacterInGame/Monster.ini - └── sprite_filename → .spr file under CharacterInGame/ +Monster.ini + └── sprite_filename → .spr file under MonsterInGame/ MonsterInGame/Monster.db ├── known_spell_slot1 / 2 / 3 → spell indices (-1 = SQL NULL) @@ -199,8 +199,9 @@ ProductType (Store.db slots) ├── 1 Weapon → WeaponItem.db ├── 2 Healing → HealItem.db ├── 3 EditItem → EditItem.db - ├── 4 MiscItem → MiscItem.db - └── 0 ends the list, with at most 15 products + └── 4 MiscItem → MiscItem.db + +Note: 0 ends the list. A store holds at most 15 products. ``` ## Complete cross-reference table @@ -214,7 +215,7 @@ ProductType (Store.db slots) | Ref/Map.ini | monsters_filename | Mondun01.ref | file name | Monster placements | | Ref/Map.ini | npc_filename | Npccat1.ref | file name | NPC placements | | Ref/Map.ini | extra_filename | Extdun01.ref | file name | Object placements | -| Ref/Map.ini | cd_music_track_number | Wave.ini | index | Music track | +| Ref/Map.ini | cd_music_track_number | CD audio track | number | Music track | | Mondun01.ref | monster_db_id | Monster.db | id | Monster type | | Mondun01.ref | loot_item_1 / 2 / 3 | items lookup | type:ID | Loot | | Mondun01.ref | event_id_on_kill | event index | - | Kill trigger | @@ -243,10 +244,10 @@ ProductType (Store.db slots) | Extdun01.ref | open_sfx_id | Wave.ini | index | Open sound | | DRAWITEM.ref | map_id | AllMap.ini | id | Map location | | DRAWITEM.ref | item | items lookup | type:ID | Dropped item | -| Map.map | ground GTL index | Map.gtl | tile index | Ground tiles | -| Map.map | BTL IDs | Map.btl | tile index | Roof tiles | +| Map.map | ground GTL index | per-map .gtl file | tile index | Ground tiles | +| Map.map | BTL IDs | per-map .btl file | tile index | Roof tiles | | Map.map | event ID bits | event index | - | Tile event | -| STORE.DB | product | items lookup | type:ID | Product | +| STORE.DB | product | item databases | product type:ID | Product | | PrtLevel.db | magic_spell_id_1 / 2 / 3 | spell index | - | Spells | | Monster.ini / Npc.ini / Extra.ini | sprite_filename | .spr | file name | Sprites | | Event.ini | event_filename | event script | file name | Event logic | @@ -321,7 +322,7 @@ cargo run -- extract -i "path/to/AllMap.ini" cargo run -- extract -i "path/to/Ref/Map.ini" cargo run -- extract -i "path/to/Event.ini" cargo run -- extract -i "path/to/Extra.ini" -cargo run -- extract -i "path/to/CharacterInGame/Monster.ini" +cargo run -- extract -i "path/to/Monster.ini" cargo run -- extract -i "path/to/Npc.ini" cargo run -- extract -i "path/to/Wave.ini" From 129ca2a8056b06634ba6ee4fcf430efd8011d186 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:48:51 +0100 Subject: [PATCH 12/72] refactor(gui): combine composite item selects with search --- dispel-gui/src/components/composite_item.rs | 453 ++++++++++-------- .../src/editors/map_editor/view/fields.rs | 26 +- .../view/editor/spreadsheet/view/inspector.rs | 24 +- 3 files changed, 286 insertions(+), 217 deletions(-) diff --git a/dispel-gui/src/components/composite_item.rs b/dispel-gui/src/components/composite_item.rs index a459d688..82348483 100644 --- a/dispel-gui/src/components/composite_item.rs +++ b/dispel-gui/src/components/composite_item.rs @@ -1,9 +1,9 @@ use std::rc::Rc; -use dispel_core::ItemTypeId; use iced::widget::{column as col, pick_list, row, text, text_input}; use iced::{Element, Length}; +use crate::components::select::lookup_select; use crate::message::Message; use crate::style; @@ -11,7 +11,6 @@ const LABEL_W: f32 = 140.0; /// The empty-slot option shared with the item catalog. const NO_ITEM_KEY: &str = "255:15"; -const NO_ITEM_LABEL: &str = "[-]"; /// Render a picker body, optionally prefixed with a fixed-width label column. /// @@ -38,28 +37,36 @@ fn with_optional_label<'a>( } } -/// Build a cascading item-type + item-id picker for `CompositeItem` fields. +/// Build a searchable item picker for `CompositeItem` fields. /// -/// Renders two pick-lists (type then item). Falls back to a plain `text_input` -/// when `entries` is `None` (lookups unavailable). `show_label` controls whether -/// the label column is drawn by this component or by the caller. +/// All item files share one select: every entry carries its type in the +/// display label (`[Weapon] Cap`, `[Healing] Herb`, …). A text input above the +/// select filters those labels and composite keys. Falls back to a plain +/// `text_input` when `entries` is `None` (lookups unavailable). `show_label` +/// controls whether the label column is drawn by this component or the caller. pub fn composite_item_picker( label: &'static str, value: &str, entries: Option<&[(String, String)]>, show_label: bool, + filter: &str, + on_filter: impl Fn(String) -> Message + 'static, on_change: impl Fn(String) -> Message + 'static, ) -> Element<'static, Message> { - let current_type_byte: u8 = value - .split(':') - .next() - .and_then(|s| s.parse().ok()) - .unwrap_or(255); - let current_type = ItemTypeId::from_u8(current_type_byte).unwrap_or(ItemTypeId::NoItem); - let current_id = value.split(':').nth(1).unwrap_or("0").to_string(); - + let filter = filter.to_owned(); + let on_filter: Rc Message> = Rc::new(on_filter); let on_change: Rc Message> = Rc::new(on_change); + let search_input: Element<'static, Message> = { + let of = on_filter.clone(); + text_input("Search items...", filter.clone()) + .on_input(move |v| of(v)) + .padding(4) + .size(11) + .width(Length::Fill) + .into() + }; + let Some(entries) = entries else { let oc = on_change; let input: Element<'static, Message> = text_input("", value.to_owned()) @@ -68,148 +75,174 @@ pub fn composite_item_picker( .size(11) .width(Length::Fill) .into(); - return with_optional_label(label, input, show_label); + let body: Element<'static, Message> = col![search_input, input].spacing(4).into(); + return with_optional_label(label, body, show_label); }; - // Parallel label/byte vectors, so a displayed type always maps back to the - // byte the setter needs. Insert the current type when the lookup omits it. - let mut type_labels: Vec = Vec::new(); - let mut type_bytes: Vec = Vec::new(); - for (key, _) in entries { - let tb: u8 = key - .split(':') - .next() - .and_then(|s| s.parse().ok()) - .unwrap_or(255); - if !type_bytes.contains(&tb) - && let Some(ty) = ItemTypeId::from_u8(tb) - { - type_bytes.push(tb); - type_labels.push(ty.to_string()); + // One option per item file. Every key with the no-item byte denotes the + // same empty slot, so only the canonical sentinel survives. + let mut collapsed: Vec<(String, String)> = Vec::with_capacity(entries.len()); + for (key, display) in entries { + if key.starts_with("255:") { + if key == NO_ITEM_KEY && !collapsed.iter().any(|(k, _)| k == key) { + collapsed.push((key.clone(), display.clone())); + } + } else { + collapsed.push((key.clone(), display.clone())); } } - let current_type_label = current_type.to_string(); - if !type_bytes.contains(¤t_type_byte) { - type_bytes.push(current_type_byte); - type_labels.push(current_type_label.clone()); + if !collapsed.iter().any(|(key, _)| key == NO_ITEM_KEY) { + collapsed.push((NO_ITEM_KEY.to_string(), "[-]".to_string())); } - let mut filtered_items: Vec<(String, String)> = entries + let is_no_item = value.starts_with("255:"); + let query = filter.to_lowercase(); + let mut filtered_entries: Vec<(String, String)> = collapsed .iter() - .filter(|(key, _)| { - key.split(':').next().and_then(|s| s.parse::().ok()) == Some(current_type_byte) + .filter(|(key, display)| { + display.to_lowercase().contains(&query) || key.to_lowercase().contains(&query) }) .cloned() .collect(); - // Every key with the no-item byte denotes the same empty slot, regardless - // of its id. Resolve all of them to the shared sentinel option so the - // selection is never blank. - let is_no_item = current_type_byte == u8::from(ItemTypeId::NoItem); - if is_no_item && !filtered_items.iter().any(|(key, _)| key == NO_ITEM_KEY) { - filtered_items.push((NO_ITEM_KEY.to_string(), NO_ITEM_LABEL.to_string())); + // The current value must never vanish from the select while the user + // types. A no-item value also keeps the sentinel that stands in for it. + let mut required: Vec<&str> = vec![value]; + if is_no_item { + required.push(NO_ITEM_KEY); + } + for key in required { + if !filtered_entries.iter().any(|(k, _)| k == key) + && let Some(entry) = collapsed.iter().find(|(k, _)| k == key) + { + filtered_entries.push(entry.clone()); + } } - let lookup_key = if is_no_item { NO_ITEM_KEY } else { value }; - - let mut selected_item = filtered_items - .iter() - .find(|(key, _)| *key == lookup_key) - .map(|(_, name)| name.clone()); - - let mut labelled_keys: Vec<(String, String)> = filtered_items - .iter() - .map(|(key, name)| (name.clone(), key.clone())) - .collect(); - // A non-canonical no-item key still renders as the shared "[-]" option, - // but re-selecting it must emit the exact stored key to keep the record - // byte-for-byte intact. + // A non-canonical stored key (e.g. `255:255`) still renders as the shared + // empty-slot option, but re-selecting that option must emit the exact key + // so `InventoryItem::is_empty()` keeps working. + let effective_selected_id = if is_no_item { NO_ITEM_KEY } else { value }; + let mut select = lookup_select(&filtered_entries, effective_selected_id); if is_no_item && value != NO_ITEM_KEY { - for (label, key) in &mut labelled_keys { - if label == NO_ITEM_LABEL { - *key = value.to_string(); + for id in select.label_to_id.values_mut() { + if id == NO_ITEM_KEY { + *id = value.to_string(); } } } - // An id that is gone from the lookup still gets a visible, selectable - // label. The stored value is left untouched; choosing the fallback keeps - // the original key. - if selected_item.is_none() { - let fallback_label = format!("Unknown ({})", current_id); - labelled_keys.push((fallback_label.clone(), value.to_string())); - selected_item = Some(fallback_label); - } - - let item_options: Vec = labelled_keys - .iter() - .map(|(label, _)| label.clone()) - .collect(); - - let type_picker: Element<'static, Message> = { - let oc = on_change.clone(); - let current_id = current_id.clone(); - let labels = type_labels.clone(); - let bytes = type_bytes.clone(); - let entries_owned: Vec<(String, String)> = entries.to_vec(); - pick_list(Some(current_type_label), type_labels, |v| v.to_string()) - .on_select(move |selected_label| { - let new_byte = labels - .iter() - .position(|l| l == &selected_label) - .and_then(|i| bytes.get(i).copied()) - .unwrap_or_else(|| u8::from(ItemTypeId::NoItem)); - let ids: Vec = entries_owned - .iter() - .filter(|(key, _)| { - key.split(':').next().and_then(|s| s.parse::().ok()) == Some(new_byte) - }) - .map(|(key, _)| key.split(':').nth(1).unwrap_or("0").to_string()) - .collect(); - // Prefer the current id when the new type offers it, otherwise - // use the first entry of that type, or the shared empty slot. - let key = if ids.contains(¤t_id) { - format!("{}:{}", new_byte, current_id) - } else if let Some(id) = ids.first() { - format!("{}:{}", new_byte, id) - } else { - NO_ITEM_KEY.to_string() - }; - oc(key) - }) - .width(Length::Fill) - .into() - }; - - let item_picker: Element<'static, Message> = { - let fallback_key = value.to_string(); - pick_list(selected_item, item_options, |v| v.to_string()) + let picker: Element<'static, Message> = { + let ids = select.label_to_id; + let fallback_key = value.to_owned(); + pick_list(select.selected, select.options, String::clone) .on_select(move |selected_name| { - let composite_key = labelled_keys - .iter() - .find(|(label, _)| *label == selected_name) - .map(|(_, key)| key.clone()) + let key = ids + .get(&selected_name) + .cloned() .unwrap_or_else(|| fallback_key.clone()); - on_change(composite_key) + on_change(key) }) .width(Length::Fill) .into() }; - let pickers: Element<'static, Message> = col![type_picker, item_picker].spacing(4).into(); - with_optional_label(label, pickers, show_label) + let body: Element<'static, Message> = col![search_input, picker].spacing(4).into(); + with_optional_label(label, body, show_label) } #[cfg(all(test, feature = "iced_test"))] mod tests { use super::*; + use crate::editors::weapon::WeaponEditorMessage; + use crate::message::{EditorMessage, FileTreeMessage}; + use dispel_core::ItemTypeId; + use iced_test::selector::{Candidate, Target}; use iced_test::simulator; + fn picker( + value: &str, + entries: Option<&[(String, String)]>, + filter: &str, + ) -> Element<'static, Message> { + composite_item_picker( + "Invented Item", + value, + entries, + false, + filter, + |v| Message::FileTree(FileTreeMessage::Search(v)), + |v| { + Message::Editor(EditorMessage::Weapon(WeaponEditorMessage::FieldChanged( + 0, + "item".to_string(), + v, + ))) + }, + ) + } + + fn emitted_keys(messages: Vec) -> Vec { + messages + .into_iter() + .filter_map(|m| match m { + Message::Editor(EditorMessage::Weapon(WeaponEditorMessage::FieldChanged( + _, + _, + value, + ))) => Some(value), + _ => None, + }) + .collect() + } + + /// Type into the search box and feed the emitted query back into a fresh + /// render, the way the real caller stores it in state. + fn typed_filter(element: Element<'static, Message>, query: &str) -> String { + let mut ui = simulator(element); + let mut search = |candidate: Candidate<'_>| match candidate { + Candidate::TextInput { state, .. } + if state.text().into_owned() == "Search items..." => + { + Some(Target::from(candidate)) + } + _ => None, + }; + ui.click(&mut search) + .expect("search input must be rendered"); + ui.typewrite(query); + ui.into_messages() + .filter_map(|m| match m { + Message::FileTree(FileTreeMessage::Search(v)) => Some(v), + _ => None, + }) + .last() + .expect("search input must emit its query") + } + + fn select_option( + value: &str, + entries: &[(String, String)], + filter: &str, + offset: isize, + ) -> Vec { + emitted_keys(crate::tests::common::activate_select_option( + picker(value, Some(entries), filter), + 0, + offset, + )) + } + fn label_rendered(entries: Option<&[(String, String)]>, show_label: bool) -> bool { - let element: Element<'_, Message> = - composite_item_picker("Invented Item", "1:0", entries, show_label, |_| { - Message::FileTree(crate::message::FileTreeMessage::Search(String::new())) - }); + let element: Element<'_, Message> = composite_item_picker( + "Invented Item", + "1:0", + entries, + show_label, + "", + |_| Message::FileTree(FileTreeMessage::Search(String::new())), + |_| Message::FileTree(FileTreeMessage::Search(String::new())), + ); let mut ui = simulator(element); ui.find("Invented Item").is_ok() } @@ -217,41 +250,97 @@ mod tests { #[test] fn test_unmapped_composite_keys_render_a_label_and_keep_value() { let entries = [ - ("1:0".to_string(), "Invented Sword".to_string()), + ("1:0".to_string(), "[Weapon] Invented Sword".to_string()), ("255:15".to_string(), "[-]".to_string()), ]; - let element = |value: &'static str| { - composite_item_picker("Invented Item", value, Some(&entries), false, |v| { - Message::FileTree(crate::message::FileTreeMessage::Search(v)) - }) - }; for value in ["255:0", "255:255"] { - let values = crate::tests::common::select_values(element(value)); + let values = crate::tests::common::select_values(picker(value, Some(&entries), "")); assert!( values.iter().any(|v| v == "[-]"), "{value} must resolve to the no-item sentinel label, got {values:?}" ); } - let values = crate::tests::common::select_values(element("1:999")); + let values = crate::tests::common::select_values(picker("1:999", Some(&entries), "")); assert!( - values.iter().any(|v| v.starts_with("Unknown (999)")), - "an unmapped item id must render a visible fallback label, got {values:?}" + values.iter().any(|v| v == "Unknown (1:999)"), + "an unmapped composite key must render a visible fallback label, got {values:?}" ); - let messages = crate::tests::common::activate_select_option(element("255:0"), 1, 0); - let emitted: Vec = messages - .into_iter() - .filter_map(|m| match m { - Message::FileTree(crate::message::FileTreeMessage::Search(v)) => Some(v), - _ => None, - }) - .collect(); + let keys = select_option("255:0", &entries, "", 0); + assert_eq!( + keys, + vec!["255:0"], + "choosing the sentinel must keep the exact stored key" + ); + } + + #[test] + fn test_one_select_offers_items_from_every_type() { + let entries = [ + ("1:0".to_string(), "[Weapon] Invented Sword".to_string()), + ("2:7".to_string(), "[Healing] Invented Herb".to_string()), + ("3:2".to_string(), "[Edit] Invented Charm".to_string()), + ("255:15".to_string(), "[-]".to_string()), + ]; + let values = crate::tests::common::select_values(picker("1:0", Some(&entries), "")); + assert_eq!( + values.len(), + 1, + "there must be exactly one select, got {values:?}" + ); + + assert_eq!(select_option("1:0", &entries, "", 1), vec!["2:7"]); + assert_eq!(select_option("1:0", &entries, "", 2), vec!["3:2"]); + assert_eq!(select_option("1:0", &entries, "", 3), vec!["255:15"]); + } + + #[test] + fn test_search_narrows_options_and_keeps_selection_visible() { + let entries = [ + ("1:0".to_string(), "[Weapon] Invented Sword".to_string()), + ("2:7".to_string(), "[Healing] Invented Herb".to_string()), + ("3:2".to_string(), "[Edit] Invented Charm".to_string()), + ("255:15".to_string(), "[-]".to_string()), + ]; + let query = typed_filter(picker("1:0", Some(&entries), ""), "herb"); + assert_eq!(query, "herb"); + + let values = crate::tests::common::select_values(picker("1:0", Some(&entries), &query)); assert!( - emitted.iter().any(|v| v == "255:0"), - "choosing the sentinel must keep the exact stored key, got {emitted:?}" + values.iter().any(|v| v == "[Weapon] Invented Sword"), + "the current item must stay selected while filtering, got {values:?}" + ); + + assert_eq!( + select_option("1:0", &entries, &query, -1), + vec!["2:7"], + "the only other option must be the matching item" ); + let reachable: std::collections::HashSet = (-3..=3) + .flat_map(|offset| select_option("1:0", &entries, "charm", offset)) + .collect(); + assert_eq!( + reachable, + std::collections::HashSet::from(["1:0".to_string(), "3:2".to_string()]), + "non-matching items must be absent from the narrowed list" + ); + + // Filtering by the composite key works just like filtering by label. + let query = typed_filter(picker("1:0", Some(&entries), ""), "3:2"); + assert_eq!(select_option("1:0", &entries, &query, -1), vec!["3:2"]); + } + + #[test] + fn test_selected_label_emits_its_exact_composite_key() { + let entries = [ + ("1:0".to_string(), "[Weapon] Invented Sword".to_string()), + ("2:7".to_string(), "[Healing] Invented Herb".to_string()), + ("255:15".to_string(), "[-]".to_string()), + ]; + assert_eq!(select_option("2:7", &entries, "", 0), vec!["2:7"]); + assert_eq!(select_option("2:7", &entries, "", -1), vec!["1:0"]); } #[test] @@ -259,43 +348,22 @@ mod tests { use dispel_core::InventoryItem; let entries = [ - ("1:0".to_string(), "Invented Sword".to_string()), + ("1:0".to_string(), "[Weapon] Invented Sword".to_string()), ("255:15".to_string(), "[-]".to_string()), ]; - let element = |value: &'static str| { - composite_item_picker("Invented Item", value, Some(&entries), false, |v| { - Message::FileTree(crate::message::FileTreeMessage::Search(v)) - }) - }; - let emitted_for = |value: &'static str| -> String { - let messages = crate::tests::common::activate_select_option(element(value), 1, 0); - messages - .into_iter() - .find_map(|m| match m { - Message::FileTree(crate::message::FileTreeMessage::Search(v)) => Some(v), - _ => None, - }) - .unwrap_or_else(|| panic!("no value emitted for {value}")) - }; for value in ["255:255", "255:5"] { - let values = crate::tests::common::select_values(element(value)); - assert!( - values.iter().any(|v| v == "[-]"), - "{value} must render the shared no-item label, got {values:?}" - ); + assert_eq!(select_option(value, &entries, "", 0), vec![value]); } + assert_eq!(select_option("255:15", &entries, "", 0), vec!["255:15"]); - assert_eq!(emitted_for("255:255"), "255:255"); - assert_eq!(emitted_for("255:5"), "255:5"); - assert_eq!(emitted_for("255:15"), "255:15"); - - let emitted = emitted_for("255:255"); - let parts: Vec<&str> = emitted.split(':').collect(); - let item = InventoryItem::new( - ItemTypeId::from_u8(parts[0].parse().unwrap()).unwrap(), - parts[1].parse().unwrap(), + // Filtering out "[-]" must not hide the empty slot either. + assert_eq!( + select_option("255:255", &entries, "sword", 0), + vec!["255:255"] ); + + let item = InventoryItem::new(ItemTypeId::NoItem, 255); assert!( item.is_empty(), "255:255 must decode to an empty inventory item" @@ -303,39 +371,24 @@ mod tests { } #[test] - fn test_composite_type_picker_keeps_current_type_and_selects_valid_id() { - // The lookup knows only type 2; the record currently uses type 3. - let entries = [("2:5".to_string(), "Invented Potion".to_string())]; - let element = || { - composite_item_picker("Invented Item", "3:7", Some(&entries), false, |v| { - Message::FileTree(crate::message::FileTreeMessage::Search(v)) - }) - }; - - let values = crate::tests::common::select_values(element()); - assert!( - values.first().is_some_and(|v| v == "Edit"), - "the type picker must show the current type, got {values:?}" - ); - - // "Edit" is inserted after "Healing", so move the highlight up once. - let messages = crate::tests::common::activate_select_option(element(), 0, -1); - let emitted: Vec = messages - .into_iter() - .filter_map(|m| match m { - Message::FileTree(crate::message::FileTreeMessage::Search(v)) => Some(v), - _ => None, - }) - .collect(); + fn test_duplicate_display_names_stay_distinguishable() { + let entries = [ + ("1:4".to_string(), "Invented Blade".to_string()), + ("2:4".to_string(), "Invented Blade".to_string()), + ("255:15".to_string(), "[-]".to_string()), + ]; + let values = crate::tests::common::select_values(picker("2:4", Some(&entries), "")); assert!( - emitted.iter().any(|v| v == "2:5"), - "switching type must choose an id present in the new type, got {emitted:?}" + values.iter().any(|v| v == "Invented Blade (2:4)"), + "duplicate labels must be qualified with their composite key, got {values:?}" ); + assert_eq!(select_option("2:4", &entries, "", -1), vec!["1:4"]); + assert_eq!(select_option("2:4", &entries, "", 0), vec!["2:4"]); } #[test] fn test_composite_picker_label_follows_show_label() { - let entries = [("1:0".to_string(), "Invented Sword".to_string())]; + let entries = [("1:0".to_string(), "[Weapon] Invented Sword".to_string())]; for show_label in [true, false] { assert_eq!( label_rendered(None, show_label), diff --git a/dispel-gui/src/editors/map_editor/view/fields.rs b/dispel-gui/src/editors/map_editor/view/fields.rs index 04b162ce..74cf1869 100644 --- a/dispel-gui/src/editors/map_editor/view/fields.rs +++ b/dispel-gui/src/editors/map_editor/view/fields.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use crate::components::composite_item::composite_item_picker; use crate::components::editable::{EditableRecord, FieldKind}; -use crate::message::{Message, MessageExt}; +use crate::message::{Message, MessageExt, SystemMessage}; use crate::style; use iced::widget::{column, pick_list, row, scrollable, text, text_input}; use iced::{Element, Fill}; @@ -151,14 +151,22 @@ pub fn inspector_field_row<'a>( FieldKind::CompositeItem { lookup_key } => { let entries = lookups.get(*lookup_key).map(|v| v.as_slice()); - composite_item_picker(label, value, entries, true, move |v| { - Message::map_editor(MapEditorMessage::EntityFieldChanged( - tab_id, - sel, - name.to_string(), - v, - )) - }) + composite_item_picker( + label, + value, + entries, + true, + "", + |_| Message::System(SystemMessage::DismissError), + move |v| { + Message::map_editor(MapEditorMessage::EntityFieldChanged( + tab_id, + sel, + name.to_string(), + v, + )) + }, + ) } } } diff --git a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs index 559ae3ca..70f1633c 100644 --- a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs +++ b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs @@ -12,7 +12,7 @@ use crate::components::composite_item::composite_item_picker; use crate::components::editable::{EditableRecord, FieldDescriptor, FieldKind}; use crate::components::generic_editor::GenericEditorState; use crate::components::utils::horizontal_space; -use crate::message::Message; +use crate::message::{Message, SystemMessage}; use crate::style; use crate::view::editor::spreadsheet::message::SpreadsheetMessage; use crate::view::editor::spreadsheet::state::SpreadsheetState; @@ -161,13 +161,21 @@ pub(crate) fn build_inspector_field<'a>( FieldKind::CompositeItem { lookup_key } => { let entries = lookups.get(*lookup_key).map(|v| v.as_slice()); let field_name = descriptor.name.to_string(); - composite_item_picker(descriptor.label, &value, entries, false, move |v| { - spreadsheet_msg(SpreadsheetMessage::InspectorFieldChanged( - orig_idx, - field_name.clone(), - v, - )) - }) + composite_item_picker( + descriptor.label, + &value, + entries, + false, + "", + |_| Message::System(SystemMessage::DismissError), + move |v| { + spreadsheet_msg(SpreadsheetMessage::InspectorFieldChanged( + orig_idx, + field_name.clone(), + v, + )) + }, + ) } _ => { let field_name = descriptor.name.to_string(); From 06bf6db8c90548cb8c0cc91e8e03ff5621606856 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:00:49 +0100 Subject: [PATCH 13/72] feat(gui): keep composite item search per field --- .../src/components/map_render/view_state.rs | 6 + dispel-gui/src/editors/map_editor/message.rs | 3 + .../src/editors/map_editor/update/mod.rs | 6 + .../src/editors/map_editor/view/fields.rs | 38 ++- .../src/editors/map_editor/view/inspector.rs | 33 ++- dispel-gui/src/tests/select_boxes.rs | 240 +++++++++++++++++- dispel-gui/src/update/editor/common.rs | 3 + .../src/view/editor/spreadsheet/message.rs | 3 + .../src/view/editor/spreadsheet/state.rs | 4 + .../view/editor/spreadsheet/view/inspector.rs | 36 ++- .../src/view/editor/spreadsheet/view/mod.rs | 1 + 11 files changed, 350 insertions(+), 23 deletions(-) diff --git a/dispel-gui/src/components/map_render/view_state.rs b/dispel-gui/src/components/map_render/view_state.rs index 084f80bc..c9037b37 100644 --- a/dispel-gui/src/components/map_render/view_state.rs +++ b/dispel-gui/src/components/map_render/view_state.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use crate::editors::map_editor::message::{MapTool, MapViewMode, ObjectBrushMode, SelectedEntity}; use iced::widget::canvas; @@ -53,6 +55,9 @@ pub struct MapViewState { pub selected_sprite_sequence: Option, /// Currently selected entity in the inspector panel. pub selected_entity: Option, + /// Search text of the composite item picker, keyed by field name. Each map + /// editor is per-tab, so the field name alone identifies the input. + pub composite_item_filters: HashMap, /// Cached tile-layer frame. Clear whenever pan, zoom, tiles, or entity /// sprites change. Avoids redrawing the expensive tile layer on every /// cursor-move event (which only affects the overlay canvas). @@ -96,6 +101,7 @@ impl Default for MapViewState { layers_popover_open: false, selected_sprite_sequence: None, selected_entity: None, + composite_item_filters: HashMap::new(), tile_layer_cache: canvas::Cache::new(), overlay_cache: canvas::Cache::new(), } diff --git a/dispel-gui/src/editors/map_editor/message.rs b/dispel-gui/src/editors/map_editor/message.rs index 709a4395..d3b903fa 100644 --- a/dispel-gui/src/editors/map_editor/message.rs +++ b/dispel-gui/src/editors/map_editor/message.rs @@ -125,6 +125,9 @@ pub enum MapEditorMessage { Deselect(usize), /// Entity field edited in the inspector. EntityFieldChanged(usize, SelectedEntity, String, String), + /// Search text typed into a composite item picker. State-only: the record + /// is untouched, so no cache refresh or history entry is needed. + CompositeItemFilterChanged(usize, String, String), /// Save all modified entity .ref files. SaveEntities(usize), /// Async save completed. Ok carries a status message; Err the error text. diff --git a/dispel-gui/src/editors/map_editor/update/mod.rs b/dispel-gui/src/editors/map_editor/update/mod.rs index f37dc2ca..41b97ced 100644 --- a/dispel-gui/src/editors/map_editor/update/mod.rs +++ b/dispel-gui/src/editors/map_editor/update/mod.rs @@ -23,6 +23,12 @@ pub fn handle(message: MapEditorMessage, app: &mut App) -> Task { MapEditorMessage::EntityFieldChanged(tab_id, entity, field, value) => { entity::field_changed(app, tab_id, entity, field, value) } + MapEditorMessage::CompositeItemFilterChanged(tab_id, field, query) => { + if let Some(editor) = app.state.editors.map_editors.get_mut(&tab_id) { + editor.view.composite_item_filters.insert(field, query); + } + Task::none() + } MapEditorMessage::Undo(tab_id) => entity::undo(app, tab_id), MapEditorMessage::Redo(tab_id) => entity::redo(app, tab_id), MapEditorMessage::SaveEntities(tab_id) => persistence::save_entities(app, tab_id), diff --git a/dispel-gui/src/editors/map_editor/view/fields.rs b/dispel-gui/src/editors/map_editor/view/fields.rs index 74cf1869..06517ced 100644 --- a/dispel-gui/src/editors/map_editor/view/fields.rs +++ b/dispel-gui/src/editors/map_editor/view/fields.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use crate::components::composite_item::composite_item_picker; use crate::components::editable::{EditableRecord, FieldKind}; -use crate::message::{Message, MessageExt, SystemMessage}; +use crate::message::{Message, MessageExt}; use crate::style; use iced::widget::{column, pick_list, row, scrollable, text, text_input}; use iced::{Element, Fill}; @@ -18,13 +18,21 @@ pub fn build_record_fields<'a, R: EditableRecord>( tab_id: usize, sel: SelectedEntity, lookups: &'a HashMap>, + composite_filters: &'a HashMap, ) -> Element<'a, Message> { let mut col = column![].spacing(5); for desc in R::field_descriptors() { let value = record.get_field(desc.name); col = col.push(inspector_field_row( - desc.label, desc.name, &desc.kind, &value, tab_id, sel, lookups, + desc.label, + desc.name, + &desc.kind, + &value, + tab_id, + sel, + lookups, + composite_filters, )); } scrollable(col).spacing(6).into() @@ -35,6 +43,7 @@ pub fn build_record_fields<'a, R: EditableRecord>( /// `label` and `name` are `&'static str` (from `FieldDescriptor`); `value` is a /// short-lived borrow of a locally-computed `String`; text inputs clone it before /// constructing their returned widgets. +#[allow(clippy::too_many_arguments)] pub fn inspector_field_row<'a>( label: &'static str, name: &'static str, @@ -43,6 +52,7 @@ pub fn inspector_field_row<'a>( tab_id: usize, sel: SelectedEntity, lookups: &'a HashMap>, + composite_filters: &'a HashMap, ) -> Element<'a, Message> { const LABEL_W: f32 = 140.0; match kind { @@ -151,13 +161,23 @@ pub fn inspector_field_row<'a>( FieldKind::CompositeItem { lookup_key } => { let entries = lookups.get(*lookup_key).map(|v| v.as_slice()); + let filter = composite_filters + .get(name) + .map(String::as_str) + .unwrap_or(""); composite_item_picker( label, value, entries, true, - "", - |_| Message::System(SystemMessage::DismissError), + filter, + move |text| { + Message::map_editor(MapEditorMessage::CompositeItemFilterChanged( + tab_id, + name.to_string(), + text, + )) + }, move |v| { Message::map_editor(MapEditorMessage::EntityFieldChanged( tab_id, @@ -177,6 +197,9 @@ mod tests { use iced_test::selector::{Candidate, Target}; use iced_test::simulator; + static EMPTY_FILTERS: std::sync::LazyLock> = + std::sync::LazyLock::new(HashMap::new); + fn count_label_text(element: Element<'_, Message>, label: &str) -> usize { let mut ui = simulator(element); let mut count = 0usize; @@ -221,6 +244,7 @@ mod tests { 0, SelectedEntity::Npc(0), &lookups, + &EMPTY_FILTERS, ); assert!( crate::tests::common::select_shows(element, "Left"), @@ -254,6 +278,7 @@ mod tests { 0, SelectedEntity::DrawItem(0), &lookups, + &EMPTY_FILTERS, ); assert!( crate::tests::common::select_shows(unknown, "Bogus"), @@ -268,6 +293,7 @@ mod tests { 0, SelectedEntity::DrawItem(0), &lookups, + &EMPTY_FILTERS, ); assert!( crate::tests::common::select_shows(known, "Beta"), @@ -294,6 +320,7 @@ mod tests { 0, SelectedEntity::Monster(0), &lookups, + &EMPTY_FILTERS, ); assert!( crate::tests::common::select_shows(missing, "Unknown (99)"), @@ -308,6 +335,7 @@ mod tests { 0, SelectedEntity::Monster(0), &lookups, + &EMPTY_FILTERS, ); assert!( crate::tests::common::select_shows(duplicate, "Invented Creature (9)"), @@ -322,6 +350,7 @@ mod tests { 0, SelectedEntity::Monster(0), &lookups, + &EMPTY_FILTERS, ); let messages = crate::tests::common::activate_select_option(duplicate, 0, -1); let emitted: Vec = messages @@ -353,6 +382,7 @@ mod tests { 0, SelectedEntity::DrawItem(0), &lookups, + &EMPTY_FILTERS, ); assert_eq!( count_label_text(element, "Invented Item:"), diff --git a/dispel-gui/src/editors/map_editor/view/inspector.rs b/dispel-gui/src/editors/map_editor/view/inspector.rs index 1d50b100..a4f35b09 100644 --- a/dispel-gui/src/editors/map_editor/view/inspector.rs +++ b/dispel-gui/src/editors/map_editor/view/inspector.rs @@ -24,7 +24,13 @@ pub fn build_inspector<'a>( let (title, width, body): (&'static str, f32, Element<'a, Message>) = match sel { SelectedEntity::Monster(i) => { let body = if let Some(record) = state.data.monsters.get(i) { - fields::build_record_fields::(record, tab_id, sel, lookups) + fields::build_record_fields::( + record, + tab_id, + sel, + lookups, + &state.view.composite_item_filters, + ) } else { text("Monster not found").size(12).into() }; @@ -36,7 +42,14 @@ pub fn build_inspector<'a>( for desc in NPC::field_descriptors() { let value = record.get_field(desc.name); els.push(fields::inspector_field_row( - desc.label, desc.name, &desc.kind, &value, tab_id, sel, lookups, + desc.label, + desc.name, + &desc.kind, + &value, + tab_id, + sel, + lookups, + &state.view.composite_item_filters, )); } column(els).spacing(6).into() @@ -47,7 +60,13 @@ pub fn build_inspector<'a>( } SelectedEntity::Extra(i) => { let body = if let Some(record) = state.data.extra_refs.get(i) { - fields::build_record_fields::(record, tab_id, sel, lookups) + fields::build_record_fields::( + record, + tab_id, + sel, + lookups, + &state.view.composite_item_filters, + ) } else { text("Object not found").size(12).into() }; @@ -55,7 +74,13 @@ pub fn build_inspector<'a>( } SelectedEntity::DrawItem(i) => { let body = if let Some(record) = state.data.draw_items.get(i) { - fields::build_record_fields::(record, tab_id, sel, lookups) + fields::build_record_fields::( + record, + tab_id, + sel, + lookups, + &state.view.composite_item_filters, + ) } else { text("Draw item not found").size(12).into() }; diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs index c7211567..d8311a73 100644 --- a/dispel-gui/src/tests/select_boxes.rs +++ b/dispel-gui/src/tests/select_boxes.rs @@ -5,12 +5,12 @@ //! contain and omit the displayed id. Each label must survive `set_field` / //! `get_field` and be visible in the spreadsheet inspector and the map editor. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::fmt::{Debug, Display}; use dispel_core::references::enums::WireValue; use dispel_core::{ - BooleanFlag, DialogOwner, DialogType, DialogueScript, EditItem, EditItemEffect, + BooleanFlag, DialogOwner, DialogType, DialogueScript, DrawItem, EditItem, EditItemEffect, EditItemModification, Event, EventNpcRef, EventType, ExtraObjectType, ExtraRef, HealItem, HealItemFlag, MagicSpell, MagicSpellFlag, MagicType, Map, MapLighting, Monster, MonsterAiType, MonsterRef, MonsterSpawn, NPC, NpcInteractionMode, NpcLookingDirection, NpcMovementMode, @@ -18,13 +18,19 @@ use dispel_core::{ }; use crate::components::editable::{EditableRecord, FieldDescriptor, FieldKind}; +use crate::editors::map_editor::MapEditorMessage; use crate::editors::map_editor::message::SelectedEntity; use crate::editors::map_editor::view::fields; -use crate::message::{EditorMessage, Message, SystemMessage}; +use crate::message::{EditorMessage, FileTreeMessage, Message, SystemMessage}; use crate::view::editor::spreadsheet::message::SpreadsheetMessage; use crate::view::editor::spreadsheet::view::inspector::build_inspector_field; +use iced_test::selector::{Candidate, Target}; +use iced_test::simulator; -use super::common::{activate_select_option, select_shows}; +use super::common::{activate_select_option, select_shows, select_values}; + +static EMPTY_FILTERS: std::sync::LazyLock> = + std::sync::LazyLock::new(HashMap::new); /// The formatting protocol of a field's get path. trait LabelFormat { @@ -128,11 +134,18 @@ fn render_both( None, captured_field_changed, &empty, + &EMPTY_FILTERS, captured_spreadsheet, ); + let shown = select_values(inspector); + assert!( + shown.iter().any(|value| value == expected), + "inspector for {} must render {expected:?}, got {shown:?}", + desc.name + ); assert!( - select_shows(inspector, expected), - "inspector for {} must render {expected:?}", + shown.iter().all(|value| !value.trim().is_empty()), + "inspector for {} must never render a blank selection, got {shown:?}", desc.name ); @@ -144,10 +157,17 @@ fn render_both( 0, SelectedEntity::Npc(0), lookups, + &EMPTY_FILTERS, ); + let shown = select_values(row); assert!( - select_shows(row, expected), - "map editor row for {} must render {expected:?}", + shown.iter().any(|value| value == expected), + "map editor row for {} must render {expected:?}, got {shown:?}", + desc.name + ); + assert!( + shown.iter().all(|value| !value.trim().is_empty()), + "map editor row for {} must never render a blank selection, got {shown:?}", desc.name ); } @@ -215,6 +235,7 @@ fn inspector_emissions( None, captured_field_changed, &empty, + &EMPTY_FILTERS, captured_spreadsheet, ); activate_select_option(element, nth, 0) @@ -241,6 +262,7 @@ fn map_emissions( 0, SelectedEntity::Npc(0), lookups, + &EMPTY_FILTERS, ); activate_select_option(element, 0, 0) .into_iter() @@ -253,6 +275,31 @@ fn map_emissions( .collect() } +/// Type into the composite search input of a rendered inspector and return the +/// messages emitted while typing (one per keystroke). +fn type_filter(element: iced::Element<'_, Message>, query: &str) -> Vec { + let mut ui = simulator(element); + let mut search = |candidate: Candidate<'_>| match candidate { + Candidate::TextInput { state, .. } if state.text().into_owned() == "Search items..." => { + Some(Target::from(candidate)) + } + _ => None, + }; + ui.click(&mut search) + .expect("composite search input must be rendered"); + ui.typewrite(query); + ui.into_messages().collect() +} + +fn filter_capturing_spreadsheet(msg: SpreadsheetMessage) -> Message { + match msg { + SpreadsheetMessage::CompositeItemFilterChanged(_, query) => { + Message::FileTree(FileTreeMessage::Search(query)) + } + other => captured_spreadsheet(other), + } +} + fn audit_lookup(field: &'static str) { let desc = descriptor_of::(field); let FieldKind::Lookup(key) = &desc.kind else { @@ -307,10 +354,10 @@ fn audit_composite(field: &'static str) { )]); render_both(desc, "1:5", &present, "Invented Sword"); - render_both(desc, "1:5", &absent, "Unknown (5)"); - render_both(desc, "1:99", &present, "Unknown (99)"); + render_both(desc, "1:5", &absent, "Unknown (1:5)"); + render_both(desc, "1:99", &present, "Unknown (1:99)"); - for emitted in inspector_emissions(desc, "1:5", &present, 1) + for emitted in inspector_emissions(desc, "1:5", &present, 0) .into_iter() .chain(map_emissions(desc, "1:5", &present)) { @@ -504,6 +551,176 @@ fn test_every_lookup_and_composite_field_round_trips_through_both_views() { audit_composite::("interaction_result_item"); } +#[test] +fn test_composite_filter_narrows_spreadsheet_inspector_options() { + let desc = descriptor_of::("item"); + let FieldKind::CompositeItem { lookup_key } = &desc.kind else { + panic!("item must be a composite field"); + }; + let lookups = HashMap::from([( + lookup_key.to_string(), + vec![ + ("1:5".to_string(), "[Weapon] Invented Sword".to_string()), + ("2:7".to_string(), "[Healing] Invented Herb".to_string()), + ("255:15".to_string(), "[-]".to_string()), + ], + )]); + let contents = HashMap::new(); + + let unfiltered = build_inspector_field( + desc, + "1:5".into(), + 0, + &lookups, + None, + captured_field_changed, + &contents, + &EMPTY_FILTERS, + filter_capturing_spreadsheet, + ); + let query = type_filter(unfiltered, "herb") + .into_iter() + .filter_map(|m| match m { + Message::FileTree(FileTreeMessage::Search(q)) => Some(q), + _ => None, + }) + .last() + .expect("the search input must emit its query"); + assert_eq!(query, "herb"); + + let filters = HashMap::from([("item".to_string(), query)]); + let filtered = build_inspector_field( + desc, + "1:5".into(), + 0, + &lookups, + None, + captured_field_changed, + &contents, + &filters, + captured_spreadsheet, + ); + assert!( + select_values(filtered) + .iter() + .any(|value| value == "[Weapon] Invented Sword"), + "the current item must stay visible while its filter is active" + ); + + let reachable: HashSet = (-3..=3) + .flat_map(|offset| { + let element = build_inspector_field( + desc, + "1:5".into(), + 0, + &lookups, + None, + captured_field_changed, + &contents, + &filters, + captured_spreadsheet, + ); + activate_select_option(element, 0, offset) + .into_iter() + .filter_map(|m| match m { + Message::Editor(EditorMessage::Weapon( + crate::editors::weapon::WeaponEditorMessage::FieldChanged(_, _, value), + )) => Some(value), + _ => None, + }) + }) + .collect(); + assert_eq!( + reachable, + HashSet::from(["1:5".to_string(), "2:7".to_string()]), + "the filter must remove every non-matching option" + ); +} + +#[test] +fn test_composite_filter_narrows_map_editor_options() { + let desc = descriptor_of::("item"); + let FieldKind::CompositeItem { lookup_key } = &desc.kind else { + panic!("item must be a composite field"); + }; + let lookups = HashMap::from([( + lookup_key.to_string(), + vec![ + ("1:5".to_string(), "[Weapon] Invented Sword".to_string()), + ("2:7".to_string(), "[Healing] Invented Herb".to_string()), + ("255:15".to_string(), "[-]".to_string()), + ], + )]); + + let unfiltered = fields::inspector_field_row( + desc.label, + desc.name, + &desc.kind, + "1:5", + 0, + SelectedEntity::Npc(0), + &lookups, + &EMPTY_FILTERS, + ); + let query = type_filter(unfiltered, "herb") + .into_iter() + .filter_map(|m| match m { + Message::Editor(EditorMessage::MapEditor( + MapEditorMessage::CompositeItemFilterChanged(_, _, query), + )) => Some(query), + _ => None, + }) + .last() + .expect("the search input must emit its query"); + assert_eq!(query, "herb"); + + let filters = HashMap::from([("item".to_string(), query)]); + let filtered = fields::inspector_field_row( + desc.label, + desc.name, + &desc.kind, + "1:5", + 0, + SelectedEntity::Npc(0), + &lookups, + &filters, + ); + assert!( + select_values(filtered) + .iter() + .any(|value| value == "[Weapon] Invented Sword"), + "the current item must stay visible while its filter is active" + ); + + let reachable: HashSet = (-3..=3) + .flat_map(|offset| { + let element = fields::inspector_field_row( + desc.label, + desc.name, + &desc.kind, + "1:5", + 0, + SelectedEntity::Npc(0), + &lookups, + &filters, + ); + activate_select_option(element, 0, offset) + .into_iter() + .filter_map(|m| match m { + Message::Editor(EditorMessage::MapEditor( + MapEditorMessage::EntityFieldChanged(_, _, _, value), + )) => Some(value), + _ => None, + }) + }) + .collect(); + assert_eq!( + reachable, + HashSet::from(["1:5".to_string(), "2:7".to_string()]), + "the map editor filter must remove every non-matching option" + ); +} + #[test] fn test_lookup_label_collision_emits_each_own_id() { let desc = descriptor_of::("monster_db_id"); @@ -525,6 +742,7 @@ fn test_lookup_label_collision_emits_each_own_id() { None, captured_field_changed, &empty, + &EMPTY_FILTERS, captured_spreadsheet, ); activate_select_option(element, 0, offset) diff --git a/dispel-gui/src/update/editor/common.rs b/dispel-gui/src/update/editor/common.rs index b59123c1..81ee9f6d 100644 --- a/dispel-gui/src/update/editor/common.rs +++ b/dispel-gui/src/update/editor/common.rs @@ -166,6 +166,9 @@ macro_rules! handle_spreadsheet_messages_inner { $compute_caches return task; } + SM::CompositeItemFilterChanged(field, query) => { + $ss.composite_item_filters.insert(field, query); + } SM::CachesComputed(data) => { $ss.install_caches(data); $ss.is_loading = false; diff --git a/dispel-gui/src/view/editor/spreadsheet/message.rs b/dispel-gui/src/view/editor/spreadsheet/message.rs index 7a73384c..488db432 100644 --- a/dispel-gui/src/view/editor/spreadsheet/message.rs +++ b/dispel-gui/src/view/editor/spreadsheet/message.rs @@ -63,6 +63,9 @@ pub enum SpreadsheetMessage { /// Fired by `text_input` / `pick_list` widgets in the inspector panel. /// Routes through the macro so that `compute_all_caches` is called after. InspectorFieldChanged(usize, String, String), + /// Search text typed into a composite item picker. `(field_name, query)` + /// is stored on the spreadsheet state; no record is touched. + CompositeItemFilterChanged(String, String), // ── Async cache loading ──────────────────────────────────────────────── /// Result of an off-thread `compute_caches` job. The handler installs the diff --git a/dispel-gui/src/view/editor/spreadsheet/state.rs b/dispel-gui/src/view/editor/spreadsheet/state.rs index a858fbd6..fdb4eddf 100644 --- a/dispel-gui/src/view/editor/spreadsheet/state.rs +++ b/dispel-gui/src/view/editor/spreadsheet/state.rs @@ -127,6 +127,9 @@ pub struct SpreadsheetState { /// record, keyed by field name. Populated on `SelectRow`. Allows the /// cursor / selection to survive re-renders. pub inspector_textarea_contents: HashMap, + /// Search text of the composite item picker, keyed by field name. Kept per + /// field so switching rows does not lose an in-progress item search. + pub composite_item_filters: HashMap, /// Process-wide cache of pre-shaped paragraphs. Shared by every cell /// the table widget paints; cheap to clone (Arc). @@ -165,6 +168,7 @@ impl Default for SpreadsheetState { column_filter_options: Vec::new(), column_filter_search: String::new(), inspector_textarea_contents: HashMap::new(), + composite_item_filters: HashMap::new(), paragraph_cache: ParagraphCache::default(), } } diff --git a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs index 70f1633c..2bc78f5b 100644 --- a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs +++ b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs @@ -12,7 +12,7 @@ use crate::components::composite_item::composite_item_picker; use crate::components::editable::{EditableRecord, FieldDescriptor, FieldKind}; use crate::components::generic_editor::GenericEditorState; use crate::components::utils::horizontal_space; -use crate::message::{Message, SystemMessage}; +use crate::message::Message; use crate::style; use crate::view::editor::spreadsheet::message::SpreadsheetMessage; use crate::view::editor::spreadsheet::state::SpreadsheetState; @@ -24,6 +24,7 @@ pub fn build_inspector_panel<'a, R: EditableRecord>( editor: &'a GenericEditorState, spreadsheet: &'a SpreadsheetState, lookups: &'a HashMap>, + composite_filters: &'a HashMap, field_changed_msg: fn(usize, String, String) -> Message, spreadsheet_msg: fn(SpreadsheetMessage) -> Message, ) -> Element<'a, Message> { @@ -59,6 +60,7 @@ pub fn build_inspector_panel<'a, R: EditableRecord>( validation_error, field_changed_msg, &spreadsheet.inspector_textarea_contents, + composite_filters, spreadsheet_msg, )); } @@ -89,6 +91,7 @@ pub(crate) fn build_inspector_field<'a>( validation_error: Option, field_changed_msg: fn(usize, String, String) -> Message, textarea_contents: &'a HashMap, + composite_filters: &'a HashMap, spreadsheet_msg: fn(SpreadsheetMessage) -> Message, ) -> Element<'a, Message> { let label = text(descriptor.label).size(11).style(style::subtle_text); @@ -161,13 +164,23 @@ pub(crate) fn build_inspector_field<'a>( FieldKind::CompositeItem { lookup_key } => { let entries = lookups.get(*lookup_key).map(|v| v.as_slice()); let field_name = descriptor.name.to_string(); + let filter_name = descriptor.name.to_string(); + let filter = composite_filters + .get(descriptor.name) + .map(String::as_str) + .unwrap_or(""); composite_item_picker( descriptor.label, &value, entries, false, - "", - |_| Message::System(SystemMessage::DismissError), + filter, + move |text| { + spreadsheet_msg(SpreadsheetMessage::CompositeItemFilterChanged( + filter_name.clone(), + text, + )) + }, move |v| { spreadsheet_msg(SpreadsheetMessage::InspectorFieldChanged( orig_idx, @@ -214,6 +227,9 @@ mod tests { use iced_test::selector::{Candidate, Target}; use iced_test::simulator; + static EMPTY_FILTERS: std::sync::LazyLock> = + std::sync::LazyLock::new(HashMap::new); + fn field_changed(idx: usize, name: String, value: String) -> Message { Message::Editor(crate::message::editor::EditorMessage::Weapon( crate::editors::weapon::WeaponEditorMessage::FieldChanged(idx, name, value), @@ -269,6 +285,7 @@ mod tests { None, field_changed, &contents, + &EMPTY_FILTERS, spreadsheet_msg, ); assert_eq!( @@ -290,6 +307,7 @@ mod tests { None, field_changed, &contents, + &EMPTY_FILTERS, spreadsheet_msg, ); assert_eq!( @@ -336,6 +354,7 @@ mod tests { None, field_changed, &contents, + &EMPTY_FILTERS, spreadsheet_msg, ); assert!( @@ -382,6 +401,7 @@ mod tests { None, field_changed, &contents, + &EMPTY_FILTERS, spreadsheet_msg, ); assert!( @@ -415,6 +435,7 @@ mod tests { None, field_changed, &contents, + &EMPTY_FILTERS, spreadsheet_msg, ); assert!( @@ -430,6 +451,7 @@ mod tests { None, field_changed, &contents, + &EMPTY_FILTERS, spreadsheet_msg, ); assert!( @@ -445,6 +467,7 @@ mod tests { None, field_changed, &contents, + &EMPTY_FILTERS, field_changed_spreadsheet_msg, ); let messages = crate::tests::common::activate_select_option(duplicate, 0, -1); @@ -480,11 +503,16 @@ mod tests { None, field_changed, &contents, + &EMPTY_FILTERS, spreadsheet_msg, ); let mut ui = simulator(element); + // Select by placeholder: a composite picker would render its search + // input first, and clicking that would not edit the field value. let mut pick_input = |candidate: Candidate<'_>| match candidate { - Candidate::TextInput { .. } => Some(Target::from(candidate)), + Candidate::TextInput { state, .. } if state.text().into_owned().is_empty() => { + Some(Target::from(candidate)) + } _ => None, }; ui.click(&mut pick_input) diff --git a/dispel-gui/src/view/editor/spreadsheet/view/mod.rs b/dispel-gui/src/view/editor/spreadsheet/view/mod.rs index d36f6cdb..01fc6b45 100644 --- a/dispel-gui/src/view/editor/spreadsheet/view/mod.rs +++ b/dispel-gui/src/view/editor/spreadsheet/view/mod.rs @@ -73,6 +73,7 @@ pub fn view_spreadsheet<'a, R: EditableRecord>( editor, spreadsheet, lookups, + &spreadsheet.composite_item_filters, field_changed_msg, spreadsheet_msg, ), From 4b697d4de456ec0bb0c1f2d816aa6a28c0f87697 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:14:29 +0100 Subject: [PATCH 14/72] refactor(gui): use iced combo box for composite items --- dispel-gui/src/components/composite_item.rs | 478 +++++++----------- .../src/components/map_render/view_state.rs | 6 - dispel-gui/src/components/standard/macros.rs | 1 + .../src/editors/dialogue_paragraph/view.rs | 1 + .../src/editors/dialogue_script/view.rs | 1 + dispel-gui/src/editors/extra_ref/view.rs | 1 + dispel-gui/src/editors/map_editor/message.rs | 3 - .../src/editors/map_editor/update/mod.rs | 6 - .../src/editors/map_editor/view/fields.rs | 65 +-- .../src/editors/map_editor/view/inspector.rs | 30 +- dispel-gui/src/editors/map_editor/view/mod.rs | 9 +- dispel-gui/src/editors/monster_ref/view.rs | 1 + dispel-gui/src/editors/npc_ref/view.rs | 1 + dispel-gui/src/editors/party_level_db/view.rs | 1 + dispel-gui/src/state.rs | 4 + dispel-gui/src/tests/common.rs | 78 ++- dispel-gui/src/tests/select_boxes.rs | 321 ++++++------ dispel-gui/src/update/editor/common.rs | 3 - dispel-gui/src/update/mod.rs | 6 +- .../src/view/editor/spreadsheet/message.rs | 3 - .../src/view/editor/spreadsheet/state.rs | 4 - .../view/editor/spreadsheet/view/inspector.rs | 69 +-- .../src/view/editor/spreadsheet/view/mod.rs | 5 +- 23 files changed, 491 insertions(+), 606 deletions(-) diff --git a/dispel-gui/src/components/composite_item.rs b/dispel-gui/src/components/composite_item.rs index 82348483..f4f9c8ed 100644 --- a/dispel-gui/src/components/composite_item.rs +++ b/dispel-gui/src/components/composite_item.rs @@ -1,9 +1,11 @@ -use std::rc::Rc; +use std::collections::hash_map::DefaultHasher; +use std::fmt; +use std::hash::Hasher; -use iced::widget::{column as col, pick_list, row, text, text_input}; +use iced::widget::combo_box::{self, ComboBox}; +use iced::widget::{row, text, text_input}; use iced::{Element, Length}; -use crate::components::select::lookup_select; use crate::message::Message; use crate::style; @@ -11,6 +13,73 @@ const LABEL_W: f32 = 140.0; /// The empty-slot option shared with the item catalog. const NO_ITEM_KEY: &str = "255:15"; +const NO_ITEM_LABEL: &str = "[-]"; + +/// One item in the shared composite item catalog. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ItemOption { + pub key: String, + pub label: String, +} + +impl fmt::Display for ItemOption { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.label) + } +} + +/// A single app-level option list shared by every composite item field. +#[derive(Default)] +pub struct CompositeItemOptions { + pub state: combo_box::State, + pub fingerprint: u64, +} + +fn fingerprint_options(entries: Option<&[(String, String)]>) -> u64 { + let mut hasher = DefaultHasher::new(); + hasher.write_u8(u8::from(entries.is_some())); + if let Some(entries) = entries { + for (key, label) in entries { + hasher.write(key.as_bytes()); + hasher.write_u8(0); + hasher.write(label.as_bytes()); + hasher.write_u8(1); + } + } + hasher.finish() +} + +/// Rebuild the shared option list whenever the `"items"` lookup changes. +pub fn refresh_composite_item_options(state: &mut crate::state::AppState) { + let entries = state.lookups.get("items").map(Vec::as_slice); + let fingerprint = fingerprint_options(entries); + if fingerprint == state.composite_item_options.fingerprint { + return; + } + + let options = match entries { + Some(entries) => { + let mut options: Vec = entries + .iter() + .map(|(key, label)| ItemOption { + key: key.clone(), + label: label.clone(), + }) + .collect(); + if !options.iter().any(|option| option.key == NO_ITEM_KEY) { + options.push(ItemOption { + key: NO_ITEM_KEY.to_string(), + label: NO_ITEM_LABEL.to_string(), + }); + } + options + } + None => Vec::new(), + }; + + state.composite_item_options.state = combo_box::State::new(options); + state.composite_item_options.fingerprint = fingerprint; +} /// Render a picker body, optionally prefixed with a fixed-width label column. /// @@ -39,149 +108,100 @@ fn with_optional_label<'a>( /// Build a searchable item picker for `CompositeItem` fields. /// -/// All item files share one select: every entry carries its type in the -/// display label (`[Weapon] Cap`, `[Healing] Herb`, …). A text input above the -/// select filters those labels and composite keys. Falls back to a plain -/// `text_input` when `entries` is `None` (lookups unavailable). `show_label` -/// controls whether the label column is drawn by this component or the caller. -pub fn composite_item_picker( +/// Every item file shares the one app-level option list, so all fields get the +/// same built-in fuzzy search. Falls back to a plain `text_input` before the +/// item catalog has been loaded. `show_label` controls whether the label +/// column is drawn by this component or the caller. +pub fn composite_item_picker<'a>( label: &'static str, value: &str, - entries: Option<&[(String, String)]>, + combo_state: &'a combo_box::State, show_label: bool, - filter: &str, - on_filter: impl Fn(String) -> Message + 'static, - on_change: impl Fn(String) -> Message + 'static, -) -> Element<'static, Message> { - let filter = filter.to_owned(); - let on_filter: Rc Message> = Rc::new(on_filter); - let on_change: Rc Message> = Rc::new(on_change); - - let search_input: Element<'static, Message> = { - let of = on_filter.clone(); - text_input("Search items...", filter.clone()) - .on_input(move |v| of(v)) - .padding(4) - .size(11) - .width(Length::Fill) - .into() - }; - - let Some(entries) = entries else { - let oc = on_change; - let input: Element<'static, Message> = text_input("", value.to_owned()) - .on_input(move |v| oc(v)) + on_change: impl Fn(String) -> Message + 'a, +) -> Element<'a, Message> { + // Without lookups there is nothing to search: keep the raw key editable. + if combo_state.options().is_empty() { + let input: Element<'a, Message> = text_input("", value.to_owned()) + .on_input(on_change) .padding(4) .size(11) .width(Length::Fill) .into(); - let body: Element<'static, Message> = col![search_input, input].spacing(4).into(); - return with_optional_label(label, body, show_label); - }; - - // One option per item file. Every key with the no-item byte denotes the - // same empty slot, so only the canonical sentinel survives. - let mut collapsed: Vec<(String, String)> = Vec::with_capacity(entries.len()); - for (key, display) in entries { - if key.starts_with("255:") { - if key == NO_ITEM_KEY && !collapsed.iter().any(|(k, _)| k == key) { - collapsed.push((key.clone(), display.clone())); - } - } else { - collapsed.push((key.clone(), display.clone())); - } - } - if !collapsed.iter().any(|(key, _)| key == NO_ITEM_KEY) { - collapsed.push((NO_ITEM_KEY.to_string(), "[-]".to_string())); + return with_optional_label(label, input, show_label); } - let is_no_item = value.starts_with("255:"); - let query = filter.to_lowercase(); - let mut filtered_entries: Vec<(String, String)> = collapsed + // ComboBox copies the selection into a String, so a locally-built option + // is enough. Only the label must match; the closure owns the exact key. + let selected = combo_state + .options() .iter() - .filter(|(key, display)| { - display.to_lowercase().contains(&query) || key.to_lowercase().contains(&query) - }) + .find(|option| option.key == value) .cloned() - .collect(); - - // The current value must never vanish from the select while the user - // types. A no-item value also keeps the sentinel that stands in for it. - let mut required: Vec<&str> = vec![value]; - if is_no_item { - required.push(NO_ITEM_KEY); - } - for key in required { - if !filtered_entries.iter().any(|(k, _)| k == key) - && let Some(entry) = collapsed.iter().find(|(k, _)| k == key) - { - filtered_entries.push(entry.clone()); - } - } - - // A non-canonical stored key (e.g. `255:255`) still renders as the shared - // empty-slot option, but re-selecting that option must emit the exact key - // so `InventoryItem::is_empty()` keeps working. - let effective_selected_id = if is_no_item { NO_ITEM_KEY } else { value }; - let mut select = lookup_select(&filtered_entries, effective_selected_id); - if is_no_item && value != NO_ITEM_KEY { - for id in select.label_to_id.values_mut() { - if id == NO_ITEM_KEY { - *id = value.to_string(); - } - } - } - - let picker: Element<'static, Message> = { - let ids = select.label_to_id; - let fallback_key = value.to_owned(); - pick_list(select.selected, select.options, String::clone) - .on_select(move |selected_name| { - let key = ids - .get(&selected_name) - .cloned() - .unwrap_or_else(|| fallback_key.clone()); - on_change(key) - }) - .width(Length::Fill) - .into() - }; - - let body: Element<'static, Message> = col![search_input, picker].spacing(4).into(); - with_optional_label(label, body, show_label) + .unwrap_or_else(|| ItemOption { + key: value.to_owned(), + label: if value.starts_with("255:") { + NO_ITEM_LABEL.to_string() + } else { + format!("Unknown ({value})") + }, + }); + + // A non-canonical stored key (e.g. `255:255`) renders as the shared empty + // slot. Re-selecting that option must still emit the exact stored key so + // `InventoryItem::is_empty()` keeps working. + let stored_key = value.to_owned(); + let picker: Element<'a, Message> = ComboBox::new( + combo_state, + "Search items...", + Some(&selected), + move |option: ItemOption| { + let key = if option.key == NO_ITEM_KEY && stored_key.starts_with("255:") { + stored_key.clone() + } else { + option.key + }; + on_change(key) + }, + ) + .padding(4) + .size(11) + .width(Length::Fill) + .menu_height(240.0) + .into(); + + with_optional_label(label, picker, show_label) } #[cfg(all(test, feature = "iced_test"))] mod tests { use super::*; use crate::editors::weapon::WeaponEditorMessage; - use crate::message::{EditorMessage, FileTreeMessage}; - use dispel_core::ItemTypeId; + use crate::message::EditorMessage; use iced_test::selector::{Candidate, Target}; use iced_test::simulator; - fn picker( - value: &str, - entries: Option<&[(String, String)]>, - filter: &str, - ) -> Element<'static, Message> { - composite_item_picker( - "Invented Item", - value, - entries, - false, - filter, - |v| Message::FileTree(FileTreeMessage::Search(v)), - |v| { - Message::Editor(EditorMessage::Weapon(WeaponEditorMessage::FieldChanged( - 0, - "item".to_string(), - v, - ))) - }, + fn options(entries: &[(&str, &str)]) -> combo_box::State { + combo_box::State::new( + entries + .iter() + .map(|(key, label)| ItemOption { + key: (*key).to_string(), + label: (*label).to_string(), + }) + .collect(), ) } + fn picker<'a>(value: &str, state: &'a combo_box::State) -> Element<'a, Message> { + composite_item_picker("Invented Item", value, state, false, |v| { + Message::Editor(EditorMessage::Weapon(WeaponEditorMessage::FieldChanged( + 0, + "item".to_string(), + v, + ))) + }) + } + fn emitted_keys(messages: Vec) -> Vec { messages .into_iter() @@ -196,199 +216,75 @@ mod tests { .collect() } - /// Type into the search box and feed the emitted query back into a fresh - /// render, the way the real caller stores it in state. - fn typed_filter(element: Element<'static, Message>, query: &str) -> String { - let mut ui = simulator(element); - let mut search = |candidate: Candidate<'_>| match candidate { - Candidate::TextInput { state, .. } - if state.text().into_owned() == "Search items..." => - { - Some(Target::from(candidate)) - } - _ => None, - }; - ui.click(&mut search) - .expect("search input must be rendered"); - ui.typewrite(query); - ui.into_messages() - .filter_map(|m| match m { - Message::FileTree(FileTreeMessage::Search(v)) => Some(v), - _ => None, - }) - .last() - .expect("search input must emit its query") - } - fn select_option( value: &str, - entries: &[(String, String)], - filter: &str, + state: &combo_box::State, offset: isize, ) -> Vec { emitted_keys(crate::tests::common::activate_select_option( - picker(value, Some(entries), filter), + picker(value, state), 0, offset, )) } - fn label_rendered(entries: Option<&[(String, String)]>, show_label: bool) -> bool { - let element: Element<'_, Message> = composite_item_picker( + fn label_rendered(state: Option<&combo_box::State>, show_label: bool) -> bool { + let empty = options(&[]); + let state = state.unwrap_or(&empty); + let mut ui = simulator(composite_item_picker( "Invented Item", "1:0", - entries, + state, show_label, - "", - |_| Message::FileTree(FileTreeMessage::Search(String::new())), - |_| Message::FileTree(FileTreeMessage::Search(String::new())), - ); - let mut ui = simulator(element); + |_| { + Message::Editor(EditorMessage::Weapon(WeaponEditorMessage::FieldChanged( + 0, + "item".to_string(), + String::new(), + ))) + }, + )); ui.find("Invented Item").is_ok() } #[test] - fn test_unmapped_composite_keys_render_a_label_and_keep_value() { - let entries = [ - ("1:0".to_string(), "[Weapon] Invented Sword".to_string()), - ("255:15".to_string(), "[-]".to_string()), - ]; - - for value in ["255:0", "255:255"] { - let values = crate::tests::common::select_values(picker(value, Some(&entries), "")); - assert!( - values.iter().any(|v| v == "[-]"), - "{value} must resolve to the no-item sentinel label, got {values:?}" - ); - } - - let values = crate::tests::common::select_values(picker("1:999", Some(&entries), "")); - assert!( - values.iter().any(|v| v == "Unknown (1:999)"), - "an unmapped composite key must render a visible fallback label, got {values:?}" - ); - - let keys = select_option("255:0", &entries, "", 0); - assert_eq!( - keys, - vec!["255:0"], - "choosing the sentinel must keep the exact stored key" - ); - } - - #[test] - fn test_one_select_offers_items_from_every_type() { - let entries = [ - ("1:0".to_string(), "[Weapon] Invented Sword".to_string()), - ("2:7".to_string(), "[Healing] Invented Herb".to_string()), - ("3:2".to_string(), "[Edit] Invented Charm".to_string()), - ("255:15".to_string(), "[-]".to_string()), - ]; - let values = crate::tests::common::select_values(picker("1:0", Some(&entries), "")); - assert_eq!( - values.len(), - 1, - "there must be exactly one select, got {values:?}" - ); - - assert_eq!(select_option("1:0", &entries, "", 1), vec!["2:7"]); - assert_eq!(select_option("1:0", &entries, "", 2), vec!["3:2"]); - assert_eq!(select_option("1:0", &entries, "", 3), vec!["255:15"]); - } - - #[test] - fn test_search_narrows_options_and_keeps_selection_visible() { - let entries = [ - ("1:0".to_string(), "[Weapon] Invented Sword".to_string()), - ("2:7".to_string(), "[Healing] Invented Herb".to_string()), - ("3:2".to_string(), "[Edit] Invented Charm".to_string()), - ("255:15".to_string(), "[-]".to_string()), - ]; - let query = typed_filter(picker("1:0", Some(&entries), ""), "herb"); - assert_eq!(query, "herb"); - - let values = crate::tests::common::select_values(picker("1:0", Some(&entries), &query)); - assert!( - values.iter().any(|v| v == "[Weapon] Invented Sword"), - "the current item must stay selected while filtering, got {values:?}" - ); - - assert_eq!( - select_option("1:0", &entries, &query, -1), - vec!["2:7"], - "the only other option must be the matching item" - ); - let reachable: std::collections::HashSet = (-3..=3) - .flat_map(|offset| select_option("1:0", &entries, "charm", offset)) - .collect(); - assert_eq!( - reachable, - std::collections::HashSet::from(["1:0".to_string(), "3:2".to_string()]), - "non-matching items must be absent from the narrowed list" - ); - - // Filtering by the composite key works just like filtering by label. - let query = typed_filter(picker("1:0", Some(&entries), ""), "3:2"); - assert_eq!(select_option("1:0", &entries, &query, -1), vec!["3:2"]); - } - - #[test] - fn test_selected_label_emits_its_exact_composite_key() { - let entries = [ - ("1:0".to_string(), "[Weapon] Invented Sword".to_string()), - ("2:7".to_string(), "[Healing] Invented Herb".to_string()), - ("255:15".to_string(), "[-]".to_string()), - ]; - assert_eq!(select_option("2:7", &entries, "", 0), vec!["2:7"]); - assert_eq!(select_option("2:7", &entries, "", -1), vec!["1:0"]); + fn test_selected_option_emits_its_composite_key() { + let state = options(&[ + ("1:0", "[Weapon] Invented Sword"), + ("2:7", "[Healing] Invented Herb"), + ("255:15", NO_ITEM_LABEL), + ]); + assert_eq!(select_option("1:0", &state, 1), vec!["2:7"]); } #[test] - fn test_no_item_selection_preserves_exact_key() { - use dispel_core::InventoryItem; - - let entries = [ - ("1:0".to_string(), "[Weapon] Invented Sword".to_string()), - ("255:15".to_string(), "[-]".to_string()), - ]; - - for value in ["255:255", "255:5"] { - assert_eq!(select_option(value, &entries, "", 0), vec![value]); - } - assert_eq!(select_option("255:15", &entries, "", 0), vec!["255:15"]); - - // Filtering out "[-]" must not hide the empty slot either. - assert_eq!( - select_option("255:255", &entries, "sword", 0), - vec!["255:255"] - ); - - let item = InventoryItem::new(ItemTypeId::NoItem, 255); - assert!( - item.is_empty(), - "255:255 must decode to an empty inventory item" - ); + fn test_non_canonical_no_item_key_is_preserved() { + let state = options(&[ + ("1:0", "[Weapon] Invented Sword"), + ("255:15", NO_ITEM_LABEL), + ]); + assert_eq!(select_option("255:255", &state, -1), vec!["255:255"]); } #[test] - fn test_duplicate_display_names_stay_distinguishable() { - let entries = [ - ("1:4".to_string(), "Invented Blade".to_string()), - ("2:4".to_string(), "Invented Blade".to_string()), - ("255:15".to_string(), "[-]".to_string()), - ]; - let values = crate::tests::common::select_values(picker("2:4", Some(&entries), "")); - assert!( - values.iter().any(|v| v == "Invented Blade (2:4)"), - "duplicate labels must be qualified with their composite key, got {values:?}" - ); - assert_eq!(select_option("2:4", &entries, "", -1), vec!["1:4"]); - assert_eq!(select_option("2:4", &entries, "", 0), vec!["2:4"]); + fn test_fallback_text_input_edits_the_raw_value() { + let state = options(&[]); + let mut ui = simulator(picker("255:255", &state)); + let mut input = |candidate: Candidate<'_>| match candidate { + Candidate::TextInput { state, .. } if state.text().into_owned() == "255:255" => { + Some(Target::from(candidate)) + } + _ => None, + }; + ui.click(&mut input) + .expect("raw value input must be rendered"); + ui.typewrite("5"); + assert_eq!(emitted_keys(ui.into_messages().collect()), vec!["255:2555"]); } #[test] fn test_composite_picker_label_follows_show_label() { - let entries = [("1:0".to_string(), "[Weapon] Invented Sword".to_string())]; + let state = options(&[("1:0", "[Weapon] Invented Sword")]); for show_label in [true, false] { assert_eq!( label_rendered(None, show_label), @@ -396,9 +292,9 @@ mod tests { "fallback picker label must follow show_label" ); assert_eq!( - label_rendered(Some(&entries), show_label), + label_rendered(Some(&state), show_label), show_label, - "lookup picker label must follow show_label" + "combo box label must follow show_label" ); } } diff --git a/dispel-gui/src/components/map_render/view_state.rs b/dispel-gui/src/components/map_render/view_state.rs index c9037b37..084f80bc 100644 --- a/dispel-gui/src/components/map_render/view_state.rs +++ b/dispel-gui/src/components/map_render/view_state.rs @@ -1,5 +1,3 @@ -use std::collections::HashMap; - use crate::editors::map_editor::message::{MapTool, MapViewMode, ObjectBrushMode, SelectedEntity}; use iced::widget::canvas; @@ -55,9 +53,6 @@ pub struct MapViewState { pub selected_sprite_sequence: Option, /// Currently selected entity in the inspector panel. pub selected_entity: Option, - /// Search text of the composite item picker, keyed by field name. Each map - /// editor is per-tab, so the field name alone identifies the input. - pub composite_item_filters: HashMap, /// Cached tile-layer frame. Clear whenever pan, zoom, tiles, or entity /// sprites change. Avoids redrawing the expensive tile layer on every /// cursor-move event (which only affects the overlay canvas). @@ -101,7 +96,6 @@ impl Default for MapViewState { layers_popover_open: false, selected_sprite_sequence: None, selected_entity: None, - composite_item_filters: HashMap::new(), tile_layer_cache: canvas::Cache::new(), overlay_cache: canvas::Cache::new(), } diff --git a/dispel-gui/src/components/standard/macros.rs b/dispel-gui/src/components/standard/macros.rs index bf64da7a..7b8fc5ea 100644 --- a/dispel-gui/src/components/standard/macros.rs +++ b/dispel-gui/src/components/standard/macros.rs @@ -35,6 +35,7 @@ macro_rules! define_standard_view { }, |msg| $crate::message::Message::$name(<$Msg>::Spreadsheet(msg)), &app.state.lookups, + &app.state.composite_item_options.state, |event| $crate::message::Message::$name(<$Msg>::PaneResized(event)), |pane| $crate::message::Message::$name(<$Msg>::PaneClicked(pane)), None, diff --git a/dispel-gui/src/editors/dialogue_paragraph/view.rs b/dispel-gui/src/editors/dialogue_paragraph/view.rs index 63a6067f..bf2d1c62 100644 --- a/dispel-gui/src/editors/dialogue_paragraph/view.rs +++ b/dispel-gui/src/editors/dialogue_paragraph/view.rs @@ -50,6 +50,7 @@ pub fn view(app: &App) -> Element<'_, Message> { }, |msg| Message::dialogue_paragraph(DialogueParagraphEditorMessage::Spreadsheet(msg)), &app.state.lookups, + &app.state.composite_item_options.state, |event| Message::dialogue_paragraph(DialogueParagraphEditorMessage::PaneResized(event)), |pane| Message::dialogue_paragraph(DialogueParagraphEditorMessage::PaneClicked(pane)), None, diff --git a/dispel-gui/src/editors/dialogue_script/view.rs b/dispel-gui/src/editors/dialogue_script/view.rs index 2218ef5e..c7e6b9d4 100644 --- a/dispel-gui/src/editors/dialogue_script/view.rs +++ b/dispel-gui/src/editors/dialogue_script/view.rs @@ -46,6 +46,7 @@ pub fn view(app: &App) -> Element<'_, Message> { }, |msg| Message::dialogue_script(DialogueScriptEditorMessage::Spreadsheet(msg)), &app.state.lookups, + &app.state.composite_item_options.state, |event| Message::dialogue_script(DialogueScriptEditorMessage::PaneResized(event)), |pane| Message::dialogue_script(DialogueScriptEditorMessage::PaneClicked(pane)), None, diff --git a/dispel-gui/src/editors/extra_ref/view.rs b/dispel-gui/src/editors/extra_ref/view.rs index a69dd482..22055183 100644 --- a/dispel-gui/src/editors/extra_ref/view.rs +++ b/dispel-gui/src/editors/extra_ref/view.rs @@ -36,6 +36,7 @@ pub fn view(app: &App) -> Element<'_, Message> { |idx, field, val| Message::extra_ref(ExtraRefEditorMessage::FieldChanged(idx, field, val)), |msg| Message::extra_ref(ExtraRefEditorMessage::Spreadsheet(msg)), &app.state.lookups, + &app.state.composite_item_options.state, |event| Message::extra_ref(ExtraRefEditorMessage::PaneResized(event)), |pane| Message::extra_ref(ExtraRefEditorMessage::PaneClicked(pane)), Some(Message::extra_ref(ExtraRefEditorMessage::AddEntry)), diff --git a/dispel-gui/src/editors/map_editor/message.rs b/dispel-gui/src/editors/map_editor/message.rs index d3b903fa..709a4395 100644 --- a/dispel-gui/src/editors/map_editor/message.rs +++ b/dispel-gui/src/editors/map_editor/message.rs @@ -125,9 +125,6 @@ pub enum MapEditorMessage { Deselect(usize), /// Entity field edited in the inspector. EntityFieldChanged(usize, SelectedEntity, String, String), - /// Search text typed into a composite item picker. State-only: the record - /// is untouched, so no cache refresh or history entry is needed. - CompositeItemFilterChanged(usize, String, String), /// Save all modified entity .ref files. SaveEntities(usize), /// Async save completed. Ok carries a status message; Err the error text. diff --git a/dispel-gui/src/editors/map_editor/update/mod.rs b/dispel-gui/src/editors/map_editor/update/mod.rs index 41b97ced..f37dc2ca 100644 --- a/dispel-gui/src/editors/map_editor/update/mod.rs +++ b/dispel-gui/src/editors/map_editor/update/mod.rs @@ -23,12 +23,6 @@ pub fn handle(message: MapEditorMessage, app: &mut App) -> Task { MapEditorMessage::EntityFieldChanged(tab_id, entity, field, value) => { entity::field_changed(app, tab_id, entity, field, value) } - MapEditorMessage::CompositeItemFilterChanged(tab_id, field, query) => { - if let Some(editor) = app.state.editors.map_editors.get_mut(&tab_id) { - editor.view.composite_item_filters.insert(field, query); - } - Task::none() - } MapEditorMessage::Undo(tab_id) => entity::undo(app, tab_id), MapEditorMessage::Redo(tab_id) => entity::redo(app, tab_id), MapEditorMessage::SaveEntities(tab_id) => persistence::save_entities(app, tab_id), diff --git a/dispel-gui/src/editors/map_editor/view/fields.rs b/dispel-gui/src/editors/map_editor/view/fields.rs index 06517ced..3b205ac9 100644 --- a/dispel-gui/src/editors/map_editor/view/fields.rs +++ b/dispel-gui/src/editors/map_editor/view/fields.rs @@ -1,10 +1,10 @@ use std::collections::HashMap; -use crate::components::composite_item::composite_item_picker; +use crate::components::composite_item::{ItemOption, composite_item_picker}; use crate::components::editable::{EditableRecord, FieldKind}; use crate::message::{Message, MessageExt}; use crate::style; -use iced::widget::{column, pick_list, row, scrollable, text, text_input}; +use iced::widget::{column, combo_box, pick_list, row, scrollable, text, text_input}; use iced::{Element, Fill}; use super::super::message::{MapEditorMessage, SelectedEntity}; @@ -18,7 +18,7 @@ pub fn build_record_fields<'a, R: EditableRecord>( tab_id: usize, sel: SelectedEntity, lookups: &'a HashMap>, - composite_filters: &'a HashMap, + combo_state: &'a combo_box::State, ) -> Element<'a, Message> { let mut col = column![].spacing(5); @@ -32,7 +32,7 @@ pub fn build_record_fields<'a, R: EditableRecord>( tab_id, sel, lookups, - composite_filters, + combo_state, )); } scrollable(col).spacing(6).into() @@ -52,7 +52,7 @@ pub fn inspector_field_row<'a>( tab_id: usize, sel: SelectedEntity, lookups: &'a HashMap>, - composite_filters: &'a HashMap, + combo_state: &'a combo_box::State, ) -> Element<'a, Message> { const LABEL_W: f32 = 140.0; match kind { @@ -159,34 +159,15 @@ pub fn inspector_field_row<'a>( .into() } - FieldKind::CompositeItem { lookup_key } => { - let entries = lookups.get(*lookup_key).map(|v| v.as_slice()); - let filter = composite_filters - .get(name) - .map(String::as_str) - .unwrap_or(""); - composite_item_picker( - label, - value, - entries, - true, - filter, - move |text| { - Message::map_editor(MapEditorMessage::CompositeItemFilterChanged( - tab_id, - name.to_string(), - text, - )) - }, - move |v| { - Message::map_editor(MapEditorMessage::EntityFieldChanged( - tab_id, - sel, - name.to_string(), - v, - )) - }, - ) + FieldKind::CompositeItem { lookup_key: _ } => { + composite_item_picker(label, value, combo_state, true, move |v| { + Message::map_editor(MapEditorMessage::EntityFieldChanged( + tab_id, + sel, + name.to_string(), + v, + )) + }) } } } @@ -197,8 +178,8 @@ mod tests { use iced_test::selector::{Candidate, Target}; use iced_test::simulator; - static EMPTY_FILTERS: std::sync::LazyLock> = - std::sync::LazyLock::new(HashMap::new); + static EMPTY_COMBO: std::sync::LazyLock> = + std::sync::LazyLock::new(|| combo_box::State::new(Vec::new())); fn count_label_text(element: Element<'_, Message>, label: &str) -> usize { let mut ui = simulator(element); @@ -244,7 +225,7 @@ mod tests { 0, SelectedEntity::Npc(0), &lookups, - &EMPTY_FILTERS, + &EMPTY_COMBO, ); assert!( crate::tests::common::select_shows(element, "Left"), @@ -278,7 +259,7 @@ mod tests { 0, SelectedEntity::DrawItem(0), &lookups, - &EMPTY_FILTERS, + &EMPTY_COMBO, ); assert!( crate::tests::common::select_shows(unknown, "Bogus"), @@ -293,7 +274,7 @@ mod tests { 0, SelectedEntity::DrawItem(0), &lookups, - &EMPTY_FILTERS, + &EMPTY_COMBO, ); assert!( crate::tests::common::select_shows(known, "Beta"), @@ -320,7 +301,7 @@ mod tests { 0, SelectedEntity::Monster(0), &lookups, - &EMPTY_FILTERS, + &EMPTY_COMBO, ); assert!( crate::tests::common::select_shows(missing, "Unknown (99)"), @@ -335,7 +316,7 @@ mod tests { 0, SelectedEntity::Monster(0), &lookups, - &EMPTY_FILTERS, + &EMPTY_COMBO, ); assert!( crate::tests::common::select_shows(duplicate, "Invented Creature (9)"), @@ -350,7 +331,7 @@ mod tests { 0, SelectedEntity::Monster(0), &lookups, - &EMPTY_FILTERS, + &EMPTY_COMBO, ); let messages = crate::tests::common::activate_select_option(duplicate, 0, -1); let emitted: Vec = messages @@ -382,7 +363,7 @@ mod tests { 0, SelectedEntity::DrawItem(0), &lookups, - &EMPTY_FILTERS, + &EMPTY_COMBO, ); assert_eq!( count_label_text(element, "Invented Item:"), diff --git a/dispel-gui/src/editors/map_editor/view/inspector.rs b/dispel-gui/src/editors/map_editor/view/inspector.rs index a4f35b09..de32b47c 100644 --- a/dispel-gui/src/editors/map_editor/view/inspector.rs +++ b/dispel-gui/src/editors/map_editor/view/inspector.rs @@ -1,11 +1,12 @@ use std::collections::HashMap; +use crate::components::composite_item::ItemOption; use crate::components::editable::EditableRecord; use crate::components::utils::{horizontal_rule, horizontal_space}; use crate::message::{Message, MessageExt}; use crate::style; use dispel_core::{DrawItem, ExtraRef, MonsterRef, NPC}; -use iced::widget::{button, column, container, row, scrollable, text, text_input}; +use iced::widget::{button, column, combo_box, container, row, scrollable, text, text_input}; use iced::{Element, Fill, Font}; use super::super::message::{MapEditorMessage, SelectedEntity}; @@ -18,19 +19,14 @@ pub fn build_inspector<'a>( tab_id: usize, sel: SelectedEntity, lookups: &'a HashMap>, + combo_state: &'a combo_box::State, ) -> Element<'a, Message> { let close_msg = Message::map_editor(MapEditorMessage::Deselect(tab_id)); let (title, width, body): (&'static str, f32, Element<'a, Message>) = match sel { SelectedEntity::Monster(i) => { let body = if let Some(record) = state.data.monsters.get(i) { - fields::build_record_fields::( - record, - tab_id, - sel, - lookups, - &state.view.composite_item_filters, - ) + fields::build_record_fields::(record, tab_id, sel, lookups, combo_state) } else { text("Monster not found").size(12).into() }; @@ -49,7 +45,7 @@ pub fn build_inspector<'a>( tab_id, sel, lookups, - &state.view.composite_item_filters, + combo_state, )); } column(els).spacing(6).into() @@ -60,13 +56,7 @@ pub fn build_inspector<'a>( } SelectedEntity::Extra(i) => { let body = if let Some(record) = state.data.extra_refs.get(i) { - fields::build_record_fields::( - record, - tab_id, - sel, - lookups, - &state.view.composite_item_filters, - ) + fields::build_record_fields::(record, tab_id, sel, lookups, combo_state) } else { text("Object not found").size(12).into() }; @@ -74,13 +64,7 @@ pub fn build_inspector<'a>( } SelectedEntity::DrawItem(i) => { let body = if let Some(record) = state.data.draw_items.get(i) { - fields::build_record_fields::( - record, - tab_id, - sel, - lookups, - &state.view.composite_item_filters, - ) + fields::build_record_fields::(record, tab_id, sel, lookups, combo_state) } else { text("Draw item not found").size(12).into() }; diff --git a/dispel-gui/src/editors/map_editor/view/mod.rs b/dispel-gui/src/editors/map_editor/view/mod.rs index 33471925..2651d4de 100644 --- a/dispel-gui/src/editors/map_editor/view/mod.rs +++ b/dispel-gui/src/editors/map_editor/view/mod.rs @@ -557,8 +557,13 @@ pub fn view(app: &App) -> Element<'_, Message> { let body: Element<'_, Message> = match state.view.view_mode { MapViewMode::Map => match state.view.selected_entity { Some(sel) => { - let inspector = - inspector::build_inspector(state, tab_id, sel, &app.state.lookups); + let inspector = inspector::build_inspector( + state, + tab_id, + sel, + &app.state.lookups, + &app.state.composite_item_options.state, + ); row![canvas_with_overlay, inspector] .width(Fill) .height(Fill) diff --git a/dispel-gui/src/editors/monster_ref/view.rs b/dispel-gui/src/editors/monster_ref/view.rs index a1e7a877..26741557 100644 --- a/dispel-gui/src/editors/monster_ref/view.rs +++ b/dispel-gui/src/editors/monster_ref/view.rs @@ -42,6 +42,7 @@ pub fn view(app: &App) -> Element<'_, Message> { }, |msg| Message::monster_ref(MonsterRefEditorMessage::Spreadsheet(msg)), &app.state.lookups, + &app.state.composite_item_options.state, |event| Message::monster_ref(MonsterRefEditorMessage::PaneResized(event)), |pane| Message::monster_ref(MonsterRefEditorMessage::PaneClicked(pane)), Some(Message::monster_ref(MonsterRefEditorMessage::AddEntry)), diff --git a/dispel-gui/src/editors/npc_ref/view.rs b/dispel-gui/src/editors/npc_ref/view.rs index ec9102ff..158ea24b 100644 --- a/dispel-gui/src/editors/npc_ref/view.rs +++ b/dispel-gui/src/editors/npc_ref/view.rs @@ -36,6 +36,7 @@ pub fn view(app: &App) -> Element<'_, Message> { |idx, field, val| Message::npc_ref(NpcRefEditorMessage::FieldChanged(idx, field, val)), |msg| Message::npc_ref(NpcRefEditorMessage::Spreadsheet(msg)), &app.state.lookups, + &app.state.composite_item_options.state, |event| Message::npc_ref(NpcRefEditorMessage::PaneResized(event)), |pane| Message::npc_ref(NpcRefEditorMessage::PaneClicked(pane)), Some(Message::npc_ref(NpcRefEditorMessage::AddEntry)), diff --git a/dispel-gui/src/editors/party_level_db/view.rs b/dispel-gui/src/editors/party_level_db/view.rs index 4f5bd81f..6024bb08 100644 --- a/dispel-gui/src/editors/party_level_db/view.rs +++ b/dispel-gui/src/editors/party_level_db/view.rs @@ -57,6 +57,7 @@ pub fn view(app: &App) -> Element<'_, Message> { }, |msg| Message::party_level_db(PartyLevelDbEditorMessage::Spreadsheet(msg)), &app.state.lookups, + &app.state.composite_item_options.state, |msg| Message::party_level_db(PartyLevelDbEditorMessage::PaneResized(msg)), |pane| Message::party_level_db(PartyLevelDbEditorMessage::PaneClicked(pane)), None, diff --git a/dispel-gui/src/state.rs b/dispel-gui/src/state.rs index ce2ea82d..3c24a91b 100644 --- a/dispel-gui/src/state.rs +++ b/dispel-gui/src/state.rs @@ -1,3 +1,4 @@ +use crate::components::composite_item::CompositeItemOptions; use crate::editor_registry::EditorRegistry; use crate::indexation::file_index_cache::{FileIndexCache, FileIndexCacheManager}; use crate::message::{Message, system::SystemMessage}; @@ -20,6 +21,8 @@ pub struct AppState { pub shared_game_path: String, pub editors: EditorRegistry, pub lookups: HashMap>, + /// Shared searchable options for every composite item field. + pub composite_item_options: CompositeItemOptions, pub workspace: Workspace, pub pane_state: PaneState, pub file_index_cache_manager: Option, @@ -258,6 +261,7 @@ impl Default for AppState { status_msg: String::new(), editors: EditorRegistry::default(), lookups: HashMap::new(), + composite_item_options: CompositeItemOptions::default(), workspace: Workspace::new(), pane_state: PaneState::default(), file_index_cache_manager: None, diff --git a/dispel-gui/src/tests/common.rs b/dispel-gui/src/tests/common.rs index 8f01027c..324a2e76 100644 --- a/dispel-gui/src/tests/common.rs +++ b/dispel-gui/src/tests/common.rs @@ -54,6 +54,7 @@ pub(crate) fn activate_select_option( ) -> Vec { use iced_test::core::accessibility::accesskit; use iced_test::instruction::Key; + use iced_test::selector::{Candidate, Target}; let mut ui = iced_test::simulator(element); let tree = ui.accessibility_tree(); @@ -61,16 +62,40 @@ pub(crate) fn activate_select_option( .nodes .iter() .filter(|(_, node)| node.role() == accesskit::Role::ComboBox) - .map(|(id, _)| *id) + .map(|(id, node)| (*id, node.child_supports_action(accesskit::Action::Click))) .collect(); - let target = targets[nth]; - ui.accessibility_action(&accesskit::ActionRequest { - action: accesskit::Action::Focus, - target_tree: tree.tree_id, - target_node: target, - data: None, - }); - ui.tap_key(Key::Enter); + let (target, is_combo_box) = targets[nth]; + if is_combo_box { + // A ComboBox initially filters its options by the current selection. + // Open it with a click, then erase that text to expose the full list. + let mut seen = 0; + let mut text_len = 0; + let mut select = |candidate: Candidate<'_>| match candidate { + Candidate::TextInput { state, .. } if seen == nth => { + seen += 1; + text_len = state.text().chars().count(); + Some(Target::from(candidate)) + } + Candidate::TextInput { .. } => { + seen += 1; + None + } + _ => None, + }; + ui.click(&mut select).expect("combo box must be clickable"); + for _ in 0..text_len { + ui.tap_key(Key::Backspace); + } + } else { + ui.accessibility_action(&accesskit::ActionRequest { + action: accesskit::Action::Focus, + target_tree: tree.tree_id, + target_node: target, + data: None, + }); + // A pick_list opens on Enter; a ComboBox is already open once clicked. + ui.tap_key(Key::Enter); + } let named = if offset < 0 { iced::keyboard::key::Named::ArrowUp @@ -94,3 +119,38 @@ pub(crate) fn activate_select_option( ui.tap_key(Key::Enter); ui.into_messages().collect() } + +/// Focus the `nth` combo box, type a filter query, and activate the highlighted +/// option. Returns the messages produced by the interaction. +#[cfg(feature = "iced_test")] +pub(crate) fn filter_select( + element: iced::Element<'_, M>, + nth: usize, + query: &str, +) -> Vec { + use iced_test::instruction::Key; + use iced_test::selector::{Candidate, Target}; + + let mut ui = iced_test::simulator(element); + let mut seen = 0; + let mut text_len = 0; + let mut select = |candidate: Candidate<'_>| match candidate { + Candidate::TextInput { state, .. } if seen == nth => { + seen += 1; + text_len = state.text().chars().count(); + Some(Target::from(candidate)) + } + Candidate::TextInput { .. } => { + seen += 1; + None + } + _ => None, + }; + ui.click(&mut select).expect("combo box must be clickable"); + for _ in 0..text_len { + ui.tap_key(Key::Backspace); + } + ui.typewrite(query); + ui.tap_key(Key::Enter); + ui.into_messages().collect() +} diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs index d8311a73..fc11921d 100644 --- a/dispel-gui/src/tests/select_boxes.rs +++ b/dispel-gui/src/tests/select_boxes.rs @@ -5,9 +5,11 @@ //! contain and omit the displayed id. Each label must survive `set_field` / //! `get_field` and be visible in the spreadsheet inspector and the map editor. -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::fmt::{Debug, Display}; +use iced::widget::combo_box; + use dispel_core::references::enums::WireValue; use dispel_core::{ BooleanFlag, DialogOwner, DialogType, DialogueScript, DrawItem, EditItem, EditItemEffect, @@ -17,20 +19,30 @@ use dispel_core::{ NpcRoleResult, SmallRange0to3, SpellTargetType, }; +use super::common::{activate_select_option, filter_select, select_shows, select_values}; +use crate::components::composite_item::ItemOption; use crate::components::editable::{EditableRecord, FieldDescriptor, FieldKind}; use crate::editors::map_editor::MapEditorMessage; use crate::editors::map_editor::message::SelectedEntity; use crate::editors::map_editor::view::fields; -use crate::message::{EditorMessage, FileTreeMessage, Message, SystemMessage}; +use crate::message::{EditorMessage, Message, SystemMessage}; use crate::view::editor::spreadsheet::message::SpreadsheetMessage; use crate::view::editor::spreadsheet::view::inspector::build_inspector_field; -use iced_test::selector::{Candidate, Target}; -use iced_test::simulator; -use super::common::{activate_select_option, select_shows, select_values}; +static EMPTY_COMBO: std::sync::LazyLock> = + std::sync::LazyLock::new(|| combo_box::State::new(Vec::new())); -static EMPTY_FILTERS: std::sync::LazyLock> = - std::sync::LazyLock::new(HashMap::new); +fn combo_options(entries: &[(String, String)]) -> combo_box::State { + combo_box::State::new( + entries + .iter() + .map(|(key, label)| ItemOption { + key: key.clone(), + label: label.clone(), + }) + .collect(), + ) +} /// The formatting protocol of a field's get path. trait LabelFormat { @@ -123,6 +135,7 @@ fn render_both( desc: &FieldDescriptor, value: &str, lookups: &HashMap>, + combo_state: &combo_box::State, expected: &str, ) { let empty = HashMap::new(); @@ -134,7 +147,7 @@ fn render_both( None, captured_field_changed, &empty, - &EMPTY_FILTERS, + combo_state, captured_spreadsheet, ); let shown = select_values(inspector); @@ -157,7 +170,7 @@ fn render_both( 0, SelectedEntity::Npc(0), lookups, - &EMPTY_FILTERS, + combo_state, ); let shown = select_values(row); assert!( @@ -201,7 +214,7 @@ where label, "{field}: get_field disagrees with the rendered label" ); - render_both(desc, &label, &lookups, &label); + render_both(desc, &label, &lookups, &EMPTY_COMBO, &label); } // Walk the options themselves so a variant the setter cannot accept, or @@ -224,6 +237,7 @@ fn inspector_emissions( desc: &FieldDescriptor, value: &str, lookups: &HashMap>, + combo_state: &combo_box::State, nth: usize, ) -> Vec { let empty = HashMap::new(); @@ -235,7 +249,7 @@ fn inspector_emissions( None, captured_field_changed, &empty, - &EMPTY_FILTERS, + combo_state, captured_spreadsheet, ); activate_select_option(element, nth, 0) @@ -253,6 +267,7 @@ fn map_emissions( desc: &FieldDescriptor, value: &str, lookups: &HashMap>, + combo_state: &combo_box::State, ) -> Vec { let element = fields::inspector_field_row( desc.label, @@ -262,7 +277,7 @@ fn map_emissions( 0, SelectedEntity::Npc(0), lookups, - &EMPTY_FILTERS, + combo_state, ); activate_select_option(element, 0, 0) .into_iter() @@ -275,31 +290,6 @@ fn map_emissions( .collect() } -/// Type into the composite search input of a rendered inspector and return the -/// messages emitted while typing (one per keystroke). -fn type_filter(element: iced::Element<'_, Message>, query: &str) -> Vec { - let mut ui = simulator(element); - let mut search = |candidate: Candidate<'_>| match candidate { - Candidate::TextInput { state, .. } if state.text().into_owned() == "Search items..." => { - Some(Target::from(candidate)) - } - _ => None, - }; - ui.click(&mut search) - .expect("composite search input must be rendered"); - ui.typewrite(query); - ui.into_messages().collect() -} - -fn filter_capturing_spreadsheet(msg: SpreadsheetMessage) -> Message { - match msg { - SpreadsheetMessage::CompositeItemFilterChanged(_, query) => { - Message::FileTree(FileTreeMessage::Search(query)) - } - other => captured_spreadsheet(other), - } -} - fn audit_lookup(field: &'static str) { let desc = descriptor_of::(field); let FieldKind::Lookup(key) = &desc.kind else { @@ -315,12 +305,12 @@ fn audit_lookup(field: &'static str) { vec![("7".to_string(), "Invented 7".to_string())], )]); - render_both(desc, "9", &present, "Invented 9"); - render_both(desc, "9", &absent, "Unknown (9)"); + render_both(desc, "9", &present, &EMPTY_COMBO, "Invented 9"); + render_both(desc, "9", &absent, &EMPTY_COMBO, "Unknown (9)"); - for emitted in inspector_emissions(desc, "9", &present, 0) + for emitted in inspector_emissions(desc, "9", &present, &EMPTY_COMBO, 0) .into_iter() - .chain(map_emissions(desc, "9", &present)) + .chain(map_emissions(desc, "9", &present, &EMPTY_COMBO)) { let mut record = R::default(); assert!( @@ -329,7 +319,13 @@ fn audit_lookup(field: &'static str) { ); let stored = record.get_field(field); assert_eq!(stored, emitted, "{field}: emitted id did not round-trip"); - render_both(desc, &stored, &present, &format!("Invented {stored}")); + render_both( + desc, + &stored, + &present, + &EMPTY_COMBO, + &format!("Invented {stored}"), + ); } } @@ -353,13 +349,16 @@ fn audit_composite(field: &'static str) { ], )]); - render_both(desc, "1:5", &present, "Invented Sword"); - render_both(desc, "1:5", &absent, "Unknown (1:5)"); - render_both(desc, "1:99", &present, "Unknown (1:99)"); + let present_combo = combo_options(present.get(*lookup_key).expect("present items")); + let absent_combo = combo_options(absent.get(*lookup_key).expect("absent items")); + + render_both(desc, "1:5", &present, &present_combo, "Invented Sword"); + render_both(desc, "1:5", &absent, &absent_combo, "Unknown (1:5)"); + render_both(desc, "1:99", &present, &present_combo, "Unknown (1:99)"); - for emitted in inspector_emissions(desc, "1:5", &present, 0) + for emitted in inspector_emissions(desc, "1:5", &present, &present_combo, 0) .into_iter() - .chain(map_emissions(desc, "1:5", &present)) + .chain(map_emissions(desc, "1:5", &present, &present_combo)) { let mut record = R::default(); assert!( @@ -368,7 +367,7 @@ fn audit_composite(field: &'static str) { ); let stored = record.get_field(field); assert_eq!(stored, emitted, "{field}: emitted key did not round-trip"); - render_both(desc, &stored, &present, "Invented Sword"); + render_both(desc, &stored, &present, &present_combo, "Invented Sword"); } } @@ -551,45 +550,83 @@ fn test_every_lookup_and_composite_field_round_trips_through_both_views() { audit_composite::("interaction_result_item"); } -#[test] -fn test_composite_filter_narrows_spreadsheet_inspector_options() { - let desc = descriptor_of::("item"); - let FieldKind::CompositeItem { lookup_key } = &desc.kind else { - panic!("item must be a composite field"); - }; - let lookups = HashMap::from([( - lookup_key.to_string(), - vec![ - ("1:5".to_string(), "[Weapon] Invented Sword".to_string()), - ("2:7".to_string(), "[Healing] Invented Herb".to_string()), - ("255:15".to_string(), "[-]".to_string()), - ], - )]); - let contents = HashMap::new(); - - let unfiltered = build_inspector_field( +fn inspector_combo_emissions( + desc: &FieldDescriptor, + value: &str, + lookups: &HashMap>, + combo_state: &combo_box::State, + query: &str, +) -> Vec { + let empty = HashMap::new(); + let element = build_inspector_field( desc, - "1:5".into(), + value.to_string(), 0, - &lookups, + lookups, None, captured_field_changed, - &contents, - &EMPTY_FILTERS, - filter_capturing_spreadsheet, + &empty, + combo_state, + captured_spreadsheet, + ); + filter_select(element, 0, query) + .into_iter() + .filter_map(|message| match message { + Message::Editor(EditorMessage::Weapon( + crate::editors::weapon::WeaponEditorMessage::FieldChanged(_, _, value), + )) => Some(value), + _ => None, + }) + .collect() +} + +fn map_combo_emissions( + desc: &FieldDescriptor, + value: &str, + lookups: &HashMap>, + combo_state: &combo_box::State, + query: &str, +) -> Vec { + let element = fields::inspector_field_row( + desc.label, + desc.name, + &desc.kind, + value, + 0, + SelectedEntity::Npc(0), + lookups, + combo_state, ); - let query = type_filter(unfiltered, "herb") + filter_select(element, 0, query) .into_iter() - .filter_map(|m| match m { - Message::FileTree(FileTreeMessage::Search(q)) => Some(q), + .filter_map(|message| match message { + Message::Editor(EditorMessage::MapEditor(MapEditorMessage::EntityFieldChanged( + _, + _, + _, + value, + ))) => Some(value), _ => None, }) - .last() - .expect("the search input must emit its query"); - assert_eq!(query, "herb"); + .collect() +} + +#[test] +fn test_combo_box_filter_narrows_spreadsheet_inspector_options() { + let desc = descriptor_of::("item"); + let FieldKind::CompositeItem { lookup_key } = &desc.kind else { + panic!("item must be a composite field"); + }; + let entries = vec![ + ("1:5".to_string(), "[Weapon] Invented Sword".to_string()), + ("2:7".to_string(), "[Healing] Invented Herb".to_string()), + ("255:15".to_string(), "[-]".to_string()), + ]; + let lookups = HashMap::from([(lookup_key.to_string(), entries.clone())]); + let combo = combo_options(&entries); + let contents = HashMap::new(); - let filters = HashMap::from([("item".to_string(), query)]); - let filtered = build_inspector_field( + let element = build_inspector_field( desc, "1:5".into(), 0, @@ -597,85 +634,48 @@ fn test_composite_filter_narrows_spreadsheet_inspector_options() { None, captured_field_changed, &contents, - &filters, + &combo, captured_spreadsheet, ); assert!( - select_values(filtered) + select_values(element) .iter() .any(|value| value == "[Weapon] Invented Sword"), - "the current item must stay visible while its filter is active" + "the current item must stay visible before filtering" ); - let reachable: HashSet = (-3..=3) - .flat_map(|offset| { - let element = build_inspector_field( - desc, - "1:5".into(), - 0, - &lookups, - None, - captured_field_changed, - &contents, - &filters, - captured_spreadsheet, - ); - activate_select_option(element, 0, offset) - .into_iter() - .filter_map(|m| match m { - Message::Editor(EditorMessage::Weapon( - crate::editors::weapon::WeaponEditorMessage::FieldChanged(_, _, value), - )) => Some(value), - _ => None, - }) - }) - .collect(); assert_eq!( - reachable, - HashSet::from(["1:5".to_string(), "2:7".to_string()]), - "the filter must remove every non-matching option" + inspector_combo_emissions(desc, "1:5", &lookups, &combo, "herb"), + vec!["2:7"], + "typing a label fragment must leave only the matching option" + ); + assert_eq!( + inspector_combo_emissions(desc, "1:5", &lookups, &combo, "sword"), + vec!["1:5"], + "typing the current label must leave only the current option" + ); + assert_eq!( + inspector_combo_emissions(desc, "1:5", &lookups, &combo, "nomatch"), + Vec::::new(), + "a query with no matching label must offer nothing to select" ); } #[test] -fn test_composite_filter_narrows_map_editor_options() { +fn test_combo_box_filter_narrows_map_editor_options() { let desc = descriptor_of::("item"); let FieldKind::CompositeItem { lookup_key } = &desc.kind else { panic!("item must be a composite field"); }; - let lookups = HashMap::from([( - lookup_key.to_string(), - vec![ - ("1:5".to_string(), "[Weapon] Invented Sword".to_string()), - ("2:7".to_string(), "[Healing] Invented Herb".to_string()), - ("255:15".to_string(), "[-]".to_string()), - ], - )]); - - let unfiltered = fields::inspector_field_row( - desc.label, - desc.name, - &desc.kind, - "1:5", - 0, - SelectedEntity::Npc(0), - &lookups, - &EMPTY_FILTERS, - ); - let query = type_filter(unfiltered, "herb") - .into_iter() - .filter_map(|m| match m { - Message::Editor(EditorMessage::MapEditor( - MapEditorMessage::CompositeItemFilterChanged(_, _, query), - )) => Some(query), - _ => None, - }) - .last() - .expect("the search input must emit its query"); - assert_eq!(query, "herb"); + let entries = vec![ + ("1:5".to_string(), "[Weapon] Invented Sword".to_string()), + ("2:7".to_string(), "[Healing] Invented Herb".to_string()), + ("255:15".to_string(), "[-]".to_string()), + ]; + let lookups = HashMap::from([(lookup_key.to_string(), entries.clone())]); + let combo = combo_options(&entries); - let filters = HashMap::from([("item".to_string(), query)]); - let filtered = fields::inspector_field_row( + let element = fields::inspector_field_row( desc.label, desc.name, &desc.kind, @@ -683,41 +683,24 @@ fn test_composite_filter_narrows_map_editor_options() { 0, SelectedEntity::Npc(0), &lookups, - &filters, + &combo, ); assert!( - select_values(filtered) + select_values(element) .iter() .any(|value| value == "[Weapon] Invented Sword"), - "the current item must stay visible while its filter is active" + "the current item must stay visible before filtering" ); - let reachable: HashSet = (-3..=3) - .flat_map(|offset| { - let element = fields::inspector_field_row( - desc.label, - desc.name, - &desc.kind, - "1:5", - 0, - SelectedEntity::Npc(0), - &lookups, - &filters, - ); - activate_select_option(element, 0, offset) - .into_iter() - .filter_map(|m| match m { - Message::Editor(EditorMessage::MapEditor( - MapEditorMessage::EntityFieldChanged(_, _, _, value), - )) => Some(value), - _ => None, - }) - }) - .collect(); assert_eq!( - reachable, - HashSet::from(["1:5".to_string(), "2:7".to_string()]), - "the map editor filter must remove every non-matching option" + map_combo_emissions(desc, "1:5", &lookups, &combo, "herb"), + vec!["2:7"], + "the map editor combo box must filter on label text" + ); + assert_eq!( + map_combo_emissions(desc, "1:5", &lookups, &combo, "sword"), + vec!["1:5"], + "filtering to the current label must emit its exact key" ); } @@ -742,7 +725,7 @@ fn test_lookup_label_collision_emits_each_own_id() { None, captured_field_changed, &empty, - &EMPTY_FILTERS, + &EMPTY_COMBO, captured_spreadsheet, ); activate_select_option(element, 0, offset) diff --git a/dispel-gui/src/update/editor/common.rs b/dispel-gui/src/update/editor/common.rs index 81ee9f6d..b59123c1 100644 --- a/dispel-gui/src/update/editor/common.rs +++ b/dispel-gui/src/update/editor/common.rs @@ -166,9 +166,6 @@ macro_rules! handle_spreadsheet_messages_inner { $compute_caches return task; } - SM::CompositeItemFilterChanged(field, query) => { - $ss.composite_item_filters.insert(field, query); - } SM::CachesComputed(data) => { $ss.install_caches(data); $ss.is_loading = false; diff --git a/dispel-gui/src/update/mod.rs b/dispel-gui/src/update/mod.rs index 163459ac..b8831a58 100644 --- a/dispel-gui/src/update/mod.rs +++ b/dispel-gui/src/update/mod.rs @@ -4,13 +4,15 @@ use iced::Task; impl App { pub fn update(&mut self, message: crate::message::Message) -> Task { - match message { + let task = match message { crate::message::Message::Workspace(msg) => workspace::handle(msg, self), crate::message::Message::Editor(msg) => editor::handle(msg, self), crate::message::Message::FileTree(msg) => file_tree::handle(msg, self), crate::message::Message::System(msg) => system::handle(msg, self), crate::message::Message::StartPage(msg) => startpage::handle(msg, self), - } + }; + crate::components::composite_item::refresh_composite_item_options(&mut self.state); + task } } diff --git a/dispel-gui/src/view/editor/spreadsheet/message.rs b/dispel-gui/src/view/editor/spreadsheet/message.rs index 488db432..7a73384c 100644 --- a/dispel-gui/src/view/editor/spreadsheet/message.rs +++ b/dispel-gui/src/view/editor/spreadsheet/message.rs @@ -63,9 +63,6 @@ pub enum SpreadsheetMessage { /// Fired by `text_input` / `pick_list` widgets in the inspector panel. /// Routes through the macro so that `compute_all_caches` is called after. InspectorFieldChanged(usize, String, String), - /// Search text typed into a composite item picker. `(field_name, query)` - /// is stored on the spreadsheet state; no record is touched. - CompositeItemFilterChanged(String, String), // ── Async cache loading ──────────────────────────────────────────────── /// Result of an off-thread `compute_caches` job. The handler installs the diff --git a/dispel-gui/src/view/editor/spreadsheet/state.rs b/dispel-gui/src/view/editor/spreadsheet/state.rs index fdb4eddf..a858fbd6 100644 --- a/dispel-gui/src/view/editor/spreadsheet/state.rs +++ b/dispel-gui/src/view/editor/spreadsheet/state.rs @@ -127,9 +127,6 @@ pub struct SpreadsheetState { /// record, keyed by field name. Populated on `SelectRow`. Allows the /// cursor / selection to survive re-renders. pub inspector_textarea_contents: HashMap, - /// Search text of the composite item picker, keyed by field name. Kept per - /// field so switching rows does not lose an in-progress item search. - pub composite_item_filters: HashMap, /// Process-wide cache of pre-shaped paragraphs. Shared by every cell /// the table widget paints; cheap to clone (Arc). @@ -168,7 +165,6 @@ impl Default for SpreadsheetState { column_filter_options: Vec::new(), column_filter_search: String::new(), inspector_textarea_contents: HashMap::new(), - composite_item_filters: HashMap::new(), paragraph_cache: ParagraphCache::default(), } } diff --git a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs index 2bc78f5b..6d882809 100644 --- a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs +++ b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs @@ -4,11 +4,11 @@ use std::collections::HashMap; use iced::widget::{ - Column, button, column, container, pick_list, row, scrollable, text, text_input, + Column, button, column, combo_box, container, pick_list, row, scrollable, text, text_input, }; use iced::{Element, Fill, Length}; -use crate::components::composite_item::composite_item_picker; +use crate::components::composite_item::{ItemOption, composite_item_picker}; use crate::components::editable::{EditableRecord, FieldDescriptor, FieldKind}; use crate::components::generic_editor::GenericEditorState; use crate::components::utils::horizontal_space; @@ -24,7 +24,7 @@ pub fn build_inspector_panel<'a, R: EditableRecord>( editor: &'a GenericEditorState, spreadsheet: &'a SpreadsheetState, lookups: &'a HashMap>, - composite_filters: &'a HashMap, + combo_state: &'a combo_box::State, field_changed_msg: fn(usize, String, String) -> Message, spreadsheet_msg: fn(SpreadsheetMessage) -> Message, ) -> Element<'a, Message> { @@ -60,7 +60,7 @@ pub fn build_inspector_panel<'a, R: EditableRecord>( validation_error, field_changed_msg, &spreadsheet.inspector_textarea_contents, - composite_filters, + combo_state, spreadsheet_msg, )); } @@ -91,7 +91,7 @@ pub(crate) fn build_inspector_field<'a>( validation_error: Option, field_changed_msg: fn(usize, String, String) -> Message, textarea_contents: &'a HashMap, - composite_filters: &'a HashMap, + combo_state: &'a combo_box::State, spreadsheet_msg: fn(SpreadsheetMessage) -> Message, ) -> Element<'a, Message> { let label = text(descriptor.label).size(11).style(style::subtle_text); @@ -161,34 +161,15 @@ pub(crate) fn build_inspector_field<'a>( .width(Length::Fill) .into() } - FieldKind::CompositeItem { lookup_key } => { - let entries = lookups.get(*lookup_key).map(|v| v.as_slice()); + FieldKind::CompositeItem { lookup_key: _ } => { let field_name = descriptor.name.to_string(); - let filter_name = descriptor.name.to_string(); - let filter = composite_filters - .get(descriptor.name) - .map(String::as_str) - .unwrap_or(""); - composite_item_picker( - descriptor.label, - &value, - entries, - false, - filter, - move |text| { - spreadsheet_msg(SpreadsheetMessage::CompositeItemFilterChanged( - filter_name.clone(), - text, - )) - }, - move |v| { - spreadsheet_msg(SpreadsheetMessage::InspectorFieldChanged( - orig_idx, - field_name.clone(), - v, - )) - }, - ) + composite_item_picker(descriptor.label, &value, combo_state, false, move |v| { + spreadsheet_msg(SpreadsheetMessage::InspectorFieldChanged( + orig_idx, + field_name.clone(), + v, + )) + }) } _ => { let field_name = descriptor.name.to_string(); @@ -227,8 +208,8 @@ mod tests { use iced_test::selector::{Candidate, Target}; use iced_test::simulator; - static EMPTY_FILTERS: std::sync::LazyLock> = - std::sync::LazyLock::new(HashMap::new); + static EMPTY_COMBO: std::sync::LazyLock> = + std::sync::LazyLock::new(|| combo_box::State::new(Vec::new())); fn field_changed(idx: usize, name: String, value: String) -> Message { Message::Editor(crate::message::editor::EditorMessage::Weapon( @@ -285,7 +266,7 @@ mod tests { None, field_changed, &contents, - &EMPTY_FILTERS, + &EMPTY_COMBO, spreadsheet_msg, ); assert_eq!( @@ -299,6 +280,10 @@ mod tests { "invented_items".to_string(), vec![("1:0".to_string(), "Invented Sword".to_string())], )]); + let combo = combo_box::State::new(vec![ItemOption { + key: "1:0".to_string(), + label: "Invented Sword".to_string(), + }]); let element = build_inspector_field( &descriptor, "1:0".into(), @@ -307,7 +292,7 @@ mod tests { None, field_changed, &contents, - &EMPTY_FILTERS, + &combo, spreadsheet_msg, ); assert_eq!( @@ -354,7 +339,7 @@ mod tests { None, field_changed, &contents, - &EMPTY_FILTERS, + &EMPTY_COMBO, spreadsheet_msg, ); assert!( @@ -401,7 +386,7 @@ mod tests { None, field_changed, &contents, - &EMPTY_FILTERS, + &EMPTY_COMBO, spreadsheet_msg, ); assert!( @@ -435,7 +420,7 @@ mod tests { None, field_changed, &contents, - &EMPTY_FILTERS, + &EMPTY_COMBO, spreadsheet_msg, ); assert!( @@ -451,7 +436,7 @@ mod tests { None, field_changed, &contents, - &EMPTY_FILTERS, + &EMPTY_COMBO, spreadsheet_msg, ); assert!( @@ -467,7 +452,7 @@ mod tests { None, field_changed, &contents, - &EMPTY_FILTERS, + &EMPTY_COMBO, field_changed_spreadsheet_msg, ); let messages = crate::tests::common::activate_select_option(duplicate, 0, -1); @@ -503,7 +488,7 @@ mod tests { None, field_changed, &contents, - &EMPTY_FILTERS, + &EMPTY_COMBO, spreadsheet_msg, ); let mut ui = simulator(element); diff --git a/dispel-gui/src/view/editor/spreadsheet/view/mod.rs b/dispel-gui/src/view/editor/spreadsheet/view/mod.rs index 01fc6b45..679c839c 100644 --- a/dispel-gui/src/view/editor/spreadsheet/view/mod.rs +++ b/dispel-gui/src/view/editor/spreadsheet/view/mod.rs @@ -7,6 +7,7 @@ pub mod table; use super::message::SpreadsheetMessage; use super::state::{SpreadsheetPaneContent, SpreadsheetState}; +use crate::components::composite_item::ItemOption; use crate::components::editable::EditableRecord; use crate::components::filter::{self, FilterBarExtras}; use crate::components::generic_editor::GenericEditorState; @@ -14,6 +15,7 @@ use crate::components::utils::horizontal_rule; use crate::message::Message; use gui_widgets::components::modal; use iced::widget::column; +use iced::widget::combo_box; use iced::widget::pane_grid::{self, Pane}; use iced::{Element, Fill, Length}; use std::collections::HashMap; @@ -28,6 +30,7 @@ pub fn view_spreadsheet<'a, R: EditableRecord>( field_changed_msg: fn(usize, String, String) -> Message, spreadsheet_msg: fn(SpreadsheetMessage) -> Message, lookups: &'a HashMap>, + combo_state: &'a combo_box::State, pane_resized_msg: fn(pane_grid::ResizeEvent) -> Message, pane_clicked_msg: fn(Pane) -> Message, add_msg: Option, @@ -73,7 +76,7 @@ pub fn view_spreadsheet<'a, R: EditableRecord>( editor, spreadsheet, lookups, - &spreadsheet.composite_item_filters, + combo_state, field_changed_msg, spreadsheet_msg, ), From b67b08b30239be93f2a6e4fe611e1505ea780003 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:20:38 +0100 Subject: [PATCH 15/72] test(gui): verify composite combo box behaviour --- dispel-gui/src/components/composite_item.rs | 184 +++++++++++++++++- .../src/editors/map_editor/view/fields.rs | 64 ++++++ dispel-gui/src/tests/select_boxes.rs | 31 ++- .../view/editor/spreadsheet/view/inspector.rs | 71 +++++++ 4 files changed, 341 insertions(+), 9 deletions(-) diff --git a/dispel-gui/src/components/composite_item.rs b/dispel-gui/src/components/composite_item.rs index f4f9c8ed..1e36d8e0 100644 --- a/dispel-gui/src/components/composite_item.rs +++ b/dispel-gui/src/components/composite_item.rs @@ -177,6 +177,8 @@ mod tests { use super::*; use crate::editors::weapon::WeaponEditorMessage; use crate::message::EditorMessage; + use iced_test::core::accessibility::accesskit; + use iced_test::instruction::Key; use iced_test::selector::{Candidate, Target}; use iced_test::simulator; @@ -228,6 +230,36 @@ mod tests { )) } + /// Labels of the options shown by the open combo box. The current + /// selection is erased first so the widget filters by an empty query. + fn visible_options(state: &combo_box::State) -> Vec { + let mut ui = simulator(picker("1:0", state)); + let mut seen = 0; + let mut text_len = 0; + let mut select = |candidate: Candidate<'_>| match candidate { + Candidate::TextInput { state, .. } if seen == 0 => { + seen += 1; + text_len = state.text().chars().count(); + Some(Target::from(candidate)) + } + Candidate::TextInput { .. } => { + seen += 1; + None + } + _ => None, + }; + ui.click(&mut select).expect("combo box must be clickable"); + for _ in 0..text_len { + ui.tap_key(Key::Backspace); + } + ui.accessibility_tree() + .nodes + .into_iter() + .filter(|(_, node)| node.role() == accesskit::Role::MenuListOption) + .filter_map(|(_, node)| node.label().map(str::to_owned)) + .collect() + } + fn label_rendered(state: Option<&combo_box::State>, show_label: bool) -> bool { let empty = options(&[]); let state = state.unwrap_or(&empty); @@ -248,13 +280,49 @@ mod tests { } #[test] - fn test_selected_option_emits_its_composite_key() { + fn test_one_combo_box_lists_labels_from_every_item_type() { + let state = options(&[ + ("1:0", "[Weapon] Invented Sword"), + ("2:7", "[Healing] Invented Herb"), + ("3:2", "[Edit] Invented Charm"), + ("4:1", "[Event] Invented Scroll"), + ("5:3", "[Misc] Invented Stone"), + ("255:15", NO_ITEM_LABEL), + ]); + + assert_eq!( + crate::tests::common::select_values(picker("1:0", &state)), + vec!["[Weapon] Invented Sword"], + "one item field must render exactly one combo box" + ); + let labels = visible_options(&state); + for label in [ + "[Weapon] Invented Sword", + "[Healing] Invented Herb", + "[Edit] Invented Charm", + "[Event] Invented Scroll", + "[Misc] Invented Stone", + NO_ITEM_LABEL, + ] { + assert!( + labels.iter().any(|shown| shown == label), + "the shared option list must offer {label:?}, got {labels:?}" + ); + } + assert_eq!(select_option("1:0", &state, 3), vec!["4:1"]); + assert_eq!(select_option("1:0", &state, 5), vec!["255:15"]); + } + + #[test] + fn test_selected_option_emits_its_exact_composite_key() { let state = options(&[ ("1:0", "[Weapon] Invented Sword"), ("2:7", "[Healing] Invented Herb"), ("255:15", NO_ITEM_LABEL), ]); assert_eq!(select_option("1:0", &state, 1), vec!["2:7"]); + assert_eq!(select_option("1:0", &state, 2), vec!["255:15"]); + assert_eq!(select_option("2:7", &state, 0), vec!["1:0"]); } #[test] @@ -263,12 +331,67 @@ mod tests { ("1:0", "[Weapon] Invented Sword"), ("255:15", NO_ITEM_LABEL), ]); - assert_eq!(select_option("255:255", &state, -1), vec!["255:255"]); + for value in ["255:255", "255:5"] { + assert_eq!( + crate::tests::common::select_values(picker(value, &state)), + vec![NO_ITEM_LABEL], + "{value} must display the shared empty-slot label" + ); + assert_eq!( + select_option(value, &state, -1), + vec![value], + "reselecting the empty slot must keep the exact stored key" + ); + } + assert_eq!(select_option("255:15", &state, -1), vec!["255:15"]); + } + + #[test] + fn test_duplicate_display_names_remain_distinct() { + let state = options(&[ + ("1:4", "Invented Blade"), + ("2:4", "Invented Blade"), + ("255:15", NO_ITEM_LABEL), + ]); + let labels = visible_options(&state); + assert_eq!( + labels, + vec!["Invented Blade", "Invented Blade", NO_ITEM_LABEL], + "both duplicate rows must stay in the one option list" + ); + assert_eq!(select_option("2:4", &state, 0), vec!["1:4"]); + assert_eq!(select_option("2:4", &state, 1), vec!["2:4"]); + } + + #[test] + fn test_unmapped_key_shows_visible_fallback() { + let state = options(&[ + ("1:0", "[Weapon] Invented Sword"), + ("255:15", NO_ITEM_LABEL), + ]); + assert_eq!( + crate::tests::common::select_values(picker("1:999", &state)), + vec!["Unknown (1:999)"] + ); + assert_eq!( + crate::tests::common::select_values(picker("255:0", &state)), + vec![NO_ITEM_LABEL] + ); } #[test] fn test_fallback_text_input_edits_the_raw_value() { let state = options(&[]); + let no_combo = simulator(picker("255:255", &state)) + .accessibility_tree() + .nodes + .into_iter() + .any(|(_, node)| node.role() == accesskit::Role::ComboBox); + assert!( + !no_combo, + "without a loaded catalog there must be no combo box" + ); + let mut ui = simulator(picker("255:255", &state)); let mut input = |candidate: Candidate<'_>| match candidate { Candidate::TextInput { state, .. } if state.text().into_owned() == "255:255" => { @@ -299,3 +422,60 @@ mod tests { } } } + +#[cfg(test)] +mod refresh_tests { + use super::*; + use crate::state::AppState; + + #[test] + fn test_refresh_builds_one_option_list_and_adds_the_sentinel() { + let mut app = AppState::default(); + app.lookups.insert( + "items".to_string(), + vec![ + ("1:5".to_string(), "[Weapon] Invented Sword".to_string()), + ("2:7".to_string(), "[Healing] Invented Herb".to_string()), + ], + ); + + refresh_composite_item_options(&mut app); + let options = app.composite_item_options.state.options(); + assert_eq!( + options + .iter() + .map(|option| option.key.as_str()) + .collect::>(), + vec!["1:5", "2:7", NO_ITEM_KEY] + ); + assert_eq!(options.last().unwrap().label, NO_ITEM_LABEL); + let fingerprint = app.composite_item_options.fingerprint; + let pointer = options.as_ptr(); + + refresh_composite_item_options(&mut app); + assert_eq!( + app.composite_item_options.fingerprint, fingerprint, + "an unchanged lookup must not rebuild the options" + ); + assert_eq!( + app.composite_item_options.state.options().as_ptr(), + pointer, + "the same option list must be reused" + ); + + app.lookups + .get_mut("items") + .unwrap() + .push(("3:2".to_string(), "[Edit] Invented Charm".to_string())); + refresh_composite_item_options(&mut app); + assert_ne!(app.composite_item_options.fingerprint, fingerprint); + assert_eq!(app.composite_item_options.state.options().len(), 4); + } + + #[test] + fn test_refresh_without_lookups_keeps_the_fallback_empty() { + let mut app = AppState::default(); + refresh_composite_item_options(&mut app); + assert!(app.composite_item_options.state.options().is_empty()); + } +} diff --git a/dispel-gui/src/editors/map_editor/view/fields.rs b/dispel-gui/src/editors/map_editor/view/fields.rs index 3b205ac9..df7ffd81 100644 --- a/dispel-gui/src/editors/map_editor/view/fields.rs +++ b/dispel-gui/src/editors/map_editor/view/fields.rs @@ -196,6 +196,70 @@ mod tests { count } + #[test] + fn test_map_editor_composite_combo_emits_exact_key() { + let kind = FieldKind::CompositeItem { + lookup_key: "invented_items", + }; + let lookups = HashMap::from([( + "invented_items".to_string(), + vec![ + ("1:0".to_string(), "[Weapon] Invented Sword".to_string()), + ("2:7".to_string(), "[Healing] Invented Herb".to_string()), + ], + )]); + let combo = combo_box::State::new(vec![ + ItemOption { + key: "1:0".to_string(), + label: "[Weapon] Invented Sword".to_string(), + }, + ItemOption { + key: "2:7".to_string(), + label: "[Healing] Invented Herb".to_string(), + }, + ]); + + let element = inspector_field_row( + "Invented Item:", + "item_type", + &kind, + "1:0", + 0, + SelectedEntity::DrawItem(0), + &lookups, + &combo, + ); + assert!( + crate::tests::common::select_shows(element, "[Weapon] Invented Sword"), + "the map editor combo must show the selected item label" + ); + + let element = inspector_field_row( + "Invented Item:", + "item_type", + &kind, + "1:0", + 0, + SelectedEntity::DrawItem(0), + &lookups, + &combo, + ); + let emitted: Vec = crate::tests::common::activate_select_option(element, 0, 1) + .into_iter() + .filter_map(|message| match message { + Message::Editor(crate::message::editor::EditorMessage::MapEditor( + MapEditorMessage::EntityFieldChanged(_, _, _, value), + )) => Some(value), + _ => None, + }) + .collect(); + assert_eq!( + emitted, + vec!["2:7"], + "the map editor must emit the selected composite key" + ); + } + #[test] fn test_npc_facing_directions_offer_left_in_map_editor() { use crate::components::editable::EditableRecord; diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs index fc11921d..f13c83b0 100644 --- a/dispel-gui/src/tests/select_boxes.rs +++ b/dispel-gui/src/tests/select_boxes.rs @@ -239,6 +239,7 @@ fn inspector_emissions( lookups: &HashMap>, combo_state: &combo_box::State, nth: usize, + offset: isize, ) -> Vec { let empty = HashMap::new(); let element = build_inspector_field( @@ -252,7 +253,7 @@ fn inspector_emissions( combo_state, captured_spreadsheet, ); - activate_select_option(element, nth, 0) + activate_select_option(element, nth, offset) .into_iter() .filter_map(|message| match message { Message::Editor(EditorMessage::Weapon( @@ -268,6 +269,7 @@ fn map_emissions( value: &str, lookups: &HashMap>, combo_state: &combo_box::State, + offset: isize, ) -> Vec { let element = fields::inspector_field_row( desc.label, @@ -279,7 +281,7 @@ fn map_emissions( lookups, combo_state, ); - activate_select_option(element, 0, 0) + activate_select_option(element, 0, offset) .into_iter() .filter_map(|message| match message { Message::Editor(EditorMessage::MapEditor( @@ -308,9 +310,9 @@ fn audit_lookup(field: &'static str) { render_both(desc, "9", &present, &EMPTY_COMBO, "Invented 9"); render_both(desc, "9", &absent, &EMPTY_COMBO, "Unknown (9)"); - for emitted in inspector_emissions(desc, "9", &present, &EMPTY_COMBO, 0) + for emitted in inspector_emissions(desc, "9", &present, &EMPTY_COMBO, 0, 0) .into_iter() - .chain(map_emissions(desc, "9", &present, &EMPTY_COMBO)) + .chain(map_emissions(desc, "9", &present, &EMPTY_COMBO, 0)) { let mut record = R::default(); assert!( @@ -355,10 +357,20 @@ fn audit_composite(field: &'static str) { render_both(desc, "1:5", &present, &present_combo, "Invented Sword"); render_both(desc, "1:5", &absent, &absent_combo, "Unknown (1:5)"); render_both(desc, "1:99", &present, &present_combo, "Unknown (1:99)"); + render_both(desc, "255:255", &present, &present_combo, "[-]"); - for emitted in inspector_emissions(desc, "1:5", &present, &present_combo, 0) + for emitted in inspector_emissions(desc, "1:5", &present, &present_combo, 0, 0) .into_iter() - .chain(map_emissions(desc, "1:5", &present, &present_combo)) + .chain(map_emissions(desc, "1:5", &present, &present_combo, 0)) + .chain(inspector_emissions( + desc, + "255:255", + &present, + &present_combo, + 0, + -1, + )) + .chain(map_emissions(desc, "255:255", &present, &present_combo, -1)) { let mut record = R::default(); assert!( @@ -367,7 +379,12 @@ fn audit_composite(field: &'static str) { ); let stored = record.get_field(field); assert_eq!(stored, emitted, "{field}: emitted key did not round-trip"); - render_both(desc, &stored, &present, &present_combo, "Invented Sword"); + let expected = if emitted.starts_with("255:") { + "[-]" + } else { + "Invented Sword" + }; + render_both(desc, &stored, &present, &present_combo, expected); } } diff --git a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs index 6d882809..b27149ce 100644 --- a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs +++ b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs @@ -302,6 +302,77 @@ mod tests { ); } + #[test] + fn test_composite_field_combo_emits_exact_key() { + let descriptor = FieldDescriptor { + name: "item_type", + label: "Invented Item:", + kind: FieldKind::CompositeItem { + lookup_key: "invented_items", + }, + }; + let lookups = HashMap::from([( + "invented_items".to_string(), + vec![ + ("1:0".to_string(), "[Weapon] Invented Sword".to_string()), + ("2:7".to_string(), "[Healing] Invented Herb".to_string()), + ], + )]); + let combo = combo_box::State::new(vec![ + ItemOption { + key: "1:0".to_string(), + label: "[Weapon] Invented Sword".to_string(), + }, + ItemOption { + key: "2:7".to_string(), + label: "[Healing] Invented Herb".to_string(), + }, + ]); + let contents = HashMap::new(); + + let element = build_inspector_field( + &descriptor, + "1:0".into(), + 0, + &lookups, + None, + field_changed, + &contents, + &combo, + field_changed_spreadsheet_msg, + ); + assert!( + crate::tests::common::select_shows(element, "[Weapon] Invented Sword"), + "the inspector combo must show the selected item label" + ); + + let element = build_inspector_field( + &descriptor, + "1:0".into(), + 0, + &lookups, + None, + field_changed, + &contents, + &combo, + field_changed_spreadsheet_msg, + ); + let emitted: Vec = crate::tests::common::activate_select_option(element, 0, 1) + .into_iter() + .filter_map(|message| match message { + Message::Editor(crate::message::editor::EditorMessage::Weapon( + crate::editors::weapon::WeaponEditorMessage::FieldChanged(_, _, value), + )) => Some(value), + _ => None, + }) + .collect(); + assert_eq!( + emitted, + vec!["2:7"], + "choosing an item must emit its composite key, not its label" + ); + } + #[test] fn test_npc_facing_directions_offer_left_in_inspector() { use crate::components::editable::EditableRecord; From d146a1b55b16e25d8a66c23ac66d05b569a0d213 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:31:01 +0100 Subject: [PATCH 16/72] fix(gui): disambiguate duplicate item labels and cover update hook --- dispel-gui/src/components/composite_item.rs | 130 +++++++++++++++++--- dispel-gui/src/tests/common.rs | 8 +- dispel-gui/src/update/mod.rs | 41 ++++++ 3 files changed, 161 insertions(+), 18 deletions(-) diff --git a/dispel-gui/src/components/composite_item.rs b/dispel-gui/src/components/composite_item.rs index 1e36d8e0..acc510f3 100644 --- a/dispel-gui/src/components/composite_item.rs +++ b/dispel-gui/src/components/composite_item.rs @@ -1,3 +1,4 @@ +use std::collections::HashMap; use std::collections::hash_map::DefaultHasher; use std::fmt; use std::hash::Hasher; @@ -59,14 +60,34 @@ pub fn refresh_composite_item_options(state: &mut crate::state::AppState) { let options = match entries { Some(entries) => { + // Count the original labels before adding the sentinel. The + // fingerprint above also comes from these unmodified pairs. + let mut label_counts: HashMap<&str, usize> = HashMap::new(); + for (_, label) in entries { + *label_counts.entry(label.as_str()).or_default() += 1; + } + let needs_sentinel = !entries.iter().any(|(key, _)| key == NO_ITEM_KEY); + if needs_sentinel { + *label_counts.entry(NO_ITEM_LABEL).or_default() += 1; + } + let mut options: Vec = entries .iter() - .map(|(key, label)| ItemOption { - key: key.clone(), - label: label.clone(), + .map(|(key, label)| { + let display = if key != NO_ITEM_KEY + && label_counts.get(label.as_str()).copied().unwrap_or(0) > 1 + { + format!("{label} ({key})") + } else { + label.clone() + }; + ItemOption { + key: key.clone(), + label: display, + } }) .collect(); - if !options.iter().any(|option| option.key == NO_ITEM_KEY) { + if needs_sentinel { options.push(ItemOption { key: NO_ITEM_KEY.to_string(), label: NO_ITEM_LABEL.to_string(), @@ -230,8 +251,10 @@ mod tests { )) } - /// Labels of the options shown by the open combo box. The current - /// selection is erased first so the widget filters by an empty query. + /// Labels of the options shown by the open combo box. Clicking opens the + /// dropdown; the widget clears its seeded selection on focus, but the + /// simulated click can leave that text in the input. The backspaces keep + /// the query empty so the whole option list stays visible. fn visible_options(state: &combo_box::State) -> Vec { let mut ui = simulator(picker("1:0", state)); let mut seen = 0; @@ -348,19 +371,55 @@ mod tests { #[test] fn test_duplicate_display_names_remain_distinct() { - let state = options(&[ - ("1:4", "Invented Blade"), - ("2:4", "Invented Blade"), - ("255:15", NO_ITEM_LABEL), - ]); - let labels = visible_options(&state); + let mut app = crate::state::AppState::default(); + app.lookups.insert( + "items".to_string(), + vec![ + ("1:4".to_string(), "Invented Blade".to_string()), + ("2:4".to_string(), "Invented Blade".to_string()), + ("255:15".to_string(), NO_ITEM_LABEL.to_string()), + ], + ); + refresh_composite_item_options(&mut app); + let state = &app.composite_item_options.state; + + let labels = visible_options(state); assert_eq!( labels, - vec!["Invented Blade", "Invented Blade", NO_ITEM_LABEL], - "both duplicate rows must stay in the one option list" + vec![ + "Invented Blade (1:4)", + "Invented Blade (2:4)", + NO_ITEM_LABEL + ], + "both duplicate rows must stay distinct in the one option list" + ); + assert_eq!(select_option("2:4", state, 0), vec!["1:4"]); + assert_eq!(select_option("2:4", state, 1), vec!["2:4"]); + } + + #[test] + fn test_duplicate_selected_value_shows_qualified_label() { + let mut app = crate::state::AppState::default(); + app.lookups.insert( + "items".to_string(), + vec![ + ("1:4".to_string(), "Cap".to_string()), + ("2:4".to_string(), "Cap".to_string()), + ], + ); + refresh_composite_item_options(&mut app); + let state = &app.composite_item_options.state; + + assert_eq!( + crate::tests::common::select_values(picker("2:4", state)), + vec!["Cap (2:4)"], + "a field holding 2:4 must not show the same label as 1:4" + ); + assert_eq!( + select_option("2:4", state, 1), + vec!["2:4"], + "the qualified label must still emit the exact key" ); - assert_eq!(select_option("2:4", &state, 0), vec!["1:4"]); - assert_eq!(select_option("2:4", &state, 1), vec!["2:4"]); } #[test] @@ -472,6 +531,45 @@ mod refresh_tests { assert_eq!(app.composite_item_options.state.options().len(), 4); } + #[test] + fn test_refresh_fingerprints_original_entries_and_qualifies_duplicates() { + let mut app = AppState::default(); + let entries = vec![ + ("1:4".to_string(), "Cap".to_string()), + ("2:4".to_string(), "Cap".to_string()), + (NO_ITEM_KEY.to_string(), NO_ITEM_LABEL.to_string()), + ]; + app.lookups.insert("items".to_string(), entries.clone()); + + refresh_composite_item_options(&mut app); + assert_eq!( + app.composite_item_options.fingerprint, + fingerprint_options(Some(&entries)), + "the fingerprint must come from the raw key/label pairs" + ); + let labels: Vec<&str> = app + .composite_item_options + .state + .options() + .iter() + .map(|option| option.label.as_str()) + .collect(); + assert_eq!( + labels, + vec!["Cap (1:4)", "Cap (2:4)", NO_ITEM_LABEL], + "only repeated labels are qualified, and the sentinel stays as-is" + ); + + let fingerprint = app.composite_item_options.fingerprint; + app.lookups.get_mut("items").unwrap()[1].0 = "2:5".to_string(); + refresh_composite_item_options(&mut app); + assert_ne!(fingerprint, app.composite_item_options.fingerprint); + assert_eq!( + app.composite_item_options.state.options()[1].label, + "Cap (2:5)" + ); + } + #[test] fn test_refresh_without_lookups_keeps_the_fallback_empty() { let mut app = AppState::default(); diff --git a/dispel-gui/src/tests/common.rs b/dispel-gui/src/tests/common.rs index 324a2e76..6b4fd5a2 100644 --- a/dispel-gui/src/tests/common.rs +++ b/dispel-gui/src/tests/common.rs @@ -66,8 +66,9 @@ pub(crate) fn activate_select_option( .collect(); let (target, is_combo_box) = targets[nth]; if is_combo_box { - // A ComboBox initially filters its options by the current selection. - // Open it with a click, then erase that text to expose the full list. + // Click to open the dropdown. The widget clears its seeded selection + // on focus; the extra Backspaces keep the simulated input's query + // empty so arrow navigation starts from the full option list. let mut seen = 0; let mut text_len = 0; let mut select = |candidate: Candidate<'_>| match candidate { @@ -146,6 +147,9 @@ pub(crate) fn filter_select( } _ => None, }; + // Click to open the combo. The widget clears its seeded selection on + // focus; the Backspaces keep the simulated query empty before typing so + // filtering starts from every option. ui.click(&mut select).expect("combo box must be clickable"); for _ in 0..text_len { ui.tap_key(Key::Backspace); diff --git a/dispel-gui/src/update/mod.rs b/dispel-gui/src/update/mod.rs index b8831a58..6dad4796 100644 --- a/dispel-gui/src/update/mod.rs +++ b/dispel-gui/src/update/mod.rs @@ -22,3 +22,44 @@ mod file_tree; mod startpage; mod system; mod workspace; + +#[cfg(test)] +mod tests { + use crate::app::App; + use crate::components::composite_item::ItemOption; + use crate::components::composite_item::refresh_composite_item_options; + use crate::message::{Message, SystemMessage}; + use crate::workspace::Workspace; + + /// The refresh hook must run after routing, so a handler that empties the + /// item lookup also empties the shared combo box options. + #[test] + fn test_update_refreshes_options_after_workspace_clear() { + let mut app = App::test_new(Workspace::new()); + app.state.lookups.insert( + "items".to_string(), + vec![ + ("1:5".to_string(), "Invented Sword".to_string()), + ("2:7".to_string(), "Invented Herb".to_string()), + ], + ); + refresh_composite_item_options(&mut app.state); + assert_eq!( + app.state.composite_item_options.state.options().len(), + 3, + "the item catalog and the no-item sentinel must be loaded" + ); + + let _ = app.update(Message::System(SystemMessage::ClearWorkspace)); + + assert!( + app.state.lookups.is_empty(), + "ClearWorkspace must empty the lookups" + ); + let options: &[ItemOption] = app.state.composite_item_options.state.options(); + assert!( + options.is_empty(), + "App::update must rebuild the options after the handler, got {options:?}" + ); + } +} From 4799519cef0717582d5da40c3c4e4afa05f55d1b Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:10:27 +0100 Subject: [PATCH 17/72] fix(gui): clear editor state when entering a new game --- dispel-gui/src/tests/start_page.rs | 34 ++++++++++++++++++++++++++++++ dispel-gui/src/update/startpage.rs | 8 +++++++ 2 files changed, 42 insertions(+) diff --git a/dispel-gui/src/tests/start_page.rs b/dispel-gui/src/tests/start_page.rs index e3bbb77f..7ed19d10 100644 --- a/dispel-gui/src/tests/start_page.rs +++ b/dispel-gui/src/tests/start_page.rs @@ -54,3 +54,37 @@ fn test_back_to_start_no_game_path_does_not_change_input() { assert_eq!(app.start_page_input, "existing"); assert_eq!(task.units(), 0); } + +#[test] +fn test_enter_editor_mode_new_game_path_clears_editors_and_tabs() { + use dispel_core::WeaponItem; + + let previous_game = tempfile::tempdir().expect("temp dir"); + let next_game = tempfile::tempdir().expect("temp dir"); + + let mut app = App::test_new(Workspace::new()); + app.state.workspace.game_path = Some(previous_game.path().to_path_buf()); + app.state.editors.weapon_editor.catalog = Some(vec![WeaponItem { + name: "Gloomvale Sabre".into(), + ..Default::default() + }]); + app.state.workspace.open( + "Gloomvale Sabre".to_string(), + Some(previous_game.path().join("GloomvaleWeaponItem.db")), + ); + + assert!(app.state.editors.weapon_editor.catalog.is_some()); + assert_eq!(app.state.workspace.tabs.len(), 1); + + app.start_page_input = next_game.path().to_string_lossy().to_string(); + let _task = app.update(Message::StartPage(StartPageMessage::Continue)); + + assert!( + app.state.editors.weapon_editor.catalog.is_none(), + "catalog from the previous game must not survive a game switch" + ); + assert!( + app.state.workspace.tabs.is_empty(), + "tabs from the previous game must not survive a game switch" + ); +} diff --git a/dispel-gui/src/update/startpage.rs b/dispel-gui/src/update/startpage.rs index 0dbead3b..7cc89a73 100644 --- a/dispel-gui/src/update/startpage.rs +++ b/dispel-gui/src/update/startpage.rs @@ -37,6 +37,14 @@ pub fn handle(message: StartPageMessage, app: &mut App) -> Task { } pub fn enter_editor_mode(app: &mut App, path: PathBuf) -> Task { + // A different game path invalidates every loaded catalog and open tab. + // Continuing with the same path keeps the current editor session intact. + let path_changed = app.state.workspace.game_path.as_ref() != Some(&path); + if path_changed { + app.state.clear_editor_states(); + app.state.workspace.clear_all_tabs(); + } + // Update recent game paths (max 5) let recent = &mut app.state.workspace.recent_game_paths; recent.retain(|p| p != &path); From 3b8aca35860c65d47a7b8504e4ae6d3e7f30ecbd Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:12:44 +0100 Subject: [PATCH 18/72] fix(gui): stop recording when the game path changes --- dispel-gui/src/recording_tests.rs | 20 ++++++++++++++ dispel-gui/src/update/startpage.rs | 42 ++++++++++++++++-------------- dispel-gui/src/update/system.rs | 9 ++++++- 3 files changed, 51 insertions(+), 20 deletions(-) diff --git a/dispel-gui/src/recording_tests.rs b/dispel-gui/src/recording_tests.rs index 9d236d3b..cc0a309e 100644 --- a/dispel-gui/src/recording_tests.rs +++ b/dispel-gui/src/recording_tests.rs @@ -1422,3 +1422,23 @@ fn fog_data_editor_save_without_session_writes_file_only() { "edited table persisted to disk" ); } + +#[test] +fn test_switch_game_path_stops_recording() { + use crate::message::Message; + use crate::message::startpage::StartPageMessage; + + let previous_game = tempfile::tempdir().expect("temp dir"); + let next_game = tempfile::tempdir().expect("temp dir"); + + let mut app = app_with_recording(); + app.state.workspace.game_path = Some(previous_game.path().to_path_buf()); + app.start_page_input = next_game.path().to_string_lossy().to_string(); + + let _task = app.update(Message::StartPage(StartPageMessage::Continue)); + + assert!( + app.state.recording.is_none(), + "a session tied to the old game path must not survive a game switch" + ); +} diff --git a/dispel-gui/src/update/startpage.rs b/dispel-gui/src/update/startpage.rs index 7cc89a73..0eb1cbed 100644 --- a/dispel-gui/src/update/startpage.rs +++ b/dispel-gui/src/update/startpage.rs @@ -40,10 +40,18 @@ pub fn enter_editor_mode(app: &mut App, path: PathBuf) -> Task { // A different game path invalidates every loaded catalog and open tab. // Continuing with the same path keeps the current editor session intact. let path_changed = app.state.workspace.game_path.as_ref() != Some(&path); - if path_changed { + let stop_recording_task = if path_changed { app.state.clear_editor_states(); app.state.workspace.clear_all_tabs(); - } + // Stop through the mod packager so pending edits are flushed to the + // old workspace instead of being dropped with the session. + crate::editors::mod_packager::handle( + crate::editors::mod_packager::ModPackagerMessage::StopRecording, + app, + ) + } else { + Task::none() + }; // Update recent game paths (max 5) let recent = &mut app.state.workspace.recent_game_paths; @@ -83,24 +91,20 @@ pub fn enter_editor_mode(app: &mut App, path: PathBuf) -> Task { |index| Message::System(SystemMessage::IndexLoaded(Ok(index))), ); + let mut tasks = vec![stop_recording_task, search_task]; if let Some(ref cache_manager) = app.state.file_index_cache_manager { let cache_manager = cache_manager.clone(); - Task::batch([ - search_task, - Task::perform( - async move { - let svc = crate::indexation::indexation_service::IndexationService::new( - cache_manager, - ); - svc.start_indexation_with_fallback(gp_cache).await - }, - |result| match result { - Ok(cache) => Message::System(SystemMessage::CacheIndexationComplete(cache)), - Err(_) => Message::System(SystemMessage::CacheIndexationFailed), - }, - ), - ]) - } else { - search_task + tasks.push(Task::perform( + async move { + let svc = + crate::indexation::indexation_service::IndexationService::new(cache_manager); + svc.start_indexation_with_fallback(gp_cache).await + }, + |result| match result { + Ok(cache) => Message::System(SystemMessage::CacheIndexationComplete(cache)), + Err(_) => Message::System(SystemMessage::CacheIndexationFailed), + }, + )); } + Task::batch(tasks) } diff --git a/dispel-gui/src/update/system.rs b/dispel-gui/src/update/system.rs index 916d5273..be8cb37f 100644 --- a/dispel-gui/src/update/system.rs +++ b/dispel-gui/src/update/system.rs @@ -151,6 +151,13 @@ pub fn handle(message: SystemMessage, app: &mut App) -> Task Task {} } From 74ec28135b9e57df919dd8477dfe5bffd0d37da1 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:21:20 +0100 Subject: [PATCH 19/72] fix(gui): route completion messages to their tab --- dispel-gui/src/app.rs | 4 +- .../src/editors/save_file_viewer/message.rs | 4 +- .../editors/save_file_viewer/update/mod.rs | 13 +- .../src/editors/sprite_editor/message.rs | 4 +- .../src/editors/sprite_editor/update.rs | 13 +- dispel-gui/src/editors/tileset/message.rs | 6 +- dispel-gui/src/editors/tileset/update.rs | 21 ++- dispel-gui/src/tests/common.rs | 37 +++++ dispel-gui/src/tests/tabbed_editor.rs | 139 ++++++++++++++++++ 9 files changed, 219 insertions(+), 22 deletions(-) diff --git a/dispel-gui/src/app.rs b/dispel-gui/src/app.rs index 1052eb96..08d536f1 100644 --- a/dispel-gui/src/app.rs +++ b/dispel-gui/src/app.rs @@ -410,7 +410,9 @@ impl App { }, move |result| { crate::message::Message::save_file_viewer( - crate::editors::save_file_viewer::SaveFileViewerMessage::Loaded(result), + crate::editors::save_file_viewer::SaveFileViewerMessage::Loaded( + tab_id, result, + ), ) }, ) diff --git a/dispel-gui/src/editors/save_file_viewer/message.rs b/dispel-gui/src/editors/save_file_viewer/message.rs index 098f2c99..1c7386cf 100644 --- a/dispel-gui/src/editors/save_file_viewer/message.rs +++ b/dispel-gui/src/editors/save_file_viewer/message.rs @@ -13,8 +13,8 @@ use crate::editors::save_file_viewer::state::{ pub enum SaveFileViewerMessage { /// Load a save file from disk. Load(PathBuf), - /// Result of loading a save file. - Loaded(Result), + /// Result of loading a save file, tagged with the tab that issued the load. + Loaded(usize, Result), /// Switch to a different section. SelectSection(SaveFileSection), /// Select an inventory category to view. diff --git a/dispel-gui/src/editors/save_file_viewer/update/mod.rs b/dispel-gui/src/editors/save_file_viewer/update/mod.rs index 15172a15..421c6475 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/mod.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/mod.rs @@ -234,9 +234,14 @@ fn apply_column_width(state: &mut SaveFileViewerState, key: TableKey, col: usize } pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { - let tab_id = match app.state.workspace.active() { - Some(t) => t.id, - None => return Task::none(), + // A load result carries its tab id so it still reaches the originating + // viewer if another tab became active while the async read was running. + let tab_id = match &msg { + SaveFileViewerMessage::Loaded(id, _) => *id, + _ => match app.state.workspace.active() { + Some(t) => t.id, + None => return Task::none(), + }, }; let state = match app.state.editors.save_file_viewers.get_mut(&tab_id) { @@ -1012,7 +1017,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { SaveFileViewerMessage::TableFilter { key, action } => { handle_table_filter(state, key, action) } - SaveFileViewerMessage::Loaded(result) => { + SaveFileViewerMessage::Loaded(_, result) => { state.loading = false; match result { Ok(loaded) => { diff --git a/dispel-gui/src/editors/sprite_editor/message.rs b/dispel-gui/src/editors/sprite_editor/message.rs index dd6cfda7..7d068df5 100644 --- a/dispel-gui/src/editors/sprite_editor/message.rs +++ b/dispel-gui/src/editors/sprite_editor/message.rs @@ -52,8 +52,8 @@ pub enum SpriteViewerMessage { // ── Editing ────────────────────────────────────────────────────────────── /// Save the current sprite file to disk. Save, - /// Save completed (async result). - SaveComplete(Result), + /// Save completed (async result), tagged with the tab that issued the save. + SaveComplete(usize, Result), /// Undo last edit. Undo, /// Redo last undone edit. diff --git a/dispel-gui/src/editors/sprite_editor/update.rs b/dispel-gui/src/editors/sprite_editor/update.rs index 125b0e3e..b6b0aab1 100644 --- a/dispel-gui/src/editors/sprite_editor/update.rs +++ b/dispel-gui/src/editors/sprite_editor/update.rs @@ -13,7 +13,12 @@ use iced::Task; const TICK_MS: f32 = 16.0; pub fn handle(message: SpriteViewerMessage, app: &mut App) -> Task { - let tab_id = app.state.workspace.active_tab_id().as_usize(); + // Async results carry their tab id so a save that resolves after a tab + // switch still reaches the editor that issued it. + let tab_id = match &message { + SpriteViewerMessage::SaveComplete(id, _) => *id, + _ => app.state.workspace.active_tab_id().as_usize(), + }; let Some(viewer) = app.state.editors.sprite_viewers.get_mut(&tab_id) else { return Task::none(); @@ -84,14 +89,14 @@ pub fn handle(message: SpriteViewerMessage, app: &mut App) -> Task { + SpriteViewerMessage::SaveComplete(_, result) => { match result { Ok(_msg) => { viewer.mark_clean(); diff --git a/dispel-gui/src/editors/tileset/message.rs b/dispel-gui/src/editors/tileset/message.rs index a3135e37..d3428091 100644 --- a/dispel-gui/src/editors/tileset/message.rs +++ b/dispel-gui/src/editors/tileset/message.rs @@ -17,7 +17,9 @@ pub enum TilesetEditorMessage { CloseExportDialog, SetExportFormat(TileExportFormat), ChooseExportDir, - ExportDirChosen(Option), + /// Folder selection result, tagged with the tab that opened the dialog. + ExportDirChosen(usize, Option), ExportConfirm, - ExportDone(Result), + /// Export result, tagged with the tab that issued the export. + ExportDone(usize, Result), } diff --git a/dispel-gui/src/editors/tileset/update.rs b/dispel-gui/src/editors/tileset/update.rs index f882155a..3d0b6d55 100644 --- a/dispel-gui/src/editors/tileset/update.rs +++ b/dispel-gui/src/editors/tileset/update.rs @@ -6,7 +6,14 @@ use iced::Task; use std::path::PathBuf; pub fn handle(message: TilesetEditorMessage, app: &mut App) -> Task { - let tab_id = app.state.workspace.active_tab_id().as_usize(); + // Async results carry their tab id so a result that resolves after a tab + // switch still reaches the editor that issued it. + let tab_id = match &message { + TilesetEditorMessage::ExportDirChosen(id, _) | TilesetEditorMessage::ExportDone(id, _) => { + *id + } + _ => app.state.workspace.active_tab_id().as_usize(), + }; let Some(editor) = app.state.editors.tileset_editors.get_mut(&tab_id) else { return Task::none(); @@ -38,14 +45,14 @@ pub fn handle(message: TilesetEditorMessage, app: &mut App) -> Task { + TilesetEditorMessage::ExportDirChosen(_, path) => { if let Some(ref mut dlg) = editor.export_dialog { dlg.export_dir = path; dlg.status = ExportStatus::Idle; @@ -70,14 +77,14 @@ pub fn handle(message: TilesetEditorMessage, app: &mut App) -> Task { + TilesetEditorMessage::ExportDone(_, result) => { if let Some(ref mut dlg) = editor.export_dialog { dlg.status = match result { Ok(msg) => ExportStatus::Done(msg), diff --git a/dispel-gui/src/tests/common.rs b/dispel-gui/src/tests/common.rs index 6b4fd5a2..0ac40e19 100644 --- a/dispel-gui/src/tests/common.rs +++ b/dispel-gui/src/tests/common.rs @@ -21,6 +21,43 @@ pub(crate) fn app_without_recording() -> App { App::test_new(Workspace::new()) } +/// Drain the output messages of a `Task` without an iced runtime. +/// Async operations made of immediately-ready futures resolve on the first poll. +#[cfg(feature = "iced_test")] +pub(crate) fn task_outputs( + task: iced::Task, +) -> Vec { + use iced::futures::task::noop_waker; + use std::task::Poll; + + let Some(mut stream) = iced_test::runtime::task::into_stream(task) else { + return Vec::new(); + }; + let waker = noop_waker(); + let mut context = std::task::Context::from_waker(&waker); + let mut outputs = Vec::new(); + let mut idle_polls = 0; + loop { + match stream.as_mut().poll_next(&mut context) { + Poll::Ready(Some(iced_test::runtime::Action::Output(msg))) => { + outputs.push(msg); + idle_polls = 0; + } + Poll::Ready(Some(_)) => {} + Poll::Ready(None) => break, + // `Task::stream` prepends a yield; re-poll a bounded number of + // times so immediately-ready futures can finish. + Poll::Pending => { + idle_polls += 1; + if idle_polls > 16 { + break; + } + } + } + } + outputs +} + /// Selected labels of every select box in `element`, in render order. /// Selects paint their labels directly instead of exposing them as text /// candidates, so read them from the accessibility tree where each select diff --git a/dispel-gui/src/tests/tabbed_editor.rs b/dispel-gui/src/tests/tabbed_editor.rs index a598dbd7..f860eded 100644 --- a/dispel-gui/src/tests/tabbed_editor.rs +++ b/dispel-gui/src/tests/tabbed_editor.rs @@ -530,3 +530,142 @@ mod wave_ini_extension_tests { assert!(app.state.editors.wave_ini_editor.loading_state.is_loaded()); } } + +// Async completions for per-tab editors must reach the tab that issued them. +#[cfg(test)] +mod per_tab_async_routing_tests { + use crate::app::App; + use crate::editors::sprite_editor::{ + SpriteViewerMessage, SpriteViewerState, handle as sprite_handle, + }; + use crate::editors::tileset::{ + ExportDialogState, ExportStatus, TileExportFormat, TilesetEditorMessage, + TilesetEditorState, TilesetFileType, handle as tileset_handle, + }; + use crate::tests::common::task_outputs; + use crate::workspace::{EditorType, Workspace, WorkspaceTab}; + use std::path::PathBuf; + + fn two_tab_app(first: EditorType, second: EditorType) -> App { + let mut workspace = Workspace::new(); + for (id, label, editor_type) in + [(10, "MistvaleAsset", first), (20, "DuskhavenAsset", second)] + { + workspace.tabs.push(WorkspaceTab { + id, + label: label.to_string(), + path: Some(PathBuf::from(format!("invented_{label}.dat"))), + editor_type, + modified: false, + pinned: false, + }); + } + workspace.active_tab = Some(0); + App::test_new(workspace) + } + + #[test] + fn test_tileset_export_done_reaches_originating_tab() { + let mut app = two_tab_app(EditorType::TilesetEditor, EditorType::TilesetEditor); + + for (tab_id, name) in [(10, "MistvaleGround"), (20, "DuskhavenGround")] { + app.state.editors.tileset_editors.insert( + tab_id, + TilesetEditorState { + path: PathBuf::from(format!("invented_missing_{name}.gtl")), + name: name.to_string(), + file_type: TilesetFileType::Gtl, + tiles: Vec::new(), + zoom: 1.0, + error: None, + export_dialog: Some(ExportDialogState { + format: TileExportFormat::SeparateTiles, + export_dir: Some(PathBuf::from("invented_export_dir")), + status: ExportStatus::Idle, + }), + }, + ); + } + + // Start the export on tab 10, then switch to tab 20 before it completes. + let task = tileset_handle(TilesetEditorMessage::ExportConfirm, &mut app); + assert_eq!( + app.state.editors.tileset_editors[&10] + .export_dialog + .as_ref() + .unwrap() + .status, + ExportStatus::Exporting + ); + app.state.workspace.active_tab = Some(1); + + let outputs = task_outputs(task); + assert_eq!(outputs.len(), 1, "one completion message"); + let _ = tileset_handle( + match outputs.into_iter().next().unwrap() { + crate::message::Message::Editor(crate::message::EditorMessage::Tileset(msg)) => msg, + other => panic!("unexpected message: {other:?}"), + }, + &mut app, + ); + + assert!( + matches!( + app.state.editors.tileset_editors[&10] + .export_dialog + .as_ref() + .unwrap() + .status, + ExportStatus::Error(_) + ), + "tab 10 must receive its own export result" + ); + assert_eq!( + app.state.editors.tileset_editors[&20] + .export_dialog + .as_ref() + .unwrap() + .status, + ExportStatus::Idle, + "the tab that became active must be untouched" + ); + } + + #[test] + fn test_sprite_save_complete_reaches_originating_tab() { + let mut app = two_tab_app(EditorType::SpriteViewer, EditorType::SpriteViewer); + app.state + .editors + .sprite_viewers + .insert(10, SpriteViewerState::default()); + app.state + .editors + .sprite_viewers + .insert(20, SpriteViewerState::default()); + + // A save without sprite data fails immediately, so the task is ready. + let task = sprite_handle(SpriteViewerMessage::Save, &mut app); + app.state.workspace.active_tab = Some(1); + + let outputs = task_outputs(task); + assert_eq!(outputs.len(), 1, "one completion message"); + let _ = sprite_handle( + match outputs.into_iter().next().unwrap() { + crate::message::Message::Editor(crate::message::EditorMessage::SpriteViewer( + msg, + )) => msg, + other => panic!("unexpected message: {other:?}"), + }, + &mut app, + ); + + assert!( + app.state.editors.sprite_viewers[&10].error.is_some(), + "tab 10 must receive its own save result" + ); + assert!( + app.state.editors.sprite_viewers[&20].error.is_none(), + "the tab that became active must be untouched" + ); + } +} From edb7a60758578244f7d2d810b54e090afbe2e65f Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:27:30 +0100 Subject: [PATCH 20/72] fix(hexedit): apply persisted settings to every opened file --- hexedit/README.md | 3 +- hexedit/src/app.rs | 34 +++++++++++++--- hexedit/src/config.rs | 13 ++++++- hexedit/src/lib.rs | 4 +- hexedit/src/main.rs | 90 +++++++++++++++++++++++++++++++------------ 5 files changed, 111 insertions(+), 33 deletions(-) diff --git a/hexedit/README.md b/hexedit/README.md index 6d697528..c9d5c995 100644 --- a/hexedit/README.md +++ b/hexedit/README.md @@ -416,11 +416,12 @@ pub struct HexEditorConfig { pub save_hint: String, // why save is disabled pub extra_entries: Vec, // host-specific decoders pub custom_encodings: Vec, // persisted by host + pub initial_write_mode: WriteMode, // applied to newly opened documents pub on_write_mode_changed: Option, } ``` -Build the config with `HexEditorConfig::new()` and its chainable setters: `pane_gap`, `on_save`, `save_label`, `can_save`, `save_hint`, `extra_entries`, `custom_encodings` and `on_write_mode_changed`. Both embedders use this builder. The standalone binary also uses the shared `standalone_config(...)` helper to keep its defaults aligned with the GUI. +Build the config with `HexEditorConfig::new()` and its chainable setters: `pane_gap`, `on_save`, `save_label`, `can_save`, `save_hint`, `extra_entries`, `custom_encodings`, `initial_write_mode` and `on_write_mode_changed`. Both embedders use this builder. The standalone binary also uses the shared `standalone_config(...)` helper to keep its defaults aligned with the GUI. Helper methods: `save_label()`, `has_save()` and `can_save_now(state)`. The last one checks `can_save && on_save.is_some() && dirty_count > 0`. diff --git a/hexedit/src/app.rs b/hexedit/src/app.rs index 16927145..75fa2504 100644 --- a/hexedit/src/app.rs +++ b/hexedit/src/app.rs @@ -7,13 +7,15 @@ //! [`HexEditorState`], [`crate::update`] or [`crate::view`] API consumed by //! `dispel-gui`. -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use gui_widgets::components::context_menu::{Entry, platform}; use gui_widgets::components::tab_bar::{Tab, TabBar, TabBarEvent}; use iced::{Element, Task}; -use crate::{HexEditorConfig, HexEditorMessage, HexEditorState, update, view}; +use crate::{ + EncodingEntry, HexEditorConfig, HexEditorMessage, HexEditorState, WriteMode, update, view, +}; /// One open document: an editor state plus its tab-level metadata. pub struct HexEditorDocument { @@ -43,6 +45,25 @@ impl Default for HexEditorApp { } } +/// Build an opened document with the host's persisted settings applied. +/// +/// Both the standalone binary's CLI path and its file dialog use this helper, +/// so a document never silently falls back to the built-in write mode or an +/// empty custom-encoding list. +pub fn document_with_settings( + path: &Path, + write_mode: WriteMode, + custom_encodings: &[EncodingEntry], +) -> HexEditorDocument { + let mut state = HexEditorState::load_from_path(path); + state.write_mode = write_mode; + state.custom_encodings = custom_encodings.to_vec(); + HexEditorDocument { + state, + pinned: false, + } +} + /// Messages produced by the container layer. #[derive(Debug, Clone)] pub enum AppMessage { @@ -77,10 +98,11 @@ pub fn app_update( match message { AppMessage::OpenFiles(paths) => { for p in paths { - app.documents.push(HexEditorDocument { - state: HexEditorState::load_from_path(&p), - pinned: false, - }); + app.documents.push(document_with_settings( + &p, + config.initial_write_mode, + &config.custom_encodings, + )); } if !app.documents.is_empty() { app.active_tab = Some(app.documents.len() - 1); diff --git a/hexedit/src/config.rs b/hexedit/src/config.rs index 65b249cf..55dbcb24 100644 --- a/hexedit/src/config.rs +++ b/hexedit/src/config.rs @@ -46,8 +46,11 @@ pub struct HexEditorConfig { pub save_hint: String, /// Additional inspector entries from host-specific decoders. pub extra_entries: Vec, - /// User‑defined custom text encodings (persisted by the host). + /// User‑defined custom text encodings (persisted by the host). Applied to + /// documents opened through [`crate::app_update`]. pub custom_encodings: Vec, + /// Write mode applied to documents opened through [`crate::app_update`]. + pub initial_write_mode: WriteMode, /// Optional callback fired when the write mode or custom encodings change. /// The host can use this to persist a complete settings snapshot. pub on_write_mode_changed: Option, @@ -63,6 +66,7 @@ impl Default for HexEditorConfig { save_hint: String::new(), extra_entries: Vec::new(), custom_encodings: Vec::new(), + initial_write_mode: WriteMode::Hex, on_write_mode_changed: None, } } @@ -117,6 +121,13 @@ impl HexEditorConfig { self } + /// Write mode applied to every document opened after this configuration is + /// installed. The host should pass its persisted value here. + pub fn initial_write_mode(mut self, mode: WriteMode) -> Self { + self.initial_write_mode = mode; + self + } + pub fn on_write_mode_changed(mut self, callback: WriteModeCallback) -> Self { self.on_write_mode_changed = Some(callback); self diff --git a/hexedit/src/lib.rs b/hexedit/src/lib.rs index 9a2d0e1e..397a6bf3 100644 --- a/hexedit/src/lib.rs +++ b/hexedit/src/lib.rs @@ -32,7 +32,9 @@ mod state; // Types live under the canonical `domain::*` / `ui::*` module paths; these // flat re-exports give embedders a shorter path to the same items. -pub use app::{AppMessage, HexEditorApp, HexEditorDocument, app_update, app_view}; +pub use app::{ + AppMessage, HexEditorApp, HexEditorDocument, app_update, app_view, document_with_settings, +}; pub use config::{HexEditorConfig, SavePort, WriteModeCallback, standalone_config}; pub use message::HexEditorMessage; pub use state::{ diff --git a/hexedit/src/main.rs b/hexedit/src/main.rs index 3f727f22..b9d8de13 100644 --- a/hexedit/src/main.rs +++ b/hexedit/src/main.rs @@ -1,4 +1,4 @@ -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; use iced::widget::{button, column, container, row, text}; @@ -6,8 +6,8 @@ use iced::{Element, Fill, Font, Task, Theme}; use hexedit::ui::theme::ThemeVariant; use hexedit::{ - AppMessage, EncodingEntry, HexEditorApp, HexEditorConfig, HexEditorDocument, HexEditorMessage, - HexEditorState, SaveOutcome, SaveRequest, WriteMode, app_update, app_view, standalone_config, + AppMessage, EncodingEntry, HexEditorApp, HexEditorConfig, HexEditorMessage, SaveOutcome, + SaveRequest, WriteMode, app_update, app_view, document_with_settings, standalone_config, }; /// Settings persisted to `~/.config/hexedit/settings.json`. @@ -37,8 +37,11 @@ fn settings_path() -> PathBuf { } fn load_settings() -> PersistedSettings { - let path = settings_path(); - match std::fs::read_to_string(&path) { + load_settings_from(&settings_path()) +} + +fn load_settings_from(path: &Path) -> PersistedSettings { + match std::fs::read_to_string(path) { Ok(json) => match serde_json::from_str(&json) { Ok(settings) => settings, Err(e) => { @@ -109,18 +112,13 @@ impl App { // the app stays empty and the welcome screen is shown. if !paths.is_empty() { for p in &paths { - app.documents.push(HexEditorDocument { - state: HexEditorState::load_from_path(p), - pinned: false, - }); + app.documents.push(document_with_settings( + p, + persisted.write_mode, + &persisted.custom_encodings, + )); } app.active_tab = Some(0); - - // Apply persisted settings to every document. - for doc in &mut app.documents { - doc.state.write_mode = persisted.write_mode; - doc.state.custom_encodings = persisted.custom_encodings.clone(); - } } ( @@ -137,15 +135,13 @@ impl App { /// the returned `SaveOutcome` onto its internal `SavedIntoRecording` /// message, clears the dirty flag and sets `state.status_msg`. fn editor_config(&self) -> HexEditorConfig { - let Some(active) = self.app.active_tab else { - return HexEditorConfig::default(); - }; - let Some(doc) = self.app.documents.get(active) else { - return HexEditorConfig::default(); - }; - - let has_dirty = doc.state.provider.dirty_count() > 0; + let has_dirty = self + .app + .active_tab + .and_then(|idx| self.app.documents.get(idx)) + .is_some_and(|doc| doc.state.provider.dirty_count() > 0); let settings_path = settings_path(); + let persisted = load_settings_from(&settings_path); let save_port: hexedit::SavePort = Arc::new(|request: SaveRequest| { let SaveRequest { path, bytes } = request; @@ -179,11 +175,12 @@ impl App { standalone_config( has_dirty, - doc.state.custom_encodings.clone(), + persisted.custom_encodings, Vec::new(), save_port, Some(on_write_mode_changed), ) + .initial_write_mode(persisted.write_mode) } fn update(&mut self, msg: Msg) -> Task { @@ -291,6 +288,7 @@ impl App { mod tests { use super::*; use hexedit::ui::theme::{DARK_THEME, LIGHT_THEME}; + use hexedit::{HexEditorDocument, HexEditorState}; #[test] fn test_seed_for_variant_uses_that_palette() { @@ -318,4 +316,48 @@ mod tests { app.app.documents[0].state.theme_variant = ThemeVariant::Light; assert_eq!(active_variant(&app), ThemeVariant::Light); } + + #[test] + fn test_files_picked_applies_persisted_settings() { + let settings_file = settings_path(); + let previous = std::fs::read(&settings_file).ok(); + + let invented = PersistedSettings { + write_mode: WriteMode::Windows1250, + custom_encodings: vec![EncodingEntry { + label: "Mistvale Custom".to_string(), + encoding_name: "windows-1250".to_string(), + }], + }; + std::fs::write(&settings_file, serde_json::to_string(&invented).unwrap()).unwrap(); + + let dir = + std::env::temp_dir().join(format!("hexedit_dialog_settings_{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let file = dir.join("GloomvalePadding.bin"); + std::fs::write(&file, vec![0u8; 8]).unwrap(); + + let mut app = App { + app: HexEditorApp::new(), + status: String::new(), + }; + let _task = app.update(Msg::FilesPicked(Some(vec![file.clone()]))); + + let actual = { + let state = &app.app.documents[0].state; + (state.write_mode, state.custom_encodings.clone()) + }; + + std::fs::remove_file(&file).unwrap(); + let _ = std::fs::remove_dir(&dir); + match previous { + Some(bytes) => std::fs::write(&settings_file, bytes).unwrap(), + None => { + let _ = std::fs::remove_file(&settings_file); + } + } + + assert_eq!(actual.0, WriteMode::Windows1250); + assert_eq!(actual.1, invented.custom_encodings); + } } From 5849fa8bfd36633a920f00b5f906ae9b7233fd05 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:02:47 +0100 Subject: [PATCH 21/72] fix(hexedit): remove unsupported UTF-16 write modes --- hexedit/src/domain/write_mode.rs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/hexedit/src/domain/write_mode.rs b/hexedit/src/domain/write_mode.rs index 409d34f6..75a60b2a 100644 --- a/hexedit/src/domain/write_mode.rs +++ b/hexedit/src/domain/write_mode.rs @@ -193,10 +193,9 @@ pub fn is_text_mode(mode: WriteMode) -> bool { // add any of these as a custom encoding entry through the settings modal. /// A list of `(label, encoding_rs_name)` pairs for all available encodings the -/// user may add as a custom entry. +/// user may add as a custom entry. UTF-16 is not listed: `encoding_rs` has no +/// encoder for it and would silently emit UTF-8 bytes instead. pub const COMMON_ENCODINGS: &[(&str, &str)] = &[ - ("UTF-16LE", "UTF-16LE"), - ("UTF-16BE", "UTF-16BE"), ("Windows-1250", "windows-1250"), ("Windows-1251", "windows-1251"), ("Windows-1252", "windows-1252"), @@ -372,4 +371,25 @@ mod tests { assert_eq!(*label, COMMON_ENCODINGS[i].0); } } + + #[test] + fn test_common_encodings_only_offer_real_encoders() { + let labels = common_encoding_labels(); + assert!( + !labels + .iter() + .any(|label| label.to_ascii_uppercase().contains("UTF-16")), + "encoding_rs has no UTF-16 encoder; such labels must not be offered" + ); + + for (label, name) in COMMON_ENCODINGS { + let enc = Encoding::for_label(name.as_bytes()) + .unwrap_or_else(|| panic!("{label} names unknown encoding {name}")); + assert_eq!( + enc.output_encoding().name(), + enc.name(), + "{label} silently falls back to UTF-8 when encoding" + ); + } + } } From e4892f21aa258a0a55e5d41ce6872fe3bc0e16c3 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:16:17 +0100 Subject: [PATCH 22/72] fix(gui): target the right frame in sprite context actions --- .../src/editors/sprite_editor/message.rs | 13 +- dispel-gui/src/editors/sprite_editor/mod.rs | 2 +- .../src/editors/sprite_editor/update.rs | 12 +- dispel-gui/src/editors/sprite_editor/view.rs | 22 +++- dispel-gui/src/tests/sprite_viewer.rs | 114 ++++++++++++++++++ 5 files changed, 144 insertions(+), 19 deletions(-) diff --git a/dispel-gui/src/editors/sprite_editor/message.rs b/dispel-gui/src/editors/sprite_editor/message.rs index 7d068df5..4d594f48 100644 --- a/dispel-gui/src/editors/sprite_editor/message.rs +++ b/dispel-gui/src/editors/sprite_editor/message.rs @@ -58,12 +58,13 @@ pub enum SpriteViewerMessage { Undo, /// Redo last undone edit. Redo, - /// Insert a blank frame at the current position. - InsertFrame, - /// Duplicate the selected frame after it. - DuplicateFrame, - /// Delete the selected frame. - DeleteFrame, + /// Insert a blank frame after `frame_idx`. The index is carried so a + /// thumbnail context menu can act on the frame it was opened for. + InsertFrame(usize), + /// Duplicate `frame_idx` and insert the copy after it. + DuplicateFrame(usize), + /// Delete `frame_idx`. + DeleteFrame(usize), /// Move the selected frame one position left. MoveFrameLeft, /// Move the selected frame one position right. diff --git a/dispel-gui/src/editors/sprite_editor/mod.rs b/dispel-gui/src/editors/sprite_editor/mod.rs index 539588b0..c796b2d7 100644 --- a/dispel-gui/src/editors/sprite_editor/mod.rs +++ b/dispel-gui/src/editors/sprite_editor/mod.rs @@ -11,4 +11,4 @@ pub use state::*; pub use update::handle; pub use view::view; #[cfg(test)] -pub(crate) use view::view_preview; +pub(crate) use view::{frame_strip_for_test, view_preview}; diff --git a/dispel-gui/src/editors/sprite_editor/update.rs b/dispel-gui/src/editors/sprite_editor/update.rs index b6b0aab1..22ec17f8 100644 --- a/dispel-gui/src/editors/sprite_editor/update.rs +++ b/dispel-gui/src/editors/sprite_editor/update.rs @@ -152,10 +152,10 @@ pub fn handle(message: SpriteViewerMessage, app: &mut App) -> Task { + SpriteViewerMessage::InsertFrame(frame_idx) => { viewer.push_undo(); let seq_idx = viewer.selected_sequence; - let frame_idx = viewer.selected_frame; + viewer.selected_frame = frame_idx; let new_selected = frame_idx + 1; let pixel_format = viewer .sprite_file @@ -185,10 +185,10 @@ pub fn handle(message: SpriteViewerMessage, app: &mut App) -> Task { + SpriteViewerMessage::DuplicateFrame(frame_idx) => { viewer.push_undo(); let seq_idx = viewer.selected_sequence; - let frame_idx = viewer.selected_frame; + viewer.selected_frame = frame_idx; let new_selected = frame_idx + 1; if let Some(ref mut sf) = viewer.sprite_file && let Some(seq) = sf.sequences.get_mut(seq_idx) @@ -204,9 +204,9 @@ pub fn handle(message: SpriteViewerMessage, app: &mut App) -> Task { + SpriteViewerMessage::DeleteFrame(frame_idx) => { let seq_idx = viewer.selected_sequence; - let frame_idx = viewer.selected_frame; + viewer.selected_frame = frame_idx; // Check frame count without mutable borrow let can_delete = viewer.sprite_file.as_ref().is_some_and(|sf| { sf.sequences diff --git a/dispel-gui/src/editors/sprite_editor/view.rs b/dispel-gui/src/editors/sprite_editor/view.rs index 96797e4d..c75ad188 100644 --- a/dispel-gui/src/editors/sprite_editor/view.rs +++ b/dispel-gui/src/editors/sprite_editor/view.rs @@ -327,6 +327,11 @@ fn view_zoom_controls(viewer: &SpriteViewerState) -> Element<'_, Message> { // ── Frame thumbnail strip ───────────────────────────────────────────────────── +#[cfg(test)] +pub(crate) fn frame_strip_for_test(viewer: &SpriteViewerState) -> Element<'_, Message> { + view_frame_strip(viewer) +} + fn view_frame_strip(viewer: &SpriteViewerState) -> Element<'_, Message> { if viewer.frames.is_empty() { return Space::new().into(); @@ -361,11 +366,14 @@ fn view_frame_strip(viewer: &SpriteViewerState) -> Element<'_, Message> { // Right-click context menu on each thumbnail let context_entries = vec![ - Entry::item("Insert Frame", sv(SpriteViewerMessage::InsertFrame)), - Entry::item("Duplicate Frame", sv(SpriteViewerMessage::DuplicateFrame)), + Entry::item("Insert Frame", sv(SpriteViewerMessage::InsertFrame(i))), + Entry::item( + "Duplicate Frame", + sv(SpriteViewerMessage::DuplicateFrame(i)), + ), Entry::separator(), if max_frames > 1 { - Entry::item("Delete Frame", sv(SpriteViewerMessage::DeleteFrame)) + Entry::item("Delete Frame", sv(SpriteViewerMessage::DeleteFrame(i))) } else { Entry::disabled("Delete Frame") }, @@ -402,7 +410,7 @@ fn view_edit_toolbar(viewer: &SpriteViewerState) -> Element<'_, Message> { let insert_btn = if has_frames { button(text("+ Insert").size(11)) - .on_press(sv(SpriteViewerMessage::InsertFrame)) + .on_press(sv(SpriteViewerMessage::InsertFrame(viewer.selected_frame))) .padding([3, 8]) .style(style::chip) } else { @@ -413,7 +421,9 @@ fn view_edit_toolbar(viewer: &SpriteViewerState) -> Element<'_, Message> { let dup_btn = if has_frames { button(text("⧉ Dup").size(11)) - .on_press(sv(SpriteViewerMessage::DuplicateFrame)) + .on_press(sv(SpriteViewerMessage::DuplicateFrame( + viewer.selected_frame, + ))) .padding([3, 8]) .style(style::chip) } else { @@ -430,7 +440,7 @@ fn view_edit_toolbar(viewer: &SpriteViewerState) -> Element<'_, Message> { ] .spacing(2), ) - .on_press(sv(SpriteViewerMessage::DeleteFrame)) + .on_press(sv(SpriteViewerMessage::DeleteFrame(viewer.selected_frame))) .padding([3, 8]) .style(style::chip) } else { diff --git a/dispel-gui/src/tests/sprite_viewer.rs b/dispel-gui/src/tests/sprite_viewer.rs index 46a6bc33..4629d5c6 100644 --- a/dispel-gui/src/tests/sprite_viewer.rs +++ b/dispel-gui/src/tests/sprite_viewer.rs @@ -542,4 +542,118 @@ mod bmp_viewer_tests { assert_eq!(app.state.editors.bmp_viewers[&2].zoom, 1.0); assert!(app.state.editors.bmp_viewers[&2].error.is_some()); } + + #[cfg(feature = "iced_test")] + #[test] + fn test_duplicate_frame_context_action_targets_clicked_frame() { + use crate::editors::sprite_editor::SpriteViewerState; + use crate::editors::sprite_editor::frame_strip_for_test; + use crate::message::{EditorMessage, Message}; + use dispel_core::sprite::{SpriteFile, SpriteFrameData, SpritePixelFormat, SpriteSequence}; + use iced::mouse; + use iced_test::selector::Candidate; + use std::sync::Mutex; + + static ENV_LOCK: Mutex<()> = Mutex::new(()); + let _guard = ENV_LOCK.lock().unwrap(); + unsafe { std::env::set_var("DISPEL_FORCE_CUSTOM_CONTEXT_MENU", "1") }; + + let mut app = App::test_new(Workspace::new()); + app.state.workspace.tabs.push(WorkspaceTab { + id: 0, + label: "MistvaleFrames.spr".into(), + path: None, + editor_type: EditorType::SpriteViewer, + modified: false, + pinned: false, + }); + app.state.workspace.active_tab = Some(0); + app.state + .editors + .sprite_viewers + .insert(0, SpriteViewerState::default()); + let frames = (0..10) + .map(|i| SpriteFrameData { + unknown: [0u8; 24], + origin_x: i * 7, + origin_y: 0, + width: 1, + height: 1, + pixel_format: SpritePixelFormat::Rgb565, + raw_pixels: vec![0, 0], + }) + .collect(); + { + let viewer = app.state.editors.sprite_viewers.get_mut(&0).unwrap(); + viewer.sprite_file = Some(SpriteFile { + sequences: vec![SpriteSequence { + has_stamp: false, + frames, + }], + }); + viewer.selected_frame = 3; + viewer.rebuild_preview_frames(); + viewer.selected_frame = 3; + } + + let duplicate_msg = { + let viewer = &app.state.editors.sprite_viewers[&0]; + let mut ui = iced_test::simulator(frame_strip_for_test(viewer)); + let mut nth = 0usize; + let bounds = ui + .find(move |candidate: Candidate<'_>| { + if matches!(candidate, Candidate::Focusable { .. }) { + if nth == 8 { + return Some(candidate.bounds()); + } + nth += 1; + } + None + }) + .expect("the eighth thumbnail is focusable"); + ui.point_at(bounds.center()); + ui.simulate([iced::Event::Mouse(mouse::Event::ButtonPressed( + mouse::Button::Right, + ))]); + let entry = ui + .find("Duplicate Frame") + .expect("Duplicate Frame menu entry"); + let entry_center = entry.bounds().center(); + ui.point_at(entry_center); + // The menu publishes its action on a left press only after a hover + // event has marked the entry as the hovered one. + ui.simulate([ + iced::Event::Mouse(mouse::Event::CursorMoved { + position: entry_center, + }), + iced::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)), + iced::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)), + ]); + ui.into_messages() + .find_map(|message| match message { + Message::Editor(EditorMessage::SpriteViewer(msg)) + if format!("{msg:?}").contains("DuplicateFrame") => + { + Some(msg) + } + _ => None, + }) + .expect("Duplicate Frame action message") + }; + + let _ = crate::editors::sprite_editor::handle(duplicate_msg, &mut app); + unsafe { std::env::remove_var("DISPEL_FORCE_CUSTOM_CONTEXT_MENU") }; + + let viewer = &app.state.editors.sprite_viewers[&0]; + let frames = &viewer.sprite_file.as_ref().unwrap().sequences[0].frames; + assert_eq!(frames.len(), 11); + assert_eq!( + frames[4].origin_x, 28, + "frame 4 must be untouched — the duplicate must not go after frame 3" + ); + assert_eq!( + frames[9].origin_x, 56, + "the duplicate of frame 8 must be inserted at index 9" + ); + } } From 6728c1df28c8cb07b4f1a27746adf80dee0f86ab Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:18:37 +0100 Subject: [PATCH 23/72] fix(gui): deduplicate tabs by path and editor type --- dispel-gui/src/tests/workspace_unit.rs | 19 +++++++++++++++++++ dispel-gui/src/workspace.rs | 16 +++++++++++----- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/dispel-gui/src/tests/workspace_unit.rs b/dispel-gui/src/tests/workspace_unit.rs index 22629ad9..3c95c96e 100644 --- a/dispel-gui/src/tests/workspace_unit.rs +++ b/dispel-gui/src/tests/workspace_unit.rs @@ -134,6 +134,25 @@ fn test_workspace_open_reactivates_existing() { assert_eq!(workspace.active_tab, Some(0)); } +#[test] +fn test_workspace_open_distinguishes_hex_tab_by_editor_type() { + let mut workspace = Workspace::new(); + let path = PathBuf::from("/test/MistvaleSprite.spr"); + workspace.open_with_editor_type( + "MistvaleSprite.spr (hex)".to_string(), + Some(path.clone()), + EditorType::HexEditor, + ); + + let idx = workspace.open("MistvaleSprite.spr".to_string(), Some(path)); + + assert_eq!(idx, 1); + assert_eq!(workspace.tabs.len(), 2, "normal and hex tabs are distinct"); + assert_eq!(workspace.tabs[0].editor_type, EditorType::HexEditor); + assert_eq!(workspace.tabs[1].editor_type, EditorType::SpriteViewer); + assert_eq!(workspace.active_tab, Some(1)); +} + #[test] fn test_workspace_close() { let mut workspace = Workspace::new(); diff --git a/dispel-gui/src/workspace.rs b/dispel-gui/src/workspace.rs index c9f6fdfc..62aab798 100644 --- a/dispel-gui/src/workspace.rs +++ b/dispel-gui/src/workspace.rs @@ -242,17 +242,23 @@ impl Workspace { } pub fn open(&mut self, label: String, path: Option) -> usize { - if let Some(idx) = self.tabs.iter().position(|t| t.path == path) { + let editor_type = path + .as_ref() + .map(|p| EditorType::from_path(p.as_path())) + .unwrap_or(EditorType::Unknown); + // Dedup on (path, editor type): a file already open as hex must not + // block opening it in its normal editor. + if let Some(idx) = self + .tabs + .iter() + .position(|t| t.path == path && t.editor_type == editor_type) + { self.active_tab = Some(idx); return idx; } let id = self.next_id; self.next_id += 1; let idx = self.tabs.len(); - let editor_type = path - .as_ref() - .map(|p| EditorType::from_path(p.as_path())) - .unwrap_or(EditorType::Unknown); self.tabs.push(WorkspaceTab { id, label, From ceabe68c6a3dabffa2e64d681205bcb58751b57c Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:20:45 +0100 Subject: [PATCH 24/72] fix(gui): keep active tab correct after closing another tab --- dispel-gui/src/components/tab_bar/update.rs | 41 +++++++++++++++++---- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/dispel-gui/src/components/tab_bar/update.rs b/dispel-gui/src/components/tab_bar/update.rs index c0bd692a..71d9b4c3 100644 --- a/dispel-gui/src/components/tab_bar/update.rs +++ b/dispel-gui/src/components/tab_bar/update.rs @@ -17,14 +17,9 @@ pub fn handle(message: TabBarMessage, app: &mut App) -> Task tab_index { let tab_id = app.state.workspace.tabs[tab_index].id; app.state.editors.remove_tab(tab_id); - app.state.workspace.tabs.remove(tab_index); - if let Some(active) = app.state.workspace.active_tab { - if app.state.workspace.tabs.is_empty() { - app.state.workspace.active_tab = None; - } else if active >= app.state.workspace.tabs.len() { - app.state.workspace.active_tab = Some(app.state.workspace.tabs.len() - 1); - } - } + // Workspace::close also shifts the active index down when a + // tab before it is closed. + app.state.workspace.close(tab_index); } Task::none() } @@ -245,6 +240,36 @@ mod tests { assert_eq!(app.state.workspace.active_tab, Some(1)); } + #[test] + fn test_close_tab_before_active_keeps_active_tab() { + let mut workspace = Workspace::new(); + for (i, name) in ["MistvaleMap", "DuskhavenMap", "ElderglenMap"] + .iter() + .enumerate() + { + workspace.tabs.push(WorkspaceTab { + id: i, + label: (*name).to_string(), + path: Some(std::path::PathBuf::from(format!("{name}.spr"))), + editor_type: EditorType::SpriteViewer, + modified: false, + pinned: false, + }); + } + workspace.active_tab = Some(1); + let mut app = crate::app::App::test_new(workspace); + + let _ = handle(TabBarMessage::CloseTab(0), &mut app); + + assert_eq!(app.state.workspace.tabs.len(), 2); + assert_eq!(app.state.workspace.active_tab, Some(0)); + assert_eq!( + app.state.workspace.active().unwrap().path.as_deref(), + Some(std::path::Path::new("DuskhavenMap.spr")), + "the tab that was active must stay active after an earlier one closed" + ); + } + // ═══════════════════════════════════════════════════════════════════════════ // TogglePin Tests // ═══════════════════════════════════════════════════════════════════════════ From 651719a3a0a5a89a3ffdf8641d2dad1c12fd481e Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:28:32 +0100 Subject: [PATCH 25/72] fix(gui): mark structural edits as unsaved --- .../src/components/define_tab_editor.rs | 12 ++++-- .../src/editors/party_level_db/update.rs | 2 + dispel-gui/src/editors/store/update.rs | 5 +++ dispel-gui/src/tests/editor_field_edit.rs | 42 +++++++++++++++++++ dispel-gui/src/tests/tabbed_editor.rs | 31 ++++++++++++++ 5 files changed, 88 insertions(+), 4 deletions(-) diff --git a/dispel-gui/src/components/define_tab_editor.rs b/dispel-gui/src/components/define_tab_editor.rs index 6ebe6242..7179dbe8 100644 --- a/dispel-gui/src/components/define_tab_editor.rs +++ b/dispel-gui/src/components/define_tab_editor.rs @@ -209,14 +209,18 @@ macro_rules! define_tab_editor { ) } [<$Name EditorMessage>]::AddEntry => { - $crate::update::editor::tab::add_entry( + let task = $crate::update::editor::tab::add_entry( &mut app.state.editors.$field, tab_id, - ) + ); + app.state.workspace.mark_modified(); + task } [<$Name EditorMessage>]::RemoveEntry(index) => { - $crate::update::editor::tab::remove_entry( + let task = $crate::update::editor::tab::remove_entry( &mut app.state.editors.$field, tab_id, index, - ) + ); + app.state.workspace.mark_modified(); + task } [<$Name EditorMessage>]::Saved(saved_tab_id, result) => { if result.is_ok() { diff --git a/dispel-gui/src/editors/party_level_db/update.rs b/dispel-gui/src/editors/party_level_db/update.rs index e9b7dbf2..a6391af5 100644 --- a/dispel-gui/src/editors/party_level_db/update.rs +++ b/dispel-gui/src/editors/party_level_db/update.rs @@ -145,6 +145,7 @@ pub fn handle(message: PartyLevelDbEditorMessage, app: &mut App) -> Task Task { + app.state.workspace.clear_modified(); app.state.editors.party_level_db_editor.status_msg = "Party levels saved successfully.".into(); app.state.editors.party_level_db_level_editor.status_msg = diff --git a/dispel-gui/src/editors/store/update.rs b/dispel-gui/src/editors/store/update.rs index de3a6cac..943564ae 100644 --- a/dispel-gui/src/editors/store/update.rs +++ b/dispel-gui/src/editors/store/update.rs @@ -164,6 +164,7 @@ pub fn handle(message: StoreEditorMessage, app: &mut App) -> Task { crate::editors::mod_packager::recording::observe_field_change( @@ -185,10 +186,12 @@ pub fn handle(message: StoreEditorMessage, app: &mut App) -> Task { app.state.editors.store_editor.add_product(); + app.state.workspace.mark_modified(); Task::none() } StoreEditorMessage::RemoveProduct(index) => { app.state.editors.store_editor.remove_product(index); + app.state.workspace.mark_modified(); Task::none() } StoreEditorMessage::ProductFieldChanged(product_idx, field, value) => { @@ -196,6 +199,7 @@ pub fn handle(message: StoreEditorMessage, app: &mut App) -> Task { @@ -228,6 +232,7 @@ pub fn handle(message: StoreEditorMessage, app: &mut App) -> Task { + app.state.workspace.clear_modified(); if let Some(ref catalog) = app.state.editors.store_editor.catalog { app.state.editors.store_editor.status_msg = format!("Successfully saved {} stores", catalog.len()); diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index caa69ea6..2127023b 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1008,3 +1008,45 @@ mod modified_flag_routing { ); } } + +// ============================================================================ +// Structural edits must mark the tab dirty +// ============================================================================ + +mod structural_edit_tests { + use super::*; + + #[test] + fn store_product_edit_marks_tab_modified_and_save_clears_it() { + use crate::editors::store::{EditableProduct, StoreEditorMessage, handle}; + use std::path::PathBuf; + + let mut app = App::test_new(Workspace::new()); + app.state.workspace.open( + "MistvaleStore.DB".into(), + Some(PathBuf::from("CharacterInGame/STORE.DB")), + ); + app.state.editors.store_editor.edit_products = vec![EditableProduct { + order: 0, + product_type: 1, + item_id: 0, + }]; + assert!(!app.state.workspace.tabs[0].modified); + + let _ = handle( + StoreEditorMessage::ProductFieldChanged(0, "item_id".into(), "42".into()), + &mut app, + ); + assert_eq!(app.state.editors.store_editor.edit_products[0].item_id, 42); + assert!( + app.state.workspace.tabs[0].modified, + "editing a store product must mark the tab dirty" + ); + + let _ = handle(StoreEditorMessage::Saved(Ok(())), &mut app); + assert!( + !app.state.workspace.tabs[0].modified, + "a successful save must clear the dirty flag" + ); + } +} diff --git a/dispel-gui/src/tests/tabbed_editor.rs b/dispel-gui/src/tests/tabbed_editor.rs index f860eded..1580ba6a 100644 --- a/dispel-gui/src/tests/tabbed_editor.rs +++ b/dispel-gui/src/tests/tabbed_editor.rs @@ -80,6 +80,37 @@ mod tabbed_editor_lifecycle_tests { app } + #[test] + fn add_and_remove_entry_mark_tab_modified() { + use crate::editors::npc_ref::{NpcRefEditorMessage, handle}; + use dispel_core::NPC; + + let mut app = app_with_tabbed_editor(EditorType::NpcRefEditor); + let tab_id = app.state.workspace.active().unwrap().id; + app.state + .editors + .npc_ref_editor + .editors + .get_mut(&tab_id) + .unwrap() + .editor + .catalog = Some(vec![NPC::default()]); + assert!(!app.state.workspace.tabs[0].modified); + + let _ = handle(NpcRefEditorMessage::AddEntry, &mut app); + assert!( + app.state.workspace.tabs[0].modified, + "adding a record must mark the tab dirty" + ); + + app.state.workspace.tabs[0].modified = false; + let _ = handle(NpcRefEditorMessage::RemoveEntry(0), &mut app); + assert!( + app.state.workspace.tabs[0].modified, + "removing a record must mark the tab dirty" + ); + } + #[test] fn remove_tab_clears_tabbed_editor_entries() { let mut app = app_with_tabbed_editor(EditorType::MonsterRefEditor); From 5df65d07dda4df9198f057b732c36eee2635b2a5 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:37:01 +0100 Subject: [PATCH 26/72] fix(gui): discard stale scan results from another game --- dispel-gui/src/app.rs | 3 +- .../editors/localization_manager/message.rs | 3 +- .../editors/localization_manager/update.rs | 19 ++- dispel-gui/src/message/system.rs | 14 ++- dispel-gui/src/state.rs | 3 +- dispel-gui/src/tests/indexation.rs | 4 +- dispel-gui/src/tests/select_boxes.rs | 7 +- dispel-gui/src/tests/system_messages.rs | 114 +++++++++++++++++- dispel-gui/src/update/startpage.rs | 13 +- dispel-gui/src/update/system.rs | 55 ++++++--- 10 files changed, 196 insertions(+), 39 deletions(-) diff --git a/dispel-gui/src/app.rs b/dispel-gui/src/app.rs index 08d536f1..834cd112 100644 --- a/dispel-gui/src/app.rs +++ b/dispel-gui/src/app.rs @@ -83,9 +83,10 @@ impl App { let init_task: Option> = if game_path.is_some() && search_index.file_mappings.is_empty() { game_path.map(|gp| { + let gp_tag = gp.to_string_lossy().to_string(); Task::perform( async move { crate::indexation::search_index::build_index(&gp).await }, - |index| Message::System(SystemMessage::IndexLoaded(Ok(index))), + move |index| Message::System(SystemMessage::IndexLoaded(gp_tag, Ok(index))), ) }) } else { diff --git a/dispel-gui/src/editors/localization_manager/message.rs b/dispel-gui/src/editors/localization_manager/message.rs index 48e94759..d84bfb2b 100644 --- a/dispel-gui/src/editors/localization_manager/message.rs +++ b/dispel-gui/src/editors/localization_manager/message.rs @@ -38,7 +38,8 @@ pub struct ImportResult { #[derive(Debug, Clone)] pub enum LocalizationMessage { Scan, - Scanned(Result, String>), + /// Scan result tagged with the game path that requested it. + Scanned(String, Result, String>), SelectEntry(usize), TranslationAction(text_editor::Action), SearchChanged(String), diff --git a/dispel-gui/src/editors/localization_manager/update.rs b/dispel-gui/src/editors/localization_manager/update.rs index e6bf2bd6..ca71a7d4 100644 --- a/dispel-gui/src/editors/localization_manager/update.rs +++ b/dispel-gui/src/editors/localization_manager/update.rs @@ -24,6 +24,7 @@ pub fn handle(message: LocalizationMessage, app: &mut App) -> Task Task { + LocalizationMessage::Scanned(path, result) => { + if path != app.state.shared_game_path { + return Task::none(); + } match result { Ok(entries) => { let count = entries.len(); @@ -918,12 +925,16 @@ mod tests { } let mut app = App::test_new(Workspace::new()); + app.state.shared_game_path = "InventedGame".to_string(); app.state.editors.localization_manager.filter_file = Some("Invented/Removed.ini".to_string()); app.state.editors.localization_manager.entries = vec![entry("Invented/Removed.ini")]; let _ = app.update(crate::message::Message::localization( - LocalizationMessage::Scanned(Ok(vec![entry("Invented/Kept.ini")])), + LocalizationMessage::Scanned( + "InventedGame".to_string(), + Ok(vec![entry("Invented/Kept.ini")]), + ), )); assert_eq!( diff --git a/dispel-gui/src/message/system.rs b/dispel-gui/src/message/system.rs index c3964ec1..9793b538 100644 --- a/dispel-gui/src/message/system.rs +++ b/dispel-gui/src/message/system.rs @@ -8,16 +8,22 @@ pub enum SystemMessage { Undo, Redo, Save, - IndexLoaded(Result), - CacheIndexationComplete(crate::indexation::file_index_cache::FileIndexCache), - CacheIndexationFailed, + /// Index result tagged with the game path that requested it. + IndexLoaded( + String, + Result, + ), + /// Cache result tagged with the game path that requested it. + CacheIndexationComplete(String, crate::indexation::file_index_cache::FileIndexCache), + CacheIndexationFailed(String), IndexSaveRequested, IndexComplete, IndexSaveComplete, RebuildIndex, ClearWorkspace, BrowseSharedGamePath, - FileTreeScanned(FileTree), + /// Scan result tagged with the game path that requested it. + FileTreeScanned(String, FileTree), FileSelected { field: String, path: Option, diff --git a/dispel-gui/src/state.rs b/dispel-gui/src/state.rs index 3c24a91b..27eb3d6f 100644 --- a/dispel-gui/src/state.rs +++ b/dispel-gui/src/state.rs @@ -190,6 +190,7 @@ impl AppState { // Cache is missing or invalid, start background indexation with fallback let cache_manager_clone = cache_manager.clone(); let game_path_clone = game_path.clone(); + let game_path_tag = game_path.to_string_lossy().to_string(); Some(Task::perform( async move { @@ -224,7 +225,7 @@ impl AppState { }, move |cache: FileIndexCache| { // Even with partial results, we use what we got - Message::System(SystemMessage::CacheIndexationComplete(cache)) + Message::System(SystemMessage::CacheIndexationComplete(game_path_tag, cache)) }, )) } diff --git a/dispel-gui/src/tests/indexation.rs b/dispel-gui/src/tests/indexation.rs index 91ee8cd7..33dc7ae2 100644 --- a/dispel-gui/src/tests/indexation.rs +++ b/dispel-gui/src/tests/indexation.rs @@ -22,7 +22,9 @@ mod indexation_edge_tests { #[test] fn system_cache_indexation_failed_does_not_panic() { let mut app = App::test_new(Workspace::new()); - let task = app.update(Message::System(SystemMessage::CacheIndexationFailed)); + let task = app.update(Message::System(SystemMessage::CacheIndexationFailed( + app.state.shared_game_path.clone(), + ))); assert_eq!(task.units(), 0); } } diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs index f13c83b0..62fb94d6 100644 --- a/dispel-gui/src/tests/select_boxes.rs +++ b/dispel-gui/src/tests/select_boxes.rs @@ -519,9 +519,10 @@ fn test_localization_filter_only_survives_a_rescan_that_keeps_its_file() { app.state.editors.localization_manager.filter_file = Some("Invented/Kept.ini".to_string()); assert!(select_shows(view(&app), "Kept.ini")); - let _ = app.update(Message::localization(LocalizationMessage::Scanned(Ok( - vec![entry("Invented/Other.ini")], - )))); + let _ = app.update(Message::localization(LocalizationMessage::Scanned( + app.state.shared_game_path.clone(), + Ok(vec![entry("Invented/Other.ini")]), + ))); assert_eq!(app.state.editors.localization_manager.filter_file, None); assert!(select_shows(view(&app), "All files")); } diff --git a/dispel-gui/src/tests/system_messages.rs b/dispel-gui/src/tests/system_messages.rs index 7246a562..d0230cfb 100644 --- a/dispel-gui/src/tests/system_messages.rs +++ b/dispel-gui/src/tests/system_messages.rs @@ -154,7 +154,11 @@ mod index_messages { let mut idx = SearchIndex::new(); idx.game_path = Some("/fake/path".to_string()); - let _task = app.update(Message::System(SystemMessage::IndexLoaded(Ok(idx)))); + app.state.shared_game_path = "/fake/path".to_string(); + let _task = app.update(Message::System(SystemMessage::IndexLoaded( + "/fake/path".to_string(), + Ok(idx), + ))); assert_eq!(app.state.status_msg, "Search index loaded"); assert_eq!( @@ -167,9 +171,10 @@ mod index_messages { #[test] fn index_loaded_error_sets_error_status() { let mut app = App::test_new(Workspace::new()); - let task = app.update(Message::System(SystemMessage::IndexLoaded(Err( - "corrupt".to_string() - )))); + let task = app.update(Message::System(SystemMessage::IndexLoaded( + app.state.shared_game_path.clone(), + Err("corrupt".to_string()), + ))); assert!(app.state.status_msg.contains("Failed to load")); let _ = task; } @@ -257,6 +262,7 @@ mod cache_indexation { }; let task = app.update(Message::System(SystemMessage::CacheIndexationComplete( + app.state.shared_game_path.clone(), cache, ))); let _ = task; @@ -268,7 +274,9 @@ mod cache_indexation { let mut app = App::test_new(Workspace::new()); app.is_indexing = true; - let task = app.update(Message::System(SystemMessage::CacheIndexationFailed)); + let task = app.update(Message::System(SystemMessage::CacheIndexationFailed( + app.state.shared_game_path.clone(), + ))); let _ = task; assert!(!app.is_indexing, "indexing flag cleared on failure"); } @@ -377,3 +385,99 @@ mod save_tab_routing { ); } } + +// ============================================================================ +// Async results from a previous game must be discarded +// ============================================================================ + +#[cfg(feature = "iced_test")] +mod stale_game_results { + use super::*; + use crate::message::MessageExt; + use crate::tests::common::task_outputs; + + fn invented_dirs() -> (tempfile::TempDir, tempfile::TempDir) { + ( + tempfile::Builder::new() + .prefix("MistvaleGame") + .tempdir() + .unwrap(), + tempfile::Builder::new() + .prefix("DuskhavenGame") + .tempdir() + .unwrap(), + ) + } + + fn find_message_with<'a>(messages: &'a [Message], fragment: &str) -> &'a Message { + messages + .iter() + .find(|message| format!("{message:?}").contains(fragment)) + .unwrap_or_else(|| panic!("no message containing {fragment}")) + } + + #[test] + fn test_stale_file_tree_scan_does_not_overwrite_new_game() { + let (game_a, game_b) = invented_dirs(); + let mut app = App::test_new(Workspace::new()); + + let task = app.update(Message::System(SystemMessage::FileSelected { + field: "workspace_game_path".into(), + path: Some(game_a.path().to_path_buf()), + })); + let pending = task_outputs(task); + + // Switch to a different game before A's scan completes. + let _ = app.update(Message::System(SystemMessage::FileSelected { + field: "workspace_game_path".into(), + path: Some(game_b.path().to_path_buf()), + })); + app.file_tree.state.search_query = "DuskhavenMarker".into(); + + let scan_message = find_message_with(&pending, "FileTreeScanned").clone(); + let _ = app.update(scan_message); + + assert_eq!( + app.file_tree.state.search_query, "DuskhavenMarker", + "a scan started for the old game must not replace the new game's tree" + ); + } + + #[test] + fn test_stale_localization_scan_does_not_overwrite_new_game() { + use crate::editors::localization_manager::LocalizationMessage; + use dispel_core::TextEntry; + use dispel_core::localization::TextEncoding; + + let (game_a, game_b) = invented_dirs(); + let mut app = App::test_new(Workspace::new()); + app.state.shared_game_path = game_a.path().to_string_lossy().to_string(); + + let task = app.update(Message::localization(LocalizationMessage::Scan)); + let pending = task_outputs(task); + + app.state.shared_game_path = game_b.path().to_string_lossy().to_string(); + app.state.editors.localization_manager.entries = vec![TextEntry { + file_path: "Duskhaven/Kept.ini".into(), + record_id: 0, + field_name: "name", + original: "Kept".into(), + translation: String::new(), + encoding: TextEncoding::Utf8, + max_bytes: 64, + }]; + + let scan_message = find_message_with(&pending, "Scanned").clone(); + let _ = app.update(scan_message); + + assert_eq!( + app.state.editors.localization_manager.entries.len(), + 1, + "a scan from the old game must not replace the new game's entries" + ); + assert_eq!( + app.state.editors.localization_manager.entries[0].file_path, + "Duskhaven/Kept.ini" + ); + } +} diff --git a/dispel-gui/src/update/startpage.rs b/dispel-gui/src/update/startpage.rs index 0eb1cbed..847b082d 100644 --- a/dispel-gui/src/update/startpage.rs +++ b/dispel-gui/src/update/startpage.rs @@ -85,10 +85,13 @@ pub fn enter_editor_mode(app: &mut App, path: PathBuf) -> Task { app.search_index.game_path = Some(path.to_string_lossy().to_string()); let gp = path.clone(); let gp_cache = path.clone(); + let gp_tag = path.to_string_lossy().to_string(); + let gp_index_tag = gp_tag.clone(); + let gp_cache_tag = gp_tag; let search_task = Task::perform( async move { crate::indexation::search_index::build_index(&gp).await }, - |index| Message::System(SystemMessage::IndexLoaded(Ok(index))), + move |index| Message::System(SystemMessage::IndexLoaded(gp_index_tag, Ok(index))), ); let mut tasks = vec![stop_recording_task, search_task]; @@ -100,9 +103,11 @@ pub fn enter_editor_mode(app: &mut App, path: PathBuf) -> Task { crate::indexation::indexation_service::IndexationService::new(cache_manager); svc.start_indexation_with_fallback(gp_cache).await }, - |result| match result { - Ok(cache) => Message::System(SystemMessage::CacheIndexationComplete(cache)), - Err(_) => Message::System(SystemMessage::CacheIndexationFailed), + move |result| match result { + Ok(cache) => { + Message::System(SystemMessage::CacheIndexationComplete(gp_cache_tag, cache)) + } + Err(_) => Message::System(SystemMessage::CacheIndexationFailed(gp_cache_tag)), }, )); } diff --git a/dispel-gui/src/update/system.rs b/dispel-gui/src/update/system.rs index be8cb37f..2c2b1953 100644 --- a/dispel-gui/src/update/system.rs +++ b/dispel-gui/src/update/system.rs @@ -170,23 +170,30 @@ pub fn handle(message: SystemMessage, app: &mut App) -> Task Task browse_folder("workspace_game_path"), - SystemMessage::FileTreeScanned(tree) => { - app.file_tree = tree; + SystemMessage::FileTreeScanned(path, tree) => { + if path == app.state.shared_game_path { + app.file_tree = tree; + } Task::none() } SystemMessage::RebuildIndex => { @@ -213,11 +222,16 @@ pub fn handle(message: SystemMessage, app: &mut App) -> Task Task { - Message::System(SystemMessage::CacheIndexationComplete(cache)) - } + move |result| match result { + Ok(cache) => Message::System( + SystemMessage::CacheIndexationComplete(gp_cache_tag, cache), + ), Err(e) => { eprintln!("Failed to rebuild file index cache: {}", e); - Message::System(SystemMessage::CacheIndexationFailed) + Message::System(SystemMessage::CacheIndexationFailed( + gp_cache_tag, + )) } }, ), @@ -266,7 +282,10 @@ pub fn handle(message: SystemMessage, app: &mut App) -> Task { + SystemMessage::IndexLoaded(path, res) => { + if path != app.state.shared_game_path { + return Task::none(); + } match res { Ok(index) => { app.search_index = index; @@ -288,7 +307,10 @@ pub fn handle(message: SystemMessage, app: &mut App) -> Task { + SystemMessage::CacheIndexationComplete(path, cache) => { + if path != app.state.shared_game_path { + return Task::none(); + } // Cache indexation completed successfully if let Some(ref mut cache_manager) = app.state.file_index_cache_manager { if let Err(e) = cache_manager.save_cache(&cache) { @@ -313,7 +335,10 @@ pub fn handle(message: SystemMessage, app: &mut App) -> Task { + SystemMessage::CacheIndexationFailed(path) => { + if path != app.state.shared_game_path { + return Task::none(); + } eprintln!("File index cache indexation failed"); app.is_indexing = false; Task::none() From c19f1ba9cf1b38717f244e3a33507fd5ff2096ad Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:39:21 +0100 Subject: [PATCH 27/72] fix(gui): truncate mod preview on character boundaries --- .../src/editors/mod_packager/view/detail.rs | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/dispel-gui/src/editors/mod_packager/view/detail.rs b/dispel-gui/src/editors/mod_packager/view/detail.rs index a6eb67d6..cb4fcad7 100644 --- a/dispel-gui/src/editors/mod_packager/view/detail.rs +++ b/dispel-gui/src/editors/mod_packager/view/detail.rs @@ -205,7 +205,10 @@ fn describe(action: &ChangeAction) -> String { fn preview_value(value: &dispel_core::modding::Value) -> String { use dispel_core::modding::Value; match value { - Value::String(s) if s.len() > 40 => format!("\"{}…\"", &s[..40]), + Value::String(s) if s.chars().count() > 40 => { + let prefix: String = s.chars().take(40).collect(); + format!("\"{prefix}…\"") + } Value::String(s) => format!("\"{s}\""), Value::I64(i) => i.to_string(), Value::F64(f) => f.to_string(), @@ -223,3 +226,25 @@ fn action_btn(label: &str, msg: ModPackagerMessage, disabled: bool) -> button::B b.on_press(Message::mod_packager(msg)) } } + +#[cfg(test)] +mod tests { + use super::*; + use dispel_core::modding::Value; + + #[test] + fn test_preview_value_truncates_on_char_boundary() { + // A two-byte character starting at byte 39 makes byte 40 fall in the + // middle of it; slicing by bytes would panic here. + let mut text = "MistvaleDuskhaven".repeat(3); + text.truncate(39); + text.push('é'); + text.push_str("ElderglenTail"); + let rendered = preview_value(&Value::String(text)); + + assert!(rendered.ends_with('"')); + assert!(rendered.contains('…')); + assert!(rendered.contains('é'), "the split character must survive"); + assert_eq!(rendered.matches('…').count(), 1); + } +} From 66fb36ada9e0ef92e344d0b20ff385f1c1f1f9ab Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:42:17 +0100 Subject: [PATCH 28/72] fix(gui): clamp localization page after rescan --- .../editors/localization_manager/update.rs | 2 + .../src/editors/localization_manager/view.rs | 4 +- dispel-gui/src/tests/select_boxes.rs | 39 +++++++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/dispel-gui/src/editors/localization_manager/update.rs b/dispel-gui/src/editors/localization_manager/update.rs index ca71a7d4..a1705162 100644 --- a/dispel-gui/src/editors/localization_manager/update.rs +++ b/dispel-gui/src/editors/localization_manager/update.rs @@ -49,6 +49,7 @@ pub fn handle(message: LocalizationMessage, app: &mut App) -> Task Task Element<'_, Message> { const PAGE_SIZE: usize = 250; let visible = state.visible_entries(); let visible_total = visible.len(); - let page = state.page; let total_pages = visible_total.div_ceil(PAGE_SIZE).max(1); + // Entries can shrink underneath a stored page (rescan/import). Clamp + // before slicing so a stale page can never address outside `visible`. + let page = state.page.min(total_pages - 1); let page_start = page * PAGE_SIZE; let page_end = (page_start + PAGE_SIZE).min(visible_total); let page_visible = &visible[page_start..page_end]; diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs index 62fb94d6..6a782aee 100644 --- a/dispel-gui/src/tests/select_boxes.rs +++ b/dispel-gui/src/tests/select_boxes.rs @@ -527,6 +527,45 @@ fn test_localization_filter_only_survives_a_rescan_that_keeps_its_file() { assert!(select_shows(view(&app), "All files")); } +#[test] +fn test_rescan_to_smaller_catalog_keeps_page_valid() { + use crate::editors::localization_manager::LocalizationMessage; + use crate::editors::localization_manager::view::view; + use crate::message::MessageExt; + use dispel_core::TextEntry; + use dispel_core::localization::TextEncoding; + + fn entry(file: &str) -> TextEntry { + TextEntry { + file_path: file.to_string(), + record_id: 0, + field_name: "name", + original: "Invented".to_string(), + translation: String::new(), + encoding: TextEncoding::Utf8, + max_bytes: 64, + } + } + + let mut app = crate::app::App::test_new(crate::workspace::Workspace::new()); + app.state.editors.localization_manager.entries = (0..300) + .map(|i| entry(&format!("Invented/Chapter{i}.ini"))) + .collect(); + app.state.editors.localization_manager.page = 1; + + let _ = app.update(Message::localization(LocalizationMessage::Scanned( + app.state.shared_game_path.clone(), + Ok(vec![entry("Invented/SmallCatalog.ini")]), + ))); + + // Rendering used to slice [250..500] into a one-entry list and panic. + let _ = view(&app); + assert_eq!( + app.state.editors.localization_manager.page, 0, + "a rescan must return to the first page" + ); +} + #[test] fn test_event_script_prefix_options_keep_the_current_prefix() { use dispel_core::references::event_scr::{ActionFunction, EventScript, SpriteDefinition}; From 9ee15548609dcd9fce15274cde1ec26420791dce Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:45:22 +0100 Subject: [PATCH 29/72] fix(core): reject out-of-range map sprite ids --- src/map/reader.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 4 deletions(-) diff --git a/src/map/reader.rs b/src/map/reader.rs index 39599197..98285f2b 100644 --- a/src/map/reader.rs +++ b/src/map/reader.rs @@ -16,7 +16,7 @@ use byteorder::{LittleEndian, ReadBytesExt}; use std::collections::HashMap; use std::fs::File; -use std::io::{BufReader, Read, Result, Seek, SeekFrom}; +use std::io::{BufReader, Error, ErrorKind, Read, Result, Seek, SeekFrom}; use crate::sprite; use crate::sprite::SequenceInfo; @@ -182,9 +182,29 @@ pub fn sprite_info_block( // In known maps left==sprite_x and top==sprite_y; they are stored // in separate per-frame arrays so they may diverge in mods. - let sprite_id: usize = sprite_id.try_into().unwrap_or(0); - let skip = (sprites[sprite_id].frame_count - 1) * 6 * 4; - reader.seek(SeekFrom::Current(skip.into()))?; + let sprite_id = usize::try_from(sprite_id).map_err(|_| { + Error::new( + ErrorKind::InvalidData, + format!("negative sprite id {sprite_id} in sprite info block"), + ) + })?; + let frame_count = sprites + .get(sprite_id) + .map(|s| s.frame_count) + .ok_or_else(|| { + Error::new( + ErrorKind::InvalidData, + format!("sprite id {sprite_id} is outside the sequence table"), + ) + })?; + if frame_count <= 0 { + return Err(Error::new( + ErrorKind::InvalidData, + format!("sprite {sprite_id} has no frames"), + )); + } + let skip = i64::from(frame_count - 1) * 6 * 4; + reader.seek(SeekFrom::Current(skip))?; info.push(SpriteInfoBlock { sprite_id, @@ -523,6 +543,48 @@ mod tests { assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); } + fn one_sprite_info_bytes(sprite_id: i32) -> Vec { + let mut bytes = 1_i32.to_le_bytes().to_vec(); + bytes.extend_from_slice(&sprite_id.to_le_bytes()); + for _ in 0..6 { + bytes.extend_from_slice(&0_i32.to_le_bytes()); + } + bytes + } + + fn one_sequence(frame_count: i32) -> Vec { + vec![SequenceInfo { + sequence_start_position: 0, + sequence_end_position: 0, + frame_count, + frame_infos: Vec::new(), + }] + } + + #[test] + fn test_sprite_info_block_rejects_out_of_range_id() { + let mut reader = reader_from_bytes("sprite-info-bad-id", &one_sprite_info_bytes(5)); + let err = super::sprite_info_block(&mut reader, &one_sequence(1)) + .expect_err("a sprite id past the sequence table must fail"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); + } + + #[test] + fn test_sprite_info_block_rejects_negative_id() { + let mut reader = reader_from_bytes("sprite-info-negative-id", &one_sprite_info_bytes(-1)); + let err = super::sprite_info_block(&mut reader, &one_sequence(1)) + .expect_err("a negative sprite id must fail"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); + } + + #[test] + fn test_sprite_info_block_rejects_zero_frame_count() { + let mut reader = reader_from_bytes("sprite-info-zero-frames", &one_sprite_info_bytes(0)); + let err = super::sprite_info_block(&mut reader, &one_sequence(0)) + .expect_err("a sequence with no frames must fail"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); + } + #[test] fn test_overlay_table_reads_valid_entries() { let mut bytes = 2_i32.to_le_bytes().to_vec(); From 6903f232b59814f4f01bd41c181df77d6a4fc2a1 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:47:13 +0100 Subject: [PATCH 30/72] fix(core): reject malformed dialogue script ids --- src/references/dialogue_script.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/references/dialogue_script.rs b/src/references/dialogue_script.rs index 9509ebb1..0cd007ae 100644 --- a/src/references/dialogue_script.rs +++ b/src/references/dialogue_script.rs @@ -108,7 +108,11 @@ impl Extractor for DialogueScript { continue; } - let id: i32 = parts[0].trim().parse::().unwrap(); + // The id is mandatory for a usable row; a bad id is skipped just + // like a short line instead of aborting the whole parse. + let Some(id) = parse_int(parts[0].trim()) else { + continue; + }; let required_event_id = parse_int(parts[1].trim()); let next_dialog_to_check = parse_int(parts[2].trim()); let dialog_type_id = parse_int(parts[3].trim()); @@ -246,6 +250,16 @@ mod tests { assert_eq!(dlgs.len(), 1); } + #[test] + fn test_parse_skips_line_with_non_numeric_id() { + let data = b"MistvaleInvalid,0,2,0,1,100,200,0,0,1000\n2,0,0,1,0,101,201,202,203,0\n"; + let mut c = Cursor::new(data.as_ref()); + let dlgs = DialogueScript::parse(&mut c, data.len() as u64) + .expect("a bad id must be rejected, not panic"); + assert_eq!(dlgs.len(), 1, "only the well-formed row survives"); + assert_eq!(dlgs[0].id, 2); + } + #[test] fn serialize_round_trip() { let data = b"1,0,2,0,1,100,200,0,0,1000\r\n2,0,0,1,0,101,201,202,203,0\r\n"; From 4d1e0f660cc51695554d39903235a2fd44f39db3 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:48:57 +0100 Subject: [PATCH 31/72] fix(core): reject malformed draw item columns --- src/references/draw_item.rs | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/references/draw_item.rs b/src/references/draw_item.rs index 245b653e..b8a2d262 100644 --- a/src/references/draw_item.rs +++ b/src/references/draw_item.rs @@ -76,10 +76,16 @@ impl Extractor for DrawItem { continue; } - let map_id = parts[0].parse::().unwrap(); - let x_coord = parts[1].parse::().unwrap(); - let y_coord = parts[2].parse::().unwrap(); - let encoded_item_id = parts[3].parse::().unwrap(); + // A bad column makes the row unusable; skip it rather than + // aborting the whole scan on user-editable text. + let (Some(map_id), Some(x_coord), Some(y_coord), Some(encoded_item_id)) = ( + parts[0].trim().parse::().ok(), + parts[1].trim().parse::().ok(), + parts[2].trim().parse::().ok(), + parts[3].trim().parse::().ok(), + ) else { + continue; + }; draw_items.push(DrawItem { map_id, @@ -161,6 +167,17 @@ mod tests { assert_eq!(items[0].item.item_type(), Some(ItemTypeId::NoItem)); // byte[1]=0 → no match → NoItem } + #[test] + fn test_parse_skips_row_with_non_numeric_column() { + let data = b"(1,10,20,MistvaleInvalid)\n(2,30,40,517)\n"; + let mut c = Cursor::new(data.as_ref()); + let items = + DrawItem::parse(&mut c, data.len() as u64).expect("a bad column must not panic"); + assert_eq!(items.len(), 1, "only the well-formed row survives"); + assert_eq!(items[0].map_id, 2); + assert_eq!(items[0].item.raw(), 517); + } + #[test] fn serialize_round_trip() { let data = b"(1,10,20,517)\r\n"; From 8bfdb559a06e7b3b9a044e2a89df60c0adb4d256 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:51:25 +0100 Subject: [PATCH 32/72] fix(hexedit): ignore unsupported persisted encodings --- hexedit/src/main.rs | 80 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 1 deletion(-) diff --git a/hexedit/src/main.rs b/hexedit/src/main.rs index b9d8de13..b30bfe2a 100644 --- a/hexedit/src/main.rs +++ b/hexedit/src/main.rs @@ -36,6 +36,39 @@ fn settings_path() -> PathBuf { p } +/// True when the named encoding has an encoder that emits its own bytes. +/// `encoding_rs` reports UTF-16 as UTF-8 on encode, so those labels must not +/// stay in the persisted custom list. +fn has_real_encoder(entry: &EncodingEntry) -> bool { + match encoding_rs::Encoding::for_label(entry.encoding_name.as_bytes()) { + Some(enc) => enc.output_encoding().name() == enc.name(), + None => false, + } +} + +fn sanitize_settings(mut settings: PersistedSettings) -> PersistedSettings { + let mut kept = Vec::with_capacity(settings.custom_encodings.len()); + let mut removed = Vec::new(); + for (idx, entry) in settings.custom_encodings.iter().enumerate() { + if has_real_encoder(entry) { + kept.push(entry.clone()); + } else { + removed.push(idx); + } + } + for idx in removed { + hexedit::write_mode::remap_write_mode(&mut settings.write_mode, idx); + } + settings.custom_encodings = kept; + // Settings from older versions may name a custom slot past the end. + if let WriteMode::Custom(idx) = settings.write_mode + && idx >= settings.custom_encodings.len() + { + settings.write_mode = WriteMode::Hex; + } + settings +} + fn load_settings() -> PersistedSettings { load_settings_from(&settings_path()) } @@ -43,7 +76,7 @@ fn load_settings() -> PersistedSettings { fn load_settings_from(path: &Path) -> PersistedSettings { match std::fs::read_to_string(path) { Ok(json) => match serde_json::from_str(&json) { - Ok(settings) => settings, + Ok(settings) => sanitize_settings(settings), Err(e) => { eprintln!("[hexedit] invalid settings file, using defaults: {e}"); PersistedSettings::default() @@ -360,4 +393,49 @@ mod tests { assert_eq!(actual.0, WriteMode::Windows1250); assert_eq!(actual.1, invented.custom_encodings); } + + #[test] + fn test_load_settings_drops_unsupported_custom_encodings() { + let dir = + std::env::temp_dir().join(format!("hexedit_sanitize_settings_{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let mixed = dir.join("InventedMixed.json"); + let only_unsupported = dir.join("InventedUnsupported.json"); + + std::fs::write( + &mixed, + r#"{"write_mode":"Custom#1","custom_encodings":[{"label":"UTF-16LE","encoding_name":"UTF-16LE"},{"label":"Mistvale Valid","encoding_name":"windows-1250"}]}"#, + ) + .unwrap(); + std::fs::write( + &only_unsupported, + r#"{"write_mode":"Custom#0","custom_encodings":[{"label":"UTF-16BE","encoding_name":"UTF-16BE"}]}"#, + ) + .unwrap(); + + let loaded = load_settings_from(&mixed); + assert_eq!( + loaded.custom_encodings.len(), + 1, + "the UTF-16 entry must be dropped on load" + ); + assert_eq!(loaded.custom_encodings[0].label, "Mistvale Valid"); + assert_eq!( + loaded.write_mode, + WriteMode::Custom(0), + "the active custom mode must follow the surviving entry" + ); + + let loaded = load_settings_from(&only_unsupported); + assert!(loaded.custom_encodings.is_empty()); + assert_eq!( + loaded.write_mode, + WriteMode::Hex, + "a mode pointing at the dropped entry must not stay custom" + ); + + std::fs::remove_file(&mixed).unwrap(); + std::fs::remove_file(&only_unsupported).unwrap(); + let _ = std::fs::remove_dir(&dir); + } } From 0c315600f1b780535f9315c9aa074a6a80dad775 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:06:19 +0100 Subject: [PATCH 33/72] fix(hexedit): remap write mode after multiple removals --- hexedit/src/main.rs | 53 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/hexedit/src/main.rs b/hexedit/src/main.rs index b30bfe2a..de3f55b4 100644 --- a/hexedit/src/main.rs +++ b/hexedit/src/main.rs @@ -56,7 +56,9 @@ fn sanitize_settings(mut settings: PersistedSettings) -> PersistedSettings { removed.push(idx); } } - for idx in removed { + // Remap from the end: each removal is applied to indices as they stood + // before that removal, so a surviving entry keeps its correct new index. + for idx in removed.into_iter().rev() { hexedit::write_mode::remap_write_mode(&mut settings.write_mode, idx); } settings.custom_encodings = kept; @@ -438,4 +440,53 @@ mod tests { std::fs::remove_file(&only_unsupported).unwrap(); let _ = std::fs::remove_dir(&dir); } + + #[test] + fn test_load_settings_remaps_mode_after_multiple_removals() { + let dir = std::env::temp_dir().join(format!( + "hexedit_multi_removal_settings_{}", + std::process::id() + )); + let _ = std::fs::create_dir_all(&dir); + let surviving = dir.join("InventedSurviving.json"); + let removed = dir.join("InventedRemoved.json"); + let entries = r#"[{"label":"Mistvale UTF-16LE","encoding_name":"UTF-16LE"},{"label":"Duskhaven 1250","encoding_name":"windows-1250"},{"label":"Elderglen UTF-16BE","encoding_name":"UTF-16BE"},{"label":"Gloomvale 932","encoding_name":"Shift_JIS"}]"#; + + std::fs::write( + &surviving, + format!(r#"{{"write_mode":"Custom#3","custom_encodings":{entries}}}"#), + ) + .unwrap(); + std::fs::write( + &removed, + format!(r#"{{"write_mode":"Custom#2","custom_encodings":{entries}}}"#), + ) + .unwrap(); + + let loaded = load_settings_from(&surviving); + assert_eq!( + loaded + .custom_encodings + .iter() + .map(|e| e.label.as_str()) + .collect::>(), + vec!["Duskhaven 1250", "Gloomvale 932"] + ); + assert_eq!( + loaded.write_mode, + WriteMode::Custom(1), + "the last surviving entry moves from index 3 to index 1" + ); + + let loaded = load_settings_from(&removed); + assert_eq!( + loaded.write_mode, + WriteMode::Hex, + "a mode pointing at a removed entry must not land on another encoding" + ); + + std::fs::remove_file(&surviving).unwrap(); + std::fs::remove_file(&removed).unwrap(); + let _ = std::fs::remove_dir(&dir); + } } From 6b92b8d8e6123bd47bff2b3c95c70aaaa802fec5 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:02:52 +0100 Subject: [PATCH 34/72] fix(core): preserve store products with lodging cost --- dispel-gui/src/editors/store/view.rs | 10 +- docs/files/CharacterInGame/Store.db.md | 29 +++--- src/modding/patchers/store.rs | 11 +-- src/references/store_db.rs | 128 ++++++++++++++++++------- 4 files changed, 109 insertions(+), 69 deletions(-) diff --git a/dispel-gui/src/editors/store/view.rs b/dispel-gui/src/editors/store/view.rs index 3bc270a2..bcf5fd6f 100644 --- a/dispel-gui/src/editors/store/view.rs +++ b/dispel-gui/src/editors/store/view.rs @@ -258,7 +258,7 @@ fn product_list_pane<'a>( misc: &'a Option>, edit_items: &'a Option>, ) -> Element<'a, Message> { - let can_add = editor.selected_idx.is_some() && !editor.is_inn(); + let can_add = editor.selected_idx.is_some(); let header = container( row![ @@ -285,14 +285,6 @@ fn product_list_pane<'a>( ) .padding(16) .into() - } else if editor.is_inn() { - container( - text("Inns have no products") - .size(12) - .style(style::subtle_text), - ) - .padding(16) - .into() } else { let cards: Vec> = editor .edit_products diff --git a/docs/files/CharacterInGame/Store.db.md b/docs/files/CharacterInGame/Store.db.md index 814cc842..8dcb9ee8 100644 --- a/docs/files/CharacterInGame/Store.db.md +++ b/docs/files/CharacterInGame/Store.db.md @@ -23,13 +23,10 @@ The tool reads `Store.db` as shop and inn records. Each record holds a name, a c [Records: 948 bytes each] - name: 32 bytes (WINDOWS-1250, null-padded) -- inn_night_cost: i32 (determines record type) -- IF inn_night_cost > 0 (Inn): - - 144 bytes padding (price modifier + 15 product slots, all zero) -- ELSE (Shop): - - price_modifier: i16 (percentage applied to item prices) - - products: 15 × (i16, i16) slots (type, item_id), terminated by type = 0 - - 82 bytes padding +- inn_night_cost: i32 (>0 means lodging is offered) +- price_modifier: i16 (percentage applied to item prices) +- products: 15 × (i16, i16) slots (type, item_id), terminated by type = 0 +- 82 bytes padding - invitation: 512 bytes (WINDOWS-1250, null-padded) - haggle_success: 128 bytes (WINDOWS-1250, null-padded) - haggle_fail: 128 bytes (WINDOWS-1250, null-padded) @@ -41,20 +38,20 @@ The tool reads `Store.db` as shop and inn records. Each record holds a name, a c |----------------|------|--------|------------------------------------------------| | index | N/A | i32 | Record index (assigned during parsing) | | store_name | 32 | string | Shop/Inn name (WINDOWS-1250 encoded) | -| inn_night_cost | 4 | i32 | Night cost (>0 = inn, 0 = shop) | -| price_modifier | 2 | i16 | Percentage applied to item prices (shops only) | -| products | 60 | array | Product list (shops only, up to 15 slots) | -| padding | 82 | bytes | Always zero (shops) | +| inn_night_cost | 4 | i32 | Night cost (>0 = lodging offered) | +| price_modifier | 2 | i16 | Percentage applied to item prices | +| products | 60 | array | Product list (up to 15 slots) | +| padding | 82 | bytes | Always zero | | invitation | 512 | string | Merchant greeting (WINDOWS-1250) | | haggle_success | 128 | string | Successful haggle response | | haggle_fail | 128 | string | Failed haggle response | ### Store Types -**Inn (inn_night_cost > 0):** +**Lodging offered (inn_night_cost > 0):** -- No products, 144 bytes of padding -- A nightly cost value +- Up to 15 product slots, like any other record +- A nightly cost value and a price modifier - Text fields **Shop (inn_night_cost = 0):** @@ -129,8 +126,8 @@ Offset | Size | Field | Description ### Special Values -- **inn_night_cost > 0**: Inn record (no products) -- **inn_night_cost = 0**: Shop record (with products) +- **inn_night_cost > 0**: lodging offered; products are still present +- **inn_night_cost = 0**: shop record ### Example Structures diff --git a/src/modding/patchers/store.rs b/src/modding/patchers/store.rs index 3ab880de..c1ba826b 100644 --- a/src/modding/patchers/store.rs +++ b/src/modding/patchers/store.rs @@ -1,12 +1,9 @@ //! Field-level patcher for `CharacterInGame/Store.db` (shops & inns). //! -//! Hand-written because [`Store`] has a conditional structure: when -//! `inn_night_cost > 0` the record is an inn (144 bytes of padding, -//! no products); otherwise it's a shop with up to 71 `(type, id)` -//! product pairs. Field patching only covers the scalar fields — -//! mutating the product list is best done by replacing the whole -//! file via `FileReplace`, since rebalancing 71 packed slots from -//! a single `FieldDelta` would be fragile. +//! All records share the same layout: a price modifier followed by +//! 15 `(type, id)` product slots, whether or not lodging is offered. +//! Field patching only covers the scalar fields — mutating the product +//! list is best done by replacing the whole file via `FileReplace`. use std::io::Cursor; diff --git a/src/references/store_db.rs b/src/references/store_db.rs index bc8e8348..461891e6 100644 --- a/src/references/store_db.rs +++ b/src/references/store_db.rs @@ -1,4 +1,4 @@ -use std::io::{Cursor, Read, Seek, SeekFrom, Write}; +use std::io::{Cursor, Read, Seek, Write}; use std::path::Path; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; @@ -40,7 +40,7 @@ use dispel_macros::Localizable; /// | [Record 1] - 948 bytes | /// | - store_name: 32 bytes (WINDOWS-1250)| /// | - inn_night_cost: i32 | -/// | - price_modifier: i16 (shops only) | +/// | - price_modifier: i16 | /// | - products: 15 × (type, id) | /// | - padding: 82 bytes | /// | - invitation: 512 bytes (WINDOWS-1250)| @@ -54,9 +54,9 @@ use dispel_macros::Localizable; /// /// # Store Types /// -/// - `inn_night_cost > 0`: Inn (no products; the 2-byte price modifier and -/// 15 product slots are all zero, i.e. 144 bytes of padding) -/// - `inn_night_cost = 0`: Shop (with price modifier + products) +/// - `inn_night_cost > 0`: lodging is offered; the price modifier and the 15 +/// product slots still follow and carry the same data as any other record +/// - `inn_night_cost = 0`: shop /// /// # Product Types /// @@ -74,14 +74,14 @@ use dispel_macros::Localizable; /// # Field Categories /// /// - **Identification**: `index`, `store_name` (32 bytes, WINDOWS-1250) -/// - **Economy**: `inn_night_cost` (0 = shop, >0 = inn), `price_modifier` (i16) +/// - **Economy**: `inn_night_cost` (0 = shop, >0 = lodging), `price_modifier` (i16) /// - **Inventory**: `products` (up to 15 items as `(type, id)`) /// - **Dialogue**: `invitation` (512 bytes), `haggle_success` (128 bytes), `haggle_fail` (128 bytes) /// /// # Special Values /// -/// - `inn_night_cost > 0`: Inn mode (padding instead of products) -/// - `inn_night_cost = 0`: Shop mode (with product list) +/// - `inn_night_cost > 0`: lodging offered; product list still present +/// - `inn_night_cost = 0`: shop /// - Product list terminated by `type == 0` /// /// # File Purpose @@ -96,10 +96,9 @@ pub struct Store { /// 32-byte shopkeeper title. #[translatable(encoding = "WINDOWS-1250", max_bytes = 32)] pub store_name: String, - /// Price to rest; dictates physical structure padding in save format. + /// Price to rest. Independent of the product list. pub inn_night_cost: i32, - /// Price modifier (percentage) applied to item prices. Only meaningful for shops - /// (`inn_night_cost == 0`); for inns it is always 0. + /// Price modifier (percentage) applied to item prices. /// /// Used by the game as a signed percentage markup on an item's base price: /// `buy_price = base + (modifier * base) / 100` and @@ -134,31 +133,26 @@ impl Extractor for Store { let name = read_null_terminated_windows_1250(&buffer).unwrap(); let inn_night_cost = reader.read_i32::()?; - let mut price_modifier = 0; + let price_modifier = reader.read_i16::()?; let mut products: Vec = vec![]; - if inn_night_cost > 0 { - reader.seek(SeekFrom::Current(144))?; - } else { - price_modifier = reader.read_i16::()?; // price modifier - - // 15 product slots (4 bytes each) + 82 bytes padding - let mut buffer = [0u8; 142]; - reader.read_exact(&mut buffer)?; - let mut cursor = Cursor::new(&buffer); + // 15 product slots (4 bytes each) + 82 bytes padding. The lodge + // price does not replace this area: inns keep their products too. + let mut buffer = [0u8; 142]; + reader.read_exact(&mut buffer)?; + let mut cursor = Cursor::new(&buffer); - for i in 0..15 { - let item_type_raw = cursor.read_i16::().unwrap(); - if item_type_raw == 0 { - break; - } + for i in 0..15 { + let item_type_raw = cursor.read_i16::().unwrap(); + if item_type_raw == 0 { + break; + } - let product_type = ProductType::from_i32(item_type_raw as i32) - .unwrap_or(ProductType::MiscItem); + let product_type = + ProductType::from_i32(item_type_raw as i32).unwrap_or(ProductType::MiscItem); - let item_id = cursor.read_i16::().unwrap(); - products.push((i as i16, product_type, item_id)); - } + let item_id = cursor.read_i16::().unwrap(); + products.push((i as i16, product_type, item_id)); } // text @@ -205,18 +199,16 @@ impl Extractor for Store { writer.write_all(&name_buf)?; writer.write_i32::(record.inn_night_cost)?; - if record.inn_night_cost > 0 { - writer.write_all(&[0u8; 144])?; - } else { - writer.write_i16::(record.price_modifier)?; - let mut prod_buf = [0u8; 142]; + writer.write_i16::(record.price_modifier)?; + let mut prod_buf = [0u8; 142]; + { let mut cursor = Cursor::new(&mut prod_buf[..]); for prod in &record.products { cursor.write_i16::(i32::from(prod.1) as i16)?; // type cursor.write_i16::(prod.2)?; // id } - writer.write_all(&prod_buf)?; } + writer.write_all(&prod_buf)?; let write_str = |w: &mut dyn Write, text: &str, max_len: usize| -> std::io::Result<()> { @@ -345,4 +337,66 @@ mod tests { Store::to_writer(&records, &mut out).unwrap(); assert_eq!(out, data); } + + fn shop_record_with_products( + name: &str, + night_cost: i32, + price_modifier: i16, + products: &[(i16, i16)], + ) -> Vec { + let mut rec = Vec::with_capacity(948); + rec.extend(encode_str_w1250(name, 32)); + rec.extend_from_slice(&night_cost.to_le_bytes()); + rec.extend_from_slice(&price_modifier.to_le_bytes()); + let mut slots = [0u8; 142]; + { + let mut cursor = Cursor::new(&mut slots[..]); + for (item_type, item_id) in products { + cursor.write_i16::(*item_type).unwrap(); + cursor.write_i16::(*item_id).unwrap(); + } + } + rec.extend_from_slice(&slots); + rec.extend(encode_str_w1250("Welcome!", 512)); + rec.extend(encode_str_w1250("Sure!", 128)); + rec.extend(encode_str_w1250("No.", 128)); + assert_eq!(rec.len(), 948); + rec + } + + #[test] + fn test_lodging_store_preserves_products() { + let products = [(2i16, 11i16), (4, 27), (1, 5)]; + let mut data = 2i32.to_le_bytes().to_vec(); + data.extend(shop_record_with_products( + "Mistvale Lodge", + 60, + 7, + &products, + )); + data.extend(shop_record_with_products( + "Duskhaven Shop", + 0, + -3, + &products, + )); + + let mut cursor = Cursor::new(&data[..]); + let stores = Store::parse(&mut cursor, data.len() as u64).unwrap(); + assert_eq!(stores.len(), 2); + + let expected: Vec = vec![ + (0, ProductType::Healing, 11), + (1, ProductType::MiscItem, 27), + (2, ProductType::Weapon, 5), + ]; + assert_eq!(stores[0].inn_night_cost, 60); + assert_eq!(stores[0].price_modifier, 7); + assert_eq!(stores[0].products, expected); + assert_eq!(stores[1].products, expected, "ordinary shop is unchanged"); + + let mut out = Vec::new(); + Store::to_writer(&stores, &mut out).unwrap(); + assert_eq!(out, data, "both records round-trip bit-exactly"); + } } From 59a450e18027b6427ed15d5670a3aae5b817bbcc Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:16:27 +0100 Subject: [PATCH 35/72] fix(core): rename terminal frame flag to reset --- dispel-gui/src/editors/extra_ref/component.rs | 2 +- dispel-gui/src/tests/editor_field_edit.rs | 35 ++++++++ dispel-macros/src/record_patcher_impl.rs | 85 +++++++++++++++---- docs/files/ExtraInGame/Extra.ref.md | 4 +- src/references/extra_ref.rs | 23 ++++- 5 files changed, 128 insertions(+), 21 deletions(-) diff --git a/dispel-gui/src/editors/extra_ref/component.rs b/dispel-gui/src/editors/extra_ref/component.rs index 5940b393..fd2fc651 100644 --- a/dispel-gui/src/editors/extra_ref/component.rs +++ b/dispel-gui/src/editors/extra_ref/component.rs @@ -46,7 +46,7 @@ editable_record_fields!(ExtraRef, { { is_quest_element = DispEnum(BooleanFlag, ["True", "False"]) / "Quest Element:" }, { post_activation_tile_flag = DispEnum(BooleanFlag, ["True", "False"]) / "Post-activation tile flag:" }, { post_activation_footprint_mode = DispEnum(BooleanFlag, ["True", "False"]) / "Post-activation footprint mode:" }, - { preserve_final_sprite_frame = Integer / "Preserve final sprite frame:" }, + { reset_to_base_sprite_frame = Integer / "Non-zero resets to the base frame:" }, { alternate_render_mode = DispEnum(BooleanFlag, ["True", "False"]) / "Alternate render mode:" }, { open_sfx_id = Integer / "Open SFX (Wave.ini, 0 = none):" }, { open_sfx_reserved = Integer / "Open SFX reserved:" }, diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index 2127023b..b5b85864 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1009,6 +1009,41 @@ mod modified_flag_routing { } } +// ============================================================================ +// Renamed field labels and stored-key aliases +// ============================================================================ + +mod renamed_field_labels { + use crate::components::editable::EditableRecordGenerated; + use dispel_core::ExtraRef; + + #[test] + fn test_extra_ref_reset_frame_label_accepts_old_key() { + let fields = ExtraRef::__editable_fields(); + let descriptor = fields + .iter() + .find(|field| field.name == "reset_to_base_sprite_frame") + .expect("the reset field must be exposed in the inspector"); + assert_eq!(descriptor.label, "Non-zero resets to the base frame:"); + + let mut value = serde_json::to_value(ExtraRef::default()).unwrap(); + let object = value.as_object_mut().unwrap(); + assert!(object.remove("reset_to_base_sprite_frame").is_some()); + object.insert( + "preserve_final_sprite_frame".to_string(), + serde_json::json!(0), + ); + let restored: ExtraRef = serde_json::from_value(value).unwrap(); + assert!( + serde_json::to_value(&restored) + .unwrap() + .get("reset_to_base_sprite_frame") + .is_some(), + "the stored key must still be accepted" + ); + } +} + // ============================================================================ // Structural edits must mark the tab dirty // ============================================================================ diff --git a/dispel-macros/src/record_patcher_impl.rs b/dispel-macros/src/record_patcher_impl.rs index 903efcec..a8c3e918 100644 --- a/dispel-macros/src/record_patcher_impl.rs +++ b/dispel-macros/src/record_patcher_impl.rs @@ -1,7 +1,9 @@ +use std::collections::HashMap; + use proc_macro2::Span; use proc_macro2::TokenStream as TokenStream2; use quote::quote; -use syn::{DeriveInput, Ident}; +use syn::{DeriveInput, Ident, LitStr}; use crate::schema::{CodegenConfig, FieldInfo, PatcherKey, RecordSchema}; @@ -9,6 +11,37 @@ pub fn expand(input: DeriveInput) -> TokenStream2 { codegen(&input, &CodegenConfig::default()) } +/// Read `#[patcher(field_alias = "old_name")]` from record fields. The alias +/// keeps an existing patcher key working when a field is renamed. +fn field_aliases(input: &DeriveInput) -> HashMap> { + let mut aliases = HashMap::new(); + let syn::Data::Struct(data) = &input.data else { + return aliases; + }; + for field in &data.fields { + let Some(ident) = field.ident.as_ref() else { + continue; + }; + for attr in &field.attrs { + if !attr.path().is_ident("patcher") { + continue; + } + let _ = attr.parse_nested_meta(|meta| { + if meta.path.is_ident("field_alias") { + let value = meta.value()?; + let lit: LitStr = value.parse()?; + aliases + .entry(ident.to_string()) + .or_insert_with(Vec::new) + .push(lit.value()); + } + Ok(()) + }); + } + } + aliases +} + /// Generate the `RecordPatcher` impl from the shared record schema. pub(crate) fn codegen(input: &DeriveInput, config: &CodegenConfig) -> TokenStream2 { let name = &input.ident; @@ -53,14 +86,17 @@ pub(crate) fn codegen(input: &DeriveInput, config: &CodegenConfig) -> TokenStrea // The field grammar comes from the one shared schema parser; the patch // arms below are just another codegen path over that AST. let schema = RecordSchema::parse(input); + let aliases = field_aliases(input); let mut field_arms: Vec = Vec::new(); for info in &schema.fields { let Some(ident) = info.ident() else { continue }; let field_name = ident.to_string(); + let alias_list: &[String] = aliases.get(&field_name).map(Vec::as_slice).unwrap_or(&[]); + let pattern = quote! { #field_name #(| #alias_list)* }; let arm = match info { FieldInfo::Id { .. } | FieldInfo::Index { .. } => quote! { - #field_name => { + #pattern => { return Err(#malformed(format!( "{}.{} is positional and cannot be patched", Self::RECORD_NAME, #field_name @@ -68,16 +104,18 @@ pub(crate) fn codegen(input: &DeriveInput, config: &CodegenConfig) -> TokenStrea } }, FieldInfo::String { ident, .. } => quote! { - #field_name => match new { + #pattern => match new { #value::String(s) => rec.#ident = s.clone(), _ => return Err(#wrong_type( Self::RECORD_NAME, #field_name, "string", new, )), }, }, - FieldInfo::Primitive { ident, ty } => primitive_arm(&field_name, ident, ty, config), + FieldInfo::Primitive { ident, ty } => { + primitive_arm(&pattern, &field_name, ident, ty, config) + } FieldInfo::InventoryItem { ident, .. } => quote! { - #field_name => match new { + #pattern => match new { #value::I64(v) => { rec.#ident = i32::try_from(*v) .map_err(|_| #wrong_type( @@ -97,26 +135,26 @@ pub(crate) fn codegen(input: &DeriveInput, config: &CodegenConfig) -> TokenStrea }, }, FieldInfo::EnumFromU8 { ident, enum_ty } => { - enum_arm(&field_name, ident, enum_ty, "u8", config) + enum_arm(&pattern, &field_name, ident, enum_ty, "u8", config) } FieldInfo::EnumFromU32 { ident, enum_ty } => { - enum_arm(&field_name, ident, enum_ty, "u32", config) + enum_arm(&pattern, &field_name, ident, enum_ty, "u32", config) } FieldInfo::EnumFromI16 { ident, enum_ty } => { - enum_arm(&field_name, ident, enum_ty, "i16", config) + enum_arm(&pattern, &field_name, ident, enum_ty, "i16", config) } FieldInfo::EnumFromI32 { ident, enum_ty } => { - enum_arm(&field_name, ident, enum_ty, "i32", config) + enum_arm(&pattern, &field_name, ident, enum_ty, "i32", config) } FieldInfo::EnumFromI32FromU8 { ident, enum_ty } => { - enum_arm(&field_name, ident, enum_ty, "u8", config) + enum_arm(&pattern, &field_name, ident, enum_ty, "u8", config) } FieldInfo::Array { ident, size, ty } => { if ty != "u8" { panic!("RecordPatcher only supports array(type = \"u8\")"); } quote! { - #field_name => match new { + #pattern => match new { #value::Bytes(b) if b.len() == #size => { let mut arr = [0u8; #size]; arr.copy_from_slice(b); @@ -137,7 +175,7 @@ pub(crate) fn codegen(input: &DeriveInput, config: &CodegenConfig) -> TokenStrea } } FieldInfo::VecU8 { ident, size } => quote! { - #field_name => match new { + #pattern => match new { #value::Bytes(b) if b.len() == #size => { rec.#ident = b.clone(); } @@ -155,7 +193,7 @@ pub(crate) fn codegen(input: &DeriveInput, config: &CodegenConfig) -> TokenStrea }, }, FieldInfo::Padding { .. } => quote! { - #field_name => { + #pattern => { return Err(#malformed(format!( "{}.{} is synthetic padding and cannot be patched", Self::RECORD_NAME, #field_name @@ -224,6 +262,7 @@ pub(crate) fn codegen(input: &DeriveInput, config: &CodegenConfig) -> TokenStrea /// `Value::I64` (range-checked), `Value::F64` for `f` types (none yet), /// and `Value::String` (parsed) so recording-mode stringly deltas work. fn primitive_arm( + pattern: &TokenStream2, field_name: &str, ident: &Ident, ty: &str, @@ -234,7 +273,7 @@ fn primitive_arm( let value = config.modding(&["value", "Value"]); let wrong_type = config.modding(&["patcher", "wrong_type"]); quote! { - #field_name => match new { + #pattern => match new { #value::I64(v) => { rec.#ident = #ty_ident::try_from(*v).map_err(|_| #wrong_type( Self::RECORD_NAME, #field_name, #expected, new, @@ -258,6 +297,7 @@ fn primitive_arm( /// type). Both routes use the same `WireValue::from_wire` fallback as the /// parse side in `Extractor`. fn enum_arm( + pattern: &TokenStream2, field_name: &str, ident: &Ident, enum_ty: &str, @@ -274,7 +314,7 @@ fn enum_arm( let value = config.modding(&["value", "Value"]); let wrong_type = config.modding(&["patcher", "wrong_type"]); quote! { - #field_name => match new { + #pattern => match new { #value::I64(v) => { let wire = #wire_ident::try_from(*v).map_err(|_| #wrong_type( Self::RECORD_NAME, #field_name, #expected, new, @@ -325,6 +365,21 @@ mod tests { assert!(tokens.contains("pub const FILENAME : & 'static str = \"Sample.db\"")); } + #[test] + fn test_generated_patcher_keeps_field_alias_key() { + let input: DeriveInput = parse_quote! { + #[extractor(property_item_size = 4)] + #[patcher(filename = "Sample.db")] + struct Sample { + #[extractor(primitive(type = "i32"))] + #[patcher(field_alias = "old_value")] + value: i32, + } + }; + let tokens = codegen(&input, &CodegenConfig::default()).to_string(); + assert!(tokens.contains("\"value\" | \"old_value\" =>"), "{tokens}"); + } + #[test] fn test_generated_patcher_emits_alias_filename_consts() { let input: DeriveInput = parse_quote! { diff --git a/docs/files/ExtraInGame/Extra.ref.md b/docs/files/ExtraInGame/Extra.ref.md index a8f53723..324b1a71 100644 --- a/docs/files/ExtraInGame/Extra.ref.md +++ b/docs/files/ExtraInGame/Extra.ref.md @@ -68,7 +68,7 @@ items) on specific maps. Each map has its own `Ext*.ref` file containing all int - is_quest_element: i32 (requests a quest-state refresh after a successful requirement check) - post_activation_tile_flag: i32 (enables a post-activation map-grid tile flag) - post_activation_footprint_mode: i32 (selects the post-activation map-grid footprint update mode) -- preserve_final_sprite_frame: i32 (prevents the terminal sprite frame from being reset after interaction) +- reset_to_base_sprite_frame: i32 (non-zero resets to the base frame after interaction) - alternate_render_mode: i32 (selects the alternative object renderer) - open_sfx_id: u8 (record +0xAC; Wave.ini index played by `extra_play_open_sfx` on activation; 0 = none) - open_sfx_reserved: u8 (reserved; preserve verbatim) @@ -124,7 +124,7 @@ The seven words from `additional_loot_2_count` through `use_counter` hold the tr |--------------------------------|-------------|-----------------------------------------------------------------------| | post_activation_tile_flag | BooleanFlag | Enables the post-activation tile flag written to the map-object grid. | | post_activation_footprint_mode | BooleanFlag | Selects the footprint update mode after activation. | -| preserve_final_sprite_frame | i32 | Non-zero keeps the terminal sprite frame after interaction. | +| reset_to_base_sprite_frame | i32 | Non-zero resets to the base frame after interaction. | | alternate_render_mode | BooleanFlag | Selects the alternate renderer. | | active_overlay_enabled | BooleanFlag | Enables the active-object overlay render path. | | map_object_active | BooleanFlag | Makes the object participate in the map-object grid and update loop. | diff --git a/src/references/extra_ref.rs b/src/references/extra_ref.rs index ddafbedf..50b1774c 100644 --- a/src/references/extra_ref.rs +++ b/src/references/extra_ref.rs @@ -173,9 +173,11 @@ pub struct ExtraRef { /// Selects the post-activation footprint update mode in the map-object grid. #[extractor(enum_from_i32(type = "BooleanFlag"))] pub post_activation_footprint_mode: BooleanFlag, - /// Keeps the object's terminal sprite frame instead of resetting it after interaction. + /// Non-zero resets the object to its base sprite frame after interaction. #[extractor(primitive(type = "i32"))] - pub preserve_final_sprite_frame: i32, + #[serde(alias = "preserve_final_sprite_frame")] + #[patcher(field_alias = "preserve_final_sprite_frame")] + pub reset_to_base_sprite_frame: i32, /// Selects the alternate renderer used for this object. #[extractor(enum_from_i32(type = "BooleanFlag"))] pub alternate_render_mode: BooleanFlag, @@ -288,7 +290,7 @@ pub fn save_extra_refs(conn: &mut Connection, file_id: i32, extra_refs: &[ExtraR i32::from(extra_ref.is_quest_element), // 47 i32::from(extra_ref.post_activation_tile_flag), // 48 i32::from(extra_ref.post_activation_footprint_mode), // 49 - extra_ref.preserve_final_sprite_frame, // 50 + extra_ref.reset_to_base_sprite_frame, // 50 i32::from(extra_ref.alternate_render_mode), // 51 extra_ref.open_sfx_id, // 52 extra_ref.open_sfx_reserved, // 53 @@ -354,6 +356,21 @@ mod tests { ); } + #[test] + fn test_legacy_patcher_key_still_resets_frame() { + use crate::modding::patcher::RecordPatcher; + use crate::modding::value::Value; + + let mut data = 1i32.to_le_bytes().to_vec(); + data.extend(ref_bytes("MistvaleChest", 1, 2, 3)); + let out = ExtraRefPatcher + .apply_field(&data, 0, "preserve_final_sprite_frame", &Value::I64(1)) + .expect("the stored patcher key must still be accepted"); + let mut cursor = Cursor::new(&out[..]); + let records = ExtraRef::parse(&mut cursor, out.len() as u64).unwrap(); + assert_eq!(records[0].reset_to_base_sprite_frame, 1); + } + #[test] fn parse_single_ref() { let mut data = 1i32.to_le_bytes().to_vec(); From cdb451ef33d61261e49294336a7e4fd3b268fec0 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:22:53 +0100 Subject: [PATCH 36/72] fix(core): rename weapon durability to modification budget --- dispel-gui/src/editors/weapon/component.rs | 2 +- dispel-gui/src/tests/editor_field_edit.rs | 35 ++++++++++++++++++++- docs/files/CharacterInGame/WeaponItem.db.md | 2 +- src/references/weapons_db.rs | 33 ++++++++++++++----- 4 files changed, 61 insertions(+), 11 deletions(-) diff --git a/dispel-gui/src/editors/weapon/component.rs b/dispel-gui/src/editors/weapon/component.rs index ae239149..3c5cc8e7 100644 --- a/dispel-gui/src/editors/weapon/component.rs +++ b/dispel-gui/src/editors/weapon/component.rs @@ -19,7 +19,7 @@ editable_record_fields!(WeaponItem, { { attack = Integer / "Attack:" }, { defense = Integer / "Defense:" }, { magical_strength = Integer / "Magic Strength:" }, - { durability = Integer / "Durability:" }, + { modification_budget = Integer / "Modification Budget:" }, { reserved_0x108 = Integer / "Reserved (0x108):" }, { reserved_0x10a = Integer / "Reserved (0x10A):" }, { req_strength = Integer / "Required STR:" }, diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index b5b85864..9e750b83 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1015,7 +1015,40 @@ mod modified_flag_routing { mod renamed_field_labels { use crate::components::editable::EditableRecordGenerated; - use dispel_core::ExtraRef; + use dispel_core::{ExtraRef, Extractor, WeaponItem}; + + #[test] + fn test_weapon_modification_budget_label_accepts_old_key() { + let descriptor = WeaponItem::__editable_fields() + .iter() + .find(|field| field.name == "modification_budget") + .expect("the workshop budget must be exposed in the inspector"); + assert_eq!(descriptor.label, "Modification Budget:"); + + let mut bytes = Vec::new(); + WeaponItem::to_writer( + &[WeaponItem { + name: "Mistvale Blade".into(), + ..Default::default() + }], + &mut bytes, + ) + .unwrap(); + let mut cursor = std::io::Cursor::new(&bytes); + let records = WeaponItem::parse(&mut cursor, bytes.len() as u64).unwrap(); + let mut value = serde_json::to_value(&records[0]).unwrap(); + let object = value.as_object_mut().unwrap(); + assert!(object.remove("modification_budget").is_some()); + object.insert("durability".to_string(), serde_json::json!(5)); + let restored: WeaponItem = serde_json::from_value(value).unwrap(); + assert_eq!( + serde_json::to_value(&restored) + .unwrap() + .get("modification_budget") + .and_then(|v| v.as_i64()), + Some(5) + ); + } #[test] fn test_extra_ref_reset_frame_label_accepts_old_key() { diff --git a/docs/files/CharacterInGame/WeaponItem.db.md b/docs/files/CharacterInGame/WeaponItem.db.md index f64b0e9a..019b1665 100644 --- a/docs/files/CharacterInGame/WeaponItem.db.md +++ b/docs/files/CharacterInGame/WeaponItem.db.md @@ -27,7 +27,7 @@ Known files store zero at offset 236. The tool reads this word as `weapon_item_i | 256 | 2 | i16 | `attack` | Attack bonus | | 258 | 2 | i16 | `defense` | Defence bonus | | 260 | 2 | i16 | `magical_strength` | Magic-power bonus | -| 262 | 2 | i16 | `durability` | Item durability | +| 262 | 2 | i16 | `modification_budget` | Remaining workshop modification budget | | 264 | 2 | i16 | `reserved_0x108` | Reserved; zero by default | | 266 | 2 | i16 | `reserved_0x10a` | Reserved; zero by default | | 268 | 2 | i16 | `req_strength` | Minimum strength | diff --git a/src/references/weapons_db.rs b/src/references/weapons_db.rs index 79185e18..c6966ca8 100644 --- a/src/references/weapons_db.rs +++ b/src/references/weapons_db.rs @@ -44,7 +44,7 @@ use serde::{Deserialize, Serialize}; /// | - attack: i16 (offense) | /// | - defense: i16 (armor class) | /// | - magical_strength: i16 (magical) | -/// | - durability: i16 (item HP) | +/// | - modification_budget: i16 (budget) | /// | - reserved_0x108: i16 | /// | - reserved_0x10a: i16 | /// | - req_strength: i16 (requirement) | @@ -66,7 +66,7 @@ use serde::{Deserialize, Serialize}; /// - **Stat Modifiers**: `health_points`, `mana_points`, `strength`, `agility`, `wisdom`, `constitution` /// - **Combat Stats**: `to_dodge` (evasion), `to_hit` (accuracy), `attack` (offense), `defense` (armor) /// - **Magical**: `magical_strength` (magical power) -/// - **Durability**: `durability` (item HP/wear limit) +/// - **Workshop**: `modification_budget` (remaining modification budget) /// - **Requirements**: `req_strength`, `req_agility`, `req_wisdom` (minimum stats to equip) /// - **Runtime identity**: `weapon_item_id` is overwritten with the zero-based /// record index at load time. @@ -77,7 +77,7 @@ use serde::{Deserialize, Serialize}; /// # Special Values /// /// - `base_price`: i32 economic value -/// - `durability`: Item health points before destruction +/// - `modification_budget`: remaining workshop budget /// - `weapon_item_id`: Runtime-only ID; the on-disk value is ignored and replaced /// with the record index when the database loads. /// - `reserved_0x*`: Preserved 16-bit values. All are zero by default. @@ -86,7 +86,7 @@ use serde::{Deserialize, Serialize}; /// # File Purpose /// /// Defines weapons and armor with stat modifications, -/// requirements, and durability. Used for equipment +/// requirements, and the modification budget. Used for equipment /// system, character progression, and combat mechanics. #[derive( Debug, @@ -155,9 +155,11 @@ pub struct WeaponItem { /// Enhanced magical defense/offense. #[extractor(primitive(type = "i16"))] pub magical_strength: i16, - /// Item health points or wear limit. + /// Remaining workshop modification budget. #[extractor(primitive(type = "i16"))] - pub durability: i16, + #[serde(alias = "durability")] + #[patcher(field_alias = "durability")] + pub modification_budget: i16, /// Reserved serialized word at byte offset `0x108`. It is zero by default /// with no observed reader. #[extractor(padding(count = 1, type = "i16"))] @@ -217,7 +219,7 @@ pub fn save_weapons(conn: &mut Connection, weapons: &[WeaponItem]) -> Result<()> weapon.attack, weapon.defense, weapon.magical_strength, - weapon.durability, + weapon.modification_budget, weapon.reserved_0x108, weapon.reserved_0x10a, weapon.req_strength, @@ -251,10 +253,25 @@ mod tests { rec.extend(vec![0u8; 8]); // hp, mp, str, agi rec.extend(vec![0u8; 8]); // wis, con, dodge, to_hit rec.extend_from_slice(&attack.to_le_bytes()); - rec.extend(vec![0u8; 26]); // defense, magical_str, durability, pads, reqs + rec.extend(vec![0u8; 26]); // defense, magical_str, budget, pads, reqs rec } + #[test] + fn test_legacy_patcher_key_sets_modification_budget() { + use crate::modding::patcher::RecordPatcher; + use crate::modding::value::Value; + + let mut data = 1i32.to_le_bytes().to_vec(); + data.extend(weapon_bytes("MistvaleBlade", 100, 3, 12)); + let out = WeaponItemPatcher + .apply_field(&data, 0, "durability", &Value::I64(25)) + .expect("the stored patcher key must still be accepted"); + let mut cursor = Cursor::new(&out[..]); + let records = WeaponItem::parse(&mut cursor, out.len() as u64).unwrap(); + assert_eq!(records[0].modification_budget, 25); + } + #[test] fn parse_single_weapon() { let mut data = 1i32.to_le_bytes().to_vec(); From c2add44c1b84bbdb3523c2ef4939bbcde21579e0 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:30:41 +0100 Subject: [PATCH 37/72] fix(core): rename magic targeting mode to animation cycles --- dispel-gui/src/editors/magic/component.rs | 4 +-- dispel-gui/src/tests/editor_field_edit.rs | 34 ++++++++++++++++++-- dispel-gui/src/tests/select_boxes.rs | 3 +- docs/files/MagicInGame/Magic.db.md | 2 +- src/references/magic_db.rs | 38 ++++++++++++++++------- 5 files changed, 63 insertions(+), 18 deletions(-) diff --git a/dispel-gui/src/editors/magic/component.rs b/dispel-gui/src/editors/magic/component.rs index bf03169b..437e3f65 100644 --- a/dispel-gui/src/editors/magic/component.rs +++ b/dispel-gui/src/editors/magic/component.rs @@ -1,5 +1,5 @@ use crate::components::editable::EditableRecord; -use dispel_core::{MagicSpell, MagicSpellFlag, MagicType, SpellTargetType}; +use dispel_core::{MagicSpell, MagicSpellFlag, MagicType}; use crate::editable_record_fields; @@ -25,7 +25,7 @@ editable_record_fields!(MagicSpell, { { animation_set_id = Integer / "Animation Set ID:" }, { effect_visual_id = Integer / "Effect Visual ID:" }, { icon_id = Integer / "Icon ID:" }, - { targeting_mode = Enum(SpellTargetType, ["Single", "SelfTarget", "AreaOfEffect", "MultiTarget"]) / "Targeting Mode:" }, + { target_animation_cycles = Integer / "Target FX Cycles:" }, }); impl EditableRecord for MagicSpell { diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index 9e750b83..a93cd23a 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1014,8 +1014,38 @@ mod modified_flag_routing { // ============================================================================ mod renamed_field_labels { - use crate::components::editable::EditableRecordGenerated; - use dispel_core::{ExtraRef, Extractor, WeaponItem}; + use crate::components::editable::{EditableRecordGenerated, FieldKind}; + use dispel_core::{ExtraRef, Extractor, MagicSpell, WeaponItem}; + + #[test] + fn test_magic_animation_cycles_is_an_integer_field() { + let descriptor = MagicSpell::__editable_fields() + .iter() + .find(|field| field.name == "target_animation_cycles") + .expect("the animation cycle count must be exposed in the inspector"); + assert_eq!(descriptor.label, "Target FX Cycles:"); + assert!( + matches!(descriptor.kind, FieldKind::Integer), + "the cycle count is a number, not a pick list" + ); + + let mut bytes = vec![0u8; 88]; + bytes[84..88].copy_from_slice(&7u32.to_le_bytes()); + let mut cursor = std::io::Cursor::new(&bytes); + let spells = MagicSpell::parse(&mut cursor, bytes.len() as u64).unwrap(); + let mut value = serde_json::to_value(&spells[0]).unwrap(); + let object = value.as_object_mut().unwrap(); + assert!(object.remove("target_animation_cycles").is_some()); + object.insert("targeting_mode".to_string(), serde_json::json!(7)); + let restored: MagicSpell = serde_json::from_value(value).unwrap(); + assert_eq!( + serde_json::to_value(&restored) + .unwrap() + .get("target_animation_cycles") + .and_then(|v| v.as_u64()), + Some(7) + ); + } #[test] fn test_weapon_modification_budget_label_accepts_old_key() { diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs index 6a782aee..3c67ee85 100644 --- a/dispel-gui/src/tests/select_boxes.rs +++ b/dispel-gui/src/tests/select_boxes.rs @@ -16,7 +16,7 @@ use dispel_core::{ EditItemModification, Event, EventNpcRef, EventType, ExtraObjectType, ExtraRef, HealItem, HealItemFlag, MagicSpell, MagicSpellFlag, MagicType, Map, MapLighting, Monster, MonsterAiType, MonsterRef, MonsterSpawn, NPC, NpcInteractionMode, NpcLookingDirection, NpcMovementMode, - NpcRoleResult, SmallRange0to3, SpellTargetType, + NpcRoleResult, SmallRange0to3, }; use super::common::{activate_select_option, filter_select, select_shows, select_values}; @@ -464,7 +464,6 @@ fn test_every_enum_field_round_trips_through_both_views() { audit_enum::("modifies_item", DebugFormat); audit_enum::("additional_effect", DebugFormat); audit_enum::("magic_type", DebugFormat); - audit_enum::("targeting_mode", DebugFormat); audit_enum::("enabled", DebugFormat); } diff --git a/docs/files/MagicInGame/Magic.db.md b/docs/files/MagicInGame/Magic.db.md index 5707d26b..53809ce4 100644 --- a/docs/files/MagicInGame/Magic.db.md +++ b/docs/files/MagicInGame/Magic.db.md @@ -31,7 +31,7 @@ All fields are little-endian `u32` values. The record ID is its zero-based posit | 72 | `animation_set_id` | Cast-animation set | | 76 | `effect_visual_id` | Visual/projectile mapping selected when casting | | 80 | `icon_id` | UI icon ID (inferred from its use as a UI-facing ID) | -| 84 | `targeting_mode` | Targeting-mode configuration; exact value meanings need confirmation | +| 84 | `target_animation_cycles` | Number of times the stationary target animation cycles | ## Field semantics diff --git a/src/references/magic_db.rs b/src/references/magic_db.rs index f793b5c9..01cea6b7 100644 --- a/src/references/magic_db.rs +++ b/src/references/magic_db.rs @@ -1,6 +1,6 @@ use std::path::Path; -use crate::references::enums::{MagicSpellFlag, MagicType, SpellTargetType}; +use crate::references::enums::{MagicSpellFlag, MagicType}; use crate::references::extractor::Extractor; use dispel_macros::{Extractor, RecordLayout, RecordPatcher}; use rusqlite::{Connection, Result, params}; @@ -49,7 +49,7 @@ use serde::{Deserialize, Serialize}; /// | - animation_set_id: u32 | /// | - effect_visual_id: u32 | /// | - icon_id: u32 | -/// | - targeting_mode: u32 (SpellTargetType)| +/// | - target_animation_cycles: u32 (FX count)| /// +--------------------------------------+ /// | [Record 2] | /// | ... (same structure) ... | @@ -168,9 +168,11 @@ pub struct MagicSpell { #[extractor(primitive(type = "u32"))] pub icon_id: u32, - /// Targeting-mode configuration. Exact values need further confirmation. - #[extractor(enum_from_u32(type = "SpellTargetType"))] - pub targeting_mode: SpellTargetType, + /// Number of times the stationary target animation cycles. + #[extractor(primitive(type = "u32"))] + #[serde(alias = "targeting_mode")] + #[patcher(field_alias = "targeting_mode")] + pub target_animation_cycles: u32, } pub fn read_magic_db(source_path: &Path) -> std::io::Result> { @@ -205,7 +207,7 @@ pub fn save_magic_spells(conn: &mut Connection, spells: &[MagicSpell]) -> Result spell.animation_set_id, spell.effect_visual_id, spell.icon_id, - u32::from(spell.targeting_mode), + spell.target_animation_cycles, ])?; } } @@ -226,11 +228,11 @@ impl std::fmt::Display for MagicSpell { #[cfg(test)] mod tests { use super::*; - use crate::references::enums::{MagicType, SpellTargetType}; + use crate::references::enums::MagicType; use std::io::Cursor; - fn spell_bytes(base_damage: u32, mana_cost: u32, targeting_mode: u32) -> Vec { + fn spell_bytes(base_damage: u32, mana_cost: u32, target_animation_cycles: u32) -> Vec { let fields: [u32; 22] = [ 1, // enabled 1, // effect_visual_blends_with_background @@ -253,11 +255,25 @@ mod tests { 1, // animation_set_id 2, // effect_visual_id 3, // icon_id - targeting_mode, + target_animation_cycles, ]; fields.iter().flat_map(|&v| v.to_le_bytes()).collect() } + #[test] + fn test_legacy_patcher_key_sets_animation_cycles() { + use crate::modding::patcher::RecordPatcher; + use crate::modding::value::Value; + + let data = spell_bytes(20, 50, 1); + let out = MagicSpellPatcher + .apply_field(&data, 0, "targeting_mode", &Value::I64(7)) + .expect("the stored patcher key must still be accepted"); + let mut cursor = Cursor::new(&out[..]); + let spells = MagicSpell::parse(&mut cursor, out.len() as u64).unwrap(); + assert_eq!(spells[0].target_animation_cycles, 7); + } + #[test] fn parse_single_spell() { let data = spell_bytes(20, 50, 1); @@ -272,7 +288,7 @@ mod tests { assert_eq!(spells[0].base_damage, 20); assert_eq!(spells[0].mana_cost, 50); assert_eq!(spells[0].magic_type, MagicType::HolyMagic); - assert_eq!(spells[0].targeting_mode, SpellTargetType::Single); + assert_eq!(spells[0].target_animation_cycles, 1); } #[test] @@ -287,7 +303,7 @@ mod tests { assert_eq!(spells.len(), 2); assert_eq!(spells[0].mana_cost, 30); assert_eq!(spells[1].mana_cost, 80); - assert_eq!(spells[1].targeting_mode, SpellTargetType::AreaOfEffect); + assert_eq!(spells[1].target_animation_cycles, 3); } #[test] From 531ad1bc20352de58eca669ae7909553bdce2f79 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:33:40 +0100 Subject: [PATCH 38/72] docs(gui): describe magic range as target power cap --- dispel-gui/src/editors/magic/component.rs | 2 +- dispel-gui/src/tests/editor_field_edit.rs | 9 +++++++++ docs/files/MagicInGame/Magic.db.md | 2 +- src/references/magic_db.rs | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/dispel-gui/src/editors/magic/component.rs b/dispel-gui/src/editors/magic/component.rs index 437e3f65..18b48463 100644 --- a/dispel-gui/src/editors/magic/component.rs +++ b/dispel-gui/src/editors/magic/component.rs @@ -12,7 +12,7 @@ editable_record_fields!(MagicSpell, { { reserved_0x14 = Integer / "Reserved (0x14):" }, { reserved_0x18 = Integer / "Reserved (0x18):" }, { effect_animation_repeats = Boolean / "Effect Animation Repeats:" }, - { range = Integer / "Range:" }, + { range = Integer / "Max Target Magic Power:" }, { reserved_0x24 = Integer / "Reserved (0x24):" }, { cast_duration = Integer / "Cast Duration:" }, { animation_data_index = Integer / "Animation Data Index:" }, diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index a93cd23a..d2e0a2ff 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1017,6 +1017,15 @@ mod renamed_field_labels { use crate::components::editable::{EditableRecordGenerated, FieldKind}; use dispel_core::{ExtraRef, Extractor, MagicSpell, WeaponItem}; + #[test] + fn test_magic_range_label_describes_target_power_cap() { + let descriptor = MagicSpell::__editable_fields() + .iter() + .find(|field| field.name == "range") + .expect("range stays an editable field"); + assert_eq!(descriptor.label, "Max Target Magic Power:"); + } + #[test] fn test_magic_animation_cycles_is_an_integer_field() { let descriptor = MagicSpell::__editable_fields() diff --git a/docs/files/MagicInGame/Magic.db.md b/docs/files/MagicInGame/Magic.db.md index 53809ce4..77bea6d2 100644 --- a/docs/files/MagicInGame/Magic.db.md +++ b/docs/files/MagicInGame/Magic.db.md @@ -20,7 +20,7 @@ All fields are little-endian `u32` values. The record ID is its zero-based posit | 16 | `mana_cost` | Base mana cost before skill reduction; effective cost is at least 5 | | 20, 24 | `reserved_0x14`, `reserved_0x18` | Reserved words; zero by default | | 28 | `effect_animation_repeats` | `0`=Off, `1`=On — repeats the target-effect animation while the target remains valid | -| 32 | `range` | Maximum target distance checked by casting code | +| 32 | `range` | Maximum magic power a target may have for the spell to affect it | | 36 | `reserved_0x24` | Reserved word; zero by default | | 40 | `cast_duration` | Maximum casting/action progress counter | | 44 | `animation_data_index` | Index into the animation data table, resolved to a pointer after file load | diff --git a/src/references/magic_db.rs b/src/references/magic_db.rs index 01cea6b7..5a86fce2 100644 --- a/src/references/magic_db.rs +++ b/src/references/magic_db.rs @@ -112,7 +112,7 @@ pub struct MagicSpell { #[extractor(primitive(type = "u32"))] pub effect_animation_repeats: u32, - /// Maximum target distance checked by the casting code. + /// Maximum magic power a target may have for the spell to affect it. #[extractor(primitive(type = "u32"))] pub range: u32, From c779da28b84b5649f6fb61393868bd45626ee0b2 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:39:17 +0100 Subject: [PATCH 39/72] fix(core): rename monster walk speed to attack cooldown --- dispel-gui/src/editors/monster/component.rs | 2 +- dispel-gui/src/tests/editor_field_edit.rs | 35 ++++++++++++++++++++- docs/files/MonsterInGame/Monster.db.md | 6 ++-- src/references/monster_db.rs | 30 +++++++++++++++--- 4 files changed, 63 insertions(+), 10 deletions(-) diff --git a/dispel-gui/src/editors/monster/component.rs b/dispel-gui/src/editors/monster/component.rs index 654e965d..07d050b9 100644 --- a/dispel-gui/src/editors/monster/component.rs +++ b/dispel-gui/src/editors/monster/component.rs @@ -8,7 +8,7 @@ crate::editable_record_fields!(Monster, { { health_points_min = Integer / "HP Min:" }, { mana_points_max = Integer / "MP Max:" }, { mana_points_min = Integer / "MP Min:" }, - { walk_speed = Integer / "Walk Speed:" }, + { attack_cooldown_ticks = Integer / "Attack Cooldown Ticks:" }, { to_hit_max = Integer / "To Hit Max:" }, { to_hit_min = Integer / "To Hit Min:" }, { to_dodge_max = Integer / "Dodge Max:" }, diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index d2e0a2ff..a6ae408f 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1015,7 +1015,40 @@ mod modified_flag_routing { mod renamed_field_labels { use crate::components::editable::{EditableRecordGenerated, FieldKind}; - use dispel_core::{ExtraRef, Extractor, MagicSpell, WeaponItem}; + use dispel_core::{ExtraRef, Extractor, MagicSpell, Monster, WeaponItem}; + + #[test] + fn test_monster_attack_cooldown_label_accepts_old_key() { + let descriptor = Monster::__editable_fields() + .iter() + .find(|field| field.name == "attack_cooldown_ticks") + .expect("the cooldown must be exposed in the inspector"); + assert_eq!(descriptor.label, "Attack Cooldown Ticks:"); + + let mut bytes = Vec::new(); + Monster::to_writer( + &[Monster { + name: "MistvaleWolf".into(), + ..Default::default() + }], + &mut bytes, + ) + .unwrap(); + let mut cursor = std::io::Cursor::new(&bytes); + let records = Monster::parse(&mut cursor, bytes.len() as u64).unwrap(); + let mut value = serde_json::to_value(&records[0]).unwrap(); + let object = value.as_object_mut().unwrap(); + assert!(object.remove("attack_cooldown_ticks").is_some()); + object.insert("walk_speed".to_string(), serde_json::json!(9)); + let restored: Monster = serde_json::from_value(value).unwrap(); + assert_eq!( + serde_json::to_value(&restored) + .unwrap() + .get("attack_cooldown_ticks") + .and_then(|v| v.as_i64()), + Some(9) + ); + } #[test] fn test_magic_range_label_describes_target_power_cap() { diff --git a/docs/files/MonsterInGame/Monster.db.md b/docs/files/MonsterInGame/Monster.db.md index bc44cf55..922b4fc2 100644 --- a/docs/files/MonsterInGame/Monster.db.md +++ b/docs/files/MonsterInGame/Monster.db.md @@ -26,7 +26,7 @@ The tool reads `Monster.db` as fixed-size monster records. Each record holds a n - health_points_min: i32 - mana_points_max: i32 - mana_points_min: i32 -- walk_speed: i32 +- attack_cooldown_ticks: i32 - to_hit_max: i32 - to_hit_min: i32 - to_dodge_max: i32 @@ -68,7 +68,7 @@ The tool reads `Monster.db` as fixed-size monster records. Each record holds a n | health_points_min | 4 | i32 | Minimum HP floor | | mana_points_max | 4 | i32 | Maximum MP limit | | mana_points_min | 4 | i32 | Minimum MP limit | -| walk_speed | 4 | i32 | Baseline tiles moved per tick | +| attack_cooldown_ticks | 4 | i32 | Attack cooldown in ticks | | to_hit_max | 4 | i32 | Upper bound of accuracy | | to_hit_min | 4 | i32 | Lower bound of accuracy | | to_dodge_max | 4 | i32 | Upper bound for evasion rate | @@ -128,7 +128,7 @@ pub struct Monster { health_points_min: i32, // Minimum HP mana_points_max: i32, // Maximum MP mana_points_min: i32, // Minimum MP - walk_speed: i32, // Movement speed + attack_cooldown_ticks: i32, // Attack cooldown in ticks to_hit_max: i32, // Max accuracy to_hit_min: i32, // Min accuracy to_dodge_max: i32, // Max evasion (usually 10) diff --git a/src/references/monster_db.rs b/src/references/monster_db.rs index 821c86b4..bbe8ef59 100644 --- a/src/references/monster_db.rs +++ b/src/references/monster_db.rs @@ -34,7 +34,7 @@ use serde::{Deserialize, Serialize}; /// | - health_points_min: i32 | /// | - mana_points_max: i32 | /// | - mana_points_min: i32 | -/// | - walk_speed: i32 | +/// | - attack_cooldown_ticks: i32 | /// | - to_hit_max: i32 | /// | - to_hit_min: i32 | /// | - to_dodge_max: i32 | @@ -124,9 +124,11 @@ pub struct Monster { /// Minimum MP limit. #[extractor(primitive(type = "i32"))] pub mana_points_min: i32, - /// Baseline tiles moved per tick. + /// Attack cooldown measured in ticks. #[extractor(primitive(type = "i32"))] - pub walk_speed: i32, + #[serde(alias = "walk_speed")] + #[patcher(field_alias = "walk_speed")] + pub attack_cooldown_ticks: i32, /// Upper bound of accuracy. #[extractor(primitive(type = "i32"))] pub to_hit_max: i32, @@ -236,7 +238,7 @@ pub fn save_monsters(conn: &mut Connection, monsters: &[Monster]) -> Result<()> monster.health_points_min, monster.mana_points_max, monster.mana_points_min, - monster.walk_speed, + monster.attack_cooldown_ticks, monster.to_hit_max, monster.to_hit_min, monster.to_dodge_max, @@ -310,13 +312,31 @@ mod tests { buf } + #[test] + fn test_legacy_patcher_key_sets_attack_cooldown() { + use crate::modding::patcher::RecordPatcher; + use crate::modding::value::Value; + + let stats = [0i32; 34]; + let mut data = monster_bytes("MistvaleWolf", &stats); + let mut framed = Vec::new(); + framed.extend_from_slice(&1i32.to_le_bytes()); + framed.append(&mut data); + let out = MonsterPatcher + .apply_field(&framed, 0, "walk_speed", &Value::I64(9)) + .expect("the stored patcher key must still be accepted"); + let mut cursor = Cursor::new(&out[..]); + let records = Monster::parse(&mut cursor, out.len() as u64).unwrap(); + assert_eq!(records[0].attack_cooldown_ticks, 9); + } + #[test] fn parse_single_record() { #[rustfmt::skip] let stats: [i32; 34] = [ 100, 80, // hp max/min 50, 30, // mp max/min - 5, // walk_speed + 5, // attack cooldown 70, 60, // to_hit max/min 10, 10, // to_dodge max/min 20, 15, // offense max/min From 0b1c844b139a360849e9bfd0b3d861141aa2a3e2 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:50:18 +0100 Subject: [PATCH 40/72] fix(core): rename magic enabled to requires target --- dispel-gui/src/editors/magic/component.rs | 4 +- dispel-gui/src/tests/editor_field_edit.rs | 36 +++++++++++ dispel-gui/src/tests/select_boxes.rs | 8 +-- docs/files/MagicInGame/Magic.db.md | 2 +- src/references/enums.rs | 73 +++++++++++++---------- src/references/magic_db.rs | 36 ++++++++--- 6 files changed, 114 insertions(+), 45 deletions(-) diff --git a/dispel-gui/src/editors/magic/component.rs b/dispel-gui/src/editors/magic/component.rs index 18b48463..69de0414 100644 --- a/dispel-gui/src/editors/magic/component.rs +++ b/dispel-gui/src/editors/magic/component.rs @@ -1,10 +1,10 @@ use crate::components::editable::EditableRecord; -use dispel_core::{MagicSpell, MagicSpellFlag, MagicType}; +use dispel_core::{MagicSpell, MagicType, TargetSelectionFlag}; use crate::editable_record_fields; editable_record_fields!(MagicSpell, { - { enabled = Enum(MagicSpellFlag, ["Disabled", "Enabled"]) / "Enabled:" }, + { requires_target = Enum(TargetSelectionFlag, ["NotRequired", "Required"]) / "Requires Target:" }, { effect_visual_blends_with_background = Boolean / "Effect Visual Blends:" }, { base_damage = Integer / "Base Damage:" }, { base_success_rate = Integer / "Base Success Rate:" }, diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index a6ae408f..bae8d603 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1017,6 +1017,42 @@ mod renamed_field_labels { use crate::components::editable::{EditableRecordGenerated, FieldKind}; use dispel_core::{ExtraRef, Extractor, MagicSpell, Monster, WeaponItem}; + #[test] + fn test_magic_requires_target_flag_accepts_old_names() { + let descriptor = MagicSpell::__editable_fields() + .iter() + .find(|field| field.name == "requires_target") + .expect("the targeting flag must be exposed in the inspector"); + assert_eq!(descriptor.label, "Requires Target:"); + + let mut cursor = std::io::Cursor::new(vec![0u8; 88]); + let spells = MagicSpell::parse(&mut cursor, 88).unwrap(); + let mut value = serde_json::to_value(&spells[0]).unwrap(); + let object = value.as_object_mut().unwrap(); + assert!(object.remove("requires_target").is_some()); + object.insert("enabled".to_string(), serde_json::json!("Disabled")); + let restored: MagicSpell = serde_json::from_value(value).unwrap(); + let value = serde_json::to_value(&restored).unwrap(); + assert_eq!( + value.get("requires_target").and_then(|v| v.as_str()), + Some("NotRequired") + ); + + let mut cursor = std::io::Cursor::new(vec![1u8, 0, 0, 0]); + cursor.get_mut().extend_from_slice(&[0u8; 84]); + let spells = MagicSpell::parse(&mut cursor, 88).unwrap(); + let mut value = serde_json::to_value(&spells[0]).unwrap(); + let object = value.as_object_mut().unwrap(); + object.remove("requires_target"); + object.insert("enabled".to_string(), serde_json::json!("Enabled")); + let restored: MagicSpell = serde_json::from_value(value).unwrap(); + let value = serde_json::to_value(&restored).unwrap(); + assert_eq!( + value.get("requires_target").and_then(|v| v.as_str()), + Some("Required") + ); + } + #[test] fn test_monster_attack_cooldown_label_accepts_old_key() { let descriptor = Monster::__editable_fields() diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs index 3c67ee85..fc715faa 100644 --- a/dispel-gui/src/tests/select_boxes.rs +++ b/dispel-gui/src/tests/select_boxes.rs @@ -14,9 +14,9 @@ use dispel_core::references::enums::WireValue; use dispel_core::{ BooleanFlag, DialogOwner, DialogType, DialogueScript, DrawItem, EditItem, EditItemEffect, EditItemModification, Event, EventNpcRef, EventType, ExtraObjectType, ExtraRef, HealItem, - HealItemFlag, MagicSpell, MagicSpellFlag, MagicType, Map, MapLighting, Monster, MonsterAiType, - MonsterRef, MonsterSpawn, NPC, NpcInteractionMode, NpcLookingDirection, NpcMovementMode, - NpcRoleResult, SmallRange0to3, + HealItemFlag, MagicSpell, MagicType, Map, MapLighting, Monster, MonsterAiType, MonsterRef, + MonsterSpawn, NPC, NpcInteractionMode, NpcLookingDirection, NpcMovementMode, NpcRoleResult, + SmallRange0to3, TargetSelectionFlag, }; use super::common::{activate_select_option, filter_select, select_shows, select_values}; @@ -464,7 +464,7 @@ fn test_every_enum_field_round_trips_through_both_views() { audit_enum::("modifies_item", DebugFormat); audit_enum::("additional_effect", DebugFormat); audit_enum::("magic_type", DebugFormat); - audit_enum::("enabled", DebugFormat); + audit_enum::("requires_target", DebugFormat); } #[test] diff --git a/docs/files/MagicInGame/Magic.db.md b/docs/files/MagicInGame/Magic.db.md index 77bea6d2..cb804bb4 100644 --- a/docs/files/MagicInGame/Magic.db.md +++ b/docs/files/MagicInGame/Magic.db.md @@ -13,7 +13,7 @@ All fields are little-endian `u32` values. The record ID is its zero-based posit | Offset | Field | Meaning | |-------:|--------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------| -| 0 | `enabled` | Spell availability flag | +| 0 | `requires_target` | `0`=no target required, `1`=target required | | 4 | `effect_visual_blends_with_background` | `0`=Off, `1`=On — uses blended rendering for the initial spell visual instead of direct blitting | | 8 | `base_damage` | Base damage used by the spell-damage calculation | | 12 | `base_success_rate` | Base casting-success chance before skill adjustment | diff --git a/src/references/enums.rs b/src/references/enums.rs index c840d8fa..5e72e4d3 100644 --- a/src/references/enums.rs +++ b/src/references/enums.rs @@ -60,7 +60,7 @@ impl_wire_value!(SmallRange0to3, u8, from_u8); impl_wire_value!(HealItemFlag, u8, from_u8); impl_wire_value!(MagicType, u32, from_u32); impl_wire_value!(SpellTargetType, u32, from_u32); -impl_wire_value!(MagicSpellFlag, u32, from_u32); +impl_wire_value!(TargetSelectionFlag, u32, from_u32); impl_wire_value!(MagicSpellConstant, u32, from_u32); impl_wire_value!(NpcLookingDirection, i32, from_i32); impl_wire_value!(ProductType, i32, from_i32); @@ -1485,23 +1485,25 @@ impl From for u32 { } } -/// Magic spell boolean flags +/// Whether casting a spell requires a target. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] #[repr(u32)] -pub enum MagicSpellFlag { - /// Flag is disabled/false +pub enum TargetSelectionFlag { + /// The spell does not pick a target. #[default] - Disabled = 0, - /// Flag is enabled/true - Enabled = 1, + #[serde(alias = "Disabled")] + NotRequired = 0, + /// The spell picks a target. + #[serde(alias = "Enabled")] + Required = 1, } -impl MagicSpellFlag { +impl TargetSelectionFlag { /// Convert from u32 with validation pub fn from_u32(value: u32) -> Option { match value { - 0 => Some(MagicSpellFlag::Disabled), - 1 => Some(MagicSpellFlag::Enabled), + 0 => Some(TargetSelectionFlag::NotRequired), + 1 => Some(TargetSelectionFlag::Required), _ => None, } } @@ -1514,39 +1516,39 @@ impl MagicSpellFlag { /// Convert from display name pub fn from_name(name: &str) -> Option { match name { - "Disabled" => Some(MagicSpellFlag::Disabled), - "Enabled" => Some(MagicSpellFlag::Enabled), + "NotRequired" | "Disabled" => Some(TargetSelectionFlag::NotRequired), + "Required" | "Enabled" => Some(TargetSelectionFlag::Required), _ => None, } } } -impl TryFrom for MagicSpellFlag { +impl TryFrom for TargetSelectionFlag { type Error = &'static str; fn try_from(value: u32) -> Result { - MagicSpellFlag::from_u32(value).ok_or("Invalid magic spell flag value") + TargetSelectionFlag::from_u32(value).ok_or("Invalid target selection flag value") } } -impl From for u32 { - fn from(flag: MagicSpellFlag) -> Self { +impl From for u32 { + fn from(flag: TargetSelectionFlag) -> Self { flag.value() } } -impl From for bool { - fn from(flag: MagicSpellFlag) -> Self { - flag == MagicSpellFlag::Enabled +impl From for bool { + fn from(flag: TargetSelectionFlag) -> Self { + flag == TargetSelectionFlag::Required } } -impl From for MagicSpellFlag { +impl From for TargetSelectionFlag { fn from(value: bool) -> Self { if value { - MagicSpellFlag::Enabled + TargetSelectionFlag::Required } else { - MagicSpellFlag::Disabled + TargetSelectionFlag::NotRequired } } } @@ -2046,15 +2048,24 @@ mod tests { } #[test] - fn test_magic_spell_flag_conversion() { - assert_eq!(MagicSpellFlag::from_u32(0), Some(MagicSpellFlag::Disabled)); - assert_eq!(MagicSpellFlag::from_u32(1), Some(MagicSpellFlag::Enabled)); - assert_eq!(MagicSpellFlag::from_u32(99), None); + fn test_target_selection_flag_conversion() { + assert_eq!( + TargetSelectionFlag::from_u32(0), + Some(TargetSelectionFlag::NotRequired) + ); + assert_eq!( + TargetSelectionFlag::from_u32(1), + Some(TargetSelectionFlag::Required) + ); + assert_eq!(TargetSelectionFlag::from_u32(99), None); - assert_eq!(u32::from(MagicSpellFlag::Enabled), 1); - assert_eq!(MagicSpellFlag::Enabled.value(), 1); - assert!(bool::from(MagicSpellFlag::Enabled)); - assert_eq!(MagicSpellFlag::from(true), MagicSpellFlag::Enabled); + assert_eq!(u32::from(TargetSelectionFlag::Required), 1); + assert_eq!(TargetSelectionFlag::Required.value(), 1); + assert!(bool::from(TargetSelectionFlag::Required)); + assert_eq!( + TargetSelectionFlag::from(true), + TargetSelectionFlag::Required + ); } #[test] @@ -2169,7 +2180,7 @@ mod tests { assert_wire_fallback!(HealItemFlag, u8, from_u8, 1, 254); assert_wire_fallback!(MagicType, u32, from_u32, 1, u32::MAX); assert_wire_fallback!(SpellTargetType, u32, from_u32, 1, u32::MAX); - assert_wire_fallback!(MagicSpellFlag, u32, from_u32, 1, u32::MAX); + assert_wire_fallback!(TargetSelectionFlag, u32, from_u32, 1, u32::MAX); assert_wire_fallback!(MagicSpellConstant, u32, from_u32, 1, u32::MAX); assert_wire_fallback!(NpcLookingDirection, i32, from_i32, 7, i32::MIN); assert_wire_fallback!(ProductType, i32, from_i32, 2, i32::MIN); diff --git a/src/references/magic_db.rs b/src/references/magic_db.rs index 5a86fce2..263cbf5a 100644 --- a/src/references/magic_db.rs +++ b/src/references/magic_db.rs @@ -1,6 +1,6 @@ use std::path::Path; -use crate::references::enums::{MagicSpellFlag, MagicType}; +use crate::references::enums::{MagicType, TargetSelectionFlag}; use crate::references::extractor::Extractor; use dispel_macros::{Extractor, RecordLayout, RecordPatcher}; use rusqlite::{Connection, Result, params}; @@ -28,7 +28,7 @@ use serde::{Deserialize, Serialize}; /// +--------------------------------------+ /// | [Record 1] - 88 bytes | /// | - id: i32 (auto-generated) | -/// | - enabled: u32 (MagicSpellFlag) | +/// | - requires_target: u32 (TargetSelectionFlag) | /// | - effect_visual_blends_with_background: u32 (0=Off, 1=On) | /// | - base_damage: u32 | /// | - base_success_rate: u32 | @@ -78,9 +78,11 @@ pub struct MagicSpell { #[extractor(index)] pub id: i32, - /// Whether the spell is enabled/available - #[extractor(enum_from_u32(type = "MagicSpellFlag"))] - pub enabled: MagicSpellFlag, + /// Whether casting the spell requires a target. + #[extractor(enum_from_u32(type = "TargetSelectionFlag"))] + #[serde(alias = "enabled")] + #[patcher(field_alias = "enabled")] + pub requires_target: TargetSelectionFlag, /// Selects blended rendering (`1`) rather than direct blitting (`0`) for /// the spell's initial visual effect. @@ -186,7 +188,7 @@ pub fn save_magic_spells(conn: &mut Connection, spells: &[MagicSpell]) -> Result for spell in spells { stmt.execute(params![ spell.id, - u32::from(spell.enabled), + u32::from(spell.requires_target), spell.effect_visual_blends_with_background, spell.base_damage, spell.base_success_rate, @@ -260,6 +262,23 @@ mod tests { fields.iter().flat_map(|&v| v.to_le_bytes()).collect() } + #[test] + fn test_legacy_patcher_key_sets_requires_target() { + use crate::modding::patcher::RecordPatcher; + use crate::modding::value::Value; + + let data = spell_bytes(20, 50, 1); + let out = MagicSpellPatcher + .apply_field(&data, 0, "enabled", &Value::I64(1)) + .expect("the stored patcher key must still be accepted"); + let mut cursor = Cursor::new(&out[..]); + let spells = MagicSpell::parse(&mut cursor, out.len() as u64).unwrap(); + assert_eq!( + spells[0].requires_target, + crate::references::enums::TargetSelectionFlag::Required + ); + } + #[test] fn test_legacy_patcher_key_sets_animation_cycles() { use crate::modding::patcher::RecordPatcher; @@ -284,7 +303,10 @@ mod tests { assert_eq!(spells.len(), 1); assert_eq!(spells[0].id, 0); - assert_eq!(spells[0].enabled, MagicSpellFlag::Enabled); + assert_eq!( + spells[0].requires_target, + crate::references::enums::TargetSelectionFlag::Required + ); assert_eq!(spells[0].base_damage, 20); assert_eq!(spells[0].mana_cost, 50); assert_eq!(spells[0].magic_type, MagicType::HolyMagic); From 21b70e31bb7151e8533f4608814eab91c920179d Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:01:14 +0100 Subject: [PATCH 41/72] fix(core): rename mana drain to health leech --- dispel-gui/src/editors/edit_item/component.rs | 2 +- dispel-gui/src/tests/editor_field_edit.rs | 30 ++++++++++++++++++- docs/files/CharacterInGame/EditItem.db.md | 2 +- src/modding/patchers/derived.rs | 4 +-- src/references/edit_item_db.rs | 4 +-- src/references/enums.rs | 20 ++++++++----- 6 files changed, 48 insertions(+), 14 deletions(-) diff --git a/dispel-gui/src/editors/edit_item/component.rs b/dispel-gui/src/editors/edit_item/component.rs index 080981bf..ce012cb2 100644 --- a/dispel-gui/src/editors/edit_item/component.rs +++ b/dispel-gui/src/editors/edit_item/component.rs @@ -22,7 +22,7 @@ editable_record_fields!(EditItem, { { modification_resistance = Integer / "Modification Resistance:" }, { reserved_byte = Integer / "Reserved Byte:" }, { modifies_item = Enum(EditItemModification, ["DoesNotModify", "CanModify"]) / "Modifies Item:" }, - { additional_effect = Enum(EditItemEffect, ["None", "Fire", "ManaDrain"]) / "Effect:" }, + { additional_effect = Enum(EditItemEffect, ["None", "Fire", "HealthLeech"]) / "Effect:" }, }); impl EditableRecord for EditItem { diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index bae8d603..562bd348 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1015,7 +1015,35 @@ mod modified_flag_routing { mod renamed_field_labels { use crate::components::editable::{EditableRecordGenerated, FieldKind}; - use dispel_core::{ExtraRef, Extractor, MagicSpell, Monster, WeaponItem}; + use dispel_core::{ + EditItem, EditItemEffect, ExtraRef, Extractor, MagicSpell, Monster, WeaponItem, + }; + + #[test] + fn test_edit_item_effect_health_leech_uses_new_name() { + let descriptor = EditItem::__editable_fields() + .iter() + .find(|field| field.name == "additional_effect") + .expect("the effect field must be exposed in the inspector"); + match &descriptor.kind { + FieldKind::Enum { variants } => { + assert!( + variants.contains(&"HealthLeech"), + "GUI option: {variants:?}" + ); + } + _ => panic!("the effect field must be an enum"), + } + + let wire = EditItemEffect::from_i16(2).unwrap(); + assert_eq!(serde_json::to_string(&wire).unwrap(), "\"HealthLeech\""); + let legacy: EditItemEffect = serde_json::from_str("\"ManaDrain\"").unwrap(); + assert_eq!(legacy.value(), 2); + assert_eq!( + EditItemEffect::from_name("HealthLeech").map(|effect| effect.value()), + Some(2) + ); + } #[test] fn test_magic_requires_target_flag_accepts_old_names() { diff --git a/docs/files/CharacterInGame/EditItem.db.md b/docs/files/CharacterInGame/EditItem.db.md index 3f67359c..aac8f087 100644 --- a/docs/files/CharacterInGame/EditItem.db.md +++ b/docs/files/CharacterInGame/EditItem.db.md @@ -24,7 +24,7 @@ | 262 | 2 | `modification_resistance` | Resistance to modification; a negative value lowers resistance. | | 264 | 1 | `reserved_byte` | Always zero by default; purpose unknown. | | 265 | 1 | `modifies_item` | Whether this material can modify an item. | -| 266 | 2 | `additional_effect` | Extra effect: none, fire, or mana drain. | +| 266 | 2 | `additional_effect` | Extra effect: none, fire, or health leech. | ## Runtime item ID diff --git a/src/modding/patchers/derived.rs b/src/modding/patchers/derived.rs index 00975a5d..71a1599c 100644 --- a/src/modding/patchers/derived.rs +++ b/src/modding/patchers/derived.rs @@ -132,7 +132,7 @@ mod tests { #[test] fn edit_enum_from_i16_via_i64() { let p = EditItemPatcher; - let target = i16::from(EditItemEffect::ManaDrain); + let target = i16::from(EditItemEffect::HealthLeech); let out = p .apply_field( &edit_blob(), @@ -143,7 +143,7 @@ mod tests { .unwrap(); assert_eq!( parse_edit(&out)[0].additional_effect, - EditItemEffect::ManaDrain + EditItemEffect::HealthLeech ); } diff --git a/src/references/edit_item_db.rs b/src/references/edit_item_db.rs index 6bc103f1..a649072b 100644 --- a/src/references/edit_item_db.rs +++ b/src/references/edit_item_db.rs @@ -72,7 +72,7 @@ use dispel_macros::RecordPatcher; /// # Special Values /// /// - `modifies_item`: Enum controlling if item mutates behavior -/// - `additional_effect`: Enum for procedural elemental modifiers (mana drain, fire, etc.) +/// - `additional_effect`: Extra effect: none, fire, or health leech /// - `runtime_item_id`: Stored as zero in known files; overwritten with the zero-based /// record index at load time and used to identify this item definition. /// - `reserved_byte`: Always zero by default; no reader accesses it. @@ -160,7 +160,7 @@ pub struct EditItem { /// Flag specifying if behavior mutates. #[extractor(enum_from_u8(type = "EditItemModification"))] pub modifies_item: EditItemModification, - /// Procedural elemental modifier appended (mana drain, fire). + /// Extra effect (none, fire, or health leech). #[extractor(enum_from_i16(type = "EditItemEffect"))] pub additional_effect: EditItemEffect, } diff --git a/src/references/enums.rs b/src/references/enums.rs index 5e72e4d3..b15097cc 100644 --- a/src/references/enums.rs +++ b/src/references/enums.rs @@ -547,8 +547,9 @@ pub enum EditItemEffect { None = 0, /// Fire effect Fire = 1, - /// Mana drain effect - ManaDrain = 2, + /// Health leech effect + #[serde(alias = "ManaDrain")] + HealthLeech = 2, } impl EditItemEffect { @@ -557,7 +558,7 @@ impl EditItemEffect { match value { 0 => Some(EditItemEffect::None), 1 => Some(EditItemEffect::Fire), - 2 => Some(EditItemEffect::ManaDrain), + 2 => Some(EditItemEffect::HealthLeech), _ => None, } } @@ -572,7 +573,9 @@ impl EditItemEffect { match name { "None" => Some(EditItemEffect::None), "Fire" => Some(EditItemEffect::Fire), - "ManaDrain" | "Mana Drain" => Some(EditItemEffect::ManaDrain), + "HealthLeech" | "Health Leech" | "ManaDrain" | "Mana Drain" => { + Some(EditItemEffect::HealthLeech) + } _ => None, } } @@ -1926,11 +1929,14 @@ mod tests { fn test_edit_item_effect_conversion() { assert_eq!(EditItemEffect::from_i16(0), Some(EditItemEffect::None)); assert_eq!(EditItemEffect::from_i16(1), Some(EditItemEffect::Fire)); - assert_eq!(EditItemEffect::from_i16(2), Some(EditItemEffect::ManaDrain)); + assert_eq!( + EditItemEffect::from_i16(2), + Some(EditItemEffect::HealthLeech) + ); assert_eq!(EditItemEffect::from_i16(99), None); - assert_eq!(i16::from(EditItemEffect::ManaDrain), 2); - assert_eq!(EditItemEffect::ManaDrain.value(), 2); + assert_eq!(i16::from(EditItemEffect::HealthLeech), 2); + assert_eq!(EditItemEffect::HealthLeech.value(), 2); } #[test] From 0e13889af7e6ffaf620f32b29946f0a0c9aa14f2 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:09:16 +0100 Subject: [PATCH 42/72] fix(core): rename cures petrification to cures paralysis --- dispel-gui/src/editors/heal_item/component.rs | 4 +-- dispel-gui/src/tests/editor_field_edit.rs | 27 ++++++++++++++++++- dispel-gui/src/tests/select_boxes.rs | 2 +- docs/files/CharacterInGame/HealItem.db.md | 2 +- src/references/heal_item_db.rs | 27 +++++++++++++++---- 5 files changed, 52 insertions(+), 10 deletions(-) diff --git a/dispel-gui/src/editors/heal_item/component.rs b/dispel-gui/src/editors/heal_item/component.rs index a0e89b48..a3b04d41 100644 --- a/dispel-gui/src/editors/heal_item/component.rs +++ b/dispel-gui/src/editors/heal_item/component.rs @@ -17,7 +17,7 @@ editable_record_fields!(HealItem, { { restores_full_health = Enum(HealItemFlag, Shared(FLAGS)) / "Restore Full HP:" }, { restores_full_mana = Enum(HealItemFlag, Shared(FLAGS)) / "Restore Full MP:" }, { cures_poison = Enum(HealItemFlag, Shared(FLAGS)) / "Cures Poison:" }, - { cures_petrification = Enum(HealItemFlag, Shared(FLAGS)) / "Cures Petrification:" }, + { cures_paralysis = Enum(HealItemFlag, Shared(FLAGS)) / "Cures Paralysis:" }, { cures_polymorph = Enum(HealItemFlag, Shared(FLAGS)) / "Cures Polymorph:" }, { reserved_trailer = HexString / "Reserved Trailer:" }, }); @@ -42,7 +42,7 @@ impl EditableRecord for HealItem { "restores_full_health" | "restores_full_mana" | "cures_poison" - | "cures_petrification" + | "cures_paralysis" | "cures_polymorph" => { if HealItemFlag::from_name(value).is_none() { Some(format!("Invalid {field}")) diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index 562bd348..bf057fcb 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1016,9 +1016,34 @@ mod modified_flag_routing { mod renamed_field_labels { use crate::components::editable::{EditableRecordGenerated, FieldKind}; use dispel_core::{ - EditItem, EditItemEffect, ExtraRef, Extractor, MagicSpell, Monster, WeaponItem, + EditItem, EditItemEffect, ExtraRef, Extractor, HealItem, MagicSpell, Monster, WeaponItem, }; + #[test] + fn test_heal_item_paralysis_label_accepts_old_key() { + let descriptor = HealItem::__editable_fields() + .iter() + .find(|field| field.name == "cures_paralysis") + .expect("the paralysis cure must be exposed in the inspector"); + assert_eq!(descriptor.label, "Cures Paralysis:"); + + let mut value = serde_json::to_value(HealItem::default()).unwrap(); + let object = value.as_object_mut().unwrap(); + assert!(object.remove("cures_paralysis").is_some()); + object.insert( + "cures_petrification".to_string(), + serde_json::json!("Active"), + ); + let restored: HealItem = serde_json::from_value(value).unwrap(); + assert!( + serde_json::to_value(&restored) + .unwrap() + .get("cures_paralysis") + .is_some(), + "the stored key must still be accepted" + ); + } + #[test] fn test_edit_item_effect_health_leech_uses_new_name() { let descriptor = EditItem::__editable_fields() diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs index fc715faa..a4275bae 100644 --- a/dispel-gui/src/tests/select_boxes.rs +++ b/dispel-gui/src/tests/select_boxes.rs @@ -441,7 +441,7 @@ fn test_every_enum_field_round_trips_through_both_views() { "restores_full_health", "restores_full_mana", "cures_poison", - "cures_petrification", + "cures_paralysis", "cures_polymorph", ] { audit_enum::(field, DebugFormat); diff --git a/docs/files/CharacterInGame/HealItem.db.md b/docs/files/CharacterInGame/HealItem.db.md index 387115a0..3e66769e 100644 --- a/docs/files/CharacterInGame/HealItem.db.md +++ b/docs/files/CharacterInGame/HealItem.db.md @@ -24,7 +24,7 @@ The tool reads `HealItem.db` as fixed-size definitions for items that restore he | 244 | 1 | `restores_full_health` | flag | Full-health restore. | | 245 | 1 | `restores_full_mana` | flag | Full-mana restore. | | 246 | 1 | `cures_poison` | flag | Poison cure. | -| 247 | 1 | `cures_petrification` | flag | Petrification cure. | +| 247 | 1 | `cures_paralysis` | flag | Paralysis cure. | | 248 | 1 | `cures_polymorph` | flag | Polymorph cure. | | 249 | 3 | `reserved_trailer` | bytes | Preserved opaque data. Unused. | diff --git a/src/references/heal_item_db.rs b/src/references/heal_item_db.rs index d25c583d..39ebf576 100644 --- a/src/references/heal_item_db.rs +++ b/src/references/heal_item_db.rs @@ -40,7 +40,7 @@ use dispel_macros::{Extractor, Localizable, RecordLayout, RecordPatcher}; /// | - restores_full_health: u8 | /// | - restores_full_mana: u8 | /// | - cures_poison: u8 | -/// | - cures_petrification: u8 | +/// | - cures_paralysis: u8 | /// | - cures_polymorph: u8 | /// | - reserved_trailer: 3 bytes | /// +--------------------------------------+ @@ -55,7 +55,7 @@ use dispel_macros::{Extractor, Localizable, RecordLayout, RecordPatcher}; /// - **Economy**: `base_price` (i32, merchant valuation) /// - **Healing**: `health_points` (HP restore), `mana_points` (MP restore) /// - **Full Restore Flags**: `restores_full_health`, `restores_full_mana` (HealItemFlag) -/// - **Cure Effects**: `cures_poison`, `cures_petrification`, `cures_polymorph` (HealItemFlag) +/// - **Cure Effects**: `cures_poison`, `cures_paralysis`, `cures_polymorph` (HealItemFlag) /// - **Runtime bookkeeping**: `runtime_item_index_slot` is overwritten with the /// record index while loading. /// - **Reserved data**: `reserved_trailer` is retained verbatim. @@ -65,7 +65,7 @@ use dispel_macros::{Extractor, Localizable, RecordLayout, RecordPatcher}; /// - `restores_full_health`: HealItemFlag::Active = restore full HP /// - `restores_full_mana`: HealItemFlag::Active = restore full MP /// - `cures_poison`: HealItemFlag::Active = cure poison -/// - `cures_petrification`: HealItemFlag::Active = cure petrification +/// - `cures_paralysis`: HealItemFlag::Active = cure paralysis /// - `cures_polymorph`: HealItemFlag::Active = cure polymorph /// - `runtime_item_index_slot`: Overwritten with the sequential record index. /// - `reserved_trailer`: Three bytes, zero in the bundled fixture. @@ -122,7 +122,9 @@ pub struct HealItem { #[extractor(enum_from_u8(type = "HealItemFlag"))] pub cures_poison: HealItemFlag, #[extractor(enum_from_u8(type = "HealItemFlag"))] - pub cures_petrification: HealItemFlag, + #[serde(alias = "cures_petrification")] + #[patcher(field_alias = "cures_petrification")] + pub cures_paralysis: HealItemFlag, #[extractor(enum_from_u8(type = "HealItemFlag"))] pub cures_polymorph: HealItemFlag, /// Reserved bytes at offsets `0xF9..0xFB`. @@ -153,7 +155,7 @@ pub fn save_heal_items(conn: &mut Connection, heal_items: &[HealItem]) -> Result u8::from(item.restores_full_health), u8::from(item.restores_full_mana), u8::from(item.cures_poison), - u8::from(item.cures_petrification), + u8::from(item.cures_paralysis), u8::from(item.cures_polymorph), item.reserved_trailer, ])?; @@ -188,6 +190,21 @@ mod tests { rec } + #[test] + fn test_legacy_patcher_key_sets_paralysis_cure() { + use crate::modding::patcher::RecordPatcher; + use crate::modding::value::Value; + + let mut data = 1i32.to_le_bytes().to_vec(); + data.extend(item_bytes("MistvaleTonic", 40, 20)); + let out = HealItemPatcher + .apply_field(&data, 0, "cures_petrification", &Value::I64(1)) + .expect("the stored patcher key must still be accepted"); + let mut cursor = Cursor::new(&out[..]); + let items = HealItem::parse(&mut cursor, out.len() as u64).unwrap(); + assert_eq!(items[0].cures_paralysis, HealItemFlag::Active); + } + #[test] fn parse_single_item() { let mut data = 1i32.to_le_bytes().to_vec(); From 1f7d307fb311177a23134c0a0357ce85a0138cbb Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:16:30 +0100 Subject: [PATCH 43/72] fix(core): relabel monster ini sound fields --- .../src/editors/monster_ini/component.rs | 10 +-- dispel-gui/src/tests/editor_field_edit.rs | 21 +++++- docs/files/CharacterInGame/Monster.ini.md | 73 +++++++++---------- src/references/monster_ini.rs | 16 ++-- 4 files changed, 69 insertions(+), 51 deletions(-) diff --git a/dispel-gui/src/editors/monster_ini/component.rs b/dispel-gui/src/editors/monster_ini/component.rs index a7492322..4ebc363e 100644 --- a/dispel-gui/src/editors/monster_ini/component.rs +++ b/dispel-gui/src/editors/monster_ini/component.rs @@ -7,11 +7,11 @@ editable_record_fields!(MonsterIni, { { id = Integer / "ID:" }, { name = OptStr / "Name:" }, { sprite_filename = OptStr / "Sprite:" }, - { attack = Integer / "Attack Seq:" }, - { hit = Integer / "Hit Seq:" }, - { death = Integer / "Death Seq:" }, - { walking = Integer / "Walking Seq:" }, - { casting_magic = Integer / "Casting Seq:" }, + { attack = Integer / "Approach SFX:" }, + { hit = Integer / "Attack SFX:" }, + { death = Integer / "Death SFX:" }, + { walking = Integer / "Post-strike SFX:" }, + { casting_magic = Integer / "Magic SFX:" }, }); impl EditableRecord for MonsterIni { diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index bf057fcb..378895c2 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1016,9 +1016,28 @@ mod modified_flag_routing { mod renamed_field_labels { use crate::components::editable::{EditableRecordGenerated, FieldKind}; use dispel_core::{ - EditItem, EditItemEffect, ExtraRef, Extractor, HealItem, MagicSpell, Monster, WeaponItem, + EditItem, EditItemEffect, ExtraRef, Extractor, HealItem, MagicSpell, Monster, MonsterIni, + WeaponItem, }; + #[test] + fn test_monster_ini_sound_fields_have_sfx_labels() { + let descriptors = MonsterIni::__editable_fields(); + for (name, label) in [ + ("attack", "Approach SFX:"), + ("hit", "Attack SFX:"), + ("death", "Death SFX:"), + ("walking", "Post-strike SFX:"), + ("casting_magic", "Magic SFX:"), + ] { + let descriptor = descriptors + .iter() + .find(|field| field.name == name) + .expect("field must be exposed in the inspector"); + assert_eq!(descriptor.label, label, "label for {name}"); + } + } + #[test] fn test_heal_item_paralysis_label_accepts_old_key() { let descriptor = HealItem::__editable_fields() diff --git a/docs/files/CharacterInGame/Monster.ini.md b/docs/files/CharacterInGame/Monster.ini.md index e5dab941..59c44d79 100644 --- a/docs/files/CharacterInGame/Monster.ini.md +++ b/docs/files/CharacterInGame/Monster.ini.md @@ -4,7 +4,7 @@ ### Overview -The tool reads `Monster.ini` as a CSV file with comments. Each row holds a visual type ID, a name, a sprite filename and five animation sequence IDs. +The tool reads `Monster.ini` as a CSV file with comments. Each row holds a visual type ID, a name, a sprite filename and five Wave.ini sound IDs. ### File Structure @@ -30,22 +30,21 @@ id,name,sprite_filename,attack_seq,hit_seq,death_seq,walk_seq,cast_seq | id | i32 | Unique monster visual type identifier | | name | string | Monster display name or "null" | | sprite_filename | string | SPR filename or "null" for no sprite | -| attack_seq | i32 | Animation sequence ID for attacking | -| hit_seq | i32 | Animation sequence ID for taking damage | -| death_seq | i32 | Animation sequence ID for dying | -| walk_seq | i32 | Animation sequence ID for walking | -| cast_seq | i32 | Animation sequence ID for spellcasting | +| attack_seq | i32 | Wave.ini sound ID for the approach cry | +| hit_seq | i32 | Wave.ini sound ID for a successful hit | +| death_seq | i32 | Wave.ini sound ID for death | +| walk_seq | i32 | Wave.ini sound ID for the post-strike cry | +| cast_seq | i32 | Wave.ini sound ID for spellcasting | -### Animation System +### Sound Fields -The file maps monster types to animation sequences that reference frame indices in SPR files: +The five numeric columns are Wave.ini sound IDs, not sprite animation sequences: -**Animation Sequence IDs:** +**Sound IDs:** -- **0**: No animation (unused sequence) -- **1-N**: Frame sequence numbers in SPR file -- **-1**: Special/alternative animation sequence -- **Positive numbers**: Link to specific animation frames +- **0**: No sound +- **1-N**: Wave.ini sound index +- **-1**: No sound selected ### Monster Categories @@ -58,26 +57,26 @@ The file organizes monsters into logical groups based on the comment header: **Example Monsters:** - ID 0: Default/null entry (no monster) -- IDs 1+: Various monster types with sprites and animations +- IDs 1+: Various monster types with sprites and sound IDs -### Animation Sequence Details +### Sound Field Details -**Combat Animations:** +**Combat sounds:** -- `attack_seq`: attack animations -- `hit_seq`: Damage/taking hit animations -- `death_seq`: Death/dying animations +- `attack_seq`: approach cry +- `hit_seq`: successful strike +- `death_seq`: death -**Movement Animations:** +**Other sounds:** -- `walk_seq`: movement animations -- `cast_seq`: magic animations +- `walk_seq`: post-strike cry +- `cast_seq`: spellcasting ### Special Values - **"null"**: Literal string indicating no name or sprite -- **0**: Unused animation sequence (no animation) -- **-1**: Special or alternative animation sequence +- **0**: No sound +- **-1**: No sound selected - **`;`**: Lines starting with this mark are comments. - **Empty lines**: Ignored during processing @@ -91,7 +90,7 @@ The file organizes monsters into logical groups based on the comment header: 1,MonsterType,monster.spr,201,202,203,204,205 2,MonsterType,monster.spr,206,207,208,209,210 -; Monster with special casting animation +; Monster with a distinct spellcasting sound 30,EliteMonster,elite.spr,251,252,253,254,-1 ``` @@ -116,36 +115,36 @@ The file organizes monsters into logical groups based on the comment header: - Monster placement files (`mondun*.ref`, `monmap*.ref`) use these IDs. - Other file formats reference these IDs. -### Animation Sequence System +### Sound Field Structure -The animation sequences link to specific frame ranges in SPR files: +The sound columns are stored as Wave.ini indices: ```rust pub struct MonsterIni { id: i32, // Monster ID name: Option, // Display name sprite_filename: Option, // SPR file - attack: i32, // Attack animation sequence - hit: i32, // Hit animation sequence - death: i32, // Death animation sequence - walking: i32, // Walking animation sequence - casting_magic: i32, // Casting animation sequence + attack: i32, // Approach cry sound index + hit: i32, // Strike sound index + death: i32, // Death sound index + walking: i32, // Post-strike cry sound index + casting_magic: i32, // Spellcasting sound index } ``` ### File use 1. The tool reads visual definitions from `Monster.ini`. -2. It links monster IDs to animation sequence IDs. -3. It stores the attack, hit and death sequence IDs. -4. It stores the walking sequence ID. -5. It stores the casting sequence ID. +2. It links monster IDs to Wave.ini sound IDs. +3. It stores the approach, strike and death sound IDs. +4. It stores the post-strike cry sound ID. +5. It stores the spellcasting sound ID. ### Notes - File uses Windows-style line endings (\r\n) - Comments are in Polish (WINDOWS-1250 encoding) -- Animation sequences link to SPR file frame indices +- Sound columns hold Wave.ini indices, not sprite frame ranges - Other file formats link to these IDs. ## Extractor diff --git a/src/references/monster_ini.rs b/src/references/monster_ini.rs index 2aaa1355..7179215c 100644 --- a/src/references/monster_ini.rs +++ b/src/references/monster_ini.rs @@ -5,9 +5,9 @@ use dispel_macros::{Localizable, TextExtractor, TextRecordPatcher}; use rusqlite::{Connection, Result, params}; use serde::{Deserialize, Serialize}; -/// Monster.ini - Monster Animations +/// Monster.ini - monster visuals and sound IDs /// -/// Stores visual references and configuration for monsters. +/// Stores visual references, Wave.ini sound IDs and configuration for monsters. /// /// Reads file: `Monster.ini` /// @@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize}; /// /// ```text /// +--------------------------------------+ -/// | Monster.ini - Monster Animations | +/// | Monster.ini - visuals and SFX IDs | /// +--------------------------------------+ /// | Encoding: WINDOWS-1250 | /// | Format: CSV with comments | @@ -74,19 +74,19 @@ pub struct MonsterIni { /// Base sprite filename for the monster rendering. #[extractor(field = 2, parse_null)] pub sprite_filename: Option, - /// Sprite animation sequence number for attacking. + /// Wave.ini sound index played as the approach cry. #[extractor(field = 3)] pub attack: i32, - /// Sprite animation sequence number for getting hit. + /// Wave.ini sound index played on a successful strike. #[extractor(field = 4)] pub hit: i32, - /// Sprite animation sequence number for death. + /// Wave.ini sound index played on death. #[extractor(field = 5)] pub death: i32, - /// Sprite animation sequence number for walking. + /// Wave.ini sound index played after striking. #[extractor(field = 6)] pub walking: i32, - /// Sprite animation sequence number for casting spells. + /// Wave.ini sound index played when casting a spell. #[extractor(field = 7)] pub casting_magic: i32, } From 55f73ac54b451d8b08c72fcfc8a8969152cbfc13 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:30:30 +0100 Subject: [PATCH 44/72] fix(core): rename payload counts to journal strides --- dispel-gui/src/editors/save_ifo/state.rs | 42 +++++++-------- dispel-gui/src/editors/save_ifo/view.rs | 67 +++++++++++++++--------- docs/files/Save.ifo.md | 8 +-- src/modding/patchers/save_ifo.rs | 22 +++++--- src/references/save_ifo/mod.rs | 32 ++++++++--- src/references/save_ifo/swap.rs | 15 +++--- 6 files changed, 114 insertions(+), 72 deletions(-) diff --git a/dispel-gui/src/editors/save_ifo/state.rs b/dispel-gui/src/editors/save_ifo/state.rs index 6615467e..97634093 100644 --- a/dispel-gui/src/editors/save_ifo/state.rs +++ b/dispel-gui/src/editors/save_ifo/state.rs @@ -10,6 +10,13 @@ use crate::components::generic_editor::UndoRedo; use crate::components::loading_state::LoadingState; use dispel_core::{SaveIfo, SlotSummary}; +/// Read a stride index from either the current or the stored field path. +fn stride_index(path: &str) -> Option { + path.strip_prefix("tail.journal_strides.") + .or_else(|| path.strip_prefix("tail.payload_counts.")) + .and_then(|s| s.parse::().ok()) +} + /// Loaded editor payload. #[derive(Debug, Clone)] pub struct EditorData { @@ -25,7 +32,7 @@ pub struct TailBuffers { pub game_tmp_key: String, pub map_id: String, pub reserved: String, - pub payload_counts: [String; 4], + pub journal_strides: [String; 4], } #[derive(Debug, Clone)] @@ -87,7 +94,7 @@ impl SaveIfoEditorState { game_tmp_key: ifo.game_tmp_key.to_string(), map_id: ifo.map_id.to_string(), reserved: ifo.reserved.to_string(), - payload_counts: ifo.payload_counts.map(|v| v.to_string()), + journal_strides: ifo.journal_strides.map(|v| v.to_string()), }; } @@ -99,11 +106,8 @@ impl SaveIfoEditorState { "tail.map_id" => Some(ifo.map_id.to_string()), "tail.reserved" => Some(ifo.reserved.to_string()), other => { - let index = other - .strip_prefix("tail.payload_counts.")? - .parse::() - .ok()?; - ifo.payload_counts.get(index).map(|v| v.to_string()) + let index = stride_index(other)?; + ifo.journal_strides.get(index).map(|v| v.to_string()) } } } @@ -122,14 +126,11 @@ impl SaveIfoEditorState { "tail.game_tmp_key" => Self::apply_u32(&mut ifo.game_tmp_key, value), "tail.map_id" => Self::apply_u32(&mut ifo.map_id, value), "tail.reserved" => Self::apply_u32(&mut ifo.reserved, value), - other => match other.strip_prefix("tail.payload_counts.") { - Some(index) => match index.parse::() { - Ok(i) if i < ifo.payload_counts.len() => { - Self::apply_u32(&mut ifo.payload_counts[i], value) - } - _ => false, - }, - None => false, + other => match stride_index(other) { + Some(i) if i < ifo.journal_strides.len() => { + Self::apply_u32(&mut ifo.journal_strides[i], value) + } + _ => false, }, } } @@ -177,11 +178,10 @@ impl SaveIfoEditorState { "tail.map_id" => self.tail_buffers.map_id = value, "tail.reserved" => self.tail_buffers.reserved = value, other => { - if let Some(index) = other.strip_prefix("tail.payload_counts.") - && let Ok(i) = index.parse::() - && i < self.tail_buffers.payload_counts.len() + if let Some(i) = stride_index(other) + && i < self.tail_buffers.journal_strides.len() { - self.tail_buffers.payload_counts[i] = value; + self.tail_buffers.journal_strides[i] = value; } } } @@ -289,8 +289,8 @@ mod tests { editor.update_field("tail.payload_counts.0".into(), "350".into()); editor.undo(); editor.redo(); - assert_eq!(editor.data.as_ref().unwrap().ifo.payload_counts[0], 350); - assert_eq!(editor.tail_buffers.payload_counts[0], "350"); + assert_eq!(editor.data.as_ref().unwrap().ifo.journal_strides[0], 350); + assert_eq!(editor.tail_buffers.journal_strides[0], "350"); } #[test] diff --git a/dispel-gui/src/editors/save_ifo/view.rs b/dispel-gui/src/editors/save_ifo/view.rs index 3b380c92..dde2bf01 100644 --- a/dispel-gui/src/editors/save_ifo/view.rs +++ b/dispel-gui/src/editors/save_ifo/view.rs @@ -218,23 +218,29 @@ fn labeled_input<'a>(label: &'a str, value: &'a str, path: &'static str) -> Elem fn tail_section(editor: &SaveIfoEditorState) -> Element<'_, Message> { let buffers = &editor.tail_buffers; - let counts = row![ - container(text("Payload counts").style(style::subtle_text)).width(140.0), - text_input("", &buffers.payload_counts[0]) - .on_input(|v| count_msg(0, v)) - .width(90.0), - text_input("", &buffers.payload_counts[1]) - .on_input(|v| count_msg(1, v)) - .width(90.0), - text_input("", &buffers.payload_counts[2]) - .on_input(|v| count_msg(2, v)) - .width(90.0), - text_input("", &buffers.payload_counts[3]) - .on_input(|v| count_msg(3, v)) - .width(90.0), + let strides = column![ + labeled_input( + "Monster stride:", + &buffers.journal_strides[0], + "tail.journal_strides.0" + ), + labeled_input( + "NPC stride:", + &buffers.journal_strides[1], + "tail.journal_strides.1" + ), + labeled_input( + "Spell stride:", + &buffers.journal_strides[2], + "tail.journal_strides.2" + ), + labeled_input( + "Extra stride:", + &buffers.journal_strides[3], + "tail.journal_strides.3" + ), ] - .spacing(8) - .align_y(iced::alignment::Vertical::Center); + .spacing(4); column![ text("Global state").size(16), @@ -242,19 +248,12 @@ fn tail_section(editor: &SaveIfoEditorState) -> Element<'_, Message> { labeled_input("Tmp key", &buffers.game_tmp_key, "tail.game_tmp_key"), labeled_input("Map id", &buffers.map_id, "tail.map_id"), labeled_input("Reserved", &buffers.reserved, "tail.reserved"), - counts, + strides, ] .spacing(8) .into() } -fn count_msg(index: usize, value: String) -> Message { - Message::save_ifo(SaveIfoEditorMessage::FieldChanged( - format!("tail.payload_counts.{index}"), - value, - )) -} - fn status_bar(editor: &SaveIfoEditorState) -> Element<'_, Message> { container( row![ @@ -324,3 +323,23 @@ fn failed_view(error: &str) -> Element<'_, Message> { .padding(24) .into() } + +#[cfg(all(test, feature = "iced_test"))] +mod tests { + use super::*; + + #[test] + fn test_tail_section_names_journal_strides() { + let editor = SaveIfoEditorState::default(); + let mut ui = iced_test::simulator(tail_section(&editor)); + for label in [ + "Monster stride:", + "NPC stride:", + "Spell stride:", + "Extra stride:", + ] { + ui.find(label) + .unwrap_or_else(|_| panic!("missing label {label}")); + } + } +} diff --git a/docs/files/Save.ifo.md b/docs/files/Save.ifo.md index 8fed629d..eb55edeb 100644 --- a/docs/files/Save.ifo.md +++ b/docs/files/Save.ifo.md @@ -29,10 +29,10 @@ | 196 | u32 | `game.tmp` journal key identifying the current session's payload | | 200 | u32 | map/world id active at save time | | 204 | u32 | reserved; zero in known files | -| 208 | u32 | payload element count A — snapshot used as size multiplier when traversing the `game.tmp` log | -| 212 | u32 | payload element count B (same role) | -| 216 | u32 | payload element count C (same role) | -| 220 | u32 | payload element count D (same role) | +| 208 | u32 | monster journal record stride — size multiplier for traversing the `game.tmp` log | +| 212 | u32 | NPC journal record stride (same role) | +| 216 | u32 | spell journal record stride (same role) | +| 220 | u32 | extra journal record stride (same role) | ## Usage diff --git a/src/modding/patchers/save_ifo.rs b/src/modding/patchers/save_ifo.rs index 612dc260..8b5575c1 100644 --- a/src/modding/patchers/save_ifo.rs +++ b/src/modding/patchers/save_ifo.rs @@ -2,7 +2,7 @@ //! //! Hand-written because the editable surface is the 32-byte global tail of a //! single fixed-size record, addressed by dotted field paths -//! (`tail.game_version`, `tail.payload_counts.0`, …) rather than the flat +//! (`tail.game_version`, `tail.journal_strides.0`, …) rather than the flat //! field names the derive macros generate. use crate::modding::error::{ModdingError, Result}; @@ -44,12 +44,10 @@ impl RecordPatcher for SaveIfoPatcher { "tail.map_id" => ifo.map_id = parse_u32(field, new)?, "tail.reserved" => ifo.reserved = parse_u32(field, new)?, other => { - let index = other - .strip_prefix("tail.payload_counts.") - .and_then(|s| s.parse::().ok()) - .filter(|&i| i < ifo.payload_counts.len()) + let index = stride_index(other) + .filter(|&i| i < ifo.journal_strides.len()) .ok_or_else(|| unknown_field(Self::RECORD_NAME, other))?; - ifo.payload_counts[index] = parse_u32(field, new)?; + ifo.journal_strides[index] = parse_u32(field, new)?; } } @@ -59,6 +57,14 @@ impl RecordPatcher for SaveIfoPatcher { } } +/// Read a stride index from either the current or the stored field path. +fn stride_index(field: &str) -> Option { + field + .strip_prefix("tail.journal_strides.") + .or_else(|| field.strip_prefix("tail.payload_counts.")) + .and_then(|s| s.parse::().ok()) +} + fn parse_f32(field: &str, new: &Value) -> Result { match new { Value::F64(v) => Ok(*v as f32), @@ -94,7 +100,7 @@ mod tests { game_tmp_key: 6, map_id: 12, reserved: 0, - payload_counts: [329, 349, 0, 200], + journal_strides: [329, 349, 0, 200], }; let mut out = Vec::new(); ifo.write_to(&mut out).unwrap(); @@ -120,7 +126,7 @@ mod tests { let patched = apply(&original, "tail.payload_counts.2", Value::I64(42)); let ifo = SaveIfo::parse(&patched).unwrap(); - assert_eq!(ifo.payload_counts, [329, 349, 42, 200]); + assert_eq!(ifo.journal_strides, [329, 349, 42, 200]); } #[test] diff --git a/src/references/save_ifo/mod.rs b/src/references/save_ifo/mod.rs index 51799d13..32c7b05b 100644 --- a/src/references/save_ifo/mod.rs +++ b/src/references/save_ifo/mod.rs @@ -29,8 +29,9 @@ pub struct SaveIfo { pub map_id: u32, /// Reserved word; observed zero in all known files. pub reserved: u32, - /// Element counts snapshotted for traversing `game.tmp` payloads. - pub payload_counts: [u32; 4], + /// Per-journal record strides used when traversing `game.tmp`. + #[serde(alias = "payload_counts")] + pub journal_strides: [u32; 4], } impl Default for SaveIfo { @@ -41,7 +42,7 @@ impl Default for SaveIfo { game_tmp_key: 0, map_id: 0, reserved: 0, - payload_counts: [0; 4], + journal_strides: [0; 4], } } } @@ -105,8 +106,8 @@ impl SaveIfo { let game_tmp_key = cursor.read_u32::()?; let map_id = cursor.read_u32::()?; let reserved = cursor.read_u32::()?; - let mut payload_counts = [0u32; 4]; - for count in payload_counts.iter_mut() { + let mut journal_strides = [0u32; 4]; + for count in journal_strides.iter_mut() { *count = cursor.read_u32::()?; } @@ -127,7 +128,7 @@ impl SaveIfo { game_tmp_key, map_id, reserved, - payload_counts, + journal_strides, }) } @@ -155,7 +156,7 @@ impl SaveIfo { writer.write_u32::(self.game_tmp_key)?; writer.write_u32::(self.map_id)?; writer.write_u32::(self.reserved)?; - for count in &self.payload_counts { + for count in &self.journal_strides { writer.write_u32::(*count)?; } Ok(()) @@ -181,4 +182,19 @@ impl Extractor for SaveIfo { } #[cfg(test)] -mod tests {} +mod tests { + use super::*; + + #[test] + fn test_old_payload_counts_key_resolves() { + let mut value = serde_json::to_value(SaveIfo::default()).unwrap(); + let object = value.as_object_mut().unwrap(); + assert!(object.remove("journal_strides").is_some()); + object.insert( + "payload_counts".to_string(), + serde_json::json!([11, 22, 33, 44]), + ); + let ifo: SaveIfo = serde_json::from_value(value).unwrap(); + assert_eq!(ifo.journal_strides, [11, 22, 33, 44]); + } +} diff --git a/src/references/save_ifo/swap.rs b/src/references/save_ifo/swap.rs index 9a445fb2..7fe129f9 100644 --- a/src/references/save_ifo/swap.rs +++ b/src/references/save_ifo/swap.rs @@ -22,7 +22,8 @@ pub struct SavTail { pub game_tmp_key: u32, pub map_id: u32, pub reserved: u32, - pub payload_counts: [u32; 4], + #[serde(alias = "payload_counts")] + pub journal_strides: [u32; 4], } impl SavTail { @@ -40,8 +41,8 @@ impl SavTail { let game_tmp_key = cursor.read_u32::()?; let map_id = cursor.read_u32::()?; let reserved = cursor.read_u32::()?; - let mut payload_counts = [0u32; 4]; - for count in payload_counts.iter_mut() { + let mut journal_strides = [0u32; 4]; + for count in journal_strides.iter_mut() { *count = cursor.read_u32::()?; } Ok(SavTail { @@ -49,7 +50,7 @@ impl SavTail { game_tmp_key, map_id, reserved, - payload_counts, + journal_strides, }) } @@ -59,7 +60,7 @@ impl SavTail { writer.write_u32::(self.game_tmp_key)?; writer.write_u32::(self.map_id)?; writer.write_u32::(self.reserved)?; - for count in &self.payload_counts { + for count in &self.journal_strides { writer.write_u32::(*count)?; } Ok(()) @@ -354,7 +355,7 @@ mod tests { game_tmp_key: key, map_id: map, reserved: 0, - payload_counts: [key, key * 2, 0, key * 3], + journal_strides: [key, key * 2, 0, key * 3], } .write_to(&mut out) .unwrap(); @@ -401,7 +402,7 @@ mod tests { // Global tail untouched. assert_eq!(ifo.game_version, 0.0); assert_eq!(ifo.game_tmp_key, 0); - assert_eq!(ifo.payload_counts, [0; 4]); + assert_eq!(ifo.journal_strides, [0; 4]); } #[test] From 72d11ccada69166daf0a2aa0cb00b20ee024cb76 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:36:03 +0100 Subject: [PATCH 45/72] fix(core): rename modification resistance to cost --- dispel-gui/src/editors/edit_item/component.rs | 2 +- dispel-gui/src/tests/editor_field_edit.rs | 22 +++++++++++++++ docs/files/CharacterInGame/EditItem.db.md | 2 +- src/references/edit_item_db.rs | 27 +++++++++++++++---- 4 files changed, 46 insertions(+), 7 deletions(-) diff --git a/dispel-gui/src/editors/edit_item/component.rs b/dispel-gui/src/editors/edit_item/component.rs index ce012cb2..f2d55fed 100644 --- a/dispel-gui/src/editors/edit_item/component.rs +++ b/dispel-gui/src/editors/edit_item/component.rs @@ -19,7 +19,7 @@ editable_record_fields!(EditItem, { { offense = Integer / "Offense:" }, { defense = Integer / "Defense:" }, { magical_power = Integer / "Magic Power:" }, - { modification_resistance = Integer / "Modification Resistance:" }, + { modification_cost = Integer / "Modification Cost:" }, { reserved_byte = Integer / "Reserved Byte:" }, { modifies_item = Enum(EditItemModification, ["DoesNotModify", "CanModify"]) / "Modifies Item:" }, { additional_effect = Enum(EditItemEffect, ["None", "Fire", "HealthLeech"]) / "Effect:" }, diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index 378895c2..7e181244 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1063,6 +1063,28 @@ mod renamed_field_labels { ); } + #[test] + fn test_edit_item_modification_cost_label_accepts_old_key() { + let descriptor = EditItem::__editable_fields() + .iter() + .find(|field| field.name == "modification_cost") + .expect("the modification cost must be exposed in the inspector"); + assert_eq!(descriptor.label, "Modification Cost:"); + + let mut value = serde_json::to_value(EditItem::default()).unwrap(); + let object = value.as_object_mut().unwrap(); + assert!(object.remove("modification_cost").is_some()); + object.insert("modification_resistance".to_string(), serde_json::json!(12)); + let restored: EditItem = serde_json::from_value(value).unwrap(); + assert_eq!( + serde_json::to_value(&restored) + .unwrap() + .get("modification_cost") + .and_then(|v| v.as_i64()), + Some(12) + ); + } + #[test] fn test_edit_item_effect_health_leech_uses_new_name() { let descriptor = EditItem::__editable_fields() diff --git a/docs/files/CharacterInGame/EditItem.db.md b/docs/files/CharacterInGame/EditItem.db.md index aac8f087..42d6bc05 100644 --- a/docs/files/CharacterInGame/EditItem.db.md +++ b/docs/files/CharacterInGame/EditItem.db.md @@ -21,7 +21,7 @@ | 256 | 2 | `offense` | Offense modifier. | | 258 | 2 | `defense` | Defense modifier. | | 260 | 2 | `magical_power` | Magical-power modifier. | -| 262 | 2 | `modification_resistance` | Resistance to modification; a negative value lowers resistance. | +| 262 | 2 | `modification_cost` | Budget cost charged when modifying an item. | | 264 | 1 | `reserved_byte` | Always zero by default; purpose unknown. | | 265 | 1 | `modifies_item` | Whether this material can modify an item. | | 266 | 2 | `additional_effect` | Extra effect: none, fire, or health leech. | diff --git a/src/references/edit_item_db.rs b/src/references/edit_item_db.rs index a649072b..63162973 100644 --- a/src/references/edit_item_db.rs +++ b/src/references/edit_item_db.rs @@ -49,7 +49,7 @@ use dispel_macros::RecordPatcher; /// | - offense: i16 | /// | - defense: i16 | /// | - magical_power: i16 | -/// | - modification_resistance: i16 | +/// | - modification_cost: i16 | /// | - reserved_byte: u8 | /// | - modifies_item: u8 (EditItemModification)| /// | - additional_effect: i16 (EditItemEffect)| @@ -65,7 +65,7 @@ use dispel_macros::RecordPatcher; /// - **Economy**: `base_price` (i32, economic valuation) /// - **Stats**: `health_points`, `mana_points`, `strength`, `agility`, `wisdom`, `constitution` /// - **Combat**: `to_dodge`, `to_hit`, `offense`, `defense`, `magical_power` -/// - **Modification**: `modification_resistance` (resistance to item modification) +/// - **Modification**: `modification_cost` (budget cost of modifying an item) /// - **Behavior**: `modifies_item` (EditItemModification flag), `additional_effect` (EditItemEffect) /// - **Runtime metadata**: `runtime_item_id` is assigned by the game after loading. /// @@ -151,9 +151,11 @@ pub struct EditItem { /// Magical power bonus. #[extractor(primitive(type = "i16"))] pub magical_power: i16, - /// Resistance to modification by edit items. Negative values make an item easier to modify. + /// Budget cost charged when modifying an item. #[extractor(primitive(type = "i16"))] - pub modification_resistance: i16, + #[serde(alias = "modification_resistance")] + #[patcher(field_alias = "modification_resistance")] + pub modification_cost: i16, /// Reserved byte. Always zero by default; purpose unknown. #[extractor(primitive(type = "u8"))] pub reserved_byte: u8, @@ -191,7 +193,7 @@ pub fn save_edit_items(conn: &mut Connection, edit_items: &[EditItem]) -> Result item.offense, item.defense, item.magical_power, - item.modification_resistance, + item.modification_cost, item.reserved_byte, u8::from(item.modifies_item), i16::from(item.additional_effect), @@ -223,6 +225,21 @@ mod tests { rec } + #[test] + fn test_legacy_patcher_key_sets_modification_cost() { + use crate::modding::patcher::RecordPatcher; + use crate::modding::value::Value; + + let mut data = 1i32.to_le_bytes().to_vec(); + data.extend(item_bytes("MistvaleCharm", 120, 4, 10)); + let out = EditItemPatcher + .apply_field(&data, 0, "modification_resistance", &Value::I64(15)) + .expect("the stored patcher key must still be accepted"); + let mut cursor = Cursor::new(&out[..]); + let items = EditItem::parse(&mut cursor, out.len() as u64).unwrap(); + assert_eq!(items[0].modification_cost, 15); + } + #[test] fn parse_single_item() { let mut data = 1i32.to_le_bytes().to_vec(); From 1f9cbe6fb5e2a120b85f919ea37a1db76e6e5c40 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:46:35 +0100 Subject: [PATCH 46/72] docs(gui): clarify magic type proficiency --- dispel-gui/src/editors/magic/component.rs | 22 ++++++++++++++++++++-- dispel-gui/src/tests/editor_field_edit.rs | 19 +++++++++++++++++++ dispel-gui/src/tests/select_boxes.rs | 15 ++++++++++++++- docs/files/MagicInGame/Magic.db.md | 2 +- src/references/enums.rs | 14 +++++++------- src/references/magic_db.rs | 4 ++-- 6 files changed, 63 insertions(+), 13 deletions(-) diff --git a/dispel-gui/src/editors/magic/component.rs b/dispel-gui/src/editors/magic/component.rs index 69de0414..de218e6a 100644 --- a/dispel-gui/src/editors/magic/component.rs +++ b/dispel-gui/src/editors/magic/component.rs @@ -20,7 +20,7 @@ editable_record_fields!(MagicSpell, { { effect_type = Integer / "Effect Type:" }, { effect_modifier = Integer / "Effect Modifier:" }, { reserved_0x3c = Integer / "Reserved (0x3C):" }, - { magic_type = Enum(MagicType, ["Magic", "HolyMagic", "DarkMagic", "Fire", "Water", "Earth", "Air"]) / "Magic Type:" }, + { magic_type = Enum(MagicType, ["Magic", "HolyMagic", "DarkMagic", "Fire (no proficiency)", "Water (no proficiency)", "Earth (no proficiency)", "Air (no proficiency)"]) / "Magic Type:" }, { target_animation_blends_with_background = Boolean / "Target Animation Blends:" }, { animation_set_id = Integer / "Animation Set ID:" }, { effect_visual_id = Integer / "Effect Visual ID:" }, @@ -29,7 +29,25 @@ editable_record_fields!(MagicSpell, { }); impl EditableRecord for MagicSpell { - crate::editable_record_delegate!(); + fn field_descriptors() -> &'static [crate::components::editable::FieldDescriptor] { + ::__editable_fields() + } + + fn get_field(&self, f: &str) -> String { + if f == "magic_type" + && matches!( + self.magic_type, + MagicType::Fire | MagicType::Water | MagicType::Earth | MagicType::Air + ) + { + return format!("{:?} (no proficiency)", self.magic_type); + } + ::__editable_get(self, f) + } + + fn set_field(&mut self, f: &str, v: String) -> bool { + ::__editable_set(self, f, v) + } fn list_label(&self) -> String { format!( diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index 7e181244..baf51be7 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1015,6 +1015,25 @@ mod modified_flag_routing { mod renamed_field_labels { use crate::components::editable::{EditableRecordGenerated, FieldKind}; + + #[test] + fn test_magic_type_options_mark_elemental_schools_without_proficiency() { + let descriptor = MagicSpell::__editable_fields() + .iter() + .find(|field| field.name == "magic_type") + .expect("magic type must be exposed in the inspector"); + let FieldKind::Enum { variants } = &descriptor.kind else { + panic!("magic type must be an enum"); + }; + for school in ["Fire", "Water", "Earth", "Air"] { + let label = format!("{school} (no proficiency)"); + assert!(variants.contains(&label.as_str()), "missing option {label}"); + } + for school in ["Magic", "HolyMagic", "DarkMagic"] { + assert!(variants.contains(&school), "missing option {school}"); + } + } + use dispel_core::{ EditItem, EditItemEffect, ExtraRef, Extractor, HealItem, MagicSpell, Monster, MonsterIni, WeaponItem, diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs index a4275bae..6a5e8a34 100644 --- a/dispel-gui/src/tests/select_boxes.rs +++ b/dispel-gui/src/tests/select_boxes.rs @@ -64,6 +64,19 @@ impl LabelFormat for DisplayFormat { } } +struct MagicSchoolFormat; + +impl LabelFormat for MagicSchoolFormat { + fn label(value: &MagicType) -> String { + match value { + MagicType::Fire | MagicType::Water | MagicType::Earth | MagicType::Air => { + format!("{value:?} (no proficiency)") + } + _ => format!("{value:?}"), + } + } +} + /// Wire widths used by the enum fields under audit. trait WireScan: Copy { fn scan() -> Vec; @@ -463,7 +476,7 @@ fn test_every_enum_field_round_trips_through_both_views() { } audit_enum::("modifies_item", DebugFormat); audit_enum::("additional_effect", DebugFormat); - audit_enum::("magic_type", DebugFormat); + audit_enum::("magic_type", MagicSchoolFormat); audit_enum::("requires_target", DebugFormat); } diff --git a/docs/files/MagicInGame/Magic.db.md b/docs/files/MagicInGame/Magic.db.md index cb804bb4..21710393 100644 --- a/docs/files/MagicInGame/Magic.db.md +++ b/docs/files/MagicInGame/Magic.db.md @@ -26,7 +26,7 @@ All fields are little-endian `u32` values. The record ID is its zero-based posit | 44 | `animation_data_index` | Index into the animation data table, resolved to a pointer after file load | | 48–56 | `effect_value`, `effect_type`, `effect_modifier` | Effect configuration; exact semantics are not yet established | | 60 | `reserved_0x3c` | Reserved word; zero by default | -| 64 | `magic_type` | Magic type (0=Magic, 1=HolyMagic, 2=DarkMagic) — selects which character magic-skill attribute drives damage, success, and mana-cost calculations | +| 64 | `magic_type` | Magic type (0=Magic, 1=HolyMagic, 2=DarkMagic); only these three have proficiency. 3=Fire, 4=Water, 5=Earth, 6=Air have none. | | 68 | `target_animation_blends_with_background` | `0`=Off, `1`=On — uses blended rendering for the target animation instead of direct blitting | | 72 | `animation_set_id` | Cast-animation set | | 76 | `effect_visual_id` | Visual/projectile mapping selected when casting | diff --git a/src/references/enums.rs b/src/references/enums.rs index b15097cc..43cb0b6c 100644 --- a/src/references/enums.rs +++ b/src/references/enums.rs @@ -1358,9 +1358,9 @@ impl From for HealItemFlag { /// Magic type classification for spells. /// -/// Each spell belongs to one of seven types: three schools of magic plus four -/// elemental types. The player's proficiency in a type rises as they cast -/// spells of that type. +/// Each spell belongs to one of seven types. Only wizardry, holy and dark magic +/// have a proficiency that rises as their spells are cast; the four elemental +/// types have no proficiency progression. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] #[repr(u32)] pub enum MagicType { @@ -1407,10 +1407,10 @@ impl MagicType { "Magic" => Some(MagicType::Magic), "HolyMagic" => Some(MagicType::HolyMagic), "DarkMagic" => Some(MagicType::DarkMagic), - "Fire" => Some(MagicType::Fire), - "Water" => Some(MagicType::Water), - "Earth" => Some(MagicType::Earth), - "Air" => Some(MagicType::Air), + "Fire" | "Fire (no proficiency)" => Some(MagicType::Fire), + "Water" | "Water (no proficiency)" => Some(MagicType::Water), + "Earth" | "Earth (no proficiency)" => Some(MagicType::Earth), + "Air" | "Air (no proficiency)" => Some(MagicType::Air), _ => None, } } diff --git a/src/references/magic_db.rs b/src/references/magic_db.rs index 263cbf5a..9c0d4132 100644 --- a/src/references/magic_db.rs +++ b/src/references/magic_db.rs @@ -148,8 +148,8 @@ pub struct MagicSpell { #[extractor(primitive(type = "u32"))] pub reserved_0x3c: u32, - /// Magic type (Magic=0, HolyMagic=1, DarkMagic=2) — selects which character - /// magic-skill attribute drives damage, success, and mana-cost calculations. + /// Magic type. Wizardry, holy and dark magic have a proficiency that feeds + /// damage, success and mana-cost calculations; the elemental types do not. #[extractor(enum_from_u32(type = "MagicType"))] pub magic_type: MagicType, From 507a75f3964a265669e8d26ee22ca51d6fb0749e Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:52:32 +0100 Subject: [PATCH 47/72] docs: describe shipped sprites as RGB565 --- docs/files/Sprites.spr.md | 13 +++++++------ src/sprite.rs | 29 ++++++++++++++++++++--------- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/docs/files/Sprites.spr.md b/docs/files/Sprites.spr.md index 7be8f3ae..e162ff60 100644 --- a/docs/files/Sprites.spr.md +++ b/docs/files/Sprites.spr.md @@ -10,7 +10,7 @@ little-endian byte order. - **Extension:** `.spr` - **Data:** counted sequence records - **Pixel data:** one or two bytes per pixel -- **Two-byte formats:** RGB555 or RGB565 +- **Two-byte format:** RGB565 for shipped assets; RGB555 is a legacy compatibility option ## File Layout @@ -72,7 +72,7 @@ pixel_data_size = pixel_count × bytes_per_pixel ## Two-Byte Pixel Data -Two-byte pixels use RGB555 or RGB565 packing. +Shipped assets use RGB565 packing. RGB555 is a legacy compatibility option and is not used by shipped assets. | Format | Red | Green | Blue | |---|---|---|---| @@ -86,16 +86,17 @@ to export this value as opaque `#000000`. ### Format Selection -The layout has no field that selects RGB555 or RGB565. +The layout has no field that selects RGB555 or RGB565. Shipped assets use +RGB565, so that is the expected format for every two-byte archive. -The parser uses this rule for an archive with two-byte pixels: +The bit-15 classifier is a legacy compatibility option only: 1. If a non-zero pixel has bit 15 set, use RGB565. 2. Otherwise, use RGB555. 3. If all pixels are zero, use RGB565. -This rule cannot identify an RGB565 archive that never sets bit 15. Add an -explicit format option if such a file needs different handling. +The classifier cannot identify an RGB565 archive that never sets bit 15. It is +retained for compatibility and does not change how shipped assets are encoded. ## Frame Position diff --git a/src/sprite.rs b/src/sprite.rs index 5ba33337..7d39f707 100644 --- a/src/sprite.rs +++ b/src/sprite.rs @@ -18,7 +18,8 @@ use std::{fs::File, path::Path}; // - leading i32 sequence count, followed by counted, variable-length groups // - each sequence has a 268-byte header and zero or more frame groups // - each group: 12-byte header → frame metadata blocks → pixel data -// - 16-bit RGB555 or RGB565, 0x0000=transparent, little-endian +// - 16-bit RGB565 for shipped assets, 0x0000=transparent, little-endian +// - RGB555 classification is a legacy compatibility option only // - Frames have origin_x/origin_y for alignment in a bounding rect // // Reading flow: @@ -63,8 +64,8 @@ pub struct ImageInfo { pub size_bytes: i64, /// Number of bytes occupied by one pixel in the source stream. /// - /// Normal groups use two-byte RGB555 or RGB565 pixels. The original loader - /// also recognizes one-byte groups; they are parsed and skipped correctly, + /// Normal groups use two-byte RGB565 pixels; RGB555 classification is a + /// legacy compatibility option. One-byte groups are parsed and skipped correctly, /// but cannot be rendered without their palette. pub bytes_per_pixel: u8, /// Channel packing for a two-byte pixel. @@ -310,9 +311,9 @@ fn read_sprite_sequence_infos( Ok(sequences) } -/// The archive has no explicit RGB555/RGB565 tag. The original blitter selects -/// its masks from the display configuration; assets themselves reveal RGB555 -/// by never using bit 15. `Menu/MBack.spr` is the verified shipped example. +/// The archive has no explicit RGB555/RGB565 tag. Shipped assets use RGB565. +/// The bit-15 check below is a legacy compatibility option kept for files that +/// need the older classification; it does not change the shipped-asset format. fn assign_16bit_pixel_format( reader: &mut BufReader, sequences: &mut [SequenceInfo], @@ -966,7 +967,8 @@ pub fn rgba_to_rgb565_bytes(r: u8, g: u8, b: u8, a: u8) -> [u8; 2] { /// Encode a single RGBA pixel as two RGB555 bytes (little-endian). /// -/// Pixels with alpha < 128 are encoded as `0x0000` (transparent). +/// Shipped assets use RGB565; this helper supports the legacy classification +/// path only. Pixels with alpha < 128 are encoded as `0x0000`. pub fn rgba_to_rgb555_bytes(r: u8, g: u8, b: u8, a: u8) -> [u8; 2] { if a < 128 { return [0, 0]; @@ -995,6 +997,15 @@ mod tests { use super::*; use std::io::Cursor; + #[test] + fn test_docs_state_shipped_sprites_use_rgb565() { + let docs = include_str!("../docs/files/Sprites.spr.md"); + assert!( + docs.contains("Shipped assets use RGB565"), + "the format doc must describe RGB565 as the shipped format" + ); + } + #[test] fn test_get_sequence_info_rejects_negative_frame_count() { // A zero stamp is followed by frame_count and a reserved word. @@ -1109,8 +1120,8 @@ mod tests { #[test] fn test_editor_model_write_reparse_fidelity() { - // Rgb565 (bit 15 set) and Rgb555 (bit 15 clear) archives must both - // survive a write → reparse through the authoritative decoder. + // Shipped RGB565 archives and legacy-classified Rgb555 archives must + // both survive a write → reparse through the decoder. for (label, pixel, format) in [ ("rgb565", 0xF800_u16, SpritePixelFormat::Rgb565), ("rgb555", 0x03E0_u16, SpritePixelFormat::Rgb555), From 06f0f9ffb65e6df3ccaa87c4d589af32194ca8ea Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:02:25 +0100 Subject: [PATCH 48/72] docs(save): describe walk records as countdowns --- AGENTS.md | 4 ++-- docs/files/SaveFile.md | 4 ++-- src/references/save_file/events.rs | 26 +++++++++++++++++++++++--- 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ef5086ac..10c30c96 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -179,7 +179,7 @@ Core modules: `apply`, `bsdiff`, `change`, `changelog`, `conflicts`, `manifest`, The directory holds 118 SQL files: 59 `create_table_*.sql` files for schema DDL and 59 parameterized `insert_*.sql` files. `database.rs` runs them to drop and recreate the schema. The schema has no foreign keys. Code enforces relationships. ### Tests -The root crate has **95 `#[cfg(test)]` blocks across 87 `.rs` files**. Parsers use hardcoded byte-slice unit tests. Save-file round-trip checking lives in `examples/check_save_roundtrip.rs`. +The root crate has **96 `#[cfg(test)]` blocks across 88 `.rs` files**. Parsers use hardcoded byte-slice unit tests. Save-file round-trip checking lives in `examples/check_save_roundtrip.rs`. --- @@ -495,7 +495,7 @@ Read the relevant `docs/files/*.md` before you change a parser. ### Testing Effective tests: find real bugs. Compilation alone is not enough. Prefer `iced_test` integration tests that simulate user flows. They catch behavioural regressions, state corruption and edge cases. -- **dispel-core**: unit test every new parser with hardcoded byte slices (95 `#[cfg(test)]` blocks across 87 `.rs` files) +- **dispel-core**: unit test every new parser with hardcoded byte slices (96 `#[cfg(test)]` blocks across 88 `.rs` files) - dispel-gui: write iced_test integration tests that simulate user flows, such as tab opens, data edits, undo, redo and saves. Test state transitions and behaviour, not visuals. The dedicated suite is in `dispel-gui/src/tests/` (30 files), with co-located `#[cfg(test)]` blocks. - **Round-trip checks**: `examples/check_save_roundtrip.rs` (parse → write → compare) - **Test naming**: `test_${scenario}_${condition}` e.g. `test_undo_weapon_editor_empty_history` diff --git a/docs/files/SaveFile.md b/docs/files/SaveFile.md index 1324204c..12bc6b8e 100644 --- a/docs/files/SaveFile.md +++ b/docs/files/SaveFile.md @@ -314,7 +314,7 @@ The tool writes milestone records at walk animation milestones. These occur when | Field | Type | Description | |-------------|-------|-------------------------------------------------------------------------------------------------------------------------| -| `id` | `u32` | Event id: `400`; `10`/`100`/`200`/`300` while the walk-freshness counter is active; ascending global counter by default | +| `id` | `u32` | Descending countdown kind: `400`, or `10`/`100`/`200`/`300` while the walk freshness countdown is active | | `direction` | `u32` | Walk direction (animation-step direction, 0-7) | | `state` | `u32` | Character state byte (`1` while walking) | | `walk_type` | `u32` | Walk-type flag: `0` in save-format version 1.45 (which duplicates `direction` here); `1` by default | @@ -325,7 +325,7 @@ The tool writes milestone records at walk animation milestones. These occur when | Field | Type | Description | |-------------------|-------|-----------------------------------------------------------------------------------------| -| `id` | `u32` | Event id: `2000` in save-format version 1.45; ascending global counter by default | +| `id` | `u32` | Countdown kind: `2000` for a completed walk cycle | | `direction` | `u32` | Normalized walk direction (0-3; walk directions 4-7 map to 0-3) | | `diagonal` | `u32` | Diagonal flag (`1` for diagonal walk directions) | | `character_index` | `u32` | Character index (`0` for party members in save-format version 1.45; `0`-`2` by default) | diff --git a/src/references/save_file/events.rs b/src/references/save_file/events.rs index d79f1323..6ce32909 100644 --- a/src/references/save_file/events.rs +++ b/src/references/save_file/events.rs @@ -172,8 +172,8 @@ impl PostEventsData { /// reaches its movement milestone. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default, BinaryRecord)] pub struct WalkMilestoneRecord { - /// Event id. `400`; `10`/`100`/`200`/`300` when the - /// walk-freshness counter is active; ascending global counter across saves. + /// Countdown kind. `400`, or `10`/`100`/`200`/`300` while the walk + /// freshness countdown is active. Descending values, not an event id. pub id: u32, /// Walk direction (animation-step direction, 0-7). pub direction: u32, @@ -193,7 +193,7 @@ pub struct WalkMilestoneRecord { /// The record is created when the active path reaches its completion point. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default, BinaryRecord)] pub struct WalkCompletionRecord { - /// Event id. `2000`; ascending global counter across saves. + /// Countdown kind. `2000` for a completed walk cycle; not an event id. pub id: u32, /// Normalized walk direction (0-3; walk directions 4-7 map to 0-3). pub direction: u32, @@ -207,3 +207,23 @@ pub struct WalkCompletionRecord { /// Y coordinate. pub y: u32, } + +#[cfg(test)] +mod tests { + #[test] + fn test_walk_records_describe_countdown_kinds() { + let source = include_str!("events.rs"); + let docs = include_str!("../../../docs/files/SaveFile.md"); + for text in [source, docs] { + assert!( + text.contains("countdown"), + "countdown description is missing" + ); + let stale_claim = format!("ascending {} counter", "global"); + assert!( + !text.contains(&stale_claim), + "the counter claim must be gone" + ); + } + } +} From e32c885d0828ddcbe24c2f7e267c7e8801dd1cf1 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:09:19 +0100 Subject: [PATCH 49/72] fix(core): rename next dialog to fallback --- .../src/editors/dialogue_script/component.rs | 2 +- dispel-gui/src/tests/editor_field_edit.rs | 26 +++++++++++++++++-- docs/files/CROSS_REFERENCES.md | 4 +-- src/modding/patchers/dialogue.rs | 2 +- src/references/dialogue_script.rs | 15 ++++++----- 5 files changed, 36 insertions(+), 13 deletions(-) diff --git a/dispel-gui/src/editors/dialogue_script/component.rs b/dispel-gui/src/editors/dialogue_script/component.rs index e6ca32bf..73c78f0c 100644 --- a/dispel-gui/src/editors/dialogue_script/component.rs +++ b/dispel-gui/src/editors/dialogue_script/component.rs @@ -4,7 +4,7 @@ use dispel_core::{DialogOwner, DialogType, DialogueScript}; crate::editable_record_fields!(DialogueScript, { { id = Integer / "ID:" }, { required_event_id = OptInt / "Requires Event ID:" }, - { next_dialog_to_check = OptInt / "Next Dialog:" }, + { fallback_dialog_id = OptInt / "Fallback Node (gate fails):" }, { dialog_type = Opti32Enum(DialogType, ["Normal", "Choice"]) / "Type:" }, { dialog_owner = Opti32Enum(DialogOwner, ["Player", "Npc"]) / "Owner:" }, { dialog_id = OptInt / "Dialog ID:" }, diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index baf51be7..746b88d3 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1016,6 +1016,28 @@ mod modified_flag_routing { mod renamed_field_labels { use crate::components::editable::{EditableRecordGenerated, FieldKind}; + #[test] + fn test_dialogue_fallback_label_accepts_old_key() { + let descriptor = DialogueScript::__editable_fields() + .iter() + .find(|field| field.name == "fallback_dialog_id") + .expect("the fallback node must be exposed in the inspector"); + assert_eq!(descriptor.label, "Fallback Node (gate fails):"); + + let mut value = serde_json::to_value(DialogueScript::default()).unwrap(); + let object = value.as_object_mut().unwrap(); + assert!(object.remove("fallback_dialog_id").is_some()); + object.insert("next_dialog_to_check".to_string(), serde_json::json!(42)); + let restored: DialogueScript = serde_json::from_value(value).unwrap(); + assert_eq!( + serde_json::to_value(&restored) + .unwrap() + .get("fallback_dialog_id") + .and_then(|v| v.as_i64()), + Some(42) + ); + } + #[test] fn test_magic_type_options_mark_elemental_schools_without_proficiency() { let descriptor = MagicSpell::__editable_fields() @@ -1035,8 +1057,8 @@ mod renamed_field_labels { } use dispel_core::{ - EditItem, EditItemEffect, ExtraRef, Extractor, HealItem, MagicSpell, Monster, MonsterIni, - WeaponItem, + DialogueScript, EditItem, EditItemEffect, ExtraRef, Extractor, HealItem, MagicSpell, + Monster, MonsterIni, WeaponItem, }; #[test] diff --git a/docs/files/CROSS_REFERENCES.md b/docs/files/CROSS_REFERENCES.md index b1d668cc..44730718 100644 --- a/docs/files/CROSS_REFERENCES.md +++ b/docs/files/CROSS_REFERENCES.md @@ -138,7 +138,7 @@ NpcInGame/Eventnpc.ref NpcInGame/Dlgcat1.dlg (on-disk labels in parentheses) ├── required_event_id (prev_event) → event index - ├── next_dialog_to_check (next_dlg) → Dlg script + ├── fallback_dialog_id (next_dlg) → alternate Dlg script on gate failure ├── dialog_id (dlg_id) → Pgpcat1.pgp paragraph └── triggered_event_id (event_id) → event index @@ -227,7 +227,7 @@ Note: 0 ends the list. A store holds at most 15 products. | Eventnpc.ref | show_on_event | event index | - | Trigger | | Eventnpc.ref | dialog_id | Dlgcat1.dlg | id | Dialogue | | Dlgcat1.dlg | required_event_id | event index | - | Prerequisite | -| Dlgcat1.dlg | next_dialog_to_check | Dlgcat1.dlg | id | Chain | +| Dlgcat1.dlg | fallback_dialog_id | Dlgcat1.dlg | id | Gate-failure fallback | | Dlgcat1.dlg | dialog_id | Pgpcat1.pgp | paragraph | Text | | Dlgcat1.dlg | triggered_event_id | event index | - | Trigger | | Pgpcat1.pgp | wave_ini_entry_id | Wave.ini | index | Voice audio | diff --git a/src/modding/patchers/dialogue.rs b/src/modding/patchers/dialogue.rs index eed365d4..233a80d7 100644 --- a/src/modding/patchers/dialogue.rs +++ b/src/modding/patchers/dialogue.rs @@ -61,7 +61,7 @@ impl RecordPatcher for DialogueScriptPatcher { ))); } "required_event_id" => rec.required_event_id = parse_optional_i32(field, new)?, - "next_dialog_to_check" => rec.next_dialog_to_check = parse_optional_i32(field, new)?, + "next_dialog_to_check" => rec.fallback_dialog_id = parse_optional_i32(field, new)?, "dialog_id" => rec.dialog_id = parse_optional_i32(field, new)?, "next_dialog_id1" => rec.next_dialog_id1 = parse_optional_i32(field, new)?, "next_dialog_id2" => rec.next_dialog_id2 = parse_optional_i32(field, new)?, diff --git a/src/references/dialogue_script.rs b/src/references/dialogue_script.rs index 0cd007ae..0c46cd68 100644 --- a/src/references/dialogue_script.rs +++ b/src/references/dialogue_script.rs @@ -36,7 +36,7 @@ use serde::{Deserialize, Serialize}; /// /// - `id`: Unique dialogue line identifier /// - `required_event_id`: Required event ID to trigger (shown as `prev_event` in file) -/// - `next_dialog_to_check`: Next dialogue ID in chain (shown as `next_dlg` in file) +/// - `fallback_dialog_id`: alternate dialogue when the gate fails or the paragraph is empty (`next_dlg` in file) /// - `dialog_type`: 0 = normal, 1 = choice dialog (shown as `type` in file) /// - `dialog_owner`: 0 = player, 1 = NPC (shown as `owner` in file) /// - `dialog_id`: Reference to PGP text content (shown as `dlg_id` in file) @@ -72,8 +72,9 @@ pub struct DialogueScript { pub id: i32, /// Required event to trigger this dialog. pub required_event_id: Option, - /// Reference link to the next dialog node in the chain. - pub next_dialog_to_check: Option, + /// Alternate dialog used when the gate fails or the paragraph is empty; `0` ends the chain. + #[serde(alias = "next_dialog_to_check")] + pub fallback_dialog_id: Option, /// Type of dialog (normal or choice). /// In case of the choice, the choices are in next_dialog_id1, next_dialog_id2, next_dialog_id3 unless they are zero. pub dialog_type: Option, @@ -114,7 +115,7 @@ impl Extractor for DialogueScript { continue; }; let required_event_id = parse_int(parts[1].trim()); - let next_dialog_to_check = parse_int(parts[2].trim()); + let fallback_dialog_id = parse_int(parts[2].trim()); let dialog_type_id = parse_int(parts[3].trim()); let dialog_owner_id = parse_int(parts[4].trim()); let dialog_id = parse_int(parts[5].trim()); @@ -129,7 +130,7 @@ impl Extractor for DialogueScript { dlgs.push(DialogueScript { id, required_event_id, - next_dialog_to_check, + fallback_dialog_id, dialog_type, dialog_owner, dialog_id, @@ -148,7 +149,7 @@ impl Extractor for DialogueScript { .required_event_id .map_or_else(|| "0".to_string(), |v| v.to_string()); let next = record - .next_dialog_to_check + .fallback_dialog_id .map_or_else(|| "0".to_string(), |v| v.to_string()); let dtype = record .dialog_type @@ -200,7 +201,7 @@ pub fn save_dialogs( dialog_file_id, dialog.id, dialog.required_event_id, - dialog.next_dialog_to_check, + dialog.fallback_dialog_id, dialog.dialog_type.map(|v| v.value()), dialog.dialog_owner.map(|v| v.value()), dialog.dialog_id, From 12b7bd40579f4a6ab379eb7794da7e7114e22d01 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:19:50 +0100 Subject: [PATCH 50/72] fix(core): rename dialogue param1 to next page id --- .../editors/dialogue_paragraph/component.rs | 2 +- dispel-gui/src/tests/editor_field_edit.rs | 26 +++++++++++++++++-- docs/files/NpcInGame/PgpMapFiles.pgp.md | 8 +++--- src/modding/patchers/dialogue.rs | 11 +++++++- src/references/dialogue_paragraph.rs | 21 ++++++++------- 5 files changed, 50 insertions(+), 18 deletions(-) diff --git a/dispel-gui/src/editors/dialogue_paragraph/component.rs b/dispel-gui/src/editors/dialogue_paragraph/component.rs index 25b47ea0..59472369 100644 --- a/dispel-gui/src/editors/dialogue_paragraph/component.rs +++ b/dispel-gui/src/editors/dialogue_paragraph/component.rs @@ -7,7 +7,7 @@ editable_record_fields!(DialogueParagraph, { { id = Integer / "ID:" }, { text = TextArea / "Text:" }, { comment = TextArea / "Comment:" }, - { param1 = Integer / "Param 1:" }, + { next_page_id = Integer / "Next Page ID:" }, { wave_ini_entry_id = Integer / "Wave ID:" }, }); diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index 746b88d3..f61b998c 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1016,6 +1016,28 @@ mod modified_flag_routing { mod renamed_field_labels { use crate::components::editable::{EditableRecordGenerated, FieldKind}; + #[test] + fn test_dialogue_next_page_id_label_accepts_old_key() { + let descriptor = DialogueParagraph::__editable_fields() + .iter() + .find(|field| field.name == "next_page_id") + .expect("the next page id must be exposed in the inspector"); + assert_eq!(descriptor.label, "Next Page ID:"); + + let mut value = serde_json::to_value(DialogueParagraph::default()).unwrap(); + let object = value.as_object_mut().unwrap(); + assert!(object.remove("next_page_id").is_some()); + object.insert("param1".to_string(), serde_json::json!(17)); + let restored: DialogueParagraph = serde_json::from_value(value).unwrap(); + assert_eq!( + serde_json::to_value(&restored) + .unwrap() + .get("next_page_id") + .and_then(|v| v.as_i64()), + Some(17) + ); + } + #[test] fn test_dialogue_fallback_label_accepts_old_key() { let descriptor = DialogueScript::__editable_fields() @@ -1057,8 +1079,8 @@ mod renamed_field_labels { } use dispel_core::{ - DialogueScript, EditItem, EditItemEffect, ExtraRef, Extractor, HealItem, MagicSpell, - Monster, MonsterIni, WeaponItem, + DialogueParagraph, DialogueScript, EditItem, EditItemEffect, ExtraRef, Extractor, HealItem, + MagicSpell, Monster, MonsterIni, WeaponItem, }; #[test] diff --git a/docs/files/NpcInGame/PgpMapFiles.pgp.md b/docs/files/NpcInGame/PgpMapFiles.pgp.md index a52cc18b..bcc725c9 100644 --- a/docs/files/NpcInGame/PgpMapFiles.pgp.md +++ b/docs/files/NpcInGame/PgpMapFiles.pgp.md @@ -20,7 +20,7 @@ - `id`: i32 - Unique dialogue text identifier - `text`: String - Display text content - `comment`: String - Developer notes (accumulated from preceding `;` comment lines, joined with ` | `) -- `param1`: i32 - Dialogue branch conditions +- `param1`: i32 - next page id in the PGP chain - `wave_ini_entry_id`: i32 - ID of sound from `Wave.ini`, played at start of dialogue ## Field Definitions @@ -28,12 +28,12 @@ - `id`: Unique dialogue text identifier - `text`: Display text content - `comment`: Developer notes (accumulated from preceding `;` comment lines) -- `param1`: Dialogue branch conditions +- `param1`: next page id in the PGP chain - `wave_ini_entry_id`: Sound effect ID from `Wave.ini` ## Parameter Usage -- `param1`: Dialogue branch conditions +- `param1`: next page id; zero ends the chain - `wave_ini_entry_id`: sound effect at dialogue start. Zero means none. ## Text Formatting @@ -46,7 +46,7 @@ ## Special Values -- `param1 = 0`: Unconditional dialogue +- `param1 = 0`: no next page - `wave_ini_entry_id = 0`: No sound trigger - Empty text: `"null"` literal (mapped to empty string on parse) - Comment lines preserved with `;` prefix diff --git a/src/modding/patchers/dialogue.rs b/src/modding/patchers/dialogue.rs index 233a80d7..48127dd2 100644 --- a/src/modding/patchers/dialogue.rs +++ b/src/modding/patchers/dialogue.rs @@ -149,7 +149,7 @@ impl RecordPatcher for DialogueParagraphPatcher { Value::String(s) => rec.comment = s.clone(), _ => return Err(wrong_type(Self::RECORD_NAME, field, "string", new)), }, - "param1" => rec.param1 = parse_i32(field, new)?, + "param1" => rec.next_page_id = parse_i32(field, new)?, "wave_ini_entry_id" => rec.wave_ini_entry_id = parse_i32(field, new)?, other => return Err(unknown_field(Self::RECORD_NAME, other)), } @@ -253,6 +253,15 @@ mod tests { DialogueParagraph::parse(&mut Cursor::new(b), b.len() as u64).unwrap() } + #[test] + fn pgp_param1_key_still_sets_next_page_id() { + let p = DialogueParagraphPatcher; + let out = p + .apply_field(&pgp_blob(), 1, "param1", &Value::I64(17)) + .expect("the stored patcher key must still be accepted"); + assert_eq!(parse_paras(&out)[1].next_page_id, 17); + } + #[test] fn pgp_change_text() { let p = DialogueParagraphPatcher; diff --git a/src/references/dialogue_paragraph.rs b/src/references/dialogue_paragraph.rs index 1e87aa1d..85f0303b 100644 --- a/src/references/dialogue_paragraph.rs +++ b/src/references/dialogue_paragraph.rs @@ -41,7 +41,7 @@ use dispel_macros::Localizable; /// - `id`: Unique dialogue text identifier /// - `text`: Display text content (uses `"null"` for empty strings) /// - `comment`: Developer notes (multi-line, separated by ` | `) -/// - `param1`: Logic parameter (dialogue branch conditions) +/// - `param1` column: next page id in the PGP chain (may be `0` to end) /// - `wave_ini_entry_id`: ID of sound from `wave.ini` file, played at start of dialogue /// /// # Text Formatting @@ -54,7 +54,7 @@ use dispel_macros::Localizable; /// /// # Special Values /// -/// - `param1` = 0: Unconditional dialogue +/// - `param1` = 0: no next page /// - `wave_ini_entry_id` = 0: No sound trigger /// - Empty text: `"null"` literal /// - Comment lines preserved with `;` prefix @@ -73,8 +73,9 @@ pub struct DialogueParagraph { pub text: String, /// Developer trailing strings (`\;`) restored and preserved internally. pub comment: String, - /// Internal tracking modifier block associated to dialog output. - pub param1: i32, + /// Next page id in the PGP dialogue chain. + #[serde(alias = "param1")] + pub next_page_id: i32, /// ID of the sound from the wave.ini file. Played at start of dialogue. pub wave_ini_entry_id: i32, } @@ -132,14 +133,14 @@ impl Extractor for DialogueParagraph { } else { raw_text.to_string() }; - let param1 = parts[2].trim().parse::().unwrap_or(0); + let next_page_id = parts[2].trim().parse::().unwrap_or(0); let wave_ini_entry_id = parts[3].trim().parse::().unwrap_or(0); texts.push(DialogueParagraph { id, text, comment: current_comment.clone().trim_matches('|').to_string(), - param1, + next_page_id, wave_ini_entry_id, }); @@ -164,7 +165,7 @@ impl Extractor for DialogueParagraph { }; let line = format!( "{}|{}|{}|{}\r\n", - record.id, text_val, record.param1, record.wave_ini_entry_id + record.id, text_val, record.next_page_id, record.wave_ini_entry_id ); let (cow, _, _) = WINDOWS_1250.encode(&line); writer.write_all(&cow)?; @@ -191,7 +192,7 @@ pub fn save_dialogue_paragraphs( text.id, text.text, text.comment, - text.param1, + text.next_page_id, if text.wave_ini_entry_id > 0 { Some(text.wave_ini_entry_id) } else { @@ -218,11 +219,11 @@ mod tests { assert_eq!(paras[0].id, 1); assert_eq!(paras[0].text, "Hello there"); assert_eq!(paras[0].comment, "dev note"); - assert_eq!(paras[0].param1, 0); + assert_eq!(paras[0].next_page_id, 0); assert_eq!(paras[0].wave_ini_entry_id, 0); assert_eq!(paras[1].id, 2); assert_eq!(paras[1].text, ""); // "null" replaced with "" - assert_eq!(paras[1].param1, 5); + assert_eq!(paras[1].next_page_id, 5); assert_eq!(paras[1].wave_ini_entry_id, 3); } From fd5e3a3345561b28154c537bbc5d9f26f462505d Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:27:46 +0100 Subject: [PATCH 51/72] fix(core): rename overlay mode fields --- docs/files/Map/Map.map.md | 2 +- docs/files/Map/MapModule.md | 2 +- src/database/map_persistence.rs | 2 +- src/map/mod.rs | 71 ++++++++++++++++++++++++++++++++- src/map/reader.rs | 31 ++++++++++++-- src/map/render.rs | 22 +++++----- 6 files changed, 112 insertions(+), 18 deletions(-) diff --git a/docs/files/Map/Map.map.md b/docs/files/Map/Map.map.md index be5cbdb0..2e04b60d 100644 --- a/docs/files/Map/Map.map.md +++ b/docs/files/Map/Map.map.md @@ -203,7 +203,7 @@ This grid packs **two layers** in one u32: 1. BTL overlay ref (bits 0 to 14): when the referenced Second Block entry has its high byte set, the renderer blits BTL pixels from `btl_base + ref_id × 2048` (entry *low* byte selects transparent vs opaque - blit). So the Second Block is `{transparency, draw_enable}` per overlay id. + blit). So the Second Block is `{blit_mode, shadow_on}` per overlay id. 2. Shadow and fog level (bits 15 to 29): the value spans 0 to 199. The documented rule raises the value for light sources. The highest value wins. On a dark map, a BTL overlay must have a non-zero reference and at least one diff --git a/docs/files/Map/MapModule.md b/docs/files/Map/MapModule.md index cfd04d2d..c0077eb2 100644 --- a/docs/files/Map/MapModule.md +++ b/docs/files/Map/MapModule.md @@ -841,7 +841,7 @@ This JSON schema describes exported `.MAP` data: | 12 | 4 | `object_ref_count` | i32 LE | | 16 | var | `object_ref_records` | Skip `(count − 1) × 8` bytes; each record's `value2` is a linear tile index into the end grids | | var | 4 | `overlay_table_size` | i32 LE | -| var | var | `overlay_table` | `size × 2` bytes; u16 entries `{transparency, draw_enable}` indexed by Access-Ref ids | +| var | var | `overlay_table` | `size × 2` bytes; u16 entries `{blit_mode, shadow_on}` indexed by Access-Ref ids | | var | 4 | `sprite_count` | i32 LE | | var | var | `sprite entries` | Each: stamp(4) + meta(264) + sequence_info + padding | | var | 4 | `sprite_placement_count` | i32 LE | diff --git a/src/database/map_persistence.rs b/src/database/map_persistence.rs index 051e773d..ea211d4e 100644 --- a/src/database/map_persistence.rs +++ b/src/database/map_persistence.rs @@ -312,7 +312,7 @@ pub fn save_map_metadata(conn: &mut Connection, map_id: &str, model: &MapModel) } /// Persists the overlay-id lookup table: one row per u16 entry, with the -/// low byte decoded as transparency mode and the high byte as draw-enable. +/// low byte decoded as the roof blit mode and the high byte as shadow-on. pub fn save_map_overlay_modes( conn: &mut Connection, map_id: &str, diff --git a/src/map/mod.rs b/src/map/mod.rs index fcfb8c3c..833a891f 100644 --- a/src/map/mod.rs +++ b/src/map/mod.rs @@ -144,11 +144,72 @@ use std::io::{BufReader, Seek, SeekFrom}; use std::path::Path; use crate::sprite::SequenceInfo; -use serde::{Deserialize, Serialize}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// IO Result type for file operations type IoResult = std::io::Result; +/// Roof overlay blit mode stored in the low byte of an overlay-table entry. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum RoofBlitMode { + /// Copy the tile diamond opaquely. + #[default] + Opaque = 0, + /// Blit the tile diamond while skipping black pixels. + SkipBlack = 1, +} + +impl RoofBlitMode { + /// Classify the byte value stored in the map file. + pub fn from_byte(value: u8) -> Self { + if value == 0 { + Self::Opaque + } else { + Self::SkipBlack + } + } + + pub fn byte(self) -> u8 { + self as u8 + } +} + +impl Serialize for RoofBlitMode { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_u8(self.byte()) + } +} + +impl<'de> Deserialize<'de> for RoofBlitMode { + fn deserialize>(deserializer: D) -> Result { + Ok(Self::from_byte(u8::deserialize(deserializer)?)) + } +} + +/// One overlay-table entry: a roof blit mode and the shadow-on flag. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +pub struct OverlayMode { + #[serde(alias = "transparency_mode")] + pub blit_mode: RoofBlitMode, + #[serde(alias = "draw_enable")] + pub shadow_on: u8, +} + +impl OverlayMode { + /// Decode an overlay-table entry without changing its bytes. + pub fn from_raw(raw: u16) -> Self { + Self { + blit_mode: RoofBlitMode::from_byte((raw & 0xFF) as u8), + shadow_on: (raw >> 8) as u8, + } + } + + /// Rebuild the on-disk entry from its decoded parts. + pub fn to_raw(self) -> u16 { + u16::from(self.shadow_on) << 8 | u16::from(self.blit_mode.byte()) + } +} + use reader::{ read_events_block, read_overlay_id_table, read_roof_tiles, read_tiled_object_refs, read_tiles_and_access_block, sprite_block, sprite_info_block, tiled_objects_block, @@ -163,7 +224,7 @@ pub struct MapData { pub model: MapModel, pub gtl_tiles: HashMap, pub btl_tiles: HashMap, - /// Per-overlay-id `{lo: transparency mode, hi: draw-enable}` table from + /// Per-overlay-id `{lo: roof blit mode, hi: shadow-on}` table from /// the map file; drives roof rendering (see `render::plot_roofs`). pub overlay_modes: Vec, /// Raw packed u32 words of the access-ref grid ("roof" block), preserved @@ -270,6 +331,12 @@ pub struct SpriteFrameJson { } impl MapData { + /// Decode the roof overlay mode for an overlay id. Missing entries decode + /// to the default mode. + pub fn overlay_mode(&self, overlay_id: usize) -> OverlayMode { + OverlayMode::from_raw(self.overlay_modes.get(overlay_id).copied().unwrap_or(0)) + } + /// Iterate tiles carrying a light level, yielding `(coords, level)` with /// levels in `1..=199`. /// diff --git a/src/map/reader.rs b/src/map/reader.rs index 98285f2b..1a28d903 100644 --- a/src/map/reader.rs +++ b/src/map/reader.rs @@ -64,11 +64,11 @@ pub fn read_tiled_object_refs(reader: &mut BufReader) -> Result) -> Result> { let size = reader.read_i32::()?; @@ -585,6 +585,29 @@ mod tests { assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); } + #[test] + fn test_overlay_entries_expose_blit_mode_and_shadow() { + use crate::map::{OverlayMode, RoofBlitMode}; + + let mut bytes = 2_i32.to_le_bytes().to_vec(); + bytes.extend_from_slice(&0x0100_u16.to_le_bytes()); + bytes.extend_from_slice(&0x0002_u16.to_le_bytes()); + let mut reader = reader_from_bytes("overlay-mode-entries", &bytes); + let table = super::read_overlay_id_table(&mut reader).unwrap(); + + let first = OverlayMode::from_raw(table[0]); + assert_eq!(first.blit_mode, RoofBlitMode::Opaque); + assert_eq!(first.shadow_on, 1); + let second = OverlayMode::from_raw(table[1]); + assert_eq!(second.blit_mode, RoofBlitMode::SkipBlack); + assert_eq!(second.shadow_on, 0); + + let legacy: OverlayMode = + serde_json::from_str(r#"{"transparency_mode":2,"draw_enable":1}"#).unwrap(); + assert_eq!(legacy.blit_mode, RoofBlitMode::SkipBlack); + assert_eq!(legacy.shadow_on, 1); + } + #[test] fn test_overlay_table_reads_valid_entries() { let mut bytes = 2_i32.to_le_bytes().to_vec(); diff --git a/src/map/render.rs b/src/map/render.rs index 2b89b463..51fc2311 100644 --- a/src/map/render.rs +++ b/src/map/render.rs @@ -5,6 +5,7 @@ use std::io::{BufReader, Result, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use crate::map::tileset::{TILE_HEIGHT, Tile, plot_tile, plot_tile_opaque}; +use crate::map::{OverlayMode, RoofBlitMode}; use crate::sprite::{ImageInfo, rgb16_565_produce_color}; use byteorder::{LittleEndian, ReadBytesExt}; @@ -525,22 +526,25 @@ pub fn plot_roofs( if btl_tile_id > 0 { let btl_tile_idx = btl_tile_id as usize; if let Some(btl_tile) = btl_tileset.get(btl_tile_idx) { - // Per-id mode from the map's overlay table: high byte is - // the draw-enable flag (0 hides the overlay), low byte - // selects the blit mode — 0 draws opaquely, any other - // value skips black pixels. + // Per-id mode from the map's overlay table: the shadow-on + // byte gates the overlay, the blit-mode byte picks the + // opaque or skip-black path. let entry = overlay_modes.get(btl_tile_idx).copied().unwrap_or(0); - if entry >> 8 == 0 { + let mode = OverlayMode::from_raw(entry); + if mode.shadow_on == 0 { continue; } let (mut sx, mut sy) = convert_map_coords_to_image_coords(x, y, map_diagonal_tiles); sx -= model.map_non_occluded_start_x; sy -= model.map_non_occluded_start_y; - if entry & 0xFF == 0 { - plot_tile_opaque(image, btl_tile.colors, sx, sy); - } else { - plot_tile(image, btl_tile.colors, sx, sy); + match mode.blit_mode { + RoofBlitMode::Opaque => { + plot_tile_opaque(image, btl_tile.colors, sx, sy); + } + RoofBlitMode::SkipBlack => { + plot_tile(image, btl_tile.colors, sx, sy); + } } } } From 907e2770c9fdf22b336d4facf891348000c30d1f Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:52:47 +0100 Subject: [PATCH 52/72] fix(core): rename save runtime state fields --- .../src/editors/save_file_viewer/state.rs | 37 +++++++++++++++++-- .../editors/save_file_viewer/update/mod.rs | 6 +-- docs/files/SaveFile.md | 3 +- src/references/save_file/game_tmp.rs | 15 +++++--- 4 files changed, 48 insertions(+), 13 deletions(-) diff --git a/dispel-gui/src/editors/save_file_viewer/state.rs b/dispel-gui/src/editors/save_file_viewer/state.rs index 56a544dd..30ea888a 100644 --- a/dispel-gui/src/editors/save_file_viewer/state.rs +++ b/dispel-gui/src/editors/save_file_viewer/state.rs @@ -150,7 +150,7 @@ impl MapsTableKind { ("render_direction_flag", 60.0), ("cell_offset_x", 60.0), ("cell_offset_y", 60.0), - ("spawn_group_id", 60.0), + ("own_entity_id", 60.0), ("constructor_marker", 60.0), ("movement_animation_frame", 60.0), ("dead_or_removed_flag", 60.0), @@ -162,7 +162,7 @@ impl MapsTableKind { ("status_effect_animation_ticks_remaining", 60.0), ("ground_effect_animation_active", 60.0), ("ground_effect_animation_frame", 60.0), - ("ground_effect_handle", 60.0), + ("selected_spell_id", 60.0), ("path_buffer_length", 60.0), ("path_buffer_index", 60.0), ("loot_item1", 60.0), @@ -188,7 +188,7 @@ impl MapsTableKind { ("blood_effect_direction", 60.0), ("timed_overlay_active", 60.0), ("timed_overlay_ticks_remaining", 60.0), - ("ai_tick_counter", 60.0), + ("flee_throttle", 60.0), ("sight_backup", 60.0), ("patrol_countdown_backup", 60.0), ("hidden_or_delisted_flag", 60.0), @@ -1115,3 +1115,34 @@ pub fn get_hex_editors(save_file: &SaveFile) -> Vec { hex_editors } + +#[cfg(test)] +mod tests { + use super::*; + use dispel_core::references::save_file::MonsterRecord; + + #[test] + fn test_monster_columns_name_runtime_state_accurately() { + let columns = MapsTableKind::Monsters.default_columns(); + let headers: Vec<&str> = columns.iter().map(|column| column.label.as_str()).collect(); + for header in ["own_entity_id", "selected_spell_id", "flee_throttle"] { + assert!(headers.contains(&header), "missing column {header}"); + } + for stale in ["spawn_group_id", "ground_effect_handle", "ai_tick_counter"] { + assert!(!headers.contains(&stale), "stale column {stale}"); + } + + let mut value = serde_json::to_value(MonsterRecord::default()).unwrap(); + let object = value.as_object_mut().unwrap(); + assert!(object.remove("own_entity_id").is_some()); + assert!(object.remove("selected_spell_id").is_some()); + assert!(object.remove("flee_throttle").is_some()); + object.insert("spawn_group_id".to_string(), serde_json::json!(7)); + object.insert("ground_effect_handle".to_string(), serde_json::json!(11)); + object.insert("ai_tick_counter".to_string(), serde_json::json!(13)); + let restored: MonsterRecord = serde_json::from_value(value).unwrap(); + assert_eq!(restored.own_entity_id, 7); + assert_eq!(restored.selected_spell_id, 11); + assert_eq!(restored.flee_throttle, 13); + } +} diff --git a/dispel-gui/src/editors/save_file_viewer/update/mod.rs b/dispel-gui/src/editors/save_file_viewer/update/mod.rs index 421c6475..a5f87e47 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/mod.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/mod.rs @@ -1410,7 +1410,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { m.render_direction_flag.to_string(), m.cell_offset_x.to_string(), m.cell_offset_y.to_string(), - m.spawn_group_id.to_string(), + m.own_entity_id.to_string(), m.constructor_marker.to_string(), m.movement_animation_frame.to_string(), m.dead_or_removed_flag.to_string(), @@ -1422,7 +1422,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { m.status_effect_animation_ticks_remaining.to_string(), m.ground_effect_animation_active.to_string(), m.ground_effect_animation_frame.to_string(), - m.ground_effect_handle.to_string(), + m.selected_spell_id.to_string(), m.path_buffer_length.to_string(), m.path_buffer_index.to_string(), m.loot_item1.raw().to_string(), @@ -1448,7 +1448,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { m.blood_effect_direction.to_string(), m.timed_overlay_active.to_string(), m.timed_overlay_ticks_remaining.to_string(), - m.ai_tick_counter.to_string(), + m.flee_throttle.to_string(), m.sight_backup.to_string(), m.patrol_countdown_backup.to_string(), m.hidden_or_delisted_flag.to_string(), diff --git a/docs/files/SaveFile.md b/docs/files/SaveFile.md index 12bc6b8e..43e2fbdc 100644 --- a/docs/files/SaveFile.md +++ b/docs/files/SaveFile.md @@ -67,7 +67,8 @@ are `0=(0,+32)`, `1=(-32,+16)`, `2=(-64,0)`, `3=(-32,-16)`, destination cell. Monster runtime data includes the current combat target, timed status-effect type and duration, movement-animation frame -and offsets, path-buffer length and index, and temporary visual effects. Temporary visuals have separate active, frame, +and offsets, path-buffer length and index, and temporary visual effects. The runtime state also carries this entity's own +id, the selected spell id and a flee-check throttle. Temporary visuals have separate active, frame, and duration fields for status, ground, special-attack, guard, blood, and timed-overlay effects. Blood-effect directions use values `0..=7`. diff --git a/src/references/save_file/game_tmp.rs b/src/references/save_file/game_tmp.rs index 50ec6c34..4e7cece0 100644 --- a/src/references/save_file/game_tmp.rs +++ b/src/references/save_file/game_tmp.rs @@ -329,8 +329,9 @@ pub struct MonsterRecord { pub cell_offset_x: u8, /// Screen-space Y offset while moving between cells. pub cell_offset_y: u8, - /// Spawn/group ID. - pub spawn_group_id: u16, + /// This entity's own id. + #[serde(alias = "spawn_group_id")] + pub own_entity_id: u16, /// Constructor-initialized to `0xff`. pub constructor_marker: u8, /// Current frame within the active movement animation. @@ -353,8 +354,9 @@ pub struct MonsterRecord { pub ground_effect_animation_active: u8, /// Current frame of the ground-effect animation. pub ground_effect_animation_frame: u32, - /// Runtime handle for the active ground effect; `-1` means none. - pub ground_effect_handle: i32, + /// Selected spell id; `-1` means none. + #[serde(alias = "ground_effect_handle")] + pub selected_spell_id: i32, /// Number of entries in the movement path buffer. pub path_buffer_length: u32, /// Current entry in the movement path buffer. @@ -410,8 +412,9 @@ pub struct MonsterRecord { pub timed_overlay_active: u8, /// Remaining ticks for the timed overlay. pub timed_overlay_ticks_remaining: u32, - /// AI update/tick counter. - pub ai_tick_counter: u32, + /// Throttle countdown before the next flee check. + #[serde(alias = "ai_tick_counter")] + pub flee_throttle: u32, /// Backup of `detection_sight_size`. pub sight_backup: u8, /// Backup of `patrol_countdown`. From b44054305863cae6a73cde9449432cbe030bf3a6 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:10:11 +0100 Subject: [PATCH 53/72] fix(core): accept renamed dialogue keys in patchers --- dispel-gui/src/editors/chdata/component.rs | 2 +- src/modding/patchers/dialogue.rs | 33 ++++++++++++++++++++-- src/references/chdata_db.rs | 8 +++--- 3 files changed, 36 insertions(+), 7 deletions(-) diff --git a/dispel-gui/src/editors/chdata/component.rs b/dispel-gui/src/editors/chdata/component.rs index bafb4554..420992e3 100644 --- a/dispel-gui/src/editors/chdata/component.rs +++ b/dispel-gui/src/editors/chdata/component.rs @@ -24,8 +24,8 @@ editable_record_fields!(ChData, { { reserved_stat = Integer / "Reserved:" }, { warrior_offense_bonus = Integer / "Warrior Offense:" }, { knight_defense_bonus = Integer / "Knight Defense:" }, + { archer_hit_bonus = Integer / "Archer Accuracy:" }, { archer_dodge_bonus = Integer / "Archer Dodge:" }, - { archer_hit_bonus = Integer / "Archer Hit:" }, { mage_magic_power_bonus = Integer / "Mage Magic Power:" }, }); diff --git a/src/modding/patchers/dialogue.rs b/src/modding/patchers/dialogue.rs index 48127dd2..beb972d0 100644 --- a/src/modding/patchers/dialogue.rs +++ b/src/modding/patchers/dialogue.rs @@ -61,7 +61,9 @@ impl RecordPatcher for DialogueScriptPatcher { ))); } "required_event_id" => rec.required_event_id = parse_optional_i32(field, new)?, - "next_dialog_to_check" => rec.fallback_dialog_id = parse_optional_i32(field, new)?, + "fallback_dialog_id" | "next_dialog_to_check" => { + rec.fallback_dialog_id = parse_optional_i32(field, new)? + } "dialog_id" => rec.dialog_id = parse_optional_i32(field, new)?, "next_dialog_id1" => rec.next_dialog_id1 = parse_optional_i32(field, new)?, "next_dialog_id2" => rec.next_dialog_id2 = parse_optional_i32(field, new)?, @@ -149,7 +151,7 @@ impl RecordPatcher for DialogueParagraphPatcher { Value::String(s) => rec.comment = s.clone(), _ => return Err(wrong_type(Self::RECORD_NAME, field, "string", new)), }, - "param1" => rec.next_page_id = parse_i32(field, new)?, + "next_page_id" | "param1" => rec.next_page_id = parse_i32(field, new)?, "wave_ini_entry_id" => rec.wave_ini_entry_id = parse_i32(field, new)?, other => return Err(unknown_field(Self::RECORD_NAME, other)), } @@ -191,6 +193,24 @@ mod tests { DialogueScript::parse(&mut Cursor::new(b), b.len() as u64).unwrap() } + #[test] + fn dlg_new_fallback_key_is_accepted() { + let p = DialogueScriptPatcher; + let out = p + .apply_field(&dlg_blob(), 0, "fallback_dialog_id", &Value::I64(55)) + .expect("the new key must be accepted by the patcher"); + assert_eq!(parse_dlgs(&out)[0].fallback_dialog_id, Some(55)); + } + + #[test] + fn dlg_legacy_next_dialog_key_still_works() { + let p = DialogueScriptPatcher; + let out = p + .apply_field(&dlg_blob(), 0, "next_dialog_to_check", &Value::I64(65)) + .expect("the stored key must still be accepted"); + assert_eq!(parse_dlgs(&out)[0].fallback_dialog_id, Some(65)); + } + #[test] fn dlg_change_dialog_id() { let p = DialogueScriptPatcher; @@ -253,6 +273,15 @@ mod tests { DialogueParagraph::parse(&mut Cursor::new(b), b.len() as u64).unwrap() } + #[test] + fn pgp_new_next_page_key_is_accepted() { + let p = DialogueParagraphPatcher; + let out = p + .apply_field(&pgp_blob(), 0, "next_page_id", &Value::I64(27)) + .expect("the new key must be accepted by the patcher"); + assert_eq!(parse_paras(&out)[0].next_page_id, 27); + } + #[test] fn pgp_param1_key_still_sets_next_page_id() { let p = DialogueParagraphPatcher; diff --git a/src/references/chdata_db.rs b/src/references/chdata_db.rs index f4c910a6..437b1c10 100644 --- a/src/references/chdata_db.rs +++ b/src/references/chdata_db.rs @@ -78,12 +78,12 @@ pub struct ChData { /// Derived-stat bonus for the Knight class: added to defense (AGI-derived). #[extractor(primitive(type = "i32"))] pub knight_defense_bonus: i32, - /// Derived-stat bonus for the Archer class: added to dodge_rate (CON-derived). - #[extractor(primitive(type = "i32"))] - pub archer_dodge_bonus: i32, - /// Derived-stat bonus for the Archer class: added to hit_rate (CON-derived). + /// Archer accuracy bonus. #[extractor(primitive(type = "i32"))] pub archer_hit_bonus: i32, + /// Archer dodge bonus at offset 0x4C (CON-derived). + #[extractor(primitive(type = "i32"))] + pub archer_dodge_bonus: i32, /// Derived-stat bonus for the Mage class: added to magic_power (WIS-derived). #[extractor(primitive(type = "i32"))] pub mage_magic_power_bonus: i32, From 54fba64f53a5071a8bc329a8321878178615eea8 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:39:40 +0100 Subject: [PATCH 54/72] fix(core): swap chdata archer seed labels --- docs/files/CharacterInGame/ChData.db.md | 8 ++++---- src/queries/create_table_chdata.sql | 2 +- src/queries/insert_chdata.sql | 2 +- src/references/chdata_db.rs | 6 +++--- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/files/CharacterInGame/ChData.db.md b/docs/files/CharacterInGame/ChData.db.md index 236cbcb5..9ef94ac9 100644 --- a/docs/files/CharacterInGame/ChData.db.md +++ b/docs/files/CharacterInGame/ChData.db.md @@ -36,8 +36,8 @@ The tool reads 5 `i32` derived-stat bonuses, one per class. Known files store sm |--------|---------|------------------------|--------------|-----------| | 64 | Warrior | warrior_offense_bonus | offense | STR | | 68 | Knight | knight_defense_bonus | defense | AGI | -| 72 | Archer | archer_dodge_bonus | dodge_rate | CON | -| 76 | Archer | archer_hit_bonus | hit_rate | CON | +| 72 | Archer | archer_hit_bonus | hit_rate | CON | +| 76 | Archer | archer_dodge_bonus | dodge_rate | CON | | 80 | Mage | mage_magic_power_bonus | magic_power | WIS | > The tool does not read a points-per-level value from this file. The documented value is 5. @@ -100,8 +100,8 @@ Bytes 60-61: mage_agility (i16) Bytes 62-63: reserved_stat (i16) Bytes 64-67: warrior_offense_bonus (i32) Bytes 68-71: knight_defense_bonus (i32) -Bytes 72-75: archer_dodge_bonus (i32) -Bytes 76-79: archer_hit_bonus (i32) +Bytes 72-75: archer_hit_bonus (i32) +Bytes 76-79: archer_dodge_bonus (i32) Bytes 80-83: mage_magic_power_bonus (i32) ``` diff --git a/src/queries/create_table_chdata.sql b/src/queries/create_table_chdata.sql index c8f79339..136d2cde 100644 --- a/src/queries/create_table_chdata.sql +++ b/src/queries/create_table_chdata.sql @@ -19,7 +19,7 @@ CREATE TABLE IF NOT EXISTS ch_datas ( reserved_stat INTEGER, warrior_offense_bonus INTEGER, knight_defense_bonus INTEGER, - archer_dodge_bonus INTEGER, archer_hit_bonus INTEGER, + archer_dodge_bonus INTEGER, mage_magic_power_bonus INTEGER ); diff --git a/src/queries/insert_chdata.sql b/src/queries/insert_chdata.sql index 534a6a5f..0d000590 100644 --- a/src/queries/insert_chdata.sql +++ b/src/queries/insert_chdata.sql @@ -19,7 +19,7 @@ INSERT OR REPLACE INTO ch_datas ( reserved_stat, warrior_offense_bonus, knight_defense_bonus, - archer_dodge_bonus, archer_hit_bonus, + archer_dodge_bonus, mage_magic_power_bonus ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23); diff --git a/src/references/chdata_db.rs b/src/references/chdata_db.rs index 437b1c10..02837780 100644 --- a/src/references/chdata_db.rs +++ b/src/references/chdata_db.rs @@ -78,10 +78,10 @@ pub struct ChData { /// Derived-stat bonus for the Knight class: added to defense (AGI-derived). #[extractor(primitive(type = "i32"))] pub knight_defense_bonus: i32, - /// Archer accuracy bonus. + /// Archer accuracy bonus (CON-derived). #[extractor(primitive(type = "i32"))] pub archer_hit_bonus: i32, - /// Archer dodge bonus at offset 0x4C (CON-derived). + /// Archer dodge bonus (CON-derived). #[extractor(primitive(type = "i32"))] pub archer_dodge_bonus: i32, /// Derived-stat bonus for the Mage class: added to magic_power (WIS-derived). @@ -119,8 +119,8 @@ pub fn save_chdatas(conn: &mut Connection, records: &[ChData]) -> Result<()> { record.reserved_stat, record.warrior_offense_bonus, record.knight_defense_bonus, - record.archer_dodge_bonus, record.archer_hit_bonus, + record.archer_dodge_bonus, record.mage_magic_power_bonus, ])?; } From 01f75a8c51097f71583c8317b6856ab7288b7420 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:36:22 +0100 Subject: [PATCH 55/72] fix(core): remove SmallRange0to3 enum --- dispel-gui/src/editors/extra_ref/component.rs | 6 +- dispel-gui/src/tests/editor_field_edit.rs | 26 ------ dispel-gui/src/tests/select_boxes.rs | 4 +- docs/files/ExtraInGame/Extra.ref.md | 34 +------ src/references/enums.rs | 88 ------------------- src/references/extra_ref.rs | 37 +++----- 6 files changed, 15 insertions(+), 180 deletions(-) diff --git a/dispel-gui/src/editors/extra_ref/component.rs b/dispel-gui/src/editors/extra_ref/component.rs index fd2fc651..4b80832e 100644 --- a/dispel-gui/src/editors/extra_ref/component.rs +++ b/dispel-gui/src/editors/extra_ref/component.rs @@ -1,5 +1,5 @@ use crate::components::editable::EditableRecord; -use dispel_core::{BooleanFlag, ExtraObjectType, ExtraRef, SmallRange0to3}; +use dispel_core::{BooleanFlag, ExtraObjectType, ExtraRef}; use crate::editable_record_fields; @@ -38,8 +38,8 @@ editable_record_fields!(ExtraRef, { { use_counter = Integer / "Use counter:" }, { interaction_event_id = Integer / "Interaction event ID:" }, { interaction_message_id = Integer / "Interaction message ID:" }, - { footprint_width = DispEnum(SmallRange0to3, ["0", "1", "2", "3"]) / "Footprint width:" }, - { footprint_height = DispEnum(SmallRange0to3, ["0", "1", "2", "3"]) / "Footprint height:" }, + { footprint_width = Integer / "Footprint width:" }, + { footprint_height = Integer / "Footprint height:" }, { footprint_orientation = Integer / "Footprint orientation:" }, { interaction_range = Integer / "Interaction range:" }, { interaction_range_padding = HexString / "Interaction range padding:" }, diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index f61b998c..f663431a 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1314,32 +1314,6 @@ mod renamed_field_labels { Some(5) ); } - - #[test] - fn test_extra_ref_reset_frame_label_accepts_old_key() { - let fields = ExtraRef::__editable_fields(); - let descriptor = fields - .iter() - .find(|field| field.name == "reset_to_base_sprite_frame") - .expect("the reset field must be exposed in the inspector"); - assert_eq!(descriptor.label, "Non-zero resets to the base frame:"); - - let mut value = serde_json::to_value(ExtraRef::default()).unwrap(); - let object = value.as_object_mut().unwrap(); - assert!(object.remove("reset_to_base_sprite_frame").is_some()); - object.insert( - "preserve_final_sprite_frame".to_string(), - serde_json::json!(0), - ); - let restored: ExtraRef = serde_json::from_value(value).unwrap(); - assert!( - serde_json::to_value(&restored) - .unwrap() - .get("reset_to_base_sprite_frame") - .is_some(), - "the stored key must still be accepted" - ); - } } // ============================================================================ diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs index 6a5e8a34..67e9b455 100644 --- a/dispel-gui/src/tests/select_boxes.rs +++ b/dispel-gui/src/tests/select_boxes.rs @@ -16,7 +16,7 @@ use dispel_core::{ EditItemModification, Event, EventNpcRef, EventType, ExtraObjectType, ExtraRef, HealItem, HealItemFlag, MagicSpell, MagicType, Map, MapLighting, Monster, MonsterAiType, MonsterRef, MonsterSpawn, NPC, NpcInteractionMode, NpcLookingDirection, NpcMovementMode, NpcRoleResult, - SmallRange0to3, TargetSelectionFlag, + TargetSelectionFlag, }; use super::common::{activate_select_option, filter_select, select_shows, select_values}; @@ -410,8 +410,6 @@ fn test_every_enum_field_round_trips_through_both_views() { audit_enum::("dialog_owner", DisplayFormat); audit_enum::("object_type", DebugFormat); audit_enum::("requires_key", DisplayFormat); - audit_enum::("footprint_width", DisplayFormat); - audit_enum::("footprint_height", DisplayFormat); for field in [ "is_quest_element", "post_activation_tile_flag", diff --git a/docs/files/ExtraInGame/Extra.ref.md b/docs/files/ExtraInGame/Extra.ref.md index 324b1a71..11dc90ae 100644 --- a/docs/files/ExtraInGame/Extra.ref.md +++ b/docs/files/ExtraInGame/Extra.ref.md @@ -202,7 +202,7 @@ SQL columns and GUI numeric keys keep the on-disk byte value, so no item reads a | 0 | Pillars (e.g., Gods garden) | | 1 | Standard interactive | | 2 | Unknown variant | -| 3 | Special altars (e.g., Vera altar) | +| 3 | Special altars (e.g., Vara altar) | ### File Purpose @@ -227,38 +227,6 @@ The tool reads these files as interactive object placements. Each placement hold - **Text encoding**: WINDOWS-1250 for name fields - **Padding**: zeros and 205 bytes -### File Processing - -1. Read 4-byte record count header -2. Calculate expected file size: 4 + (count × 184) -3. Parse each 184-byte record sequentially -4. Decode name fields using WINDOWS-1250 encoding -5. Apply enum conversions for typed fields - -### Characteristics - -- **Fixed Record Size**: All records are exactly 184 bytes -- **Binary Format**: Not human-readable without parsing -- **Map-Specific**: Each map has its own file -- **Extensive Padding**: Many unknown fields with consistent patterns -- **Cross-Referenced**: Links to multiple other game data files -- **Quest-Aware**: Special flag for quest-related objects -- **Container Support**: Built-in gold and item storage -- **Key System**: Dual key requirement system (lower/upper bounds) - -### Notes - -- File uses little-endian byte order throughout -- Name fields are null-terminated WINDOWS-1250 strings -- Padding bytes are often filled with the byte value 205 or zero -- Sign objects use `interaction_message_id` to display text from `Message.scr`. -- Door objects may require specific keys defined by `required_item_*` fields -- The dual key system (`required_item_id`/`required_item_id2`) supports key ranges or multiple key types - -## Extractor - -An extractor is available in `src/references/extra_ref.rs` to parse this file format. - ### How to Run ```bash diff --git a/src/references/enums.rs b/src/references/enums.rs index 43cb0b6c..00406322 100644 --- a/src/references/enums.rs +++ b/src/references/enums.rs @@ -55,8 +55,6 @@ impl_wire_value!(NpcMovementMode, i32, from_i32); impl_wire_value!(NpcRoleResult, i32, from_i32); impl_wire_value!(NpcInteractionMode, i32, from_i32); impl_wire_value!(TriStateFlag, i32, from_i32); -impl_wire_value!(SmallRange0to3, i32, from_i32); -impl_wire_value!(SmallRange0to3, u8, from_u8); impl_wire_value!(HealItemFlag, u8, from_u8); impl_wire_value!(MagicType, u32, from_u32); impl_wire_value!(SpellTargetType, u32, from_u32); @@ -1195,90 +1193,6 @@ impl std::str::FromStr for TriStateFlag { } } -/// Enum for small range values (0, 1, 2, 3) -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] -#[repr(i32)] -pub enum SmallRange0to3 { - /// Value 0 (default) - #[default] - Value0 = 0, - /// Value 1 - Value1 = 1, - /// Value 2 - Value2 = 2, - /// Value 3 - Value3 = 3, -} - -impl SmallRange0to3 { - pub fn from_i32(value: i32) -> Option { - match value { - 0 => Some(SmallRange0to3::Value0), - 1 => Some(SmallRange0to3::Value1), - 2 => Some(SmallRange0to3::Value2), - 3 => Some(SmallRange0to3::Value3), - _ => None, - } - } - - pub fn from_u8(value: u8) -> Option { - match value { - 0 => Some(SmallRange0to3::Value0), - 1 => Some(SmallRange0to3::Value1), - 2 => Some(SmallRange0to3::Value2), - 3 => Some(SmallRange0to3::Value3), - _ => None, - } - } - - pub fn from_name(name: &str) -> Option { - match name { - "0" => Some(SmallRange0to3::Value0), - "1" => Some(SmallRange0to3::Value1), - "2" => Some(SmallRange0to3::Value2), - "3" => Some(SmallRange0to3::Value3), - _ => None, - } - } -} - -impl From for i32 { - fn from(value: SmallRange0to3) -> Self { - value as i32 - } -} - -impl From for u8 { - fn from(value: SmallRange0to3) -> Self { - value as u8 - } -} - -impl std::fmt::Display for SmallRange0to3 { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - SmallRange0to3::Value0 => write!(f, "0"), - SmallRange0to3::Value1 => write!(f, "1"), - SmallRange0to3::Value2 => write!(f, "2"), - SmallRange0to3::Value3 => write!(f, "3"), - } - } -} - -impl std::str::FromStr for SmallRange0to3 { - type Err = &'static str; - - fn from_str(s: &str) -> Result { - match s { - "0" => Ok(SmallRange0to3::Value0), - "1" => Ok(SmallRange0to3::Value1), - "2" => Ok(SmallRange0to3::Value2), - "3" => Ok(SmallRange0to3::Value3), - _ => Err("Invalid SmallRange0to3 value"), - } - } -} - /// Enable flags for individual healing-item effects. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] #[repr(u8)] @@ -2181,8 +2095,6 @@ mod tests { assert_wire_fallback!(NpcRoleResult, i32, from_i32, 1, i32::MIN); assert_wire_fallback!(NpcInteractionMode, i32, from_i32, 1, i32::MIN); assert_wire_fallback!(TriStateFlag, i32, from_i32, 1, i32::MIN); - assert_wire_fallback!(SmallRange0to3, i32, from_i32, 3, i32::MIN); - assert_wire_fallback!(SmallRange0to3, u8, from_u8, 3, 254); assert_wire_fallback!(HealItemFlag, u8, from_u8, 1, 254); assert_wire_fallback!(MagicType, u32, from_u32, 1, u32::MAX); assert_wire_fallback!(SpellTargetType, u32, from_u32, 1, u32::MAX); diff --git a/src/references/extra_ref.rs b/src/references/extra_ref.rs index 50b1774c..7bcf9783 100644 --- a/src/references/extra_ref.rs +++ b/src/references/extra_ref.rs @@ -1,7 +1,7 @@ use std::path::Path; use crate::references::enums::{ - BooleanFlag, ExtraObjectType, InventoryItem, ItemTypeId, SmallRange0to3, + BooleanFlag, ExtraObjectType, InventoryItem, ItemTypeId, }; use crate::references::extractor::Extractor; use dispel_macros::{Extractor, Localizable, RecordLayout, RecordPatcher}; @@ -150,17 +150,17 @@ pub struct ExtraRef { #[extractor(primitive(type = "i32"))] pub interaction_message_id: i32, /// Occupied-footprint width in map cells. - #[extractor(enum_from_i32(type = "SmallRange0to3"))] - pub footprint_width: SmallRange0to3, + #[extractor(primitive(type = "i32"))] + pub footprint_width: i32, /// Occupied-footprint height in map cells. - #[extractor(enum_from_i32(type = "SmallRange0to3"))] - pub footprint_height: SmallRange0to3, + #[extractor(primitive(type = "i32"))] + pub footprint_height: i32, /// Footprint traversal orientation. Zero selects the normal direction. #[extractor(primitive(type = "u8"))] pub footprint_orientation: u8, /// Maximum distance at which the object can be activated. - #[extractor(enum_from_i32_from_u8(type = "SmallRange0to3"))] - pub interaction_range: SmallRange0to3, + #[extractor(primitive(type = "i8"))] + pub interaction_range: i8, /// Padding after [`Self::interaction_range`] (normally `[0xCD; 2]`). #[extractor(vec_u8(size = 2))] pub interaction_range_padding: Vec, @@ -175,8 +175,6 @@ pub struct ExtraRef { pub post_activation_footprint_mode: BooleanFlag, /// Non-zero resets the object to its base sprite frame after interaction. #[extractor(primitive(type = "i32"))] - #[serde(alias = "preserve_final_sprite_frame")] - #[patcher(field_alias = "preserve_final_sprite_frame")] pub reset_to_base_sprite_frame: i32, /// Selects the alternate renderer used for this object. #[extractor(enum_from_i32(type = "BooleanFlag"))] @@ -282,10 +280,10 @@ pub fn save_extra_refs(conn: &mut Connection, file_id: i32, extra_refs: &[ExtraR } else { None }, // 41 - i32::from(extra_ref.footprint_width), // 42 - i32::from(extra_ref.footprint_height), // 43 + extra_ref.footprint_width, // 42 + extra_ref.footprint_height, // 43 extra_ref.footprint_orientation, // 44 - u8::from(extra_ref.interaction_range), // 45 + extra_ref.interaction_range, // 45 extra_ref.interaction_range_padding, // 46 i32::from(extra_ref.is_quest_element), // 47 i32::from(extra_ref.post_activation_tile_flag), // 48 @@ -356,21 +354,6 @@ mod tests { ); } - #[test] - fn test_legacy_patcher_key_still_resets_frame() { - use crate::modding::patcher::RecordPatcher; - use crate::modding::value::Value; - - let mut data = 1i32.to_le_bytes().to_vec(); - data.extend(ref_bytes("MistvaleChest", 1, 2, 3)); - let out = ExtraRefPatcher - .apply_field(&data, 0, "preserve_final_sprite_frame", &Value::I64(1)) - .expect("the stored patcher key must still be accepted"); - let mut cursor = Cursor::new(&out[..]); - let records = ExtraRef::parse(&mut cursor, out.len() as u64).unwrap(); - assert_eq!(records[0].reset_to_base_sprite_frame, 1); - } - #[test] fn parse_single_ref() { let mut data = 1i32.to_le_bytes().to_vec(); From 2dd6009d3879df2d44e74d2330956e1096aeb6ed Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:38:41 +0100 Subject: [PATCH 56/72] fix(core): Remove alias in EditItem.db --- dispel-gui/src/tests/editor_field_edit.rs | 22 ---------------------- src/references/edit_item_db.rs | 17 ----------------- 2 files changed, 39 deletions(-) diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index f663431a..61c0a404 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1126,28 +1126,6 @@ mod renamed_field_labels { ); } - #[test] - fn test_edit_item_modification_cost_label_accepts_old_key() { - let descriptor = EditItem::__editable_fields() - .iter() - .find(|field| field.name == "modification_cost") - .expect("the modification cost must be exposed in the inspector"); - assert_eq!(descriptor.label, "Modification Cost:"); - - let mut value = serde_json::to_value(EditItem::default()).unwrap(); - let object = value.as_object_mut().unwrap(); - assert!(object.remove("modification_cost").is_some()); - object.insert("modification_resistance".to_string(), serde_json::json!(12)); - let restored: EditItem = serde_json::from_value(value).unwrap(); - assert_eq!( - serde_json::to_value(&restored) - .unwrap() - .get("modification_cost") - .and_then(|v| v.as_i64()), - Some(12) - ); - } - #[test] fn test_edit_item_effect_health_leech_uses_new_name() { let descriptor = EditItem::__editable_fields() diff --git a/src/references/edit_item_db.rs b/src/references/edit_item_db.rs index 63162973..a89e253e 100644 --- a/src/references/edit_item_db.rs +++ b/src/references/edit_item_db.rs @@ -153,8 +153,6 @@ pub struct EditItem { pub magical_power: i16, /// Budget cost charged when modifying an item. #[extractor(primitive(type = "i16"))] - #[serde(alias = "modification_resistance")] - #[patcher(field_alias = "modification_resistance")] pub modification_cost: i16, /// Reserved byte. Always zero by default; purpose unknown. #[extractor(primitive(type = "u8"))] @@ -225,21 +223,6 @@ mod tests { rec } - #[test] - fn test_legacy_patcher_key_sets_modification_cost() { - use crate::modding::patcher::RecordPatcher; - use crate::modding::value::Value; - - let mut data = 1i32.to_le_bytes().to_vec(); - data.extend(item_bytes("MistvaleCharm", 120, 4, 10)); - let out = EditItemPatcher - .apply_field(&data, 0, "modification_resistance", &Value::I64(15)) - .expect("the stored patcher key must still be accepted"); - let mut cursor = Cursor::new(&out[..]); - let items = EditItem::parse(&mut cursor, out.len() as u64).unwrap(); - assert_eq!(items[0].modification_cost, 15); - } - #[test] fn parse_single_item() { let mut data = 1i32.to_le_bytes().to_vec(); From 3c50f56f1d9e050c9d2ac96fb01b56e20cc49ea6 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:49:17 +0100 Subject: [PATCH 57/72] fix(core): Remove more aliases --- .../src/editors/save_file_viewer/state.rs | 12 +- .../editors/save_file_viewer/update/mod.rs | 14 +- dispel-gui/src/tests/editor_field_edit.rs | 139 +----------------- src/database/tests.rs | 2 +- src/modding/patchers/dialogue.rs | 11 +- src/queries/create_table_dialogue_scripts.sql | 2 +- src/queries/create_table_edit_items.sql | 2 +- src/queries/create_table_extra_refs.sql | 2 +- src/queries/create_table_heal_items.sql | 2 +- src/queries/create_table_monsters.sql | 6 +- src/queries/create_table_weapons.sql | 2 +- src/queries/insert_dialogue_scripts.sql | 2 +- src/queries/insert_edit_item.sql | 2 +- src/queries/insert_extra_ref.sql | 2 +- src/queries/insert_heal_item.sql | 2 +- src/queries/insert_monster.sql | 2 +- src/queries/insert_weapon.sql | 2 +- src/references/dialogue_paragraph.rs | 3 +- src/references/dialogue_script.rs | 17 +-- src/references/heal_item_db.rs | 17 --- src/references/monster_db.rs | 20 --- src/references/save_file/game_tmp.rs | 10 +- src/references/save_file/inventory.rs | 6 +- src/references/weapons_db.rs | 17 --- 24 files changed, 48 insertions(+), 248 deletions(-) diff --git a/dispel-gui/src/editors/save_file_viewer/state.rs b/dispel-gui/src/editors/save_file_viewer/state.rs index 30ea888a..175131ff 100644 --- a/dispel-gui/src/editors/save_file_viewer/state.rs +++ b/dispel-gui/src/editors/save_file_viewer/state.rs @@ -109,7 +109,7 @@ impl MapsTableKind { ("hp_maximum", 60.0), ("mp_current", 60.0), ("mp_maximum", 60.0), - ("walk_speed", 60.0), + ("attack_cooldown_ticks", 60.0), ("hit_rate", 60.0), ("dodge_rate", 60.0), ("offense_rate", 60.0), @@ -317,7 +317,7 @@ impl MapsTableKind { ("is_quest_element", 60.0), ("post_activation_tile_flag", 60.0), ("post_activation_footprint_mode", 60.0), - ("preserve_final_sprite_frame", 60.0), + ("reset_to_base_sprite_frame", 60.0), ("alternate_render_mode", 60.0), ("open_sfx_id", 60.0), ("open_sfx_reserved", 60.0), @@ -342,7 +342,7 @@ impl MapsTableKind { ("attack", 60.0), ("defense", 60.0), ("magical_strength", 60.0), - ("durability", 60.0), + ("modification_budget", 60.0), ("padding2", 60.0), ("padding3", 60.0), ("req_strength", 60.0), @@ -368,7 +368,7 @@ impl MapsTableKind { ("restore_full_health", 60.0), ("restore_full_mana", 60.0), ("poison_heal", 60.0), - ("petrif_heal", 60.0), + ("cures_paralysis", 60.0), ("polimorph_heal", 60.0), ("reserved_trailer", 80.0), ("map_coordinate_x", 60.0), @@ -689,7 +689,7 @@ impl InventoryCategory { ("attack", 60.0), ("defense", 60.0), ("magical_strength", 60.0), - ("durability", 60.0), + ("modification_budget", 60.0), ("padding2", 60.0), ("padding3", 60.0), ("req_strength", 60.0), @@ -713,7 +713,7 @@ impl InventoryCategory { ("restore_full_health", 60.0), ("restore_full_mana", 60.0), ("poison_heal", 60.0), - ("petrif_heal", 60.0), + ("cures_paralysis", 60.0), ("polimorph_heal", 60.0), ("reserved_definition_byte", 100.0), ("item_category", 70.0), diff --git a/dispel-gui/src/editors/save_file_viewer/update/mod.rs b/dispel-gui/src/editors/save_file_viewer/update/mod.rs index a5f87e47..d8bc4ceb 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/mod.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/mod.rs @@ -1081,7 +1081,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { item.attack.to_string(), item.defense.to_string(), item.magical_strength.to_string(), - item.durability.to_string(), + item.modification_budget.to_string(), item.padding2.to_string(), item.padding3.to_string(), item.req_strength.to_string(), @@ -1113,7 +1113,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { item.restore_full_health.to_string(), item.restore_full_mana.to_string(), item.poison_heal.to_string(), - item.petrif_heal.to_string(), + item.cures_paralysis.to_string(), item.polimorph_heal.to_string(), item.reserved_definition_byte.to_string(), item.item_category.to_string(), @@ -1144,7 +1144,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { item.offense.to_string(), item.defense.to_string(), item.magical_power.to_string(), - item.modification_resistance.to_string(), + item.modification_cost.to_string(), item.reserved_byte.to_string(), item.modifies_item.to_string(), item.additional_effect.to_string(), @@ -1369,7 +1369,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { m.hp_maximum.to_string(), m.mp_current.to_string(), m.mp_maximum.to_string(), - m.walk_speed.to_string(), + m.attack_cooldown_ticks.to_string(), m.hit_rate.to_string(), m.dodge_rate.to_string(), m.offense_rate.to_string(), @@ -1591,7 +1591,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { e.is_quest_element.to_string(), e.post_activation_tile_flag.to_string(), e.post_activation_footprint_mode.to_string(), - e.preserve_final_sprite_frame.to_string(), + e.reset_to_base_sprite_frame.to_string(), e.alternate_render_mode.to_string(), e.open_sfx_id.to_string(), e.open_sfx_reserved.to_string(), @@ -1623,7 +1623,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { d.attack.to_string(), d.defense.to_string(), d.magical_strength.to_string(), - d.durability.to_string(), + d.modification_budget.to_string(), d.padding2.to_string(), d.padding3.to_string(), d.req_strength.to_string(), @@ -1687,7 +1687,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { d.offense.to_string(), d.defense.to_string(), d.magical_power.to_string(), - d.modification_resistance.to_string(), + d.modification_cost.to_string(), d.reserved_byte.to_string(), d.modifies_item.to_string(), d.additional_effect.to_string(), diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index 61c0a404..2bf10a15 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1016,50 +1016,6 @@ mod modified_flag_routing { mod renamed_field_labels { use crate::components::editable::{EditableRecordGenerated, FieldKind}; - #[test] - fn test_dialogue_next_page_id_label_accepts_old_key() { - let descriptor = DialogueParagraph::__editable_fields() - .iter() - .find(|field| field.name == "next_page_id") - .expect("the next page id must be exposed in the inspector"); - assert_eq!(descriptor.label, "Next Page ID:"); - - let mut value = serde_json::to_value(DialogueParagraph::default()).unwrap(); - let object = value.as_object_mut().unwrap(); - assert!(object.remove("next_page_id").is_some()); - object.insert("param1".to_string(), serde_json::json!(17)); - let restored: DialogueParagraph = serde_json::from_value(value).unwrap(); - assert_eq!( - serde_json::to_value(&restored) - .unwrap() - .get("next_page_id") - .and_then(|v| v.as_i64()), - Some(17) - ); - } - - #[test] - fn test_dialogue_fallback_label_accepts_old_key() { - let descriptor = DialogueScript::__editable_fields() - .iter() - .find(|field| field.name == "fallback_dialog_id") - .expect("the fallback node must be exposed in the inspector"); - assert_eq!(descriptor.label, "Fallback Node (gate fails):"); - - let mut value = serde_json::to_value(DialogueScript::default()).unwrap(); - let object = value.as_object_mut().unwrap(); - assert!(object.remove("fallback_dialog_id").is_some()); - object.insert("next_dialog_to_check".to_string(), serde_json::json!(42)); - let restored: DialogueScript = serde_json::from_value(value).unwrap(); - assert_eq!( - serde_json::to_value(&restored) - .unwrap() - .get("fallback_dialog_id") - .and_then(|v| v.as_i64()), - Some(42) - ); - } - #[test] fn test_magic_type_options_mark_elemental_schools_without_proficiency() { let descriptor = MagicSpell::__editable_fields() @@ -1079,8 +1035,8 @@ mod renamed_field_labels { } use dispel_core::{ - DialogueParagraph, DialogueScript, EditItem, EditItemEffect, ExtraRef, Extractor, HealItem, - MagicSpell, Monster, MonsterIni, WeaponItem, + DialogueScript, EditItem, EditItemEffect, ExtraRef, Extractor, HealItem, MagicSpell, + Monster, MonsterIni, WeaponItem, }; #[test] @@ -1101,31 +1057,6 @@ mod renamed_field_labels { } } - #[test] - fn test_heal_item_paralysis_label_accepts_old_key() { - let descriptor = HealItem::__editable_fields() - .iter() - .find(|field| field.name == "cures_paralysis") - .expect("the paralysis cure must be exposed in the inspector"); - assert_eq!(descriptor.label, "Cures Paralysis:"); - - let mut value = serde_json::to_value(HealItem::default()).unwrap(); - let object = value.as_object_mut().unwrap(); - assert!(object.remove("cures_paralysis").is_some()); - object.insert( - "cures_petrification".to_string(), - serde_json::json!("Active"), - ); - let restored: HealItem = serde_json::from_value(value).unwrap(); - assert!( - serde_json::to_value(&restored) - .unwrap() - .get("cures_paralysis") - .is_some(), - "the stored key must still be accepted" - ); - } - #[test] fn test_edit_item_effect_health_leech_uses_new_name() { let descriptor = EditItem::__editable_fields() @@ -1188,39 +1119,6 @@ mod renamed_field_labels { ); } - #[test] - fn test_monster_attack_cooldown_label_accepts_old_key() { - let descriptor = Monster::__editable_fields() - .iter() - .find(|field| field.name == "attack_cooldown_ticks") - .expect("the cooldown must be exposed in the inspector"); - assert_eq!(descriptor.label, "Attack Cooldown Ticks:"); - - let mut bytes = Vec::new(); - Monster::to_writer( - &[Monster { - name: "MistvaleWolf".into(), - ..Default::default() - }], - &mut bytes, - ) - .unwrap(); - let mut cursor = std::io::Cursor::new(&bytes); - let records = Monster::parse(&mut cursor, bytes.len() as u64).unwrap(); - let mut value = serde_json::to_value(&records[0]).unwrap(); - let object = value.as_object_mut().unwrap(); - assert!(object.remove("attack_cooldown_ticks").is_some()); - object.insert("walk_speed".to_string(), serde_json::json!(9)); - let restored: Monster = serde_json::from_value(value).unwrap(); - assert_eq!( - serde_json::to_value(&restored) - .unwrap() - .get("attack_cooldown_ticks") - .and_then(|v| v.as_i64()), - Some(9) - ); - } - #[test] fn test_magic_range_label_describes_target_power_cap() { let descriptor = MagicSpell::__editable_fields() @@ -1259,39 +1157,6 @@ mod renamed_field_labels { Some(7) ); } - - #[test] - fn test_weapon_modification_budget_label_accepts_old_key() { - let descriptor = WeaponItem::__editable_fields() - .iter() - .find(|field| field.name == "modification_budget") - .expect("the workshop budget must be exposed in the inspector"); - assert_eq!(descriptor.label, "Modification Budget:"); - - let mut bytes = Vec::new(); - WeaponItem::to_writer( - &[WeaponItem { - name: "Mistvale Blade".into(), - ..Default::default() - }], - &mut bytes, - ) - .unwrap(); - let mut cursor = std::io::Cursor::new(&bytes); - let records = WeaponItem::parse(&mut cursor, bytes.len() as u64).unwrap(); - let mut value = serde_json::to_value(&records[0]).unwrap(); - let object = value.as_object_mut().unwrap(); - assert!(object.remove("modification_budget").is_some()); - object.insert("durability".to_string(), serde_json::json!(5)); - let restored: WeaponItem = serde_json::from_value(value).unwrap(); - assert_eq!( - serde_json::to_value(&restored) - .unwrap() - .get("modification_budget") - .and_then(|v| v.as_i64()), - Some(5) - ); - } } // ============================================================================ diff --git a/src/database/tests.rs b/src/database/tests.rs index 9d137a4e..7f4fa7a5 100644 --- a/src/database/tests.rs +++ b/src/database/tests.rs @@ -24,7 +24,7 @@ fn weapon_bytes(name: &str, base_price: i32, weapon_item_id: i32, attack: i16) - rec.extend(vec![0u8; 8]); // hp, mp, str, agi rec.extend(vec![0u8; 8]); // wis, con, dodge, to_hit rec.extend_from_slice(&attack.to_le_bytes()); - rec.extend(vec![0u8; 26]); // defense, magical_str, durability, pads, reqs + rec.extend(vec![0u8; 26]); // defense, magical_str, modification_budget, pads, reqs assert_eq!(rec.len(), 284); let mut data = 1i32.to_le_bytes().to_vec(); diff --git a/src/modding/patchers/dialogue.rs b/src/modding/patchers/dialogue.rs index beb972d0..93f2342a 100644 --- a/src/modding/patchers/dialogue.rs +++ b/src/modding/patchers/dialogue.rs @@ -61,7 +61,7 @@ impl RecordPatcher for DialogueScriptPatcher { ))); } "required_event_id" => rec.required_event_id = parse_optional_i32(field, new)?, - "fallback_dialog_id" | "next_dialog_to_check" => { + "fallback_dialog_id" => { rec.fallback_dialog_id = parse_optional_i32(field, new)? } "dialog_id" => rec.dialog_id = parse_optional_i32(field, new)?, @@ -202,15 +202,6 @@ mod tests { assert_eq!(parse_dlgs(&out)[0].fallback_dialog_id, Some(55)); } - #[test] - fn dlg_legacy_next_dialog_key_still_works() { - let p = DialogueScriptPatcher; - let out = p - .apply_field(&dlg_blob(), 0, "next_dialog_to_check", &Value::I64(65)) - .expect("the stored key must still be accepted"); - assert_eq!(parse_dlgs(&out)[0].fallback_dialog_id, Some(65)); - } - #[test] fn dlg_change_dialog_id() { let p = DialogueScriptPatcher; diff --git a/src/queries/create_table_dialogue_scripts.sql b/src/queries/create_table_dialogue_scripts.sql index af8495f5..202c530d 100644 --- a/src/queries/create_table_dialogue_scripts.sql +++ b/src/queries/create_table_dialogue_scripts.sql @@ -2,7 +2,7 @@ CREATE TABLE IF NOT EXISTS dialogue_scripts( dialog_file_id INTEGER NOT NULL, id INTEGER NOT NULL, required_event_id INTEGER, - next_dialog_to_check INTEGER, + fallback_dialog_id INTEGER, dialog_type INTEGER, dialog_owner INTEGER, dialog_id INTEGER, diff --git a/src/queries/create_table_edit_items.sql b/src/queries/create_table_edit_items.sql index 52b47dc8..3f021272 100644 --- a/src/queries/create_table_edit_items.sql +++ b/src/queries/create_table_edit_items.sql @@ -16,7 +16,7 @@ CREATE TABLE IF NOT EXISTS edit_items offense INTEGER, defense INTEGER, magical_power INTEGER, - modification_resistance INTEGER, + modification_cost INTEGER, reserved_byte INTEGER, modifies_item BOOLEAN, additional_effect INTEGER diff --git a/src/queries/create_table_extra_refs.sql b/src/queries/create_table_extra_refs.sql index 423daa75..eccef60a 100644 --- a/src/queries/create_table_extra_refs.sql +++ b/src/queries/create_table_extra_refs.sql @@ -49,7 +49,7 @@ CREATE TABLE IF NOT EXISTS extra_refs is_quest_element INTEGER, post_activation_tile_flag INTEGER, post_activation_footprint_mode INTEGER, - preserve_final_sprite_frame INTEGER, + reset_to_base_sprite_frame INTEGER, alternate_render_mode INTEGER, open_sfx_id INTEGER, open_sfx_reserved INTEGER, diff --git a/src/queries/create_table_heal_items.sql b/src/queries/create_table_heal_items.sql index 762c2045..0ec4870c 100644 --- a/src/queries/create_table_heal_items.sql +++ b/src/queries/create_table_heal_items.sql @@ -10,7 +10,7 @@ CREATE TABLE IF NOT EXISTS heal_items restores_full_health BOOLEAN, restores_full_mana BOOLEAN, cures_poison BOOLEAN, - cures_petrification BOOLEAN, + cures_paralysis BOOLEAN, cures_polymorph BOOLEAN, reserved_trailer BLOB ); diff --git a/src/queries/create_table_monsters.sql b/src/queries/create_table_monsters.sql index e52f8705..e0f32862 100644 --- a/src/queries/create_table_monsters.sql +++ b/src/queries/create_table_monsters.sql @@ -4,9 +4,9 @@ CREATE TABLE IF NOT EXISTS monsters name TEXT, health_points_max INTEGER, health_points_min INTEGER, - mana_points_max INTEGER, - mana_points_min INTEGER, - walk_speed INTEGER, + mana_points_max INTEGER, + mana_points_min INTEGER, + attack_cooldown_ticks INTEGER, to_hit_max INTEGER, to_hit_min INTEGER, to_dodge_max INTEGER, diff --git a/src/queries/create_table_weapons.sql b/src/queries/create_table_weapons.sql index a32973b1..a236e935 100644 --- a/src/queries/create_table_weapons.sql +++ b/src/queries/create_table_weapons.sql @@ -16,7 +16,7 @@ CREATE TABLE IF NOT EXISTS weapons attack INTEGER, defense INTEGER, magical_strength INTEGER, - durability INTEGER, + modification_budget INTEGER, reserved_0x108 INTEGER, reserved_0x10a INTEGER, req_strength INTEGER, diff --git a/src/queries/insert_dialogue_scripts.sql b/src/queries/insert_dialogue_scripts.sql index 780eac47..4d15e042 100644 --- a/src/queries/insert_dialogue_scripts.sql +++ b/src/queries/insert_dialogue_scripts.sql @@ -2,7 +2,7 @@ INSERT OR REPLACE INTO dialogue_scripts( dialog_file_id, id, required_event_id, - next_dialog_to_check, + fallback_dialog_id, dialog_type, dialog_owner, dialog_id, diff --git a/src/queries/insert_edit_item.sql b/src/queries/insert_edit_item.sql index 90ea3bdb..5f27a284 100644 --- a/src/queries/insert_edit_item.sql +++ b/src/queries/insert_edit_item.sql @@ -14,7 +14,7 @@ INSERT OR REPLACE INTO edit_items(id, offense, defense, magical_power, - modification_resistance, + modification_cost, reserved_byte, modifies_item, additional_effect) diff --git a/src/queries/insert_extra_ref.sql b/src/queries/insert_extra_ref.sql index da909023..555dfd2f 100644 --- a/src/queries/insert_extra_ref.sql +++ b/src/queries/insert_extra_ref.sql @@ -47,7 +47,7 @@ INSERT OR REPLACE INTO extra_refs(file_id, is_quest_element, post_activation_tile_flag, post_activation_footprint_mode, - preserve_final_sprite_frame, + reset_to_base_sprite_frame, alternate_render_mode, open_sfx_id, open_sfx_reserved, diff --git a/src/queries/insert_heal_item.sql b/src/queries/insert_heal_item.sql index de263ef5..1405ee4a 100644 --- a/src/queries/insert_heal_item.sql +++ b/src/queries/insert_heal_item.sql @@ -8,7 +8,7 @@ INSERT OR REPLACE INTO heal_items(id, restores_full_health, restores_full_mana, cures_poison, - cures_petrification, + cures_paralysis, cures_polymorph, reserved_trailer) VALUES (?1, diff --git a/src/queries/insert_monster.sql b/src/queries/insert_monster.sql index e2ed73b0..af6732cc 100644 --- a/src/queries/insert_monster.sql +++ b/src/queries/insert_monster.sql @@ -4,7 +4,7 @@ INSERT OR REPLACE INTO monsters(id, health_points_min, mana_points_max, mana_points_min, - walk_speed, + attack_cooldown_ticks, to_hit_max, to_hit_min, to_dodge_max, diff --git a/src/queries/insert_weapon.sql b/src/queries/insert_weapon.sql index 786acec5..cd5b1388 100644 --- a/src/queries/insert_weapon.sql +++ b/src/queries/insert_weapon.sql @@ -14,7 +14,7 @@ INSERT OR REPLACE INTO weapons(id, attack, defense, magical_strength, - durability, + modification_budget, reserved_0x108, reserved_0x10a, req_strength, diff --git a/src/references/dialogue_paragraph.rs b/src/references/dialogue_paragraph.rs index 85f0303b..39376316 100644 --- a/src/references/dialogue_paragraph.rs +++ b/src/references/dialogue_paragraph.rs @@ -73,8 +73,7 @@ pub struct DialogueParagraph { pub text: String, /// Developer trailing strings (`\;`) restored and preserved internally. pub comment: String, - /// Next page id in the PGP dialogue chain. - #[serde(alias = "param1")] + /// Next page ID in the PGP dialogue chain. pub next_page_id: i32, /// ID of the sound from the wave.ini file. Played at start of dialogue. pub wave_ini_entry_id: i32, diff --git a/src/references/dialogue_script.rs b/src/references/dialogue_script.rs index 0c46cd68..140421b5 100644 --- a/src/references/dialogue_script.rs +++ b/src/references/dialogue_script.rs @@ -35,14 +35,14 @@ use serde::{Deserialize, Serialize}; /// # Field Definitions /// /// - `id`: Unique dialogue line identifier -/// - `required_event_id`: Required event ID to trigger (shown as `prev_event` in file) -/// - `fallback_dialog_id`: alternate dialogue when the gate fails or the paragraph is empty (`next_dlg` in file) -/// - `dialog_type`: 0 = normal, 1 = choice dialog (shown as `type` in file) -/// - `dialog_owner`: 0 = player, 1 = NPC (shown as `owner` in file) -/// - `dialog_id`: Reference to PGP text content (shown as `dlg_id` in file) -/// - `next_dialog_id1`: Next dialog option [1] for choice dialogs (shown as `opt0` in file) -/// - `next_dialog_id2`: Next dialog option [2] for choice dialogs (shown as `opt1` in file) -/// - `next_dialog_id3`: Next dialog option [3] for choice dialogs (shown as `opt2` in file) +/// - `required_event_id`: Required event ID to trigger +/// - `fallback_dialog_id`: alternate dialogue when the gate fails or the paragraph is empty +/// - `dialog_type`: 0 = normal, 1 = choice dialog +/// - `dialog_owner`: 0 = player, 1 = NPC +/// - `dialog_id`: Reference to PGP text content +/// - `next_dialog_id1`: Next dialog option [1] for choice dialogs +/// - `next_dialog_id2`: Next dialog option [2] for choice dialogs +/// - `next_dialog_id3`: Next dialog option [3] for choice dialogs /// - `triggered_event_id`: Event triggered by dialogue (shown as `event_id` in file) /// /// # Dialogue Types @@ -73,7 +73,6 @@ pub struct DialogueScript { /// Required event to trigger this dialog. pub required_event_id: Option, /// Alternate dialog used when the gate fails or the paragraph is empty; `0` ends the chain. - #[serde(alias = "next_dialog_to_check")] pub fallback_dialog_id: Option, /// Type of dialog (normal or choice). /// In case of the choice, the choices are in next_dialog_id1, next_dialog_id2, next_dialog_id3 unless they are zero. diff --git a/src/references/heal_item_db.rs b/src/references/heal_item_db.rs index 39ebf576..af3a8534 100644 --- a/src/references/heal_item_db.rs +++ b/src/references/heal_item_db.rs @@ -122,8 +122,6 @@ pub struct HealItem { #[extractor(enum_from_u8(type = "HealItemFlag"))] pub cures_poison: HealItemFlag, #[extractor(enum_from_u8(type = "HealItemFlag"))] - #[serde(alias = "cures_petrification")] - #[patcher(field_alias = "cures_petrification")] pub cures_paralysis: HealItemFlag, #[extractor(enum_from_u8(type = "HealItemFlag"))] pub cures_polymorph: HealItemFlag, @@ -190,21 +188,6 @@ mod tests { rec } - #[test] - fn test_legacy_patcher_key_sets_paralysis_cure() { - use crate::modding::patcher::RecordPatcher; - use crate::modding::value::Value; - - let mut data = 1i32.to_le_bytes().to_vec(); - data.extend(item_bytes("MistvaleTonic", 40, 20)); - let out = HealItemPatcher - .apply_field(&data, 0, "cures_petrification", &Value::I64(1)) - .expect("the stored patcher key must still be accepted"); - let mut cursor = Cursor::new(&out[..]); - let items = HealItem::parse(&mut cursor, out.len() as u64).unwrap(); - assert_eq!(items[0].cures_paralysis, HealItemFlag::Active); - } - #[test] fn parse_single_item() { let mut data = 1i32.to_le_bytes().to_vec(); diff --git a/src/references/monster_db.rs b/src/references/monster_db.rs index bbe8ef59..49f8bc4c 100644 --- a/src/references/monster_db.rs +++ b/src/references/monster_db.rs @@ -126,8 +126,6 @@ pub struct Monster { pub mana_points_min: i32, /// Attack cooldown measured in ticks. #[extractor(primitive(type = "i32"))] - #[serde(alias = "walk_speed")] - #[patcher(field_alias = "walk_speed")] pub attack_cooldown_ticks: i32, /// Upper bound of accuracy. #[extractor(primitive(type = "i32"))] @@ -312,24 +310,6 @@ mod tests { buf } - #[test] - fn test_legacy_patcher_key_sets_attack_cooldown() { - use crate::modding::patcher::RecordPatcher; - use crate::modding::value::Value; - - let stats = [0i32; 34]; - let mut data = monster_bytes("MistvaleWolf", &stats); - let mut framed = Vec::new(); - framed.extend_from_slice(&1i32.to_le_bytes()); - framed.append(&mut data); - let out = MonsterPatcher - .apply_field(&framed, 0, "walk_speed", &Value::I64(9)) - .expect("the stored patcher key must still be accepted"); - let mut cursor = Cursor::new(&out[..]); - let records = Monster::parse(&mut cursor, out.len() as u64).unwrap(); - assert_eq!(records[0].attack_cooldown_ticks, 9); - } - #[test] fn parse_single_record() { #[rustfmt::skip] diff --git a/src/references/save_file/game_tmp.rs b/src/references/save_file/game_tmp.rs index 4e7cece0..948d20f6 100644 --- a/src/references/save_file/game_tmp.rs +++ b/src/references/save_file/game_tmp.rs @@ -252,7 +252,7 @@ pub struct MonsterRecord { /// Maximum mana points. pub mp_maximum: u16, /// Movement speed. - pub walk_speed: u8, + pub attack_cooldown_ticks: u8, /// Hit rate. pub hit_rate: u8, /// Dodge rate. @@ -621,7 +621,7 @@ pub struct ExtraObjectRecord { pub is_quest_element: u32, pub post_activation_tile_flag: u32, pub post_activation_footprint_mode: u32, - pub preserve_final_sprite_frame: u32, + pub reset_to_base_sprite_frame: u32, pub alternate_render_mode: u32, /// Wave.ini open-SFX index (record `+0xAC`). See `ExtraRef`. pub open_sfx_id: u8, @@ -742,7 +742,7 @@ pub struct DrawItemEditItem { pub offense: i16, // 258 pub defense: i16, // 260 pub magical_power: i16, // 262 - pub modification_resistance: i16, // 264 + pub modification_cost: i16, // 264 /// Reserved byte; observed as zero and not used by the game. pub reserved_byte: u8, // 265 pub modifies_item: u8, // 266 @@ -769,7 +769,7 @@ pub struct DrawItemHealItem { pub restore_full_health: u8, // 245 pub restore_full_mana: u8, // 246 pub poison_heal: u8, // 247 - pub petrif_heal: u8, // 248 + pub cures_paralysis: u8, // 248 pub polimorph_heal: u8, // 249 /// Reserved trailer bytes; preserve them verbatim. pub reserved_trailer: [u8; 3], // 252 @@ -801,7 +801,7 @@ pub struct DrawItemWeaponItem { pub attack: i16, // 258 pub defense: i16, // 260 pub magical_strength: i16, // 262 - pub durability: i16, // 264 + pub modification_budget: i16, // 264 pub padding2: i16, // 266 pub padding3: i16, // 268 pub req_strength: i16, // 270 diff --git a/src/references/save_file/inventory.rs b/src/references/save_file/inventory.rs index e3d8d28f..584a28a7 100644 --- a/src/references/save_file/inventory.rs +++ b/src/references/save_file/inventory.rs @@ -341,7 +341,7 @@ pub struct InventoryEditItem { pub offense: i16, // 258 pub defense: i16, // 260 pub magical_power: i16, // 262 - pub modification_resistance: i16, // 264 + pub modification_cost: i16, // 264 /// Reserved byte; observed as zero and not used by the game. pub reserved_byte: u8, // 265 pub modifies_item: u8, // 266 @@ -368,7 +368,7 @@ pub struct InventoryHealItem { pub restore_full_health: u8, // 245 pub restore_full_mana: u8, // 246 pub poison_heal: u8, // 247 - pub petrif_heal: u8, // 248 + pub cures_paralysis: u8, // 248 pub polimorph_heal: u8, // 249 /// First byte of the item definition's reserved trailer; normally zero. pub reserved_definition_byte: u8, @@ -400,7 +400,7 @@ pub struct InventoryWeaponItem { pub attack: i16, // 258 pub defense: i16, // 260 pub magical_strength: i16, // 262 - pub durability: i16, // 264 + pub modification_budget: i16, // 264 pub padding2: i16, // 266 pub padding3: i16, // 268 pub req_strength: i16, // 270 diff --git a/src/references/weapons_db.rs b/src/references/weapons_db.rs index c6966ca8..7fa02dca 100644 --- a/src/references/weapons_db.rs +++ b/src/references/weapons_db.rs @@ -157,8 +157,6 @@ pub struct WeaponItem { pub magical_strength: i16, /// Remaining workshop modification budget. #[extractor(primitive(type = "i16"))] - #[serde(alias = "durability")] - #[patcher(field_alias = "durability")] pub modification_budget: i16, /// Reserved serialized word at byte offset `0x108`. It is zero by default /// with no observed reader. @@ -257,21 +255,6 @@ mod tests { rec } - #[test] - fn test_legacy_patcher_key_sets_modification_budget() { - use crate::modding::patcher::RecordPatcher; - use crate::modding::value::Value; - - let mut data = 1i32.to_le_bytes().to_vec(); - data.extend(weapon_bytes("MistvaleBlade", 100, 3, 12)); - let out = WeaponItemPatcher - .apply_field(&data, 0, "durability", &Value::I64(25)) - .expect("the stored patcher key must still be accepted"); - let mut cursor = Cursor::new(&out[..]); - let records = WeaponItem::parse(&mut cursor, out.len() as u64).unwrap(); - assert_eq!(records[0].modification_budget, 25); - } - #[test] fn parse_single_weapon() { let mut data = 1i32.to_le_bytes().to_vec(); From 22ee06e78124fce535a9c3abf3a7477a0dea20c2 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:59:33 +0100 Subject: [PATCH 58/72] fix(core): fix compilation error --- src/references/extra_ref.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/references/extra_ref.rs b/src/references/extra_ref.rs index 7bcf9783..620b9a03 100644 --- a/src/references/extra_ref.rs +++ b/src/references/extra_ref.rs @@ -159,8 +159,8 @@ pub struct ExtraRef { #[extractor(primitive(type = "u8"))] pub footprint_orientation: u8, /// Maximum distance at which the object can be activated. - #[extractor(primitive(type = "i8"))] - pub interaction_range: i8, + #[extractor(primitive(type = "u8"))] + pub interaction_range: u8, /// Padding after [`Self::interaction_range`] (normally `[0xCD; 2]`). #[extractor(vec_u8(size = 2))] pub interaction_range_padding: Vec, From 5ccb1102b9821db55d8ce00b26a92bd231894163 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:13:01 +0100 Subject: [PATCH 59/72] fix(core): Use in-memory or /tmp for saving any files within tests --- dispel-gui/src/app.rs | 24 ++++- dispel-gui/src/editors/fog_data/update.rs | 2 +- .../src/editors/map_editor/update/entity.rs | 4 +- .../src/editors/map_editor/update/map.rs | 8 +- dispel-gui/src/indexation/file_index_cache.rs | 29 +++--- .../src/indexation/indexation_service.rs | 16 +++- dispel-gui/src/indexation/tests.rs | 8 +- dispel-gui/src/main.rs | 1 + dispel-gui/src/paths.rs | 29 ++++++ dispel-gui/src/state.rs | 17 ++-- dispel-gui/src/update/system.rs | 28 +++--- dispel-gui/src/update/tests.rs | 4 +- src/map/reader.rs | 46 ++++++---- src/modding/patchers/dialogue.rs | 4 +- src/references/extra_ref.rs | 4 +- src/references/save_file/game_tmp.rs | 88 +++++++++---------- src/references/save_file/inventory.rs | 50 +++++------ 17 files changed, 211 insertions(+), 151 deletions(-) create mode 100644 dispel-gui/src/paths.rs diff --git a/dispel-gui/src/app.rs b/dispel-gui/src/app.rs index 834cd112..11633390 100644 --- a/dispel-gui/src/app.rs +++ b/dispel-gui/src/app.rs @@ -36,11 +36,16 @@ pub struct App { pub start_page_input: String, pub is_indexing: bool, pub error_dialog: Option, + #[cfg(test)] + _test_root: Option, } impl App { pub fn new() -> (Self, Task) { - let mut state = AppState::default(); + Self::boot(AppState::default()) + } + + fn boot(mut state: AppState) -> (Self, Task) { if let Err(e) = state.load_workspace() { eprintln!("Failed to load workspace: {}", e); } @@ -134,11 +139,23 @@ impl App { start_page_input, is_indexing, error_dialog: None, + #[cfg(test)] + _test_root: None, }, final_init_task, ) } + #[cfg(test)] + pub fn test_app() -> Self { + let root = tempfile::tempdir().expect("temp dir"); + let mut state = AppState::default(); + state.paths = crate::paths::AppPaths::test_paths(root.path()); + let (mut app, _) = Self::boot(state); + app._test_root = Some(root); + app + } + pub(crate) fn set_title(&self) -> String { let default_title: String = "Dispel Extractor".to_owned(); @@ -152,10 +169,12 @@ impl App { pub fn test_new(workspace: crate::workspace::Workspace) -> Self { use crate::state::AppState; - let state = AppState { + let root = tempfile::tempdir().expect("temp dir"); + let mut state = AppState { workspace, ..Default::default() }; + state.paths = crate::paths::AppPaths::test_paths(root.path()); Self { state, @@ -171,6 +190,7 @@ impl App { start_page_input: String::new(), is_indexing: false, error_dialog: None, + _test_root: Some(root), } } diff --git a/dispel-gui/src/editors/fog_data/update.rs b/dispel-gui/src/editors/fog_data/update.rs index aaade94c..0c14e514 100644 --- a/dispel-gui/src/editors/fog_data/update.rs +++ b/dispel-gui/src/editors/fog_data/update.rs @@ -313,7 +313,7 @@ mod tests { use std::path::Path; fn app_with_recording() -> App { - let mut app = App::new().0; + let mut app = App::test_app(); app.state.shared_game_path = "/game/root".to_string(); app.state.recording = Some(RecordingSession { workspace_root: PathBuf::from("/workspace"), diff --git a/dispel-gui/src/editors/map_editor/update/entity.rs b/dispel-gui/src/editors/map_editor/update/entity.rs index b955e36b..a4e97f43 100644 --- a/dispel-gui/src/editors/map_editor/update/entity.rs +++ b/dispel-gui/src/editors/map_editor/update/entity.rs @@ -337,7 +337,7 @@ mod tests { /// Create an App with a map editor tab that has one DrawItem. fn app_with_draw_item() -> (App, usize) { let tab_id = 42; - let mut app = App::new().0; + let mut app = App::test_app(); let state = app.state.editors.map_editors.entry(tab_id).or_default(); state.data.all_map_id = Some(0); @@ -487,7 +487,7 @@ mod tests { use std::collections::HashMap; let tab_id = 99; - let mut app = App::new().0; + let mut app = App::test_app(); let state = app.state.editors.map_editors.entry(tab_id).or_default(); let model = MapModel { diff --git a/dispel-gui/src/editors/map_editor/update/map.rs b/dispel-gui/src/editors/map_editor/update/map.rs index fd8ef771..8b53faf7 100644 --- a/dispel-gui/src/editors/map_editor/update/map.rs +++ b/dispel-gui/src/editors/map_editor/update/map.rs @@ -863,10 +863,8 @@ mod tests { #[test] fn test_resolve_map_id_missing_file() { - let tmp = std::env::temp_dir().join("dispel_test_no_allmap"); - let _ = std::fs::create_dir_all(&tmp); - // No AllMap.ini in this dir → should return None - assert_eq!(resolve_map_id("map1", &tmp), None); + let tmp = tempfile::tempdir().expect("temp dir"); + assert_eq!(resolve_map_id("map1", tmp.path()), None); } #[test] @@ -969,7 +967,7 @@ mod tests { /// App with a map editor tab whose map data is loaded (8×8 tiles). fn app_with_loaded_map(object_ids: HashMap<(i32, i32), i32>) -> App { - let mut app = App::new().0; + let mut app = App::test_app(); let model = MapModel { border_count: 2, tiled_map_width: 8, diff --git a/dispel-gui/src/indexation/file_index_cache.rs b/dispel-gui/src/indexation/file_index_cache.rs index 4406c542..18996503 100644 --- a/dispel-gui/src/indexation/file_index_cache.rs +++ b/dispel-gui/src/indexation/file_index_cache.rs @@ -59,18 +59,18 @@ pub struct FileIndexCacheManager { impl FileIndexCacheManager { /// Create new cache manager pub fn new() -> Result { - let cache_dir = Self::get_cache_directory()?; + let base = dirs::cache_dir().ok_or(CacheError::DirectoryAccess)?; + Self::new_with_dir(base) + } + + /// Create a cache manager under a given base directory + pub fn new_with_dir(base: PathBuf) -> Result { + let cache_dir = base.join("dispel-gui"); std::fs::create_dir_all(&cache_dir)?; Ok(Self { cache_dir }) } - /// Get cache directory using dirs crate - fn get_cache_directory() -> Result { - let cache_dir = dirs::cache_dir().ok_or(CacheError::DirectoryAccess)?; - Ok(cache_dir.join("dispel-gui")) - } - /// Get cache file path pub(crate) fn get_cache_path(&self) -> PathBuf { self.cache_dir.join("file_index.cache") @@ -192,19 +192,20 @@ mod tests { #[test] fn test_cache_directory_is_app_subdirectory() { - let dir = FileIndexCacheManager::get_cache_directory().expect("cache directory available"); + let root = tempfile::tempdir().expect("temp dir"); + let manager = + FileIndexCacheManager::new_with_dir(root.path().to_path_buf()).expect("cache manager"); assert_eq!( - dir.file_name().and_then(|name| name.to_str()), + manager.cache_dir.file_name().and_then(|name| name.to_str()), Some("dispel-gui") ); assert!( - !dir.components() + !manager + .cache_dir + .components() .any(|component| component == std::path::Component::ParentDir), - "cache path must not traverse above the platform cache directory" + "cache path must not traverse above the base directory" ); - - let manager = FileIndexCacheManager::new().expect("cache manager created"); - assert_eq!(manager.cache_dir, dir); assert!( manager.cache_dir.exists(), "cache directory must exist after creation" diff --git a/dispel-gui/src/indexation/indexation_service.rs b/dispel-gui/src/indexation/indexation_service.rs index c4c2e494..d9a3df3b 100644 --- a/dispel-gui/src/indexation/indexation_service.rs +++ b/dispel-gui/src/indexation/indexation_service.rs @@ -477,7 +477,9 @@ mod tests { #[test] fn test_scan_directory_with_files() { - let cache_manager = FileIndexCacheManager::new().unwrap(); + let cache_dir = tempfile::tempdir().unwrap(); + let cache_manager = + FileIndexCacheManager::new_with_dir(cache_dir.path().to_path_buf()).unwrap(); let service = IndexationService::new(cache_manager); let test_dir = tempfile::tempdir().unwrap(); @@ -504,7 +506,9 @@ mod tests { #[test] fn test_scan_empty_directory() { - let cache_manager = FileIndexCacheManager::new().unwrap(); + let cache_dir = tempfile::tempdir().unwrap(); + let cache_manager = + FileIndexCacheManager::new_with_dir(cache_dir.path().to_path_buf()).unwrap(); let service = IndexationService::new(cache_manager); let test_dir = tempfile::tempdir().unwrap(); @@ -527,7 +531,9 @@ mod tests { #[test] fn test_progress_tracking_basic() { // Test basic progress tracking functionality - let cache_manager = FileIndexCacheManager::new().unwrap(); + let cache_dir = tempfile::tempdir().unwrap(); + let cache_manager = + FileIndexCacheManager::new_with_dir(cache_dir.path().to_path_buf()).unwrap(); let service = IndexationService::new(cache_manager); // Create a channel for progress updates @@ -634,7 +640,9 @@ mod tests { #[test] fn test_progress_history_methods() { // Test progress history methods - let cache_manager = FileIndexCacheManager::new().unwrap(); + let cache_dir = tempfile::tempdir().unwrap(); + let cache_manager = + FileIndexCacheManager::new_with_dir(cache_dir.path().to_path_buf()).unwrap(); let mut service = IndexationService::new(cache_manager); let rt = tokio::runtime::Runtime::new().unwrap(); diff --git a/dispel-gui/src/indexation/tests.rs b/dispel-gui/src/indexation/tests.rs index 06a00c1a..099a89d2 100644 --- a/dispel-gui/src/indexation/tests.rs +++ b/dispel-gui/src/indexation/tests.rs @@ -44,7 +44,6 @@ fn test_cache_serialization_deserialization() { }); // Test serialization - let _cache_manager = FileIndexCacheManager::new().unwrap(); let temp_dir = tempdir().unwrap(); let _test_cache_path = temp_dir.path().join("test.cache"); @@ -84,8 +83,6 @@ fn test_cache_serialization_deserialization() { #[test] fn test_cache_validation() { - let _cache_manager = FileIndexCacheManager::new().unwrap(); - // Create test cache let cache = FileIndexCache { game_path: PathBuf::from("/test/game"), @@ -108,8 +105,6 @@ fn test_cache_validation() { #[test] fn test_cache_invalidation_by_time() { - let _cache_manager = FileIndexCacheManager::new().unwrap(); - // Create cache that's 31 days old (should be invalid) let old_timestamp = FileIndexCacheManager::current_timestamp() - (31 * 24 * 60 * 60); @@ -156,7 +151,8 @@ fn test_future_timestamp_does_not_underflow_cache_validator() { #[test] fn test_cache_directory_creation() { - let cache_manager = FileIndexCacheManager::new().unwrap(); + let root = tempdir().unwrap(); + let cache_manager = FileIndexCacheManager::new_with_dir(root.path().to_path_buf()).unwrap(); // Verify cache directory was created assert!(cache_manager.cache_dir.exists()); diff --git a/dispel-gui/src/main.rs b/dispel-gui/src/main.rs index 75e5a03a..8faaa22a 100644 --- a/dispel-gui/src/main.rs +++ b/dispel-gui/src/main.rs @@ -13,6 +13,7 @@ pub mod editor_registry; pub mod editors; pub mod indexation; pub mod message; +pub mod paths; pub mod subscriptions; pub mod platform; diff --git a/dispel-gui/src/paths.rs b/dispel-gui/src/paths.rs new file mode 100644 index 00000000..774d85fc --- /dev/null +++ b/dispel-gui/src/paths.rs @@ -0,0 +1,29 @@ +//! Base directories for config and cache files. + +use std::path::{Path, PathBuf}; + +#[derive(Clone, Debug)] +pub struct AppPaths { + pub config_dir: PathBuf, + pub cache_dir: PathBuf, +} + +impl AppPaths { + pub fn from_dirs() -> Self { + Self { + config_dir: dirs::config_dir().unwrap_or_else(|| PathBuf::from(".")), + cache_dir: dirs::cache_dir().unwrap_or_else(|| PathBuf::from(".")), + } + } + + pub fn test_paths(root: &Path) -> Self { + Self { + config_dir: root.join("config"), + cache_dir: root.join("cache"), + } + } + + pub fn workspace_path(&self) -> PathBuf { + self.config_dir.join("dispel-gui").join("workspace.json") + } +} diff --git a/dispel-gui/src/state.rs b/dispel-gui/src/state.rs index 27eb3d6f..f30b3139 100644 --- a/dispel-gui/src/state.rs +++ b/dispel-gui/src/state.rs @@ -2,9 +2,9 @@ use crate::components::composite_item::CompositeItemOptions; use crate::editor_registry::EditorRegistry; use crate::indexation::file_index_cache::{FileIndexCache, FileIndexCacheManager}; use crate::message::{Message, system::SystemMessage}; +use crate::paths::AppPaths; use crate::workspace::EditorType; use crate::workspace::Workspace; -use dirs; use dispel_core::Extractor; use iced::{ Task, @@ -17,6 +17,7 @@ use std::path::{Path, PathBuf}; /// Application state — all mutable data for the GUI. pub struct AppState { + pub paths: AppPaths, pub status_msg: String, pub shared_game_path: String, pub editors: EditorRegistry, @@ -73,7 +74,7 @@ pub struct PendingEdit { impl AppState { pub fn save_workspace(&self) -> io::Result<()> { - let path = Self::workspace_path(); + let path = self.workspace_path(); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } @@ -84,7 +85,8 @@ impl AppState { } pub fn load_workspace(&mut self) -> io::Result<()> { - self.load_workspace_from(&Self::workspace_path()) + let path = self.workspace_path(); + self.load_workspace_from(&path) } fn load_workspace_from(&mut self, path: &PathBuf) -> io::Result<()> { @@ -102,7 +104,8 @@ impl AppState { /// Initialize file index cache manager pub fn initialize_cache_manager(&mut self) { if self.file_index_cache_manager.is_none() - && let Ok(cache_manager) = FileIndexCacheManager::new() + && let Ok(cache_manager) = + FileIndexCacheManager::new_with_dir(self.paths.cache_dir.clone()) { // Perform initial cache cleanup if let Err(e) = cache_manager.perform_periodic_cleanup() { @@ -230,9 +233,8 @@ impl AppState { )) } - fn workspace_path() -> PathBuf { - let base = dirs::config_dir().unwrap_or_else(|| PathBuf::from(".")); - base.join("dispel-gui").join("workspace.json") + fn workspace_path(&self) -> PathBuf { + self.paths.workspace_path() } /// Clear all editor states when workspace changes @@ -258,6 +260,7 @@ impl AppState { impl Default for AppState { fn default() -> Self { Self { + paths: AppPaths::from_dirs(), shared_game_path: String::new(), status_msg: String::new(), editors: EditorRegistry::default(), diff --git a/dispel-gui/src/update/system.rs b/dispel-gui/src/update/system.rs index 2c2b1953..4d65bfda 100644 --- a/dispel-gui/src/update/system.rs +++ b/dispel-gui/src/update/system.rs @@ -377,7 +377,7 @@ mod tests { #[test] fn test_clear_workspace_message_handler() { // Create a test app with some state - let mut app = App::new().0; + let mut app = App::test_app(); // Add some workspace tabs app.state @@ -446,7 +446,7 @@ mod tests { #[test] fn test_clear_workspace_with_no_tabs() { // Create a test app with no tabs - let mut app = App::new().0; + let mut app = App::test_app(); // Note: App is created with some default tabs, so we just verify the clear works let _initial_tab_count = app.state.workspace.tabs.len(); @@ -470,7 +470,7 @@ mod tests { #[test] fn test_clear_workspace_preserves_game_path() { // Create a test app - let mut app = App::new().0; + let mut app = App::test_app(); // Set a game path app.state.workspace.game_path = Some(std::path::PathBuf::from("/test/game")); @@ -497,7 +497,7 @@ mod tests { #[test] fn test_clear_workspace_is_idempotent() { // Create a test app - let mut app = App::new().0; + let mut app = App::test_app(); // First clear let task1 = handle(SystemMessage::ClearWorkspace, &mut app); @@ -531,7 +531,7 @@ mod tests { #[test] fn test_undo_nothing_no_tab() { - let mut app = App::new().0; + let mut app = App::test_app(); app.state.workspace.tabs.clear(); app.state.workspace.active_tab = None; let _ = handle(SystemMessage::Undo, &mut app); @@ -540,7 +540,7 @@ mod tests { #[test] fn test_redo_nothing_no_tab() { - let mut app = App::new().0; + let mut app = App::test_app(); app.state.workspace.tabs.clear(); app.state.workspace.active_tab = None; let _ = handle(SystemMessage::Redo, &mut app); @@ -549,7 +549,7 @@ mod tests { #[test] fn test_undo_viewer_tab_returns_nothing() { - let mut app = App::new().0; + let mut app = App::test_app(); app.state.workspace.tabs.clear(); app.state .workspace @@ -571,7 +571,7 @@ mod tests { fn test_undo_weapon_editor() { use dispel_core::WeaponItem; - let mut app = App::new().0; + let mut app = App::test_app(); push_weapon_tab(&mut app); // Load a weapon into the editor @@ -607,7 +607,7 @@ mod tests { fn test_redo_weapon_editor() { use dispel_core::WeaponItem; - let mut app = App::new().0; + let mut app = App::test_app(); push_weapon_tab(&mut app); let weapon = WeaponItem { @@ -639,7 +639,7 @@ mod tests { #[test] fn test_undo_weapon_editor_empty_history() { - let mut app = App::new().0; + let mut app = App::test_app(); push_weapon_tab(&mut app); let _ = handle(SystemMessage::Undo, &mut app); assert_eq!(app.state.status_msg, "Nothing to undo"); @@ -647,7 +647,7 @@ mod tests { #[test] fn test_file_selected_cancelled_or_empty_path_is_noop() { - let mut app = App::new().0; + let mut app = App::test_app(); push_weapon_tab(&mut app); let game_path = std::path::PathBuf::from("/test/game"); @@ -678,7 +678,7 @@ mod tests { #[test] fn test_modified_tab_warns_file_edits_discarded() { - let mut app = App::new().0; + let mut app = App::test_app(); let (title, description) = close_dialog_text(&app); assert_eq!(title, "Save workspace?"); assert!(!description.contains("unsaved")); @@ -718,7 +718,7 @@ mod tests { #[test] fn test_dirty_snf_tab_warns_without_tab_modified_flag() { - let mut app = App::new().0; + let mut app = App::test_app(); app.state.workspace.tabs.clear(); app.state .workspace @@ -742,7 +742,7 @@ mod tests { #[test] fn test_dirty_event_script_tab_warns_without_tab_modified_flag() { - let mut app = App::new().0; + let mut app = App::test_app(); app.state.workspace.tabs.clear(); app.state .workspace diff --git a/dispel-gui/src/update/tests.rs b/dispel-gui/src/update/tests.rs index f0b84c68..e446fee7 100644 --- a/dispel-gui/src/update/tests.rs +++ b/dispel-gui/src/update/tests.rs @@ -11,7 +11,7 @@ mod tests { #[test] fn test_clear_workspace_message() { // Create a test app with some state - let mut app = App::new().0; + let mut app = App::test_app(); // Add some workspace tabs app.state.workspace.tabs.push(crate::workspace::WorkspaceTab { @@ -50,7 +50,7 @@ mod tests { #[test] fn test_clear_workspace_with_no_tabs() { // Create a test app with no tabs - let mut app = App::new().0; + let mut app = App::test_app(); // Verify initial state assert_eq!(app.state.workspace.tabs.len(), 0); diff --git a/src/map/reader.rs b/src/map/reader.rs index 1a28d903..9c70f8ca 100644 --- a/src/map/reader.rs +++ b/src/map/reader.rs @@ -26,6 +26,13 @@ use super::types::{ TiledBundle, TiledObjectInfo, TiledObjectRef, }; +fn reader_len(reader: &mut BufReader) -> Result { + let pos = reader.stream_position()?; + let end = reader.seek(SeekFrom::End(0))?; + reader.seek(SeekFrom::Start(pos))?; + Ok(end) +} + // -------------------------------------------------------------------------- // Skipped blocks (parsed by the format but not persisted in MapData) // -------------------------------------------------------------------------- @@ -70,7 +77,7 @@ pub fn read_tiled_object_refs(reader: &mut BufReader) -> Result) -> Result> { +pub fn read_overlay_id_table(reader: &mut BufReader) -> Result> { let size = reader.read_i32::()?; let size = usize::try_from(size).map_err(|_| { std::io::Error::new( @@ -82,7 +89,7 @@ pub fn read_overlay_id_table(reader: &mut BufReader) -> Result> { // Every entry is two bytes. Refuse a count that cannot fit in the bytes // left in the file before reserving, so a corrupt size cannot trigger a // huge allocation. - let file_len = reader.get_ref().metadata()?.len(); + let file_len = reader_len(reader)?; let pos = reader.stream_position()?; let remaining = file_len.saturating_sub(pos); let max_entries = usize::try_from(remaining / 2).unwrap_or(usize::MAX); @@ -106,7 +113,9 @@ pub fn read_overlay_id_table(reader: &mut BufReader) -> Result> { /// Returns `(sequences, image_stamps)` — one stamp per sequence, same order /// (stamps are always 6 or 9; anything else is a parse error). -pub fn sprite_block(reader: &mut BufReader) -> Result<(Vec, Vec)> { +pub fn sprite_block( + reader: &mut BufReader, +) -> Result<(Vec, Vec)> { let sprite_count = reader.read_i32::()?; let sprite_count = usize::try_from(sprite_count).map_err(|_| { std::io::Error::new( @@ -117,7 +126,7 @@ pub fn sprite_block(reader: &mut BufReader) -> Result<(Vec, // Each sprite reads at least one four-byte image stamp. Cap the capacity // by the bytes actually left in the file before reserving. - let file_len = reader.get_ref().metadata()?.len(); + let file_len = reader_len(reader)?; let pos = reader.stream_position()?; let remaining = file_len.saturating_sub(pos); let max_sprites = usize::try_from(remaining / 4).unwrap_or(usize::MAX); @@ -161,8 +170,8 @@ pub fn sprite_block(reader: &mut BufReader) -> Result<(Vec, // Sprite info block – pixel placements for each embedded sprite // -------------------------------------------------------------------------- -pub fn sprite_info_block( - reader: &mut BufReader, +pub fn sprite_info_block( + reader: &mut BufReader, sprites: &[SequenceInfo], ) -> Result> { let count = reader.read_i32::()?; @@ -507,16 +516,15 @@ pub fn read_roof_tiles( #[cfg(test)] mod tests { use super::*; + use std::io::Cursor; - fn reader_from_bytes(name: &str, bytes: &[u8]) -> BufReader { - let path = std::env::temp_dir().join(format!("dispel-{name}-{}.bin", std::process::id())); - std::fs::write(&path, bytes).expect("write crafted map block"); - BufReader::new(File::open(&path).expect("open crafted map block")) + fn reader_from_bytes(bytes: &[u8]) -> BufReader>> { + BufReader::new(Cursor::new(bytes.to_vec())) } #[test] fn test_overlay_table_rejects_negative_size() { - let mut reader = reader_from_bytes("overlay-negative", &(-5_i32).to_le_bytes()); + let mut reader = reader_from_bytes(&(-5_i32).to_le_bytes()); let err = super::read_overlay_id_table(&mut reader).expect_err("negative size must fail"); assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); } @@ -524,21 +532,21 @@ mod tests { #[test] fn test_overlay_table_rejects_size_larger_than_file() { // Size claims a million u16 entries but the file only holds the size. - let mut reader = reader_from_bytes("overlay-oversized", &1_000_000_i32.to_le_bytes()); + let mut reader = reader_from_bytes(&1_000_000_i32.to_le_bytes()); let err = super::read_overlay_id_table(&mut reader).expect_err("oversized size must fail"); assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); } #[test] fn test_sprite_block_rejects_negative_count() { - let mut reader = reader_from_bytes("sprite-count-negative", &(-1_i32).to_le_bytes()); + let mut reader = reader_from_bytes(&(-1_i32).to_le_bytes()); let err = super::sprite_block(&mut reader).expect_err("negative count must fail"); assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); } #[test] fn test_sprite_block_rejects_count_larger_than_file() { - let mut reader = reader_from_bytes("sprite-count-oversized", &1_000_000_i32.to_le_bytes()); + let mut reader = reader_from_bytes(&1_000_000_i32.to_le_bytes()); let err = super::sprite_block(&mut reader).expect_err("oversized count must fail"); assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); } @@ -563,7 +571,7 @@ mod tests { #[test] fn test_sprite_info_block_rejects_out_of_range_id() { - let mut reader = reader_from_bytes("sprite-info-bad-id", &one_sprite_info_bytes(5)); + let mut reader = reader_from_bytes(&one_sprite_info_bytes(5)); let err = super::sprite_info_block(&mut reader, &one_sequence(1)) .expect_err("a sprite id past the sequence table must fail"); assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); @@ -571,7 +579,7 @@ mod tests { #[test] fn test_sprite_info_block_rejects_negative_id() { - let mut reader = reader_from_bytes("sprite-info-negative-id", &one_sprite_info_bytes(-1)); + let mut reader = reader_from_bytes(&one_sprite_info_bytes(-1)); let err = super::sprite_info_block(&mut reader, &one_sequence(1)) .expect_err("a negative sprite id must fail"); assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); @@ -579,7 +587,7 @@ mod tests { #[test] fn test_sprite_info_block_rejects_zero_frame_count() { - let mut reader = reader_from_bytes("sprite-info-zero-frames", &one_sprite_info_bytes(0)); + let mut reader = reader_from_bytes(&one_sprite_info_bytes(0)); let err = super::sprite_info_block(&mut reader, &one_sequence(0)) .expect_err("a sequence with no frames must fail"); assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); @@ -592,7 +600,7 @@ mod tests { let mut bytes = 2_i32.to_le_bytes().to_vec(); bytes.extend_from_slice(&0x0100_u16.to_le_bytes()); bytes.extend_from_slice(&0x0002_u16.to_le_bytes()); - let mut reader = reader_from_bytes("overlay-mode-entries", &bytes); + let mut reader = reader_from_bytes(&bytes); let table = super::read_overlay_id_table(&mut reader).unwrap(); let first = OverlayMode::from_raw(table[0]); @@ -613,7 +621,7 @@ mod tests { let mut bytes = 2_i32.to_le_bytes().to_vec(); bytes.extend_from_slice(&7_u16.to_le_bytes()); bytes.extend_from_slice(&9_u16.to_le_bytes()); - let mut reader = reader_from_bytes("overlay-valid", &bytes); + let mut reader = reader_from_bytes(&bytes); assert_eq!( super::read_overlay_id_table(&mut reader).unwrap(), vec![7, 9] diff --git a/src/modding/patchers/dialogue.rs b/src/modding/patchers/dialogue.rs index 93f2342a..8c95fda4 100644 --- a/src/modding/patchers/dialogue.rs +++ b/src/modding/patchers/dialogue.rs @@ -61,9 +61,7 @@ impl RecordPatcher for DialogueScriptPatcher { ))); } "required_event_id" => rec.required_event_id = parse_optional_i32(field, new)?, - "fallback_dialog_id" => { - rec.fallback_dialog_id = parse_optional_i32(field, new)? - } + "fallback_dialog_id" => rec.fallback_dialog_id = parse_optional_i32(field, new)?, "dialog_id" => rec.dialog_id = parse_optional_i32(field, new)?, "next_dialog_id1" => rec.next_dialog_id1 = parse_optional_i32(field, new)?, "next_dialog_id2" => rec.next_dialog_id2 = parse_optional_i32(field, new)?, diff --git a/src/references/extra_ref.rs b/src/references/extra_ref.rs index 620b9a03..0f1ccb12 100644 --- a/src/references/extra_ref.rs +++ b/src/references/extra_ref.rs @@ -1,8 +1,6 @@ use std::path::Path; -use crate::references::enums::{ - BooleanFlag, ExtraObjectType, InventoryItem, ItemTypeId, -}; +use crate::references::enums::{BooleanFlag, ExtraObjectType, InventoryItem, ItemTypeId}; use crate::references::extractor::Extractor; use dispel_macros::{Extractor, Localizable, RecordLayout, RecordPatcher}; use rusqlite::{Connection, Result, params}; diff --git a/src/references/save_file/game_tmp.rs b/src/references/save_file/game_tmp.rs index 948d20f6..42c96362 100644 --- a/src/references/save_file/game_tmp.rs +++ b/src/references/save_file/game_tmp.rs @@ -729,26 +729,26 @@ pub struct DrawItemEditItem { pub name: String, // 30 #[binary_record(string(encoding = "WINDOWS-1250", size = 202))] pub description: String, // 232 - pub base_price: u32, // 236 - pub edit_item_id: u32, // 240 - pub health_points: i16, // 242 - pub mana_points: i16, // 244 - pub strength: i16, // 246 - pub agility: i16, // 248 - pub wisdom: i16, // 250 - pub constitution: i16, // 252 - pub to_dodge: i16, // 254 - pub to_hit: i16, // 256 - pub offense: i16, // 258 - pub defense: i16, // 260 - pub magical_power: i16, // 262 + pub base_price: u32, // 236 + pub edit_item_id: u32, // 240 + pub health_points: i16, // 242 + pub mana_points: i16, // 244 + pub strength: i16, // 246 + pub agility: i16, // 248 + pub wisdom: i16, // 250 + pub constitution: i16, // 252 + pub to_dodge: i16, // 254 + pub to_hit: i16, // 256 + pub offense: i16, // 258 + pub defense: i16, // 260 + pub magical_power: i16, // 262 pub modification_cost: i16, // 264 /// Reserved byte; observed as zero and not used by the game. pub reserved_byte: u8, // 265 - pub modifies_item: u8, // 266 - pub additional_effect: i16, // 268 - pub map_coordinate_x: u32, // 272 - pub map_coordinate_y: u32, // 276 + pub modifies_item: u8, // 266 + pub additional_effect: i16, // 268 + pub map_coordinate_x: u32, // 272 + pub map_coordinate_y: u32, // 276 /// One-based encoded object ID used by the map's ground-item grid. pub ground_item_object_id: u16, /// Preserved bytes following the ground-item object ID. @@ -769,7 +769,7 @@ pub struct DrawItemHealItem { pub restore_full_health: u8, // 245 pub restore_full_mana: u8, // 246 pub poison_heal: u8, // 247 - pub cures_paralysis: u8, // 248 + pub cures_paralysis: u8, // 248 pub polimorph_heal: u8, // 249 /// Reserved trailer bytes; preserve them verbatim. pub reserved_trailer: [u8; 3], // 252 @@ -788,32 +788,32 @@ pub struct DrawItemWeaponItem { pub name: String, #[binary_record(string(encoding = "WINDOWS-1250", size = 202))] pub description: String, // 232 - pub base_price: u32, // 236 - pub weapon_item_id: u32, // 240 - pub health_points: i16, // 242 - pub mana_points: i16, // 244 - pub strength: i16, // 246 - pub agility: i16, // 248 - pub wisdom: i16, // 250 - pub constitution: i16, // 252 - pub to_dodge: i16, // 254 - pub to_hit: i16, // 256 - pub attack: i16, // 258 - pub defense: i16, // 260 - pub magical_strength: i16, // 262 - pub modification_budget: i16, // 264 - pub padding2: i16, // 266 - pub padding3: i16, // 268 - pub req_strength: i16, // 270 - pub padding4: i16, // 272 - pub req_agility: i16, // 274 - pub padding5: i16, // 276 - pub req_wisdom: i16, // 278 - pub padding6: i16, // 280 - pub padding7: i16, // 282 - pub padding8: i16, // 284 - pub map_coordinate_x: u32, // 288 - pub map_coordinate_y: u32, // 292 + pub base_price: u32, // 236 + pub weapon_item_id: u32, // 240 + pub health_points: i16, // 242 + pub mana_points: i16, // 244 + pub strength: i16, // 246 + pub agility: i16, // 248 + pub wisdom: i16, // 250 + pub constitution: i16, // 252 + pub to_dodge: i16, // 254 + pub to_hit: i16, // 256 + pub attack: i16, // 258 + pub defense: i16, // 260 + pub magical_strength: i16, // 262 + pub modification_budget: i16, // 264 + pub padding2: i16, // 266 + pub padding3: i16, // 268 + pub req_strength: i16, // 270 + pub padding4: i16, // 272 + pub req_agility: i16, // 274 + pub padding5: i16, // 276 + pub req_wisdom: i16, // 278 + pub padding6: i16, // 280 + pub padding7: i16, // 282 + pub padding8: i16, // 284 + pub map_coordinate_x: u32, // 288 + pub map_coordinate_y: u32, // 292 /// One-based encoded object ID used by the map's ground-item grid. pub ground_item_object_id: u16, /// Preserved bytes following the ground-item object ID. diff --git a/src/references/save_file/inventory.rs b/src/references/save_file/inventory.rs index 584a28a7..9c526efb 100644 --- a/src/references/save_file/inventory.rs +++ b/src/references/save_file/inventory.rs @@ -368,7 +368,7 @@ pub struct InventoryHealItem { pub restore_full_health: u8, // 245 pub restore_full_mana: u8, // 246 pub poison_heal: u8, // 247 - pub cures_paralysis: u8, // 248 + pub cures_paralysis: u8, // 248 pub polimorph_heal: u8, // 249 /// First byte of the item definition's reserved trailer; normally zero. pub reserved_definition_byte: u8, @@ -387,30 +387,30 @@ pub struct InventoryWeaponItem { pub name: String, #[binary_record(string(encoding = "WINDOWS-1250", size = 202))] pub description: String, // 232 - pub base_price: u32, // 236 - pub weapon_item_id: u32, // 240 - pub health_points: i16, // 242 - pub mana_points: i16, // 244 - pub strength: i16, // 246 - pub agility: i16, // 248 - pub wisdom: i16, // 250 - pub constitution: i16, // 252 - pub to_dodge: i16, // 254 - pub to_hit: i16, // 256 - pub attack: i16, // 258 - pub defense: i16, // 260 - pub magical_strength: i16, // 262 - pub modification_budget: i16, // 264 - pub padding2: i16, // 266 - pub padding3: i16, // 268 - pub req_strength: i16, // 270 - pub padding4: i16, // 272 - pub req_agility: i16, // 274 - pub padding5: i16, // 276 - pub req_wisdom: i16, // 278 - pub padding6: i16, // 280 - pub padding7: i16, // 282 - pub padding8: i16, // 284 + pub base_price: u32, // 236 + pub weapon_item_id: u32, // 240 + pub health_points: i16, // 242 + pub mana_points: i16, // 244 + pub strength: i16, // 246 + pub agility: i16, // 248 + pub wisdom: i16, // 250 + pub constitution: i16, // 252 + pub to_dodge: i16, // 254 + pub to_hit: i16, // 256 + pub attack: i16, // 258 + pub defense: i16, // 260 + pub magical_strength: i16, // 262 + pub modification_budget: i16, // 264 + pub padding2: i16, // 266 + pub padding3: i16, // 268 + pub req_strength: i16, // 270 + pub padding4: i16, // 272 + pub req_agility: i16, // 274 + pub padding5: i16, // 276 + pub req_wisdom: i16, // 278 + pub padding6: i16, // 280 + pub padding7: i16, // 282 + pub padding8: i16, // 284 /// Zero-based inventory category: `0`=weapon, `1`=heal, `2`=edit, `3`=misc, `4`=event. pub item_category: u32, /// Per-save item identity referenced by equipped slots and inventory placement cells. From 98a11e764060dcbdb14517f067c28bf7263ac59f Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:14:18 +0100 Subject: [PATCH 60/72] fix(core): Remove more aliases --- dispel-gui/src/editors/save_ifo/state.rs | 5 +- dispel-gui/src/tests/editor_field_edit.rs | 150 ---------------------- dispel-macros/src/record_patcher_impl.rs | 44 +------ src/map/mod.rs | 2 - src/map/reader.rs | 15 ++- src/modding/patchers/dialogue.rs | 10 +- src/modding/patchers/save_ifo.rs | 19 ++- src/references/enums.rs | 75 +++++++++-- src/references/magic_db.rs | 37 +----- src/references/save_file/game_tmp.rs | 3 - src/references/save_ifo/mod.rs | 19 --- src/references/save_ifo/swap.rs | 1 - 12 files changed, 100 insertions(+), 280 deletions(-) diff --git a/dispel-gui/src/editors/save_ifo/state.rs b/dispel-gui/src/editors/save_ifo/state.rs index 97634093..677c7f23 100644 --- a/dispel-gui/src/editors/save_ifo/state.rs +++ b/dispel-gui/src/editors/save_ifo/state.rs @@ -10,10 +10,9 @@ use crate::components::generic_editor::UndoRedo; use crate::components::loading_state::LoadingState; use dispel_core::{SaveIfo, SlotSummary}; -/// Read a stride index from either the current or the stored field path. +/// Read a stride index from the current field path. fn stride_index(path: &str) -> Option { path.strip_prefix("tail.journal_strides.") - .or_else(|| path.strip_prefix("tail.payload_counts.")) .and_then(|s| s.parse::().ok()) } @@ -286,7 +285,7 @@ mod tests { #[test] fn test_redo_reapplies_tail_field() { let mut editor = editor_with_data(); - editor.update_field("tail.payload_counts.0".into(), "350".into()); + editor.update_field("tail.journal_strides.0".into(), "350".into()); editor.undo(); editor.redo(); assert_eq!(editor.data.as_ref().unwrap().ifo.journal_strides[0], 350); diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index 2bf10a15..2127023b 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1009,156 +1009,6 @@ mod modified_flag_routing { } } -// ============================================================================ -// Renamed field labels and stored-key aliases -// ============================================================================ - -mod renamed_field_labels { - use crate::components::editable::{EditableRecordGenerated, FieldKind}; - - #[test] - fn test_magic_type_options_mark_elemental_schools_without_proficiency() { - let descriptor = MagicSpell::__editable_fields() - .iter() - .find(|field| field.name == "magic_type") - .expect("magic type must be exposed in the inspector"); - let FieldKind::Enum { variants } = &descriptor.kind else { - panic!("magic type must be an enum"); - }; - for school in ["Fire", "Water", "Earth", "Air"] { - let label = format!("{school} (no proficiency)"); - assert!(variants.contains(&label.as_str()), "missing option {label}"); - } - for school in ["Magic", "HolyMagic", "DarkMagic"] { - assert!(variants.contains(&school), "missing option {school}"); - } - } - - use dispel_core::{ - DialogueScript, EditItem, EditItemEffect, ExtraRef, Extractor, HealItem, MagicSpell, - Monster, MonsterIni, WeaponItem, - }; - - #[test] - fn test_monster_ini_sound_fields_have_sfx_labels() { - let descriptors = MonsterIni::__editable_fields(); - for (name, label) in [ - ("attack", "Approach SFX:"), - ("hit", "Attack SFX:"), - ("death", "Death SFX:"), - ("walking", "Post-strike SFX:"), - ("casting_magic", "Magic SFX:"), - ] { - let descriptor = descriptors - .iter() - .find(|field| field.name == name) - .expect("field must be exposed in the inspector"); - assert_eq!(descriptor.label, label, "label for {name}"); - } - } - - #[test] - fn test_edit_item_effect_health_leech_uses_new_name() { - let descriptor = EditItem::__editable_fields() - .iter() - .find(|field| field.name == "additional_effect") - .expect("the effect field must be exposed in the inspector"); - match &descriptor.kind { - FieldKind::Enum { variants } => { - assert!( - variants.contains(&"HealthLeech"), - "GUI option: {variants:?}" - ); - } - _ => panic!("the effect field must be an enum"), - } - - let wire = EditItemEffect::from_i16(2).unwrap(); - assert_eq!(serde_json::to_string(&wire).unwrap(), "\"HealthLeech\""); - let legacy: EditItemEffect = serde_json::from_str("\"ManaDrain\"").unwrap(); - assert_eq!(legacy.value(), 2); - assert_eq!( - EditItemEffect::from_name("HealthLeech").map(|effect| effect.value()), - Some(2) - ); - } - - #[test] - fn test_magic_requires_target_flag_accepts_old_names() { - let descriptor = MagicSpell::__editable_fields() - .iter() - .find(|field| field.name == "requires_target") - .expect("the targeting flag must be exposed in the inspector"); - assert_eq!(descriptor.label, "Requires Target:"); - - let mut cursor = std::io::Cursor::new(vec![0u8; 88]); - let spells = MagicSpell::parse(&mut cursor, 88).unwrap(); - let mut value = serde_json::to_value(&spells[0]).unwrap(); - let object = value.as_object_mut().unwrap(); - assert!(object.remove("requires_target").is_some()); - object.insert("enabled".to_string(), serde_json::json!("Disabled")); - let restored: MagicSpell = serde_json::from_value(value).unwrap(); - let value = serde_json::to_value(&restored).unwrap(); - assert_eq!( - value.get("requires_target").and_then(|v| v.as_str()), - Some("NotRequired") - ); - - let mut cursor = std::io::Cursor::new(vec![1u8, 0, 0, 0]); - cursor.get_mut().extend_from_slice(&[0u8; 84]); - let spells = MagicSpell::parse(&mut cursor, 88).unwrap(); - let mut value = serde_json::to_value(&spells[0]).unwrap(); - let object = value.as_object_mut().unwrap(); - object.remove("requires_target"); - object.insert("enabled".to_string(), serde_json::json!("Enabled")); - let restored: MagicSpell = serde_json::from_value(value).unwrap(); - let value = serde_json::to_value(&restored).unwrap(); - assert_eq!( - value.get("requires_target").and_then(|v| v.as_str()), - Some("Required") - ); - } - - #[test] - fn test_magic_range_label_describes_target_power_cap() { - let descriptor = MagicSpell::__editable_fields() - .iter() - .find(|field| field.name == "range") - .expect("range stays an editable field"); - assert_eq!(descriptor.label, "Max Target Magic Power:"); - } - - #[test] - fn test_magic_animation_cycles_is_an_integer_field() { - let descriptor = MagicSpell::__editable_fields() - .iter() - .find(|field| field.name == "target_animation_cycles") - .expect("the animation cycle count must be exposed in the inspector"); - assert_eq!(descriptor.label, "Target FX Cycles:"); - assert!( - matches!(descriptor.kind, FieldKind::Integer), - "the cycle count is a number, not a pick list" - ); - - let mut bytes = vec![0u8; 88]; - bytes[84..88].copy_from_slice(&7u32.to_le_bytes()); - let mut cursor = std::io::Cursor::new(&bytes); - let spells = MagicSpell::parse(&mut cursor, bytes.len() as u64).unwrap(); - let mut value = serde_json::to_value(&spells[0]).unwrap(); - let object = value.as_object_mut().unwrap(); - assert!(object.remove("target_animation_cycles").is_some()); - object.insert("targeting_mode".to_string(), serde_json::json!(7)); - let restored: MagicSpell = serde_json::from_value(value).unwrap(); - assert_eq!( - serde_json::to_value(&restored) - .unwrap() - .get("target_animation_cycles") - .and_then(|v| v.as_u64()), - Some(7) - ); - } -} - // ============================================================================ // Structural edits must mark the tab dirty // ============================================================================ diff --git a/dispel-macros/src/record_patcher_impl.rs b/dispel-macros/src/record_patcher_impl.rs index a8c3e918..139ed784 100644 --- a/dispel-macros/src/record_patcher_impl.rs +++ b/dispel-macros/src/record_patcher_impl.rs @@ -1,9 +1,7 @@ -use std::collections::HashMap; - use proc_macro2::Span; use proc_macro2::TokenStream as TokenStream2; use quote::quote; -use syn::{DeriveInput, Ident, LitStr}; +use syn::{DeriveInput, Ident}; use crate::schema::{CodegenConfig, FieldInfo, PatcherKey, RecordSchema}; @@ -11,37 +9,6 @@ pub fn expand(input: DeriveInput) -> TokenStream2 { codegen(&input, &CodegenConfig::default()) } -/// Read `#[patcher(field_alias = "old_name")]` from record fields. The alias -/// keeps an existing patcher key working when a field is renamed. -fn field_aliases(input: &DeriveInput) -> HashMap> { - let mut aliases = HashMap::new(); - let syn::Data::Struct(data) = &input.data else { - return aliases; - }; - for field in &data.fields { - let Some(ident) = field.ident.as_ref() else { - continue; - }; - for attr in &field.attrs { - if !attr.path().is_ident("patcher") { - continue; - } - let _ = attr.parse_nested_meta(|meta| { - if meta.path.is_ident("field_alias") { - let value = meta.value()?; - let lit: LitStr = value.parse()?; - aliases - .entry(ident.to_string()) - .or_insert_with(Vec::new) - .push(lit.value()); - } - Ok(()) - }); - } - } - aliases -} - /// Generate the `RecordPatcher` impl from the shared record schema. pub(crate) fn codegen(input: &DeriveInput, config: &CodegenConfig) -> TokenStream2 { let name = &input.ident; @@ -86,14 +53,12 @@ pub(crate) fn codegen(input: &DeriveInput, config: &CodegenConfig) -> TokenStrea // The field grammar comes from the one shared schema parser; the patch // arms below are just another codegen path over that AST. let schema = RecordSchema::parse(input); - let aliases = field_aliases(input); let mut field_arms: Vec = Vec::new(); for info in &schema.fields { let Some(ident) = info.ident() else { continue }; let field_name = ident.to_string(); - let alias_list: &[String] = aliases.get(&field_name).map(Vec::as_slice).unwrap_or(&[]); - let pattern = quote! { #field_name #(| #alias_list)* }; + let pattern = quote! { #field_name }; let arm = match info { FieldInfo::Id { .. } | FieldInfo::Index { .. } => quote! { #pattern => { @@ -366,7 +331,7 @@ mod tests { } #[test] - fn test_generated_patcher_keeps_field_alias_key() { + fn test_generated_patcher_keeps_only_current_field_key() { let input: DeriveInput = parse_quote! { #[extractor(property_item_size = 4)] #[patcher(filename = "Sample.db")] @@ -377,7 +342,8 @@ mod tests { } }; let tokens = codegen(&input, &CodegenConfig::default()).to_string(); - assert!(tokens.contains("\"value\" | \"old_value\" =>"), "{tokens}"); + assert!(tokens.contains("\"value\" =>"), "{tokens}"); + assert!(!tokens.contains("old_value"), "{tokens}"); } #[test] diff --git a/src/map/mod.rs b/src/map/mod.rs index 833a891f..095aa8d5 100644 --- a/src/map/mod.rs +++ b/src/map/mod.rs @@ -189,9 +189,7 @@ impl<'de> Deserialize<'de> for RoofBlitMode { /// One overlay-table entry: a roof blit mode and the shadow-on flag. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] pub struct OverlayMode { - #[serde(alias = "transparency_mode")] pub blit_mode: RoofBlitMode, - #[serde(alias = "draw_enable")] pub shadow_on: u8, } diff --git a/src/map/reader.rs b/src/map/reader.rs index 9c70f8ca..0dd5f61e 100644 --- a/src/map/reader.rs +++ b/src/map/reader.rs @@ -610,10 +610,17 @@ mod tests { assert_eq!(second.blit_mode, RoofBlitMode::SkipBlack); assert_eq!(second.shadow_on, 0); - let legacy: OverlayMode = - serde_json::from_str(r#"{"transparency_mode":2,"draw_enable":1}"#).unwrap(); - assert_eq!(legacy.blit_mode, RoofBlitMode::SkipBlack); - assert_eq!(legacy.shadow_on, 1); + let legacy = + serde_json::from_str::(r#"{"transparency_mode":2,"draw_enable":1}"#); + assert!( + legacy.is_err(), + "legacy overlay keys must no longer be accepted" + ); + + let current: OverlayMode = + serde_json::from_str(r#"{"blit_mode":2,"shadow_on":1}"#).unwrap(); + assert_eq!(current.blit_mode, RoofBlitMode::SkipBlack); + assert_eq!(current.shadow_on, 1); } #[test] diff --git a/src/modding/patchers/dialogue.rs b/src/modding/patchers/dialogue.rs index 8c95fda4..b3fc50de 100644 --- a/src/modding/patchers/dialogue.rs +++ b/src/modding/patchers/dialogue.rs @@ -149,7 +149,7 @@ impl RecordPatcher for DialogueParagraphPatcher { Value::String(s) => rec.comment = s.clone(), _ => return Err(wrong_type(Self::RECORD_NAME, field, "string", new)), }, - "next_page_id" | "param1" => rec.next_page_id = parse_i32(field, new)?, + "next_page_id" => rec.next_page_id = parse_i32(field, new)?, "wave_ini_entry_id" => rec.wave_ini_entry_id = parse_i32(field, new)?, other => return Err(unknown_field(Self::RECORD_NAME, other)), } @@ -272,12 +272,12 @@ mod tests { } #[test] - fn pgp_param1_key_still_sets_next_page_id() { + fn pgp_param1_key_is_no_longer_accepted() { let p = DialogueParagraphPatcher; - let out = p + let err = p .apply_field(&pgp_blob(), 1, "param1", &Value::I64(17)) - .expect("the stored patcher key must still be accepted"); - assert_eq!(parse_paras(&out)[1].next_page_id, 17); + .expect_err("the stored patcher key must now be rejected"); + assert!(format!("{err}").contains("param1"), "{err}"); } #[test] diff --git a/src/modding/patchers/save_ifo.rs b/src/modding/patchers/save_ifo.rs index 8b5575c1..741f7b2f 100644 --- a/src/modding/patchers/save_ifo.rs +++ b/src/modding/patchers/save_ifo.rs @@ -57,11 +57,10 @@ impl RecordPatcher for SaveIfoPatcher { } } -/// Read a stride index from either the current or the stored field path. +/// Read a stride index from the current field path. fn stride_index(field: &str) -> Option { field .strip_prefix("tail.journal_strides.") - .or_else(|| field.strip_prefix("tail.payload_counts.")) .and_then(|s| s.parse::().ok()) } @@ -124,11 +123,23 @@ mod tests { let ifo = SaveIfo::parse(&patched).unwrap(); assert!((ifo.game_version - 1.5).abs() < f32::EPSILON); - let patched = apply(&original, "tail.payload_counts.2", Value::I64(42)); + let patched = apply(&original, "tail.journal_strides.2", Value::I64(42)); let ifo = SaveIfo::parse(&patched).unwrap(); assert_eq!(ifo.journal_strides, [329, 349, 42, 200]); } + #[test] + fn rejects_legacy_payload_counts_path() { + let bytes = sample_bytes(); + // Index 2 is valid under the current name; the legacy prefix must be + // rejected rather than silently accepted. + assert!( + SaveIfoPatcher + .apply_field(&bytes, 0, "tail.payload_counts.2", &Value::I64(42)) + .is_err() + ); + } + #[test] fn rejects_unknown_fields_and_bad_ids() { let bytes = sample_bytes(); @@ -144,7 +155,7 @@ mod tests { ); assert!( SaveIfoPatcher - .apply_field(&bytes, 0, "tail.payload_counts.9", &Value::I64(1)) + .apply_field(&bytes, 0, "tail.journal_strides.9", &Value::I64(1)) .is_err() ); assert!( diff --git a/src/references/enums.rs b/src/references/enums.rs index 00406322..18b5fd6b 100644 --- a/src/references/enums.rs +++ b/src/references/enums.rs @@ -546,7 +546,6 @@ pub enum EditItemEffect { /// Fire effect Fire = 1, /// Health leech effect - #[serde(alias = "ManaDrain")] HealthLeech = 2, } @@ -571,9 +570,7 @@ impl EditItemEffect { match name { "None" => Some(EditItemEffect::None), "Fire" => Some(EditItemEffect::Fire), - "HealthLeech" | "Health Leech" | "ManaDrain" | "Mana Drain" => { - Some(EditItemEffect::HealthLeech) - } + "HealthLeech" => Some(EditItemEffect::HealthLeech), _ => None, } } @@ -1232,9 +1229,7 @@ impl HealItemFlag { pub fn from_name(name: &str) -> Option { match name { "None" => Some(HealItemFlag::None), - "Active" | "Enabled" | "FullRestoration" | "Full Restoration" => { - Some(HealItemFlag::Active) - } + "Active" => Some(HealItemFlag::Active), _ => None, } } @@ -1380,9 +1375,9 @@ impl SpellTargetType { pub fn from_name(name: &str) -> Option { match name { "Single" => Some(SpellTargetType::Single), - "SelfTarget" | "Self" => Some(SpellTargetType::SelfTarget), - "AreaOfEffect" | "Area Of Effect" => Some(SpellTargetType::AreaOfEffect), - "MultiTarget" | "Multi Target" => Some(SpellTargetType::MultiTarget), + "SelfTarget" => Some(SpellTargetType::SelfTarget), + "AreaOfEffect" => Some(SpellTargetType::AreaOfEffect), + "MultiTarget" => Some(SpellTargetType::MultiTarget), _ => None, } } @@ -1408,10 +1403,8 @@ impl From for u32 { pub enum TargetSelectionFlag { /// The spell does not pick a target. #[default] - #[serde(alias = "Disabled")] NotRequired = 0, /// The spell picks a target. - #[serde(alias = "Enabled")] Required = 1, } @@ -1433,8 +1426,8 @@ impl TargetSelectionFlag { /// Convert from display name pub fn from_name(name: &str) -> Option { match name { - "NotRequired" | "Disabled" => Some(TargetSelectionFlag::NotRequired), - "Required" | "Enabled" => Some(TargetSelectionFlag::Required), + "NotRequired" => Some(TargetSelectionFlag::NotRequired), + "Required" => Some(TargetSelectionFlag::Required), _ => None, } } @@ -1988,6 +1981,60 @@ mod tests { ); } + #[test] + fn test_removed_name_aliases_are_no_longer_accepted() { + assert_eq!( + EditItemEffect::from_name("HealthLeech"), + Some(EditItemEffect::HealthLeech) + ); + for old in ["Health Leech", "ManaDrain", "Mana Drain"] { + assert_eq!(EditItemEffect::from_name(old), None, "old name {old}"); + } + + assert_eq!( + HealItemFlag::from_name("Active"), + Some(HealItemFlag::Active) + ); + for old in ["Enabled", "FullRestoration", "Full Restoration"] { + assert_eq!(HealItemFlag::from_name(old), None, "old name {old}"); + } + + assert_eq!( + SpellTargetType::from_name("SelfTarget"), + Some(SpellTargetType::SelfTarget) + ); + assert_eq!( + SpellTargetType::from_name("AreaOfEffect"), + Some(SpellTargetType::AreaOfEffect) + ); + assert_eq!( + SpellTargetType::from_name("MultiTarget"), + Some(SpellTargetType::MultiTarget) + ); + for old in ["Self", "Area Of Effect", "Multi Target"] { + assert_eq!(SpellTargetType::from_name(old), None, "old name {old}"); + } + + assert_eq!( + TargetSelectionFlag::from_name("NotRequired"), + Some(TargetSelectionFlag::NotRequired) + ); + assert_eq!( + TargetSelectionFlag::from_name("Required"), + Some(TargetSelectionFlag::Required) + ); + for old in ["Disabled", "Enabled"] { + assert_eq!(TargetSelectionFlag::from_name(old), None, "old name {old}"); + } + } + + #[test] + fn test_removed_serde_enum_aliases_are_no_longer_accepted() { + assert!(serde_json::from_str::("\"ManaDrain\"").is_err()); + assert!(serde_json::from_str::("\"Disabled\"").is_err()); + assert!(serde_json::from_str::("\"Enabled\"").is_err()); + } + #[test] fn test_magic_spell_constant_conversion() { assert_eq!( diff --git a/src/references/magic_db.rs b/src/references/magic_db.rs index 9c0d4132..7d413661 100644 --- a/src/references/magic_db.rs +++ b/src/references/magic_db.rs @@ -80,8 +80,6 @@ pub struct MagicSpell { /// Whether casting the spell requires a target. #[extractor(enum_from_u32(type = "TargetSelectionFlag"))] - #[serde(alias = "enabled")] - #[patcher(field_alias = "enabled")] pub requires_target: TargetSelectionFlag, /// Selects blended rendering (`1`) rather than direct blitting (`0`) for @@ -172,8 +170,6 @@ pub struct MagicSpell { /// Number of times the stationary target animation cycles. #[extractor(primitive(type = "u32"))] - #[serde(alias = "targeting_mode")] - #[patcher(field_alias = "targeting_mode")] pub target_animation_cycles: u32, } @@ -236,7 +232,7 @@ mod tests { fn spell_bytes(base_damage: u32, mana_cost: u32, target_animation_cycles: u32) -> Vec { let fields: [u32; 22] = [ - 1, // enabled + 1, // requires_target 1, // effect_visual_blends_with_background base_damage, 100, // base_success_rate @@ -262,37 +258,6 @@ mod tests { fields.iter().flat_map(|&v| v.to_le_bytes()).collect() } - #[test] - fn test_legacy_patcher_key_sets_requires_target() { - use crate::modding::patcher::RecordPatcher; - use crate::modding::value::Value; - - let data = spell_bytes(20, 50, 1); - let out = MagicSpellPatcher - .apply_field(&data, 0, "enabled", &Value::I64(1)) - .expect("the stored patcher key must still be accepted"); - let mut cursor = Cursor::new(&out[..]); - let spells = MagicSpell::parse(&mut cursor, out.len() as u64).unwrap(); - assert_eq!( - spells[0].requires_target, - crate::references::enums::TargetSelectionFlag::Required - ); - } - - #[test] - fn test_legacy_patcher_key_sets_animation_cycles() { - use crate::modding::patcher::RecordPatcher; - use crate::modding::value::Value; - - let data = spell_bytes(20, 50, 1); - let out = MagicSpellPatcher - .apply_field(&data, 0, "targeting_mode", &Value::I64(7)) - .expect("the stored patcher key must still be accepted"); - let mut cursor = Cursor::new(&out[..]); - let spells = MagicSpell::parse(&mut cursor, out.len() as u64).unwrap(); - assert_eq!(spells[0].target_animation_cycles, 7); - } - #[test] fn parse_single_spell() { let data = spell_bytes(20, 50, 1); diff --git a/src/references/save_file/game_tmp.rs b/src/references/save_file/game_tmp.rs index 42c96362..aca314a5 100644 --- a/src/references/save_file/game_tmp.rs +++ b/src/references/save_file/game_tmp.rs @@ -330,7 +330,6 @@ pub struct MonsterRecord { /// Screen-space Y offset while moving between cells. pub cell_offset_y: u8, /// This entity's own id. - #[serde(alias = "spawn_group_id")] pub own_entity_id: u16, /// Constructor-initialized to `0xff`. pub constructor_marker: u8, @@ -355,7 +354,6 @@ pub struct MonsterRecord { /// Current frame of the ground-effect animation. pub ground_effect_animation_frame: u32, /// Selected spell id; `-1` means none. - #[serde(alias = "ground_effect_handle")] pub selected_spell_id: i32, /// Number of entries in the movement path buffer. pub path_buffer_length: u32, @@ -413,7 +411,6 @@ pub struct MonsterRecord { /// Remaining ticks for the timed overlay. pub timed_overlay_ticks_remaining: u32, /// Throttle countdown before the next flee check. - #[serde(alias = "ai_tick_counter")] pub flee_throttle: u32, /// Backup of `detection_sight_size`. pub sight_backup: u8, diff --git a/src/references/save_ifo/mod.rs b/src/references/save_ifo/mod.rs index 32c7b05b..03eb7271 100644 --- a/src/references/save_ifo/mod.rs +++ b/src/references/save_ifo/mod.rs @@ -30,7 +30,6 @@ pub struct SaveIfo { /// Reserved word; observed zero in all known files. pub reserved: u32, /// Per-journal record strides used when traversing `game.tmp`. - #[serde(alias = "payload_counts")] pub journal_strides: [u32; 4], } @@ -180,21 +179,3 @@ impl Extractor for SaveIfo { records[0].write_to(writer) } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_old_payload_counts_key_resolves() { - let mut value = serde_json::to_value(SaveIfo::default()).unwrap(); - let object = value.as_object_mut().unwrap(); - assert!(object.remove("journal_strides").is_some()); - object.insert( - "payload_counts".to_string(), - serde_json::json!([11, 22, 33, 44]), - ); - let ifo: SaveIfo = serde_json::from_value(value).unwrap(); - assert_eq!(ifo.journal_strides, [11, 22, 33, 44]); - } -} diff --git a/src/references/save_ifo/swap.rs b/src/references/save_ifo/swap.rs index 7fe129f9..8fd6898a 100644 --- a/src/references/save_ifo/swap.rs +++ b/src/references/save_ifo/swap.rs @@ -22,7 +22,6 @@ pub struct SavTail { pub game_tmp_key: u32, pub map_id: u32, pub reserved: u32, - #[serde(alias = "payload_counts")] pub journal_strides: [u32; 4], } From 162452f13c822493fdfdb2a943d76e5846c6df30 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:23:44 +0100 Subject: [PATCH 61/72] refactor: remove legacy field and name aliases --- dispel-gui/src/app.rs | 6 ++-- .../src/editors/save_file_viewer/state.rs | 12 ++------ .../editors/save_file_viewer/update/mod.rs | 2 +- dispel-gui/src/tests/editor_field_edit.rs | 28 +++++++++++++++++++ dispel-macros/src/record_patcher_impl.rs | 4 +-- src/map/reader.rs | 7 ----- src/modding/patchers/dialogue.rs | 9 ------ src/modding/patchers/save_ifo.rs | 12 -------- src/references/enums.rs | 24 +--------------- src/references/magic_db.rs | 24 ++++++++++++++++ src/references/save_ifo/mod.rs | 17 +++++++++++ 11 files changed, 79 insertions(+), 66 deletions(-) diff --git a/dispel-gui/src/app.rs b/dispel-gui/src/app.rs index 11633390..c7f80073 100644 --- a/dispel-gui/src/app.rs +++ b/dispel-gui/src/app.rs @@ -149,8 +149,10 @@ impl App { #[cfg(test)] pub fn test_app() -> Self { let root = tempfile::tempdir().expect("temp dir"); - let mut state = AppState::default(); - state.paths = crate::paths::AppPaths::test_paths(root.path()); + let state = AppState { + paths: crate::paths::AppPaths::test_paths(root.path()), + ..AppState::default() + }; let (mut app, _) = Self::boot(state); app._test_root = Some(root); app diff --git a/dispel-gui/src/editors/save_file_viewer/state.rs b/dispel-gui/src/editors/save_file_viewer/state.rs index 175131ff..bd69b8a8 100644 --- a/dispel-gui/src/editors/save_file_viewer/state.rs +++ b/dispel-gui/src/editors/save_file_viewer/state.rs @@ -1128,18 +1128,12 @@ mod tests { for header in ["own_entity_id", "selected_spell_id", "flee_throttle"] { assert!(headers.contains(&header), "missing column {header}"); } - for stale in ["spawn_group_id", "ground_effect_handle", "ai_tick_counter"] { - assert!(!headers.contains(&stale), "stale column {stale}"); - } let mut value = serde_json::to_value(MonsterRecord::default()).unwrap(); let object = value.as_object_mut().unwrap(); - assert!(object.remove("own_entity_id").is_some()); - assert!(object.remove("selected_spell_id").is_some()); - assert!(object.remove("flee_throttle").is_some()); - object.insert("spawn_group_id".to_string(), serde_json::json!(7)); - object.insert("ground_effect_handle".to_string(), serde_json::json!(11)); - object.insert("ai_tick_counter".to_string(), serde_json::json!(13)); + object.insert("own_entity_id".to_string(), serde_json::json!(7)); + object.insert("selected_spell_id".to_string(), serde_json::json!(11)); + object.insert("flee_throttle".to_string(), serde_json::json!(13)); let restored: MonsterRecord = serde_json::from_value(value).unwrap(); assert_eq!(restored.own_entity_id, 7); assert_eq!(restored.selected_spell_id, 11); diff --git a/dispel-gui/src/editors/save_file_viewer/update/mod.rs b/dispel-gui/src/editors/save_file_viewer/update/mod.rs index d8bc4ceb..00b65628 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/mod.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/mod.rs @@ -1656,7 +1656,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { d.restore_full_health.to_string(), d.restore_full_mana.to_string(), d.poison_heal.to_string(), - d.petrif_heal.to_string(), + d.cures_paralysis.to_string(), d.polimorph_heal.to_string(), hex_bytes(&d.reserved_trailer), d.map_coordinate_x.to_string(), diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index 2127023b..1cb04bdf 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1009,6 +1009,34 @@ mod modified_flag_routing { } } +// ============================================================================ +// Renamed field labels and current stored keys +// ============================================================================ + +mod renamed_field_labels { + use crate::components::editable::{EditableRecordGenerated, FieldKind}; + + #[test] + fn test_magic_type_options_mark_elemental_schools_without_proficiency() { + let descriptor = MagicSpell::__editable_fields() + .iter() + .find(|field| field.name == "magic_type") + .expect("magic type must be exposed in the inspector"); + let FieldKind::Enum { variants } = &descriptor.kind else { + panic!("magic type must be an enum"); + }; + for school in ["Fire", "Water", "Earth", "Air"] { + let label = format!("{school} (no proficiency)"); + assert!(variants.contains(&label.as_str()), "missing option {label}"); + } + for school in ["Magic", "HolyMagic", "DarkMagic"] { + assert!(variants.contains(&school), "missing option {school}"); + } + } + + use dispel_core::{EditItem, EditItemEffect, Extractor, MagicSpell, MonsterIni}; +} + // ============================================================================ // Structural edits must mark the tab dirty // ============================================================================ diff --git a/dispel-macros/src/record_patcher_impl.rs b/dispel-macros/src/record_patcher_impl.rs index 139ed784..cdf5e4bd 100644 --- a/dispel-macros/src/record_patcher_impl.rs +++ b/dispel-macros/src/record_patcher_impl.rs @@ -331,19 +331,17 @@ mod tests { } #[test] - fn test_generated_patcher_keeps_only_current_field_key() { + fn test_generated_patcher_uses_current_field_key() { let input: DeriveInput = parse_quote! { #[extractor(property_item_size = 4)] #[patcher(filename = "Sample.db")] struct Sample { #[extractor(primitive(type = "i32"))] - #[patcher(field_alias = "old_value")] value: i32, } }; let tokens = codegen(&input, &CodegenConfig::default()).to_string(); assert!(tokens.contains("\"value\" =>"), "{tokens}"); - assert!(!tokens.contains("old_value"), "{tokens}"); } #[test] diff --git a/src/map/reader.rs b/src/map/reader.rs index 0dd5f61e..99cc44be 100644 --- a/src/map/reader.rs +++ b/src/map/reader.rs @@ -610,13 +610,6 @@ mod tests { assert_eq!(second.blit_mode, RoofBlitMode::SkipBlack); assert_eq!(second.shadow_on, 0); - let legacy = - serde_json::from_str::(r#"{"transparency_mode":2,"draw_enable":1}"#); - assert!( - legacy.is_err(), - "legacy overlay keys must no longer be accepted" - ); - let current: OverlayMode = serde_json::from_str(r#"{"blit_mode":2,"shadow_on":1}"#).unwrap(); assert_eq!(current.blit_mode, RoofBlitMode::SkipBlack); diff --git a/src/modding/patchers/dialogue.rs b/src/modding/patchers/dialogue.rs index b3fc50de..615222e5 100644 --- a/src/modding/patchers/dialogue.rs +++ b/src/modding/patchers/dialogue.rs @@ -271,15 +271,6 @@ mod tests { assert_eq!(parse_paras(&out)[0].next_page_id, 27); } - #[test] - fn pgp_param1_key_is_no_longer_accepted() { - let p = DialogueParagraphPatcher; - let err = p - .apply_field(&pgp_blob(), 1, "param1", &Value::I64(17)) - .expect_err("the stored patcher key must now be rejected"); - assert!(format!("{err}").contains("param1"), "{err}"); - } - #[test] fn pgp_change_text() { let p = DialogueParagraphPatcher; diff --git a/src/modding/patchers/save_ifo.rs b/src/modding/patchers/save_ifo.rs index 741f7b2f..44b5acda 100644 --- a/src/modding/patchers/save_ifo.rs +++ b/src/modding/patchers/save_ifo.rs @@ -128,18 +128,6 @@ mod tests { assert_eq!(ifo.journal_strides, [329, 349, 42, 200]); } - #[test] - fn rejects_legacy_payload_counts_path() { - let bytes = sample_bytes(); - // Index 2 is valid under the current name; the legacy prefix must be - // rejected rather than silently accepted. - assert!( - SaveIfoPatcher - .apply_field(&bytes, 0, "tail.payload_counts.2", &Value::I64(42)) - .is_err() - ); - } - #[test] fn rejects_unknown_fields_and_bad_ids() { let bytes = sample_bytes(); diff --git a/src/references/enums.rs b/src/references/enums.rs index 18b5fd6b..1565bfdf 100644 --- a/src/references/enums.rs +++ b/src/references/enums.rs @@ -1982,23 +1982,15 @@ mod tests { } #[test] - fn test_removed_name_aliases_are_no_longer_accepted() { + fn test_enum_from_name_accepts_current_names() { assert_eq!( EditItemEffect::from_name("HealthLeech"), Some(EditItemEffect::HealthLeech) ); - for old in ["Health Leech", "ManaDrain", "Mana Drain"] { - assert_eq!(EditItemEffect::from_name(old), None, "old name {old}"); - } - assert_eq!( HealItemFlag::from_name("Active"), Some(HealItemFlag::Active) ); - for old in ["Enabled", "FullRestoration", "Full Restoration"] { - assert_eq!(HealItemFlag::from_name(old), None, "old name {old}"); - } - assert_eq!( SpellTargetType::from_name("SelfTarget"), Some(SpellTargetType::SelfTarget) @@ -2011,10 +2003,6 @@ mod tests { SpellTargetType::from_name("MultiTarget"), Some(SpellTargetType::MultiTarget) ); - for old in ["Self", "Area Of Effect", "Multi Target"] { - assert_eq!(SpellTargetType::from_name(old), None, "old name {old}"); - } - assert_eq!( TargetSelectionFlag::from_name("NotRequired"), Some(TargetSelectionFlag::NotRequired) @@ -2023,16 +2011,6 @@ mod tests { TargetSelectionFlag::from_name("Required"), Some(TargetSelectionFlag::Required) ); - for old in ["Disabled", "Enabled"] { - assert_eq!(TargetSelectionFlag::from_name(old), None, "old name {old}"); - } - } - - #[test] - fn test_removed_serde_enum_aliases_are_no_longer_accepted() { - assert!(serde_json::from_str::("\"ManaDrain\"").is_err()); - assert!(serde_json::from_str::("\"Disabled\"").is_err()); - assert!(serde_json::from_str::("\"Enabled\"").is_err()); } #[test] diff --git a/src/references/magic_db.rs b/src/references/magic_db.rs index 7d413661..b0dedb1d 100644 --- a/src/references/magic_db.rs +++ b/src/references/magic_db.rs @@ -258,6 +258,30 @@ mod tests { fields.iter().flat_map(|&v| v.to_le_bytes()).collect() } + #[test] + fn test_current_patcher_keys_set_renamed_fields() { + use crate::modding::patcher::RecordPatcher; + use crate::modding::value::Value; + + let data = spell_bytes(20, 50, 1); + let out = MagicSpellPatcher + .apply_field(&data, 0, "requires_target", &Value::I64(0)) + .expect("the current patcher key must be accepted"); + let mut cursor = Cursor::new(&out[..]); + let spells = MagicSpell::parse(&mut cursor, out.len() as u64).unwrap(); + assert_eq!( + spells[0].requires_target, + crate::references::enums::TargetSelectionFlag::NotRequired + ); + + let out = MagicSpellPatcher + .apply_field(&data, 0, "target_animation_cycles", &Value::I64(7)) + .expect("the current patcher key must be accepted"); + let mut cursor = Cursor::new(&out[..]); + let spells = MagicSpell::parse(&mut cursor, out.len() as u64).unwrap(); + assert_eq!(spells[0].target_animation_cycles, 7); + } + #[test] fn parse_single_spell() { let data = spell_bytes(20, 50, 1); diff --git a/src/references/save_ifo/mod.rs b/src/references/save_ifo/mod.rs index 03eb7271..2360d265 100644 --- a/src/references/save_ifo/mod.rs +++ b/src/references/save_ifo/mod.rs @@ -179,3 +179,20 @@ impl Extractor for SaveIfo { records[0].write_to(writer) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_journal_strides_key_deserializes() { + let mut value = serde_json::to_value(SaveIfo::default()).unwrap(); + let object = value.as_object_mut().unwrap(); + object.insert( + "journal_strides".to_string(), + serde_json::json!([11, 22, 33, 44]), + ); + let ifo: SaveIfo = serde_json::from_value(value).unwrap(); + assert_eq!(ifo.journal_strides, [11, 22, 33, 44]); + } +} From db17e552e3b084b8fe85b6f3d7894da5a21b109d Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:32:46 +0100 Subject: [PATCH 62/72] docs: drop conflicting save version values --- docs/files/Save.ifo.md | 2 +- docs/files/SaveFile.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/files/Save.ifo.md b/docs/files/Save.ifo.md index eb55edeb..b98fdff6 100644 --- a/docs/files/Save.ifo.md +++ b/docs/files/Save.ifo.md @@ -25,7 +25,7 @@ | Off | Type | Meaning | |-----|------|-----------------------------------------------------------------------------------------------| -| 192 | f32 | game version — written as 1.4 before every save | +| 192 | f32 | game version value stored in the slot tail | | 196 | u32 | `game.tmp` journal key identifying the current session's payload | | 200 | u32 | map/world id active at save time | | 204 | u32 | reserved; zero in known files | diff --git a/docs/files/SaveFile.md b/docs/files/SaveFile.md index 43e2fbdc..23658024 100644 --- a/docs/files/SaveFile.md +++ b/docs/files/SaveFile.md @@ -94,7 +94,7 @@ The section holds save-world header values and a list of visited map IDs: | Field | Type | Description | |--------------------------------|------------|--------------------------------------------------------------------------------------------------| | `map_section_terminator` | `u32` | Terminator after the final map section (known saves store zero) | -| `game_version` | `f32` | Save-format version (observed as 1.45) | +| `game_version` | `f32` | Game version value stored in the save header | | `all_map_ini_id` | `u32` | `AllMap.ini.id` for the loaded map's files, geometry, name, dialogue, and lighting | | `ref_map_ini_id` | `u32` | `Ref/Map.ini.id` for the entrance configuration, including spawn coordinates and placement files | | `reserved_header_word` | `u32` | Reserved header word (observed as zero) | @@ -318,7 +318,7 @@ The tool writes milestone records at walk animation milestones. These occur when | `id` | `u32` | Descending countdown kind: `400`, or `10`/`100`/`200`/`300` while the walk freshness countdown is active | | `direction` | `u32` | Walk direction (animation-step direction, 0-7) | | `state` | `u32` | Character state byte (`1` while walking) | -| `walk_type` | `u32` | Walk-type flag: `0` in save-format version 1.45 (which duplicates `direction` here); `1` by default | +| `walk_type` | `u32` | Walk-type flag: observed as `0`, duplicating `direction` here; `1` by default | | `x` | `u32` | X coordinate | | `y` | `u32` | Y coordinate | @@ -329,7 +329,7 @@ The tool writes milestone records at walk animation milestones. These occur when | `id` | `u32` | Countdown kind: `2000` for a completed walk cycle | | `direction` | `u32` | Normalized walk direction (0-3; walk directions 4-7 map to 0-3) | | `diagonal` | `u32` | Diagonal flag (`1` for diagonal walk directions) | -| `character_index` | `u32` | Character index (`0` for party members in save-format version 1.45; `0`-`2` by default) | +| `character_index` | `u32` | Character index (`0` for party members; `0`-`2` by default) | | `x` | `u32` | X coordinate | | `y` | `u32` | Y coordinate | From fea53b2ff797c6bad09b83d7cae799d6925aae81 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:39:33 +0100 Subject: [PATCH 63/72] fix(core): read full sprite frame header into named fields --- .../src/editors/sprite_editor/update.rs | 6 +- dispel-gui/src/tests/sprite_viewer.rs | 6 +- docs/files/Sprites.spr.md | 11 +- src/database/tests.rs | 10 +- src/map/render.rs | 1 + src/sprite.rs | 149 ++++++++++++++++-- 6 files changed, 157 insertions(+), 26 deletions(-) diff --git a/dispel-gui/src/editors/sprite_editor/update.rs b/dispel-gui/src/editors/sprite_editor/update.rs index 22ec17f8..2254f868 100644 --- a/dispel-gui/src/editors/sprite_editor/update.rs +++ b/dispel-gui/src/editors/sprite_editor/update.rs @@ -5,7 +5,7 @@ use crate::editors::sprite_editor::{ ExportDialogState, ExportFormat, ExportStatus, SpriteViewerMessage, }; use dispel_core::sprite::{ - SpriteFrameData, SpritePixelFormat, rgba_to_rgb16_bytes, write_sprite_to_path, + FrameHeader, SpriteFrameData, SpritePixelFormat, rgba_to_rgb16_bytes, write_sprite_to_path, }; use iced::Task; @@ -168,7 +168,7 @@ pub fn handle(message: SpriteViewerMessage, app: &mut App) -> Task Task = [11, 22, 33] .into_iter() .map(|height| ImageInfo { + header: crate::sprite::FrameHeader::default(), origin_x: 0, origin_y: 0, width: 1, diff --git a/src/sprite.rs b/src/sprite.rs index 7d39f707..1c0217ec 100644 --- a/src/sprite.rs +++ b/src/sprite.rs @@ -45,6 +45,56 @@ use std::{fs::File, path::Path}; // Types // =========================================================================== +/// Named fields from the 24 bytes that precede a frame's width words. +/// +/// The structure stores a screen-space rectangle as left, top, right and bottom +/// edges, then two frame offset dwords. The right edge is the left edge plus +/// the frame width; the bottom edge is the top edge plus the frame height. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct FrameHeader { + /// Left edge of the frame rectangle. + pub left: i32, + /// Top edge of the frame rectangle. + pub top: i32, + /// Right edge of the frame rectangle. + pub right: i32, + /// Bottom edge of the frame rectangle. + pub bottom: i32, + /// X offset applied to the frame. + pub offset_x: i32, + /// Y offset applied to the frame. + pub offset_y: i32, +} + +impl FrameHeader { + fn read(reader: &mut BufReader) -> Result { + Ok(Self { + left: reader.read_i32::()?, + top: reader.read_i32::()?, + right: reader.read_i32::()?, + bottom: reader.read_i32::()?, + offset_x: reader.read_i32::()?, + offset_y: reader.read_i32::()?, + }) + } + + fn to_bytes(self) -> [u8; 24] { + let words = [ + self.left, + self.top, + self.right, + self.bottom, + self.offset_x, + self.offset_y, + ]; + let mut bytes = [0_u8; 24]; + for (index, word) in words.iter().enumerate() { + bytes[index * 4..index * 4 + 4].copy_from_slice(&word.to_le_bytes()); + } + bytes + } +} + /// Metadata for a single frame within a sprite sequence. /// /// The `origin_x` and `origin_y` fields define the anchor point relative to @@ -52,6 +102,8 @@ use std::{fs::File, path::Path}; /// sizes and origins, so a bounding rectangle must be computed to align them. #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] pub struct ImageInfo { + /// Named rectangle and offset dwords from the frame header. + pub header: FrameHeader, /// X offset from the frame's top-left to its anchor point. pub origin_x: i32, /// Y offset from the frame's top-left to its anchor point. @@ -162,7 +214,7 @@ fn get_image_info_with_pixel_stride( reader: &mut BufReader, bytes_per_pixel: u8, ) -> Result { - reader.seek(SeekFrom::Current(6 * 4))?; + let header = FrameHeader::read(reader)?; let origin_x = reader.read_i32::()?; let origin_y = reader.read_i32::()?; @@ -179,6 +231,7 @@ fn get_image_info_with_pixel_stride( let image_start_position = reader.stream_position()?; Ok(ImageInfo { + header, origin_x, origin_y, width, @@ -773,8 +826,8 @@ pub struct SpriteSequence { /// Decoded frame data ready for editing and re-saving. #[derive(Debug, Clone)] pub struct SpriteFrameData { - /// 24 raw bytes (6 × i32) of unknown per-frame data, preserved verbatim. - pub unknown: [u8; 24], + /// Frame rectangle and offset dwords from the 44-byte header, kept verbatim. + pub header: FrameHeader, /// X offset from anchor point. pub origin_x: i32, /// Y offset from anchor point. @@ -871,12 +924,6 @@ pub fn parse_sprite_bytes(bytes: &[u8]) -> Result { "editor support for one-byte sprite groups requires a palette", )); } - let metadata_start = usize::try_from(frame.image_start_position) - .ok() - .and_then(|offset| offset.checked_sub(44)) - .ok_or_else(|| { - std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid frame offset") - })?; let pixel_start = usize::try_from(frame.image_start_position).map_err(|_| { std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid frame offset") })?; @@ -894,10 +941,8 @@ pub fn parse_sprite_bytes(bytes: &[u8]) -> Result { )); } - let mut unknown = [0_u8; 24]; - unknown.copy_from_slice(&bytes[metadata_start..metadata_start + 24]); frames.push(SpriteFrameData { - unknown, + header: frame.header, origin_x: frame.origin_x, origin_y: frame.origin_y, width: frame.width, @@ -937,7 +982,7 @@ pub fn write_sprite_to_path(path: &Path, sprite: &SpriteFile) -> Result<()> { buf.extend_from_slice(&0_i32.to_le_bytes()); for frame in &seq.frames { - buf.extend_from_slice(&frame.unknown); + buf.extend_from_slice(&frame.header.to_bytes()); buf.extend_from_slice(&frame.origin_x.to_le_bytes()); buf.extend_from_slice(&frame.origin_y.to_le_bytes()); buf.extend_from_slice(&frame.width.to_le_bytes()); @@ -1085,6 +1130,16 @@ mod tests { } } + /// Invented rectangle and offset words for synthetic frame headers. + const TEST_HEADER: FrameHeader = FrameHeader { + left: 11, + top: 22, + right: 33, + bottom: 44, + offset_x: 55, + offset_y: -66, + }; + /// Build one outer sequence record containing the given frame groups, /// using the byte layout read by `read_sprite_sequence_infos`. fn build_archive(groups: &[Vec]) -> Vec { @@ -1099,7 +1154,7 @@ mod tests { buf.extend_from_slice(&word.to_le_bytes()); } for frame in group { - buf.extend_from_slice(&[0xA5_u8; 24]); // per-frame unknown bytes + buf.extend_from_slice(&TEST_HEADER.to_bytes()); for value in [frame.origin_x, frame.origin_y, frame.width, frame.height] { buf.extend_from_slice(&value.to_le_bytes()); } @@ -1159,7 +1214,7 @@ mod tests { assert_eq!(a.frames.len(), b.frames.len(), "{label} seq {si} frames"); for (fi, (af, bf)) in a.frames.iter().zip(b.frames.iter()).enumerate() { let where_ = format!("{label} seq {si} frame {fi}"); - assert_eq!(af.unknown, bf.unknown, "{where_} unknown"); + assert_eq!(af.header, bf.header, "{where_} header"); assert_eq!(af.origin_x, bf.origin_x, "{where_} origin_x"); assert_eq!(af.origin_y, bf.origin_y, "{where_} origin_y"); assert_eq!(af.width, bf.width, "{where_} width"); @@ -1171,6 +1226,68 @@ mod tests { } } + #[test] + fn test_frame_header_named_fields_and_pixel_decode() { + let bytes = build_archive(&[vec![TestFrame { + origin_x: 3, + origin_y: 4, + width: 2, + height: 1, + pixels: vec![0xF800, 0x0000], + }]]); + + let mut reader = BufReader::new(Cursor::new(&bytes)); + let infos = read_sprite_sequence_infos(&mut reader).expect("parse streaming header"); + let streamed = &infos[0].frame_infos[0]; + assert_eq!(streamed.header, TEST_HEADER, "streamed frame header"); + assert_eq!(streamed.origin_x, 3, "streamed origin x"); + assert_eq!(streamed.origin_y, 4, "streamed origin y"); + assert_eq!(streamed.width, 2, "streamed width"); + assert_eq!(streamed.height, 1, "streamed height"); + assert_eq!(streamed.size_bytes, 4, "streamed pixel bytes"); + let streamed_rgba = render_frame_to_rgba_with_options( + &mut reader, + streamed, + 2, + 1, + 0, + 0, + SpriteRenderOptions::default(), + ) + .expect("render streamed frame") + .as_raw() + .to_vec(); + + let sprite = parse_sprite_bytes(&bytes).expect("parse editor header"); + let frame = &sprite.sequences[0].frames[0]; + assert_eq!(frame.header, TEST_HEADER, "editor frame header"); + let rgba = frame.decode_to_rgba(); + assert_eq!(rgba, streamed_rgba, "both models decode the same pixels"); + let color = rgb16_produce_color(0xF800, SpritePixelFormat::Rgb565); + assert_eq!( + &rgba[..4], + &[color.r, color.g, color.b, 255], + "first pixel color" + ); + + let path = temp_sprite_path("frame-header-round-trip"); + write_sprite_to_path(&path, &sprite).expect("write normalized archive"); + let written = std::fs::read(&path).expect("read normalized archive"); + std::fs::remove_file(&path).expect("remove temp sprite"); + let reloaded = parse_sprite_bytes(&written).expect("reparse normalized archive"); + let again = &reloaded.sequences[0].frames[0]; + assert_eq!( + again.header, TEST_HEADER, + "header survives write and reparse" + ); + assert_eq!(again.raw_pixels, frame.raw_pixels, "pixels survive write"); + assert_eq!( + again.decode_to_rgba(), + rgba, + "decoded output survives write" + ); + } + // ── Boundary: both models decode the same bytes identically ────── #[test] @@ -1359,7 +1476,7 @@ mod tests { }) .collect(); let mut frame = SpriteFrameData { - unknown: [0; 24], + header: FrameHeader::default(), origin_x: 0, origin_y: 0, width: 4, From 3d90fe3f7800640ead34823a193ea287e5a0d40a Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:43:46 +0100 Subject: [PATCH 64/72] fix(items): name weapon proc and item mod budget fields --- .../src/editors/save_file_viewer/state.rs | 4 +- .../editors/save_file_viewer/update/mod.rs | 4 +- dispel-gui/src/editors/weapon/component.rs | 5 +- dispel-gui/src/tests/select_boxes.rs | 3 +- docs/files/CharacterInGame/EditItem.db.md | 4 +- docs/files/CharacterInGame/WeaponItem.db.md | 9 ++- src/queries/create_table_weapons.sql | 3 +- src/queries/insert_weapon.sql | 6 +- src/references/edit_item_db.rs | 36 +++++++++-- src/references/enums.rs | 52 ++++++++++++++++ src/references/save_file/game_tmp.rs | 3 +- src/references/save_file/inventory.rs | 3 +- src/references/weapons_db.rs | 62 +++++++++++++++---- 13 files changed, 161 insertions(+), 33 deletions(-) diff --git a/dispel-gui/src/editors/save_file_viewer/state.rs b/dispel-gui/src/editors/save_file_viewer/state.rs index bd69b8a8..18802b24 100644 --- a/dispel-gui/src/editors/save_file_viewer/state.rs +++ b/dispel-gui/src/editors/save_file_viewer/state.rs @@ -343,7 +343,7 @@ impl MapsTableKind { ("defense", 60.0), ("magical_strength", 60.0), ("modification_budget", 60.0), - ("padding2", 60.0), + ("weapon_proc", 60.0), ("padding3", 60.0), ("req_strength", 60.0), ("padding4", 60.0), @@ -690,7 +690,7 @@ impl InventoryCategory { ("defense", 60.0), ("magical_strength", 60.0), ("modification_budget", 60.0), - ("padding2", 60.0), + ("weapon_proc", 60.0), ("padding3", 60.0), ("req_strength", 60.0), ("padding4", 60.0), diff --git a/dispel-gui/src/editors/save_file_viewer/update/mod.rs b/dispel-gui/src/editors/save_file_viewer/update/mod.rs index 00b65628..cc9e2d09 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/mod.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/mod.rs @@ -1082,7 +1082,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { item.defense.to_string(), item.magical_strength.to_string(), item.modification_budget.to_string(), - item.padding2.to_string(), + item.weapon_proc.to_string(), item.padding3.to_string(), item.req_strength.to_string(), item.padding4.to_string(), @@ -1624,7 +1624,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { d.defense.to_string(), d.magical_strength.to_string(), d.modification_budget.to_string(), - d.padding2.to_string(), + d.weapon_proc.to_string(), d.padding3.to_string(), d.req_strength.to_string(), d.padding4.to_string(), diff --git a/dispel-gui/src/editors/weapon/component.rs b/dispel-gui/src/editors/weapon/component.rs index 3c5cc8e7..0c279105 100644 --- a/dispel-gui/src/editors/weapon/component.rs +++ b/dispel-gui/src/editors/weapon/component.rs @@ -1,5 +1,5 @@ use crate::components::editable::EditableRecord; -use dispel_core::WeaponItem; +use dispel_core::{WeaponItem, WeaponProc}; use crate::editable_record_fields; @@ -20,7 +20,8 @@ editable_record_fields!(WeaponItem, { { defense = Integer / "Defense:" }, { magical_strength = Integer / "Magic Strength:" }, { modification_budget = Integer / "Modification Budget:" }, - { reserved_0x108 = Integer / "Reserved (0x108):" }, + { proc_effect = Enum(WeaponProc, ["None", "Burn", "HealthLeech"]) / "Proc Effect:" }, + { proc_effect_reserved = Integer / "Proc Reserved:" }, { reserved_0x10a = Integer / "Reserved (0x10A):" }, { req_strength = Integer / "Required STR:" }, { reserved_0x10e = Integer / "Reserved (0x10E):" }, diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs index 67e9b455..2c14cdfb 100644 --- a/dispel-gui/src/tests/select_boxes.rs +++ b/dispel-gui/src/tests/select_boxes.rs @@ -16,7 +16,7 @@ use dispel_core::{ EditItemModification, Event, EventNpcRef, EventType, ExtraObjectType, ExtraRef, HealItem, HealItemFlag, MagicSpell, MagicType, Map, MapLighting, Monster, MonsterAiType, MonsterRef, MonsterSpawn, NPC, NpcInteractionMode, NpcLookingDirection, NpcMovementMode, NpcRoleResult, - TargetSelectionFlag, + TargetSelectionFlag, WeaponItem, WeaponProc, }; use super::common::{activate_select_option, filter_select, select_shows, select_values}; @@ -474,6 +474,7 @@ fn test_every_enum_field_round_trips_through_both_views() { } audit_enum::("modifies_item", DebugFormat); audit_enum::("additional_effect", DebugFormat); + audit_enum::("proc_effect", DebugFormat); audit_enum::("magic_type", MagicSchoolFormat); audit_enum::("requires_target", DebugFormat); } diff --git a/docs/files/CharacterInGame/EditItem.db.md b/docs/files/CharacterInGame/EditItem.db.md index 42d6bc05..1ec25876 100644 --- a/docs/files/CharacterInGame/EditItem.db.md +++ b/docs/files/CharacterInGame/EditItem.db.md @@ -21,10 +21,10 @@ | 256 | 2 | `offense` | Offense modifier. | | 258 | 2 | `defense` | Defense modifier. | | 260 | 2 | `magical_power` | Magical-power modifier. | -| 262 | 2 | `modification_cost` | Budget cost charged when modifying an item. | +| 262 | 2 | `modification_cost` | Budget charged against the weapon's remaining modification budget | | 264 | 1 | `reserved_byte` | Always zero by default; purpose unknown. | | 265 | 1 | `modifies_item` | Whether this material can modify an item. | -| 266 | 2 | `additional_effect` | Extra effect: none, fire, or health leech. | +| 266 | 2 | `additional_effect` | Extra effect. 1 = Fire attack, 2 = health leech | ## Runtime item ID diff --git a/docs/files/CharacterInGame/WeaponItem.db.md b/docs/files/CharacterInGame/WeaponItem.db.md index 019b1665..0b614f73 100644 --- a/docs/files/CharacterInGame/WeaponItem.db.md +++ b/docs/files/CharacterInGame/WeaponItem.db.md @@ -27,8 +27,9 @@ Known files store zero at offset 236. The tool reads this word as `weapon_item_i | 256 | 2 | i16 | `attack` | Attack bonus | | 258 | 2 | i16 | `defense` | Defence bonus | | 260 | 2 | i16 | `magical_strength` | Magic-power bonus | -| 262 | 2 | i16 | `modification_budget` | Remaining workshop modification budget | -| 264 | 2 | i16 | `reserved_0x108` | Reserved; zero by default | +| 262 | 2 | i16 | `modification_budget` | Remaining workshop modification budget. An edit item charge is subtracted from it | +| 264 | 1 | u8 | `proc_effect` | Proc: 0 none, 1 burn rider, 2 health leech | +| 265 | 1 | u8 | `proc_effect_reserved` | Reserved byte; zero by default | | 266 | 2 | i16 | `reserved_0x10a` | Reserved; zero by default | | 268 | 2 | i16 | `req_strength` | Minimum strength | | 270 | 2 | i16 | `reserved_0x10e` | Reserved; zero by default | @@ -39,4 +40,6 @@ Known files store zero at offset 236. The tool reads this word as `weapon_item_i | 280 | 2 | i16 | `reserved_0x118` | Reserved; zero by default | | 282 | 2 | i16 | `reserved_0x11a` | Reserved; zero by default | -The tool writes the seven reserved words into save-game inventory records. All known records contain zero at those offsets. Keep their values when you edit them. Their purpose is unknown. +The tool writes the proc and the other reserved words into save-game inventory records. The proc byte comes from the edit item effect. A burn rider applies a burn status to the target. A health leech heals the wearer by one tenth of the target's current health, rounded up. + +The remaining reserved words are zero in known records. Keep their values when you edit them. Their purpose is unknown. diff --git a/src/queries/create_table_weapons.sql b/src/queries/create_table_weapons.sql index a236e935..6e1d567f 100644 --- a/src/queries/create_table_weapons.sql +++ b/src/queries/create_table_weapons.sql @@ -17,7 +17,8 @@ CREATE TABLE IF NOT EXISTS weapons defense INTEGER, magical_strength INTEGER, modification_budget INTEGER, - reserved_0x108 INTEGER, + proc_effect INTEGER, + proc_effect_reserved INTEGER, reserved_0x10a INTEGER, req_strength INTEGER, reserved_0x10e INTEGER, diff --git a/src/queries/insert_weapon.sql b/src/queries/insert_weapon.sql index cd5b1388..bd84775b 100644 --- a/src/queries/insert_weapon.sql +++ b/src/queries/insert_weapon.sql @@ -15,7 +15,8 @@ INSERT OR REPLACE INTO weapons(id, defense, magical_strength, modification_budget, - reserved_0x108, + proc_effect, + proc_effect_reserved, reserved_0x10a, req_strength, reserved_0x10e, @@ -51,4 +52,5 @@ VALUES (?1, ?24, ?25, ?26, - ?27) + ?27, + ?28) diff --git a/src/references/edit_item_db.rs b/src/references/edit_item_db.rs index a89e253e..12744cda 100644 --- a/src/references/edit_item_db.rs +++ b/src/references/edit_item_db.rs @@ -65,14 +65,18 @@ use dispel_macros::RecordPatcher; /// - **Economy**: `base_price` (i32, economic valuation) /// - **Stats**: `health_points`, `mana_points`, `strength`, `agility`, `wisdom`, `constitution` /// - **Combat**: `to_dodge`, `to_hit`, `offense`, `defense`, `magical_power` -/// - **Modification**: `modification_cost` (budget cost of modifying an item) -/// - **Behavior**: `modifies_item` (EditItemModification flag), `additional_effect` (EditItemEffect) +/// - **Modification**: `modification_cost` (cost charged against the weapon's +/// remaining modification budget) +/// - **Behavior**: `modifies_item` (EditItemModification flag), `additional_effect` +/// (EditItemEffect; value 2 heals the wearer) /// - **Runtime metadata**: `runtime_item_id` is assigned by the game after loading. /// /// # Special Values /// /// - `modifies_item`: Enum controlling if item mutates behavior -/// - `additional_effect`: Extra effect: none, fire, or health leech +/// - `modification_cost`: budget spent when this edit modifies a weapon +/// - `additional_effect`: Extra effect: none, fire, or health leech. Value 2 +/// heals the wearer by one tenth of the target's current health, rounded up. /// - `runtime_item_id`: Stored as zero in known files; overwritten with the zero-based /// record index at load time and used to identify this item definition. /// - `reserved_byte`: Always zero by default; no reader accesses it. @@ -151,7 +155,7 @@ pub struct EditItem { /// Magical power bonus. #[extractor(primitive(type = "i16"))] pub magical_power: i16, - /// Budget cost charged when modifying an item. + /// Budget charged against the weapon's remaining modification budget. #[extractor(primitive(type = "i16"))] pub modification_cost: i16, /// Reserved byte. Always zero by default; purpose unknown. @@ -160,7 +164,7 @@ pub struct EditItem { /// Flag specifying if behavior mutates. #[extractor(enum_from_u8(type = "EditItemModification"))] pub modifies_item: EditItemModification, - /// Extra effect (none, fire, or health leech). + /// Extra effect. Value 2 heals the wearer from the target's current health. #[extractor(enum_from_i16(type = "EditItemEffect"))] pub additional_effect: EditItemEffect, } @@ -238,6 +242,28 @@ mod tests { assert_eq!(items[0].defense, 15); } + #[test] + fn test_modification_cost_and_effect_map_to_named_fields() { + let mut rec = item_bytes("Shield", 200, 7, 15); + rec[0x106..0x108].copy_from_slice(&9_i16.to_le_bytes()); + rec[0x10a..0x10c].copy_from_slice(&2_i16.to_le_bytes()); + let mut data = 1_i32.to_le_bytes().to_vec(); + data.extend(rec); + + let mut cursor = Cursor::new(&data[..]); + let items = EditItem::parse(&mut cursor, data.len() as u64).unwrap(); + assert_eq!(items[0].modification_cost, 9, "cost at 0x106"); + assert_eq!( + items[0].additional_effect, + EditItemEffect::HealthLeech, + "effect value 2 heals the wearer" + ); + + let mut out = Vec::new(); + EditItem::to_writer(&items, &mut out).unwrap(); + assert_eq!(out, data, "cost and effect must keep their wire values"); + } + #[test] fn serialize_round_trip() { let mut data = 1i32.to_le_bytes().to_vec(); diff --git a/src/references/enums.rs b/src/references/enums.rs index 1565bfdf..c404418c 100644 --- a/src/references/enums.rs +++ b/src/references/enums.rs @@ -590,6 +590,58 @@ impl From for i16 { } } +/// Proc carried by a weapon. +/// +/// The value comes from an edit item effect and is read on each attack. Burn +/// applies a burn rider to the target. Health leech heals the wearer by one +/// tenth of the target's current health, rounded up. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[repr(u8)] +pub enum WeaponProc { + /// No additional effect. + #[default] + None = 0, + /// Applies a burn rider to the target. + Burn = 1, + /// Heals the wearer from the target's current health. + HealthLeech = 2, +} + +impl WeaponProc { + /// Strict conversion from the on-disk byte. + pub fn from_u8(value: u8) -> Option { + match value { + 0 => Some(Self::None), + 1 => Some(Self::Burn), + 2 => Some(Self::HealthLeech), + _ => None, + } + } + + /// On-disk byte for this proc. + pub fn value(self) -> u8 { + self as u8 + } + + /// Conversion from a display name. + pub fn from_name(name: &str) -> Option { + match name { + "None" => Some(Self::None), + "Burn" => Some(Self::Burn), + "HealthLeech" => Some(Self::HealthLeech), + _ => None, + } + } +} + +impl From for u8 { + fn from(proc: WeaponProc) -> Self { + proc.value() + } +} + +impl_wire_value!(WeaponProc, u8, from_u8); + /// Extra object types for interactive map objects #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[repr(u8)] diff --git a/src/references/save_file/game_tmp.rs b/src/references/save_file/game_tmp.rs index aca314a5..bd82d449 100644 --- a/src/references/save_file/game_tmp.rs +++ b/src/references/save_file/game_tmp.rs @@ -799,7 +799,8 @@ pub struct DrawItemWeaponItem { pub defense: i16, // 260 pub magical_strength: i16, // 262 pub modification_budget: i16, // 264 - pub padding2: i16, // 266 + /// Proc carried by the weapon; see [`crate::references::enums::WeaponProc`]. + pub weapon_proc: i16, // 266 pub padding3: i16, // 268 pub req_strength: i16, // 270 pub padding4: i16, // 272 diff --git a/src/references/save_file/inventory.rs b/src/references/save_file/inventory.rs index 9c526efb..8de02043 100644 --- a/src/references/save_file/inventory.rs +++ b/src/references/save_file/inventory.rs @@ -401,7 +401,8 @@ pub struct InventoryWeaponItem { pub defense: i16, // 260 pub magical_strength: i16, // 262 pub modification_budget: i16, // 264 - pub padding2: i16, // 266 + /// Proc carried by the weapon; see [`crate::references::enums::WeaponProc`]. + pub weapon_proc: i16, // 266 pub padding3: i16, // 268 pub req_strength: i16, // 270 pub padding4: i16, // 272 diff --git a/src/references/weapons_db.rs b/src/references/weapons_db.rs index 7fa02dca..dd4ac1a7 100644 --- a/src/references/weapons_db.rs +++ b/src/references/weapons_db.rs @@ -1,5 +1,6 @@ use std::path::Path; +use crate::references::enums::WeaponProc; use crate::references::extractor::Extractor; use dispel_macros::{Extractor, Localizable, RecordLayout, RecordPatcher}; use rusqlite::{Connection, Result, params}; @@ -45,7 +46,8 @@ use serde::{Deserialize, Serialize}; /// | - defense: i16 (armor class) | /// | - magical_strength: i16 (magical) | /// | - modification_budget: i16 (budget) | -/// | - reserved_0x108: i16 | +/// | - proc_effect: WeaponProc (u8) | +/// | - proc padding: u8 | /// | - reserved_0x10a: i16 | /// | - req_strength: i16 (requirement) | /// | - reserved_0x10e: i16 | @@ -67,17 +69,21 @@ use serde::{Deserialize, Serialize}; /// - **Combat Stats**: `to_dodge` (evasion), `to_hit` (accuracy), `attack` (offense), `defense` (armor) /// - **Magical**: `magical_strength` (magical power) /// - **Workshop**: `modification_budget` (remaining modification budget) +/// - **Combat proc**: `proc_effect` (none, burn, or health leech) /// - **Requirements**: `req_strength`, `req_agility`, `req_wisdom` (minimum stats to equip) /// - **Runtime identity**: `weapon_item_id` is overwritten with the zero-based /// record index at load time. -/// - **Reserved**: the seven `reserved_0x*` words are serialized in the file and -/// copied into inventory items, but are zero by default and have -/// no observed reader. +/// - **Reserved**: the other `reserved_0x*` words are serialized in the file and +/// copied into inventory items. They are zero by default and have no +/// observed reader. /// /// # Special Values /// /// - `base_price`: i32 economic value -/// - `modification_budget`: remaining workshop budget +/// - `modification_budget`: remaining workshop budget. Modifying an item +/// charges the edit item's `modification_cost` against this word. +/// - `proc_effect`: `0` none, `1` burn rider, `2` health leech. A health leech +/// heals the wearer by one tenth of the target's current health, rounded up. /// - `weapon_item_id`: Runtime-only ID; the on-disk value is ignored and replaced /// with the record index when the database loads. /// - `reserved_0x*`: Preserved 16-bit values. All are zero by default. @@ -155,13 +161,17 @@ pub struct WeaponItem { /// Enhanced magical defense/offense. #[extractor(primitive(type = "i16"))] pub magical_strength: i16, - /// Remaining workshop modification budget. + /// Remaining workshop modification budget. Each modification charges the + /// edit item's cost against this field. #[extractor(primitive(type = "i16"))] pub modification_budget: i16, - /// Reserved serialized word at byte offset `0x108`. It is zero by default - /// with no observed reader. - #[extractor(padding(count = 1, type = "i16"))] - pub reserved_0x108: i16, + /// Weapon proc selected by an edit item effect. Value 1 applies a burn + /// rider; value 2 heals the wearer from the target's current health. + #[extractor(enum_from_u8(type = "WeaponProc"))] + pub proc_effect: WeaponProc, + /// Reserved byte after [`Self::proc_effect`]. Preserve it verbatim. + #[extractor(primitive(type = "u8"))] + pub proc_effect_reserved: u8, /// Reserved serialized word at byte offset `0x10a`. #[extractor(padding(count = 1, type = "i16"))] pub reserved_0x10a: i16, @@ -218,7 +228,8 @@ pub fn save_weapons(conn: &mut Connection, weapons: &[WeaponItem]) -> Result<()> weapon.defense, weapon.magical_strength, weapon.modification_budget, - weapon.reserved_0x108, + weapon.proc_effect.value(), + weapon.proc_effect_reserved, weapon.reserved_0x10a, weapon.req_strength, weapon.reserved_0x10e, @@ -270,6 +281,35 @@ mod tests { assert_eq!(weapons[0].attack, 25); } + #[test] + fn test_proc_byte_and_budget_map_to_named_fields() { + for (wire, expected) in [ + (0_u8, WeaponProc::None), + (1, WeaponProc::Burn), + (2, WeaponProc::HealthLeech), + ] { + let mut rec = weapon_bytes("Proc", 100, 1, 5); + rec[0x106..0x108].copy_from_slice(&42_i16.to_le_bytes()); + rec[0x108] = wire; + rec[0x109] = 0xA5; + let mut data = 1_i32.to_le_bytes().to_vec(); + data.extend(rec); + + let mut cursor = Cursor::new(&data[..]); + let weapons = WeaponItem::parse(&mut cursor, data.len() as u64).unwrap(); + assert_eq!(weapons[0].modification_budget, 42, "budget at 0x106"); + assert_eq!(weapons[0].proc_effect, expected, "proc byte at 0x108"); + assert_eq!(weapons[0].proc_effect_reserved, 0xA5); + + let mut out = Vec::new(); + WeaponItem::to_writer(&weapons, &mut out).unwrap(); + assert_eq!( + out, data, + "proc byte and budget must keep their wire values" + ); + } + } + #[test] fn serialize_round_trip() { let mut data = 1i32.to_le_bytes().to_vec(); From e52d15c6c12f90d184c0ad3513682c66c05fe913 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:53:16 +0100 Subject: [PATCH 65/72] fix(core): preserve WAVEFORMATEX in snf files --- dispel-gui/src/tests/snf_editor.rs | 2 + docs/file_formats.md | 2 +- src/snf.rs | 74 ++++++++++++++++++++++++------ 3 files changed, 64 insertions(+), 14 deletions(-) diff --git a/dispel-gui/src/tests/snf_editor.rs b/dispel-gui/src/tests/snf_editor.rs index 8bab1216..56309c44 100644 --- a/dispel-gui/src/tests/snf_editor.rs +++ b/dispel-gui/src/tests/snf_editor.rs @@ -48,6 +48,7 @@ mod snf_editor_tests { fn app_with_snf_editor_loaded() -> App { let mut app = app_with_snf_editor(); let tone = SnfFile { + format_size_word: 8, pcmaudio_format: 1, number_of_channels: 1, sample_rate: 8000, @@ -352,6 +353,7 @@ mod audio_viewer_tests { fn synthetic_tone() -> SnfFile { SnfFile { + format_size_word: 8, pcmaudio_format: 1, number_of_channels: 1, sample_rate: 8000, diff --git a/docs/file_formats.md b/docs/file_formats.md index e391bf17..6102a0c6 100644 --- a/docs/file_formats.md +++ b/docs/file_formats.md @@ -28,7 +28,7 @@ The tool reads SNF files as PCM data with a 22-byte header. | 12 | i32 | Byte Rate | | 16 | i16 | Block Align | | 18 | i16 | Bits Per Sample | -| 20 | i16 | Unknown value that the tool skips | +| 20 | i16 | WAVEFORMATEX size | ### Conversion diff --git a/src/snf.rs b/src/snf.rs index 3febb923..6af4695d 100644 --- a/src/snf.rs +++ b/src/snf.rs @@ -22,19 +22,18 @@ use std::path::Path; // - byte_rate (i32): Byte rate (sample_rate * number_of_channels * bits_per_sample/8) // - block_align (i16): Block alignment (number_of_channels * bits_per_sample/8) // - bits_per_sample (i16): Bits per sample (typically 16) -// -// After the header, there are 2 bytes that typically contain the value 8. -// The remainder of the file contains raw PCM audio data. +// - format_size_word (i6): WAVEFORMATEX size #[derive(Debug, Clone)] pub struct SnfFile { + pub data_size: i32, pub pcmaudio_format: i16, pub number_of_channels: i16, pub sample_rate: i32, pub byte_rate: i32, pub block_align: i16, pub bits_per_sample: i16, - pub data_size: i32, + pub format_size_word: i16, pub pcm_data: Vec, } @@ -191,6 +190,7 @@ impl SnfFile { })?; Ok(SnfFile { + format_size_word: 8, pcmaudio_format, number_of_channels, sample_rate, @@ -214,8 +214,7 @@ impl SnfFile { out.extend_from_slice(&self.byte_rate.to_le_bytes()); out.extend_from_slice(&self.block_align.to_le_bytes()); out.extend_from_slice(&self.bits_per_sample.to_le_bytes()); - // Unknown field (value 8) - out.extend_from_slice(&8i16.to_le_bytes()); + out.extend_from_slice(&self.format_size_word.to_le_bytes()); out.extend_from_slice(&self.pcm_data); out } @@ -321,22 +320,21 @@ pub fn read(path: &Path) -> Result { let byte_rate = file.read_i32::()?; let block_align = file.read_i16::()?; let bits_per_sample = file.read_i16::()?; - - // Skip the unknown 2-byte field (typically contains value 8). - let _ = file.read_i16::()?; + let format_size_word = file.read_i16::()?; let capacity = data_size.max(0) as usize; let mut pcm_data = Vec::with_capacity(capacity); file.read_to_end(&mut pcm_data)?; Ok(SnfFile { + data_size, pcmaudio_format, number_of_channels, sample_rate, byte_rate, block_align, bits_per_sample, - data_size, + format_size_word, pcm_data, }) } @@ -379,13 +377,14 @@ mod tests { #[test] fn wav_sizes_follow_pcm_length_not_header_data_size() { let file = SnfFile { + data_size: 9999, pcmaudio_format: 1, number_of_channels: 1, sample_rate: 44100, byte_rate: 88200, block_align: 2, bits_per_sample: 16, - data_size: 9999, + format_size_word: 8, pcm_data: vec![0u8; 6], }; let wav = file.to_wav_bytes(); @@ -403,13 +402,14 @@ mod tests { #[test] fn wav_round_trip() { let original = SnfFile { + data_size: 4, pcmaudio_format: 1, number_of_channels: 1, sample_rate: 44100, byte_rate: 88200, block_align: 2, bits_per_sample: 16, - data_size: 4, + format_size_word: 8, pcm_data: vec![0u8, 0, 0, 0], }; @@ -429,13 +429,14 @@ mod tests { #[test] fn snf_round_trip() { let original = SnfFile { + data_size: 6, pcmaudio_format: 1, number_of_channels: 1, sample_rate: 22050, byte_rate: 44100, block_align: 2, bits_per_sample: 16, - data_size: 6, + format_size_word: 8, pcm_data: vec![0u8, 0, 0, 0, 0, 0], }; @@ -455,9 +456,56 @@ mod tests { assert_eq!(original.pcm_data, reloaded.pcm_data); } + #[test] + fn snf_format_size_word_survives_read_and_write() { + let mut bytes = Vec::new(); + bytes.extend_from_slice(&4i32.to_le_bytes()); + bytes.extend_from_slice(&1i16.to_le_bytes()); + bytes.extend_from_slice(&1i16.to_le_bytes()); + bytes.extend_from_slice(&8000i32.to_le_bytes()); + bytes.extend_from_slice(&8000i32.to_le_bytes()); + bytes.extend_from_slice(&1i16.to_le_bytes()); + bytes.extend_from_slice(&8i16.to_le_bytes()); + bytes.extend_from_slice(&0x6164i16.to_le_bytes()); + bytes.extend_from_slice(&[128, 129, 130, 131]); + + let path = std::env::temp_dir().join("invented_cbsize.snf"); + std::fs::write(&path, &bytes).unwrap(); + let parsed = read(&path).unwrap(); + std::fs::remove_file(&path).ok(); + + assert_eq!(parsed.to_snf_bytes(), bytes); + } + + #[test] + fn wav_import_defaults_format_size_word_to_eight() { + let source = SnfFile { + format_size_word: 0x6164, + pcmaudio_format: 1, + number_of_channels: 1, + sample_rate: 8000, + byte_rate: 8000, + block_align: 1, + bits_per_sample: 8, + data_size: 4, + pcm_data: vec![128, 129, 130, 131], + }; + let wav_path = std::env::temp_dir().join("invented_default_cbsize.wav"); + let snf_path = std::env::temp_dir().join("invented_default_cbsize.snf"); + std::fs::write(&wav_path, source.to_wav_bytes()).unwrap(); + + import_wav(&wav_path, &snf_path).unwrap(); + let encoded = std::fs::read(&snf_path).unwrap(); + std::fs::remove_file(&wav_path).ok(); + std::fs::remove_file(&snf_path).ok(); + + assert_eq!(encoded[20..22], 8i16.to_le_bytes()); + } + #[test] fn import_wav_export_snf() { let original = SnfFile { + format_size_word: 8, pcmaudio_format: 1, number_of_channels: 2, sample_rate: 48000, From 660a177754b77477b0b1a5afe72fdde4c67282d0 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:57:38 +0100 Subject: [PATCH 66/72] refactor: prepare stable keys and strict validation --- dispel-gui/src/components/editable.rs | 3 + .../src/editors/party_level_db/component.rs | 2 + .../save_file_viewer/update/csv_export.rs | 542 +++++++++++++++++- .../src/view/editor/spreadsheet/state.rs | 2 +- .../view/editor/spreadsheet/view/inspector.rs | 24 + src/cli.rs | 44 ++ src/commands/unified.rs | 42 ++ src/commands/validate.rs | 51 ++ 8 files changed, 682 insertions(+), 28 deletions(-) diff --git a/dispel-gui/src/components/editable.rs b/dispel-gui/src/components/editable.rs index ae96d317..adfb76f1 100644 --- a/dispel-gui/src/components/editable.rs +++ b/dispel-gui/src/components/editable.rs @@ -8,6 +8,8 @@ pub struct FieldDescriptor { pub name: &'static str, /// Human-readable label for the GUI. pub label: &'static str, + /// Stable column key used in CSV headers. + pub csv_key: &'static str, /// The kind of field (determines how it's edited). pub kind: FieldKind, } @@ -566,6 +568,7 @@ macro_rules! editable_record_fields { $crate::components::editable::FieldDescriptor { name: stringify!($name), label: $label, + csv_key: stringify!($name), kind: $crate::__er_kind!($kind, [ $($($kind_args)*)? ]), }, )*] diff --git a/dispel-gui/src/editors/party_level_db/component.rs b/dispel-gui/src/editors/party_level_db/component.rs index cee1a5ae..f20d95ad 100644 --- a/dispel-gui/src/editors/party_level_db/component.rs +++ b/dispel-gui/src/editors/party_level_db/component.rs @@ -11,11 +11,13 @@ impl EditableRecord for PartyLevelNpc { FieldDescriptor { name: "npc_index", label: "NPC Index:", + csv_key: "npc_index", kind: FieldKind::Integer, }, FieldDescriptor { name: "records_count", label: "Records:", + csv_key: "records_count", kind: FieldKind::Integer, }, ] diff --git a/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs b/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs index 6c00baac..57ace522 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs @@ -1,8 +1,469 @@ use crate::editors::save_file_viewer::message::TableKey; use crate::editors::save_file_viewer::state::{ - CharacterTableKind, JournalSection, MapsTableKind, SaveFileViewerState, + CharacterTableKind, InventoryCategory, JournalSection, MapsTableKind, SaveFileViewerState, }; +/// Fixed CSV header keys, one per entry in the matching `default_columns()` list. +/// Display labels can change without changing exported headers. +fn stable_csv_keys(key: TableKey) -> &'static [&'static str] { + match key { + TableKey::Inventory(InventoryCategory::Event) => &[ + "name", + "description", + "base_price", + "event_item_id", + "item_category", + "item_category_padding", + "inventory_record_index", + ], + TableKey::Inventory(InventoryCategory::Misc) => &[ + "name", + "description", + "base_price", + "reserved_definition_bytes", + "misc_item_id", + "item_category", + "inventory_record_index", + "inventory_instance_id", + ], + TableKey::Inventory(InventoryCategory::Edit) => &[ + "name", + "description", + "base_price", + "unknown_1", + "unknown_2", + "health_points", + "mana_points", + "strength", + "agility", + "wisdom", + "constitution", + "to_dodge", + "to_hit", + "offense", + "defense", + "magical_power", + "item_destroying_power", + "unknown_3", + "modifies_item", + "additional_effect", + "item_category", + "item_category_padding", + "inventory_record_index", + ], + TableKey::Inventory(InventoryCategory::Weapon) => &[ + "name", + "description", + "base_price", + "weapon_item_id", + "health_points", + "mana_points", + "strength", + "agility", + "wisdom", + "constitution", + "to_dodge", + "to_hit", + "attack", + "defense", + "magical_strength", + "modification_budget", + "weapon_proc", + "padding3", + "req_strength", + "padding4", + "req_agility", + "padding5", + "req_wisdom", + "padding6", + "padding7", + "padding8", + "item_category", + "inventory_instance_id", + ], + TableKey::Inventory(InventoryCategory::Heal) => &[ + "name", + "description", + "base_price", + "heal_item_id", + "health_points", + "mana_points", + "restore_full_health", + "restore_full_mana", + "poison_heal", + "cures_paralysis", + "polimorph_heal", + "reserved_definition_byte", + "item_category", + "inventory_record_index", + "reserved_runtime_bytes", + ], + TableKey::Character(CharacterTableKind::Equipment) => &[ + "panel_slot_marker", + "weapon_catalog_index", + "weapon_inventory_instance_id", + ], + TableKey::Character(CharacterTableKind::BeltPotions) => { + &["item_category", "item_catalog_index", "icon_x", "icon_y"] + } + TableKey::Character(CharacterTableKind::InventoryPlacement) => &[ + "item_category", + "item_catalog_index", + "icon_x", + "icon_y", + "item_instance_index", + ], + TableKey::Events => &[ + "event_id", + "required_event_id", + "event_type", + "script_filename", + "execution_limit", + "execution_count", + "has_triggered", + ], + TableKey::Journal(_) => &[ + "entry_index", + "quest_title", + "quest_id", + "follow_up_quest_id_1", + "follow_up_quest_id_2", + "is_completed", + ], + TableKey::Map(_, MapsTableKind::Monsters) => &[ + "monster_state", + "record_index", + "sprite_frame_id", + "name", + "monster_db_id", + "hp_current", + "hp_maximum", + "mp_current", + "mp_maximum", + "attack_cooldown_ticks", + "hit_rate", + "dodge_rate", + "offense_rate", + "defense_rate", + "magic_rate", + "is_undead", + "has_blood", + "monster_ai_type", + "experience_on_kill", + "gold_drop_on_kill", + "distance_range_size", + "detection_sight_size", + "aggression_flag", + "spell_slot_1", + "spell_slot_2", + "spell_slot_3", + "oversize", + "magic_level", + "patrol_countdown", + "behavior_flag", + "ai_state", + "ai_sub_state", + "movement_direction", + "target_position_x", + "target_position_y", + "status_effect_ticks_remaining", + "status_effect_type", + "awake_flag", + "combat_target_entity_index", + "event_id_on_kill", + "status_effect_parameter", + "current_position_x", + "current_position_y", + "spawn_position_x", + "spawn_position_y", + "home_position_x", + "home_position_y", + "render_direction_flag", + "cell_offset_x", + "cell_offset_y", + "own_entity_id", + "constructor_marker", + "movement_animation_frame", + "dead_or_removed_flag", + "sprite_render_override_pending", + "movement_animation_frame_count", + "periodic_status_animation_timer", + "status_effect_animation_frame", + "status_effect_animation_active", + "status_effect_animation_ticks_remaining", + "ground_effect_animation_active", + "ground_effect_animation_frame", + "selected_spell_id", + "path_buffer_length", + "path_buffer_index", + "loot_item1", + "loot_item2", + "loot_item3", + "force_ai_update", + "drop_all_loot", + "respawn_timer", + "saved_sprite_frame_id", + "saved_render_direction", + "special_attack", + "special_attack_chance", + "special_attack_duration", + "special_attack_effect_ticks_remaining", + "special_attack_effect_frame", + "boldness", + "attack_speed", + "guard_flag", + "guard_effect_active", + "guard_effect_frame", + "blood_effect_active", + "blood_effect_frame", + "blood_effect_direction", + "timed_overlay_active", + "timed_overlay_ticks_remaining", + "flee_throttle", + "sight_backup", + "patrol_countdown_backup", + "hidden_or_delisted_flag", + "path_buffer_position_x", + "path_buffer_position_y", + "nested_summon_flag", + "nested_summon_record", + ], + TableKey::Map(_, MapsTableKind::Npcs) => &[ + "name", + "role_description", + "movement_state", + "tile_data_entry", + "path_progress", + "current_position_x", + "current_position_y", + "last_position_x", + "last_position_y", + "target_position_x", + "target_position_y", + "path_destination_x", + "path_destination_y", + "render_direction_flag", + "cell_offset_x", + "cell_offset_y", + "map_npc_index_plus_500", + "path_step_direction", + "path_step_animation_frame", + "path_handle", + "path_step_counter", + "npc_ini_id", + "patrol_waypoint_count", + "current_patrol_waypoint_index", + "world_active", + "transient_spawn", + "removed_from_world", + "event_npc_origin", + "current_waypoint_index", + "player_interaction_latched", + "wait_tick_counter", + "reserved_runtime_90", + "reserved_runtime_94", + "npc_ref_party_member_slot", + "npc_ref_show_on_event_id", + "npc_ref_movement_mode", + "waypoint1_filled", + "waypoint1_x", + "waypoint1_y", + "waypoint1_wait_time", + "waypoint1_facing_direction", + "waypoint1_reserved", + "waypoint2_filled", + "waypoint2_x", + "waypoint2_y", + "waypoint2_wait_time", + "waypoint2_facing_direction", + "waypoint2_reserved", + "waypoint3_filled", + "waypoint3_x", + "waypoint3_y", + "waypoint3_wait_time", + "waypoint3_facing_direction", + "waypoint3_reserved", + "waypoint4_filled", + "waypoint4_x", + "waypoint4_y", + "waypoint4_wait_time", + "waypoint4_facing_direction", + "waypoint4_reserved", + "activation_rect_x1", + "activation_rect_y1", + "activation_rect_x2", + "activation_rect_y2", + "npc_ref_interaction_mode", + "npc_ref_interaction_result", + "npc_ref_interaction_range", + "npc_ref_dialog_id", + "dialogue_face_sprite_id", + "move_mode", + "start_dialogue_on_arrival", + "runtime_target_position_x", + "runtime_target_position_y", + "arrival_dialogue_id", + "freeze_flag", + "freeze_counter", + ], + TableKey::Map(_, MapsTableKind::ExtraObjects) => &[ + "render_state_slot", + "render_variant_index", + "current_sprite_frame", + "map_object_id", + "extra_definition_id", + "object_name", + "object_type", + "map_x", + "map_y", + "direction", + "interaction_state", + "requires_key", + "required_item_and_padding", + "required_item2_and_padding", + "requirement_range_2_start", + "requirement_range_2_end", + "requirement_range_3_start", + "requirement_range_3_end", + "gold_amount", + "loot_item_and_padding", + "loot_item_count", + "additional_loot_1", + "additional_loot_1_count", + "additional_loot_2", + "additional_loot_2_count", + "loot_delivery_mode", + "is_trapped", + "trap_spell_id", + "interaction_config_reserved_1", + "interaction_config_reserved_2", + "use_counter", + "interaction_event_id", + "interaction_message_id", + "footprint_width", + "footprint_height", + "footprint_orientation", + "interaction_range", + "interaction_range_padding", + "is_quest_element", + "post_activation_tile_flag", + "post_activation_footprint_mode", + "reset_to_base_sprite_frame", + "alternate_render_mode", + "open_sfx_id", + "open_sfx_reserved", + "open_sfx_padding", + "active_overlay_enabled", + "map_object_active", + "interaction_pending", + ], + TableKey::Map(_, MapsTableKind::Weapon) => &[ + "name", + "description", + "base_price", + "weapon_item_id", + "health_points", + "mana_points", + "strength", + "agility", + "wisdom", + "constitution", + "to_dodge", + "to_hit", + "attack", + "defense", + "magical_strength", + "modification_budget", + "weapon_proc", + "padding3", + "req_strength", + "padding4", + "req_agility", + "padding5", + "req_wisdom", + "padding6", + "padding7", + "padding8", + "map_coordinate_x", + "map_coordinate_y", + "ground_item_object_id", + "ground_item_object_id_padding", + ], + TableKey::Map(_, MapsTableKind::Heal) => &[ + "name", + "description", + "base_price", + "heal_item_id", + "health_points", + "mana_points", + "restore_full_health", + "restore_full_mana", + "poison_heal", + "cures_paralysis", + "polimorph_heal", + "reserved_trailer", + "map_coordinate_x", + "map_coordinate_y", + "ground_item_object_id", + "ground_item_object_id_padding", + ], + TableKey::Map(_, MapsTableKind::Edit) => &[ + "name", + "description", + "base_price", + "edit_item_id", + "health_points", + "mana_points", + "strength", + "agility", + "wisdom", + "constitution", + "to_dodge", + "to_hit", + "offense", + "defense", + "magical_power", + "item_destroying_power", + "unknown_3", + "modifies_item", + "additional_effect", + "map_coordinate_x", + "map_coordinate_y", + "ground_item_object_id", + "ground_item_object_id_padding", + ], + TableKey::Map(_, MapsTableKind::Misc) => &[ + "name", + "description", + "base_price", + "reserved_bytes", + "misc_item_id", + "map_coordinate_x", + "map_coordinate_y", + "ground_item_object_id", + "ground_item_object_id_padding", + ], + TableKey::Map(_, MapsTableKind::Event) => &[ + "name", + "description", + "base_price", + "event_item_id", + "map_coordinate_x", + "map_coordinate_y", + "ground_item_object_id", + "ground_item_object_id_padding", + ], + } +} + +/// CSV headers come from the fixed key table, never from display labels. +fn csv_headers(key: TableKey) -> Vec { + stable_csv_keys(key) + .iter() + .map(|key| (*key).to_string()) + .collect() +} + /// Build a default filename for a CSV export based on the table key. pub fn csv_default_filename(key: TableKey) -> String { match key { @@ -48,11 +509,7 @@ pub fn resolve_csv_export_data( ) -> Option<(Vec, Vec>)> { match key { TableKey::Inventory(cat) => { - let headers: Vec = cat - .default_columns() - .iter() - .map(|c| c.label.clone()) - .collect(); + let headers = csv_headers(TableKey::Inventory(cat)); let cache = state.inventory_display_caches.get(&cat)?; let indices = state.inventory_filtered_indices.get(&cat)?; let rows: Vec> = indices @@ -62,11 +519,7 @@ pub fn resolve_csv_export_data( Some((headers, rows)) } TableKey::Character(kind) => { - let headers: Vec = kind - .default_columns() - .iter() - .map(|c| c.label.clone()) - .collect(); + let headers = csv_headers(TableKey::Character(kind)); let cache = state.character_display_caches.get(&kind)?; let indices = state.character_filtered_indices.get(&kind)?; let rows: Vec> = indices @@ -76,11 +529,7 @@ pub fn resolve_csv_export_data( Some((headers, rows)) } TableKey::Events => { - let headers: Vec = - crate::editors::save_file_viewer::state::events_default_columns() - .iter() - .map(|c| c.label.clone()) - .collect(); + let headers = csv_headers(TableKey::Events); let rows: Vec> = state .events_filtered_indices .iter() @@ -89,11 +538,7 @@ pub fn resolve_csv_export_data( Some((headers, rows)) } TableKey::Journal(section) => { - let headers: Vec = section - .default_columns() - .iter() - .map(|c| c.label.clone()) - .collect(); + let headers = csv_headers(TableKey::Journal(section)); let cache = state.journal_display_caches.get(§ion)?; let indices = state.journal_filtered_indices.get(§ion)?; let rows: Vec> = indices @@ -103,11 +548,7 @@ pub fn resolve_csv_export_data( Some((headers, rows)) } TableKey::Map(map_idx, kind) => { - let headers: Vec = kind - .default_columns() - .iter() - .map(|c| c.label.clone()) - .collect(); + let headers = csv_headers(TableKey::Map(map_idx, kind)); let cache = state.maps_display_caches.get(map_idx)?; let (rows_data, indices_slice): (&[Vec], &[usize]) = match kind { MapsTableKind::Monsters => (&cache.monsters, &cache.monsters_indices), @@ -133,8 +574,55 @@ pub fn resolve_csv_export_data( #[cfg(test)] mod tests { use super::{ - CharacterTableKind, JournalSection, MapsTableKind, TableKey, csv_default_filename, + CharacterTableKind, InventoryCategory, JournalSection, MapsTableKind, TableKey, + csv_default_filename, csv_headers, stable_csv_keys, }; + use crate::editors::save_file_viewer::state::events_default_columns; + + #[test] + fn csv_headers_match_default_column_keys() { + let mut keys = vec![TableKey::Events]; + keys.extend(JournalSection::all().iter().copied().map(TableKey::Journal)); + keys.extend( + CharacterTableKind::all() + .iter() + .copied() + .map(TableKey::Character), + ); + keys.extend( + [ + InventoryCategory::Event, + InventoryCategory::Misc, + InventoryCategory::Edit, + InventoryCategory::Weapon, + InventoryCategory::Heal, + ] + .into_iter() + .map(TableKey::Inventory), + ); + keys.extend( + MapsTableKind::all() + .iter() + .copied() + .map(|kind| TableKey::Map(0, kind)), + ); + + for key in keys { + let columns = match key { + TableKey::Inventory(category) => category.default_columns(), + TableKey::Character(kind) => kind.default_columns(), + TableKey::Events => events_default_columns(), + TableKey::Journal(section) => section.default_columns(), + TableKey::Map(_, kind) => kind.default_columns(), + }; + let expected: Vec = stable_csv_keys(key) + .iter() + .map(|name| (*name).to_string()) + .collect(); + assert_eq!(columns.len(), expected.len(), "{key:?}"); + assert_eq!(csv_headers(key), expected, "{key:?}"); + } + } #[test] fn csv_filename_inventory() { diff --git a/dispel-gui/src/view/editor/spreadsheet/state.rs b/dispel-gui/src/view/editor/spreadsheet/state.rs index a858fbd6..24613737 100644 --- a/dispel-gui/src/view/editor/spreadsheet/state.rs +++ b/dispel-gui/src/view/editor/spreadsheet/state.rs @@ -609,7 +609,7 @@ impl SpreadsheetState { pub fn to_csv_bytes(&self, catalog: &[R]) -> Result, String> { let mut wtr = csv::Writer::from_writer(Vec::new()); let descriptors = R::field_descriptors(); - let header: Vec<&'static str> = descriptors.iter().map(|d| d.label).collect(); + let header: Vec<&'static str> = descriptors.iter().map(|d| d.csv_key).collect(); wtr.write_record(&header).map_err(|e| e.to_string())?; for &orig_idx in &self.filtered_indices { diff --git a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs index b27149ce..75b034ca 100644 --- a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs +++ b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs @@ -221,6 +221,26 @@ mod tests { Message::System(crate::message::SystemMessage::DismissError) } + #[test] + fn test_csv_header_uses_stable_field_keys() { + let state = SpreadsheetState::default(); + let csv = state + .to_csv_bytes(&[dispel_core::WeaponItem::default()]) + .unwrap(); + let text = String::from_utf8(csv).unwrap(); + let header = text.lines().next().unwrap(); + let expected: Vec<&str> = dispel_core::WeaponItem::field_descriptors() + .iter() + .map(|descriptor| descriptor.csv_key) + .collect(); + + assert_eq!(header, expected.join(",")); + assert!( + !header.contains(':'), + "CSV headers must not use display labels" + ); + } + fn field_changed_spreadsheet_msg(msg: SpreadsheetMessage) -> Message { match msg { SpreadsheetMessage::InspectorFieldChanged(idx, name, value) => { @@ -250,6 +270,7 @@ mod tests { let descriptor = FieldDescriptor { name: "item_type", label: "Invented Item:", + csv_key: "item_type", kind: FieldKind::CompositeItem { lookup_key: "invented_items", }, @@ -307,6 +328,7 @@ mod tests { let descriptor = FieldDescriptor { name: "item_type", label: "Invented Item:", + csv_key: "item_type", kind: FieldKind::CompositeItem { lookup_key: "invented_items", }, @@ -472,6 +494,7 @@ mod tests { let descriptor = FieldDescriptor { name: "monster_db_id", label: "Monster ID:", + csv_key: "monster_db_id", kind: FieldKind::Lookup("monster_names"), }; let lookups = HashMap::from([( @@ -547,6 +570,7 @@ mod tests { let descriptor = FieldDescriptor { name: "monster_db_id", label: "Monster ID:", + csv_key: "monster_db_id", kind: FieldKind::Lookup("monster_names"), }; let lookups = HashMap::new(); diff --git a/src/cli.rs b/src/cli.rs index 839e8ab3..b851d021 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -69,6 +69,10 @@ pub struct PatchArgs { /// Skip backup creation (with --in-place) #[arg(long)] pub no_backup: bool, + + /// Reject JSON keys that are absent from the file type schema + #[arg(long)] + pub strict: bool, } /// `validate`: validate JSON against the registered file-type schema. @@ -85,6 +89,10 @@ pub struct ValidateArgs { /// Verbose output #[arg(long)] pub verbose: bool, + + /// Reject JSON keys that are absent from the file type schema + #[arg(long)] + pub strict: bool, } /// `list`: show supported file types. @@ -568,6 +576,41 @@ mod tests { cmd.execute() } + #[test] + fn test_patch_and_validate_accept_strict_flag() { + let patch = Cli::try_parse_from([ + "dispel-extractor", + "patch", + "-i", + "invented.json", + "-t", + "invented.db", + "--output", + "invented-out.db", + "--strict", + ]) + .unwrap(); + match patch.command { + Some(Commands::Patch(args)) => assert!(args.strict), + _ => panic!("expected patch command"), + } + + let validate = Cli::try_parse_from([ + "dispel-extractor", + "validate", + "-i", + "invented.json", + "--type", + "weapons", + "--strict", + ]) + .unwrap(); + match validate.command { + Some(Commands::Validate(args)) => assert!(args.strict), + _ => panic!("expected validate command"), + } + } + const MAKEFILE: &str = include_str!("../Makefile"); /// Snapshot of the advertised command surface. Adding, removing or renaming @@ -756,6 +799,7 @@ mod tests { input: "/definitely/not/a/real/file.json".to_owned(), r#type: "weapons".to_owned(), verbose: false, + strict: false, }) .expect_err("validate on a missing file must fail"); assert!(err.to_string().contains("File not found"), "{err}"); diff --git a/src/commands/unified.rs b/src/commands/unified.rs index 649945ee..f010a041 100644 --- a/src/commands/unified.rs +++ b/src/commands/unified.rs @@ -5,6 +5,7 @@ use std::path::{Path, PathBuf}; use crate::cli::{ExtractArgs, PatchArgs}; use crate::commands::Command; use crate::commands::registry::{self, DetectResult, FileType}; +use crate::commands::validate::strict_key_errors; impl Command for ExtractArgs { fn execute(&self) -> Result<(), Box> { @@ -79,6 +80,18 @@ impl Command for PatchArgs { .and_then(|v| v.as_str()); let file_type = resolve_type(&self.r#type, target_path, meta_hint)?; + if self.strict { + let errors = strict_key_errors(&patch_data, file_type); + if !errors.is_empty() { + return Err(format!( + "Strict key validation failed ({} error(s)):\n{}", + errors.len(), + errors.join("\n") + ) + .into()); + } + } + if self.dry_run { if let Some(validate_fn) = file_type.validate_fn { match validate_fn(&patch_data) { @@ -273,6 +286,7 @@ mod tests { dry_run: false, in_place: false, no_backup: false, + strict: false, }; let err = args.execute().unwrap_err().to_string(); assert!(err.contains("--output"), "{err}"); @@ -282,4 +296,32 @@ mod tests { fs::remove_dir_all(&dir).expect("remove temp dir"); } + + #[test] + fn test_strict_key_errors_reports_stale_keys_with_record_index() { + let file_type = registry::get_by_key("weapons").expect("weapons type is registered"); + let canonical = file_type.field_names().next().unwrap().to_string(); + + let mut valid = serde_json::Map::new(); + valid.insert(canonical, serde_json::json!(1)); + let mut stale = serde_json::Map::new(); + stale.insert("invented_field".to_string(), serde_json::json!(2)); + let data = serde_json::Value::Array(vec![ + serde_json::Value::Object(valid), + serde_json::Value::Object(stale), + ]); + + let errors = strict_key_errors(&data, file_type); + + assert_eq!(errors.len(), 1, "{errors:?}"); + assert!(errors[0].contains("record 1"), "{errors:?}"); + assert!(errors[0].contains("invented_field"), "{errors:?}"); + assert!( + strict_key_errors( + &serde_json::json!([{ "name": "invented weapon" }]), + registry::get_by_key("weapons").unwrap() + ) + .is_empty() + ); + } } diff --git a/src/commands/validate.rs b/src/commands/validate.rs index a631f4f0..51740f31 100644 --- a/src/commands/validate.rs +++ b/src/commands/validate.rs @@ -5,6 +5,33 @@ use std::path::Path; use crate::cli::ValidateArgs; use crate::commands::Command; use crate::commands::registry; +use crate::commands::registry::FileType; +use serde_json::Value; +use std::collections::HashSet; + +/// Report record keys that the file type does not define. +/// +/// The check runs on parsed JSON before typed deserialization, so a stale key +/// is reported with the index of the record that holds it. +pub(crate) fn strict_key_errors(data: &Value, file_type: &FileType) -> Vec { + let Some(records) = data.as_array() else { + return vec!["strict mode expects an array of records".to_string()]; + }; + let allowed: HashSet<&str> = file_type.field_names().collect(); + let mut errors = Vec::new(); + for (index, record) in records.iter().enumerate() { + let Some(object) = record.as_object() else { + errors.push(format!("record {index}: expected an object")); + continue; + }; + for key in object.keys() { + if !allowed.contains(key.as_str()) { + errors.push(format!("record {index}: unknown field '{key}'")); + } + } + } + errors +} impl Command for ValidateArgs { fn execute(&self) -> Result<(), Box> { @@ -35,6 +62,30 @@ impl Command for ValidateArgs { data.clone() }; + if self.strict { + let errors = strict_key_errors(&validate_data, file_type); + if !errors.is_empty() { + if self.verbose { + let error_json = serde_json::json!({ + "valid": false, + "type": file_type.key, + "error_count": errors.len(), + "errors": errors, + }); + eprintln!("{}", serde_json::to_string_pretty(&error_json).unwrap()); + } else { + for err in &errors { + eprintln!("Error: {}", err); + } + } + return Err(format!( + "Strict key validation failed: {} error(s) found", + errors.len() + ) + .into()); + } + } + if let Some(validate_fn) = file_type.validate_fn { match validate_fn(&validate_data) { Ok(()) => { From dbdbb882a997fb74b0532ea10dc2f637fd12cfc4 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:10:05 +0100 Subject: [PATCH 67/72] fix(core): split misc rune words and merge wave index --- dispel-gui/src/editors/extra_ref/component.rs | 4 +- dispel-gui/src/editors/misc_item/component.rs | 5 +- .../src/editors/save_file_viewer/state.rs | 9 +-- .../save_file_viewer/update/csv_export.rs | 23 ++++++-- .../editors/save_file_viewer/update/mod.rs | 9 +-- docs/files/CROSS_REFERENCES.md | 4 +- docs/files/CharacterInGame/MiscItem.db.md | 17 ++++-- docs/files/ExtraInGame/Extra.ref.md | 23 +++----- src/modding/patchers/derived.rs | 12 ---- src/queries/create_table_extra_refs.sql | 4 +- src/queries/create_table_misc_items.sql | 5 +- src/queries/insert_extra_ref.sql | 6 +- src/queries/insert_misc_item.sql | 10 +++- src/references/extra_ref.rs | 56 ++++++++++--------- src/references/layout.rs | 2 +- src/references/misc_item_db.rs | 52 +++++++++++++++-- src/references/save_file/game_tmp.rs | 15 +++-- src/references/save_file/tests.rs | 6 +- 18 files changed, 160 insertions(+), 102 deletions(-) diff --git a/dispel-gui/src/editors/extra_ref/component.rs b/dispel-gui/src/editors/extra_ref/component.rs index 4b80832e..10b4a7d7 100644 --- a/dispel-gui/src/editors/extra_ref/component.rs +++ b/dispel-gui/src/editors/extra_ref/component.rs @@ -48,9 +48,7 @@ editable_record_fields!(ExtraRef, { { post_activation_footprint_mode = DispEnum(BooleanFlag, ["True", "False"]) / "Post-activation footprint mode:" }, { reset_to_base_sprite_frame = Integer / "Non-zero resets to the base frame:" }, { alternate_render_mode = DispEnum(BooleanFlag, ["True", "False"]) / "Alternate render mode:" }, - { open_sfx_id = Integer / "Open SFX (Wave.ini, 0 = none):" }, - { open_sfx_reserved = Integer / "Open SFX reserved:" }, - { open_sfx_padding = Integer / "Open SFX padding:" }, + { wave_index = Integer / "Wave index (Wave.ini, 0 = none):" }, { active_overlay_enabled = DispEnum(BooleanFlag, ["True", "False"]) / "Active overlay enabled:" }, { map_object_active = DispEnum(BooleanFlag, ["True", "False"]) / "Map object active:" }, }); diff --git a/dispel-gui/src/editors/misc_item/component.rs b/dispel-gui/src/editors/misc_item/component.rs index b8be3af2..560fcd54 100644 --- a/dispel-gui/src/editors/misc_item/component.rs +++ b/dispel-gui/src/editors/misc_item/component.rs @@ -7,7 +7,10 @@ editable_record_fields!(MiscItem, { { name = String / "Name:" }, { description = TextArea / "Description:" }, { base_price = Integer / "Base Price:" }, - { reserved_bytes = HexString / "Reserved bytes:" }, + { rune_mark_x = Integer / "Rune mark X:" }, + { rune_mark_y = Integer / "Rune mark Y:" }, + { rune_mark_map_id = Integer / "Rune mark map id:" }, + { unassigned_word = Integer / "Unassigned word:" }, { runtime_record_index_slot = Integer / "Runtime record index slot:" }, }); diff --git a/dispel-gui/src/editors/save_file_viewer/state.rs b/dispel-gui/src/editors/save_file_viewer/state.rs index 18802b24..60fbc34e 100644 --- a/dispel-gui/src/editors/save_file_viewer/state.rs +++ b/dispel-gui/src/editors/save_file_viewer/state.rs @@ -319,9 +319,7 @@ impl MapsTableKind { ("post_activation_footprint_mode", 60.0), ("reset_to_base_sprite_frame", 60.0), ("alternate_render_mode", 60.0), - ("open_sfx_id", 60.0), - ("open_sfx_reserved", 60.0), - ("open_sfx_padding", 60.0), + ("wave_index", 60.0), ("active_overlay_enabled", 60.0), ("map_object_active", 60.0), ("interaction_pending", 60.0), @@ -405,7 +403,10 @@ impl MapsTableKind { ("name", 160.0), ("description", 160.0), ("base_price", 60.0), - ("reserved_bytes", 320.0), + ("rune_mark_x", 60.0), + ("rune_mark_y", 60.0), + ("rune_mark_map_id", 60.0), + ("unassigned_word", 60.0), ("misc_item_id", 60.0), ("map_coordinate_x", 60.0), ("map_coordinate_y", 60.0), diff --git a/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs b/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs index 57ace522..5014fdc6 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs @@ -350,9 +350,7 @@ fn stable_csv_keys(key: TableKey) -> &'static [&'static str] { "post_activation_footprint_mode", "reset_to_base_sprite_frame", "alternate_render_mode", - "open_sfx_id", - "open_sfx_reserved", - "open_sfx_padding", + "wave_index", "active_overlay_enabled", "map_object_active", "interaction_pending", @@ -436,7 +434,10 @@ fn stable_csv_keys(key: TableKey) -> &'static [&'static str] { "name", "description", "base_price", - "reserved_bytes", + "rune_mark_x", + "rune_mark_y", + "rune_mark_map_id", + "unassigned_word", "misc_item_id", "map_coordinate_x", "map_coordinate_y", @@ -624,6 +625,20 @@ mod tests { } } + #[test] + fn csv_headers_use_conversion_keys() { + let extra_keys = stable_csv_keys(TableKey::Map(0, MapsTableKind::ExtraObjects)); + assert!(extra_keys.contains(&"wave_index")); + assert!(!extra_keys.contains(&"open_sfx_id")); + + let misc_keys = stable_csv_keys(TableKey::Map(0, MapsTableKind::Misc)); + assert!(misc_keys.contains(&"rune_mark_x")); + assert!(misc_keys.contains(&"rune_mark_y")); + assert!(misc_keys.contains(&"rune_mark_map_id")); + assert!(misc_keys.contains(&"unassigned_word")); + assert!(!misc_keys.contains(&"reserved_bytes")); + } + #[test] fn csv_filename_inventory() { let name = csv_default_filename(TableKey::Inventory( diff --git a/dispel-gui/src/editors/save_file_viewer/update/mod.rs b/dispel-gui/src/editors/save_file_viewer/update/mod.rs index cc9e2d09..577fd97e 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/mod.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/mod.rs @@ -1593,9 +1593,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { e.post_activation_footprint_mode.to_string(), e.reset_to_base_sprite_frame.to_string(), e.alternate_render_mode.to_string(), - e.open_sfx_id.to_string(), - e.open_sfx_reserved.to_string(), - e.open_sfx_padding.to_string(), + e.wave_index.to_string(), e.active_overlay_enabled.to_string(), e.map_object_active.to_string(), e.interaction_pending.to_string(), @@ -1707,7 +1705,10 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { d.name.clone(), d.description.clone(), d.base_price.to_string(), - hex_bytes(&d.reserved_bytes), + d.rune_mark_x.to_string(), + d.rune_mark_y.to_string(), + d.rune_mark_map_id.to_string(), + d.unassigned_word.to_string(), d.misc_item_id.to_string(), d.map_coordinate_x.to_string(), d.map_coordinate_y.to_string(), diff --git a/docs/files/CROSS_REFERENCES.md b/docs/files/CROSS_REFERENCES.md index 44730718..cf1f7a8b 100644 --- a/docs/files/CROSS_REFERENCES.md +++ b/docs/files/CROSS_REFERENCES.md @@ -161,7 +161,7 @@ ExtraInGame/Extdun01.ref ├── loot_item → items lookup (type:ID) ├── additional_loot_1 / additional_loot_2 → item IDs ├── trap_spell_id → spell index - └── open_sfx_id → Wave.ini index + └── wave_index → Wave.ini index Ref/DRAWITEM.ref ├── map_id → AllMap.ini.id @@ -241,7 +241,7 @@ Note: 0 ends the list. A store holds at most 15 products. | Extdun01.ref | required_item / required_item2 | items lookup | type:ID | Required item | | Extdun01.ref | loot_item | items lookup | type:ID | Loot | | Extdun01.ref | trap_spell_id | spell index | - | Trap spell | -| Extdun01.ref | open_sfx_id | Wave.ini | index | Open sound | +| Extdun01.ref | wave_index | Wave.ini | index | Open sound | | DRAWITEM.ref | map_id | AllMap.ini | id | Map location | | DRAWITEM.ref | item | items lookup | type:ID | Dropped item | | Map.map | ground GTL index | per-map .gtl file | tile index | Ground tiles | diff --git a/docs/files/CharacterInGame/MiscItem.db.md b/docs/files/CharacterInGame/MiscItem.db.md index 703980c2..440b43de 100644 --- a/docs/files/CharacterInGame/MiscItem.db.md +++ b/docs/files/CharacterInGame/MiscItem.db.md @@ -25,7 +25,7 @@ The tool reads `MiscItem.db` as name, description and price records for miscella - name: 30 bytes (WINDOWS-1250, null-padded) - description: 202 bytes (EUC-KR, null-padded) - base_price: i32 (economic value) -- reserved_bytes: 16 bytes (preserved raw data) +- rune_mark_x, rune_mark_y, rune_mark_map_id, unassigned_word: four u32 words - runtime_record_index_slot: i32 (overwritten with the sequential record index at load time) ``` @@ -37,7 +37,10 @@ The tool reads `MiscItem.db` as name, description and price records for miscella | name | 30 | string | Item name (WINDOWS-1250 encoded) | | description | 202 | string | Item description (EUC-KR encoded) | | base_price | 4 | i32 | Economic value (0 = non-tradable, -1 = quest item) | -| reserved_bytes | 16 | bytes | Unused bytes | +| rune_mark_x | 4 | u32 | Rune mark X coordinate | +| rune_mark_y | 4 | u32 | Rune mark Y coordinate | +| rune_mark_map_id | 4 | u32 | Map id stored with the rune mark | +| unassigned_word | 4 | u32 | Word with no confirmed meaning | | runtime_record_index_slot | 4 | i32 | Slot at offsets 252–255. The game overwrites it in memory with the sequential record index. | ### Data Structure @@ -50,7 +53,10 @@ pub struct MiscItem { name: String, // Item name (30 chars max) description: String, // Item description (202 chars max) base_price: i32, // Economic value - reserved_bytes: [u8; 16], + rune_mark_x: u32, + rune_mark_y: u32, + rune_mark_map_id: u32, + unassigned_word: u32, runtime_record_index_slot: i32, } ``` @@ -63,6 +69,9 @@ Offset | Size | Field | Description 0 | 30 | name | Null-padded WINDOWS-1250 string 30 | 202 | desc | Null-padded EUC-KR string 232 | 4 | price | Economic value (i32) -236 | 16 | reserved_bytes | Raw reserved bytes +236 | 4 | rune_mark_x | Rune mark X coordinate +240 | 4 | rune_mark_y | Rune mark Y coordinate +244 | 4 | rune_mark_map_id | Rune mark map id +248 | 4 | unassigned_word | Unassigned word 252 | 4 | runtime_record_index_slot | Replaced with the record index in memory ``` diff --git a/docs/files/ExtraInGame/Extra.ref.md b/docs/files/ExtraInGame/Extra.ref.md index 11dc90ae..b8703035 100644 --- a/docs/files/ExtraInGame/Extra.ref.md +++ b/docs/files/ExtraInGame/Extra.ref.md @@ -55,8 +55,8 @@ items) on specific maps. Each map has its own `Ext*.ref` file containing all int - loot_delivery_mode: i32 (0 = deterministic, 1 = roll-gated) - is_trapped: i32 (trap arming flag) - trap_spell_id: i32 (Magic.db index used when a trap triggers) -- interaction_config_reserved_1: i32 (record +0x78; preserve verbatim) -- interaction_config_reserved_2: i32 (record +0x7C; preserve verbatim) +- interaction_config_reserved_1: i32 (unknown; preserve verbatim) +- interaction_config_reserved_2: i32 (unknown; preserve verbatim) - use_counter: i32 (record +0x80; remaining uses, default 999) - interaction_event_id: i32 (links to Event.ini) - interaction_message_id: i32 (links to Message.scr) @@ -65,14 +65,12 @@ items) on specific maps. Each map has its own `Ext*.ref` file containing all int - footprint_orientation: u8 (normal/reversed footprint traversal) - interaction_range: u8 (maximum activation distance) - interaction_range_padding: 2 bytes (padding, normally [205, 205]) -- is_quest_element: i32 (requests a quest-state refresh after a successful requirement check) +- is_quest_element: i32 (gates an event link or quest refresh) - post_activation_tile_flag: i32 (enables a post-activation map-grid tile flag) - post_activation_footprint_mode: i32 (selects the post-activation map-grid footprint update mode) - reset_to_base_sprite_frame: i32 (non-zero resets to the base frame after interaction) - alternate_render_mode: i32 (selects the alternative object renderer) -- open_sfx_id: u8 (record +0xAC; Wave.ini index played by `extra_play_open_sfx` on activation; 0 = none) -- open_sfx_reserved: u8 (reserved; preserve verbatim) -- open_sfx_padding: i16 (padding, normally 0) +- wave_index: u32 (links to Wave.ini; 0 = none) - active_overlay_enabled: i32 (enables the active-object overlay render path) - map_object_active: i32 (marks the object active in the map-object grid and update loop) @@ -90,7 +88,7 @@ items) on specific maps. Each map has its own `Ext*.ref` file containing all int - `gold_amount` holds the gold value. The tool reads three `(item, count)` loot pairs: `loot_item` with `loot_item_count`, then the two `additional_loot_*` pairs. - `footprint_width`, `footprint_height` and `footprint_orientation` describe the map cells the object occupies. `interaction_range` limits activation distance. -The seven words from `additional_loot_2_count` through `use_counter` hold the trap flag, trap spell index and related configuration. Both trap fields are zero in every sample placement. They are separate from `open_sfx_id`. +The seven words from `additional_loot_2_count` through `use_counter` hold the trap flag, trap spell index and related configuration. Both trap fields are zero in every sample placement. They are separate from `wave_index`. #### Core Identification @@ -114,9 +112,9 @@ The seven words from `additional_loot_2_count` through `use_counter` hold the tr | Field | Type | Description | |----------------------|------|---------------------------------------------------------------------------| | object_type | u8 | Object category enum | -| open_sfx_id | u8 | Wave.ini index played on successful activation (`extra_play_open_sfx`). | +| wave_index | u32 | Wave.ini index played on activation. | | interaction_range | u8 | Maximum tile distance at which the engine allows activation. | -| is_quest_element | i32 | Quest-related interaction flag; set after a successful requirement check. | +| is_quest_element | i32 | Gates an event link or quest refresh. The key flag role is unconfirmed. | #### Runtime and Rendering Controls @@ -128,7 +126,6 @@ The seven words from `additional_loot_2_count` through `use_counter` hold the tr | alternate_render_mode | BooleanFlag | Selects the alternate renderer. | | active_overlay_enabled | BooleanFlag | Enables the active-object overlay render path. | | map_object_active | BooleanFlag | Makes the object participate in the map-object grid and update loop. | -| open_sfx_reserved | u8 | Reserved byte adjacent to `open_sfx_id`; preserve verbatim. | #### Container State @@ -175,11 +172,9 @@ The seven words from `additional_loot_2_count` through `use_counter` hold the tr | 6 | Interactive | General interactive element | | 7 | Magic | Magical object | -#### Trap fields and open sound +#### Trap fields -`is_trapped` and `trap_spell_id` hold the trap arming flag and `Magic.db` spell index. The 1,039 sample placements carry zero in both fields. - -`open_sfx_id` holds a `Wave.ini` sound index for a door, lever, chest, key or subtype-8 object. Zero means no sound. The field is a `u8`. +`is_trapped` and `trap_spell_id` hold the trap arming flag and `Magic.db` spell index. #### Item Type ID (required_item_type_id, loot_item_type_id) diff --git a/src/modding/patchers/derived.rs b/src/modding/patchers/derived.rs index 71a1599c..20e63c71 100644 --- a/src/modding/patchers/derived.rs +++ b/src/modding/patchers/derived.rs @@ -293,18 +293,6 @@ mod tests { assert_ne!(parsed.requires_key, BooleanFlag::default()); } - #[test] - fn extra_ref_wide_enum_wire_is_u8() { - // open_sfx_id is a plain u8 Wave.ini index (record +0xAC); the old - // ActivationEffectId enum collapsed unknown indices to 255. - let p = crate::modding::patchers::ExtraRefPatcher; - let out = p - .apply_field(&extra_ref_blob(), 0, "open_sfx_id", &Value::I64(1)) - .unwrap(); - // Round-trip should not panic; just verify parse succeeds. - assert!(!parse_extra(&out).is_empty()); - } - #[test] fn extra_ref_inventory_item_rejects_out_of_range_i64() { let p = crate::modding::patchers::ExtraRefPatcher; diff --git a/src/queries/create_table_extra_refs.sql b/src/queries/create_table_extra_refs.sql index eccef60a..1ddac80e 100644 --- a/src/queries/create_table_extra_refs.sql +++ b/src/queries/create_table_extra_refs.sql @@ -51,9 +51,7 @@ CREATE TABLE IF NOT EXISTS extra_refs post_activation_footprint_mode INTEGER, reset_to_base_sprite_frame INTEGER, alternate_render_mode INTEGER, - open_sfx_id INTEGER, - open_sfx_reserved INTEGER, - open_sfx_padding INTEGER, + wave_index INTEGER, active_overlay_enabled INTEGER, map_object_active INTEGER ); \ No newline at end of file diff --git a/src/queries/create_table_misc_items.sql b/src/queries/create_table_misc_items.sql index 7aafb403..721c908b 100644 --- a/src/queries/create_table_misc_items.sql +++ b/src/queries/create_table_misc_items.sql @@ -4,6 +4,9 @@ CREATE TABLE IF NOT EXISTS misc_items name TEXT, description TEXT, base_price INTEGER, - reserved_bytes BLOB, + rune_mark_x INTEGER, + rune_mark_y INTEGER, + rune_mark_map_id INTEGER, + unassigned_word INTEGER, runtime_record_index_slot INTEGER ); diff --git a/src/queries/insert_extra_ref.sql b/src/queries/insert_extra_ref.sql index 555dfd2f..530af60e 100644 --- a/src/queries/insert_extra_ref.sql +++ b/src/queries/insert_extra_ref.sql @@ -49,9 +49,7 @@ INSERT OR REPLACE INTO extra_refs(file_id, post_activation_footprint_mode, reset_to_base_sprite_frame, alternate_render_mode, - open_sfx_id, - open_sfx_reserved, - open_sfx_padding, + wave_index, active_overlay_enabled, map_object_active) -VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, ?29, ?30, ?31, ?32, ?33, ?34, ?35, ?36, ?37, ?38, ?39, ?40, ?41, ?42, ?43, ?44, ?45, ?46, ?47, ?48, ?49, ?50, ?51, ?52, ?53, ?54, ?55, ?56); \ No newline at end of file +VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, ?29, ?30, ?31, ?32, ?33, ?34, ?35, ?36, ?37, ?38, ?39, ?40, ?41, ?42, ?43, ?44, ?45, ?46, ?47, ?48, ?49, ?50, ?51, ?52, ?53, ?54); \ No newline at end of file diff --git a/src/queries/insert_misc_item.sql b/src/queries/insert_misc_item.sql index 8df8cdf4..e4389af7 100644 --- a/src/queries/insert_misc_item.sql +++ b/src/queries/insert_misc_item.sql @@ -2,7 +2,10 @@ INSERT OR REPLACE INTO misc_items(id, name, description, base_price, - reserved_bytes, + rune_mark_x, + rune_mark_y, + rune_mark_map_id, + unassigned_word, runtime_record_index_slot ) VALUES (?1, @@ -10,4 +13,7 @@ VALUES (?1, ?3, ?4, ?5, - ?6); + ?6, + ?7, + ?8, + ?9); diff --git a/src/references/extra_ref.rs b/src/references/extra_ref.rs index 0f1ccb12..b92c8fff 100644 --- a/src/references/extra_ref.rs +++ b/src/references/extra_ref.rs @@ -125,15 +125,12 @@ pub struct ExtraRef { #[extractor(primitive(type = "i32"))] pub is_trapped: i32, /// `Magic.db` spell index used when a trap triggers. - /// - /// Zero in all shipped placements. This is distinct from the open-sound - /// index in [`Self::open_sfx_id`]. #[extractor(primitive(type = "i32"))] pub trap_spell_id: i32, - /// Unassigned configuration word at record `+0x78`. Preserve verbatim. + /// Unknown. Preserve verbatim. #[extractor(primitive(type = "i32"))] pub interaction_config_reserved_1: i32, - /// Unassigned configuration word at record `+0x7C`. Preserve verbatim. + /// Unknown. Preserve verbatim. #[extractor(primitive(type = "i32"))] pub interaction_config_reserved_2: i32, /// Remaining interaction uses for levers and buttons. @@ -162,7 +159,7 @@ pub struct ExtraRef { /// Padding after [`Self::interaction_range`] (normally `[0xCD; 2]`). #[extractor(vec_u8(size = 2))] pub interaction_range_padding: Vec, - /// Requests a quest-state refresh after a successful requirement check. + /// Gates an event link or quest refresh. #[extractor(enum_from_i32(type = "BooleanFlag"))] pub is_quest_element: BooleanFlag, /// Enables the post-activation tile flag used by the map-object grid. @@ -178,20 +175,9 @@ pub struct ExtraRef { #[extractor(enum_from_i32(type = "BooleanFlag"))] pub alternate_render_mode: BooleanFlag, /// Wave.ini sound index played when an object is activated successfully. - /// `0` means no sound. - /// - /// This is a sound index, not a trap or spell id. It was previously - /// exported as `activation_effect_id` and parsed through an enum that - /// rewrote every index other than `0` and `10` to `255` on save. The trap - /// fields are [`Self::is_trapped`] and [`Self::trap_spell_id`]. - #[extractor(primitive(type = "u8"))] - pub open_sfx_id: u8, - /// Reserved byte after [`Self::open_sfx_id`]. Preserve it verbatim. - #[extractor(primitive(type = "u8"))] - pub open_sfx_reserved: u8, - /// Padding following [`Self::open_sfx_reserved`] (normally 0). - #[extractor(primitive(type = "i16"))] - pub open_sfx_padding: i16, + /// `0` means no sound. The four on-disk bytes hold one little-endian word. + #[extractor(primitive(type = "u32"))] + pub wave_index: u32, /// Enables the active-object overlay render path. #[extractor(enum_from_i32(type = "BooleanFlag"))] pub active_overlay_enabled: BooleanFlag, @@ -288,9 +274,7 @@ pub fn save_extra_refs(conn: &mut Connection, file_id: i32, extra_refs: &[ExtraR i32::from(extra_ref.post_activation_footprint_mode), // 49 extra_ref.reset_to_base_sprite_frame, // 50 i32::from(extra_ref.alternate_render_mode), // 51 - extra_ref.open_sfx_id, // 52 - extra_ref.open_sfx_reserved, // 53 - extra_ref.open_sfx_padding, // 54 + i64::from(extra_ref.wave_index), // 52 i32::from(extra_ref.active_overlay_enabled), // 55 i32::from(extra_ref.map_object_active) // 56 ])?; @@ -326,13 +310,35 @@ mod tests { /// The open-SFX byte is a Wave.ini index (0..N), not an effect enum. /// A byte of 251 used to be rewritten to 255 by the old enum parser. + #[test] + fn test_wave_bytes_expose_one_index() { + let mut rec = ref_bytes("Invented Chest", 10, 20, 50); + rec[0xac..0xb0].copy_from_slice(&0x6164u32.to_le_bytes()); + let mut data = 1i32.to_le_bytes().to_vec(); + data.extend(rec); + + let mut cursor = Cursor::new(&data[..]); + let records = ExtraRef::parse(&mut cursor, data.len() as u64).unwrap(); + let json = serde_json::to_value(&records[0]).unwrap(); + let object = json.as_object().unwrap(); + + assert_eq!(object["wave_index"], 0x6164u32); + assert!(!object.contains_key("open_sfx_id")); + assert!(!object.contains_key("open_sfx_reserved")); + assert!(!object.contains_key("open_sfx_padding")); + + let mut output = Vec::new(); + ExtraRef::to_writer(&records, &mut output).unwrap(); + assert_eq!(output, data); + } + #[test] fn test_open_sfx_byte_round_trip_preserved() { let mut rec = ref_bytes("Chest1", 10, 20, 50); rec[0x70..0x74].copy_from_slice(&1i32.to_le_bytes()); // is_trapped rec[0x74..0x78].copy_from_slice(&27i32.to_le_bytes()); // trap_spell_id rec[0x80..0x84].copy_from_slice(&999i32.to_le_bytes()); // use_counter - rec[0xac] = 251; // open_sfx_id + rec[0xac..0xb0].copy_from_slice(&251u32.to_le_bytes()); // wave_index let mut data = 1i32.to_le_bytes().to_vec(); data.extend(rec); @@ -342,7 +348,7 @@ mod tests { assert_eq!(records[0].is_trapped, 1); assert_eq!(records[0].trap_spell_id, 27); assert_eq!(records[0].use_counter, 999); - assert_eq!(records[0].open_sfx_id, 251); + assert_eq!(records[0].wave_index, 251); let mut out = Vec::new(); ExtraRef::to_writer(&records, &mut out).unwrap(); diff --git a/src/references/layout.rs b/src/references/layout.rs index cfafd7b5..5d784c6d 100644 --- a/src/references/layout.rs +++ b/src/references/layout.rs @@ -319,7 +319,7 @@ mod tests { assert_eq!(extra.field_offset("is_trapped"), Some(0x70)); assert_eq!(extra.field_offset("trap_spell_id"), Some(0x74)); assert_eq!(extra.field_offset("use_counter"), Some(0x80)); - assert_eq!(extra.field_offset("open_sfx_id"), Some(0xac)); + assert_eq!(extra.field_offset("wave_index"), Some(0xac)); } /// The hand-maintained party-level layout must match the monolithic parser diff --git a/src/references/misc_item_db.rs b/src/references/misc_item_db.rs index 3c1ada87..087f989c 100644 --- a/src/references/misc_item_db.rs +++ b/src/references/misc_item_db.rs @@ -36,7 +36,10 @@ use dispel_macros::{Extractor, Localizable, RecordLayout, RecordPatcher}; /// | - name: 30 bytes (WINDOWS-1250) | /// | - description: 202 bytes (WINDOWS...) | /// | - base_price: i32 | -/// | - reserved_bytes: 16 bytes | +/// | - rune_mark_x: u32 | +/// | - rune_mark_y: u32 | +/// | - rune_mark_map_id: u32 | +/// | - unassigned_word: u32 | /// | - runtime_record_index_slot: i32 | /// +--------------------------------------+ /// | [Record 2] | @@ -72,9 +75,18 @@ pub struct MiscItem { /// Value retrieved when standard bartering. #[extractor(primitive(type = "i32"))] pub base_price: i32, - /// Unused bytes. - #[extractor(vec_u8(size = 16))] - pub reserved_bytes: Vec, + /// Rune mark X coordinate. + #[extractor(primitive(type = "u32"))] + pub rune_mark_x: u32, + /// Rune mark Y coordinate. + #[extractor(primitive(type = "u32"))] + pub rune_mark_y: u32, + /// Map id stored with the rune mark. + #[extractor(primitive(type = "u32"))] + pub rune_mark_map_id: u32, + /// Fourth tail word. No meaning is known for it. + #[extractor(primitive(type = "u32"))] + pub unassigned_word: u32, /// On-disk slot at offset `0xFC` for the runtime record index. /// /// During database loading, the game unconditionally replaces this value @@ -98,7 +110,10 @@ pub fn save_misc_items(conn: &mut Connection, misc_items: &[MiscItem]) -> Result item.name, item.description, item.base_price, - item.reserved_bytes, + item.rune_mark_x, + item.rune_mark_y, + item.rune_mark_map_id, + item.unassigned_word, item.runtime_record_index_slot, ])?; } @@ -135,10 +150,35 @@ mod tests { assert_eq!(items.len(), 1); assert_eq!(items[0].name, "Torch"); assert_eq!(items[0].base_price, 15); - assert_eq!(items[0].reserved_bytes, vec![0xA5; 16]); + assert_eq!(items[0].rune_mark_x, u32::from_ne_bytes([0xA5; 4])); + assert_eq!(items[0].rune_mark_y, u32::from_ne_bytes([0xA5; 4])); + assert_eq!(items[0].rune_mark_map_id, u32::from_ne_bytes([0xA5; 4])); + assert_eq!(items[0].unassigned_word, u32::from_ne_bytes([0xA5; 4])); assert_eq!(items[0].runtime_record_index_slot, 0x1234_5678); } + #[test] + fn test_misc_reserved_tail_exposes_four_words() { + let mut data = 1i32.to_le_bytes().to_vec(); + let mut rec = item_bytes("Invented Charm", 7); + rec[236..240].copy_from_slice(&0x1111_2222u32.to_le_bytes()); + rec[240..244].copy_from_slice(&0x3333_4444u32.to_le_bytes()); + rec[244..248].copy_from_slice(&0x5555_6666u32.to_le_bytes()); + rec[248..252].copy_from_slice(&0x7777_8888u32.to_le_bytes()); + data.extend(rec); + + let mut cursor = Cursor::new(&data[..]); + let items = MiscItem::parse(&mut cursor, data.len() as u64).unwrap(); + let json = serde_json::to_value(&items[0]).unwrap(); + let object = json.as_object().unwrap(); + + assert_eq!(object["rune_mark_x"], 0x1111_2222u32); + assert_eq!(object["rune_mark_y"], 0x3333_4444u32); + assert_eq!(object["rune_mark_map_id"], 0x5555_6666u32); + assert_eq!(object["unassigned_word"], 0x7777_8888u32); + assert!(!object.contains_key("reserved_bytes")); + } + #[test] fn serialize_round_trip() { let mut data = 1i32.to_le_bytes().to_vec(); diff --git a/src/references/save_file/game_tmp.rs b/src/references/save_file/game_tmp.rs index bd82d449..a18cc873 100644 --- a/src/references/save_file/game_tmp.rs +++ b/src/references/save_file/game_tmp.rs @@ -621,10 +621,7 @@ pub struct ExtraObjectRecord { pub reset_to_base_sprite_frame: u32, pub alternate_render_mode: u32, /// Wave.ini open-SFX index (record `+0xAC`). See `ExtraRef`. - pub open_sfx_id: u8, - /// Reserved byte after [`Self::open_sfx_id`]. Preserve it verbatim. - pub open_sfx_reserved: u8, - pub open_sfx_padding: i16, + pub wave_index: u32, /// Active-object overlay: 0=disabled, non-zero=enabled. pub active_overlay_enabled: u32, /// Map-grid/update participation: 0=inactive, non-zero=active. @@ -691,10 +688,12 @@ pub struct DrawItemMiscItem { pub name: String, // 30 #[binary_record(string(encoding = "WINDOWS-1250", size = 202))] pub description: String, // 232 - pub base_price: u32, // 236 - #[binary_record(size = 16)] - pub reserved_bytes: Vec, // 252 - pub misc_item_id: u32, // 256 + pub base_price: u32, // 236 + pub rune_mark_x: u32, // 240 + pub rune_mark_y: u32, // 244 + pub rune_mark_map_id: u32, // 248 + pub unassigned_word: u32, // 252 + pub misc_item_id: u32, // 256 pub map_coordinate_x: u32, // 260 coord-X pub map_coordinate_y: u32, // 264 coord-Y /// One-based encoded object ID used by the map's ground-item grid. diff --git a/src/references/save_file/tests.rs b/src/references/save_file/tests.rs index d5dac741..2d3bc3f8 100644 --- a/src/references/save_file/tests.rs +++ b/src/references/save_file/tests.rs @@ -386,16 +386,14 @@ fn test_npc_record_decodes_path_step_animation_state_at_exact_offsets() { #[test] fn test_extra_object_decodes_runtime_tail_at_exact_offsets() { let mut bytes = vec![0u8; 200]; - bytes[184] = 10; - bytes[185] = 0xa5; + bytes[184..188].copy_from_slice(&0x6164u32.to_le_bytes()); bytes[188..192].copy_from_slice(&1u32.to_le_bytes()); bytes[192..196].copy_from_slice(&1u32.to_le_bytes()); bytes[196..200].copy_from_slice(&1u32.to_le_bytes()); let parsed = super::ExtraObjectRecord::parse(&bytes).unwrap(); - assert_eq!(parsed.open_sfx_id, 10); - assert_eq!(parsed.open_sfx_reserved, 0xa5); + assert_eq!(parsed.wave_index, 0x6164); assert_eq!(parsed.active_overlay_enabled, 1); assert_eq!(parsed.map_object_active, 1); assert_eq!(parsed.interaction_pending, 1); From a5a7c47efce7835fcb7000650b8e06ca0ce4b206 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:13:16 +0100 Subject: [PATCH 68/72] refactor(core): name character field renames --- src/references/save_file/character.rs | 228 +++++++++++++------------- 1 file changed, 114 insertions(+), 114 deletions(-) diff --git a/src/references/save_file/character.rs b/src/references/save_file/character.rs index edd87fc7..5c3c7f96 100644 --- a/src/references/save_file/character.rs +++ b/src/references/save_file/character.rs @@ -260,20 +260,20 @@ impl CharacterData { /// /// Layout (all integers little-endian): /// `[5 × inventory_item_serial u16] -/// [current_action_id u32][waypoint_index u32][waypoint_count u32] +/// [animation_mode u32][waypoint_index u32][waypoint_count u32] /// [waypoint_data: waypoint_count × 8 bytes] -/// [move_requested u8][move_destination_x u32][move_destination_y u32] -/// [movement_blocked u8][teleport_mode u8][teleport_destination_pending u8] -/// [teleport_execution_pending u8][model_animation_index u16] -/// [teleport_target_x u32][teleport_target_y u32][teleport_target_value u32] -/// [stop_after_path_end u8][movement_sub_state u8][character_class u8] -/// [position_changed u8][global_object_id_counter u32] -/// [interaction_state u8][interaction_state_paired u8] -/// [warrior_offense_bonus u8][knight_defense_bonus u8][archer_dodge_rate_bonus u8] -/// [archer_hit_rate_bonus u8][mage_magic_power_bonus u8] -/// [action_index u32][pathfinding_scratch_a u32][pathfinding_scratch_b u32] -/// [reserved_500 u32][action_current_step u32][action_total_steps u32] -/// [position_x u32][position_y u32]` +/// [move_requested u8][click_target_x u32][click_target_y u32] +/// [store_ui_input_gate u8][spell_targeting_latch u8][warp_armed u8] +/// [warp_execute u8][status_form_sprite_id u16] +/// [teleport_target_x u32][teleport_target_y u32][destination_map_id u32] +/// [scripted_move_halt_at_arrival u8][scripted_move_mode u8][title_tier u8] +/// [self_target_latch u8][inventory_instance_id_next u32] +/// [ceremony_lock u8][freeze_latch u8] +/// [title_attack_bonus u8][title_defense_bonus u8][title_accuracy_bonus u8] +/// [title_dodge_bonus u8][title_magic_bonus u8] +/// [entity_action_state u32][pathfinding_scratch_a u32][pathfinding_scratch_b u32] +/// [reserved_500 u32][animation_step_index u32][animation_step_limit u32] +/// [screen_anchor_x u32][screen_anchor_y u32]` #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct CharacterState { /// Next-slot serial for the Event item category. Each new item in the @@ -296,7 +296,7 @@ pub struct CharacterState { /// Current scripted action (0–7), or −1 when idle. Drives scripted /// movement and action sequences. - pub current_action_id: u32, + pub animation_mode: u32, /// Index of the current waypoint in the path being followed. pub waypoint_index: u32, @@ -313,25 +313,25 @@ pub struct CharacterState { pub move_requested: u8, /// Destination tile X of the requested move. - pub move_destination_x: u32, + pub click_target_x: u32, /// Destination tile Y of the requested move. - pub move_destination_y: u32, + pub click_target_y: u32, /// Set while movement is blocked (event or cutscene in progress). - pub movement_blocked: u8, + pub store_ui_input_gate: u8, /// Teleport mode selector. - pub teleport_mode: u8, + pub spell_targeting_latch: u8, /// Set when a teleport destination has been queued. - pub teleport_destination_pending: u8, + pub warp_armed: u8, /// Set when the queued teleport is about to execute. - pub teleport_execution_pending: u8, + pub warp_execute: u8, /// Index into the model animation table used to render the character. - pub model_animation_index: u16, + pub status_form_sprite_id: u16, /// Teleport target tile X. pub teleport_target_x: u32, @@ -340,48 +340,48 @@ pub struct CharacterState { pub teleport_target_y: u32, /// Teleport target value. - pub teleport_target_value: u32, + pub destination_map_id: u32, /// Set to stop the character once the waypoint path is exhausted. - pub stop_after_path_end: u8, + pub scripted_move_halt_at_arrival: u8, /// Movement sub-state: 0=idle, 1=started, 2=walking, 3=arrived. - pub movement_sub_state: u8, + pub scripted_move_mode: u8, - /// Character class: 1=Paladin, 2=Hero. Derived from the morale + /// Character class: 1=Paladin, 2=Hero. Derived from the karma /// (good/evil path), the class, and the level. - pub character_class: u8, + pub title_tier: u8, /// Latch set when the position changed; used to sync the position to /// the character's map coordinates. - pub position_changed: u8, + pub self_target_latch: u8, /// Monotonic counter of spawned world objects. - pub global_object_id_counter: u32, + pub inventory_instance_id_next: u32, /// Current interaction state. - pub interaction_state: u8, + pub ceremony_lock: u8, /// Paired interaction state. - pub interaction_state_paired: u8, + pub freeze_latch: u8, /// Offense stat bonus applied to the Warrior class. - pub warrior_offense_bonus: u8, + pub title_attack_bonus: u8, /// Defense stat bonus applied to the Knight class. - pub knight_defense_bonus: u8, + pub title_defense_bonus: u8, /// Dodge-rate stat bonus applied to the Archer class. - pub archer_dodge_rate_bonus: u8, + pub title_accuracy_bonus: u8, /// Hit-rate stat bonus applied to the Archer class. - pub archer_hit_rate_bonus: u8, + pub title_dodge_bonus: u8, /// Magic-power stat bonus applied to the Mage class. - pub mage_magic_power_bonus: u8, + pub title_magic_bonus: u8, /// Index of the current action. - pub action_index: u32, + pub entity_action_state: u32, /// Transient pathfinding scratch value. pub pathfinding_scratch_a: u32, @@ -414,7 +414,7 @@ impl CharacterState { let weapon_items_serial = reader.read_u16::()?; let heal_items_serial = reader.read_u16::()?; - let current_action_id = reader.read_u32::()?; + let animation_mode = reader.read_u32::()?; let waypoint_index = reader.read_u32::()?; let waypoint_count = reader.read_u32::()?; @@ -422,36 +422,36 @@ impl CharacterState { reader.read_exact(&mut waypoint_data)?; let move_requested = reader.read_u8()?; - let move_destination_x = reader.read_u32::()?; - let move_destination_y = reader.read_u32::()?; - let movement_blocked = reader.read_u8()?; - let teleport_mode = reader.read_u8()?; - let teleport_destination_pending = reader.read_u8()?; - let teleport_execution_pending = reader.read_u8()?; - let model_animation_index = reader.read_u16::()?; + let click_target_x = reader.read_u32::()?; + let click_target_y = reader.read_u32::()?; + let store_ui_input_gate = reader.read_u8()?; + let spell_targeting_latch = reader.read_u8()?; + let warp_armed = reader.read_u8()?; + let warp_execute = reader.read_u8()?; + let status_form_sprite_id = reader.read_u16::()?; let teleport_target_x = reader.read_u32::()?; let teleport_target_y = reader.read_u32::()?; - let teleport_target_value = reader.read_u32::()?; - let stop_after_path_end = reader.read_u8()?; - let movement_sub_state = reader.read_u8()?; - let character_class = reader.read_u8()?; - let position_changed = reader.read_u8()?; - let global_object_id_counter = reader.read_u32::()?; - let interaction_state = reader.read_u8()?; - let interaction_state_paired = reader.read_u8()?; - let warrior_offense_bonus = reader.read_u8()?; - let knight_defense_bonus = reader.read_u8()?; - let archer_dodge_rate_bonus = reader.read_u8()?; - let archer_hit_rate_bonus = reader.read_u8()?; - let mage_magic_power_bonus = reader.read_u8()?; - let action_index = reader.read_u32::()?; + let destination_map_id = reader.read_u32::()?; + let scripted_move_halt_at_arrival = reader.read_u8()?; + let scripted_move_mode = reader.read_u8()?; + let title_tier = reader.read_u8()?; + let self_target_latch = reader.read_u8()?; + let inventory_instance_id_next = reader.read_u32::()?; + let ceremony_lock = reader.read_u8()?; + let freeze_latch = reader.read_u8()?; + let title_attack_bonus = reader.read_u8()?; + let title_defense_bonus = reader.read_u8()?; + let title_accuracy_bonus = reader.read_u8()?; + let title_dodge_bonus = reader.read_u8()?; + let title_magic_bonus = reader.read_u8()?; + let entity_action_state = reader.read_u32::()?; let pathfinding_scratch_a = reader.read_u32::()?; let pathfinding_scratch_b = reader.read_u32::()?; let reserved_500 = reader.read_u32::()?; - let action_current_step = reader.read_u32::()?; - let action_total_steps = reader.read_u32::()?; - let position_x = reader.read_u32::()?; - let position_y = reader.read_u32::()?; + let animation_step_index = reader.read_u32::()?; + let animation_step_limit = reader.read_u32::()?; + let screen_anchor_x = reader.read_u32::()?; + let screen_anchor_y = reader.read_u32::()?; Ok(Self { event_items_serial, @@ -459,41 +459,41 @@ impl CharacterState { edit_items_serial, weapon_items_serial, heal_items_serial, - current_action_id, + animation_mode, waypoint_index, waypoint_count, waypoint_data, move_requested, - move_destination_x, - move_destination_y, - movement_blocked, - teleport_mode, - teleport_destination_pending, - teleport_execution_pending, - model_animation_index, + click_target_x, + click_target_y, + store_ui_input_gate, + spell_targeting_latch, + warp_armed, + warp_execute, + status_form_sprite_id, teleport_target_x, teleport_target_y, - teleport_target_value, - stop_after_path_end, - movement_sub_state, - character_class, - position_changed, - global_object_id_counter, - interaction_state, - interaction_state_paired, - warrior_offense_bonus, - knight_defense_bonus, - archer_dodge_rate_bonus, - archer_hit_rate_bonus, - mage_magic_power_bonus, - action_index, + destination_map_id, + scripted_move_halt_at_arrival, + scripted_move_mode, + title_tier, + self_target_latch, + inventory_instance_id_next, + ceremony_lock, + freeze_latch, + title_attack_bonus, + title_defense_bonus, + title_accuracy_bonus, + title_dodge_bonus, + title_magic_bonus, + entity_action_state, pathfinding_scratch_a, pathfinding_scratch_b, reserved_500, - action_current_step, - action_total_steps, - position_x, - position_y, + animation_step_index, + animation_step_limit, + screen_anchor_x, + screen_anchor_y, }) } @@ -504,42 +504,42 @@ impl CharacterState { writer.write_u16::(self.weapon_items_serial)?; writer.write_u16::(self.heal_items_serial)?; - writer.write_u32::(self.current_action_id)?; + writer.write_u32::(self.animation_mode)?; writer.write_u32::(self.waypoint_index)?; writer.write_u32::(self.waypoint_count)?; writer.write_all(&self.waypoint_data)?; writer.write_u8(self.move_requested)?; - writer.write_u32::(self.move_destination_x)?; - writer.write_u32::(self.move_destination_y)?; - writer.write_u8(self.movement_blocked)?; - writer.write_u8(self.teleport_mode)?; - writer.write_u8(self.teleport_destination_pending)?; - writer.write_u8(self.teleport_execution_pending)?; - writer.write_u16::(self.model_animation_index)?; + writer.write_u32::(self.click_target_x)?; + writer.write_u32::(self.click_target_y)?; + writer.write_u8(self.store_ui_input_gate)?; + writer.write_u8(self.spell_targeting_latch)?; + writer.write_u8(self.warp_armed)?; + writer.write_u8(self.warp_execute)?; + writer.write_u16::(self.status_form_sprite_id)?; writer.write_u32::(self.teleport_target_x)?; writer.write_u32::(self.teleport_target_y)?; - writer.write_u32::(self.teleport_target_value)?; - writer.write_u8(self.stop_after_path_end)?; - writer.write_u8(self.movement_sub_state)?; - writer.write_u8(self.character_class)?; - writer.write_u8(self.position_changed)?; - writer.write_u32::(self.global_object_id_counter)?; - writer.write_u8(self.interaction_state)?; - writer.write_u8(self.interaction_state_paired)?; - writer.write_u8(self.warrior_offense_bonus)?; - writer.write_u8(self.knight_defense_bonus)?; - writer.write_u8(self.archer_dodge_rate_bonus)?; - writer.write_u8(self.archer_hit_rate_bonus)?; - writer.write_u8(self.mage_magic_power_bonus)?; - writer.write_u32::(self.action_index)?; + writer.write_u32::(self.destination_map_id)?; + writer.write_u8(self.scripted_move_halt_at_arrival)?; + writer.write_u8(self.scripted_move_mode)?; + writer.write_u8(self.title_tier)?; + writer.write_u8(self.self_target_latch)?; + writer.write_u32::(self.inventory_instance_id_next)?; + writer.write_u8(self.ceremony_lock)?; + writer.write_u8(self.freeze_latch)?; + writer.write_u8(self.title_attack_bonus)?; + writer.write_u8(self.title_defense_bonus)?; + writer.write_u8(self.title_accuracy_bonus)?; + writer.write_u8(self.title_dodge_bonus)?; + writer.write_u8(self.title_magic_bonus)?; + writer.write_u32::(self.entity_action_state)?; writer.write_u32::(self.pathfinding_scratch_a)?; writer.write_u32::(self.pathfinding_scratch_b)?; writer.write_u32::(self.reserved_500)?; - writer.write_u32::(self.action_current_step)?; - writer.write_u32::(self.action_total_steps)?; - writer.write_u32::(self.position_x)?; - writer.write_u32::(self.position_y)?; + writer.write_u32::(self.animation_step_index)?; + writer.write_u32::(self.animation_step_limit)?; + writer.write_u32::(self.screen_anchor_x)?; + writer.write_u32::(self.screen_anchor_y)?; Ok(()) } From 9ca42a201ce5730c8871a2833d2b38d8d5e34f68 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:14:23 +0100 Subject: [PATCH 69/72] refactor(core): name monster data fields from saves --- .../src/editors/save_file_viewer/state.rs | 2 +- .../save_file_viewer/update/csv_export.rs | 2 +- .../editors/save_file_viewer/update/mod.rs | 2 +- src/references/save_file/game_tmp.rs | 2 +- src/references/save_file/tests.rs | 31 +++++++++++++++++++ 5 files changed, 35 insertions(+), 4 deletions(-) diff --git a/dispel-gui/src/editors/save_file_viewer/state.rs b/dispel-gui/src/editors/save_file_viewer/state.rs index 60fbc34e..8d0681d0 100644 --- a/dispel-gui/src/editors/save_file_viewer/state.rs +++ b/dispel-gui/src/editors/save_file_viewer/state.rs @@ -100,7 +100,7 @@ impl MapsTableKind { use MapsTableKind::*; let defs: &[(&str, f32)] = match self { Monsters => &[ - ("monster_state", 60.0), + ("ai_action_state", 60.0), ("record_index", 60.0), ("sprite_frame_id", 60.0), ("name", 160.0), diff --git a/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs b/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs index 5014fdc6..47389afc 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs @@ -131,7 +131,7 @@ fn stable_csv_keys(key: TableKey) -> &'static [&'static str] { "is_completed", ], TableKey::Map(_, MapsTableKind::Monsters) => &[ - "monster_state", + "ai_action_state", "record_index", "sprite_frame_id", "name", diff --git a/dispel-gui/src/editors/save_file_viewer/update/mod.rs b/dispel-gui/src/editors/save_file_viewer/update/mod.rs index 577fd97e..f816db3d 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/mod.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/mod.rs @@ -1360,7 +1360,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { .iter() .map(|m| { vec![ - m.monster_state.to_string(), + m.ai_action_state.to_string(), m.record_index.to_string(), m.sprite_frame_id.to_string(), m.name.clone(), diff --git a/src/references/save_file/game_tmp.rs b/src/references/save_file/game_tmp.rs index a18cc873..916ccde8 100644 --- a/src/references/save_file/game_tmp.rs +++ b/src/references/save_file/game_tmp.rs @@ -233,7 +233,7 @@ pub(super) fn write_maps(maps: &[MapSectionData], writer: &mut W) -> s #[derive(Debug, Clone, Serialize, Deserialize, Default, BinaryRecord)] pub struct MonsterRecord { /// Runtime state. Zero is alive, one appears to be patrolling, and eight is dead. - pub monster_state: u32, + pub ai_action_state: u32, /// Index of this monster in the map record list. pub record_index: u32, /// ID of the current sprite frame. diff --git a/src/references/save_file/tests.rs b/src/references/save_file/tests.rs index 2d3bc3f8..409d3563 100644 --- a/src/references/save_file/tests.rs +++ b/src/references/save_file/tests.rs @@ -329,6 +329,37 @@ fn test_monster_record_decodes_runtime_subsystems_at_exact_offsets() { assert_eq!(output, bytes); } +#[test] +fn test_monster_renamed_fields_keep_bytes() { + let mut record = MonsterRecord::parse(&[0u8; super::game_tmp::MONSTER_RECORD_SIZE]).unwrap(); + record.ai_action_state = 7; + record.polymorph_transition_gate = 1; + record.path_target_x = 11; + record.path_target_y = 12; + record.polymorph_form_present = 1; + record.path_waypoint_x = 13; + record.path_waypoint_y = 14; + record.flee_throttle = 9; + + let mut encoded = Vec::new(); + record.write(&mut encoded).unwrap(); + assert_eq!(encoded.len(), super::game_tmp::MONSTER_RECORD_SIZE); + + let parsed = MonsterRecord::parse(&encoded).unwrap(); + assert_eq!(parsed.ai_action_state, 7); + assert_eq!(parsed.polymorph_transition_gate, 1); + assert_eq!(parsed.path_target_y, 12); + assert_eq!(parsed.polymorph_form_present, 1); + assert_eq!(parsed.path_waypoint_x, 13); + assert_eq!(parsed.path_waypoint_y, 14); + assert_eq!(parsed.flee_throttle, 9); + assert_eq!(parsed.polymorph_form_record.len(), 72); + + let mut again = Vec::new(); + parsed.write(&mut again).unwrap(); + assert_eq!(again, encoded); +} + #[test] fn test_ground_item_records_decode_trailing_object_id_and_padding() { macro_rules! assert_trailing_id { From bd0e516f353d4e650a26538555f35b17afa43b0b Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:16:44 +0100 Subject: [PATCH 70/72] feat(gui): add runtime, snapshot and session views from saves --- .../src/editors/save_file_viewer/character.rs | 94 ++++++++ .../src/editors/save_file_viewer/events.rs | 97 ++++++++- .../src/editors/save_file_viewer/helpers.rs | 21 ++ .../src/editors/save_file_viewer/journal.rs | 50 ++++- .../src/editors/save_file_viewer/message.rs | 11 +- .../editors/save_file_viewer/party_members.rs | 69 +++++- .../src/editors/save_file_viewer/state.rs | 71 ++++++ .../save_file_viewer/update/csv_export.rs | 76 ++++++- .../editors/save_file_viewer/update/filter.rs | 63 ++++++ .../editors/save_file_viewer/update/mod.rs | 202 ++++++++++++++++++ .../editors/save_file_viewer/update/table.rs | 23 ++ .../src/editors/save_file_viewer/view.rs | 3 + 12 files changed, 763 insertions(+), 17 deletions(-) diff --git a/dispel-gui/src/editors/save_file_viewer/character.rs b/dispel-gui/src/editors/save_file_viewer/character.rs index f608eb7c..c26aadbd 100644 --- a/dispel-gui/src/editors/save_file_viewer/character.rs +++ b/dispel-gui/src/editors/save_file_viewer/character.rs @@ -15,6 +15,100 @@ use crate::style; use gui_widgets::components::modal; use gui_widgets::{RowFlags, TableWidget}; +use crate::editors::save_file_viewer::helpers::{label_row, read_only_table, section_header}; + +/// Read-only runtime scalars and waypoint table from the character state block. +pub fn runtime_view<'a>(state: &'a SaveFileViewerState) -> Element<'a, Message> { + use iced::widget::{Column, scrollable}; + + let Some(save) = state.save_file.as_ref() else { + return container(text("Character runtime data is unavailable")) + .width(Fill) + .height(Fill) + .padding(16) + .into(); + }; + let runtime = &save.character_state; + let mut body = Column::::new() + .push(section_header("Runtime and Navigation")) + .push(label_row( + "Item serials", + format!( + "event {} · misc {} · edit {} · weapon {} · heal {}", + runtime.event_items_serial, + runtime.misc_items_serial, + runtime.edit_items_serial, + runtime.weapon_items_serial, + runtime.heal_items_serial + ), + )) + .push(label_row( + "Path cursor / count", + format!("{} / {}", runtime.waypoint_index, runtime.waypoint_count), + )) + .push(label_row( + "Click target", + format!("{} , {}", runtime.click_target_x, runtime.click_target_y), + )) + .push(label_row( + "Movement / store gate", + format!( + "{} / {}", + runtime.move_requested, runtime.store_ui_input_gate + ), + )) + .push(label_row( + "Spell target latch", + runtime.spell_targeting_latch.to_string(), + )) + .push(label_row( + "Warp armed / execute", + format!("{} / {}", runtime.warp_armed, runtime.warp_execute), + )) + .push(label_row( + "Title bonuses", + format!( + "atk {} · def {} · acc {} · dodge {} · magic {}", + runtime.title_attack_bonus, + runtime.title_defense_bonus, + runtime.title_accuracy_bonus, + runtime.title_dodge_bonus, + runtime.title_magic_bonus + ), + )) + .push(label_row( + "Screen anchor", + format!("{} , {}", runtime.screen_anchor_x, runtime.screen_anchor_y), + )) + .push(label_row( + "Status form id", + runtime.status_form_sprite_id.to_string(), + )) + .push(label_row( + "Instance id next", + runtime.inventory_instance_id_next.to_string(), + )) + .push(label_row( + "Waypoint nodes", + (runtime.waypoint_data.len() / 8).to_string(), + )) + .push(section_header("Waypoints")) + .spacing(4) + .padding(12); + + if state.waypoint_cache.is_empty() { + body = body.push(text("(no waypoints)")); + } else { + body = body.push(read_only_table( + &state.waypoint_cache, + &state.waypoint_indices, + crate::editors::save_file_viewer::state::waypoint_columns(), + state.paragraph_cache.clone(), + )); + } + scrollable(body).height(Fill).into() +} + /// Character section: kind buttons + TableWidget per character table. pub fn view<'a>(state: &'a SaveFileViewerState) -> Element<'a, Message> { let active = state.character_kind; diff --git a/dispel-gui/src/editors/save_file_viewer/events.rs b/dispel-gui/src/editors/save_file_viewer/events.rs index 64efcf1a..e135493e 100644 --- a/dispel-gui/src/editors/save_file_viewer/events.rs +++ b/dispel-gui/src/editors/save_file_viewer/events.rs @@ -12,8 +12,98 @@ use crate::message::MessageExt; use gui_widgets::components::modal; use gui_widgets::{RowFlags, TableWidget}; -/// Events section: virtualized table of event script records. +use crate::editors::save_file_viewer::helpers::{label_row, read_only_table, section_header}; +use crate::editors::save_file_viewer::state::EventsSubView; +use crate::style; + +/// Render the decoded session state under Events. +fn session_view<'a>(state: &'a SaveFileViewerState) -> Element<'a, Message> { + use iced::widget::{Column, scrollable}; + + let Some(save) = state.save_file.as_ref() else { + return container(text("No session state loaded")) + .width(Fill) + .padding(16) + .into(); + }; + let events = &save.post_events; + let mut body = Column::::new() + .push(section_header("Events Session State")) + .push(label_row( + "Shake", + format!( + "active {} · frames {}", + events.shake_active, events.shake_frames_remaining + ), + )) + .push(section_header("Walk Milestones")) + .push(read_only_table( + &state.walk_milestone_cache, + &state.walk_milestone_indices, + crate::editors::save_file_viewer::state::walk_milestone_columns(), + state.paragraph_cache.clone(), + )) + .push(section_header("Walk Completions")) + .push(read_only_table( + &state.walk_completion_cache, + &state.walk_completion_indices, + crate::editors::save_file_viewer::state::walk_completion_columns(), + state.paragraph_cache.clone(), + )) + .push(section_header("Companion Status")) + .spacing(4) + .padding(12); + + for (index, value) in events + .recruitable_companion_world_presence + .iter() + .enumerate() + { + body = body.push(label_row( + format!("Companion {}", index + 1), + value.to_string(), + )); + } + scrollable(body).height(Fill).into() +} + +/// Events section: sub-tabs plus either the session view or the script table. pub fn view<'a>(state: &'a SaveFileViewerState) -> Element<'a, Message> { + let sub_buttons = iced::widget::Row::new() + .push({ + let mut btn = iced::widget::button(text("Scripts").size(12)); + if state.events_sub_view == EventsSubView::Scripts { + btn = btn.style(style::active_tab_button); + } else { + btn = btn.style(style::tab_button); + } + btn.on_press(Message::save_file_viewer( + SaveFileViewerMessage::SelectEventsSubView(EventsSubView::Scripts), + )) + .padding([4, 8]) + }) + .push({ + let mut btn = iced::widget::button(text("Session").size(12)); + if state.events_sub_view == EventsSubView::Session { + btn = btn.style(style::active_tab_button); + } else { + btn = btn.style(style::tab_button); + } + btn.on_press(Message::save_file_viewer( + SaveFileViewerMessage::SelectEventsSubView(EventsSubView::Session), + )) + .padding([4, 8]) + }) + .spacing(4) + .padding(8); + + if state.events_sub_view == EventsSubView::Session { + return iced::widget::Column::new() + .push(sub_buttons) + .push(session_view(state)) + .into(); + } + let n = state.events_filtered_indices.len(); if n == 0 { return container(text("No events")) @@ -136,6 +226,7 @@ pub fn view<'a>(state: &'a SaveFileViewerState) -> Element<'a, Message> { let content = iced::widget::column![filter_bar, table_element].spacing(8); + let with_tabs = iced::widget::Column::new().push(sub_buttons).push(content); if let Some(col) = filter.active_column_filter { let modal_content = filter::build_column_filter_modal( col, @@ -145,12 +236,12 @@ pub fn view<'a>(state: &'a SaveFileViewerState) -> Element<'a, Message> { filter_msg_fn, ); modal::modal( - content, + with_tabs, modal_content, move || filter_msg_fn(ColumnFilterAction::CloseColumnFilterModal), 0.5, ) } else { - content.into() + with_tabs.into() } } diff --git a/dispel-gui/src/editors/save_file_viewer/helpers.rs b/dispel-gui/src/editors/save_file_viewer/helpers.rs index 2419f264..904199d5 100644 --- a/dispel-gui/src/editors/save_file_viewer/helpers.rs +++ b/dispel-gui/src/editors/save_file_viewer/helpers.rs @@ -4,6 +4,27 @@ use iced::widget::{Row, container, text}; use iced::{Element, Fill}; use crate::message::Message; +use gui_widgets::components::paragraph_cache::ParagraphCache; +use gui_widgets::{RowFlags, TableColumn, TableWidget}; + +/// Render a table whose rows come from the loaded save and never change. +pub fn read_only_table<'a>( + rows: &'a [Vec], + indices: &'a [usize], + columns: Vec, + paragraph_cache: ParagraphCache, +) -> Element<'a, Message> { + TableWidget::new( + rows, + indices, + columns, + 0.0, + |_| RowFlags::default(), + 22.0, + paragraph_cache, + ) + .into() +} /// Section header label (e.g. "Core Attributes", "Combat Stats"). pub fn section_header(label: &str) -> Element<'static, Message> { diff --git a/dispel-gui/src/editors/save_file_viewer/journal.rs b/dispel-gui/src/editors/save_file_viewer/journal.rs index d48866a3..5d4d862e 100644 --- a/dispel-gui/src/editors/save_file_viewer/journal.rs +++ b/dispel-gui/src/editors/save_file_viewer/journal.rs @@ -13,8 +13,50 @@ use crate::style; use gui_widgets::components::modal; use gui_widgets::{RowFlags, TableWidget}; -/// Journal section: sub-tabs (Main/Side/Trade) + table per section. +/// Journal section: header panel, sub-tabs (Main/Side/Trade) + table per section. pub fn view<'a>(state: &'a SaveFileViewerState) -> Element<'a, Message> { + let header_panel = match state.save_file.as_ref() { + Some(save) => { + use crate::editors::save_file_viewer::helpers::{label_row, section_header}; + let header = &save.journal.header; + let marker = &header.map_marker_discovery; + let flags: Vec = marker + .layer_0 + .iter() + .chain(marker.layer_1.iter()) + .chain(marker.layer_2.iter()) + .map(|flag| flag.to_string()) + .collect(); + iced::widget::Column::new() + .push(section_header("Journal Header")) + .push(label_row("View mode", header.is_world_map_open.to_string())) + .push(label_row( + "Selected layer", + header.selected_map_layer.to_string(), + )) + .push(label_row( + "Active section", + header.active_section.to_string(), + )) + .push(label_row( + "First visible", + format!("{:?}", header.section_first_visible_entries), + )) + .push(label_row( + "Selected rows", + format!("{:?}", header.section_selected_entries), + )) + .push(label_row( + "Entry counts", + format!("{:?}", header.section_entry_counts), + )) + .push(label_row("Marker flags", flags.join(" "))) + .spacing(2) + .padding(8) + } + None => iced::widget::Column::new(), + }; + // Sub-tab bar let sections = [ (JournalSection::Main, "Main"), @@ -190,5 +232,9 @@ pub fn view<'a>(state: &'a SaveFileViewerState) -> Element<'a, Message> { _ => container(text("No entries")).width(Fill).padding(16).into(), }; - Column::::new().push(tab_bar).push(table).into() + Column::::new() + .push(header_panel) + .push(tab_bar) + .push(table) + .into() } diff --git a/dispel-gui/src/editors/save_file_viewer/message.rs b/dispel-gui/src/editors/save_file_viewer/message.rs index 1c7386cf..7f56dec1 100644 --- a/dispel-gui/src/editors/save_file_viewer/message.rs +++ b/dispel-gui/src/editors/save_file_viewer/message.rs @@ -4,7 +4,8 @@ use std::path::PathBuf; use crate::components::filter::{ColumnFilterAction, GlobalFilterMode}; use crate::editors::save_file_viewer::map_preview::PreviewMessage; use crate::editors::save_file_viewer::state::{ - CharacterTableKind, InventoryCategory, JournalSection, MapsTableKind, SaveFileSection, + CharacterTableKind, EventsSubView, InventoryCategory, JournalSection, MapsTableKind, + SaveFileSection, }; /// Messages for the save file viewer. @@ -17,6 +18,8 @@ pub enum SaveFileViewerMessage { Loaded(usize, Result), /// Switch to a different section. SelectSection(SaveFileSection), + /// Switch between the event script table and the session sub-view. + SelectEventsSubView(EventsSubView), /// Select an inventory category to view. SelectCategory(InventoryCategory), /// Select a character table (equipment/belt/inventory placement) to view. @@ -179,6 +182,12 @@ pub enum TableKey { Events, /// A journal table for one sub-section. Journal(JournalSection), + /// Waypoint nodes from the character runtime block. + Waypoints, + /// Decoded post-event walk milestones. + WalkMilestones, + /// Decoded post-event walk completions. + WalkCompletions, } /// Filtering actions shared by every viewer table (mirrors the spreadsheet editor). diff --git a/dispel-gui/src/editors/save_file_viewer/party_members.rs b/dispel-gui/src/editors/save_file_viewer/party_members.rs index cd50c943..54781b22 100644 --- a/dispel-gui/src/editors/save_file_viewer/party_members.rs +++ b/dispel-gui/src/editors/save_file_viewer/party_members.rs @@ -36,14 +36,67 @@ pub fn view<'a>(state: &'a SaveFileViewerState) -> Element<'a, Message> { "Party Members Count", sf.party_members_count.to_string(), )) - .push(Column::new().spacing(4).push(match party_members.first() { - Some(member) => party_member_block(member), - None => text("No party member in slot 1").into(), - })) - .push(Column::new().spacing(4).push(match party_members.get(1) { - Some(member) => party_member_block(member), - None => text("No party member in slot 2").into(), - })) + .push(section_header("Combat Snapshots")) + .push(party_members.iter().enumerate().fold( + Column::new().spacing(4), + |column, (index, member)| { + column.push(label_row( + format!("Slot {}", index + 1), + member.name.clone(), + )) + }, + )) + .push(party_members.iter().enumerate().fold( + Column::new().spacing(4), + |column, (index, member)| { + column + .push(text(format!("Member {} — {}", index + 1, member.name))) + .push(party_member_block(member)) + .push(match &member.combat_snapshot { + Some(snapshot) => Column::new() + .push(label_row( + "Form HP", + format!( + "{} / {}", + snapshot.current_health_points, + snapshot.maximum_health_points + ), + )) + .push(label_row( + "Form stats", + format!( + "agi {} · atk {} · str {} · con {} · wis {}", + snapshot.agility, + snapshot.attack, + snapshot.strength, + snapshot.constitution, + snapshot.wisdom + ), + )) + .push(label_row( + "Form behaviour", + format!( + "class {} · scan {}", + snapshot.class_behaviour, snapshot.ai_target_search_range + ), + )) + .push(label_row( + "Form spells", + format!( + "{}, {}, {}", + snapshot.magic_spell_id_1, + snapshot.magic_spell_id_2, + snapshot.magic_spell_id_3 + ), + )) + .push(label_row( + "Form terminator", + snapshot.terminator.to_string(), + )), + None => Column::new().push(label_row("Polymorph form", "absent")), + }) + }, + )) .spacing(8) .padding(16), ) diff --git a/dispel-gui/src/editors/save_file_viewer/state.rs b/dispel-gui/src/editors/save_file_viewer/state.rs index 8d0681d0..1fb63910 100644 --- a/dispel-gui/src/editors/save_file_viewer/state.rs +++ b/dispel-gui/src/editors/save_file_viewer/state.rs @@ -18,6 +18,7 @@ pub enum SaveFileSection { Inventory, PartyMembers, Character, + Runtime, Events, Journal, Raw, @@ -34,6 +35,7 @@ impl SaveFileSection { SaveFileSection::Inventory => "Inventory", SaveFileSection::PartyMembers => "Party Members", SaveFileSection::Character => "Character", + SaveFileSection::Runtime => "Runtime", SaveFileSection::Events => "Events", SaveFileSection::Journal => "Journal", SaveFileSection::Raw => "Raw", @@ -51,6 +53,7 @@ impl SaveFileSection { Inventory, PartyMembers, Character, + Runtime, Events, Journal, Raw, @@ -64,6 +67,13 @@ pub struct RawHexViewer { pub state: HexEditorState, } +/// Sub-view shown inside the Events section. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EventsSubView { + Scripts, + Session, +} + /// Identifies one of the entity tables rendered for a map. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum MapsTableKind { @@ -550,11 +560,52 @@ pub struct MapsDisplayCaches { pub draw_items_event_indices: Vec, } +/// Columns for the read-only waypoint table. +pub fn waypoint_columns() -> Vec { + ["#", "x", "y", "raw"] + .into_iter() + .map(|label| TableColumn { + width_px: 60.0, + label: label.to_string(), + sort: None, + has_filter: false, + }) + .collect() +} + +/// Columns for the decoded walk milestone table. +pub fn walk_milestone_columns() -> Vec { + ["decal bucket", "direction", "state", "class", "x", "y"] + .into_iter() + .map(|label| TableColumn { + width_px: 80.0, + label: label.to_string(), + sort: None, + has_filter: false, + }) + .collect() +} + +/// Columns for the decoded walk completion table. +pub fn walk_completion_columns() -> Vec { + ["value", "direction", "diagonal", "sprite", "x", "y"] + .into_iter() + .map(|label| TableColumn { + width_px: 80.0, + label: label.to_string(), + sort: None, + has_filter: false, + }) + .collect() +} + /// State for a single save file viewer tab. pub struct SaveFileViewerState { pub save_file: Option, pub raw_hex_viewers: Vec, pub active_section: SaveFileSection, + /// Which sub-view the Events section shows. + pub events_sub_view: EventsSubView, /// Map ID → display name lookup from AllMap.ini (empty if unavailable). pub map_name_lookup: HashMap, pub loading: bool, @@ -598,6 +649,16 @@ pub struct SaveFileViewerState { pub character_table_states: HashMap, // Events table interaction state (single table). pub events_table_state: TableInteractionState, + // Read-only runtime and post-event tables. + pub waypoint_cache: Vec>, + pub waypoint_indices: Vec, + pub waypoint_table_state: TableInteractionState, + pub walk_milestone_cache: Vec>, + pub walk_milestone_indices: Vec, + pub walk_milestone_table_state: TableInteractionState, + pub walk_completion_cache: Vec>, + pub walk_completion_indices: Vec, + pub walk_completion_table_state: TableInteractionState, // Journal table interaction state, keyed by section. pub journal_table_states: HashMap, // Maps display caches (built on load, one per map at positional index) @@ -624,6 +685,7 @@ impl Default for SaveFileViewerState { save_file: None, raw_hex_viewers: Vec::new(), active_section: SaveFileSection::Overview, + events_sub_view: EventsSubView::Scripts, map_name_lookup: HashMap::new(), loading: false, error: None, @@ -646,6 +708,15 @@ impl Default for SaveFileViewerState { character_filtered_indices: HashMap::new(), character_table_states: HashMap::new(), events_table_state: TableInteractionState::default(), + waypoint_cache: Vec::new(), + waypoint_indices: Vec::new(), + waypoint_table_state: TableInteractionState::default(), + walk_milestone_cache: Vec::new(), + walk_milestone_indices: Vec::new(), + walk_milestone_table_state: TableInteractionState::default(), + walk_completion_cache: Vec::new(), + walk_completion_indices: Vec::new(), + walk_completion_table_state: TableInteractionState::default(), journal_table_states: HashMap::new(), maps_display_caches: Vec::new(), maps_table_states: Vec::new(), diff --git a/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs b/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs index 47389afc..319ee60f 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/csv_export.rs @@ -444,6 +444,9 @@ fn stable_csv_keys(key: TableKey) -> &'static [&'static str] { "ground_item_object_id", "ground_item_object_id_padding", ], + TableKey::Waypoints => &["#", "x", "y", "raw"], + TableKey::WalkMilestones => &["decal bucket", "direction", "state", "class", "x", "y"], + TableKey::WalkCompletions => &["value", "direction", "diagonal", "sprite", "x", "y"], TableKey::Map(_, MapsTableKind::Event) => &[ "name", "description", @@ -478,6 +481,9 @@ pub fn csv_default_filename(key: TableKey) -> String { format!("character-{label}.csv") } TableKey::Events => "events.csv".to_string(), + TableKey::Waypoints => "waypoints.csv".to_string(), + TableKey::WalkMilestones => "walk-milestones.csv".to_string(), + TableKey::WalkCompletions => "walk-completions.csv".to_string(), TableKey::Journal(section) => { let label = match section { JournalSection::Main => "main", @@ -548,6 +554,30 @@ pub fn resolve_csv_export_data( .collect(); Some((headers, rows)) } + TableKey::Waypoints => Some(( + csv_headers(TableKey::Waypoints), + state + .waypoint_indices + .iter() + .filter_map(|&i| state.waypoint_cache.get(i).cloned()) + .collect(), + )), + TableKey::WalkMilestones => Some(( + csv_headers(TableKey::WalkMilestones), + state + .walk_milestone_indices + .iter() + .filter_map(|&i| state.walk_milestone_cache.get(i).cloned()) + .collect(), + )), + TableKey::WalkCompletions => Some(( + csv_headers(TableKey::WalkCompletions), + state + .walk_completion_indices + .iter() + .filter_map(|&i| state.walk_completion_cache.get(i).cloned()) + .collect(), + )), TableKey::Map(map_idx, kind) => { let headers = csv_headers(TableKey::Map(map_idx, kind)); let cache = state.maps_display_caches.get(map_idx)?; @@ -575,14 +605,19 @@ pub fn resolve_csv_export_data( #[cfg(test)] mod tests { use super::{ - CharacterTableKind, InventoryCategory, JournalSection, MapsTableKind, TableKey, - csv_default_filename, csv_headers, stable_csv_keys, + CharacterTableKind, InventoryCategory, JournalSection, MapsTableKind, SaveFileViewerState, + TableKey, csv_default_filename, csv_headers, resolve_csv_export_data, stable_csv_keys, }; use crate::editors::save_file_viewer::state::events_default_columns; #[test] fn csv_headers_match_default_column_keys() { - let mut keys = vec![TableKey::Events]; + let mut keys = vec![ + TableKey::Events, + TableKey::Waypoints, + TableKey::WalkMilestones, + TableKey::WalkCompletions, + ]; keys.extend(JournalSection::all().iter().copied().map(TableKey::Journal)); keys.extend( CharacterTableKind::all() @@ -615,6 +650,13 @@ mod tests { TableKey::Events => events_default_columns(), TableKey::Journal(section) => section.default_columns(), TableKey::Map(_, kind) => kind.default_columns(), + TableKey::Waypoints => crate::editors::save_file_viewer::state::waypoint_columns(), + TableKey::WalkMilestones => { + crate::editors::save_file_viewer::state::walk_milestone_columns() + } + TableKey::WalkCompletions => { + crate::editors::save_file_viewer::state::walk_completion_columns() + } }; let expected: Vec = stable_csv_keys(key) .iter() @@ -639,6 +681,34 @@ mod tests { assert!(!misc_keys.contains(&"reserved_bytes")); } + #[test] + fn csv_new_tables_use_fixed_headers_and_cached_rows() { + assert_eq!(csv_headers(TableKey::Waypoints), ["#", "x", "y", "raw"]); + assert_eq!( + csv_headers(TableKey::WalkMilestones), + ["decal bucket", "direction", "state", "class", "x", "y"] + ); + assert_eq!( + csv_headers(TableKey::WalkCompletions), + ["value", "direction", "diagonal", "sprite", "x", "y"] + ); + + let state = SaveFileViewerState { + waypoint_cache: vec![vec![ + "0".to_string(), + "4660".to_string(), + "22136".to_string(), + "34 12 78 56".to_string(), + ]], + waypoint_indices: vec![0], + ..Default::default() + }; + let (headers, rows) = resolve_csv_export_data(&state, TableKey::Waypoints).unwrap(); + assert_eq!(headers[1], "x"); + assert_eq!(rows[0][1], "4660"); + assert_eq!(rows[0][3], "34 12 78 56"); + } + #[test] fn csv_filename_inventory() { let name = csv_default_filename(TableKey::Inventory( diff --git a/dispel-gui/src/editors/save_file_viewer/update/filter.rs b/dispel-gui/src/editors/save_file_viewer/update/filter.rs index 536d4a1f..90705aec 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/filter.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/filter.rs @@ -187,6 +187,21 @@ fn table_filter_access( ); Some((filter, rows, indices)) } + TableKey::Waypoints => Some(( + &mut state.waypoint_table_state.filter, + &state.waypoint_cache, + &mut state.waypoint_indices, + )), + TableKey::WalkMilestones => Some(( + &mut state.walk_milestone_table_state.filter, + &state.walk_milestone_cache, + &mut state.walk_milestone_indices, + )), + TableKey::WalkCompletions => Some(( + &mut state.walk_completion_table_state.filter, + &state.walk_completion_cache, + &mut state.walk_completion_indices, + )), } } @@ -289,6 +304,9 @@ fn filtered_indices_for(state: &SaveFileViewerState, key: TableKey) -> Option<&[ TableKey::Character(kind) => state.character_filtered_indices.get(&kind).map(|v| &v[..]), TableKey::Events => Some(&state.events_filtered_indices), TableKey::Journal(section) => state.journal_filtered_indices.get(§ion).map(|v| &v[..]), + TableKey::Waypoints => Some(&state.waypoint_indices), + TableKey::WalkMilestones => Some(&state.walk_milestone_indices), + TableKey::WalkCompletions => Some(&state.walk_completion_indices), } } @@ -348,6 +366,39 @@ fn navigate_highlight(state: &mut SaveFileViewerState, key: TableKey, next: bool ts.filter.navigate_prev_highlight(); } } + TableKey::Waypoints => { + if next { + state.waypoint_table_state.filter.navigate_next_highlight(); + } else { + state.waypoint_table_state.filter.navigate_prev_highlight(); + } + } + TableKey::WalkMilestones => { + if next { + state + .walk_milestone_table_state + .filter + .navigate_next_highlight(); + } else { + state + .walk_milestone_table_state + .filter + .navigate_prev_highlight(); + } + } + TableKey::WalkCompletions => { + if next { + state + .walk_completion_table_state + .filter + .navigate_next_highlight(); + } else { + state + .walk_completion_table_state + .filter + .navigate_prev_highlight(); + } + } } // Resolve the focused original index, then the focused table state so we @@ -372,6 +423,18 @@ fn navigate_highlight(state: &mut SaveFileViewerState, key: TableKey, next: bool .journal_table_states .get(§ion) .and_then(|ts| ts.filter.current_highlight_orig_idx()), + TableKey::Waypoints => state + .waypoint_table_state + .filter + .current_highlight_orig_idx(), + TableKey::WalkMilestones => state + .walk_milestone_table_state + .filter + .current_highlight_orig_idx(), + TableKey::WalkCompletions => state + .walk_completion_table_state + .filter + .current_highlight_orig_idx(), }; let Some(orig) = orig else { diff --git a/dispel-gui/src/editors/save_file_viewer/update/mod.rs b/dispel-gui/src/editors/save_file_viewer/update/mod.rs index f816db3d..fdcab0b7 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/mod.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/mod.rs @@ -90,6 +90,24 @@ fn column_width_by_key(state: &SaveFileViewerState, key: TableKey, col: usize) - .get(§ion) .and_then(|ts| ts.column_widths.get(col).copied()) .unwrap_or(80.0), + TableKey::Waypoints => state + .waypoint_table_state + .column_widths + .get(col) + .copied() + .unwrap_or(60.0), + TableKey::WalkMilestones => state + .walk_milestone_table_state + .column_widths + .get(col) + .copied() + .unwrap_or(80.0), + TableKey::WalkCompletions => state + .walk_completion_table_state + .column_widths + .get(col) + .copied() + .unwrap_or(80.0), } } @@ -135,6 +153,21 @@ fn auto_size_column_by_key(state: &mut SaveFileViewerState, key: TableKey, col: } None => default_column_width_by_key(key, col), }, + TableKey::Waypoints => { + auto_size_column(&state.waypoint_cache, &state.waypoint_indices, col, &header) + } + TableKey::WalkMilestones => auto_size_column( + &state.walk_milestone_cache, + &state.walk_milestone_indices, + col, + &header, + ), + TableKey::WalkCompletions => auto_size_column( + &state.walk_completion_cache, + &state.walk_completion_indices, + col, + &header, + ), }; apply_column_width(state, key, col, width); @@ -148,6 +181,13 @@ fn default_column_width_by_key(key: TableKey, col: usize) -> f32 { TableKey::Inventory(cat) => cat.default_columns(), TableKey::Character(kind) => kind.default_columns(), TableKey::Journal(section) => section.default_columns(), + TableKey::Waypoints => crate::editors::save_file_viewer::state::waypoint_columns(), + TableKey::WalkMilestones => { + crate::editors::save_file_viewer::state::walk_milestone_columns() + } + TableKey::WalkCompletions => { + crate::editors::save_file_viewer::state::walk_completion_columns() + } }; columns .into_iter() @@ -188,6 +228,25 @@ fn column_label_by_key(key: TableKey, col: usize) -> String { .nth(col) .map(|c| c.label) .unwrap_or_default(), + TableKey::Waypoints => crate::editors::save_file_viewer::state::waypoint_columns() + .into_iter() + .nth(col) + .map(|c| c.label) + .unwrap_or_default(), + TableKey::WalkMilestones => { + crate::editors::save_file_viewer::state::walk_milestone_columns() + .into_iter() + .nth(col) + .map(|c| c.label) + .unwrap_or_default() + } + TableKey::WalkCompletions => { + crate::editors::save_file_viewer::state::walk_completion_columns() + .into_iter() + .nth(col) + .map(|c| c.label) + .unwrap_or_default() + } } } @@ -230,9 +289,79 @@ fn apply_column_width(state: &mut SaveFileViewerState, key: TableKey, col: usize *w = width; } } + TableKey::Waypoints => { + if let Some(w) = state.waypoint_table_state.column_widths.get_mut(col) { + *w = width; + } + } + TableKey::WalkMilestones => { + if let Some(w) = state.walk_milestone_table_state.column_widths.get_mut(col) { + *w = width; + } + } + TableKey::WalkCompletions => { + if let Some(w) = state.walk_completion_table_state.column_widths.get_mut(col) { + *w = width; + } + } } } +/// Build display rows for the read-only waypoint table. +fn waypoint_rows(data: &[u8]) -> Vec> { + data.as_chunks::<8>() + .0 + .iter() + .enumerate() + .map(|(index, chunk)| { + vec![ + index.to_string(), + u32::from_le_bytes(chunk[0..4].try_into().unwrap()).to_string(), + u32::from_le_bytes(chunk[4..8].try_into().unwrap()).to_string(), + crate::editors::save_file_viewer::update::table::hex_bytes(chunk), + ] + }) + .collect() +} + +/// Build display rows for decoded walk milestones. +fn walk_milestone_rows( + records: &[dispel_core::references::save_file::WalkMilestoneRecord], +) -> Vec> { + records + .iter() + .map(|record| { + vec![ + record.id.to_string(), + record.direction.to_string(), + record.entity_state_byte.to_string(), + record.decal_class.to_string(), + record.x.to_string(), + record.y.to_string(), + ] + }) + .collect() +} + +/// Build display rows for decoded walk completions. +fn walk_completion_rows( + records: &[dispel_core::references::save_file::WalkCompletionRecord], +) -> Vec> { + records + .iter() + .map(|record| { + vec![ + record.id.to_string(), + record.direction.to_string(), + record.diagonal.to_string(), + record.effect_sprite_index.to_string(), + record.x.to_string(), + record.y.to_string(), + ] + }) + .collect() +} + pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { // A load result carries its tab id so it still reaches the originating // viewer if another tab became active while the async read was running. @@ -250,6 +379,10 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { }; match msg { + SaveFileViewerMessage::SelectEventsSubView(sub_view) => { + state.events_sub_view = sub_view; + Task::none() + } SaveFileViewerMessage::SelectSection(section) => { if state.active_section == SaveFileSection::SavedViewport && section != SaveFileSection::SavedViewport @@ -1039,6 +1172,44 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task { } state.events_display_cache = display_cache; state.events_filtered_indices = (0..n).collect(); + + // Read-only runtime and post-event tables. + state.waypoint_cache = + waypoint_rows(&loaded.save_file.character_state.waypoint_data); + state.waypoint_indices = (0..state.waypoint_cache.len()).collect(); + state.waypoint_table_state = TableInteractionState { + column_widths: crate::editors::save_file_viewer::state::waypoint_columns() + .iter() + .map(|c| c.width_px) + .collect(), + ..Default::default() + }; + + state.walk_milestone_cache = + walk_milestone_rows(&loaded.save_file.post_events.walk_milestones); + state.walk_milestone_indices = (0..state.walk_milestone_cache.len()).collect(); + state.walk_milestone_table_state = TableInteractionState { + column_widths: + crate::editors::save_file_viewer::state::walk_milestone_columns() + .iter() + .map(|c| c.width_px) + .collect(), + ..Default::default() + }; + + state.walk_completion_cache = + walk_completion_rows(&loaded.save_file.post_events.walk_completions); + state.walk_completion_indices = + (0..state.walk_completion_cache.len()).collect(); + state.walk_completion_table_state = TableInteractionState { + column_widths: + crate::editors::save_file_viewer::state::walk_completion_columns() + .iter() + .map(|c| c.width_px) + .collect(), + ..Default::default() + }; + state.raw_hex_viewers = loaded .hex_editors .into_iter() @@ -1848,6 +2019,37 @@ mod tests { app } + #[test] + fn test_runtime_and_session_row_builders_keep_sentinels() { + let mut waypoint = vec![0u8; 16]; + waypoint[0..4].copy_from_slice(&0x1234u32.to_le_bytes()); + waypoint[4..8].copy_from_slice(&0x5678u32.to_le_bytes()); + let rows = waypoint_rows(&waypoint); + assert_eq!(rows.len(), 2); + assert_eq!(rows[0][1], "4660"); + assert_eq!(rows[0][2], "22136"); + assert!(rows[0][3].starts_with("34 12 00 00 78 56")); + + let milestone = dispel_core::references::save_file::WalkMilestoneRecord { + id: 777, + x: 11, + y: 12, + ..Default::default() + }; + let rows = walk_milestone_rows(&[milestone]); + assert_eq!(rows[0][0], "777"); + assert_eq!(rows[0][4], "11"); + + let completion = dispel_core::references::save_file::WalkCompletionRecord { + id: 888, + y: 13, + ..Default::default() + }; + let rows = walk_completion_rows(&[completion]); + assert_eq!(rows[0][0], "888"); + assert_eq!(rows[0][5], "13"); + } + fn table(width: f32) -> TableInteractionState { TableInteractionState { column_widths: vec![width], diff --git a/dispel-gui/src/editors/save_file_viewer/update/table.rs b/dispel-gui/src/editors/save_file_viewer/update/table.rs index 985fdbdc..58621a41 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/table.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/table.rs @@ -59,6 +59,29 @@ pub fn apply_resize_cursor(state: &mut SaveFileViewerState, x: f32) { *w = new_width; } } + TableKey::Waypoints => { + if let Some(w) = state.waypoint_table_state.column_widths.get_mut(drag.col) { + *w = new_width; + } + } + TableKey::WalkMilestones => { + if let Some(w) = state + .walk_milestone_table_state + .column_widths + .get_mut(drag.col) + { + *w = new_width; + } + } + TableKey::WalkCompletions => { + if let Some(w) = state + .walk_completion_table_state + .column_widths + .get_mut(drag.col) + { + *w = new_width; + } + } } } diff --git a/dispel-gui/src/editors/save_file_viewer/view.rs b/dispel-gui/src/editors/save_file_viewer/view.rs index ce520b57..b378a326 100644 --- a/dispel-gui/src/editors/save_file_viewer/view.rs +++ b/dispel-gui/src/editors/save_file_viewer/view.rs @@ -60,6 +60,9 @@ pub fn view<'a>(app: &'a App) -> Element<'a, Message> { } SaveFileSection::Inventory => crate::editors::save_file_viewer::inventory::view(state), SaveFileSection::Character => crate::editors::save_file_viewer::character::view(state), + SaveFileSection::Runtime => { + crate::editors::save_file_viewer::character::runtime_view(state) + } SaveFileSection::Raw => crate::editors::save_file_viewer::raw::view(state), SaveFileSection::Events => crate::editors::save_file_viewer::events::view(state), SaveFileSection::Journal => crate::editors::save_file_viewer::journal::view(state), From fe1b3ca25ed9b7ed0d862bfbe0fa5048476125a7 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:02:26 +0100 Subject: [PATCH 71/72] fix(gui): remove unused imports --- dispel-gui/src/tests/editor_field_edit.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dispel-gui/src/tests/editor_field_edit.rs b/dispel-gui/src/tests/editor_field_edit.rs index 1cb04bdf..6dabe933 100644 --- a/dispel-gui/src/tests/editor_field_edit.rs +++ b/dispel-gui/src/tests/editor_field_edit.rs @@ -1034,7 +1034,7 @@ mod renamed_field_labels { } } - use dispel_core::{EditItem, EditItemEffect, Extractor, MagicSpell, MonsterIni}; + use dispel_core::MagicSpell; } // ============================================================================ From 48e0f205046fe77b67e83e3717e8913bb3fbb9a4 Mon Sep 17 00:00:00 2001 From: dimspell <141545384+dimspell@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:47:30 +0100 Subject: [PATCH 72/72] fix(map): name roof overlay byte 1 as draw-enable --- docs/files/Map/Map.map.md | 39 ++++++------ docs/files/Map/MapModule.md | 17 +++--- src/database/map_persistence.rs | 2 +- src/map/mod.rs | 25 ++++---- src/map/reader.rs | 48 +++++++-------- src/map/render.rs | 103 +++++++++++++++++++++++--------- 6 files changed, 136 insertions(+), 98 deletions(-) diff --git a/docs/files/Map/Map.map.md b/docs/files/Map/Map.map.md index 2e04b60d..181ea67d 100644 --- a/docs/files/Map/Map.map.md +++ b/docs/files/Map/Map.map.md @@ -53,7 +53,7 @@ count: i32 records: (count − 1) × 8 bytes -- each record: word0: i32, word1: i32 ``` -The tool skips `(count − 1) × 8` bytes and lands on the next block's size field. The cat1, cat3, dun01, map1 and catp samples contain 99,104 records. In those records `word0 == 0` and `word1 == 1`. The supplied data shows no use for these fields. +The block holds `(count − 1)` records of 2 × i32. Both words are constant (`word0 == 0`, `word1 == 1`); the format gives them no further role. ### Second Block *(u16 lookup table)* @@ -62,10 +62,10 @@ size: i32 data: size × 2 bytes -- table of u16 entries ``` -Not dead data: the Access-Ref block indexes into this table. Each u16 entry is -`{low byte: transparency mode (0 = opaque copy, 1 = skip transparent pixels), -high byte: draw-enable flag}`. All non-zero ids observed fall inside the table -bounds. +The Access-Ref block indexes into this table. Each u16 entry is +`{low byte: blit mode (0 = opaque copy, non-zero = skip black pixels), +high byte: draw-enable flag}` (0 = the roof tile is not drawn). Non-zero +ref ids always stay inside the table bounds. ### Sprite Block *(embedded sprites)* @@ -96,7 +96,7 @@ for each placement: frame_skip: (frame_count − 1) × 6 × 4 bytes ``` -The seven i32 values after `sprite_id` hold frame 0 of a per-frame record. Each record has 24 bytes: a `{left, top, right, bottom}` box and a duplicated `{x, y}` anchor. The format stores these values in separate per-frame arrays. In the cat1 and map1 samples, `right − left` and `bottom − top` equal the frame pixel `width × height`. Placements sort by `bottom` on the Y axis. +The seven i32 values after `sprite_id` hold frame 0 of a per-frame record. Each record has 24 bytes: a `{left, top, right, bottom}` box and a duplicated `{x, y}` anchor. The format stores these values in separate per-frame arrays. `right − left` and `bottom − top` equal the frame pixel `width × height`. Placements sort by `bottom` on the Y axis. ### Tiled Objects Block *(buildings)*: fully typed @@ -107,41 +107,39 @@ bundle_count: i32 for each bundle: record_count: i32 for each record: - field_04: i32 -- observed as 0 in shipped maps + field_04: i32 -- reserved, always 0 body: 260 bytes -- binary metadata, not text item_count: i32 for each item: type_flag: i32 -- 1 ⇒ entries carry extra bytes entry_count: i32 - field_14: i32 -- always 0 in all shipped maps + field_14: i32 -- reserved, always 0 for each entry: bound_x, bound_y, -- bounding box, map pixels: bound_right, bound_bottom right = x + 64 and - bottom = y + grid_height*32, - exact across all shipped entries + bottom = y + grid_height*32 anchor_x, anchor_y -- stack anchor, map-local pixels draw_x, draw_y -- position terms used during -- drawing relative to the camera - grid_width -- constant 1 in all shipped maps + grid_width -- constant 1 grid_height -- equals ids.len() stored_cell_count -- equals grid_width*grid_height - -- in all shipped maps ids: stored_cell_count × u16 -- BTL tile stack of this entry if type_flag == 1: extra_payload: stored_cell_count bytes n = first_record.first_item.entries[0].grid_height - level_flags: n × (flag_a: i32, flag_b: i32) -- two binary 0/1 flags per - -- stack level; their meaning is unknown + level_flags: n × (flag_a: i32, flag_b: i32) -- two binary flags per + -- stack level ``` There is no end-of-block sentinel. The three end grids follow the last bundle's level flags immediately. -The 33 sample maps contain 43,554 entries. Those entries use this layout: +Entries use this layout: - `anchor_x` and `anchor_y` give the stack anchor `(x, y)` in map-local pixels. The entry's `ids` u16 array is its BTL tile stack. The renderer-facing `TiledObjectInfo` comes from the bundle's first entry (first record, first item, first entry). - The 43,554 entries follow the bounding-box relations above. - An entry's `grid_height` sizes the per-bundle flag arrays that follow. -The sample maps contain one record per bundle, eight items per record and at most one entry per item. `type_flag` and `field_14` are zero in those files. +Each bundle holds one record, each record eight items and each item at most one entry. `type_flag` and `field_14` are zero. The tool draws each bundle's first-entry tile stack downward from the anchor. It draws one 62×32 diamond per id. Negative ids occur. The tool skips them when it draws. @@ -184,10 +182,9 @@ One packed u32 per tile, row-major: | 25–31 | Unused (always 0) | The index points straight into the `.gtl` pixel data: the renderer blits from -`gtl_base + index × 2048` (one 32×32 RGB565 tile). Across observed maps the maximum index matches the `.gtl` tile -capacity minus one. +`gtl_base + index × 2048` (one 32×32 RGB565 tile). The maximum index matches the `.gtl` tile capacity minus one. -Bits 0 to 9 form one access field. The tool can rewrite that field without changing the tile index. The sample maps use bit 0 only. No sample value sets bits 1 to 9. +Bits 0 to 9 form one access field. The tool can rewrite that field without changing the tile index. The map data sets bit 0 only; bits 1 to 9 are set at runtime. ### Access-Ref Block *(a.k.a. "roof" block)* @@ -202,8 +199,8 @@ shadow_and_flags: i16 -- bits 15–29 of the u32: shadow level 0–19 This grid packs **two layers** in one u32: 1. BTL overlay ref (bits 0 to 14): when the referenced Second Block entry has its high byte set, the renderer blits BTL pixels from - `btl_base + ref_id × 2048` (entry *low* byte selects transparent vs opaque - blit). So the Second Block is `{blit_mode, shadow_on}` per overlay id. + `btl_base + ref_id × 2048` (entry *low* byte selects skip-black vs opaque + blit). So the Second Block is `{blit_mode, draw_enable}` per overlay id. 2. Shadow and fog level (bits 15 to 29): the value spans 0 to 199. The documented rule raises the value for light sources. The highest value wins. On a dark map, a BTL overlay must have a non-zero reference and at least one diff --git a/docs/files/Map/MapModule.md b/docs/files/Map/MapModule.md index c0077eb2..6f59d13b 100644 --- a/docs/files/Map/MapModule.md +++ b/docs/files/Map/MapModule.md @@ -54,7 +54,7 @@ The file holds geometry, embedded sprites, tiled objects, event triggers, ground | OVERLAY-ID TABLE (skipped by the parser) | | size: i32 | | entries: size × u16 | -| {low byte: transparency mode, | +| {low byte: blit mode, | | high byte: draw-enable} | | indexed by the Access-Ref grid's refs | +-----------------------------------------------+ @@ -78,7 +78,7 @@ The file holds geometry, embedded sprites, tiled objects, event triggers, ground | bottom-top = frame height; | | bottom is the Y-sort key | | anchor_x, anchor_y i32 × 2 | -| ← duplicate left/top in shipped maps | +| ← duplicate of left/top | | remaining frames: (frame_count-1) × 24 B | +-----------------------------------------------+ | TILED OBJECTS BLOCK (buildings) | @@ -87,9 +87,9 @@ The file holds geometry, embedded sprites, tiled objects, event triggers, ground | For each bundle: | | metadata: 264 bytes | | control_0..3: i32 × 4 ← (8,0,1,0) | -| param_0..3: i32 × 4 ← unmapped | +| param_0..3: i32 × 4 ← reserved | | anchor_x, anchor_y: i32 ← map px | -| param_4..5: i32 × 2 ← unmapped | +| param_4..5: i32 × 2 ← reserved | | extra_count_a/b: i32 × 2 | | tile_stack_len: i32 | | tile_ids: i16 × tile_stack_len | @@ -101,7 +101,7 @@ The file holds geometry, embedded sprites, tiled objects, event triggers, ground | For each tile: packed u32 | | bits 0-13 event id (ids < 70 valid) | | bit 22 tile marked / entity occupies | -| remainder unmapped | +| remainder reserved | +-----------------------------------------------+ | TILE & ACCESS GRID | | For each tile: packed u32 | @@ -247,8 +247,7 @@ type Coords = (i32, i32); // isometric (x, y) tile coordinate struct EventBlock { x: i32, // tile X y: i32, // tile Y - event_id: i16, // event trigger ID - _unknown_value: i16, + word: u32, // packed event word exactly as stored in the file } struct SpriteInfoBlock { @@ -841,7 +840,7 @@ This JSON schema describes exported `.MAP` data: | 12 | 4 | `object_ref_count` | i32 LE | | 16 | var | `object_ref_records` | Skip `(count − 1) × 8` bytes; each record's `value2` is a linear tile index into the end grids | | var | 4 | `overlay_table_size` | i32 LE | -| var | var | `overlay_table` | `size × 2` bytes; u16 entries `{blit_mode, shadow_on}` indexed by Access-Ref ids | +| var | var | `overlay_table` | `size × 2` bytes; u16 entries `{blit_mode, draw_enable}` indexed by Access-Ref ids | | var | 4 | `sprite_count` | i32 LE | | var | var | `sprite entries` | Each: stamp(4) + meta(264) + sequence_info + padding | | var | 4 | `sprite_placement_count` | i32 LE | @@ -871,7 +870,7 @@ The tool draws entities as colored diamond markers when `game_path` is absent or ## Notes -1. The tool skips the first two blocks. The supplied data shows no use for these fields. +1. The tool skips the first two blocks; their fields are constant and carry no data. 2. Image stamp 6 uses 1904 bytes of padding after sprite sequence data. Image stamp 9 uses 2996 bytes. 3. The tool finds the end of the tiled objects block with a 20-byte backwards scan for byte value 1. 4. The tool parses the roof block only when enough bytes remain. diff --git a/src/database/map_persistence.rs b/src/database/map_persistence.rs index ea211d4e..0f49b842 100644 --- a/src/database/map_persistence.rs +++ b/src/database/map_persistence.rs @@ -312,7 +312,7 @@ pub fn save_map_metadata(conn: &mut Connection, map_id: &str, model: &MapModel) } /// Persists the overlay-id lookup table: one row per u16 entry, with the -/// low byte decoded as the roof blit mode and the high byte as shadow-on. +/// low byte decoded as the roof blit mode and the high byte as draw-enable. pub fn save_map_overlay_modes( conn: &mut Connection, map_id: &str, diff --git a/src/map/mod.rs b/src/map/mod.rs index 095aa8d5..fe10cffe 100644 --- a/src/map/mod.rs +++ b/src/map/mod.rs @@ -31,9 +31,7 @@ // | - Count (i32) | // | - Data: (count-1)*8 bytes | // | (count-1 records of 2×i32; | -// | word0 ≡ 0 and word1 ≡ 1 | -// | across all shipped maps — | -// | semantics unknown) | +// | word0 = 0 and word1 = 1) | // +------------------------------+ // | SECOND BLOCK (variable) | // | - Size (i32) | @@ -81,7 +79,7 @@ // | For each tile: packed u32 | // | bits 0-13 event id | // | bit 22 tile marked | -// | remainder unmapped | +// | remainder reserved | // +------------------------------+ // | TILE & ACCESS GRID | // | For each tile: packed u32 | @@ -186,11 +184,15 @@ impl<'de> Deserialize<'de> for RoofBlitMode { } } -/// One overlay-table entry: a roof blit mode and the shadow-on flag. +/// One overlay-table entry: a roof blit mode and its draw-enable byte. +/// +/// A zero draw-enable byte hides the roof tile. The blit-mode byte picks the +/// opaque copy or the skip-black path. No lighting pass reads the draw-enable +/// byte. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] pub struct OverlayMode { pub blit_mode: RoofBlitMode, - pub shadow_on: u8, + pub draw_enable: u8, } impl OverlayMode { @@ -198,13 +200,13 @@ impl OverlayMode { pub fn from_raw(raw: u16) -> Self { Self { blit_mode: RoofBlitMode::from_byte((raw & 0xFF) as u8), - shadow_on: (raw >> 8) as u8, + draw_enable: (raw >> 8) as u8, } } /// Rebuild the on-disk entry from its decoded parts. pub fn to_raw(self) -> u16 { - u16::from(self.shadow_on) << 8 | u16::from(self.blit_mode.byte()) + u16::from(self.draw_enable) << 8 | u16::from(self.blit_mode.byte()) } } @@ -222,7 +224,7 @@ pub struct MapData { pub model: MapModel, pub gtl_tiles: HashMap, pub btl_tiles: HashMap, - /// Per-overlay-id `{lo: roof blit mode, hi: shadow-on}` table from + /// Per-overlay-id `{lo: roof blit mode, hi: draw-enable}` table from /// the map file; drives roof rendering (see `render::plot_roofs`). pub overlay_modes: Vec, /// Raw packed u32 words of the access-ref grid ("roof" block), preserved @@ -239,7 +241,7 @@ pub struct MapData { /// `internal_sprites` — same length, same order. pub internal_sprite_stamps: Vec, /// First-block tiled-object ref records in file order (both words are - /// constant across all shipped maps). + /// constant: 0 and 1). pub tiled_object_refs: Vec, /// Fully typed tiled-bundle trees, parallel to `tiled_infos` — same /// length, same order. @@ -697,8 +699,7 @@ pub fn extract( /// - Sequence info with frame count and positions /// - Pixel data for each animation frame /// -/// Sprites are extracted with their original animation sequences preserved, -/// allowing for proper reconstruction of the observed animations. +/// Sprites are extracted with their original animation sequences preserved. pub fn extract_sprites(input_map_file: &Path, output_path: &Path) -> IoResult<()> { let file = File::open(input_map_file)?; let mut reader = BufReader::new(file); diff --git a/src/map/reader.rs b/src/map/reader.rs index 99cc44be..6a59340c 100644 --- a/src/map/reader.rs +++ b/src/map/reader.rs @@ -40,17 +40,12 @@ fn reader_len(reader: &mut BufReader) -> Result { /// Tiled-object ref records: `count` (i32) followed by `(count - 1)` records /// of 2 × i32 each. /// -/// Both words are constant across ALL shipped maps (`word0 == 0`, -/// `word1 == 1` in all 99,104 records probed); their semantics are unknown. -/// The earlier "linear tile index into the end grids" interpretation was -/// wrong. See [`TiledObjectRef`]. +/// Each record is a pair of i32 words. Both words are constant +/// (`word0 == 0`, `word1 == 1`); the format gives them no further role. +/// See [`TiledObjectRef`]. /// -/// Verified against cat1/cat3/dun01/map1/catp fixtures: reading `(count-1)` -/// pairs lands exactly on the overlay table's size field, while `count*8` -/// lands on `0x01010101` garbage. -/// -/// A count below 1 cannot be honored (the format has no negative-record -/// semantics) and yields a clear error instead of a silent negative seek. +/// A count below 1 is invalid and yields a clear error instead of a +/// silent negative seek. pub fn read_tiled_object_refs(reader: &mut BufReader) -> Result> { let count = reader.read_i32::()?; if count < 1 { @@ -71,10 +66,10 @@ pub fn read_tiled_object_refs(reader: &mut BufReader) -> Result(reader: &mut BufReader) -> Result> { @@ -237,9 +232,8 @@ pub fn sprite_info_block( // first entry. // // The three end grids follow immediately after the last bundle's flags — -// the format has no end-of-block sentinel. The previous empirical parser's -// "sentinel alignment scan" is gone; any decode error now surfaces as an -// explicit `Err` instead of being papered over by a resync hack. +// the format has no end-of-block sentinel. Any decode error surfaces as an +// explicit `Err`. // -------------------------------------------------------------------------- fn read_bundle_entry(reader: &mut BufReader, type_flag: i32) -> Result { @@ -399,9 +393,9 @@ pub fn tiled_objects_block( // -------------------------------------------------------------------------- // Event block – per-tile packed u32 (located near end of file) // -// Low 14 bits hold an event/transition id; observed behavior: hovering such -// a tile shows a name resolved through the Map.ini/AllMap.ini tables (ids < 70 are -// treated as valid). Bit 22 of the word ("tile marked / entity occupies") +// Low 14 bits hold an event/transition id; hovering such a tile shows a +// name resolved through the Map.ini/AllMap.ini tables (ids < 70 are valid). +// Bit 22 of the word ("tile marked / entity occupies") // monster chase logic treats marked tiles as blocked; see // [`EventBlock::is_tile_marked`]. // -------------------------------------------------------------------------- @@ -433,11 +427,11 @@ pub fn read_events_block( // bits 10–24 – GTL ground-tile index: (word >> 10) & 0x7FFF. // The renderer blits from gtl_base + index * 0x800 // (2048 B = one 32×32 RGB565 tile in the .gtl file). -// bits 25–31 – unused (always 0 in known maps) +// bits 25–31 – unused (always 0) // // Access-modifying script commands rewrite exactly bits 0–9, // preserving the tile index — this whole field is called "access". -// Known maps only use bit 0; bits 1–9 are set at runtime. +// The map data only sets bit 0; bits 1–9 are set at runtime. // -------------------------------------------------------------------------- /// Parsed result of `read_tiles_and_access_block`: (gtl_tiles, collisions, object_ids). @@ -477,7 +471,7 @@ pub fn read_tiles_and_access_block( // Access-ref grid ("roof") – one packed u32 per tile // // bits 0–14 BTL overlay ref → indexes the u16 table read by -// `skip_overlay_id_table` ({lo byte: transparency mode, +// `skip_overlay_id_table` ({lo byte: blit mode, // hi byte: draw-enable}); pixels at btl_base + id * 0x800 // bit 15 bleeds into the signed-i16 view of the ref (negative ⇒ skip) // bits 15–29 light level (0–199) selecting a brightness pattern from @@ -594,7 +588,7 @@ mod tests { } #[test] - fn test_overlay_entries_expose_blit_mode_and_shadow() { + fn test_overlay_entries_expose_blit_mode_and_draw_enable() { use crate::map::{OverlayMode, RoofBlitMode}; let mut bytes = 2_i32.to_le_bytes().to_vec(); @@ -605,15 +599,17 @@ mod tests { let first = OverlayMode::from_raw(table[0]); assert_eq!(first.blit_mode, RoofBlitMode::Opaque); - assert_eq!(first.shadow_on, 1); + assert_eq!(first.draw_enable, 1); let second = OverlayMode::from_raw(table[1]); assert_eq!(second.blit_mode, RoofBlitMode::SkipBlack); - assert_eq!(second.shadow_on, 0); + assert_eq!(second.draw_enable, 0); let current: OverlayMode = - serde_json::from_str(r#"{"blit_mode":2,"shadow_on":1}"#).unwrap(); + serde_json::from_str(r#"{"blit_mode":2,"draw_enable":1}"#).unwrap(); assert_eq!(current.blit_mode, RoofBlitMode::SkipBlack); - assert_eq!(current.shadow_on, 1); + assert_eq!(current.draw_enable, 1); + // Skip-black normalizes any non-zero mode byte back to one. + assert_eq!(current.to_raw(), 0x0101); } #[test] diff --git a/src/map/render.rs b/src/map/render.rs index 68a63497..6e2e6c5f 100644 --- a/src/map/render.rs +++ b/src/map/render.rs @@ -167,8 +167,8 @@ pub fn render_map(config: MapRenderConfig) -> Result<()> { lights, } = config; - // The renderer reproduces the observed occluded viewport — the region - // the player actually sees — not the full map canvas. + // The renderer draws the occluded viewport — the region the player + // sees — not the full map canvas. let image_width = data.model.occluded_map_in_pixels_width; let image_height = data.model.occluded_map_in_pixels_height; @@ -366,10 +366,10 @@ pub fn render_map(config: MapRenderConfig) -> Result<()> { } // ── Pass 3b: Shadows ───────────────────────────────────────────────── - // Reproduction of the observed lighting pass: on maps flagged - // Dark in AllMap.ini, level-0 tiles are blacked out and tiles with a - // light level are faded through the fogdata.dat tables. Drawn after - // world pixels so annotations added later stay fully visible. + // The lighting pass: on maps flagged Dark in AllMap.ini, level-0 tiles + // are blacked out and tiles with a light level are faded through the + // fogdata.dat tables. Drawn after world pixels so annotations added + // later stay fully visible. if toggles.show_shadows && let Some(fog) = prepare_shadow_pass(game_path, map_id) { @@ -526,12 +526,12 @@ pub fn plot_roofs( if btl_tile_id > 0 { let btl_tile_idx = btl_tile_id as usize; if let Some(btl_tile) = btl_tileset.get(btl_tile_idx) { - // Per-id mode from the map's overlay table: the shadow-on + // Per-id mode from the map's overlay table: the draw-enable // byte gates the overlay, the blit-mode byte picks the // opaque or skip-black path. let entry = overlay_modes.get(btl_tile_idx).copied().unwrap_or(0); let mode = OverlayMode::from_raw(entry); - if mode.shadow_on == 0 { + if mode.draw_enable == 0 { continue; } let (mut sx, mut sy) = @@ -553,25 +553,21 @@ pub fn plot_roofs( } // -------------------------------------------------------------------------- -// Shadow overlay – reproduction of the observed lighting pass +// Shadow overlay – the lighting pass // // Applied near the end of the world render sequence. The pass only runs on -// maps flagged Dark in AllMap.ini — an observed per-map-catalog flag, -// toggleable at runtime via the "Turn off the light" / "Honey, It's too -// dark" cheat codes. +// maps flagged Dark in AllMap.ini, toggleable at runtime via the +// "Turn off the light" / "Honey, It's too dark" cheat codes. // // Per tile, with level = (access_ref_word >> 15) & 0x7FFF: -// level ≥ 124 → untouched by the pass (124..=199 fit the level field -// but read past the fade tables = undefined; levels -// ≥ 200 are simply not darkened) +// level ≥ 124 → untouched by the pass (levels above the fade-table +// range are not darkened) // level == 0 → span diamond filled solid black (fog of war) -// level 1..=123 → per pixel pair, red, green and blue are scaled by f/32 -// where f = fogdata.dat[(level-1)*512 + pair]. The -// all three channels are scaled by f/32. Flag bits -// 30–31 mark -// tiles whose factor is blended with dynamic entity -// lights via max(); statically we render the tile's own -// pattern. +// level 1..=123 → each pixel pair's red, green and blue channels are +// scaled by f/32, where f = fogdata.dat[(level-1)*512 + +// pair]. Flag bits 30–31 mark tiles whose factor is +// blended with dynamic entity lights via max(); the +// static render uses the tile's own pattern. // -------------------------------------------------------------------------- /// Per-row `(x_start, width)` spans of the shadow mask (32 rows). The rows @@ -661,13 +657,12 @@ fn prepare_shadow_pass(game_path: Option<&Path>, map_id: &str) -> Option MapModel { } } +#[test] +fn test_overlay_draw_enable_gates_roof_and_blit_mode_selects_path() { + use crate::decode::Color; + + let model = test_model(); + let black = Color { r: 0, g: 0, b: 0 }; + let mut tile = Tile { + colors: [black; 1024], + }; + tile.colors[0] = Color { r: 255, g: 0, b: 0 }; + let btl_tiles = HashMap::from([((0, 0), 1)]); + // Overlay id 1 selects the second tile in the set. + let tileset = [ + Tile { + colors: [black; 1024], + }, + tile, + ]; + const BACKGROUND: Rgb = Rgb([200, 100, 50]); + + let render = |modes: &[u16]| { + let mut image = ImageBuffer::, Vec>::from_pixel(128, 128, BACKGROUND); + plot_roofs(&mut image, &model, &btl_tiles, &tileset, modes); + let red = image.pixels().filter(|p| p.0 == [255, 0, 0]).count(); + let background = image.pixels().filter(|p| p.0 == BACKGROUND.0).count(); + (red, background) + }; + + // The tile uses overlay id 1. A zero high byte skips the roof entirely. + let (red, background) = render(&[0, 0x0000]); + assert_eq!(red, 0, "zero draw-enable must skip drawing"); + assert_eq!(background, 128 * 128, "canvas stays untouched"); + + // A non-zero high byte draws. A zero low byte copies black pixels too. + let (red, background) = render(&[0, 0x0100]); + assert_eq!(red, 1, "opaque mode draws the red pixel"); + assert!( + background < 128 * 128, + "opaque mode overwrites black pixels" + ); + + // A non-zero low byte skips black pixels and keeps the background. + let (red, background) = render(&[0, 0x0102]); + assert_eq!(red, 1, "skip-black mode draws the red pixel"); + assert_eq!( + background, + 128 * 128 - 1, + "skip-black mode keeps every background pixel but one" + ); +} + #[test] fn level_zero_tile_is_blacked_out_inside_spans_only() { let (mut img, px, py) = shadow_test_canvas();