diff --git a/docs/json_format.md b/docs/json_format.md index 381ecdf..5e55261 100644 --- a/docs/json_format.md +++ b/docs/json_format.md @@ -1,4 +1,4 @@ -# Anm2Ed JSON format (version 1) +# Anm2Ed JSON format 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. @@ -7,12 +7,11 @@ A regular save is different: it writes the game's `.anm2` XML, with the editor's ## 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. +- **A file is JSON** when its first character, after whitespace, is `{`. There is no format version. - **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. @@ -21,7 +20,7 @@ A regular save is different: it writes the game's `.anm2` XML, with the editor's ## Content ```json -"spritesheets": [ +"sheets": [ {"path": "parts.png"}, { "path": "body.svg", @@ -55,7 +54,7 @@ A regular save is different: it writes the game's `.anm2` XML, with the editor's | Item | Key | Default | Meaning | |---|---|---|---| -| Spritesheet | `path` | | The image, relative to the document. | +| Sheet | `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. | @@ -83,12 +82,12 @@ A regular save is different: it writes the game's `.anm2` XML, with the editor's - **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. +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; a group may share a name with an animation inside it. ```json -"defaultAnimation": "Walk", +"default": "Walk", "animations": { "Walk": { - "length": 24, "startMarker": 4, "endMarker": 19, + "length": 24, "markers": [4, 19], "root": […frames…], "layers": [ {"layer": 0, "frames": […frames…]}, @@ -108,7 +107,7 @@ Animations are an object keyed by their name; names are unique (a repeated one i |---|---|---| | `length` | `1` | Frames in the animation. | | `loop` | `true` | | -| `startMarker`, `endMarker` | none | Editor playback stays between these frames, inclusive. Editor-only. | +| `markers` | `[-1, -1]` | Start and end frames editor playback stays between, inclusive; `-1` for none. Editor-only. | | `root`, `triggers` | none | Frame arrays. | | `layers`, `nulls` | none | Tracks and groups, in order. | | Track `layer` / `null` | | The item the track animates. | @@ -143,7 +142,7 @@ Keys on a frame of a layer, null or root track: | `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. | +| `ease` | none | `lerp`, `in` (t²), `out` (1−(1−t)²) or `inOut`. 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: ``` @@ -153,14 +152,17 @@ world = Root · GroupRoot · ( pos + Flip · Rotate · Skew · |scale| · (p − - 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: +On a layer that plays an animation, a frame places the child, and its `child` object plays it. The object is left out when all its keys are defaults: +```json +{"pos": [8, 0], "child": {"name": "Spin", "mode": "once", "start": 3}} +``` | 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. | +| `name` | the layer's | The animation this keyframe plays, from the same file or library. | +| `mode` | `loop` | `loop`, `once` (stops on its last frame) or `hold` (stays on the start frame). | +| `start` | `0` | The child's frame when its clock starts. | +| `random` | `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: @@ -172,12 +174,12 @@ world = Root · GroupRoot · ( pos + Flip · Rotate · Skew · |scale| · (q − - **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)`. +1. **Clock start.** The child's clock starts at the first keyframe. It restarts at any keyframe with `restart`, or whose `name` differs from the previous keyframe's. Each start begins at that keyframe's `start`. +2. **Child time.** Take the start keyframe that most recently began (call its frame `S` and its `start` `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`. + - `hold` uses that keyframe's own `start`. 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. diff --git a/src/model/json.cpp b/src/model/json.cpp index 07e8f82..0a83351 100644 --- a/src/model/json.cpp +++ b/src/model/json.cpp @@ -17,15 +17,13 @@ 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 INTERPOLATION_NAMES[] = {"", "lerp", "in", "out", "inOut"}; 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; @@ -234,12 +232,18 @@ namespace anm2ed::model if (value != defaultValue) field(name, names[(int)value]); } - template void object(std::string_view name, Fn&& fn, bool isInline) + // An object with nothing in it is left out when `isOmittedEmpty`. + template void object(std::string_view name, Fn&& fn, bool isInline, bool isOmittedEmpty = false) { + auto size = text.size(); + auto isParentEmpty = scopes.back().isEmpty; key(name); open('{', isInline); fn(*this); - close('}'); + if (!isOmittedEmpty || !scopes.back().isEmpty) return close('}'); + scopes.pop_back(); + text.resize(size); + scopes.back().isEmpty = isParentEmpty; } template @@ -427,7 +431,7 @@ namespace anm2ed::model reader.unknown_keys_check(); } - template void object(std::string_view name, Fn&& fn, bool) + template void object(std::string_view name, Fn&& fn, bool, bool = false) { dom::element element{}; if (element_get(name, element)) object_each(element, std::format("{}{}.", path, name), fn); @@ -500,16 +504,22 @@ namespace anm2ed::model 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.choice("ease", 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); + io.object( + "child", + [&](auto& childIo) + { + childIo.field("name", frame.childAnimation, FRAME_DEFAULT.childAnimation); + childIo.choice("mode", frame.childMode, CHILD_MODE_NAMES, FRAME_DEFAULT.childMode); + childIo.field("start", frame.childStart, FRAME_DEFAULT.childStart); + childIo.field("random", frame.isChildStartRandom, FRAME_DEFAULT.isChildStartRandom); + childIo.field("restart", frame.isChildRestart, FRAME_DEFAULT.isChildRestart); + }, + true, true); } template @@ -575,8 +585,9 @@ namespace anm2ed::model { io.field("length", animation.frameNum, 1); io.field("loop", animation.isLoop, true); - io.field("startMarker", animation.startMarker, -1); - io.field("endMarker", animation.endMarker, -1); + glm::ivec2 markers{animation.startMarker, animation.endMarker}; + io.field("markers", markers, glm::ivec2{-1}); + if constexpr (Io::IS_READING) std::tie(animation.startMarker, animation.endMarker) = std::tie(markers.x, markers.y); 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_); @@ -584,19 +595,26 @@ namespace anm2ed::model } // Animations (and groups, which hold an "animations" object) are keyed by name; a repeated name is renumbered. + // Animation names are unique document-wide (default names one); a group's only among the top-level keys. void animations_write(JsonWriter& io, const Model& model) { - std::set names{}; - auto name_unique_get = [&](const std::string& name) + std::set animationNames{}; + std::set keys{}; + auto name_unique_get = [](const std::string& name, std::initializer_list*> sets) { auto candidate = name; - for (int i = 2; names.contains(candidate); ++i) + for (int i = 2; std::ranges::any_of(sets, [&](auto* names) { return names->contains(candidate); }); ++i) candidate = std::format("{} {}", name, i); - names.insert(candidate); + for (auto* names : sets) + names->insert(candidate); return candidate; }; - auto animation_write = [&](const Animation& animation) - { io.object(name_unique_get(animation.name), [&](JsonWriter&) { animation_io(io, animation); }, false); }; + auto animation_write = [&](const Animation& animation, bool isTopLevel) + { + auto name = isTopLevel ? name_unique_get(animation.name, {&animationNames, &keys}) + : name_unique_get(animation.name, {&animationNames}); + io.object(name, [&](JsonWriter&) { animation_io(io, animation); }, false); + }; io.object( "animations", @@ -606,12 +624,12 @@ namespace anm2ed::model { if (auto animation = std::get_if>(&entry)) { - animation_write(**animation); + animation_write(**animation, true); continue; } auto& group = std::get(entry); io.object( - name_unique_get(group.name), + name_unique_get(group.name, {&keys}), [&](JsonWriter&) { io.field("expanded", group.isExpanded, true); @@ -621,7 +639,7 @@ namespace anm2ed::model [&](JsonWriter&) { for (const auto& animation : group.animations) - animation_write(*animation); + animation_write(*animation, false); }, false); }, @@ -691,7 +709,7 @@ namespace anm2ed::model }, true); io.list( - "spritesheets", content.spritesheets, + "sheets", content.spritesheets, [](auto& spritesheetIo, auto& spritesheet) { spritesheetIo.field("path", spritesheet.path, {}); @@ -757,7 +775,7 @@ namespace anm2ed::model 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.field("defaultAnimation", model.animations.defaultAnimation, {}); + io.field("default", model.animations.defaultAnimation, {}); if constexpr (Io::IS_READING) animations_read(io, model); else @@ -768,14 +786,13 @@ namespace anm2ed::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`. + // Fails only when the text isn't a JSON object; 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{}; @@ -785,9 +802,9 @@ namespace anm2ed::model 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 (error) { - if (errorString) *errorString = error ? error_message(error) : "Not an anm2ed JSON document."; + if (errorString) *errorString = error_message(error); return false; } model = Model{}; diff --git a/tests/draw.cpp b/tests/draw.cpp index ef683d8..563802c 100644 --- a/tests/draw.cpp +++ b/tests/draw.cpp @@ -212,11 +212,11 @@ TEST_CASE("an animation layer's child sits where the layer's frame puts it") TEST_CASE("the game's copy stands in for depth and alpha offsets") { - auto anm2 = model_load(R"({ "anm2ed": 1, "spritesheets": [ { "path": "a.png" } ], + auto anm2 = model_load(R"({ "sheets": [ { "path": "a.png" } ], "layers": [ { "name": "a" }, { "name": "b" }, { "name": "c" } ], "animations": { "A": { "length": 6, "layers": [ { "layer": 0, "frames": [ { "crop": [0, 0], "size": [1, 1], "delay": 2 }, - { "crop": [1, 0], "size": [1, 1], "delay": 2, "depth": 2, "interpolation": "linear" }, + { "crop": [1, 0], "size": [1, 1], "delay": 2, "depth": 2, "ease": "lerp" }, { "crop": [1, 0], "size": [1, 1], "pos": [8, 0], "delay": 2, "depth": -1 } ] }, { "layer": 1, "frames": [ { "crop": [2, 0], "size": [1, 1], "delay": 6, "depth": -1 } ] }, { "layer": 2, "frames": [ { "crop": [3, 0], "size": [1, 1], "delay": 6, "offset": [0, 0, 0, -64] } ] } ] } } })"); diff --git a/tests/invariants.cpp b/tests/invariants.cpp index 5fa9f22..5c0d36f 100644 --- a/tests/invariants.cpp +++ b/tests/invariants.cpp @@ -68,6 +68,35 @@ TEST_CASE("JSON animations get unique names") CHECK(reloaded.animation_get(1)->name == reloaded.animation_get(0)->name + " 2"); } +TEST_CASE("JSON groups don't renumber an animation sharing their name") +{ + auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); + auto animation = std::get>(model.animations.entries.front()); + model.animations.entries = {model::AnimationGroup{.name = animation->name, .animations = {animation}}}; + auto reloaded = model_load(model::model_to_json(model)); + REQUIRE(reloaded.animations_count_get() == 1); + CHECK(reloaded.animation_get(0)->name == animation->name); +} + +TEST_CASE("JSON markers are a pair, and a frame's child an object only when it has one") +{ + auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); + auto text = model::model_to_json(model); + CHECK(text.find("\"child\"") == std::string::npos); + model.animation_edit(0)->startMarker = 2; + model.animation_edit(0)->endMarker = 5; + auto frame = model.frame_edit({0, (int)ItemType::LAYER, 0, 0}); + REQUIRE(frame); + frame->childMode = ChildMode::HOLD; + frame->childStart = 3; + text = model::model_to_json(model); + CHECK(text.find("\"markers\": [2, 5]") != std::string::npos); + CHECK(text.find("\"child\": {\"mode\": \"hold\", \"start\": 3}") != std::string::npos); + auto reloaded = model_load(text); + CHECK(reloaded.animation_get(0)->endMarker == 5); + CHECK(model::model_to_json(reloaded) == text); +} + TEST_CASE("JSON dates are ISO 8601") { auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); @@ -84,9 +113,9 @@ TEST_CASE("JSON dates are ISO 8601") 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" }, + auto text = R"({ "colour": 1, "info": { "fps": "fast" }, "layers": [ { "name": "a", "sheet": 4 } ], - "animations": { "Idle": { "length": 3, "root": [ { "pos": [1], "interpolation": "bouncy", "delay": 3 } ] } } })"; + "animations": { "Idle": { "length": 3, "root": [ { "pos": [1], "ease": "bouncy", "delay": 3 } ] } } })"; model::Model model{}; std::string issues{}; REQUIRE(model::model_load_string(model, text, &issues)); @@ -94,16 +123,15 @@ TEST_CASE("JSON that can't be read is reported by where it is, and the rest stil 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\""}) + "animations.Idle.root[0].ease: 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)); + CHECK_FALSE(model::model_load_string(model, "{ \"fps\": 30, ", &issues)); } TEST_CASE("JSON layers can name a library listed after them in the file") { - auto text = R"({ "anm2ed": 1, "layers": [ { "name": "shadow", "library": 0, "animation": "Small" } ], + auto text = R"({ "layers": [ { "name": "shadow", "library": 0, "animation": "Small" } ], "libraries": [ "shared/shadows.anm2" ] })"; model::Model model{}; std::string issues{}; diff --git a/tests/render/render.cpp b/tests/render/render.cpp index df38cbc..049f28a 100644 --- a/tests/render/render.cpp +++ b/tests/render/render.cpp @@ -268,12 +268,12 @@ TEST_CASE("the game's copy bakes skew and blur into a spritesheet that draws the std::filesystem::remove_all(directory); std::filesystem::create_directories(directory); std::filesystem::copy_file(RENDER_TEST_DIR / "sheet.png", directory / "sheet.png"); - std::ofstream(directory / "bake.anm2") << R"({ "anm2ed": 1, "spritesheets": [ { "path": "sheet.png" } ], + std::ofstream(directory / "bake.anm2") << R"({ "sheets": [ { "path": "sheet.png" } ], "layers": [ { "name": "skewed" }, { "name": "blurred" } ], "animations": { "Layers": { "length": 6, "layers": [ { "layer": 0, "frames": [ - { "size": [16, 16], "pivot": [8, 8], "pos": [-12, 0], "skew": [40, 0], "delay": 3, "interpolation": "linear" }, + { "size": [16, 16], "pivot": [8, 8], "pos": [-12, 0], "skew": [40, 0], "delay": 3, "ease": "lerp" }, { "size": [16, 16], "pivot": [8, 8], "pos": [-12, 4], "skew": [0, 30], "rotation": 45, "delay": 3 } ] }, { "layer": 1, "frames": [ { "crop": [16, 0], "size": [16, 16], "pivot": [8, 8], "pos": [12, 0], "blur": 4, "delay": 6 } ] } ] },