diff --git a/.gitmodules b/.gitmodules index 39508a8..4bd4ef6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -17,3 +17,6 @@ [submodule "external/SDL_mixer"] path = external/SDL_mixer url = https://github.com/libsdl-org/SDL_mixer +[submodule "external/simdjson"] + path = external/simdjson + url = https://github.com/simdjson/simdjson diff --git a/CMakeLists.txt b/CMakeLists.txt index 0baac0c..c35bf66 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -82,6 +82,7 @@ set(IMGUI_SRC external/imgui/backends/imgui_impl_opengl3.cpp) set(TINYXML2_SRC external/tinyxml2/tinyxml2.cpp) +set(SIMDJSON_SRC external/simdjson/singleheader/simdjson.cpp) file(GLOB PROJECT_SRC CONFIGURE_DEPENDS src/resource/*.cpp @@ -126,7 +127,7 @@ set(CORE_INCLUDE_DIRS src/resource src/util) -add_library(anm2ed_core STATIC ${CORE_SRC} ${TINYXML2_SRC} ${IMGUI_CORE_SRC}) +add_library(anm2ed_core STATIC ${CORE_SRC} ${TINYXML2_SRC} ${SIMDJSON_SRC} ${IMGUI_CORE_SRC}) target_include_directories(anm2ed_core PUBLIC ${CORE_INCLUDE_DIRS}) target_link_libraries(anm2ed_core PUBLIC lunasvg) target_compile_definitions(anm2ed_core PUBLIC IMGUI_DISABLE_OBSOLETE_FUNCTIONS IMGUI_DEBUG_PARANOID IMGUI_ENABLE_DOCKING) diff --git a/README.md b/README.md index 1555e91..5d995d2 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ This application was developed with the assistance of a large language model. - Animation preview with grid, axes, pivots, borders, onionskin (with pivot paths), and another document's animation as an overlay. - Wizards: generate animations from a grid, generate regions, change all frame properties, merge animations and files. - Render to video, GIF, spritesheet or PNG sequence (FFmpeg), with trigger sounds. -- Each document targets Rebirth or the extended format. Rebirth saves write the game's format with the editor's own copy embedded (`SourceDocument`), so nothing is lost; animation layers are flattened for the game, and anything else the game doesn't support is warned about first. Extended saves write the editor's document alone ([format](docs/extended_format.md)). +- Saves write the game's format with the editor's own copy embedded (`SourceDocument`), so nothing is lost; animation layers are flattened for the game, and anything else the game doesn't support is warned about first. Documents can instead be saved as the editor's own, human-readable JSON ([format](docs/json_format.md)), which opens like any `.anm2`. - Undo/redo, autosave (spritesheet edits included) with crash restore, and overwrite warnings. ### Supported Languages diff --git a/docs/extended_format.md b/docs/extended_format.md deleted file mode 100644 index 67b555e..0000000 --- a/docs/extended_format.md +++ /dev/null @@ -1,162 +0,0 @@ -# Anm2Ed extended format (ExtendedVersion 2) - -An extended `.anm2` is the editor's own document, saved alone. It is the Rebirth `.anm2` XML with extra elements and attributes. This page lists what it adds and how the editor plays it, so that a converter or a game's loader can match the editor exactly. - -A Rebirth document is different: it saves the game's copy, followed by the extended document embedded as ``. A loader for extended files can ignore it. - -## Recognizing one -```xml - - - … -``` -- **`ExtendedVersion`** is present only on extended documents. -- **Version 1** files can only use the features marked *(v1)*. -- **Unknown elements and attributes** are kept by the editor and written back unchanged. - -## Content -```xml - - - - - - - - - - - - - … - - - - - … - - - - -``` - -**SVG spritesheets** -- A spritesheet whose path ends in `.svg` is an SVG. -- One SVG unit is one pixel. Crops, sizes and pivots are in SVG units. -- The editor draws an SVG at whatever resolution it is shown at. - -**Regions** *(v1)* -- `Origin` is `TopLeft`, `Center`, or absent (custom, with `XPivot`/`YPivot`). -- A layer frame with `RegionId` takes the region's crop, size and pivot. - -**Libraries** -- A library is another `.anm2` whose animations layers can play. -- `Path` is relative to the file that names it, so a library's own libraries are relative to that library. - -**Layers** -- A layer either shows its spritesheet, or plays an animation when `Animation` is set. -- **Same file or library:** with no `Library`, the animation comes from this file. With `Library`, it comes from that library. -- **`SpritesheetId`** is still written on animation layers (the game expects it) but is not used. -- **Instance name:** the layer's `Name` is the name code should use for the instance. -- **No self-nesting:** an animation never plays inside itself, even through other animations. That draw is skipped. - -## Animations -```xml - - - …frames… - - …frames… - - …frames… - … - - - … - - - - - - -``` - -**Markers** *(v1)* -- `StartMarker`/`EndMarker` keep editor playback between those frames, inclusive. They are editor-only. - -**Groups** *(v1)* -- A group nests tracks and has its own `RootAnimation`, a transform applied to its tracks after the animation's root. - -**Layer order** -- Layers draw in `LayerAnimations` order: the first one is drawn first, so it ends up at the bottom. -- `Depth` on a layer frame moves it among the layers for that frame. The sort key is (position in the list + depth, depth). - -**Triggers** -- A trigger's events are its `EventId`, followed by its `` children in order. All of them fire on `AtFrame`. -- `` children are the trigger's sounds. The editor picks one at random. -- An older single `SoundId` attribute is still read. - -## Frames -Attributes on `` (layer, null and root tracks): - -| Attribute | Meaning | -|---|---| -| `XPosition`, `YPosition` | Position in pixels; y points down. | -| `XPivot`, `YPivot` | Pivot in the frame's pixels (layer frames). | -| `XCrop`, `YCrop`, `Width`, `Height` | The spritesheet rectangle (layer frames). | -| `XScale`, `YScale` | Scale in percent. A negative value flips. | -| `Rotation` | Degrees, clockwise on screen. | -| `SkewX`, `SkewY` *(v1)* | Skew in percent: `x' = x + SkewX/100·y`, `y' = y + SkewY/100·x`. Older files say `ShearX`/`ShearY`. | -| `RedTint` … `AlphaTint` | 0–255, multiplied. | -| `RedOffset` … `BlueOffset` | 0–255, added after the tint. | -| `AlphaOffset` | 0–255 (may be negative), added to alpha after the tint; the result is clamped to 0–1. | -| `Blur` | Flash's low-quality BlurFilter: a box this many canvas pixels wide, averaged over the frame's crop. | -| `Depth` *(v1)* | Layer frames only; see Layer order. | -| `ShaderId` *(v1)* | A custom shader from ``. | -| `Delay` | Duration in frames. | -| `Visible` | Hidden frames draw nothing. | -| `Interpolated` | `false`, `true` (linear), `EaseIn` (t²), `EaseOut` (1−(1−t)²) or `EaseInOut`. It blends position, scale, skew, rotation, tint, color offset and blur toward the next frame. | - -**A layer frame's transform.** A point `p` of the spritesheet crop, in pixels, lands at: -``` -world = Root · GroupRoot · ( position + Flip · Rotate · Skew · |scale| · (p − pivot) ) -``` -- `Flip` holds the signs of the scale. When exactly one axis is flipped, the rotation turns the other way. -- A root's transform is `position + Flip · Rotate · Skew · |scale| · p`. A root has no pivot. - -### Animation layer frames -On a layer that plays an animation, a frame places and plays the child: - -| Attribute | Default | Meaning | -|---|---|---| -| `ChildAnimation` | the layer's | The animation this keyframe plays, from the same file or library. | -| `ChildMode` | `Loop` | `Loop`, `Once` (stops on its last frame) or `Hold` (stays on the start frame). | -| `ChildStart` | `0` | The child's frame when its clock starts, or `Random`. | -| `Restart` | `false` | Restarts the child's clock at this keyframe. | - -**Placement.** The child's whole drawing goes through the frame's transform, with the frame's pivot as the child's origin: -``` -world = Root · GroupRoot · ( position + Flip · Rotate · Skew · |scale| · (q − pivot) ) -``` -- `q` is a point in the child's space, after the child's own root and groups. -- **Colour:** the frame's tint multiplies the child's colour, and its colour offset adds to it. -- **Unused fields:** crop, size, region and shader are not used. - -**Timing.** The child's time when the parent is at time `t`: -1. **Clock start.** The child's clock starts at the first keyframe. It restarts at any keyframe with `Restart="true"`, or whose `ChildAnimation` differs from the previous keyframe's. Each start begins at that keyframe's `ChildStart`. -2. **Child time.** Take the start keyframe that most recently began (call its start frame `S` and its `ChildStart` `C`). The child time is `C + (t − S)`. -3. **Mode.** The keyframe playing at `t` decides the mode: - - `Loop` wraps the time over the child's `FrameNum`. - - `Once` stops at `FrameNum − 1`. - - `Hold` uses that keyframe's own `ChildStart`. -4. **Random start.** A `Random` start is `(layerId·73856093 xor keyframeIndex·19349663) mod FrameNum`, using unsigned 32-bit arithmetic. - -**Child triggers.** A child fires its trigger on each frame it reaches. That is the frames where its whole-number time, or its animation, differs from the previous parent frame's, and always on parent frame 0. A held child fires once. - -## Rebirth copies -A Rebirth document's game copy keeps only what the game reads: -- **Animation layers** are flattened into plain layers, one per layer the child draws, named `layer/childLayer`. Their frames are baked one per frame and skew is dropped. A library's spritesheets are added with paths relative to the document. -- **Children's trigger events** join the animation's triggers, matched by name. -- **Triggers** keep one event each: the first. -- **Dropped attributes:** markers, depth, skew, alpha offset, blur, shaders, extra events, trigger sounds and libraries. -- **SVG spritesheets** are offered for conversion to PNGs before saving. diff --git a/docs/json_format.md b/docs/json_format.md new file mode 100644 index 0000000..542771d --- /dev/null +++ b/docs/json_format.md @@ -0,0 +1,192 @@ +# Anm2Ed JSON format (version 1) + +The JSON format is the editor's own document, saved alone when **Save as JSON** is on (Configure → Serialization). It holds everything the editor knows about a document; the game can't read it. This page lists its shape and how the editor plays it, so that a converter or a game's loader can match the editor exactly. + +A regular save is different: it writes the game's `.anm2` XML, with the editor's copy embedded as ``. See [XML saves](#xml-saves). + +## Recognizing one +```json +{ + "anm2ed": 1, + "info": {"createdBy": "…", "createdOn": "2026-01-01T12:00:00", "fps": 30, "version": 2}, + … +} +``` +- **`anm2ed`** is the format version. A JSON file without it is not opened. +- **Defaults are left out.** Any key missing from an object has its default (listed below). +- **Ids are indices.** An item is referred to by its position in its array, starting at 0. +- **Unknown keys, wrong types, unknown values and out-of-range indices** are reported by where they are (e.g. `animations.Idle.layers[0].frames[2].pos: expected an array of 2 numbers`); the document still opens, with the default in their place. +- **`createdOn`** is ISO 8601 local time. + +## Content +```json +"spritesheets": [ + {"path": "parts.png"}, + { + "path": "body.svg", + "regions": [ + {"name": "head", "crop": [48, 0], "size": [32, 32], "pivot": [16, 16], "origin": "center"} + ] + } +], +"shaders": [ + {"name": "glow", "vertex": "glow.vs", "fragment": "glow.fs", "uniforms": [{"name": "strength", "value": "0.5"}]} +], +"layers": [ + {"name": "torso", "sheet": 1}, + {"name": "hx", "animation": "Head"}, + {"name": "shadow", "library": 0, "animation": "SmallShadow"} +], +"nulls": [ + {"name": "hitbox", "showRect": true} +], +"events": [ + "shoot", + "done" +], +"sounds": [ + "sounds/step.ogg" +], +"libraries": [ + "shared/shadows.anm2" +] +``` + +| Item | Key | Default | Meaning | +|---|---|---|---| +| Spritesheet | `path` | | The image, relative to the document. | +| Region | `name` | `""` | | +| | `crop`, `size`, `pivot` | `[0, 0]` | The rectangle in the spritesheet, and its pivot. | +| | `origin` | custom | `topLeft` or `center` sets the pivot from the size. | +| Shader | `name`, `vertex`, `fragment` | `""` | A custom shader and its source files. | +| | `uniforms` | none | `{ name, binding, value, components: [ { index, binding, value } ] }` | +| Layer | `name` | `""` | The name code should use for the layer (or its instance). | +| | `sheet` | `0` | Its spritesheet; `-1` for one that is missing. | +| | `animation` | none | Makes it an animation layer, playing this animation. | +| | `library` | none | Where `animation` comes from; none means this file. | +| Null | `name` | `""` | | +| | `showRect` | `false` | | +| Event, sound, library | | | A name, or a path relative to the document. | + +**SVG spritesheets** +- A spritesheet whose path ends in `.svg` is an SVG. +- One SVG unit is one pixel. Crops, sizes and pivots are in SVG units. +- The editor draws an SVG at whatever resolution it is shown at. + +**Libraries** +- A library is another `.anm2` (XML or JSON) whose animations layers can play. +- A path is relative to the file that names it, so a library's own libraries are relative to that library. + +**Layers** +- A layer either shows its spritesheet, or plays an animation when `animation` is set. +- **No self-nesting:** an animation never plays inside itself, even through other animations. That draw is skipped. + +## Animations +Animations are an object keyed by their name; names are unique (a repeated one is saved as `"Name 2"`, `"Name 3"`…). A key whose object has an `animations` object is a group of animations. +```json +"defaultAnimation": "Walk", +"animations": { + "Walk": { + "length": 24, "startMarker": 4, "endMarker": 19, + "root": […frames…], + "layers": [ + {"layer": 0, "frames": […frames…]}, + {"group": "arms", "root": […frames…], "layers": [{"layer": 3, "frames": […]}]} + ], + "nulls": [{"null": 0, "frames": […]}], + "triggers": [ + {"at": 12, "events": [0], "sounds": [0]}, + {"at": 23, "events": [0, 1]} + ] + }, + "Combat": {"expanded": false, "animations": {"Attack": {…}}} +} +``` + +| Key | Default | Meaning | +|---|---|---| +| `length` | `1` | Frames in the animation. | +| `loop` | `true` | | +| `startMarker`, `endMarker` | none | Editor playback stays between these frames, inclusive. Editor-only. | +| `root`, `triggers` | none | Frame arrays. | +| `layers`, `nulls` | none | Tracks and groups, in order. | +| Track `layer` / `null` | | The item the track animates. | +| Track `visible` | `true` | | +| Group `group` | | The group's name; always present. | +| Group `expanded`, `visible` | `true` | Timeline state. | +| Group `root` | one default frame | A transform applied to its tracks after the animation's root. | +| Trigger `at` | | The frame it fires on. | +| Trigger `events` | none | Every event fires on `at`. | +| Trigger `sounds` | none | The editor picks one at random. | + +**Layer order** +- Layers draw in `layers` order: the first one is drawn first, so it ends up at the bottom. +- `depth` on a layer frame moves it among the layers for that frame. The sort key is (position in the list + depth, depth). + +## Frames +Keys on a frame of a layer, null or root track: + +| Key | Default | Meaning | +|---|---|---| +| `pos` | `[0, 0]` | Position in pixels; y points down. | +| `region` | none | Layer frames: a region of the layer's spritesheet. The frame takes its crop, size and pivot, and has none of its own. | +| `crop`, `size` | `[0, 0]` | Layer frames without a region: the spritesheet rectangle. | +| `pivot` | `[0, 0]` | Layer frames without a region: the pivot in the frame's pixels. | +| `scale` | `[100, 100]` | Percent. A negative value flips. | +| `rotation` | `0` | Degrees, clockwise on screen. | +| `skew` | `[0, 0]` | Percent: `x' = x + skew.x/100·y`, `y' = y + skew.y/100·x`. | +| `tint` | `[255, 255, 255, 255]` | RGBA, multiplied. | +| `offset` | `[0, 0, 0, 0]` | RGBA, added after the tint. Alpha may be negative; the result is clamped to 0–1. | +| `blur` | `0` | Layer frames: Flash's low-quality BlurFilter, a box this many canvas pixels wide, averaged over the frame's crop. | +| `depth` | `0` | Layer frames; see Layer order. | +| `shader` | none | A custom shader from `shaders`. | +| `delay` | `1` | Duration in frames. | +| `visible` | `true` | Hidden frames draw nothing. | +| `interpolation` | none | `linear`, `easeIn` (t²), `easeOut` (1−(1−t)²) or `easeInOut`. It blends position, scale, skew, rotation, tint, color offset and blur toward the next frame. | + +**A layer frame's transform.** A point `p` of the spritesheet crop, in pixels, lands at: +``` +world = Root · GroupRoot · ( pos + Flip · Rotate · Skew · |scale| · (p − pivot) ) +``` +- `Flip` holds the signs of the scale. When exactly one axis is flipped, the rotation turns the other way. +- A root's transform is `pos + Flip · Rotate · Skew · |scale| · p`. A root has no pivot. + +### Animation layer frames +On a layer that plays an animation, a frame places and plays the child: + +| Key | Default | Meaning | +|---|---|---| +| `child` | the layer's | The animation this keyframe plays, from the same file or library. | +| `childMode` | `loop` | `loop`, `once` (stops on its last frame) or `hold` (stays on the start frame). | +| `childStart` | `0` | The child's frame when its clock starts. | +| `childStartRandom` | `false` | Start on a random frame instead. | +| `restart` | `false` | Restarts the child's clock at this keyframe. | + +**Placement.** The child's whole drawing goes through the frame's transform, with the frame's pivot as the child's origin: +``` +world = Root · GroupRoot · ( pos + Flip · Rotate · Skew · |scale| · (q − pivot) ) +``` +- `q` is a point in the child's space, after the child's own root and groups. +- **Colour:** the frame's tint multiplies the child's colour, and its offset adds to it. +- **Unused keys:** crop, size, region and shader are not used. + +**Timing.** The child's time when the parent is at time `t`: +1. **Clock start.** The child's clock starts at the first keyframe. It restarts at any keyframe with `restart`, or whose `child` differs from the previous keyframe's. Each start begins at that keyframe's `childStart`. +2. **Child time.** Take the start keyframe that most recently began (call its start frame `S` and its `childStart` `C`). The child time is `C + (t − S)`. +3. **Mode.** The keyframe playing at `t` decides the mode: + - `loop` wraps the time over the child's `length`. + - `once` stops at `length − 1`. + - `hold` uses that keyframe's own `childStart`. +4. **Random start.** A random start is `(layerIndex·73856093 xor keyframeIndex·19349663) mod length`, using unsigned 32-bit arithmetic. + +**Child triggers.** A child fires its trigger on each frame it reaches. That is the frames where its whole-number time, or its animation, differs from the previous parent frame's, and always on parent frame 0. A held child fires once. + +## XML saves +A regular save writes the game's `.anm2` XML, keeping only what the game reads, followed by the editor's full copy as `` (the same data as the JSON, in XML): +- **Animation layers** are flattened into plain layers, one per layer the child draws, named `layer/childLayer`. Their frames are baked one per frame and skew is dropped. A library's spritesheets are added with paths relative to the document. +- **Children's trigger events** join the animation's triggers, matched by name. +- **Triggers** keep one event each: the first. +- **Dropped attributes:** markers, depth, skew, alpha offset, blur, shaders, extra events, trigger sounds and libraries. +- **SVG spritesheets** are offered for conversion to PNGs before saving. + +Older editor files saved without a game copy (the former extended format) still open, and are written as above when saved again. diff --git a/external/simdjson b/external/simdjson new file mode 160000 index 0000000..cfcbfa3 --- /dev/null +++ b/external/simdjson @@ -0,0 +1 @@ +Subproject commit cfcbfa3311ed7b320041e1b719e0c39987dc5cc7 diff --git a/src/document.cpp b/src/document.cpp index eafeab3..cfd7ad2 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -49,7 +49,10 @@ namespace anm2ed::document void library_load(const std::filesystem::path& path, LibraryData& library) { library = {}; - model::model_load(library.model, path); + std::string errorString{}; + model::model_load(library.model, path, &errorString); + // Why it couldn't load, or what a JSON library couldn't read. + if (!errorString.empty()) toast_log(Level::WARNING, TOAST_LIBRARY_ISSUES, path::to_utf8(path), errorString); std::error_code ec{}; library.writeTime = std::filesystem::last_write_time(path, ec); util::WorkingDirectory workingDirectory(path.parent_path()); @@ -181,11 +184,10 @@ namespace anm2ed::document namespace anm2ed { - Document::Document(const std::filesystem::path& path, bool isNew, std::string* errorString, bool isExtendedFormat) + Document::Document(const std::filesystem::path& path, bool isNew, std::string* errorString) { tabId = document::document_tab_id_next(); model = model::model_make(); - model.isExtendedFormat = isExtendedFormat; if (!isNew) model::model_load(model, path, errorString); if (isNew ? !save(path, errorString) : !model.isValid) { @@ -210,11 +212,11 @@ namespace anm2ed return *this; } - bool Document::save(const std::filesystem::path& path, std::string* errorString, bool isPurgeDefaultColors) + bool Document::save(const std::filesystem::path& path, std::string* errorString, Options options) { auto absolutePath = !path.empty() ? path : this->path; auto absolutePathUtf8 = path::to_utf8(absolutePath); - if (file_write(absolutePath, errorString, isPurgeDefaultColors)) + if (file_write(absolutePath, errorString, options)) { this->path = absolutePath; toast_log(Level::INFO, TOAST_SAVE_DOCUMENT, absolutePathUtf8); @@ -226,10 +228,10 @@ namespace anm2ed } // Writes the document; a Rebirth document's game copy has its animation layers flattened into plain layers. - bool Document::file_write(const std::filesystem::path& path, std::string* errorString, bool isPurgeDefaultColors) + bool Document::file_write(const std::filesystem::path& path, std::string* errorString, Options options) { std::optional game{}; - if (!model.isExtendedFormat && std::ranges::any_of(model.content.layers, &model::Layer::is_animation)) + if (!options.isJson && std::ranges::any_of(model.content.layers, &model::Layer::is_animation)) game = edit::animation_layers_flatten( model, library_resolver_get(), [&](const model::Model& source, const std::filesystem::path& spritesheetPath) @@ -241,10 +243,8 @@ namespace anm2ed std::filesystem::absolute(directory_get()))); return spritesheetPath; }); - return model::model_save(model, path, errorString, - {.isExtendedFormat = model.isExtendedFormat, - .isPurgeDefaultColors = isPurgeDefaultColors, - .gameModel = game ? &*game : nullptr}); + options.gameModel = game ? &*game : nullptr; + return model::model_save(model, path, errorString, options); } std::filesystem::path Document::autosave_path_get() @@ -262,11 +262,11 @@ namespace anm2ed return path.parent_path() / std::filesystem::path(std::u8string(fileName.begin(), fileName.end())); } - bool Document::autosave(std::string* errorString, bool isPurgeDefaultColors) + bool Document::autosave(std::string* errorString, Options options) { auto autosavePath = autosave_path_get(); auto autosavePathUtf8 = path::to_utf8(autosavePath); - if (file_write(autosavePath, errorString, isPurgeDefaultColors)) + if (file_write(autosavePath, errorString, options)) { for (auto id : spritesheets_autosave_dirty_get()) { diff --git a/src/document.hpp b/src/document.hpp index 2716c17..5e42aaf 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -125,13 +125,13 @@ namespace anm2ed EditTarget editTarget{EditTarget::NONE}; model::UidIndex index{}; - Document(const std::filesystem::path&, bool = false, std::string* = nullptr, bool = false); + Document(const std::filesystem::path&, bool = false, std::string* = nullptr); Document(const Document&) = delete; Document& operator=(const Document&) = delete; Document(Document&&) noexcept; Document& operator=(Document&&) noexcept; - bool save(const std::filesystem::path& = {}, std::string* = nullptr, bool = true); - bool file_write(const std::filesystem::path&, std::string* = nullptr, bool = true); + bool save(const std::filesystem::path& = {}, std::string* = nullptr, Options = SAVE_OPTIONS_DEFAULT); + bool file_write(const std::filesystem::path&, std::string* = nullptr, Options = SAVE_OPTIONS_DEFAULT); void assets_sync(); void texture_change(int); bool texture_reload(int); @@ -228,7 +228,7 @@ namespace anm2ed void sounds_add(const std::vector&); void libraries_add(const std::vector&); - bool autosave(std::string* = nullptr, bool = true); + bool autosave(std::string* = nullptr, Options = SAVE_OPTIONS_DEFAULT); std::filesystem::path autosave_path_get(); std::filesystem::path path_from_autosave_get(const std::filesystem::path&); diff --git a/src/imgui/taskbar.cpp b/src/imgui/taskbar.cpp index 04b252d..9928608 100644 --- a/src/imgui/taskbar.cpp +++ b/src/imgui/taskbar.cpp @@ -51,16 +51,16 @@ namespace anm2ed::imgui if (isQueued) { // Rebirth can't load SVG spritesheets: offer to convert them (the request waits in isaacSave either way). - if (!document->model.isExtendedFormat && !document->isVectorKept && + if (!settings.fileIsJson && !document->isVectorKept && !model::spritesheets_vector_used_get(document->model).empty()) { isaacSave = request; vectorPopup.open(); return false; } - // The game's copy would differ from the document: ask first. - if (settings.fileIsWarnIsaac && !document->model.isExtendedFormat && - model::isaac_issues_get(document->model) != model::IsaacIssues{}) + // The game can't read JSON, or its copy would differ from the document: ask first. + if (settings.fileIsWarnIsaac && + (settings.fileIsJson || model::isaac_issues_get(document->model) != model::IsaacIssues{})) { isaacSave = request; isaacPopup.open(); @@ -131,16 +131,6 @@ namespace anm2ed::imgui if (ImGui::MenuItem(localize.get(LABEL_EXPLORE_XML_LOCATION), nullptr, false, document)) dialog.file_explorer_open(document->path); - // Which game this document is saved for: the editor's format alone, or Rebirth's (with the editor's copy). - auto isExtendedFormat = document && document->model.isExtendedFormat; - if (ImGui::MenuItem(localize.get(LABEL_DOCUMENT_EXTENDED_FORMAT), nullptr, isExtendedFormat, document)) - manager.command_push({manager.selected, [isExtendedFormat](Manager&, Document& document) - { - document.edit_apply(EDIT_DOCUMENT_FORMAT, [&](model::Model& model) - { model.isExtendedFormat = !isExtendedFormat; }); - }}); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_DOCUMENT_EXTENDED_FORMAT)); - ImGui::Separator(); if (ImGui::MenuItem(localize.get(LABEL_EXIT), settings.shortcutExit.c_str())) isQuitting = true; ImGui::EndMenu(); @@ -148,8 +138,7 @@ namespace anm2ed::imgui if (dialog.is_selected(Dialog::ANM2_CREATE)) { auto path = dialog.path; - manager.command_push({.runManager = [path, isExtendedFormat = settings.isFileExtendedFormat](Manager& manager) - { manager.new_(path, isExtendedFormat); }}); + manager.command_push({.runManager = [path](Manager& manager) { manager.new_(path); }}); dialog.reset(); } @@ -408,9 +397,11 @@ namespace anm2ed::imgui isaacPopup.trigger(); if (ImGui::BeginPopupModal(isaacPopup.label(), &isaacPopup.isOpen, ImGuiWindowFlags_NoResize)) { - ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_ISSUES)); - if (auto document = manager.get(isaacSave.index)) + if (settings.fileIsJson) + ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_JSON)); + else if (auto document = manager.get(isaacSave.index)) { + ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_ISSUES)); auto issues = model::isaac_issues_get(document->model); for (auto [count, format] : {std::pair{issues.easedFrames, FORMAT_ISAAC_EASED_FRAMES}, {issues.groupTransforms, FORMAT_ISAAC_GROUP_TRANSFORMS}, @@ -424,8 +415,8 @@ namespace anm2ed::imgui {issues.animationLayers, FORMAT_ISAAC_ANIMATION_LAYERS}, {issues.vectorSpritesheets, FORMAT_ISAAC_VECTOR_SPRITESHEETS}}) if (count > 0) ImGui::BulletText("%s", localize_format(format, count).c_str()); + ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_EDITOR_COPY)); } - ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_EDITOR_COPY)); auto widgetSize = widget_size_with_row_get(2); shortcut(manager.chords[SHORTCUT_CONFIRM]); diff --git a/src/imgui/wizard/configure.cpp b/src/imgui/wizard/configure.cpp index 63833ac..d330548 100644 --- a/src/imgui/wizard/configure.cpp +++ b/src/imgui/wizard/configure.cpp @@ -87,11 +87,11 @@ namespace anm2ed::imgui::wizard ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ISAAC_COMPATIBILITY_WARNING)); ImGui::SeparatorText(localize.get(LABEL_SERIALIZATION)); - ImGui::Checkbox(localize.get(LABEL_EXTENDED_FORMAT), &temporary.isFileExtendedFormat); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_EXTENDED_FORMAT)); - ImGui::SameLine(); ImGui::Checkbox(localize.get(LABEL_PURGE_DEFAULT_COLORS), &temporary.fileIsPurgeDefaultColors); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PURGE_DEFAULT_COLORS)); + ImGui::SameLine(); + ImGui::Checkbox(localize.get(LABEL_SAVE_AS_JSON), &temporary.fileIsJson); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SAVE_AS_JSON)); } ImGui::EndChild(); diff --git a/src/manager.cpp b/src/manager.cpp index 76c7a8e..d2d3072 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -133,10 +133,10 @@ namespace anm2ed if (command.runManager) command.runManager(*this); } - Document* Manager::open(const std::filesystem::path& path, bool isNew, bool isRecent, bool isExtendedFormat) + Document* Manager::open(const std::filesystem::path& path, bool isNew, bool isRecent) { std::string errorString{}; - documents.emplace_back(path, isNew, &errorString, isExtendedFormat); + documents.emplace_back(path, isNew, &errorString); auto pathString = path::to_utf8(path); auto& document = documents.back(); @@ -153,15 +153,13 @@ namespace anm2ed pendingSelected = selected; selection_history_push(selected); toast_log(Level::INFO, TOAST_OPEN_DOCUMENT, pathString); + // A JSON document that opened lists what it couldn't read. + if (!errorString.empty()) toast_log(Level::WARNING, TOAST_OPEN_DOCUMENT_ISSUES, pathString, errorString); return &document; } - // A new document targets the extended format or Rebirth's, as the settings default. - void Manager::new_(const std::filesystem::path& path, bool isExtendedFormat) - { - open(path, true, true, isExtendedFormat); - } + void Manager::new_(const std::filesystem::path& path) { open(path, true, true); } bool Manager::save(int index, const std::filesystem::path& path) { @@ -173,7 +171,7 @@ namespace anm2ed savePath.replace_extension(".anm2"); ensure_parent_directory_exists(savePath); - if (!document->save(savePath, &errorString, isPurgeDefaultColors)) return false; + if (!document->save(savePath, &errorString, saveOptions)) return false; const auto autosavePath = document->autosave_path_get(); autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), previousAutosavePath), @@ -196,7 +194,7 @@ namespace anm2ed { std::string errorString{}; auto autosavePath = document.autosave_path_get(); - if (!document.autosave(&errorString, isPurgeDefaultColors)) return; + if (!document.autosave(&errorString, saveOptions)) return; autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), autosavePath), autosaveFiles.end()); autosaveFiles.insert(autosaveFiles.begin(), autosavePath); @@ -472,7 +470,7 @@ namespace anm2ed // What the manager keeps from the settings: shortcuts, and how documents save. void Manager::settings_apply(Settings& settings) { - isPurgeDefaultColors = settings.fileIsPurgeDefaultColors; + saveOptions = {.isPurgeDefaultColors = settings.fileIsPurgeDefaultColors, .isJson = settings.fileIsJson}; for (int i = 0; i < SHORTCUT_COUNT; i++) chords[i] = imgui::string_to_chord(settings.*SHORTCUT_MEMBERS[i]); } diff --git a/src/manager.hpp b/src/manager.hpp index b82ed21..468e810 100644 --- a/src/manager.hpp +++ b/src/manager.hpp @@ -52,7 +52,7 @@ namespace anm2ed bool isAbleToRecord{}; ImGuiKeyChord chords[SHORTCUT_COUNT]{}; - bool isPurgeDefaultColors{true}; + Options saveOptions{SAVE_OPTIONS_DEFAULT}; std::vector anm2DragDropPaths{}; bool isAnm2DragDrop{}; @@ -94,8 +94,8 @@ namespace anm2ed Document* get(int = -1); void command_push(Command); void commands_run(); - Document* open(const std::filesystem::path&, bool = false, bool = true, bool = false); - void new_(const std::filesystem::path&, bool); + Document* open(const std::filesystem::path&, bool = false, bool = true); + void new_(const std::filesystem::path&); bool save(int, const std::filesystem::path& = {}); bool save(const std::filesystem::path& = {}); void autosave(Document&); diff --git a/src/model/common.hpp b/src/model/common.hpp index e6931f3..edd21b5 100644 --- a/src/model/common.hpp +++ b/src/model/common.hpp @@ -151,8 +151,7 @@ namespace anm2ed SERIALIZE_NESTED_GROUPS = 1 << 6, SERIALIZE_EXTENSIONS = 1 << 7, SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES = 1 << 8, - SERIALIZE_EXTENDED_DOCUMENT = 1 << 9, - SERIALIZE_PURGE_DEFAULT_COLORS = 1 << 10 + SERIALIZE_PURGE_DEFAULT_COLORS = 1 << 9 }; using Flags = int; @@ -171,14 +170,15 @@ namespace anm2ed class Model; } - // How a document saves: the editor's document alone (extended), or the game's copy with the editor's embedded; - // `gameModel` is the game's copy when it differs from the document (animation layers flattened). + // How a document saves: the game's copy with the editor's embedded, or the editor's own JSON; `gameModel` is the + // game's copy when it differs from the document (animation layers flattened). struct Options { - bool isExtendedFormat{}; bool isPurgeDefaultColors{}; // leave out tints of 255 and color offsets of 0, which readers assume + bool isJson{}; // the editor's own JSON document instead const model::Model* gameModel{}; }; + constexpr Options SAVE_OPTIONS_DEFAULT{.isPurgeDefaultColors = true}; #define FRAME_CHANGE_SCALARS \ X(cropX, crop.x, true, false, changeIsCropX, changeCrop.x) \ diff --git a/src/model/json.cpp b/src/model/json.cpp new file mode 100644 index 0000000..ba07949 --- /dev/null +++ b/src/model/json.cpp @@ -0,0 +1,802 @@ +#include "json.hpp" + +#include +#include +#include +#include +#include + +#include + +#include "math.hpp" +#include "path.hpp" +#include "xml.hpp" + +using namespace simdjson; +using namespace anm2ed::util; + +namespace anm2ed::model +{ + constexpr std::string_view VERSION_KEY = "anm2ed"; + constexpr int VERSION = 1; + constexpr std::string_view INDENT = " "; + constexpr std::size_t LINE_WIDTH_MAX = 100; + constexpr std::string_view WHITESPACE = " \t\r\n"; + constexpr std::size_t NUMBER_BUFFER_SIZE = 64; + constexpr std::pair ESCAPES[] = { + {'"', "\\\""}, {'\\', "\\\\"}, {'\n', "\\n"}, {'\r', "\\r"}, {'\t', "\\t"}}; + constexpr std::string_view INTERPOLATION_NAMES[] = {"", "linear", "easeIn", "easeOut", "easeInOut"}; + constexpr std::string_view CHILD_MODE_NAMES[] = {"loop", "once", "hold"}; + constexpr std::string_view ORIGIN_NAMES[] = {"", "topLeft", "center"}; + constexpr std::size_t ISSUES_SHOWN_MAX = 5; + constexpr int HOURS_HALF_DAY = 12; + constexpr int DATE_FIELDS = 6; + constexpr int DATE_MERIDIEM_SIZE = 3; + const std::vector REGIONS_NONE{}; + + bool is_json(std::string_view text) + { + auto start = text.find_first_not_of(WHITESPACE); + return start != std::string_view::npos && text[start] == '{'; + } + + template int index_get(const Items& items, int id) + { + auto it = std::ranges::find(items, id, &std::ranges::range_value_t::id); + return it == items.end() ? -1 : (int)(it - items.begin()); + } + + glm::ivec4 color_to_bytes(const glm::vec4& color) + { + return {math::float_to_uint8(color.r), math::float_to_uint8(color.g), math::float_to_uint8(color.b), + math::float_to_uint8(color.a)}; + } + + glm::vec4 color_from_bytes(const glm::ivec4& bytes) + { + return {math::uint8_to_float(bytes.r), math::uint8_to_float(bytes.g), math::uint8_to_float(bytes.b), + math::uint8_to_float(bytes.a)}; + } + + // The editor keeps dates as "MM/DD/YYYY hh:mm:ss AM"; JSON has them as ISO 8601. Anything else is kept as it is. + std::string date_to_iso(const std::string& date) + { + int month{}, day{}, year{}, hour{}, minute{}, second{}; + char meridiem[DATE_MERIDIEM_SIZE]{}; + if (std::sscanf(date.c_str(), "%d/%d/%d %d:%d:%d %2s", &month, &day, &year, &hour, &minute, &second, meridiem) != + DATE_FIELDS + 1) + return date; + hour = hour % HOURS_HALF_DAY + (std::string_view(meridiem) == "PM" ? HOURS_HALF_DAY : 0); + return std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}", year, month, day, hour, minute, second); + } + + std::string date_from_iso(const std::string& date) + { + int year{}, month{}, day{}, hour{}, minute{}, second{}; + if (std::sscanf(date.c_str(), "%d-%d-%dT%d:%d:%d", &year, &month, &day, &hour, &minute, &second) != DATE_FIELDS) + return date; + auto hour12 = hour % HOURS_HALF_DAY == 0 ? HOURS_HALF_DAY : hour % HOURS_HALF_DAY; + return std::format("{:02}/{:02}/{:04} {:02}:{:02}:{:02} {}", month, day, year, hour12, minute, second, + hour < HOURS_HALF_DAY ? "AM" : "PM"); + } + + void line_break(std::string& text, int depth) + { + text += '\n'; + for (int i = 0; i < depth; ++i) + text += INDENT; + } + + // Writing: defaults are left out and ids become indices. Containers opened inline (and everything inside them) stay + // on one line; any other that fits within LINE_WIDTH_MAX is joined onto one when it closes, unless it keeps its items + // a line each (frames and content items). + struct JsonWriter + { + static constexpr bool IS_READING = false; + + struct Scope + { + bool isInline{}; + bool isJoinable{true}; + std::size_t start{}; + bool isEmpty{true}; + }; + + const Model& model; + std::string text{}; + std::vector scopes{}; + + void separate() + { + if (scopes.empty()) return; + auto& scope = scopes.back(); + if (!scope.isEmpty) text += scope.isInline ? ", " : ","; + if (!scope.isInline) line_break(text, (int)scopes.size()); + scope.isEmpty = false; + } + + void open(char bracket, bool isInline, bool isJoinable = true) + { + scopes.push_back({isInline || (!scopes.empty() && scopes.back().isInline), isJoinable, text.size()}); + text += bracket; + } + + // Line breaks become nothing, or a space after a comma. + void join(const Scope& scope) + { + std::string joined{}; + for (auto i = scope.start; i < text.size(); ++i) + if (text[i] != '\n') + joined += text[i]; + else + { + i = text.find_first_not_of(' ', i + 1) - 1; + if (joined.back() == ',') joined += ' '; + } + auto column = scope.start - (text.rfind('\n', scope.start) + 1); + if (column + joined.size() <= LINE_WIDTH_MAX) text.replace(scope.start, std::string::npos, joined); + } + + void close(char bracket) + { + auto scope = scopes.back(); + scopes.pop_back(); + if (!scope.isEmpty && !scope.isInline) line_break(text, (int)scopes.size()); + text += bracket; + if (!scope.isInline && scope.isJoinable) join(scope); + } + + void key(std::string_view name) + { + separate(); + value(name); + text += ": "; + } + + template void number(T number) + { + char buffer[NUMBER_BUFFER_SIZE]{}; + text.append(buffer, std::to_chars(buffer, buffer + sizeof(buffer), number).ptr); + } + + void value(bool value) { text += value ? "true" : "false"; } + void value(int value) { number(value); } + void value(float value) { number(value); } + void value(const std::string& value) { this->value(std::string_view(value)); } + void value(const std::filesystem::path& value) { this->value(path::to_utf8(value)); } + + void value(std::string_view value) + { + text += '"'; + for (auto character : value) + { + auto escape = std::ranges::find(ESCAPES, character, &std::pair::first); + if (escape != std::end(ESCAPES)) + text += escape->second; + else if ((unsigned char)character < ' ') + text += std::format("\\u{:04x}", (unsigned char)character); + else + text += character; + } + text += '"'; + } + + template void array(const Values& values, int count) + { + open('[', true); + for (int i = 0; i < count; ++i) + { + separate(); + value(values[i]); + } + close(']'); + } + + template void value(const glm::vec& value) { array(value, L); } + void value(const std::vector& value) { array(value, (int)value.size()); } + + template void field(std::string_view name, const T& value) + { + key(name); + this->value(value); + } + + template void field(std::string_view name, const T& value, const std::type_identity_t& defaultValue) + { + if (value != defaultValue) field(name, value); + } + + // Written as `to` makes it (and read back through `from`). + template + void field(std::string_view name, const T& value, const T& defaultValue, To&& to, From&&) + { + field(name, to(value), to(defaultValue)); + } + + template int reference(std::string_view name, int id, const Items& items, int defaultIndex = -1) + { + auto index = index_get(items, id); + field(name, index, defaultIndex); + return index; + } + + template void references(std::string_view name, const std::vector& ids, const Items& items) + { + std::vector indices{}; + for (auto id : ids) + if (auto index = index_get(items, id); index != -1) indices.push_back(index); + field(name, indices, {}); + } + + template + void choice(std::string_view name, E value, const std::string_view (&names)[N], E defaultValue) + { + if (value != defaultValue) field(name, names[(int)value]); + } + + template void object(std::string_view name, Fn&& fn, bool isInline) + { + key(name); + open('{', isInline); + fn(*this); + close('}'); + } + + template + void list(std::string_view name, const std::vector& items, Fn&& fn, bool isInline, bool isJoinable = true) + { + if (items.empty()) return; + key(name); + open('[', false, isJoinable); + for (const auto& item : items) + { + separate(); + open('{', isInline); + fn(*this, item); + close('}'); + } + close(']'); + } + + template void values(std::string_view name, const std::vector& items, Get&& get) + { + if (items.empty()) return; + key(name); + open('[', false, false); + for (const auto& item : items) + { + separate(); + value(get(item)); + } + close(']'); + } + }; + + // Each returns what it expected when the value is the wrong kind (and leaves the value as it was). + std::string_view value_read(dom::element element, bool& value) + { + bool read{}; + if (element.get(read)) return "true or false"; + value = read; + return {}; + } + + template + requires std::is_same_v || std::is_same_v + std::string_view value_read(dom::element element, T& value) + { + double read{}; + if (element.get(read)) return "a number"; + value = (T)read; + return {}; + } + + std::string_view value_read(dom::element element, std::string& value) + { + std::string_view read{}; + if (element.get(read)) return "a string"; + value = read; + return {}; + } + + std::string_view value_read(dom::element element, std::filesystem::path& value) + { + std::string read{}; + auto expected = value_read(element, read); + if (expected.empty()) value = path::from_utf8(read); + return expected; + } + + template + std::string_view value_read(dom::element element, glm::vec& value) + { + static const auto EXPECTED = std::format("an array of {} numbers", L); + dom::array array{}; + if (element.get(array) || array.size() != L) return EXPECTED; + auto read = value; + int i{}; + for (auto item : array) + if (!value_read(item, read[i++]).empty()) return EXPECTED; + value = read; + return {}; + } + + std::string_view value_read(dom::element element, std::vector& value) + { + dom::array array{}; + if (element.get(array)) return "an array of numbers"; + std::vector read{}; + for (auto item : array) + if (!value_read(item, read.emplace_back()).empty()) return "an array of numbers"; + value = std::move(read); + return {}; + } + + // Reading: only the keys present change the model, and an item's id is its index. Whatever can't be read (and any + // key it doesn't know) is noted in `issues` by where it is, e.g. "animations.Idle.layers[0].frames[2].pos". + struct JsonReader + { + static constexpr bool IS_READING = true; + + const Model& model; + std::vector* issues{}; + std::string path{}; + dom::object fields{}; + std::set used{}; + bool isKeyed{}; // its keys are names rather than fields + + void issue_add(std::string_view name, std::string_view message) + { + issues->push_back(std::format("{}{}: {}", path, name, message)); + } + + bool element_get(std::string_view name, dom::element& element) + { + used.insert(name); + return !fields[name].get(element); + } + + bool has(std::string_view name) + { + dom::element element{}; + return element_get(name, element); + } + + template bool field(std::string_view name, T& value, const std::type_identity_t& = {}) + { + dom::element element{}; + if (!element_get(name, element)) return false; + if (auto expected = value_read(element, value); !expected.empty()) + issue_add(name, std::format("expected {}", expected)); + return true; + } + + template void field(std::string_view name, T& value, const T&, To&& to, From&& from) + { + auto converted = to(value); + if (field(name, converted)) value = from(converted); + } + + template bool is_index_valid(const Items& items, int index) + { + return index >= -1 && index < (int)items.size(); + } + + template int reference(std::string_view name, int& id, const Items& items, int = -1) + { + if (field(name, id) && !is_index_valid(items, id)) issue_add(name, std::format("no item at index {}", id)); + return id; + } + + template void references(std::string_view name, std::vector& ids, const Items& items) + { + if (!field(name, ids)) return; + for (auto id : ids) + if (!is_index_valid(items, id)) issue_add(name, std::format("no item at index {}", id)); + } + + template + void choice(std::string_view name, E& value, const std::string_view (&names)[N], E) + { + std::string read{}; + if (!field(name, read)) return; + auto it = std::ranges::find(names, read); + if (read.empty() || it == std::end(names)) + issue_add(name, std::format("unknown value \"{}\"", read)); + else + value = (E)(it - std::begin(names)); + } + + void unknown_keys_check() + { + if (isKeyed) return; + for (auto [key, value] : fields) + if (!used.contains(key)) issue_add(key, "unknown key"); + } + + // Reads `element` as an object at `childPath` (ending in '.'), then notes the keys it never asked for. + template void object_each(dom::element element, std::string childPath, Fn&& fn) + { + JsonReader reader{model, issues, std::move(childPath)}; + if (element.get(reader.fields)) + { + issues->push_back(std::format("{}: expected an object", reader.path.substr(0, reader.path.size() - 1))); + return; + } + fn(reader); + reader.unknown_keys_check(); + } + + template void object(std::string_view name, Fn&& fn, bool) + { + dom::element element{}; + if (element_get(name, element)) object_each(element, std::format("{}{}.", path, name), fn); + } + + bool array_get(std::string_view name, dom::array& array) + { + dom::element element{}; + if (!element_get(name, element)) return false; + if (!element.get(array)) return true; + issue_add(name, "expected an array"); + return false; + } + + template void list(std::string_view name, std::vector& items, Fn&& fn, bool, bool = true) + { + dom::array array{}; + if (!array_get(name, array)) return; + items.clear(); + for (auto element : array) + { + auto& item = items.emplace_back(); + auto index = (int)items.size() - 1; + if constexpr (requires { item.id; }) item.id = index; + object_each(element, std::format("{}{}[{}].", path, name, index), + [&](JsonReader& reader) { fn(reader, item); }); + } + } + + template void values(std::string_view name, std::vector& items, Get&& get) + { + dom::array array{}; + if (!array_get(name, array)) return; + items.clear(); + for (auto element : array) + { + auto& item = items.emplace_back(); + item.id = (int)items.size() - 1; + if (auto expected = value_read(element, get(item)); !expected.empty()) + issue_add(std::format("{}[{}]", name, item.id), std::format("expected {}", expected)); + } + } + }; + + // Each part of the document is described once; with a JsonWriter it is written, with a JsonReader read. + + template void frame_io(Io& io, F& frame, ItemType type, const std::vector& regions) + { + static const Frame FRAME_DEFAULT{}; + auto& content = io.model.content; + if (type == ItemType::TRIGGER) + { + io.field("at", frame.atFrame, FRAME_DEFAULT.atFrame); + io.references("events", frame.eventIds, content.events); + io.references("sounds", frame.soundIds, content.sounds); + return; + } + // A frame on a region takes the region's rectangle. + if (type == ItemType::LAYER && io.reference("region", frame.regionId, regions) == -1) + { + io.field("crop", frame.crop, FRAME_DEFAULT.crop); + io.field("size", frame.size, FRAME_DEFAULT.size); + io.field("pivot", frame.pivot, FRAME_DEFAULT.pivot); + } + io.field("pos", frame.position, FRAME_DEFAULT.position); + io.field("scale", frame.scale, FRAME_DEFAULT.scale); + io.field("skew", frame.skew, FRAME_DEFAULT.skew); + io.field("rotation", frame.rotation, FRAME_DEFAULT.rotation); + io.field("tint", frame.tint, FRAME_DEFAULT.tint, color_to_bytes, color_from_bytes); + io.field("offset", frame.colorOffset, FRAME_DEFAULT.colorOffset, color_to_bytes, color_from_bytes); + io.field("delay", frame.duration, FRAME_DEFAULT.duration); + io.field("visible", frame.isVisible, FRAME_DEFAULT.isVisible); + io.choice("interpolation", frame.interpolation, INTERPOLATION_NAMES, FRAME_DEFAULT.interpolation); + io.reference("shader", frame.shaderId, content.shaders); + if (type != ItemType::LAYER) return; + io.field("depth", frame.depth, FRAME_DEFAULT.depth); + io.field("blur", frame.blur, FRAME_DEFAULT.blur); + io.field("child", frame.childAnimation, FRAME_DEFAULT.childAnimation); + io.choice("childMode", frame.childMode, CHILD_MODE_NAMES, FRAME_DEFAULT.childMode); + io.field("childStart", frame.childStart, FRAME_DEFAULT.childStart); + io.field("childStartRandom", frame.isChildStartRandom, FRAME_DEFAULT.isChildStartRandom); + io.field("restart", frame.isChildRestart, FRAME_DEFAULT.isChildRestart); + } + + template + void frames_io(Io& io, std::string_view name, Frames& frames, ItemType type, + const std::vector& regions = REGIONS_NONE) + { + // Each frame keeps a line of its own. + io.list(name, frames, [&](auto& frameIo, auto& frame) { frame_io(frameIo, frame, type, regions); }, true, false); + } + + template void track_io(Io& io, T& track, ItemType type) + { + auto isLayer = type == ItemType::LAYER; + if constexpr (Io::IS_READING) track.type = type; + if (isLayer) + io.reference("layer", track.id, io.model.content.layers); + else + io.reference("null", track.id, io.model.content.nulls); + io.field("visible", track.isVisible, true); + auto spritesheet = isLayer ? io.model.layer_spritesheet_get(track.id) : nullptr; + frames_io(io, "frames", track.frames, type, spritesheet ? spritesheet->regions : REGIONS_NONE); + if constexpr (Io::IS_READING) + if (isLayer) + for (auto& frame : track.frames) + frame = io.model.frame_effective(track.id, frame); + } + + // A group is an entry with a "group" name, its root and its own tracks. + template void entries_io(Io& io, std::string_view name, Entries& entries, ItemType type) + { + io.list( + name, entries, + [&](auto& entryIo, auto& entry) + { + if constexpr (Io::IS_READING) + if (entryIo.has("group")) entry = TrackGroup{}; + std::visit( + [&](auto& item) + { + if constexpr (std::is_same_v, Track>) + return track_io(entryIo, item, type); + else + { + entryIo.field("group", item.name); + entryIo.field("expanded", item.isExpanded, true); + entryIo.field("visible", item.isVisible, true); + frames_io(entryIo, "root", item.root.frames, ItemType::ROOT); + entryIo.list( + name, item.tracks, [&](auto& trackIo, auto& track) { track_io(trackIo, track, type); }, false); + } + }, + entry); + }, + false); + if constexpr (Io::IS_READING) + { + int id{}; + groups_each(entries, [&](TrackGroup& group) { group.id = id++; }); + } + } + + template void animation_io(Io& io, A& animation) + { + io.field("length", animation.frameNum, 1); + io.field("loop", animation.isLoop, true); + io.field("startMarker", animation.startMarker, -1); + io.field("endMarker", animation.endMarker, -1); + frames_io(io, "root", animation.root.frames, ItemType::ROOT); + entries_io(io, "layers", animation.layers, ItemType::LAYER); + entries_io(io, "nulls", animation.nulls, ItemType::NULL_); + frames_io(io, "triggers", animation.triggers.frames, ItemType::TRIGGER); + } + + // Animations (and groups, which hold an "animations" object) are keyed by name; a repeated name is renumbered. + void animations_write(JsonWriter& io, const Model& model) + { + std::set names{}; + auto name_unique_get = [&](const std::string& name) + { + auto candidate = name; + for (int i = 2; names.contains(candidate); ++i) + candidate = std::format("{} {}", name, i); + names.insert(candidate); + return candidate; + }; + auto animation_write = [&](const Animation& animation) + { io.object(name_unique_get(animation.name), [&](JsonWriter&) { animation_io(io, animation); }, false); }; + + io.object( + "animations", + [&](JsonWriter&) + { + for (const auto& entry : model.animations.entries) + { + if (auto animation = std::get_if>(&entry)) + { + animation_write(**animation); + continue; + } + auto& group = std::get(entry); + io.object( + name_unique_get(group.name), + [&](JsonWriter&) + { + io.field("expanded", group.isExpanded, true); + io.field("visible", group.isVisible, true); + io.object( + "animations", + [&](JsonWriter&) + { + for (const auto& animation : group.animations) + animation_write(*animation); + }, + false); + }, + false); + } + }, + false); + } + + void animations_read(JsonReader& io, Model& model) + { + auto animation_read = [&](std::string_view name, JsonReader& animationIo) + { + Animation animation{.name = std::string(name), .root = {.type = ItemType::ROOT}}; + animation_io(animationIo, animation); + return std::make_shared(std::move(animation)); + }; + int groupId{}; + io.object( + "animations", + [&](JsonReader& animationsIo) + { + animationsIo.isKeyed = true; + for (auto [name, value] : animationsIo.fields) + io.object_each(value, std::format("{}{}.", animationsIo.path, name), + [&](JsonReader& entryIo) + { + if (!entryIo.has("animations")) + { + model.animations.entries.emplace_back(animation_read(name, entryIo)); + return; + } + AnimationGroup group{.id = groupId++, .name = std::string(name)}; + entryIo.field("expanded", group.isExpanded); + entryIo.field("visible", group.isVisible); + entryIo.object( + "animations", + [&](JsonReader& membersIo) + { + membersIo.isKeyed = true; + for (auto [memberName, member] : membersIo.fields) + io.object_each( + member, std::format("{}{}.", membersIo.path, memberName), + [&](JsonReader& animationIo) + { group.animations.push_back(animation_read(memberName, animationIo)); }); + }, + false); + model.animations.entries.emplace_back(std::move(group)); + }); + }, + false); + } + + // Content comes before animations, which read it. + template void model_io(Io& io, M& model) + { + auto& content = model.content; + io.object( + "info", + [&](auto& infoIo) + { + infoIo.field("createdBy", model.info.createdBy, Info{}.createdBy); + infoIo.field("createdOn", model.info.createdOn, {}, date_to_iso, date_from_iso); + infoIo.field("fps", model.info.fps, Info{}.fps); + infoIo.field("version", model.info.version, Info{}.version); + }, + true); + io.list( + "spritesheets", content.spritesheets, + [](auto& spritesheetIo, auto& spritesheet) + { + spritesheetIo.field("path", spritesheet.path, {}); + spritesheetIo.list( + "regions", spritesheet.regions, + [](auto& regionIo, auto& region) + { + regionIo.field("name", region.name, {}); + regionIo.field("crop", region.crop, {}); + regionIo.field("size", region.size, {}); + regionIo.field("pivot", region.pivot, {}); + regionIo.choice("origin", region.origin, ORIGIN_NAMES, Origin::CUSTOM); + }, + true, false); + }, + false, false); + io.list( + "shaders", content.shaders, + [](auto& shaderIo, auto& shader) + { + shaderIo.field("name", shader.name, {}); + shaderIo.field("vertex", shader.vertex, {}); + shaderIo.field("fragment", shader.fragment, {}); + shaderIo.list( + "uniforms", shader.uniforms, + [](auto& uniformIo, auto& uniform) + { + uniformIo.field("name", uniform.name, {}); + uniformIo.field("binding", uniform.binding, {}); + uniformIo.field("value", uniform.value, {}); + uniformIo.list( + "components", uniform.components, + [](auto& componentIo, auto& component) + { + componentIo.field("index", component.index); + componentIo.field("binding", component.binding, {}); + componentIo.field("value", component.value, {}); + }, + true); + }, + true); + }, + false, false); + io.list( + "layers", content.layers, + [&](auto& layerIo, auto& layer) + { + layerIo.field("name", layer.name, {}); + layerIo.reference("sheet", layer.spritesheetId, content.spritesheets, Layer{}.spritesheetId); + layerIo.reference("library", layer.libraryId, content.libraries); + layerIo.field("animation", layer.animation, {}); + }, + true, false); + io.list( + "nulls", content.nulls, + [](auto& nullIo, auto& null) + { + nullIo.field("name", null.name, {}); + nullIo.field("showRect", null.isShowRect, false); + }, + true, false); + io.values("events", content.events, [](auto& event) -> auto& { return event.name; }); + io.values("sounds", content.sounds, [](auto& sound) -> auto& { return sound.path; }); + io.values("libraries", content.libraries, [](auto& library) -> auto& { return library.path; }); + io.field("defaultAnimation", model.animations.defaultAnimation, {}); + if constexpr (Io::IS_READING) + animations_read(io, model); + else + animations_write(io, model); + } + + std::string model_to_json(const Model& model) + { + JsonWriter io{model}; + io.open('{', false); + io.field(VERSION_KEY, VERSION); + model_io(io, model); + io.close('}'); + io.text += '\n'; + return std::move(io.text); + } + + // Fails only when the text isn't an anm2ed JSON document; anything it couldn't read is listed in `errorString`. + bool model_from_json(Model& model, std::string_view text, std::string* errorString) + { + dom::parser parser{}; + padded_string json(text); + dom::element root{}; + std::vector issues{}; + JsonReader io{model, &issues}; + auto error = parser.parse(json).get(root); + if (!error) error = root.get(io.fields); + if (error || !io.has(VERSION_KEY)) + { + if (errorString) *errorString = error ? error_message(error) : "Not an anm2ed JSON document."; + return false; + } + model = Model{}; + model_io(io, model); + io.unknown_keys_check(); + model_repair(model); + if (!errorString || issues.empty()) return true; + errorString->clear(); + for (std::size_t i = 0; i < std::min(issues.size(), ISSUES_SHOWN_MAX); ++i) + *errorString += (i ? "\n" : "") + issues[i]; + if (issues.size() > ISSUES_SHOWN_MAX) *errorString += std::format("\n({} more)", issues.size() - ISSUES_SHOWN_MAX); + return true; + } +} diff --git a/src/model/json.hpp b/src/model/json.hpp new file mode 100644 index 0000000..93df090 --- /dev/null +++ b/src/model/json.hpp @@ -0,0 +1,15 @@ +#pragma once + +#include +#include + +#include "model.hpp" + +// The editor's own JSON document: content items in arrays (an item's index is its id), animations keyed by their +// unique name, and every value left out when it is the default. Unknown XML (extras) is not kept. +namespace anm2ed::model +{ + bool is_json(std::string_view); + std::string model_to_json(const Model&); + bool model_from_json(Model&, std::string_view, std::string* = nullptr); +} diff --git a/src/model/model.hpp b/src/model/model.hpp index e476ba2..724b4f0 100644 --- a/src/model/model.hpp +++ b/src/model/model.hpp @@ -359,8 +359,6 @@ namespace anm2ed::model std::vector layout{ElementType::INFO, ElementType::CONTENT, ElementType::ANIMATIONS}; Extras extras{}; bool isValid{true}; - // Saved as the editor's document alone (true), or as Rebirth's document with the editor's copy embedded. - bool isExtendedFormat{}; int animations_count_get() const; const Animation* animation_get(int) const; diff --git a/src/model/xml.cpp b/src/model/xml.cpp index 922d131..3c06255 100644 --- a/src/model/xml.cpp +++ b/src/model/xml.cpp @@ -13,6 +13,7 @@ #include "file.hpp" #include "frames.hpp" +#include "json.hpp" #include "math.hpp" #include "path.hpp" #include "time.hpp" @@ -33,7 +34,8 @@ namespace anm2ed::model constexpr std::string_view CHILD_START_RANDOM = "Random"; constexpr const char* TINT_ATTRIBUTES[] = {"RedTint", "GreenTint", "BlueTint", "AlphaTint"}; constexpr const char* OFFSET_ATTRIBUTES[] = {"RedOffset", "GreenOffset", "BlueOffset"}; - // Attributes the editor reads (or older builds wrote); any other attribute is kept verbatim as Extras. + // Attributes the editor reads (or older builds wrote, like ExtendedVersion); any other attribute is kept verbatim as + // Extras. // clang-format off constexpr std::string_view KNOWN_ATTRIBUTES[] = { "Name", "CreatedBy", "CreatedOn", "ExtendedVersion", "Binding", "Value", "DefaultAnimation", "Path", "Vertex", "Fragment", "Id", @@ -51,7 +53,6 @@ namespace anm2ed::model constexpr const char* CREATED_ON_FORMAT = "%m/%d/%Y %I:%M:%S %p"; constexpr const char* SHADER_NAME_DEFAULT = "New Shader"; constexpr std::size_t VALUE_BUFFER_SIZE = 64; - constexpr int EXTENDED_VERSION = 2; constexpr int FLOAT_DIGITS = 8; constexpr int DOUBLE_DIGITS = 17; constexpr double FLOAT_WHOLE_MAX = 1e8; @@ -1724,8 +1725,7 @@ namespace anm2ed::model sink.open(tag.empty() ? tag_get(ElementType::ANIMATED_ACTOR) : tag); extras_write(sink, model.extras); Children children{sink, model.extras}; - auto isInfo = model.info.fps != Info{}.fps || model.info.createdBy != Info{}.createdBy || - writer.is(SERIALIZE_EXTENDED_DOCUMENT); + auto isInfo = model.info.fps != Info{}.fps || model.info.createdBy != Info{}.createdBy; for (auto type : layout_get(model.layout, {{ElementType::INFO, isInfo}, {ElementType::CONTENT, true}, {ElementType::ANIMATIONS, !model.animations.entries.empty()}})) @@ -1739,7 +1739,6 @@ namespace anm2ed::model sink.attribute("CreatedOn", model.info.createdOn); sink.attribute("Fps", model.info.fps); sink.attribute("Version", model.info.version); - if (writer.is(SERIALIZE_EXTENDED_DOCUMENT)) sink.attribute("ExtendedVersion", EXTENDED_VERSION); extras_write(sink, model.info.extras); element_close(sink, model.info.extras); } @@ -1748,12 +1747,10 @@ namespace anm2ed::model sink.close(); } - // A save is the game's document with the editor's own copy embedded as SourceDocument (or just the editor's copy). + // A save is the game's document with the editor's own copy embedded as SourceDocument. void document_write(Sink& sink, const Model& model, Options options) { Flags purge = options.isPurgeDefaultColors ? SERIALIZE_PURGE_DEFAULT_COLORS : 0; - if (options.isExtendedFormat) - return model_write(sink, model, SERIALIZE_ANM2ED_DEFAULT | SERIALIZE_EXTENDED_DOCUMENT | purge); model_write(sink, options.gameModel ? *options.gameModel : model, SERIALIZE_ISAAC_DEFAULT | purge, [&]() { model_write(sink, model, SERIALIZE_ANM2ED_DEFAULT | purge, {}, SOURCE_DOCUMENT_TAG); }); } @@ -1766,21 +1763,24 @@ namespace anm2ed::model return std::move(sink.text); } + bool model_invalid_set(Model& model) + { + model = model_make(); + model.isValid = false; + return false; + } + bool document_load(Model& model, XMLDocument& document, XMLError result, std::string* errorString) { auto root = result == XML_SUCCESS ? document.RootElement() : nullptr; if (!root) { if (errorString) *errorString = result == XML_SUCCESS ? "No root element." : document.ErrorStr(); - model = model_make(); - model.isValid = false; - return false; + return model_invalid_set(model); } auto source = root->Name() == SOURCE_DOCUMENT_TAG ? root : root->FirstChildElement(SOURCE_DOCUMENT_TAG.data()); + // A document without one (as the old extended format saved) is read as the editor's own. model = model_read(source ? source : root); - // An extended document is the editor's own, marked in its Info; anything else is a Rebirth document. - auto info = root->FirstChildElement(tag_get(ElementType::INFO)); - model.isExtendedFormat = !source && info && info->Attribute("ExtendedVersion"); return true; } @@ -1793,17 +1793,15 @@ namespace anm2ed::model bool model_load(Model& model, const std::filesystem::path& path, std::string* errorString) { - XMLDocument document{}; - File file(path, "rb"); - if (file) return document_load(model, document, document.LoadFile(file.get()), errorString); + std::string text{}; + if (file::read_to_string(path, &text)) return model_load_string(model, text, errorString); if (errorString) *errorString = "File not found."; - model = model_make(); - model.isValid = false; - return false; + return model_invalid_set(model); } bool model_load_string(Model& model, std::string_view text, std::string* errorString) { + if (is_json(text)) return model_from_json(model, text, errorString) || model_invalid_set(model); XMLDocument document{}; return document_load(model, document, document.Parse(text.data(), text.size()), errorString); } @@ -1824,6 +1822,7 @@ namespace anm2ed::model std::string model_to_string(const Model& model, Options options) { + if (options.isJson) return model_to_json(model); return text_get([&](Sink& sink) { document_write(sink, model, options); }); } @@ -1836,7 +1835,7 @@ namespace anm2ed::model std::uint64_t model_hash(const Model& model) { Sink sink{.mode = Sink::HASH}; - model_write(sink, model, SERIALIZE_ANM2ED_DEFAULT | (model.isExtendedFormat ? SERIALIZE_EXTENDED_DOCUMENT : 0)); + model_write(sink, model, SERIALIZE_ANM2ED_DEFAULT); return sink.hash; } diff --git a/src/model/xml.hpp b/src/model/xml.hpp index 2cca0cb..dad3f0c 100644 --- a/src/model/xml.hpp +++ b/src/model/xml.hpp @@ -28,6 +28,7 @@ namespace anm2ed::model Model model_make(); IsaacIssues isaac_issues_get(const Model&); + void model_repair(Model&); bool model_load(Model&, const std::filesystem::path&, std::string* = nullptr); bool model_load_string(Model&, std::string_view, std::string* = nullptr); bool model_save(const Model&, const std::filesystem::path&, std::string* = nullptr, Options = {}); diff --git a/src/resource/strings.hpp b/src/resource/strings.hpp index 30a4506..f846061 100644 --- a/src/resource/strings.hpp +++ b/src/resource/strings.hpp @@ -124,7 +124,6 @@ namespace anm2ed X(EDIT_ADD_TRIGGER_SOUND, "Add Trigger Sound", "Añadir Sonido del Trigger", "Добавить звук триггера", "添加事件触发器声音", "트리거 사운드 추가") \ X(EDIT_CONVERT_SVG_SPRITESHEETS, "Convert SVG Spritesheets", "Convertir Spritesheets SVG", "Преобразовать SVG спрайт-листы", "转换 SVG 图集", "SVG 스프라이트 시트 변환") \ X(EDIT_CUT_FRAME_PROPERTY, "Cut Frame Property", "Cortar Propiedad del Frame", "Вырезание свойства кадра", "剪切帧属性", "프레임 속성 잘라내기") \ - X(EDIT_DOCUMENT_FORMAT, "Document Format", "Formato del Documento", "Формат документа", "文档格式", "문서 형식") \ X(EDIT_END_MARKER, "Set End Marker", "Poner Marcador de Fin", "Конечный маркер", "设置结束标记", "끝 마커 설정") \ X(EDIT_FRAME_CHILD, "Frame Child", "Hijo del Frame", "Дочерняя анимация кадра", "帧子动画", "프레임 자식") \ X(EDIT_FRAME_DEPTH, "Frame Depth", "Profundidad del Frame", "Глубина кадра", "帧深度", "프레임 깊이") \ @@ -293,7 +292,6 @@ namespace anm2ed X(LABEL_CONVERT_SVG_POPUP, "Convert SVG Spritesheets", "Convertir Spritesheets SVG", "Преобразовать SVG спрайт-листы", "转换 SVG 图集", "SVG 스프라이트 시트 변환") \ X(LABEL_DETACHABLE_WINDOWS, "Detachable Windows", "Ventanas Desacoplables", "Отделяемые окна", "可分离窗口", "분리 가능한 창") \ X(LABEL_DOCUMENTS_ADD_AS_LIBRARY, "Add as Library", "Añadir como Biblioteca", "Добавить как библиотеку", "添加为库", "라이브러리로 추가") \ - X(LABEL_DOCUMENT_EXTENDED_FORMAT, "Extended Format", "Formato Extendido", "Расширенный формат", "扩展格式", "확장 형식") \ X(LABEL_EVENTS, "Events", "Eventos", "События", "事件", "이벤트") \ X(LABEL_HOLD, "Hold", "Mantener", "Удерживать", "保持", "유지") \ X(LABEL_ISAAC_COMPATIBILITY_WARNING, "Isaac Compatibility Warning", "Advertencia de Compatibilidad con Isaac", "Предупреждение о совместимости с Isaac", "Isaac 兼容性警告", "Isaac 호환성 경고") \ @@ -311,6 +309,7 @@ namespace anm2ed X(LABEL_REMOVE_MARKERS, "Remove Markers", "Quitar Marcadores", "Удалить маркеры", "移除标记", "마커 제거") \ X(LABEL_RESTART, "Restart", "Reiniciar", "Перезапуск", "重新开始", "다시 시작") \ X(LABEL_SAVE_ANYWAY, "Save Anyway", "Guardar de Todos Modos", "Всё равно сохранить", "仍然保存", "그래도 저장") \ + X(LABEL_SAVE_AS_JSON, "Save as JSON", "Guardar como JSON", "Сохранять в JSON", "保存为 JSON", "JSON으로 저장") \ X(LABEL_SPRITESHEETS_PACK_POPUP, "Pack Spritesheet", "Empaquetar spritesheet", "Упаковать спрайт-лист", "打包图集", "스프라이트 시트 패킹") \ X(LABEL_SPRITESHEETS_MERGE_POPUP, "Merge Spritesheets", "Combinar Spritesheets", "Объединить спрайт-листы", "合并图集", "스프라이트 시트 병합") \ X(LABEL_PACK_PADDING, "Padding", "Relleno", "Отступ", "填充", "패딩") \ @@ -440,7 +439,6 @@ namespace anm2ed X(LABEL_OVERWRITE_CONFIRMATION, "Are you sure? This will overwrite the existing file.", "¿Estas Seguro? Esto sobreescribira el archivo existente.", "Вы уверены? Это перезапишет существующий файл.", "你确定吗? 这样会覆盖原本的文件.", "저장하시겠습니까? 기존 파일을 덮어쓰게 됩니다.") \ X(LABEL_OVERWRITE_WARNING, "Overwrite Warning", "Alerta de Sobreescribir", "Предупреждение о перезаписи", "覆盖提醒", "덮어쓰기 경고") \ X(LABEL_SERIALIZATION, "Serialization", "Serialization", "Serialization", "Serialization", "Serialization") \ - X(LABEL_EXTENDED_FORMAT, "Extended Format for New Files", "Formato Extendido para Archivos Nuevos", "Расширенный формат для новых файлов", "新文件使用扩展格式", "새 파일에 확장 형식 사용") \ X(LABEL_PAUSE, "Pause", "Pausar", "Пауза", "暂停", "일시정지") \ X(LABEL_PIVOTS, "Pivots", "Pivotes", "Точки вращения", "枢轴", "중심점") \ X(LABEL_PLAY, "Play", "Reproducir", "Возпроизвести", "播放", "재생") \ @@ -573,6 +571,7 @@ namespace anm2ed X(TEXT_CONVERT_SVG, "Rebirth can't load SVG spritesheets. Convert the ones layers use into PNGs beside them, and use those instead?", "Rebirth no puede cargar spritesheets SVG. ¿Convertir los que usan las capas en PNG junto a ellos y usar esos?", "Rebirth не может загружать SVG спрайт-листы. Преобразовать используемые слоями в PNG рядом с ними и использовать их?", "Rebirth 无法加载 SVG 图集。要将图层使用的图集转换为旁边的 PNG 并改用它们吗?", "Rebirth는 SVG 스프라이트 시트를 불러올 수 없습니다. 레이어가 사용하는 시트를 옆에 PNG로 변환해 대신 사용할까요?") \ X(TEXT_ISAAC_EDITOR_COPY, "The editor's own copy inside the file keeps everything.", "La copia del editor dentro del archivo lo conserva todo.", "Копия редактора внутри файла сохраняет всё.", "文件内的编辑器副本会保留所有内容。", "파일 안의 편집기 사본에는 모든 것이 그대로 남습니다.") \ X(TEXT_ISAAC_ISSUES, "Some of this file won't work in the game as it is:", "Parte de este archivo no funcionará tal cual en el juego:", "Часть этого файла не будет работать в игре как есть:", "此文件的部分内容在游戏中无法按原样工作:", "이 파일의 일부는 게임에서 그대로 작동하지 않습니다:") \ + X(TEXT_ISAAC_JSON, "Save as JSON is on: the game only reads XML, so it won't be able to load this file. Turn it off in Configure to save a copy the game can read.", "Guardar como JSON está activado: el juego solo lee XML, así que no podrá cargar este archivo. Desactívalo en Configurar para guardar una copia que el juego pueda leer.", "Включено сохранение в JSON: игра читает только XML, поэтому не сможет загрузить этот файл. Отключите это в настройках, чтобы сохранить копию, которую игра сможет прочитать.", "已启用保存为 JSON:游戏只读取 XML,因此无法加载此文件。在配置中关闭此选项以保存游戏可读取的副本。", "JSON으로 저장이 켜져 있습니다: 게임은 XML만 읽으므로 이 파일을 불러올 수 없습니다. 게임이 읽을 수 있는 사본을 저장하려면 설정에서 끄세요.") \ X(TEXT_LAYER_ANIMATION, "Layer's", "De la Capa", "Как у слоя", "图层的", "레이어 기본값") \ X(TEXT_SELECT_FRAME, "Select a frame first!", "¡Selecciona primero un frame!", "Сначала выберите кадр!", "请先选择帧!", "먼저 프레임을 선택하세요!") \ X(TEXT_SELECT_FRAME_OR_REGION, "Select a frame or region first!", "¡Selecciona primero un frame o región!", "Сначала выберите кадр или регион!", "请先选择帧或区域!", "먼저 프레임 또는 영역을 선택하세요!") \ @@ -586,7 +585,6 @@ namespace anm2ed X(TOOLTIP_CHILD_TRACK, "A track of the animation this layer plays, timed as it plays here. Double-click to edit it.", "Una pista de la animación que reproduce esta capa, con el tiempo con que se reproduce aquí. Haz doble clic para editarla.", "Дорожка анимации, которую проигрывает этот слой, по времени её проигрывания здесь. Дважды щёлкните, чтобы редактировать.", "此图层播放的动画中的一条轨道,按此处的播放时间显示。双击以编辑。", "이 레이어가 재생하는 애니메이션의 트랙으로, 여기서 재생되는 시간에 맞춰 표시됩니다. 두 번 클릭해 편집하세요.") \ X(TOOLTIP_DEPTH, "Draw this layer this many layers above (or, negative, below) its place in the timeline, for this frame.\n(Editor only; the game always uses the timeline's order.)", "Dibuja esta capa tantas capas por encima (o, en negativo, por debajo) de su lugar en la línea de tiempo, durante este Frame.\n(Solo en el editor; el juego siempre usa el orden de la línea de tiempo.)", "Рисовать этот слой на столько слоёв выше (или, если отрицательно, ниже) его места на таймлайне в этом кадре.\n(Только в редакторе; игра всегда использует порядок таймлайна.)", "在此帧中,将此图层绘制在其时间轴位置之上(负数则之下)若干层。\n(仅限编辑器;游戏始终使用时间轴顺序。)", "이 프레임 동안 이 레이어를 타임라인 위치보다 지정한 수만큼 위(음수면 아래)에 그립니다.\n(편집기 전용이며, 게임은 항상 타임라인 순서를 사용합니다.)") \ X(TOOLTIP_DETACHABLE_WINDOWS, "Windows can be dragged outside the main window into their own windows.\n(Not available on Wayland.)", "Las ventanas pueden arrastrarse fuera de la ventana principal a sus propias ventanas.\n(No disponible en Wayland.)", "Окна можно вытаскивать за пределы главного окна в отдельные окна.\n(Недоступно в Wayland.)", "可以将窗口拖出主窗口,成为独立的窗口。\n(Wayland 下不可用。)", "창을 메인 창 밖으로 끌어내 별도의 창으로 만들 수 있습니다.\n(Wayland에서는 사용할 수 없습니다.)") \ - X(TOOLTIP_DOCUMENT_EXTENDED_FORMAT, "Save this document in the extended Anm2Ed format alone, instead of as a Rebirth document with the editor's copy inside.\nThe extended format is NOT compatible with The Binding of Isaac: Rebirth!", "Guarda este documento solo en el formato extendido de Anm2Ed, en vez de como documento de Rebirth con la copia del editor dentro.\n¡El formato extendido NO es compatible con The Binding of Isaac: Rebirth!", "Сохранять этот документ только в расширенном формате Anm2Ed, а не как документ Rebirth с копией редактора внутри.\nРасширенный формат НЕ совместим с The Binding of Isaac: Rebirth!", "仅以 Anm2Ed 扩展格式保存此文档,而不是保存为内含编辑器副本的 Rebirth 文档。\n扩展格式与 The Binding of Isaac: Rebirth 不兼容!", "이 문서를 편집기 사본이 들어 있는 Rebirth 문서 대신 Anm2Ed 확장 형식으로만 저장합니다.\n확장 형식은 The Binding of Isaac: Rebirth와 호환되지 않습니다!") \ X(TOOLTIP_ISAAC_COMPATIBILITY_WARNING, "Before saving, list anything the game doesn't support and what will happen to it.", "Antes de guardar, muestra lo que el juego no soporta y lo que pasará con ello.", "Перед сохранением показывать всё, что игра не поддерживает, и что с этим произойдёт.", "保存前列出游戏不支持的内容及其处理方式。", "저장하기 전에 게임이 지원하지 않는 항목과 그 처리 방식을 알려줍니다.") \ X(TOOLTIP_LAYER_ANIMATION, "The animation this layer plays.", "La animación que reproduce esta capa.", "Анимация, которую проигрывает этот слой.", "此图层播放的动画。", "이 레이어가 재생하는 애니메이션.") \ X(TOOLTIP_LAYER_ANIMATION_MISSING, "This layer's animation isn't in its file; it draws nothing.", "La animación de esta capa no está en su archivo; no dibuja nada.", "Анимации этого слоя нет в её файле; слой ничего не рисует.", "此图层的动画不在其文件中;它不会绘制任何内容。", "이 레이어의 애니메이션이 파일에 없어 아무것도 그리지 않습니다.") \ @@ -634,9 +632,11 @@ namespace anm2ed X(TOAST_ADD_SOUND_FAILED, "Failed to add sound! Open a document first.", "¡Error al añadir sonido! Abre un documento primero.", "Не удалось добавить звук! Сначала откройте документ.", "无法添加声音!请先打开文档。", "사운드를 추가할 수 없습니다! 먼저 문서를 여세요.") \ X(TOAST_INVALID_FFMPEG, "Unable to run FFmpeg. Make sure the executable exists, has the proper permissions, and is a valid FFmpeg executable.", "No se pudo ejecutar FFmpeg. Asegúrate de que el ejecutable exista, tenga los permisos adecuados y sea un FFmpeg válido.", "Не удалось запустить FFmpeg. Убедитесь, что исполняемый файл существует, имеет нужные права и является корректным исполняемым FFmpeg.", "无法运行 FFmpeg。请确保可执行文件存在,具有正确的权限,并且是有效的 FFmpeg 可执行文件。", "FFmpeg을 실행할 수 없습니다. 실행 파일이 존재하고 올바른 권한을 가지며 유효한 FFmpeg 실행 파일인지 확인하세요.") \ X(TOAST_LIBRARY_INITIALIZED, "Initialized library #{0}: {1}", "Biblioteca inicializada #{0}: {1}", "Библиотека #{0} инициализирована: {1}", "已初始化库 #{0}: {1}", "{0}번 라이브러리 초기화됨: {1}") \ + X(TOAST_LIBRARY_ISSUES, "Library has issues: {0}\n{1}", "La biblioteca tiene problemas: {0}\n{1}", "Проблемы с библиотекой: {0}\n{1}", "库存在问题: {0}\n{1}", "라이브러리에 문제가 있습니다: {0}\n{1}") \ X(TOAST_NOT_SUPPORTED, "Operation not supported.", "Operacion no soportada.", "Операция не поддерживается.", "不支持此操作.", "해당 작업은 지원되지 않습니다.") \ X(TOAST_OPEN_DOCUMENT, "Opened document: {0}", "Documento Abierto: {0}", "Открыт документ: {0}", "已打开文件: {0}", "{0} 파일 열기") \ X(TOAST_OPEN_DOCUMENT_FAILED, "Failed to open document: {0} ({1})", "Error al abrir el documento: {0} ({1})", "Не удалось открыть документ: {0} ({1})", "打开文件失败: {0} ({1})", "{0} 파일을 여는데 실패했습니다. {1}") \ + X(TOAST_OPEN_DOCUMENT_ISSUES, "Opened document with issues: {0}\n{1}", "Documento abierto con problemas: {0}\n{1}", "Документ открыт с проблемами: {0}\n{1}", "已打开文件,但存在问题: {0}\n{1}", "{0} 파일을 열었지만 문제가 있습니다\n{1}") \ X(TOAST_PNG_DIRECTORY_INVALID, "Unable to create PNG directory. Make sure to check permissions.", "No se puede crear el directorio PNG. Verifica los permisos.", "Не удалось создать каталог PNG. Проверьте права доступа.", "无法创建 PNG 目录。请检查权限。", "PNG 디렉터리를 만들 수 없습니다. 권한을 확인하세요.") \ X(TOAST_PNG_FORMAT_INVALID, "PNG format invalid. Make sure it contains \"{}\".", "Formato PNG inválido. Asegúrate de que contenga \"{}\".", "Недопустимый формат PNG. Убедитесь, что он содержит \"{}\".", "PNG 格式无效。请确保其中包含 \"{}\"。", "PNG 형식이 잘못되었습니다. \"{}\"을 포함하는지 확인하세요.") \ X(TOAST_REDO, "Redo: {0}", "Rehacer: {0}", "Повтор: {0}", "重做: {0}", "다시 실행: {0}") \ @@ -779,7 +779,6 @@ namespace anm2ed X(TOOLTIP_OVERLAY_OVER, "Draw the overlay animation above the current animation.", "Dibuja la animacion overlay encima de la animacion actual.", "Рисовать оверлей-анимацию поверх текущей анимации.", "在当前动画上方绘制覆盖动画.", "오버레이 애니메이션을 현재 애니메이션 위에 그립니다.") \ X(TOOLTIP_OVERLAY_UNDER, "Draw the overlay animation below the current animation.", "Dibuja la animacion overlay debajo de la animacion actual.", "Рисовать оверлей-анимацию под текущей анимацией.", "在当前动画下方绘制覆盖动画.", "오버레이 애니메이션을 현재 애니메이션 아래에 그립니다.") \ X(TOOLTIP_OVERWRITE_WARNING, "A warning will be shown when saving/overwriting a file.", "Una advertencia se mostrara cuando se este guardando/sobreguardando un archivo.", "При сохранении/перезаписи файла будет показано предупреждение.", "保存或覆盖文件时会提示确认。", "저장하거나 덮어쓸 때 경고가 표시됩니다.") \ - X(TOOLTIP_EXTENDED_FORMAT, "New documents save in the extended Anm2Ed format, with no Rebirth copy.\nEach document keeps its own format; change it from the File menu.\nThe extended format is NOT compatible with The Binding of Isaac: Rebirth!", "Los documentos nuevos se guardan en el formato extendido de Anm2Ed, sin copia para Rebirth.\nCada documento conserva su formato; cámbialo desde el menú Archivo.\n¡El formato extendido NO es compatible con The Binding of Isaac: Rebirth!", "Новые документы сохраняются в расширенном формате Anm2Ed, без копии для Rebirth.\nУ каждого документа свой формат; его можно сменить в меню «Файл».\nРасширенный формат НЕ совместим с The Binding of Isaac: Rebirth!", "新文档以 Anm2Ed 扩展格式保存,不含 Rebirth 副本。\n每个文档保留自己的格式,可在“文件”菜单中更改。\n扩展格式与 The Binding of Isaac: Rebirth 不兼容!", "새 문서를 Rebirth 사본 없이 Anm2Ed 확장 형식으로 저장합니다.\n문서마다 자체 형식을 유지하며, 파일 메뉴에서 바꿀 수 있습니다.\n확장 형식은 The Binding of Isaac: Rebirth와 호환되지 않습니다!") \ X(TOOLTIP_PAUSE_ANIMATION, "Pause the animation.", "Pausa la animacion.", "Поставить анимацию на паузу.", "暂停动画.", "애니메이션을 일시정지합니다.") \ X(TOOLTIP_PIVOT, "Change the pivot of the frame; i.e., where it is centered.", "Cambia el pivote del Frame; i. e., donde esta centrado.", "Изменить точку поворота кадра, т. е. где он центрирован.", "更改帧枢轴; 比如可以让帧枢轴居中.", "프레임의 중심점을 변경합니다.") \ X(TOOLTIP_PIVOTS, "Toggle the visibility of the animation's pivots.", "Alterna la visibilidad de los pivotes de la animacion.", "Переключить видимость точек поворота анимации.", "切换动画枢轴是否可见.", "애니메이션의 중심점을 표시하거나 숨깁니다.") \ @@ -793,6 +792,7 @@ namespace anm2ed X(TOOLTIP_RELOAD_LIBRARIES, "Reloads the selected libraries.", "Recarga las bibliotecas seleccionadas.", "Перезагружает выбранные библиотеки.", "重新加载所选库.", "선택한 라이브러리를 다시 불러옵니다.") \ X(TOOLTIP_REMOVE_TRIGGER_EVENT, "Remove the last trigger event.", "Remover el último evento del trigger.", "Удалить последнее событие триггера.", "移除最后一个触发事件。", "마지막 트리거 이벤트를 제거합니다.") \ X(TOOLTIP_REMOVE_UNUSED_LIBRARIES, "Remove libraries no layer plays from.", "Elimina las bibliotecas que ninguna capa usa.", "Удалить библиотеки, которые не использует ни один слой.", "删除没有图层使用的库。", "어떤 레이어도 사용하지 않는 라이브러리를 제거합니다.") \ + X(TOOLTIP_SAVE_AS_JSON, "Save documents as JSON (the editor's copy only; the game reads XML). JSON documents are recognized when opened either way.", "Guarda los documentos como JSON (solo la copia del editor; el juego lee XML). Los documentos JSON se reconocen al abrirlos de todas formas.", "Сохранять документы в JSON (только копия редактора; игра читает XML). JSON-документы распознаются при открытии в любом случае.", "将文档保存为 JSON(仅编辑器副本;游戏读取 XML)。无论如何,打开时都会识别 JSON 文档。", "문서를 JSON으로 저장합니다(에디터 사본만, 게임은 XML을 읽습니다). JSON 문서는 어느 경우든 열 때 인식됩니다.") \ X(TOOLTIP_STEP_OUT, "Go back to editing this animation.", "Volver a editar esta animación.", "Вернуться к редактированию этой анимации.", "返回编辑此动画。", "이 애니메이션 편집으로 돌아갑니다.") \ X(TOOLTIP_USE_ANIMATION_BOUNDS, "Render using the animation's bounds instead of the preview viewport.", "Render using the animation's bounds instead of the preview viewport.", "Render using the animation's bounds instead of the preview viewport.", "Render using the animation's bounds instead of the preview viewport.", "Render using the animation's bounds instead of the preview viewport.") \ X(TOOLTIP_USE_ISOLATED_ANIMATION, "Render only animation layers with a transparent background and preview helpers hidden.", "Render only animation layers with a transparent background and preview helpers hidden.", "Render only animation layers with a transparent background and preview helpers hidden.", "Render only animation layers with a transparent background and preview helpers hidden.", "Render only animation layers with a transparent background and preview helpers hidden.") \ diff --git a/src/settings.hpp b/src/settings.hpp index 9f5f538..3ee1f7a 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -65,8 +65,8 @@ namespace anm2ed X(FILE_IS_WARN_OVERWRITE, fileIsWarnOverwrite, STRING_UNDEFINED, BOOL, true) \ X(FILE_IS_WARN_ISAAC, fileIsWarnIsaac, STRING_UNDEFINED, BOOL, true) \ X(FILE_IS_AUTO_RELOAD_RESOURCES, fileIsAutoReloadResources, STRING_UNDEFINED, BOOL, true) \ - X(FILE_IS_EXTENDED_FORMAT, isFileExtendedFormat, STRING_UNDEFINED, BOOL, false) \ X(FILE_IS_PURGE_DEFAULT_COLORS, fileIsPurgeDefaultColors, STRING_UNDEFINED, BOOL, true) \ + X(FILE_IS_JSON, fileIsJson, STRING_UNDEFINED, BOOL, false) \ X(FILE_SNAPSHOT_STACK_SIZE, fileSnapshotStackSize, STRING_UNDEFINED, INT, 50) \ \ X(KEYBOARD_REPEAT_DELAY, keyboardRepeatDelay, STRING_UNDEFINED, FLOAT, 0.300f) \ diff --git a/tests/common.hpp b/tests/common.hpp index 9c1e7bc..70252ca 100644 --- a/tests/common.hpp +++ b/tests/common.hpp @@ -11,6 +11,7 @@ #include #include "edit/edit.hpp" +#include "model/json.hpp" #include "model/xml.hpp" namespace anm2ed::test @@ -23,7 +24,6 @@ namespace anm2ed::test {"editor", SERIALIZE_EDITOR_DEFAULT}, {"isaac", SERIALIZE_ISAAC_DEFAULT}, {"anm2ed", SERIALIZE_ANM2ED_DEFAULT}}; - inline constexpr std::pair FORMATS[] = {{"save", false}, {"extended", true}}; inline constexpr std::pair MERGES[] = {{"merge_prepend", types::merge::PREPEND}, {"merge_append", types::merge::APPEND}, {"merge_replace", types::merge::REPLACE}, @@ -67,15 +67,14 @@ namespace anm2ed::test std::vector variants{}; for (auto [name, flags] : PRESETS) variants.emplace_back(name, model::model_serialize(model, flags)); - for (auto [name, isExtended] : FORMATS) - variants.emplace_back(name, model::model_to_string(model, {.isExtendedFormat = isExtended})); + variants.emplace_back("save", model::model_to_string(model)); for (auto [name, type] : MERGES) { auto merged = model; std::set sources{0, 1, 2}; edit::animations_merge(merged, 0, sources, type, type == types::merge::PREPEND || type == types::merge::REPLACE, {}); - variants.emplace_back(name, model::model_to_string(merged, {.isExtendedFormat = true})); + variants.emplace_back(name, model::model_serialize(merged, SERIALIZE_ANM2ED_DEFAULT)); } return variants; } @@ -96,16 +95,12 @@ namespace anm2ed::test inline void invariants_check(const model::Model& model) { - for (auto [name, isExtended] : FORMATS) - { - INFO("format: ", std::string(name)); - // The first save may repair invalid input (dangling ids, duplicates); after that, saves must be fixed points. - auto text = model::model_to_string(model, {.isExtendedFormat = isExtended}); - auto reloaded = model_load(text); - auto resaved = model::model_to_string(reloaded, {.isExtendedFormat = isExtended}); - CHECK(resaved == text); - CHECK(model::model_hash(model_load(resaved)) == model::model_hash(reloaded)); - } + // The first save may repair invalid input (dangling ids, duplicates); after that, saves must be fixed points. + auto text = model::model_to_string(model); + auto reloaded = model_load(text); + auto resaved = model::model_to_string(reloaded); + CHECK(resaved == text); + CHECK(model::model_hash(model_load(resaved)) == model::model_hash(reloaded)); // Loading only the game's view and re-saving it for the game must not change it. auto game = game_document_get(model::model_to_string(model)); diff --git a/tests/draw.cpp b/tests/draw.cpp index bbba7bd..0f0fd69 100644 --- a/tests/draw.cpp +++ b/tests/draw.cpp @@ -110,7 +110,7 @@ TEST_CASE("an animation layer draws its child animation, from this file or a lib options.library_get = {}; CHECK_FALSE(red_position_get(0)); - auto text = model::model_to_string(anm2, {.isExtendedFormat = true}); + auto text = model::model_serialize(anm2, SERIALIZE_ANM2ED_DEFAULT); CHECK(model::model_hash(model_load(text)) == model::model_hash(anm2)); CHECK(model::isaac_issues_get(anm2).animationLayers == 3); CHECK(game_document_get(model::model_to_string(anm2)).find(" Animation=\"") == std::string::npos); diff --git a/tests/golden/01_minimal.extended.xml b/tests/golden/01_minimal.extended.xml deleted file mode 100644 index 30a6c72..0000000 --- a/tests/golden/01_minimal.extended.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/golden/01_minimal.merge_append.xml b/tests/golden/01_minimal.merge_append.xml index d4005ab..0b1475f 100644 --- a/tests/golden/01_minimal.merge_append.xml +++ b/tests/golden/01_minimal.merge_append.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/01_minimal.merge_ignore.xml b/tests/golden/01_minimal.merge_ignore.xml index d4005ab..0b1475f 100644 --- a/tests/golden/01_minimal.merge_ignore.xml +++ b/tests/golden/01_minimal.merge_ignore.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/01_minimal.merge_prepend.xml b/tests/golden/01_minimal.merge_prepend.xml index d4005ab..0b1475f 100644 --- a/tests/golden/01_minimal.merge_prepend.xml +++ b/tests/golden/01_minimal.merge_prepend.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/01_minimal.merge_replace.xml b/tests/golden/01_minimal.merge_replace.xml index d4005ab..0b1475f 100644 --- a/tests/golden/01_minimal.merge_replace.xml +++ b/tests/golden/01_minimal.merge_replace.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/02_items.extended.xml b/tests/golden/02_items.extended.xml deleted file mode 100644 index e1062c4..0000000 --- a/tests/golden/02_items.extended.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/golden/02_items.merge_append.xml b/tests/golden/02_items.merge_append.xml index f54d7ee..f31bb44 100644 --- a/tests/golden/02_items.merge_append.xml +++ b/tests/golden/02_items.merge_append.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/02_items.merge_ignore.xml b/tests/golden/02_items.merge_ignore.xml index 69edb89..4064a38 100644 --- a/tests/golden/02_items.merge_ignore.xml +++ b/tests/golden/02_items.merge_ignore.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/02_items.merge_prepend.xml b/tests/golden/02_items.merge_prepend.xml index 83a115e..d1b0eaf 100644 --- a/tests/golden/02_items.merge_prepend.xml +++ b/tests/golden/02_items.merge_prepend.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/02_items.merge_replace.xml b/tests/golden/02_items.merge_replace.xml index c753aed..d7c077e 100644 --- a/tests/golden/02_items.merge_replace.xml +++ b/tests/golden/02_items.merge_replace.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/03a_groups_nested.extended.xml b/tests/golden/03a_groups_nested.extended.xml deleted file mode 100644 index acc0d1a..0000000 --- a/tests/golden/03a_groups_nested.extended.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/golden/03a_groups_nested.merge_append.xml b/tests/golden/03a_groups_nested.merge_append.xml index e7df184..c5fcde1 100644 --- a/tests/golden/03a_groups_nested.merge_append.xml +++ b/tests/golden/03a_groups_nested.merge_append.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/03a_groups_nested.merge_ignore.xml b/tests/golden/03a_groups_nested.merge_ignore.xml index f682fdf..abddae4 100644 --- a/tests/golden/03a_groups_nested.merge_ignore.xml +++ b/tests/golden/03a_groups_nested.merge_ignore.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/03a_groups_nested.merge_prepend.xml b/tests/golden/03a_groups_nested.merge_prepend.xml index f203714..8ffbaab 100644 --- a/tests/golden/03a_groups_nested.merge_prepend.xml +++ b/tests/golden/03a_groups_nested.merge_prepend.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/03a_groups_nested.merge_replace.xml b/tests/golden/03a_groups_nested.merge_replace.xml index f362bde..db5bb60 100644 --- a/tests/golden/03a_groups_nested.merge_replace.xml +++ b/tests/golden/03a_groups_nested.merge_replace.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/03b_groups_legacy_flat.extended.xml b/tests/golden/03b_groups_legacy_flat.extended.xml deleted file mode 100644 index dfab7e8..0000000 --- a/tests/golden/03b_groups_legacy_flat.extended.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/golden/03b_groups_legacy_flat.merge_append.xml b/tests/golden/03b_groups_legacy_flat.merge_append.xml index 06819ca..d13cae3 100644 --- a/tests/golden/03b_groups_legacy_flat.merge_append.xml +++ b/tests/golden/03b_groups_legacy_flat.merge_append.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/03b_groups_legacy_flat.merge_ignore.xml b/tests/golden/03b_groups_legacy_flat.merge_ignore.xml index 06819ca..d13cae3 100644 --- a/tests/golden/03b_groups_legacy_flat.merge_ignore.xml +++ b/tests/golden/03b_groups_legacy_flat.merge_ignore.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/03b_groups_legacy_flat.merge_prepend.xml b/tests/golden/03b_groups_legacy_flat.merge_prepend.xml index 06819ca..d13cae3 100644 --- a/tests/golden/03b_groups_legacy_flat.merge_prepend.xml +++ b/tests/golden/03b_groups_legacy_flat.merge_prepend.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/03b_groups_legacy_flat.merge_replace.xml b/tests/golden/03b_groups_legacy_flat.merge_replace.xml index 06819ca..d13cae3 100644 --- a/tests/golden/03b_groups_legacy_flat.merge_replace.xml +++ b/tests/golden/03b_groups_legacy_flat.merge_replace.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/04_group_root_transform.extended.xml b/tests/golden/04_group_root_transform.extended.xml deleted file mode 100644 index 93fba6a..0000000 --- a/tests/golden/04_group_root_transform.extended.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/golden/04_group_root_transform.merge_append.xml b/tests/golden/04_group_root_transform.merge_append.xml index bc06bf1..5cebb7a 100644 --- a/tests/golden/04_group_root_transform.merge_append.xml +++ b/tests/golden/04_group_root_transform.merge_append.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/04_group_root_transform.merge_ignore.xml b/tests/golden/04_group_root_transform.merge_ignore.xml index bc06bf1..5cebb7a 100644 --- a/tests/golden/04_group_root_transform.merge_ignore.xml +++ b/tests/golden/04_group_root_transform.merge_ignore.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/04_group_root_transform.merge_prepend.xml b/tests/golden/04_group_root_transform.merge_prepend.xml index bc06bf1..5cebb7a 100644 --- a/tests/golden/04_group_root_transform.merge_prepend.xml +++ b/tests/golden/04_group_root_transform.merge_prepend.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/04_group_root_transform.merge_replace.xml b/tests/golden/04_group_root_transform.merge_replace.xml index bc06bf1..5cebb7a 100644 --- a/tests/golden/04_group_root_transform.merge_replace.xml +++ b/tests/golden/04_group_root_transform.merge_replace.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/05_regions.extended.xml b/tests/golden/05_regions.extended.xml deleted file mode 100644 index 84765ec..0000000 --- a/tests/golden/05_regions.extended.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/golden/05_regions.merge_append.xml b/tests/golden/05_regions.merge_append.xml index 9c20d9a..463b1fd 100644 --- a/tests/golden/05_regions.merge_append.xml +++ b/tests/golden/05_regions.merge_append.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/05_regions.merge_ignore.xml b/tests/golden/05_regions.merge_ignore.xml index 9c20d9a..463b1fd 100644 --- a/tests/golden/05_regions.merge_ignore.xml +++ b/tests/golden/05_regions.merge_ignore.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/05_regions.merge_prepend.xml b/tests/golden/05_regions.merge_prepend.xml index 9c20d9a..463b1fd 100644 --- a/tests/golden/05_regions.merge_prepend.xml +++ b/tests/golden/05_regions.merge_prepend.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/05_regions.merge_replace.xml b/tests/golden/05_regions.merge_replace.xml index 9c20d9a..463b1fd 100644 --- a/tests/golden/05_regions.merge_replace.xml +++ b/tests/golden/05_regions.merge_replace.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/06_shaders.extended.xml b/tests/golden/06_shaders.extended.xml deleted file mode 100644 index 6d9e746..0000000 --- a/tests/golden/06_shaders.extended.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/golden/06_shaders.merge_append.xml b/tests/golden/06_shaders.merge_append.xml index f2f75cb..c0c97e1 100644 --- a/tests/golden/06_shaders.merge_append.xml +++ b/tests/golden/06_shaders.merge_append.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/06_shaders.merge_ignore.xml b/tests/golden/06_shaders.merge_ignore.xml index f2f75cb..c0c97e1 100644 --- a/tests/golden/06_shaders.merge_ignore.xml +++ b/tests/golden/06_shaders.merge_ignore.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/06_shaders.merge_prepend.xml b/tests/golden/06_shaders.merge_prepend.xml index f2f75cb..c0c97e1 100644 --- a/tests/golden/06_shaders.merge_prepend.xml +++ b/tests/golden/06_shaders.merge_prepend.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/06_shaders.merge_replace.xml b/tests/golden/06_shaders.merge_replace.xml index f2f75cb..c0c97e1 100644 --- a/tests/golden/06_shaders.merge_replace.xml +++ b/tests/golden/06_shaders.merge_replace.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/07_special_interpolation.extended.xml b/tests/golden/07_special_interpolation.extended.xml deleted file mode 100644 index c00c654..0000000 --- a/tests/golden/07_special_interpolation.extended.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/golden/07_special_interpolation.merge_append.xml b/tests/golden/07_special_interpolation.merge_append.xml index b1e5243..06697e4 100644 --- a/tests/golden/07_special_interpolation.merge_append.xml +++ b/tests/golden/07_special_interpolation.merge_append.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/07_special_interpolation.merge_ignore.xml b/tests/golden/07_special_interpolation.merge_ignore.xml index b1e5243..06697e4 100644 --- a/tests/golden/07_special_interpolation.merge_ignore.xml +++ b/tests/golden/07_special_interpolation.merge_ignore.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/07_special_interpolation.merge_prepend.xml b/tests/golden/07_special_interpolation.merge_prepend.xml index b1e5243..06697e4 100644 --- a/tests/golden/07_special_interpolation.merge_prepend.xml +++ b/tests/golden/07_special_interpolation.merge_prepend.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/07_special_interpolation.merge_replace.xml b/tests/golden/07_special_interpolation.merge_replace.xml index b1e5243..06697e4 100644 --- a/tests/golden/07_special_interpolation.merge_replace.xml +++ b/tests/golden/07_special_interpolation.merge_replace.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/08_source_document.extended.xml b/tests/golden/08_source_document.extended.xml deleted file mode 100644 index c9508ee..0000000 --- a/tests/golden/08_source_document.extended.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/golden/08_source_document.merge_append.xml b/tests/golden/08_source_document.merge_append.xml index ef225a9..adc48fd 100644 --- a/tests/golden/08_source_document.merge_append.xml +++ b/tests/golden/08_source_document.merge_append.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/08_source_document.merge_ignore.xml b/tests/golden/08_source_document.merge_ignore.xml index ef225a9..adc48fd 100644 --- a/tests/golden/08_source_document.merge_ignore.xml +++ b/tests/golden/08_source_document.merge_ignore.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/08_source_document.merge_prepend.xml b/tests/golden/08_source_document.merge_prepend.xml index ef225a9..adc48fd 100644 --- a/tests/golden/08_source_document.merge_prepend.xml +++ b/tests/golden/08_source_document.merge_prepend.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/08_source_document.merge_replace.xml b/tests/golden/08_source_document.merge_replace.xml index ef225a9..adc48fd 100644 --- a/tests/golden/08_source_document.merge_replace.xml +++ b/tests/golden/08_source_document.merge_replace.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/09_legacy_quirks.extended.xml b/tests/golden/09_legacy_quirks.extended.xml deleted file mode 100644 index 0cc9fed..0000000 --- a/tests/golden/09_legacy_quirks.extended.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/golden/09_legacy_quirks.merge_append.xml b/tests/golden/09_legacy_quirks.merge_append.xml index 2f5baab..49c38f8 100644 --- a/tests/golden/09_legacy_quirks.merge_append.xml +++ b/tests/golden/09_legacy_quirks.merge_append.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/09_legacy_quirks.merge_ignore.xml b/tests/golden/09_legacy_quirks.merge_ignore.xml index 2f5baab..49c38f8 100644 --- a/tests/golden/09_legacy_quirks.merge_ignore.xml +++ b/tests/golden/09_legacy_quirks.merge_ignore.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/09_legacy_quirks.merge_prepend.xml b/tests/golden/09_legacy_quirks.merge_prepend.xml index 326d5d2..f00a670 100644 --- a/tests/golden/09_legacy_quirks.merge_prepend.xml +++ b/tests/golden/09_legacy_quirks.merge_prepend.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/09_legacy_quirks.merge_replace.xml b/tests/golden/09_legacy_quirks.merge_replace.xml index f346f30..a287eff 100644 --- a/tests/golden/09_legacy_quirks.merge_replace.xml +++ b/tests/golden/09_legacy_quirks.merge_replace.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/10_paths.extended.xml b/tests/golden/10_paths.extended.xml deleted file mode 100644 index 857bac0..0000000 --- a/tests/golden/10_paths.extended.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/golden/10_paths.merge_append.xml b/tests/golden/10_paths.merge_append.xml index dc149db..510d772 100644 --- a/tests/golden/10_paths.merge_append.xml +++ b/tests/golden/10_paths.merge_append.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/10_paths.merge_ignore.xml b/tests/golden/10_paths.merge_ignore.xml index dc149db..510d772 100644 --- a/tests/golden/10_paths.merge_ignore.xml +++ b/tests/golden/10_paths.merge_ignore.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/10_paths.merge_prepend.xml b/tests/golden/10_paths.merge_prepend.xml index dc149db..510d772 100644 --- a/tests/golden/10_paths.merge_prepend.xml +++ b/tests/golden/10_paths.merge_prepend.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/10_paths.merge_replace.xml b/tests/golden/10_paths.merge_replace.xml index dc149db..510d772 100644 --- a/tests/golden/10_paths.merge_replace.xml +++ b/tests/golden/10_paths.merge_replace.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/11_unknown.extended.xml b/tests/golden/11_unknown.extended.xml deleted file mode 100644 index 069371b..0000000 --- a/tests/golden/11_unknown.extended.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - keep me - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/golden/11_unknown.merge_append.xml b/tests/golden/11_unknown.merge_append.xml index e1a1b89..e7ff20f 100644 --- a/tests/golden/11_unknown.merge_append.xml +++ b/tests/golden/11_unknown.merge_append.xml @@ -1,5 +1,5 @@ - + keep me diff --git a/tests/golden/11_unknown.merge_ignore.xml b/tests/golden/11_unknown.merge_ignore.xml index e1a1b89..e7ff20f 100644 --- a/tests/golden/11_unknown.merge_ignore.xml +++ b/tests/golden/11_unknown.merge_ignore.xml @@ -1,5 +1,5 @@ - + keep me diff --git a/tests/golden/11_unknown.merge_prepend.xml b/tests/golden/11_unknown.merge_prepend.xml index e1a1b89..e7ff20f 100644 --- a/tests/golden/11_unknown.merge_prepend.xml +++ b/tests/golden/11_unknown.merge_prepend.xml @@ -1,5 +1,5 @@ - + keep me diff --git a/tests/golden/11_unknown.merge_replace.xml b/tests/golden/11_unknown.merge_replace.xml index e1a1b89..e7ff20f 100644 --- a/tests/golden/11_unknown.merge_replace.xml +++ b/tests/golden/11_unknown.merge_replace.xml @@ -1,5 +1,5 @@ - + keep me diff --git a/tests/golden/operation.animation_add.xml b/tests/golden/operation.animation_add.xml index b6c8244..9302743 100644 --- a/tests/golden/operation.animation_add.xml +++ b/tests/golden/operation.animation_add.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.animation_grid_generate.xml b/tests/golden/operation.animation_grid_generate.xml index daecddb..8b860fa 100644 --- a/tests/golden/operation.animation_grid_generate.xml +++ b/tests/golden/operation.animation_grid_generate.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.animations_group.xml b/tests/golden/operation.animations_group.xml index e54c71f..0c75692 100644 --- a/tests/golden/operation.animations_group.xml +++ b/tests/golden/operation.animations_group.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.animations_merge.xml b/tests/golden/operation.animations_merge.xml index eb9ef19..93d2d3e 100644 --- a/tests/golden/operation.animations_merge.xml +++ b/tests/golden/operation.animations_merge.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.animations_move.xml b/tests/golden/operation.animations_move.xml index fd27895..405687f 100644 --- a/tests/golden/operation.animations_move.xml +++ b/tests/golden/operation.animations_move.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.animations_paste.xml b/tests/golden/operation.animations_paste.xml index 96ee09d..248b4e4 100644 --- a/tests/golden/operation.animations_paste.xml +++ b/tests/golden/operation.animations_paste.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.animations_remove.xml b/tests/golden/operation.animations_remove.xml index 2fa5a5d..d19eabc 100644 --- a/tests/golden/operation.animations_remove.xml +++ b/tests/golden/operation.animations_remove.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.file_merge_append.xml b/tests/golden/operation.file_merge_append.xml index 7947dca..7919ce6 100644 --- a/tests/golden/operation.file_merge_append.xml +++ b/tests/golden/operation.file_merge_append.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.file_merge_by_name.xml b/tests/golden/operation.file_merge_by_name.xml index 7947dca..7919ce6 100644 --- a/tests/golden/operation.file_merge_by_name.xml +++ b/tests/golden/operation.file_merge_by_name.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.file_merge_replace.xml b/tests/golden/operation.file_merge_replace.xml index 7947dca..7919ce6 100644 --- a/tests/golden/operation.file_merge_replace.xml +++ b/tests/golden/operation.file_merge_replace.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frame_bake.xml b/tests/golden/operation.frame_bake.xml index a3754f4..0d13751 100644 --- a/tests/golden/operation.frame_bake.xml +++ b/tests/golden/operation.frame_bake.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frame_insert.xml b/tests/golden/operation.frame_insert.xml index 7cab3de..8344d76 100644 --- a/tests/golden/operation.frame_insert.xml +++ b/tests/golden/operation.frame_insert.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frame_split.xml b/tests/golden/operation.frame_split.xml index 8ad0e2b..5f4c319 100644 --- a/tests/golden/operation.frame_split.xml +++ b/tests/golden/operation.frame_split.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frames_bake.xml b/tests/golden/operation.frames_bake.xml index 386ccd6..c93fc12 100644 --- a/tests/golden/operation.frames_bake.xml +++ b/tests/golden/operation.frames_bake.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frames_change_add.xml b/tests/golden/operation.frames_change_add.xml index 232c136..564e77e 100644 --- a/tests/golden/operation.frames_change_add.xml +++ b/tests/golden/operation.frames_change_add.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frames_change_adjust.xml b/tests/golden/operation.frames_change_adjust.xml index cb83f93..f9f5607 100644 --- a/tests/golden/operation.frames_change_adjust.xml +++ b/tests/golden/operation.frames_change_adjust.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frames_change_apply.xml b/tests/golden/operation.frames_change_apply.xml index a1e3cbf..8901f3d 100644 --- a/tests/golden/operation.frames_change_apply.xml +++ b/tests/golden/operation.frames_change_apply.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frames_change_divide.xml b/tests/golden/operation.frames_change_divide.xml index b537fe1..4583361 100644 --- a/tests/golden/operation.frames_change_divide.xml +++ b/tests/golden/operation.frames_change_divide.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frames_change_multiply.xml b/tests/golden/operation.frames_change_multiply.xml index b44e915..94aec63 100644 --- a/tests/golden/operation.frames_change_multiply.xml +++ b/tests/golden/operation.frames_change_multiply.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frames_change_subtract.xml b/tests/golden/operation.frames_change_subtract.xml index 4a047ce..ec99043 100644 --- a/tests/golden/operation.frames_change_subtract.xml +++ b/tests/golden/operation.frames_change_subtract.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frames_delete.xml b/tests/golden/operation.frames_delete.xml index 299647b..7c293f7 100644 --- a/tests/golden/operation.frames_delete.xml +++ b/tests/golden/operation.frames_delete.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frames_duplicate.xml b/tests/golden/operation.frames_duplicate.xml index 7b46204..67ba483 100644 --- a/tests/golden/operation.frames_duplicate.xml +++ b/tests/golden/operation.frames_duplicate.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frames_move.xml b/tests/golden/operation.frames_move.xml index 1022731..87e466e 100644 --- a/tests/golden/operation.frames_move.xml +++ b/tests/golden/operation.frames_move.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frames_paste.xml b/tests/golden/operation.frames_paste.xml index e7cd6c3..93bf810 100644 --- a/tests/golden/operation.frames_paste.xml +++ b/tests/golden/operation.frames_paste.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.frames_reverse.xml b/tests/golden/operation.frames_reverse.xml index 29abd8f..6a7ab03 100644 --- a/tests/golden/operation.frames_reverse.xml +++ b/tests/golden/operation.frames_reverse.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.item_add.xml b/tests/golden/operation.item_add.xml index ae67659..8e57fcd 100644 --- a/tests/golden/operation.item_add.xml +++ b/tests/golden/operation.item_add.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.items_group.xml b/tests/golden/operation.items_group.xml index f6de948..45e6aec 100644 --- a/tests/golden/operation.items_group.xml +++ b/tests/golden/operation.items_group.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.items_move.xml b/tests/golden/operation.items_move.xml index ba7c79d..796076e 100644 --- a/tests/golden/operation.items_move.xml +++ b/tests/golden/operation.items_move.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.items_remove.xml b/tests/golden/operation.items_remove.xml index 71c8d22..608edf1 100644 --- a/tests/golden/operation.items_remove.xml +++ b/tests/golden/operation.items_remove.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.regions_generate.xml b/tests/golden/operation.regions_generate.xml index ee56a62..daf8c2d 100644 --- a/tests/golden/operation.regions_generate.xml +++ b/tests/golden/operation.regions_generate.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.regions_paste.xml b/tests/golden/operation.regions_paste.xml index 3b5ebc8..78fa5c5 100644 --- a/tests/golden/operation.regions_paste.xml +++ b/tests/golden/operation.regions_paste.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.regions_remove_unused.xml b/tests/golden/operation.regions_remove_unused.xml index 84765ec..0d81369 100644 --- a/tests/golden/operation.regions_remove_unused.xml +++ b/tests/golden/operation.regions_remove_unused.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.regions_scan.xml b/tests/golden/operation.regions_scan.xml index 84765ec..0d81369 100644 --- a/tests/golden/operation.regions_scan.xml +++ b/tests/golden/operation.regions_scan.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.root_bake_into.xml b/tests/golden/operation.root_bake_into.xml index a6c8a62..d83037b 100644 --- a/tests/golden/operation.root_bake_into.xml +++ b/tests/golden/operation.root_bake_into.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.spritesheets_merge.xml b/tests/golden/operation.spritesheets_merge.xml index 94b8ccc..14e9fd9 100644 --- a/tests/golden/operation.spritesheets_merge.xml +++ b/tests/golden/operation.spritesheets_merge.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/golden/operation.trigger_insert.xml b/tests/golden/operation.trigger_insert.xml index 3997de3..9d23f11 100644 --- a/tests/golden/operation.trigger_insert.xml +++ b/tests/golden/operation.trigger_insert.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/invariants.cpp b/tests/invariants.cpp index 0f9dd91..231350c 100644 --- a/tests/invariants.cpp +++ b/tests/invariants.cpp @@ -28,37 +28,75 @@ TEST_CASE("saved text is what tinyxml2 prints for the same document") CHECK(text == printer.CStr()); } -TEST_CASE("a document's format is kept by what it saves") -{ - auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); - CHECK_FALSE(model.isExtendedFormat); - CHECK_FALSE(model_load(model::model_to_string(model)).isExtendedFormat); - - auto rebirthHash = model::model_hash(model); - model.isExtendedFormat = true; - CHECK(model::model_hash(model) != rebirthHash); - auto text = model::model_to_string(model, {.isExtendedFormat = true}); - CHECK(text.find("SourceDocument") == std::string::npos); - auto reloaded = model_load(text); - CHECK(reloaded.isExtendedFormat); - CHECK(model::model_hash(reloaded) == model::model_hash(model)); -} - TEST_CASE("purged default colors read back the same") { for (const auto& fixture : fixtures_get()) { INFO("fixture: ", fixture.string()); auto model = model_load(file_load(fixture)); - for (auto isExtended : {false, true}) - { - auto text = model::model_to_string(model, {.isExtendedFormat = isExtended, .isPurgeDefaultColors = true}); - CHECK(text.find("Tint=\"255\"") == std::string::npos); - CHECK(text.find("Offset=\"0\"") == std::string::npos); - CHECK(text.size() <= model::model_to_string(model, {.isExtendedFormat = isExtended}).size()); - auto reloaded = model_load(text); - reloaded.isExtendedFormat = model.isExtendedFormat; - CHECK(model::model_hash(reloaded) == model::model_hash(model)); - } + auto text = model::model_to_string(model, {.isPurgeDefaultColors = true}); + CHECK(text.find("Tint=\"255\"") == std::string::npos); + CHECK(text.find("Offset=\"0\"") == std::string::npos); + CHECK(text.size() <= model::model_to_string(model).size()); + CHECK(model::model_hash(model_load(text)) == model::model_hash(model)); } } + +TEST_CASE("JSON documents read back as the editor's copy") +{ + for (const auto& fixture : fixtures_get()) + { + INFO("fixture: ", fixture.string()); + auto model = model_load(file_load(fixture)); + auto text = model::model_to_json(model); + auto reloaded = model_load(text); + CHECK(model::model_to_json(reloaded) == text); + // Unknown XML, element order, dangling references and repeated animation names are not kept. + auto isQuirky = fixture.filename() == "09_legacy_quirks.anm2" || fixture.filename() == "11_unknown.anm2"; + if (!isQuirky) + CHECK(model::model_serialize(reloaded, SERIALIZE_ANM2ED_DEFAULT) == + model::model_serialize(model, SERIALIZE_ANM2ED_DEFAULT)); + } +} + +TEST_CASE("JSON animations get unique names") +{ + auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); + model.animations.entries.push_back(model.animations.entries.front()); + auto reloaded = model_load(model::model_to_json(model)); + REQUIRE(reloaded.animations_count_get() == 2); + CHECK(reloaded.animation_get(1)->name == reloaded.animation_get(0)->name + " 2"); +} + +TEST_CASE("JSON dates are ISO 8601") +{ + auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); + for (auto [date, iso] : {std::pair{"01/01/2026 12:00:00 PM", "2026-01-01T12:00:00"}, + {"03/04/2025 12:30:05 AM", "2025-03-04T00:30:05"}, + {"12/31/2024 11:59:59 PM", "2024-12-31T23:59:59"}}) + { + model.info.createdOn = date; + auto text = model::model_to_json(model); + CHECK(text.find(iso) != std::string::npos); + CHECK(model_load(text).info.createdOn == date); + } +} + +TEST_CASE("JSON that can't be read is reported by where it is, and the rest still opens") +{ + auto text = R"({ "anm2ed": 1, "colour": 1, "info": { "fps": "fast" }, + "layers": [ { "name": "a", "sheet": 4 } ], + "animations": { "Idle": { "length": 3, "root": [ { "pos": [1], "interpolation": "bouncy", "delay": 3 } ] } } })"; + model::Model model{}; + std::string issues{}; + REQUIRE(model::model_load_string(model, text, &issues)); + CHECK(model.animation_get(0)->frameNum == 3); + CHECK(model.animation_get(0)->root.frames[0].duration == 3); + for (auto issue : {"colour: unknown key", "info.fps: expected a number", "layers[0].sheet: no item at index 4", + "animations.Idle.root[0].pos: expected an array of 2 numbers", + "animations.Idle.root[0].interpolation: unknown value \"bouncy\""}) + CHECK_MESSAGE(issues.find(issue) != std::string::npos, issue); + + CHECK_FALSE(model::model_load_string(model, "{ \"fps\": 30 }", &issues)); + CHECK_FALSE(model::model_load_string(model, "{ \"anm2ed\": 1, ", &issues)); +} diff --git a/tests/operations.cpp b/tests/operations.cpp index 16e390a..573a347 100644 --- a/tests/operations.cpp +++ b/tests/operations.cpp @@ -12,7 +12,7 @@ model::Model fixture_load(const char* name) { return model_load(file_load(CORPUS void operation_check(const char* name, const model::Model& model) { golden_check(GOLDEN_DIR / std::format("operation.{}.xml", name), - model::model_to_string(model, {.isExtendedFormat = true})); + model::model_serialize(model, SERIALIZE_ANM2ED_DEFAULT)); } model::Track& layer_track_get(model::Model& model, int animationIndex, int layerId) diff --git a/tests/render/render.cpp b/tests/render/render.cpp index 1b0dbd6..e42a36c 100644 --- a/tests/render/render.cpp +++ b/tests/render/render.cpp @@ -247,7 +247,6 @@ TEST_CASE("a Rebirth save flattens animation layers for the game") Document document(directory / "nested.anm2", false); REQUIRE(document.is_valid()); - document.model.isExtendedFormat = false; REQUIRE(document.save(directory / "rebirth.anm2")); std::ifstream file(directory / "rebirth.anm2"); std::string saved(std::istreambuf_iterator(file), {});