JSON documents; remove the extended format

Documents can be saved as the editor's own JSON (Save as JSON, in Configure's
Serialization row, off by default) and any .anm2 starting with '{' opens as
one. The schema is new, not an XML mirror: content items in arrays (an item's
index is its id), animations keyed by unique name (a repeat saves as "Name 2"),
groups nested, paired values as arrays, a frame on a region storing only the
region, ISO 8601 dates, every default left out, and one line per frame and
content item, with anything else that fits in 100 columns on one line. Unknown
XML isn't kept. Each part is described once (frame_io, track_io, model_io...)
and run by a JsonWriter or a JsonReader; simdjson parses (new submodule). A
JSON file that opens but has unknown keys, wrong types, unknown values or bad
indices lists them by location in a warning toast; libraries toast their load
problems too. With Save as JSON on, saving always shows the Isaac warning.

The extended format is gone: no setting, File menu toggle, ExtendedVersion or
isExtendedFormat. XML saves are always the game's copy with SourceDocument;
old extended files still open. Document saves take Options instead of loose
bools, and model_load reads through model_load_string. docs/json_format.md
replaces docs/extended_format.md; goldens lose ExtendedVersion and the
.extended variants.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shweetandClaude Opus 5.5 committed 2026-10-28 21:48:25 -04:00
1 parent d77b2bae71
commit b69b0eaa1b
121 files changed
+1248 -913

No files matched your search

+13 -13
View File
@@ -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<model::Model> 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())
{
+4 -4
View File
@@ -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<std::filesystem::path>&);
void libraries_add(const std::vector<std::filesystem::path>&);
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&);
+10 -19
View File
@@ -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]);
+3 -3
View File
@@ -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();
+8 -10
View File
@@ -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]);
}
+3 -3
View File
@@ -52,7 +52,7 @@ namespace anm2ed
bool isAbleToRecord{};
ImGuiKeyChord chords[SHORTCUT_COUNT]{};
bool isPurgeDefaultColors{true};
Options saveOptions{SAVE_OPTIONS_DEFAULT};
std::vector<std::filesystem::path> 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&);
+5 -5
View File
@@ -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) \
+802
View File
@@ -0,0 +1,802 @@
#include "json.hpp"
#include <algorithm>
#include <charconv>
#include <cstdio>
#include <format>
#include <set>
#include <simdjson/singleheader/simdjson.h>
#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<char, std::string_view> 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<Region> 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 <class Items> int index_get(const Items& items, int id)
{
auto it = std::ranges::find(items, id, &std::ranges::range_value_t<Items>::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<Scope> 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 <class T> 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<char, std::string_view>::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 <class Values> void array(const Values& values, int count)
{
open('[', true);
for (int i = 0; i < count; ++i)
{
separate();
value(values[i]);
}
close(']');
}
template <int L, class T, glm::qualifier Q> void value(const glm::vec<L, T, Q>& value) { array(value, L); }
void value(const std::vector<int>& value) { array(value, (int)value.size()); }
template <class T> void field(std::string_view name, const T& value)
{
key(name);
this->value(value);
}
template <class T> void field(std::string_view name, const T& value, const std::type_identity_t<T>& defaultValue)
{
if (value != defaultValue) field(name, value);
}
// Written as `to` makes it (and read back through `from`).
template <class T, class To, class From>
void field(std::string_view name, const T& value, const T& defaultValue, To&& to, From&&)
{
field(name, to(value), to(defaultValue));
}
template <class Items> 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 <class Items> void references(std::string_view name, const std::vector<int>& ids, const Items& items)
{
std::vector<int> indices{};
for (auto id : ids)
if (auto index = index_get(items, id); index != -1) indices.push_back(index);
field(name, indices, {});
}
template <class E, std::size_t N>
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 <class Fn> void object(std::string_view name, Fn&& fn, bool isInline)
{
key(name);
open('{', isInline);
fn(*this);
close('}');
}
template <class T, class Fn>
void list(std::string_view name, const std::vector<T>& 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 <class T, class Get> void values(std::string_view name, const std::vector<T>& 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 <class T>
requires std::is_same_v<T, int> || std::is_same_v<T, float>
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 <int L, class T, glm::qualifier Q>
std::string_view value_read(dom::element element, glm::vec<L, T, Q>& 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<int>& value)
{
dom::array array{};
if (element.get(array)) return "an array of numbers";
std::vector<int> 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<std::string>* issues{};
std::string path{};
dom::object fields{};
std::set<std::string_view> 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 <class T> bool field(std::string_view name, T& value, const std::type_identity_t<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 <class T, class To, class From> 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 <class Items> bool is_index_valid(const Items& items, int index)
{
return index >= -1 && index < (int)items.size();
}
template <class Items> 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 <class Items> void references(std::string_view name, std::vector<int>& 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 <class E, std::size_t N>
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 <class Fn> 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 <class Fn> 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 <class T, class Fn> void list(std::string_view name, std::vector<T>& 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 <class T, class Get> void values(std::string_view name, std::vector<T>& 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 <class Io, class F> void frame_io(Io& io, F& frame, ItemType type, const std::vector<Region>& 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 <class Io, class Frames>
void frames_io(Io& io, std::string_view name, Frames& frames, ItemType type,
const std::vector<Region>& 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 <class Io, class T> 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 <class Io, class Entries> 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<std::decay_t<decltype(item)>, 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 <class Io, class A> 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<std::string> 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<std::shared_ptr<const Animation>>(&entry))
{
animation_write(**animation);
continue;
}
auto& group = std::get<AnimationGroup>(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<const Animation>(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 <class Io, class M> 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<std::string> 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;
}
}
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include <string>
#include <string_view>
#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);
}
-2
View File
@@ -359,8 +359,6 @@ namespace anm2ed::model
std::vector<ElementType> 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;
+20 -21
View File
@@ -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;
}
+1
View File
@@ -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 = {});
+5 -5
View File
@@ -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.") \
+1 -1
View File
@@ -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) \