From d1a6d89d147e48381569db5e0d7340a02fd8a216 Mon Sep 17 00:00:00 2001 From: shweet Date: Thu, 8 Oct 2026 16:51:48 -0400 Subject: [PATCH] Libraries window, animation layers and child playback A Libraries window (docked with Spritesheets and Sounds) links other .anm2 files: cards list each one's animations, open it as a tab, and reload when it changes on disk. A layer's Source is a spritesheet or an animation, from this file or a library; the preview, renders and CLI draw the child in the layer's frame. Animation-layer keyframes set the child's animation, mode (loop, once, hold), start frame (or random) and restart; Child is also a copyable frame property. All of it is editor-only and counted by the Isaac warning. Co-Authored-By: Claude Opus 5.5 --- src/canvas.cpp | 7 +- src/canvas.hpp | 2 +- src/cli.cpp | 12 ++- src/dialog.hpp | 1 + src/document.cpp | 138 +++++++++++++++++++++++++ src/document.hpp | 21 ++++ src/edit/content.cpp | 33 +++--- src/edit/edit.hpp | 1 + src/edit/frames.cpp | 10 +- src/imgui/actions.hpp | 1 + src/imgui/dockspace.cpp | 13 ++- src/imgui/dockspace.hpp | 3 +- src/imgui/taskbar.cpp | 3 +- src/imgui/window/animation_preview.cpp | 23 +++-- src/imgui/window/frame_properties.cpp | 48 ++++++++- src/imgui/window/items.cpp | 53 ++++++++-- src/imgui/window/libraries.cpp | 135 ++++++++++++++++++++++++ src/imgui/window/panel.cpp | 1 + src/imgui/window/panel.hpp | 5 +- src/imgui/window/timeline/menus.cpp | 4 +- src/imgui/wizard/about.cpp | 4 +- src/manager.cpp | 9 +- src/manager.hpp | 3 + src/model/common.hpp | 12 +++ src/model/draw.cpp | 94 ++++++++++++++++- src/model/draw.hpp | 9 ++ src/model/frames.cpp | 6 +- src/model/frames.hpp | 4 +- src/model/model.cpp | 15 ++- src/model/model.hpp | 24 +++++ src/model/xml.cpp | 73 +++++++++++-- src/model/xml.hpp | 1 + src/render.cpp | 7 +- src/resource/strings.hpp | 35 +++++++ src/selection.cpp | 1 + src/selection.hpp | 3 +- src/settings.cpp | 6 ++ src/settings.hpp | 3 +- src/util/imgui/input.cpp | 13 +++ src/util/imgui/input.hpp | 2 + tests/draw.cpp | 39 +++++++ tests/render/golden/nested_frame_0.png | Bin 0 -> 782 bytes tests/render/nested.anm2 | 52 ++++++++++ tests/render/render.cpp | 25 +++++ 44 files changed, 873 insertions(+), 81 deletions(-) create mode 100644 src/imgui/window/libraries.cpp create mode 100644 tests/render/golden/nested_frame_0.png create mode 100644 tests/render/nested.anm2 diff --git a/src/canvas.cpp b/src/canvas.cpp index c335c95..075c09d 100644 --- a/src/canvas.cpp +++ b/src/canvas.cpp @@ -271,18 +271,17 @@ namespace anm2ed rect_end(rectVAO, mode, count); } - // An animation's layers alone (no markers or helpers); spritesheet images and custom shaders are looked up by id. + // An animation's layers alone (no markers or helpers); spritesheet images are looked up by draw, custom shaders by id. void Canvas::layers_render(Shader& shader, const model::Model& model, const model::Animation& animation, const model::DrawOptions& options, const mat4& transform, - const std::function& image_get, + const std::function& image_get, const std::function& shader_get) const { for (const auto& draw : model::animation_draws_get(model, animation, options)) { if (draw.type != model::DrawType::LAYER) continue; auto& frame = draw.frame; - auto layer = model::item_get(model.content.layers, draw.id); - auto image = layer ? image_get(layer->spritesheetId) : nullptr; + auto image = image_get(draw); if (!image || !image->is_valid() || frame.size == vec2()) continue; auto imageSize = vec2(image->size); auto uvVertices = math::uv_vertices_get(frame.crop / imageSize, (frame.crop + frame.size) / imageSize); diff --git a/src/canvas.hpp b/src/canvas.hpp index 0a961e0..c5f4c86 100644 --- a/src/canvas.hpp +++ b/src/canvas.hpp @@ -69,7 +69,7 @@ namespace anm2ed float* = (float*)TEXTURE_VERTICES, glm::vec2 = {}, float = 0.0f) const; void rect_fill_render(resource::Shader&, const glm::mat4&, const glm::mat4&, glm::vec4 = glm::vec4(1.0f)) const; void layers_render(resource::Shader&, const model::Model&, const model::Animation&, const model::DrawOptions&, - const glm::mat4&, const std::function&, + const glm::mat4&, const std::function&, const std::function& = {}) const; void dashed_render(resource::Shader&, const glm::mat4&, const glm::mat4&, glm::vec4, float, float, float, GLenum, int) const; diff --git a/src/cli.cpp b/src/cli.cpp index 6cd72b1..450e7a9 100644 --- a/src/cli.cpp +++ b/src/cli.cpp @@ -162,8 +162,14 @@ options: std::println(" #{} {} ({}), {} regions", spritesheet.id, path::to_utf8(spritesheet.path), status, spritesheet.regions.size()); } + for (const auto& library : content.libraries) + std::println("library #{} {}", library.id, path::to_utf8(library.path)); for (const auto& layer : content.layers) - std::println("layer #{} {} (spritesheet #{})", layer.id, layer.name, layer.spritesheetId); + if (layer.is_animation()) + std::println("layer #{} {} (animation {}, library #{})", layer.id, layer.name, layer.animation, + layer.libraryId); + else + std::println("layer #{} {} (spritesheet #{})", layer.id, layer.name, layer.spritesheetId); for (const auto& null : content.nulls) std::println("null #{} {}", null.id, null.name); for (const auto& event : content.events) @@ -173,9 +179,9 @@ options: auto issues = model::isaac_issues_get(model); std::println("isaac issues: {} eased frames, {} group transforms, {} skewed frames, {} shader frames, {} depth " - "frames, {} trigger sounds", + "frames, {} trigger sounds, {} animation layers", issues.easedFrames, issues.groupTransforms, issues.skewFrames, issues.shaderFrames, issues.depthFrames, - issues.triggerSounds); + issues.triggerSounds, issues.animationLayers); return 0; } diff --git a/src/dialog.hpp b/src/dialog.hpp index 859de83..8e9ef05 100644 --- a/src/dialog.hpp +++ b/src/dialog.hpp @@ -49,6 +49,7 @@ namespace anm2ed X(ANM2_OPEN, ANM2) \ X(ANM2_SAVE, ANM2) \ X(SOUND_OPEN, SOUND) \ + X(LIBRARY_OPEN, ANM2) \ X(SOUND_REPLACE, SOUND) \ X(SPRITESHEET_OPEN, PNG) \ X(SPRITESHEET_REPLACE, PNG) \ diff --git a/src/document.cpp b/src/document.cpp index 4da9ebe..765a208 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -33,6 +33,26 @@ namespace anm2ed::document constexpr std::string_view AUTOSAVE_EXTENSION = ".autosave"; constexpr std::uint64_t HASH_COMBINE_CONSTANT = 0x9e3779b97f4a7c15ULL; + // A path written in a document in `directory`, as an absolute path. + std::filesystem::path absolute_path_get(const std::filesystem::path& directory, const std::filesystem::path& path) + { + util::WorkingDirectory workingDirectory(directory); + std::error_code ec{}; + auto absolutePath = std::filesystem::weakly_canonical(directory / path::case_insensitive_find(path), ec); + return ec ? directory / path : absolutePath; + } + + void library_load(const std::filesystem::path& path, LibraryData& library) + { + library = {}; + model::model_load(library.model, path); + std::error_code ec{}; + library.writeTime = std::filesystem::last_write_time(path, ec); + util::WorkingDirectory workingDirectory(path.parent_path()); + for (const auto& spritesheet : library.model.content.spritesheets) + library.images.emplace(spritesheet.id, resource::Image(path::case_insensitive_find(spritesheet.path))); + } + uint64_t document_tab_id_next() { static uint64_t next{1}; @@ -311,6 +331,7 @@ namespace anm2ed void Document::assets_sync() { + libraries_sync(); document::resources_sync(*this, model.content.spritesheets, textures, texturePaths, [&](int id, const std::filesystem::path& path) { texture_set(id, resource::Image(path)); }); @@ -345,6 +366,97 @@ namespace anm2ed std::erase_if(shaderFragmentPaths, is_invalid); } + std::filesystem::path Document::library_path_get(int id) const + { + auto library = model::item_get(model.content.libraries, id); + return library ? document::absolute_path_get(std::filesystem::absolute(directory_get()), library->path) + : std::filesystem::path{}; + } + + const LibraryData* Document::library_get(const model::Model& from, int id) const + { + auto link = libraryLinks.find({&from == &model ? nullptr : &from, id}); + return link == libraryLinks.end() ? nullptr : link->second; + } + + model::LibraryGet Document::library_resolver_get() const + { + return [this](const model::Model& from, int id) + { + auto library = library_get(from, id); + return library ? &library->model : nullptr; + }; + } + + // The animation names of library `libraryId`, or of this document at -1. + std::vector Document::animation_names_get(int libraryId) const + { + auto library = libraryId == -1 ? nullptr : library_get(model, libraryId); + auto source = libraryId == -1 ? &model : library ? &library->model : nullptr; + std::vector names{}; + if (source) + for (auto [index, animation] : source->animations_get()) + names.push_back(animation->name); + return names; + } + + const resource::Image* Document::draw_image_get(const model::Draw& draw) const + { + if (!draw.source || draw.source == &model) return texture_get(draw.spritesheetId); + for (const auto& [path, library] : libraries) + if (&library.model == draw.source) + { + auto image = library.images.find(draw.spritesheetId); + return image == library.images.end() ? nullptr : &image->second; + } + return nullptr; + } + + // Loads every library this document reaches (libraries' own libraries too) and forgets the ones it no longer does. + void Document::libraries_sync() + { + libraryLinks.clear(); + std::set reached{}; + std::vector> pending{ + {&model, std::filesystem::absolute(directory_get())}}; + while (!pending.empty()) + { + auto [from, directory] = pending.back(); + pending.pop_back(); + for (const auto& library : from->content.libraries) + { + auto path = document::absolute_path_get(directory, library.path); + auto [it, isNew] = libraries.try_emplace(path); + if (isNew) document::library_load(path, it->second); + libraryLinks[{from == &model ? nullptr : from, library.id}] = &it->second; + if (reached.insert(path).second) pending.emplace_back(&it->second.model, path.parent_path()); + } + } + std::erase_if(libraries, [&](const auto& pair) { return !reached.contains(pair.first); }); + } + + // Reloads the libraries whose file changed on disk; true when any did. + bool Document::libraries_reload() + { + bool isReloaded{}; + for (auto& [path, library] : libraries) + { + std::error_code ec{}; + auto time = std::filesystem::last_write_time(path, ec); + if (ec || time == library.writeTime) continue; + document::library_load(path, library); + isReloaded = true; + } + if (isReloaded) libraries_sync(); + return isReloaded; + } + + void Document::library_reload(int id) + { + libraries.erase(library_path_get(id)); + libraries_sync(); + } + const resource::Image* Document::texture_get(int id) const { if (auto draft = textureDrafts.find(id); draft != textureDrafts.end()) return &draft->second; @@ -657,6 +769,7 @@ namespace anm2ed auto& content = model.content; if (kind == SelectionKind::SPRITESHEETS) add(content.spritesheets, path_label_get(FORMAT_SPRITESHEET)); if (kind == SelectionKind::SOUNDS) add(content.sounds, path_label_get(FORMAT_SOUND)); + if (kind == SelectionKind::LIBRARIES) add(content.libraries, path_label_get(FORMAT_SOUND)); if (kind == SelectionKind::EVENTS) add(content.events, name_get); if (kind == SelectionKind::SHADERS) add(content.shaders, name_get); if (kind == SelectionKind::REGIONS) @@ -901,6 +1014,31 @@ namespace anm2ed change(); } + void Document::libraries_add(const std::vector& paths) + { + std::set added{}; + edit_apply( + EDIT_ADD_LIBRARY, + [&](model::Model& model) + { + auto& libraries = model.content.libraries; + for (auto& path : paths) + if (!path.empty()) + { + auto& library = libraries.emplace_back(model::Library{ + .id = model::item_next_id_get(libraries), + .path = path::backslash_replace(path::make_relative(path::backslash_handle(path), directory_get()))}); + added.insert(library.id); + } + }); + if (added.empty()) return; + for (auto id : added) + toast_log(Level::INFO, TOAST_LIBRARY_INITIALIZED, id, + path::to_utf8(model::item_get(model.content.libraries, id)->path)); + selected_ids_set(SelectionKind::LIBRARIES, added); + focused_id_set(SelectionKind::LIBRARIES, *added.rbegin()); + } + void Document::undo() { if (!snapshots.undo()) return; diff --git a/src/document.hpp b/src/document.hpp index a949446..12ee512 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -11,6 +11,7 @@ #include "asset_store.hpp" #include "edit/edit.hpp" +#include "model/draw.hpp" #include "selection.hpp" #include "snapshots.hpp" #include "strings.hpp" @@ -31,6 +32,14 @@ namespace anm2ed std::vector labels{}; }; + // A linked .anm2, loaded read-only: its document and its spritesheets' images. + struct LibraryData + { + model::Model model{}; + std::map images{}; + std::filesystem::file_time_type writeTime{}; + }; + struct DocumentData { std::filesystem::path path{}; @@ -64,6 +73,9 @@ namespace anm2ed std::map shaderVertexPaths{}; std::map shaderFragmentPaths{}; std::map shaders{}; + // Libraries by absolute path, and what each (document, library id) points at (nullptr is this document). + std::map libraries{}; + std::map, const LibraryData*> libraryLinks{}; bool isAnimationPreviewSet{false}; bool isSpritesheetEditorSet{false}; }; @@ -110,6 +122,14 @@ namespace anm2ed const resource::AudioData* sound_get(int) const; void sound_set(int, resource::AudioData); resource::Shader* shader_get(int); + std::filesystem::path library_path_get(int) const; + const LibraryData* library_get(const model::Model&, int) const; + model::LibraryGet library_resolver_get() const; + std::vector animation_names_get(int) const; + const resource::Image* draw_image_get(const model::Draw&) const; + void libraries_sync(); + bool libraries_reload(); + void library_reload(int); bool regions_trim(int, const std::set&); bool spritesheet_pack(int, int); bool spritesheets_merge(const std::set&, bool, bool, bool, Origin); @@ -180,6 +200,7 @@ namespace anm2ed void spritesheets_add(const std::vector&); void sounds_add(const std::vector&); + void libraries_add(const std::vector&); bool autosave(std::string* = nullptr); std::filesystem::path autosave_path_get(); diff --git a/src/edit/content.cpp b/src/edit/content.cpp index 3aeb176..01b48b3 100644 --- a/src/edit/content.cpp +++ b/src/edit/content.cpp @@ -286,26 +286,33 @@ namespace anm2ed::edit return remap[sourceId] = imported.id; }; - for (auto sound : source.content.sounds) + // Sounds and libraries are matched by path. + auto paths_merge = [&](auto& items, const auto& sourceItems, ElementType type) { - auto sourceId = sound.id; - sound.path = path_remap(sound.path); - auto existing = isAppendAsNew ? content.sounds.end() - : std::ranges::find_if(content.sounds, [&](const Sound& other) - { return other.path == sound.path; }); - sound.id = existing != content.sounds.end() ? existing->id : item_next_id_get(content.sounds); - if (existing != content.sounds.end()) - *existing = sound; - else - content.sounds.push_back(sound); - remaps[ElementType::SOUND_ELEMENT][sourceId] = sound.id; - } + for (auto item : sourceItems) + { + auto sourceId = item.id; + item.path = path_remap(item.path); + auto existing = isAppendAsNew + ? items.end() + : std::ranges::find_if(items, [&](const auto& other) { return other.path == item.path; }); + item.id = existing != items.end() ? existing->id : item_next_id_get(items); + if (existing != items.end()) + *existing = item; + else + items.push_back(item); + remaps[type][sourceId] = item.id; + } + }; + paths_merge(content.sounds, source.content.sounds, ElementType::SOUND_ELEMENT); + paths_merge(content.libraries, source.content.libraries, ElementType::LIBRARY); for (auto layer : source.content.layers) { auto existing = isAppendAsNew ? nullptr : name_find(content.layers, layer.name); auto sourceId = layer.id; layer.spritesheetId = existing ? existing->spritesheetId : spritesheet_import(layer.spritesheetId); + layer.libraryId = id_remap(ElementType::LIBRARY, layer.libraryId); remaps[ElementType::LAYER_ELEMENT][sourceId] = named_merge(content.layers, layer); } for (auto null : source.content.nulls) diff --git a/src/edit/edit.hpp b/src/edit/edit.hpp index 1c2df7f..ca989ea 100644 --- a/src/edit/edit.hpp +++ b/src/edit/edit.hpp @@ -81,6 +81,7 @@ namespace anm2ed::edit DURATION, SHADER, DEPTH, + CHILD, EVENT, SOUNDS, COUNT diff --git a/src/edit/frames.cpp b/src/edit/frames.cpp index 1c5fa5f..07b620a 100644 --- a/src/edit/frames.cpp +++ b/src/edit/frames.cpp @@ -213,7 +213,8 @@ namespace anm2ed::edit if (property == FrameProperty::EVENT || property == FrameProperty::SOUNDS) return false; auto isLayerOnly = property == FrameProperty::PIVOT || property == FrameProperty::CROP || property == FrameProperty::SIZE || property == FrameProperty::REGION || - property == FrameProperty::SHADER || property == FrameProperty::DEPTH; + property == FrameProperty::SHADER || property == FrameProperty::DEPTH || + property == FrameProperty::CHILD; return type == ItemType::LAYER || !isLayerOnly; } @@ -269,6 +270,13 @@ namespace anm2ed::edit case FrameProperty::DEPTH: target.depth = source.depth; break; + case FrameProperty::CHILD: + target.childAnimation = source.childAnimation; + target.childMode = source.childMode; + target.childStart = source.childStart; + target.isChildStartRandom = source.isChildStartRandom; + target.isChildRestart = source.isChildRestart; + break; case FrameProperty::EVENT: target.eventId = source.eventId; break; diff --git a/src/imgui/actions.hpp b/src/imgui/actions.hpp index 37ef719..6334075 100644 --- a/src/imgui/actions.hpp +++ b/src/imgui/actions.hpp @@ -30,6 +30,7 @@ namespace anm2ed::imgui X(ACTION_REPLACE, BASIC_REPLACE, -1) \ X(ACTION_SAVE, BASIC_SAVE, -1) \ X(ACTION_EXPORT, BASIC_EXPORT, -1) \ + X(ACTION_OPEN, BASIC_OPEN, -1) \ X(ACTION_OPEN_DIRECTORY, BASIC_OPEN_DIRECTORY, -1) \ X(ACTION_SET_FILE_PATH, BASIC_SET_FILE_PATH, -1) \ X(ACTION_PACK, BASIC_PACK, -1) \ diff --git a/src/imgui/dockspace.cpp b/src/imgui/dockspace.cpp index 66238cc..9d6a624 100644 --- a/src/imgui/dockspace.cpp +++ b/src/imgui/dockspace.cpp @@ -9,12 +9,16 @@ namespace anm2ed::imgui if (auto document = manager.get(); document) if (settings.windowIsAnimationPreview) animationPreview.tick(manager, settings, deltaSeconds); - if (!settings.fileIsAutoReloadSpritesheets) return; - spritesheetReloadTime += deltaSeconds; - if (spritesheetReloadTime < AUTO_RELOAD_INTERVAL) return; - spritesheetReloadTime = 0.0f; + // Files changed on disk are picked up every few seconds: libraries always, spritesheets when set to. + reloadTime += deltaSeconds; + if (reloadTime < AUTO_RELOAD_INTERVAL) return; + reloadTime = 0.0f; for (auto& document : manager.documents) + { + document.libraries_reload(); + if (!settings.fileIsAutoReloadSpritesheets) continue; if (auto ids = document.spritesheets_changed_get(); !ids.empty()) document.spritesheets_reload(ids); + } } void Dockspace::update(Taskbar& taskbar, Documents& documents, Manager& manager, Settings& settings, @@ -68,6 +72,7 @@ namespace anm2ed::imgui shaders_update(panel, shaders); } if (settings.windowIsSounds) panel_update(sounds, sounds_update); + if (settings.windowIsLibraries) panel_update(libraries, libraries_update); if (settings.windowIsSpritesheetEditor) spritesheetEditor.update(manager, settings, resources); if (settings.windowIsSpritesheets) { diff --git a/src/imgui/dockspace.hpp b/src/imgui/dockspace.hpp index 6265005..b319643 100644 --- a/src/imgui/dockspace.hpp +++ b/src/imgui/dockspace.hpp @@ -15,7 +15,7 @@ namespace anm2ed::imgui { AnimationPreview animationPreview; bool isCanvasFocused{}; - float spritesheetReloadTime{}; + float reloadTime{}; AnimationsPanel animations{}; RegionsPanel regions{}; PanelState events{}; @@ -26,6 +26,7 @@ namespace anm2ed::imgui SpritesheetEditor spritesheetEditor; SpritesheetsPanel spritesheets{}; PanelState sounds{}; + PanelState libraries{}; Timeline timeline; PopupHelper toolsColorEditPopup{PopupHelper(LABEL_TOOLS_COLOR_EDIT_POPUP, POPUP_TO_CONTENT, POPUP_BY_ITEM)}; AutosaveRestore autosaveRestore; diff --git a/src/imgui/taskbar.cpp b/src/imgui/taskbar.cpp index e97e18a..e2d1d58 100644 --- a/src/imgui/taskbar.cpp +++ b/src/imgui/taskbar.cpp @@ -387,7 +387,8 @@ namespace anm2ed::imgui {issues.skewFrames, FORMAT_ISAAC_SKEW_FRAMES}, {issues.shaderFrames, FORMAT_ISAAC_SHADER_FRAMES}, {issues.depthFrames, FORMAT_ISAAC_DEPTH_FRAMES}, - {issues.triggerSounds, FORMAT_ISAAC_TRIGGER_SOUNDS}}) + {issues.triggerSounds, FORMAT_ISAAC_TRIGGER_SOUNDS}, + {issues.animationLayers, FORMAT_ISAAC_ANIMATION_LAYERS}}) if (count > 0) ImGui::BulletText("%s", localize_format(format, count).c_str()); } ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_EDITOR_COPY)); diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index 73f017a..2400982 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -111,12 +111,14 @@ namespace anm2ed::imgui std::optional rect{}; if (animation) - rect = animation_rects_merge(rect, model::animation_rect(document.model, *animation, isRootTransform)); + rect = animation_rects_merge( + rect, model::animation_rect(document.model, *animation, isRootTransform, document.library_resolver_get())); if (auto overlayDocument = overlay_animation_document_get(manager, document)) if (auto overlayAnimation = overlayDocument->model.animation_get(document.overlayIndex)) rect = animation_rects_merge(rect, - model::animation_rect(overlayDocument->model, *overlayAnimation, isRootTransform)); + model::animation_rect(overlayDocument->model, *overlayAnimation, isRootTransform, + overlayDocument->library_resolver_get())); return rect; } @@ -296,7 +298,9 @@ namespace anm2ed::imgui auto fit_view = [&]() { - if (animation) set_to_rect(zoom, pan, model::animation_rect(model, *animation, isRootTransform)); + if (animation) + set_to_rect(zoom, pan, + model::animation_rect(model, *animation, isRootTransform, document.library_resolver_get())); }; manager.isAbleToRecord = false; @@ -677,7 +681,9 @@ namespace anm2ed::imgui auto isActiveDocument = &sampleDocument == &document; auto& sampleModel = sampleDocument.model; auto targetIcon = resources.icon_id_get(isAltIcons && !isIsolated ? icon::TARGET_ALT : icon::TARGET); - for (const auto& draw : model::animation_draws_get(sampleModel, sampleAnimation, drawOptions)) + auto sampleOptions = drawOptions; + sampleOptions.library_get = sampleDocument.library_resolver_get(); + for (const auto& draw : model::animation_draws_get(sampleModel, sampleAnimation, sampleOptions)) { auto isOnion = draw.sample != -1; if (isOnion && isOnlySelected && !(isActiveDocument && is_draw_selected(draw))) continue; @@ -709,8 +715,7 @@ namespace anm2ed::imgui } else if (draw.type == model::DrawType::LAYER) { - auto layer = model::item_get(sampleModel.content.layers, draw.id); - auto layerTexture = sampleDocument.texture_get(layer->spritesheetId); + auto layerTexture = sampleDocument.draw_image_get(draw); if (!layerTexture || !layerTexture->is_valid() || layerTexture->size.x <= 0 || layerTexture->size.y <= 0) continue; auto textureSize = vec2(layerTexture->size); @@ -769,8 +774,10 @@ namespace anm2ed::imgui pivotPathsKey = key; pivotPaths.clear(); for (int time = 0; time < animation->frameNum; ++time) - for (const auto& draw : model::animation_draws_get( - model, *animation, {.time = (float)time, .isRootTransform = isRootTransform})) + for (const auto& draw : model::animation_draws_get(model, *animation, + {.time = (float)time, + .isRootTransform = isRootTransform, + .library_get = document.library_resolver_get()})) { auto path = std::ranges::find_if(pivotPaths, [&](const PivotPath& path) diff --git a/src/imgui/window/frame_properties.cpp b/src/imgui/window/frame_properties.cpp index beb2924..814f8c3 100644 --- a/src/imgui/window/frame_properties.cpp +++ b/src/imgui/window/frame_properties.cpp @@ -208,13 +208,17 @@ namespace anm2ed::imgui } else { + auto layer = type == LAYER ? model::item_get(model.content.layers, reference.itemID) : nullptr; + auto isAnimationLayer = layer && layer->is_animation(); bool isRegionSet = frame && displayFrame.regionId != -1 && displayFrame.crop == frame->crop && displayFrame.size == frame->size && displayFrame.pivot == frame->pivot; for (auto& field : VEC2_FIELDS) { const auto& source = field.isRegionField ? displayFrame : useFrame; auto value = frame ? source.*field.member : vec2(); - ImGui::BeginDisabled(field.isRegionField && (type == ROOT || type == NULL_ || isRegionSet)); + // An animation layer's pivot is where its child's origin goes; it has no crop or size. + ImGui::BeginDisabled(field.isRegionField && (type == ROOT || type == NULL_ || isRegionSet || + (isAnimationLayer && field.member != &model::Frame::pivot))); auto state = drag_float2_persistent(localize.get(field.label), frame ? &value : &dummy_value(), DRAG_SPEED, 0.0f, 0.0f, frame ? vec2_format_get(source.*field.member) : ""); @@ -273,7 +277,7 @@ namespace anm2ed::imgui const Reference&) { frame.colorOffset = colorOffset; }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_COLOR_OFFSET)); - ImGui::BeginDisabled(type != LAYER); + ImGui::BeginDisabled(type != LAYER || isAnimationLayer); if (combo_id_mapped(localize.get(BASIC_REGION), frame ? &useFrame.regionId : &dummy_value_negative(), regions.ids, regions.labels) && frame) @@ -301,7 +305,7 @@ namespace anm2ed::imgui { frame.interpolation = static_cast(interpolationValue); }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_INTERPOLATION)); - ImGui::BeginDisabled(type != LAYER); + ImGui::BeginDisabled(type != LAYER || isAnimationLayer); if (combo_id_mapped(localize.get(BASIC_SHADER), frame ? &useFrame.shaderId : &dummy_value_negative(), shaders.ids, shaders.labels) && frame) @@ -324,6 +328,44 @@ namespace anm2ed::imgui } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_VISIBILITY)); + if (isAnimationLayer && frame) + { + ImGui::SeparatorText(localize.get(LABEL_CHILD)); + auto values = document.animation_names_get(layer->libraryId); + auto labels = values; + values.insert(values.begin(), std::string{}); + labels.insert(labels.begin(), localize.get(TEXT_LAYER_ANIMATION)); + bool isChildChanged = + combo_string_mapped(localize.get(LABEL_ANIMATION), &useFrame.childAnimation, values, labels); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_ANIMATION)); + + const char* modeLabels[] = {localize.get(LABEL_LOOP), localize.get(LABEL_ONCE), localize.get(LABEL_HOLD)}; + auto mode = (int)useFrame.childMode; + if (ImGui::Combo(localize.get(BASIC_MODE), &mode, modeLabels, (int)std::size(modeLabels))) + { + useFrame.childMode = (ChildMode)mode; + isChildChanged = true; + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_MODE)); + + ImGui::BeginDisabled(useFrame.isChildStartRandom); + isChildChanged |= input_int_range(localize.get(LABEL_START_FRAME), useFrame.childStart, 0, FRAME_NUM_MAX, + STEP, STEP_FAST); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_START)); + ImGui::EndDisabled(); + + isChildChanged |= ImGui::Checkbox(localize.get(LABEL_RANDOM), &useFrame.isChildStartRandom); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_START_RANDOM)); + ImGui::SameLine(); + isChildChanged |= ImGui::Checkbox(localize.get(LABEL_RESTART), &useFrame.isChildRestart); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_RESTART)); + + if (isChildChanged) + frame_edit(edit_state::COMPLETE, EDIT_FRAME_CHILD, + [child = useFrame](Document&, model::Frame& frame, model::Track*, const Reference&) + { edit::frame_property_copy(frame, child, edit::FrameProperty::CHILD); }); + } + auto widgetSize = widget_size_with_row_get(2); for (int axis = 0; axis < (int)std::size(FLIP_BUTTONS); ++axis) diff --git a/src/imgui/window/items.cpp b/src/imgui/window/items.cpp index fe29ac4..cab39de 100644 --- a/src/imgui/window/items.cpp +++ b/src/imgui/window/items.cpp @@ -9,7 +9,8 @@ using namespace anm2ed::types; namespace anm2ed::imgui { - constexpr int ITEM_PROPERTIES_ROWS = 2; + constexpr int NULL_PROPERTIES_ROWS = 2; + constexpr int LAYER_PROPERTIES_ROWS = 4; auto& layers_get(model::Model& model) { return model.content.layers; } auto& nulls_get(model::Model& model) { return model.content.nulls; } @@ -23,7 +24,7 @@ namespace anm2ed::imgui // The layer/null properties popup: adds a new item (id -1) or replaces the edited one, then selects it. template - void item_properties_update(Panel& panel, int popupIndex, SelectionKind kind, StringType nameTooltip, + void item_properties_update(Panel& panel, int popupIndex, int rows, SelectionKind kind, StringType nameTooltip, StringType addEdit, StringType propertiesEdit, ItemsGet items_get, FieldsDraw&& fields_draw) { @@ -34,7 +35,7 @@ namespace anm2ed::imgui popup.trigger(); if (ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) { - if (ImGui::BeginChild("##Child", child_size_get(ITEM_PROPERTIES_ROWS), ImGuiChildFlags_Borders)) + if (ImGui::BeginChild("##Child", child_size_get(rows), ImGuiChildFlags_Borders)) { if (popup.isJustOpened) ImGui::SetKeyboardFocusHere(); input_text_string(localize.get(BASIC_NAME), &edit.name); @@ -49,6 +50,12 @@ namespace anm2ed::imgui Item item{.name = edit.name}; if constexpr (requires { item.spritesheetId; }) item.spritesheetId = edit.spritesheetId; if constexpr (requires { item.isShowRect; }) item.isShowRect = edit.isShowRect; + if constexpr (requires { item.animation; }) + if (edit.isAnimation) + { + item.libraryId = edit.libraryId; + item.animation = edit.animation; + } auto& state = panel.state; command_push(panel, [&state, item, id = edit.id, kind, addEdit, propertiesEdit, items_get](Document& document) @@ -115,6 +122,9 @@ namespace anm2ed::imgui [&](int id) { auto layer = model::item_get(layers, id); + if (layer->is_animation()) + return std::vformat(localize.get(FORMAT_LAYER_ANIMATION), + std::make_format_args(layer->id, layer->name, layer->animation)); return std::vformat(localize.get(FORMAT_LAYER), std::make_format_args(layer->id, layer->name, layer->spritesheetId)); }, @@ -133,12 +143,37 @@ namespace anm2ed::imgui ImGui::End(); item_properties_update( - panel, 0, SelectionKind::LAYERS, TOOLTIP_ITEM_NAME, EDIT_ADD_LAYER, EDIT_SET_LAYER_PROPERTIES, layers_get, + panel, 0, LAYER_PROPERTIES_ROWS, SelectionKind::LAYERS, TOOLTIP_ITEM_NAME, EDIT_ADD_LAYER, + EDIT_SET_LAYER_PROPERTIES, layers_get, [&](Manager::ItemEdit& layer) { - auto spritesheets = document.choices_get(SelectionKind::SPRITESHEETS); - combo_id_mapped(localize.get(LABEL_SPRITESHEET), &layer.spritesheetId, spritesheets.ids, spritesheets.labels); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SPRITESHEET)); + ImGui::TextUnformatted(localize.get(LABEL_LAYER_SOURCE)); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SOURCE)); + for (auto [label, isAnimation] : {std::pair{LABEL_SPRITESHEET, false}, std::pair{LABEL_ANIMATION, true}}) + { + ImGui::SameLine(); + if (ImGui::RadioButton(localize.get(label), layer.isAnimation == isAnimation)) + layer.isAnimation = isAnimation; + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SOURCE)); + } + + if (!layer.isAnimation) + { + auto spritesheets = document.choices_get(SelectionKind::SPRITESHEETS); + combo_id_mapped(localize.get(LABEL_SPRITESHEET), &layer.spritesheetId, spritesheets.ids, + spritesheets.labels); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SPRITESHEET)); + return; + } + + auto libraries = document.choices_get(SelectionKind::LIBRARIES); + libraries.labels.front() = localize.get(TEXT_THIS_FILE); + combo_id_mapped(localize.get(LABEL_LIBRARY), &layer.libraryId, libraries.ids, libraries.labels); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_LIBRARY)); + auto names = document.animation_names_get(layer.libraryId); + if (layer.animation.empty() && !names.empty()) layer.animation = names.front(); + combo_string_mapped(localize.get(LABEL_ANIMATION), &layer.animation, names, names); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_ANIMATION)); }); } @@ -166,8 +201,8 @@ namespace anm2ed::imgui } ImGui::End(); - item_properties_update(panel, 1, SelectionKind::NULLS, TOOLTIP_NULL_NAME, EDIT_ADD_NULL, - EDIT_SET_NULL_PROPERTIES, nulls_get, + item_properties_update(panel, 1, NULL_PROPERTIES_ROWS, SelectionKind::NULLS, TOOLTIP_NULL_NAME, + EDIT_ADD_NULL, EDIT_SET_NULL_PROPERTIES, nulls_get, [](Manager::ItemEdit& null) { ImGui::Checkbox(localize.get(LABEL_RECT), &null.isShowRect); diff --git a/src/imgui/window/libraries.cpp b/src/imgui/window/libraries.cpp new file mode 100644 index 0000000..b0eb545 --- /dev/null +++ b/src/imgui/window/libraries.cpp @@ -0,0 +1,135 @@ +#include "panel.hpp" + +#include + +#include "path.hpp" + +using namespace anm2ed::resource; +using namespace anm2ed::types; +using namespace anm2ed::util; + +namespace anm2ed::imgui +{ + constexpr int LIBRARY_CARD_LINES = 2; + + auto& libraries_get(model::Model& model) { return model.content.libraries; } + + void libraries_update(Panel& panel) + { + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + auto& libraries = document.model.content.libraries; + auto selection = document.selected_ids_get(SelectionKind::LIBRARIES); + + if (dialog.is_selected(Dialog::LIBRARY_OPEN)) + { + command_push(panel, + [&state, paths = dialog.paths](Document& document) + { + document.libraries_add(paths); + state.newId = document.focused_id_get(SelectionKind::LIBRARIES); + }); + dialog.reset(); + } + + if (ImGui::Begin(localize.get(LABEL_LIBRARIES_WINDOW), &settings.windowIsLibraries)) + { + auto isOne = [selection]() { return selection.size() == 1; }; + auto loaded_get = [&](int id) { return document.library_get(document.model, id); }; + // Opens the library as its own tab, or switches to it when it already is one. + auto open = [&](int id) + { + manager.command_push({.runManager = [path = document.library_path_get(id)](Manager& manager) + { + for (int i = 0; i < (int)manager.documents.size(); ++i) + { + std::error_code ec{}; + if (!std::filesystem::equivalent(manager.documents[i].path, path, ec)) continue; + manager.pendingSelected = i; + return manager.set(i); + } + manager.open(path); + }}); + }; + + Actions actions{}; + actions.add(ACTION_OPEN, isOne, [&]() { open(*selection.begin()); }, TOOLTIP_LIBRARY_OPEN); + actions.add(ACTION_OPEN_DIRECTORY, isOne, + [&]() { directory_open(dialog, document, model::item_get(libraries, *selection.begin())->path); }); + actions.add(ACTION_ADD, {}, [&]() { dialog.file_open(Dialog::LIBRARY_OPEN, true); }, TOOLTIP_LIBRARY_ADD); + actions.add( + ACTION_REMOVE_UNUSED, {}, + [&]() { items_unused_remove(panel, ElementType::LIBRARY, EDIT_REMOVE_UNUSED_LIBRARIES, libraries_get); }, + TOOLTIP_REMOVE_UNUSED_LIBRARIES); + actions.add( + ACTION_RELOAD, [selection]() { return !selection.empty(); }, + [&]() + { + command_push(panel, + [selection](Document& document) + { + for (auto id : selection) + if (auto library = model::item_get(document.model.content.libraries, id)) + { + document.library_reload(id); + toast_log(Level::INFO, TOAST_RELOAD_LIBRARY, id, path::to_utf8(library->path)); + } + }); + }, + TOOLTIP_RELOAD_LIBRARIES); + items_clipboard_actions_add(actions, panel, SelectionKind::LIBRARIES, EDIT_PASTE_LIBRARIES, + TOAST_DESERIALIZE_LIBRARIES_FAILED, libraries_get); + + ListRows rows{.label_get = + [&](int id) + { + auto pathString = path::to_utf8(model::item_get(libraries, id)->path); + return std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(id, pathString)); + }, + .tooltip_draw = + [&](int id) + { + auto loaded = loaded_get(id); + tooltip_name_draw(resources, path::to_utf8(model::item_get(libraries, id)->path)); + ImGui::Text("%s: %d", localize.get(BASIC_ID), id); + if (loaded && loaded->model.isValid) + ImGui::TextUnformatted(localize.get(TOOLTIP_LIBRARY_OPEN)); + else + { + ImGui::Spacing(); + ImGui::TextWrapped("%s", localize.get(TOOLTIP_LIBRARY_INVALID)); + } + }, + .image_get = + [&](int id) + { + auto loaded = loaded_get(id); + auto isValid = loaded && loaded->model.isValid; + auto& texture = resources.icons[isValid ? icon::ANIMATION : icon::NONE]; + return CardImage{.texture = &texture, .size = glm::vec2(texture.size), .isValid = isValid}; + }, + .activate = open, + .children_draw = + [&](int id) + { + auto loaded = loaded_get(id); + if (!loaded || !loaded->model.isValid) return; + auto animations = loaded->model.animations_get(); + auto count = animations.size(); + auto label = std::vformat(localize.get(FORMAT_LIBRARY_ANIMATIONS), std::make_format_args(count)); + ImGui::PushID(id); + if (ImGui::TreeNodeEx(label.c_str(), ImGuiTreeNodeFlags_SpanAvailWidth)) + { + for (auto [index, animation] : animations) + ImGui::BulletText("%s", animation->name.c_str()); + ImGui::TreePop(); + } + ImGui::PopID(); + }, + .cardLines = LIBRARY_CARD_LINES}; + list_panel_draw( + panel, actions, {{ACTION_ADD, ACTION_REMOVE_UNUSED, ACTION_RELOAD, ACTION_OPEN}}, + [&]() { content_list_draw(panel, SelectionKind::LIBRARIES, item_ids_get(libraries), rows); }, true); + } + ImGui::End(); + } +} diff --git a/src/imgui/window/panel.cpp b/src/imgui/window/panel.cpp index 6119ed6..c912ed1 100644 --- a/src/imgui/window/panel.cpp +++ b/src/imgui/window/panel.cpp @@ -254,6 +254,7 @@ namespace anm2ed::imgui else isBreak = row_draw(panel, selection, focus, rows, keys[i], i, arrowKey); if (isBreak) break; + if (rows.children_draw) rows.children_draw(keys[i]); } if (isCards) ImGui::PopStyleVar(); list_select_end(panel, selection, focus, rows, arrowKey); diff --git a/src/imgui/window/panel.hpp b/src/imgui/window/panel.hpp index b87b99c..f34e558 100644 --- a/src/imgui/window/panel.hpp +++ b/src/imgui/window/panel.hpp @@ -64,7 +64,8 @@ namespace anm2ed::imgui PanelState& state; }; - // How a list shows its keys; only `label_get` is required. With `image_get` the rows are cards. + // How a list shows its keys; only `label_get` is required. With `image_get` the rows are cards; `children_draw` draws + // under a key. struct ListRows { std::function label_get{}; @@ -76,6 +77,7 @@ namespace anm2ed::imgui std::function select{}; std::function activate{}; std::function drag_drop_update{}; + std::function children_draw{}; int cardLines{}; bool isFocusItalic{}; }; @@ -147,6 +149,7 @@ namespace anm2ed::imgui void nulls_update(Panel&); void events_update(Panel&); void sounds_update(Panel&); + void libraries_update(Panel&); void spritesheets_update(Panel&, SpritesheetsPanel&); void regions_update(Panel&, RegionsPanel&); void frame_properties_update(Manager&, Settings&, FramePropertiesPanel&); diff --git a/src/imgui/window/timeline/menus.cpp b/src/imgui/window/timeline/menus.cpp index eea917d..96ed359 100644 --- a/src/imgui/window/timeline/menus.cpp +++ b/src/imgui/window/timeline/menus.cpp @@ -3,9 +3,9 @@ namespace anm2ed::imgui { constexpr StringType FRAME_PROPERTY_LABELS[] = { - BASIC_POSITION, BASIC_SCALE, BASIC_ROTATION, BASIC_SKEW, BASIC_PIVOT, BASIC_CROP, + BASIC_POSITION, BASIC_SCALE, BASIC_ROTATION, BASIC_SKEW, BASIC_PIVOT, BASIC_CROP, BASIC_SIZE, BASIC_REGION, BASIC_TINT, BASIC_COLOR_OFFSET, BASIC_VISIBLE, BASIC_INTERPOLATED, - BASIC_DURATION, BASIC_SHADER, BASIC_DEPTH, BASIC_EVENT, LABEL_SOUNDS}; + BASIC_DURATION, BASIC_SHADER, BASIC_DEPTH, LABEL_CHILD, BASIC_EVENT, LABEL_SOUNDS}; static_assert(std::size(FRAME_PROPERTY_LABELS) == (std::size_t)edit::FrameProperty::COUNT); void TimelineContext::frame_begin() diff --git a/src/imgui/wizard/about.cpp b/src/imgui/wizard/about.cpp index d04a0f4..68416ef 100644 --- a/src/imgui/wizard/about.cpp +++ b/src/imgui/wizard/about.cpp @@ -253,9 +253,9 @@ namespace anm2ed::imgui::wizard state.canvas->layers_render(resources.shaders[shader::TEXTURE], state.model, *animation, {.time = state.time, .isRootTransform = true}, state.canvas->transform_get(zoom, pan), - [&](int id) + [&](const model::Draw& draw) { - auto texture = state.textures.find(id); + auto texture = state.textures.find(draw.spritesheetId); return texture == state.textures.end() ? nullptr : &texture->second; }); diff --git a/src/manager.cpp b/src/manager.cpp index 0382a46..fa05e3c 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -267,8 +267,13 @@ namespace anm2ed auto layer = isLayer ? model::item_get(content.layers, id) : nullptr; auto null = isLayer ? nullptr : model::item_get(content.nulls, id); if (id != -1 && !layer && !null) return; - itemEdit = layer ? ItemEdit{id, layer->name, layer->spritesheetId, false} - : null ? ItemEdit{id, null->name, 0, null->isShowRect} + itemEdit = layer ? ItemEdit{.id = id, + .name = layer->name, + .spritesheetId = layer->spritesheetId, + .isAnimation = layer->is_animation(), + .libraryId = layer->libraryId, + .animation = layer->animation} + : null ? ItemEdit{.id = id, .name = null->name, .isShowRect = null->isShowRect} : ItemEdit{}; itemPropertiesPopups[isLayer ? 0 : 1].open(); } diff --git a/src/manager.hpp b/src/manager.hpp index f395623..946c49e 100644 --- a/src/manager.hpp +++ b/src/manager.hpp @@ -70,6 +70,9 @@ namespace anm2ed std::string name{}; int spritesheetId{}; bool isShowRect{}; + bool isAnimation{}; + int libraryId{-1}; + std::string animation{}; } itemEdit{}; imgui::PopupHelper itemPropertiesPopups[2]{ imgui::PopupHelper(LABEL_MANAGER_LAYER_PROPERTIES, imgui::POPUP_SMALL_NO_HEIGHT), diff --git a/src/model/common.hpp b/src/model/common.hpp index e2b4f8a..2db7985 100644 --- a/src/model/common.hpp +++ b/src/model/common.hpp @@ -28,6 +28,8 @@ X(EVENT_ELEMENT, "Event") \ X(SOUNDS, "Sounds") \ X(SOUND_ELEMENT, "Sound") \ + X(LIBRARIES, "Libraries") \ + X(LIBRARY, "Library") \ X(ANIMATIONS, "Animations") \ X(ANIMATION, "Animation") \ X(ROOT_ANIMATION, "RootAnimation") \ @@ -70,6 +72,16 @@ namespace anm2ed COUNT }; + // How an animation layer's child animation plays through a keyframe: looping, once (then holding its last frame), + // or held at the keyframe's start frame. + enum class ChildMode + { + LOOP, + ONCE, + HOLD, + COUNT + }; + enum class ItemType { NONE, diff --git a/src/model/draw.cpp b/src/model/draw.cpp index 0355646..ad1f817 100644 --- a/src/model/draw.cpp +++ b/src/model/draw.cpp @@ -1,6 +1,7 @@ #include "draw.hpp" #include +#include #include "frames.hpp" #include "math.hpp" @@ -9,6 +10,9 @@ using namespace anm2ed::util; namespace anm2ed::model { + constexpr unsigned RANDOM_MULTIPLIER_A = 73856093u; + constexpr unsigned RANDOM_MULTIPLIER_B = 19349663u; + glm::mat4 draw_quad_model_get(const Draw& draw) { auto& frame = draw.frame; @@ -39,7 +43,43 @@ namespace anm2ed::model return times; } - std::vector animation_draws_get(const Model& model, const Animation& animation, const DrawOptions& options) + // A keyframe's start frame in its child animation; a random start is fixed per layer and keyframe. + float child_start_get(const Frame& frame, int length, int seed, int index) + { + if (!frame.isChildStartRandom) return (float)frame.childStart; + return (float)((((unsigned)seed * RANDOM_MULTIPLIER_A) ^ ((unsigned)index * RANDOM_MULTIPLIER_B)) % + (unsigned)length); + } + + // Where an animation layer's child animation is at `time`. Its clock runs from the last keyframe that restarted it + // (the first, one set to restart, or one that changes the animation), from that keyframe's start frame; the keyframe + // playing then loops the child, stops it at its end, or holds its own start frame. + float child_time_get(const Track& track, float time, int length, int seed) + { + float start{}; + float clockStart{}; + float clockOffset{}; + for (int i = 0; i < (int)track.frames.size(); ++i) + { + auto& frame = track.frames[i]; + if (i == 0 || frame.isChildRestart || frame.childAnimation != track.frames[i - 1].childAnimation) + { + clockStart = start; + clockOffset = child_start_get(frame, length, seed, i); + } + start += frame.duration; + if (time >= start && i + 1 < (int)track.frames.size()) continue; + if (frame.childMode == ChildMode::HOLD) return child_start_get(frame, length, seed, i); + auto childTime = clockOffset + std::max(time, 0.0f) - clockStart; + if (frame.childMode == ChildMode::ONCE) return std::min(childTime, (float)(length - 1)); + return std::fmod(childTime, (float)length); + } + return 0.0f; + } + + // `playing` holds the animations being drawn into one another, so an animation never draws itself. + std::vector animation_draws_get(const Model& model, const Animation& animation, const DrawOptions& options, + std::vector& playing) { std::vector draws{}; // Each layer draw's place in the drawing order: its track's position among the layers plus its frame's depth; a @@ -54,14 +94,50 @@ namespace anm2ed::model if (group) parent *= frame_parent_model_get(frame_generate(group->root, time)); return parent; }; + // An animation layer's child animation, placed by the layer's frame (its pivot is the child's origin). + auto child_draws_add = + [&](const Track& track, const Layer& layer, int sample, float time, const Frame& frame, const glm::mat4& parent) + { + auto childModel = layer.libraryId == -1 ? &model + : options.library_get ? options.library_get(model, layer.libraryId) + : nullptr; + auto childAnimation = + childModel + ? childModel->animation_named_get(frame.childAnimation.empty() ? layer.animation : frame.childAnimation) + : nullptr; + if (!childAnimation || childAnimation->frameNum < FRAME_NUM_MIN || std::ranges::contains(playing, childAnimation)) + return; + playing.push_back(childAnimation); + auto transform = parent * math::quad_model_get(glm::vec2(1.0f), frame.position, frame.pivot, + math::percent_to_unit(frame.scale), frame.rotation, + math::percent_to_unit(frame.skew)); + DrawOptions childOptions{.time = child_time_get(track, time, childAnimation->frameNum, layer.id), + .isRootTransform = true, + .library_get = options.library_get}; + for (auto child : animation_draws_get(*childModel, *childAnimation, childOptions, playing)) + { + if (child.type != DrawType::LAYER) continue; + child.id = layer.id; + child.sample = sample; + child.time = time; + child.parent = transform * child.parent; + child.frame.tint *= frame.tint; + child.frame.colorOffset += frame.colorOffset; + if (child.source != &model) child.frame.shaderId = -1; + layerOrders.emplace_back(layerOrder + frame.depth, frame.depth); + draws.push_back(std::move(child)); + } + playing.pop_back(); + }; auto track_draws_add = [&](const Track& track, DrawType type, int id, int groupType, const TrackGroup* group) { + auto layer = type == DrawType::LAYER ? item_get(model.content.layers, id) : nullptr; for (auto [sample, time] : draw_times_get(animation, track, options)) { auto frame = frame_generate(track, time); if (!frame.isVisible) continue; auto parent = parent_get(time, type == DrawType::ROOT ? nullptr : group); - if (type == DrawType::LAYER) + if (layer) { frame = model.frame_effective(id, frame); if (options.isRootTransform) @@ -72,12 +148,16 @@ namespace anm2ed::model frame.tint *= rootFrame.tint; frame.colorOffset += rootFrame.colorOffset; } + if (layer->is_animation()) + { + child_draws_add(track, *layer, sample, time, frame, parent); + continue; + } } layerOrders.emplace_back(layerOrder + frame.depth, frame.depth); - draws.push_back({type, id, groupType, sample, time, frame, parent}); + draws.push_back({type, id, groupType, sample, time, frame, parent, &model, layer ? layer->spritesheetId : -1}); } }; - if (animation.root.isVisible) track_draws_add(animation.root, DrawType::ROOT, -1, NONE, nullptr); for (auto [type, entries] : {std::pair{LAYER, &animation.layers}, std::pair{NULL_, &animation.nulls}}) { @@ -117,4 +197,10 @@ namespace anm2ed::model draws[layerIndices[i]] = std::move(layerDraws[i]); return draws; } + + std::vector animation_draws_get(const Model& model, const Animation& animation, const DrawOptions& options) + { + std::vector playing{&animation}; + return animation_draws_get(model, animation, options, playing); + } } diff --git a/src/model/draw.hpp b/src/model/draw.hpp index 7662442..f514cae 100644 --- a/src/model/draw.hpp +++ b/src/model/draw.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include "model.hpp" @@ -22,16 +23,22 @@ namespace anm2ed::model int indexOffset{}; }; + // The document a library id of a document (the one drawn, or a library) points at; nullptr when not loaded. + using LibraryGet = std::function; + struct DrawOptions { float time{}; bool isRootTransform{}; bool isIndexSampled{}; std::vector samples{}; + LibraryGet library_get{}; }; // An item's frame at a time; `parent` is the transform of its root and group root when root transforms are shown // (whose tint and color offset are then folded into a layer's frame). `sample` indexes the samples, -1 for now. + // A layer draw shows spritesheet `spritesheetId` of `source`; an animation layer's child animation draws as its + // layers' draws, with the animation layer's id and transform. struct Draw { DrawType type{}; @@ -41,6 +48,8 @@ namespace anm2ed::model float time{}; Frame frame{}; glm::mat4 parent{1.0f}; + const Model* source{}; + int spritesheetId{-1}; }; glm::mat4 draw_quad_model_get(const Draw&); diff --git a/src/model/frames.cpp b/src/model/frames.cpp index 77e50be..09a1468 100644 --- a/src/model/frames.cpp +++ b/src/model/frames.cpp @@ -209,7 +209,8 @@ namespace anm2ed::model } // Bounds of all visible layer frames over the animation's length, or -1 when nothing is drawn. - glm::vec4 animation_rect(const Model& model, const Animation& animation, bool isRootTransform) + glm::vec4 animation_rect(const Model& model, const Animation& animation, bool isRootTransform, + const LibraryGet& library_get) { constexpr glm::ivec2 CORNERS[4] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}}; glm::vec2 min{std::numeric_limits::infinity()}; @@ -217,7 +218,8 @@ namespace anm2ed::model bool isAny{}; for (float time = 0.0f; time < (float)animation.frameNum; time += 1.0f) - for (const auto& draw : animation_draws_get(model, animation, {.time = time, .isRootTransform = isRootTransform})) + for (const auto& draw : animation_draws_get( + model, animation, {.time = time, .isRootTransform = isRootTransform, .library_get = library_get})) { if (draw.type != DrawType::LAYER || draw.frame.size == glm::vec2()) continue; auto transform = draw.parent * draw_quad_model_get(draw); diff --git a/src/model/frames.hpp b/src/model/frames.hpp index 932bf0b..705ce4c 100644 --- a/src/model/frames.hpp +++ b/src/model/frames.hpp @@ -3,7 +3,7 @@ #include #include -#include "model.hpp" +#include "draw.hpp" namespace anm2ed::model { @@ -19,5 +19,5 @@ namespace anm2ed::model void frames_generate_from_grid(Track&, glm::ivec2, glm::ivec2, glm::vec2, int, int, int); void frames_sort_by_at_frame(Track&); void frames_change(Track&, FrameChange, ItemType, ChangeType, const std::set&); - glm::vec4 animation_rect(const Model&, const Animation&, bool); + glm::vec4 animation_rect(const Model&, const Animation&, bool, const LibraryGet& = {}); } diff --git a/src/model/model.cpp b/src/model/model.cpp index 972b189..a41bc6f 100644 --- a/src/model/model.cpp +++ b/src/model/model.cpp @@ -47,6 +47,13 @@ namespace anm2ed::model return const_cast(slot->get()); } + const Animation* Model::animation_named_get(std::string_view name) const + { + for (auto [index, animation] : animations_get()) + if (animation->name == name) return animation; + return nullptr; + } + std::vector> Model::animations_get() const { std::vector> result{}; @@ -232,9 +239,9 @@ namespace anm2ed::model }); }; - if (type == ElementType::SPRITESHEET) + if (type == ElementType::SPRITESHEET || type == ElementType::LIBRARY) for (const auto& layer : content.layers) - used.insert(layer.spritesheetId); + used.insert(type == ElementType::LIBRARY ? layer.libraryId : layer.spritesheetId); else if (only) used_insert(*only); else @@ -255,6 +262,8 @@ namespace anm2ed::model return unused_ids_get(content.events, used); case ElementType::SOUND_ELEMENT: return unused_ids_get(content.sounds, used); + case ElementType::LIBRARY: + return unused_ids_get(content.libraries, used); default: return {}; } @@ -356,6 +365,8 @@ namespace anm2ed::model repair(event.uid); for (auto& sound : content.sounds) repair(sound.uid); + for (auto& library : content.libraries) + repair(library.uid); } int track_frames_count_get(const Track& track) { return (int)track.frames.size(); } diff --git a/src/model/model.hpp b/src/model/model.hpp index 2740c8e..5c89e9d 100644 --- a/src/model/model.hpp +++ b/src/model/model.hpp @@ -55,6 +55,12 @@ namespace anm2ed::model int regionId{-1}; int shaderId{-1}; int depth{}; // a layer frame draws this many layers above (or below) its place in the timeline; editor-only + // On an animation layer: the child animation (empty for the layer's own) and how it plays; editor-only. + std::string childAnimation{}; + ChildMode childMode{ChildMode::LOOP}; + int childStart{}; + bool isChildStartRandom{}; + bool isChildRestart{}; int atFrame{-1}; int eventId{-1}; std::vector soundIds{}; @@ -193,11 +199,27 @@ namespace anm2ed::model int id{-1}; std::string name{}; int spritesheetId{}; + // An animation layer plays `animation` (from library `libraryId`, or this file at -1) instead of showing its + // spritesheet. + int libraryId{-1}; + std::string animation{}; Extras extras{}; + bool is_animation() const { return !animation.empty(); } bool operator==(const Layer&) const = default; }; + // Another .anm2 whose animations this one's layers can play. + struct Library + { + std::uint64_t uid{util::uid_next()}; + int id{-1}; + std::filesystem::path path{}; + Extras extras{}; + + bool operator==(const Library&) const = default; + }; + struct Null { std::uint64_t uid{util::uid_next()}; @@ -248,6 +270,7 @@ namespace anm2ed::model std::vector nulls{}; std::vector events{}; std::vector sounds{}; + std::vector libraries{}; std::vector layout{ElementType::SPRITESHEETS, ElementType::SHADERS, ElementType::LAYERS, ElementType::NULLS, ElementType::EVENTS}; Extras extras{}; @@ -338,6 +361,7 @@ namespace anm2ed::model int animations_count_get() const; const Animation* animation_get(int) const; + const Animation* animation_named_get(std::string_view) const; Animation* animation_edit(int); int animation_group_id_get(int) const; const AnimationGroup* animation_group_get(int) const; diff --git a/src/model/xml.cpp b/src/model/xml.cpp index ce553f7..9854d02 100644 --- a/src/model/xml.cpp +++ b/src/model/xml.cpp @@ -28,6 +28,8 @@ namespace anm2ed::model }; constexpr std::string_view INTERPOLATION_VALUES[] = {"", "", "EaseIn", "EaseOut", "EaseInOut"}; constexpr std::string_view ORIGIN_VALUES[] = {"", "TopLeft", "Center"}; + constexpr std::string_view CHILD_MODE_VALUES[] = {"Loop", "Once", "Hold"}; + 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. @@ -38,7 +40,8 @@ namespace anm2ed::model "ShaderId", "Depth", "SoundId", "GroupId", "Index", "Loop", "StartMarker", "EndMarker", "Visible", "ShowRect", "IsExpanded", "Enabled", "Rotation", "XPivot", "YPivot", "XCrop", "YCrop", "XPosition", "YPosition", "Width", "Height", "XScale", "YScale", "SkewX", "SkewY", "ShearX", "ShearY", "RedTint", "GreenTint", "BlueTint", "AlphaTint", "RedOffset", "GreenOffset", "BlueOffset", - "Interpolated", "Origin", "BakeInterpolation", "BakeDelay", "BakeCount", "OriginalDelay"}; + "Interpolated", "Origin", "BakeInterpolation", "BakeDelay", "BakeCount", "OriginalDelay", "Library", "Animation", + "ChildAnimation", "ChildMode", "ChildStart", "Restart"}; // clang-format on constexpr std::string_view SOURCE_DOCUMENT_TAG = "SourceDocument"; constexpr std::string_view FRAME_RESTORE_TAG = "FrameRestore"; @@ -220,6 +223,13 @@ namespace anm2ed::model frame.regionId = int_get(element, "RegionId"); frame.shaderId = int_get(element, "ShaderId"); frame.depth = int_get(element, "Depth", 0); + frame.childAnimation = string_get(element, "ChildAnimation"); + auto childMode = std::ranges::find(CHILD_MODE_VALUES, string_get(element, "ChildMode")); + if (childMode != std::end(CHILD_MODE_VALUES)) + frame.childMode = (ChildMode)(childMode - std::begin(CHILD_MODE_VALUES)); + frame.isChildStartRandom = string_get(element, "ChildStart") == CHILD_START_RANDOM; + frame.childStart = int_get(element, "ChildStart", 0); + frame.isChildRestart = bool_get(element, "Restart", false); frame.atFrame = int_get(element, "AtFrame"); frame.eventId = int_get(element, "EventId"); frame.extras = extras_read(element); @@ -588,6 +598,8 @@ namespace anm2ed::model return {.id = int_get(element, "Id"), .name = string_get(element, "Name"), .spritesheetId = int_get(element, "SpritesheetId", 0), + .libraryId = int_get(element, "Library"), + .animation = string_get(element, "Animation"), .extras = extras_read(element)}; } template <> Null item_read(const XMLElement* element) @@ -605,6 +617,10 @@ namespace anm2ed::model { return {.id = int_get(element, "Id"), .path = path_get(element, "Path"), .extras = extras_read(element)}; } + template <> Library item_read(const XMLElement* element) + { + return {.id = int_get(element, "Id"), .path = path_get(element, "Path"), .extras = extras_read(element)}; + } template constexpr ElementType ITEM_TYPE{}; template <> constexpr ElementType ITEM_TYPE{ElementType::SPRITESHEET}; @@ -614,6 +630,7 @@ namespace anm2ed::model template <> constexpr ElementType ITEM_TYPE{ElementType::NULL_ELEMENT}; template <> constexpr ElementType ITEM_TYPE{ElementType::EVENT_ELEMENT}; template <> constexpr ElementType ITEM_TYPE{ElementType::SOUND_ELEMENT}; + template <> constexpr ElementType ITEM_TYPE{ElementType::LIBRARY}; template std::vector items_read(const XMLElement* container, Content& content, ElementType type) { @@ -640,7 +657,8 @@ namespace anm2ed::model if (child->Name() == LEGACY_GROUPS_TAG) return; auto isKnown = type == ElementType::SPRITESHEETS || type == ElementType::SHADERS || type == ElementType::LAYERS || type == ElementType::NULLS || - type == ElementType::EVENTS || type == ElementType::SOUNDS; + type == ElementType::EVENTS || type == ElementType::SOUNDS || + type == ElementType::LIBRARIES; if (!isKnown || std::ranges::contains(content.layout, type)) return extras_child_add(content.extras, child, position); content.layout.push_back(type); @@ -651,6 +669,7 @@ namespace anm2ed::model if (type == ElementType::NULLS) content.nulls = items_read(child, content, type); if (type == ElementType::EVENTS) content.events = items_read(child, content, type); if (type == ElementType::SOUNDS) content.sounds = items_read(child, content, type); + if (type == ElementType::LIBRARIES) content.libraries = items_read(child, content, type); }); return content; } @@ -691,6 +710,7 @@ namespace anm2ed::model ids_repair(content.nulls); ids_repair(content.events); ids_repair(content.sounds); + ids_repair(content.libraries); for (auto& spritesheet : content.spritesheets) ids_repair(spritesheet.regions); for (auto& shader : content.shaders) @@ -1146,8 +1166,17 @@ namespace anm2ed::model sink.attribute("Rotation", frame.rotation); interpolation_add(sink, "Interpolated", frame.interpolation); if (writer.is(SERIALIZE_EXTENSIONS) && frame.shaderId != -1) sink.attribute("ShaderId", frame.shaderId); - if (writer.is(SERIALIZE_EXTENSIONS) && type == ItemType::LAYER && frame.depth != 0) - sink.attribute("Depth", frame.depth); + if (writer.is(SERIALIZE_EXTENSIONS) && type == ItemType::LAYER) + { + if (frame.depth != 0) sink.attribute("Depth", frame.depth); + if (!frame.childAnimation.empty()) sink.attribute("ChildAnimation", frame.childAnimation); + if (frame.childMode != ChildMode::LOOP) sink.attribute("ChildMode", CHILD_MODE_VALUES[(int)frame.childMode]); + if (frame.isChildStartRandom) + sink.attribute("ChildStart", CHILD_START_RANDOM); + else if (frame.childStart != 0) + sink.attribute("ChildStart", frame.childStart); + if (frame.isChildRestart) sink.attribute("Restart", frame.isChildRestart); + } extras_attributes_write(sink, frame.extras); if (bake.delay > 0) { @@ -1325,6 +1354,7 @@ namespace anm2ed::model IsaacIssues isaac_issues_get(const Model& model) { IsaacIssues issues{}; + issues.animationLayers = (int)std::ranges::count_if(model.content.layers, &Layer::is_animation); for (auto [index, animation] : model.animations_get()) { for (const auto* entries : {&animation->layers, &animation->nulls}) @@ -1544,12 +1574,17 @@ namespace anm2ed::model children.close(); } - void item_write(Sink& sink, const Writer&, const Layer& layer, int id) + void item_write(Sink& sink, const Writer& writer, const Layer& layer, int id) { sink.open(tag_get(ElementType::LAYER_ELEMENT)); sink.attribute("Id", id); sink.attribute("Name", layer.name); sink.attribute("SpritesheetId", layer.spritesheetId); + if (writer.is(SERIALIZE_EXTENSIONS) && layer.is_animation()) + { + if (layer.libraryId != -1) sink.attribute("Library", layer.libraryId); + sink.attribute("Animation", layer.animation); + } extras_write(sink, layer.extras); element_close(sink, layer.extras); } @@ -1573,13 +1608,24 @@ namespace anm2ed::model element_close(sink, event.extras); } + // Sounds and libraries are a path. + template void item_path_write(Sink& sink, const Item& item, ElementType type, int id) + { + sink.open(tag_get(type)); + sink.attribute("Id", id); + path_add(sink, "Path", item.path); + extras_write(sink, item.extras); + element_close(sink, item.extras); + } + void item_write(Sink& sink, const Writer&, const Sound& sound, int id) { - sink.open(tag_get(ElementType::SOUND_ELEMENT)); - sink.attribute("Id", id); - path_add(sink, "Path", sound.path); - extras_write(sink, sound.extras); - element_close(sink, sound.extras); + item_path_write(sink, sound, ElementType::SOUND_ELEMENT, id); + } + + void item_write(Sink& sink, const Writer&, const Library& library, int id) + { + item_path_write(sink, library, ElementType::LIBRARY, id); } // A content container's unknown XML (a file may repeat a container; its parts are merged in order). @@ -1622,7 +1668,8 @@ namespace anm2ed::model {ElementType::LAYERS, !content.layers.empty()}, {ElementType::NULLS, !content.nulls.empty()}, {ElementType::EVENTS, !content.events.empty()}, - {ElementType::SOUNDS, !content.sounds.empty()}})) + {ElementType::SOUNDS, !content.sounds.empty()}, + {ElementType::LIBRARIES, !content.libraries.empty()}})) { children.add(); auto extras = container_extras_get(content, type); @@ -1634,6 +1681,9 @@ namespace anm2ed::model if (type == ElementType::SOUNDS && writer.is(SERIALIZE_SOUNDS) && (!content.sounds.empty() || !extras.children.empty())) items_write(sink, writer, content.sounds, type, extras); + if (type == ElementType::LIBRARIES && writer.is(SERIALIZE_EXTENSIONS) && + (!content.libraries.empty() || !extras.children.empty())) + items_write(sink, writer, content.libraries, type, extras); if (type == ElementType::SPRITESHEETS) items_write(sink, writer, content.spritesheets, type, extras); if (type == ElementType::LAYERS) items_write(sink, writer, content.layers, type, extras); if (type == ElementType::NULLS) items_write(sink, writer, content.nulls, type, extras); @@ -1840,5 +1890,6 @@ namespace anm2ed::model X(Null) X(Event) X(Sound) + X(Library) #undef X } diff --git a/src/model/xml.hpp b/src/model/xml.hpp index 9d1e668..06d78e3 100644 --- a/src/model/xml.hpp +++ b/src/model/xml.hpp @@ -17,6 +17,7 @@ namespace anm2ed::model int shaderFrames{}; int depthFrames{}; int triggerSounds{}; + int animationLayers{}; bool operator==(const IsaacIssues&) const = default; }; diff --git a/src/render.cpp b/src/render.cpp index e98e329..18c3689 100644 --- a/src/render.cpp +++ b/src/render.cpp @@ -309,7 +309,7 @@ namespace anm2ed::render glm::vec4 animation_bounds_get(const Document& document, const model::Animation& animation, bool isRootTransform) { - auto bounds = model::animation_rect(document.model, animation, isRootTransform); + auto bounds = model::animation_rect(document.model, animation, isRootTransform, document.library_resolver_get()); return bounds != glm::vec4(-1.0f) ? bounds : BOUNDS_DEFAULT; } @@ -325,8 +325,9 @@ namespace anm2ed::render canvas.viewport_set(); canvas.clear(glm::vec4(glm::vec3(background) * background.a, background.a)); canvas.layers_render( - shader, document.model, animation, {.time = time, .isRootTransform = isRootTransform}, - canvas.transform_get(zoom, pan), [&](int id) { return document.texture_get(id); }, + shader, document.model, animation, + {.time = time, .isRootTransform = isRootTransform, .library_get = document.library_resolver_get()}, + canvas.transform_get(zoom, pan), [&](const model::Draw& draw) { return document.draw_image_get(draw); }, [&](int id) { return document.shader_get(id); }); auto pixels = canvas.pixels_get(); canvas.unbind(); diff --git a/src/resource/strings.hpp b/src/resource/strings.hpp index dade8a3..604917a 100644 --- a/src/resource/strings.hpp +++ b/src/resource/strings.hpp @@ -110,6 +110,7 @@ namespace anm2ed X(BASIC_YES, "Yes", "Si", "Да", "是", "예") \ X(BASIC_ZOOM, "Zoom", "Zoom", "Масштаб", "缩放", "확대") \ X(EDIT_ADD_ANIMATION, "Add Animation", "Añadir Animacion", "Добавить анимацию", "添加动画", "애니메이션 추가") \ + X(EDIT_ADD_LIBRARY, "Add Library", "Añadir Biblioteca", "Добавить библиотеку", "添加库", "라이브러리 추가") \ X(EDIT_ADD_REGION, "Add Region", "Añadir Región", "Добавить регион", "添加区域", "영역 추가") \ X(EDIT_ADD_EVENT, "Add Event", "Añadir Evento", "Добавить событие", "添加事件", "이벤트 추가") \ X(EDIT_ADD_ITEM, "Add Item", "Añadir Item", "Добавить предмет", "添加物品", "항목 추가") \ @@ -122,8 +123,10 @@ namespace anm2ed 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", "Глубина кадра", "帧深度", "프레임 깊이") \ X(EDIT_PASTE_FRAME_PROPERTY, "Paste Frame Property", "Pegar Propiedad del Frame", "Вставка свойства кадра", "粘贴帧属性", "프레임 속성 붙여넣기") \ + X(EDIT_PASTE_LIBRARIES, "Paste Libraries", "Pegar Bibliotecas", "Вставить библиотеки", "粘贴库", "라이브러리 붙여넣기") \ X(EDIT_REMOVE_MARKERS, "Remove Markers", "Quitar Marcadores", "Удаление маркеров", "移除标记", "마커 제거") \ X(EDIT_REMOVE_TRIGGER_SOUND, "Remove Trigger Sound", "Remover Sonido del Trigger", "Удалить звук триггера", "移除事件触发器声音", "트리거 사운드 제거") \ X(EDIT_ANIMATION_LENGTH, "Animation Length", "Duracion De Animacion", "Длина анимации", "动画时长", "애니메이션 길이") \ @@ -144,6 +147,7 @@ namespace anm2ed X(EDIT_FPS, "FPS", "FPS", "FPS", "每秒帧数(FPS)", "FPS") \ X(EDIT_GROUP_ITEMS, "Group Item(s)", "Agrupar item(s)", "Сгруппировать элементы", "将项目分组", "항목 그룹화") \ X(EDIT_REMOVE_GROUP, "Remove Group", "Eliminar grupo", "Удалить группу", "删除组", "그룹 삭제") \ + X(EDIT_REMOVE_UNUSED_LIBRARIES, "Remove Unused Libraries", "Eliminar Bibliotecas No Usadas", "Удалить неиспользуемые библиотеки", "删除未使用的库", "사용하지 않는 라이브러리 제거") \ X(EDIT_START_MARKER, "Set Start Marker", "Poner Marcador de Inicio", "Начальный маркер", "设置起始标记", "시작 마커 설정") \ X(EDIT_TOGGLE_GROUP_EXPANDED, "Toggle Group Expanded", "Alternar grupo expandido", "Развернуть/свернуть группу", "展开/折叠组", "그룹 펼침 전환") \ X(EDIT_FRAME_COLOR_OFFSET, "Frame Color Offset", "Offset de color de Frame", "Смещение цвета кадра", "帧颜色偏移", "프레임 색상 오프셋") \ @@ -224,12 +228,15 @@ namespace anm2ed X(FORMAT_DURATION, "Duration: {0}", "Duracion: {0}", "Продолжительность: {0}", "时长: {0}", "유지 시간: {0}") \ X(FORMAT_EVENT_LABEL, "Event: {0}", "Evento: {0}", "Событие: {0}", "事件: {0}", "이벤트: {0}") \ X(FORMAT_ID, "ID: {0}", "ID: {0}", "ID: {0}", "ID: {0}", "ID: {0}") \ + X(FORMAT_ISAAC_ANIMATION_LAYERS, "{} layer(s) play animations, which the game doesn't support; they will draw nothing.", "{} capa(s) reproducen animaciones, que el juego no soporta; no dibujarán nada.", "{} слой(ёв) проигрывают анимации, которые игра не поддерживает; они ничего не отобразят.", "{} 个图层播放动画,游戏不支持;它们将不显示任何内容。", "{}개의 레이어가 애니메이션을 재생합니다. 게임에서 지원하지 않으므로 아무것도 그리지 않습니다.") \ X(FORMAT_ISAAC_DEPTH_FRAMES, "{} frame(s) change their layer's depth, which the game doesn't support; they will draw in timeline order.", "{} Frame(s) cambian la profundidad de su capa, que el juego no soporta; se dibujarán en el orden de la línea de tiempo.", "{} кадр(ов) меняют глубину слоя, что игра не поддерживает; они будут рисоваться в порядке таймлайна.", "{} 个帧改变了图层深度,游戏不支持,将按时间轴顺序绘制。", "프레임 {}개가 게임이 지원하지 않는 레이어 깊이를 바꿉니다. 타임라인 순서로 그려집니다.") \ X(FORMAT_ISAAC_EASED_FRAMES, "{} eased frame(s) will be baked into one-frame steps.", "{} Frame(s) con suavizado se convertirán en pasos de un Frame.", "{} кадр(ов) со сглаживанием будут запечены в покадровые шаги.", "{} 个缓动帧将被烘焙为逐帧步进。", "이징 프레임 {}개가 1프레임 단위로 베이크됩니다.") \ X(FORMAT_ISAAC_GROUP_TRANSFORMS, "{} group transform(s) will be baked into their items' frames.", "{} transformación(es) de grupo se aplicarán a los Frames de sus elementos.", "{} трансформаци(й) групп будут запечены в кадры их элементов.", "{} 个组变换将被烘焙到其项目的帧中。", "그룹 변형 {}개가 항목의 프레임에 베이크됩니다.") \ X(FORMAT_ISAAC_SHADER_FRAMES, "{} frame(s) use shaders, which the game doesn't support; they will be dropped.", "{} Frame(s) usan shaders, que el juego no soporta; se descartarán.", "{} кадр(ов) используют шейдеры, которые игра не поддерживает; они будут отброшены.", "{} 个帧使用了着色器,游戏不支持,将被舍弃。", "프레임 {}개가 게임이 지원하지 않는 셰이더를 사용합니다. 셰이더는 제거됩니다.") \ X(FORMAT_ISAAC_SKEW_FRAMES, "{} frame(s) use skew, which the game doesn't support; it will be dropped.", "{} Frame(s) usan inclinación, que el juego no soporta; se descartará.", "{} кадр(ов) используют наклон, который игра не поддерживает; он будет отброшен.", "{} 个帧使用了斜切,游戏不支持,将被舍弃。", "프레임 {}개가 게임이 지원하지 않는 기울이기를 사용합니다. 기울이기는 제거됩니다.") \ X(FORMAT_ISAAC_TRIGGER_SOUNDS, "{} trigger(s) have sounds, which the game doesn't read from animations; they will be dropped.", "{} disparador(es) tienen sonidos, que el juego no lee de las animaciones; se descartarán.", "{} триггер(ов) имеют звуки, которые игра не читает из анимаций; они будут отброшены.", "{} 个触发器带有声音,游戏不会从动画中读取,将被舍弃。", "트리거 {}개에 게임이 애니메이션에서 읽지 않는 사운드가 있습니다. 사운드는 제거됩니다.") \ + X(FORMAT_LAYER_ANIMATION, "#{0} {1} (Animation: {2})", "#{0} {1} (Animación: {2})", "#{0} {1} (Анимация: {2})", "#{0} {1} (动画: {2})", "#{0} {1} (애니메이션: {2})") \ + X(FORMAT_LIBRARY_ANIMATIONS, "Animations ({0})", "Animaciones ({0})", "Анимации ({0})", "动画 ({0})", "애니메이션 ({0})") \ X(FORMAT_ORIGIN, "Origin: {0}", "Origen: {0}", "Точка отсчета: {0}", "原点: {0}", "원점: {0}") \ X(FORMAT_SPRITESHEET_ID, "Spritesheet ID: {0}", "ID de Spritesheet: {0}", "", "图集 ID: {0}", "스프라이트 시트 ID: {0}") \ X(FORMAT_INDEX, "Index: {0}", "Indice: {0}", "Индекс: {0}", "下标: {0}", "인덱스: {0}") \ @@ -266,16 +273,25 @@ namespace anm2ed X(LABEL_ADD_START_MARKER, "Add Start Marker Here", "Añadir Marcador de Inicio Aquí", "Поставить начальный маркер здесь", "在此添加起始标记", "여기에 시작 마커 추가") \ X(LABEL_ADJUST, "Adjust", "Ajustar", "Отрегулировать", "调节", "조정") \ X(LABEL_ALT_ICONS, "Alt Icons", "Iconos Alternos", "Альт-иконки", "替代图标", "대체 아이콘") \ + X(LABEL_ANIMATION, "Animation", "Animación", "Анимация", "动画", "애니메이션") \ X(LABEL_ANIMATIONS_CHILD, "Animations", "Animaciones", "", "动画", "애니메이션") \ X(LABEL_ANIMATIONS_MERGE_POPUP, "Merge Animations", "Combinar Animaciones", "Соединить анимации", "合并多个动画", "애니메이션 병합") \ X(LABEL_AUTO_SPRITESHEET_RELOAD, "Auto Spritesheet Reload", "Recarga Automática de Spritesheets", "Автоперезагрузка спрайт-листов", "自动重新加载图集", "스프라이트 시트 자동 새로고침") \ + X(LABEL_CHILD, "Child", "Hijo", "Дочерняя", "子动画", "자식") \ X(LABEL_DETACHABLE_WINDOWS, "Detachable Windows", "Ventanas Desacoplables", "Отделяемые окна", "可分离窗口", "분리 가능한 창") \ X(LABEL_DOCUMENT_EXTENDED_FORMAT, "Extended Format", "Formato Extendido", "Расширенный формат", "扩展格式", "확장 형식") \ + X(LABEL_HOLD, "Hold", "Mantener", "Удерживать", "保持", "유지") \ X(LABEL_ISAAC_COMPATIBILITY_WARNING, "Isaac Compatibility Warning", "Advertencia de Compatibilidad con Isaac", "Предупреждение о совместимости с Isaac", "Isaac 兼容性警告", "Isaac 호환성 경고") \ + X(LABEL_LAYER_SOURCE, "Source", "Fuente", "Источник", "来源", "소스") \ + X(LABEL_LIBRARIES_WINDOW, "Libraries###Libraries", "Bibliotecas###Libraries", "Библиотеки###Libraries", "库###Libraries", "라이브러리###Libraries") \ + X(LABEL_LIBRARY, "Library", "Biblioteca", "Библиотека", "库", "라이브러리") \ + X(LABEL_ONCE, "Once", "Una vez", "Один раз", "一次", "한 번") \ X(LABEL_ONLY_SELECTED_ITEM, "Only Selected Item", "Solo el Elemento Seleccionado", "Только выбранный элемент", "仅选中项目", "선택한 항목만") \ X(LABEL_PIVOT_PATH, "Pivot Path", "Trayectoria del Pivote", "Путь опорной точки", "枢轴路径", "피벗 경로") \ X(LABEL_PROPERTY, "Property", "Propiedad", "Свойство", "属性", "속성") \ + X(LABEL_RANDOM, "Random", "Aleatorio", "Случайно", "随机", "무작위") \ 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_SPRITESHEETS_PACK_POPUP, "Pack Spritesheet", "Empaquetar spritesheet", "Упаковать спрайт-лист", "打包图集", "스프라이트 시트 패킹") \ X(LABEL_SPRITESHEETS_MERGE_POPUP, "Merge Spritesheets", "Combinar Spritesheets", "Объединить спрайт-листы", "合并图集", "스프라이트 시트 병합") \ @@ -356,6 +372,7 @@ namespace anm2ed X(LABEL_LAYER, "Layer", "Capa", "Слой", "动画层", "레이어") \ X(LABEL_LAYERS_CHILD, "Layers List", "Lista de Capas", "", "动画层列表", "레이어 목록") \ X(LABEL_LAYERS_WINDOW, "Layers###Layers", "Capas###Layers", "Слои###Layers", "动画层###Layers", "레이어###Layers") \ + X(LABEL_START_FRAME, "Start Frame", "Frame Inicial", "Начальный кадр", "起始帧", "시작 프레임") \ X(LABEL_THIS_ANIMATION, "This Animation", "Esta Animacion", "Эта анимация", "此动画", "이 애니메이션") \ X(LABEL_DESTINATION, "Destination", "Destino", "Назначение", "目标", "대상") \ X(LABEL_ITEMS, "Items", "Items", "Предметы", "物品", "항목") \ @@ -537,15 +554,28 @@ namespace anm2ed X(SNAPSHOT_RENAME_ANIMATION, "Rename Animation", "Renombrar Animacion", "Переименовать анимацию", "重命名动画", "애니메이션 이름 바꾸기") \ 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_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!", "Сначала выберите кадр или регион!", "请先选择帧或区域!", "먼저 프레임 또는 영역을 선택하세요!") \ X(TOOLTIP_AUTO_SPRITESHEET_RELOAD, "Reload spritesheets automatically when their files change on disk.\n(Spritesheets with unsaved edits are left alone.)", "Recarga los spritesheets automáticamente cuando sus archivos cambian en el disco.\n(Los spritesheets con cambios sin guardar no se tocan.)", "Автоматически перезагружать спрайт-листы при изменении их файлов на диске.\n(Спрайт-листы с несохранёнными изменениями не затрагиваются.)", "当图集文件在磁盘上更改时自动重新加载。\n(有未保存修改的图集不受影响。)", "디스크의 파일이 바뀌면 스프라이트 시트를 자동으로 새로고침합니다.\n(저장하지 않은 수정이 있는 스프라이트 시트는 건드리지 않습니다.)") \ + X(TOOLTIP_CHILD_ANIMATION, "The animation this keyframe plays; the layer's unless set. Changing it restarts the child.", "La animación que reproduce este keyframe; la de la capa si no se ajusta. Cambiarla reinicia el hijo.", "Анимация этого ключевого кадра; если не задана, то анимация слоя. Смена перезапускает её.", "此关键帧播放的动画;未设置时使用图层的。更改会重新开始子动画。", "이 키프레임이 재생하는 애니메이션입니다. 설정하지 않으면 레이어의 것을 사용합니다. 바꾸면 자식이 다시 시작됩니다.") \ + X(TOOLTIP_CHILD_MODE, "Loop the child, play it once and stop on its last frame, or hold it on the start frame.", "Repite el hijo, reprodúcelo una vez y detente en su último frame, o mantenlo en el frame inicial.", "Зациклить дочернюю анимацию, проиграть один раз и остановиться на последнем кадре, или удерживать начальный кадр.", "循环子动画、播放一次并停在最后一帧,或保持在起始帧。", "자식을 반복하거나, 한 번 재생하고 마지막 프레임에서 멈추거나, 시작 프레임에 고정합니다.") \ + X(TOOLTIP_CHILD_RESTART, "Restart the child at this keyframe; otherwise it keeps playing from the keyframe before.", "Reinicia el hijo en este keyframe; si no, sigue desde el keyframe anterior.", "Перезапустить дочернюю анимацию на этом ключевом кадре; иначе она продолжается с предыдущего.", "在此关键帧重新开始子动画;否则从上一个关键帧继续播放。", "이 키프레임에서 자식을 다시 시작합니다. 그렇지 않으면 이전 키프레임부터 계속 재생됩니다.") \ + X(TOOLTIP_CHILD_START, "The child's frame when it starts (or the frame held).", "El frame del hijo al empezar (o el frame mantenido).", "Кадр дочерней анимации при старте (или удерживаемый кадр).", "子动画开始时的帧(或保持的帧)。", "자식이 시작할 때의 프레임(또는 고정된 프레임).") \ + X(TOOLTIP_CHILD_START_RANDOM, "Start the child on a random frame.", "Empieza el hijo en un frame aleatorio.", "Начинать дочернюю анимацию со случайного кадра.", "从随机帧开始子动画。", "자식을 무작위 프레임에서 시작합니다.") \ 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_LIBRARY, "Where the animation comes from: this file, or a library.", "De dónde viene la animación: este archivo o una biblioteca.", "Откуда берётся анимация: этот файл или библиотека.", "动画来自哪里:此文件或库。", "애니메이션의 출처: 이 파일 또는 라이브러리.") \ + X(TOOLTIP_LAYER_SOURCE, "Show a spritesheet, or play an animation (from this file or a library).\n(Animations are editor only; the game draws nothing for them.)", "Muestra un spritesheet o reproduce una animación (de este archivo o de una biblioteca).\n(Las animaciones son solo del editor; el juego no dibuja nada para ellas.)", "Показывать спрайт-лист или проигрывать анимацию (из этого файла или библиотеки).\n(Анимации только для редактора; игра для них ничего не рисует.)", "显示图集,或播放动画(来自此文件或库)。\n(动画仅限编辑器;游戏不会绘制它们。)", "스프라이트 시트를 표시하거나 애니메이션을 재생합니다(이 파일 또는 라이브러리에서).\n(애니메이션은 에디터 전용이며 게임에서는 아무것도 그리지 않습니다.)") \ + X(TOOLTIP_LIBRARY_ADD, "Add an .anm2 whose animations layers can play.", "Añade un .anm2 cuyas animaciones pueden reproducir las capas.", "Добавить .anm2, анимации которого могут проигрывать слои.", "添加一个 .anm2,图层可以播放其中的动画。", "레이어가 애니메이션을 재생할 수 있는 .anm2를 추가합니다.") \ + X(TOOLTIP_LIBRARY_INVALID, "This library could not be loaded. Check the file.", "Esta biblioteca no se pudo cargar. Revisa el archivo.", "Эту библиотеку не удалось загрузить. Проверьте файл.", "无法加载此库。请检查文件。", "이 라이브러리를 불러올 수 없습니다. 파일을 확인하세요.") \ + X(TOOLTIP_LIBRARY_OPEN, "Open the library in its own tab to edit it; saving it updates every file that uses it.", "Abre la biblioteca en su propia pestaña para editarla; al guardarla se actualiza cada archivo que la usa.", "Открыть библиотеку в отдельной вкладке для редактирования; сохранение обновит все файлы, которые её используют.", "在单独的标签页中打开库进行编辑;保存后所有使用它的文件都会更新。", "라이브러리를 자체 탭에서 열어 편집합니다. 저장하면 이를 사용하는 모든 파일이 업데이트됩니다.") \ X(TOOLTIP_MERGE_SPRITESHEETS, "Merge selected spritesheets into the first selected spritesheet.", "Combina los spritesheets seleccionados en el primer spritesheet seleccionado.", "Объединить выбранные спрайт-листы в первый выбранный спрайт-лист.", "将所选图集合并到第一个选中的图集中。", "선택된 스프라이트 시트를 첫 번째 선택된 스프라이트 시트로 병합합니다.") \ X(TEXT_SELECT_SPRITESHEET, "Select a spritesheet first!", "¡Selecciona primero un spritesheet!", "Сначала выберите спрайт-лист!", "请先选择图集!", "먼저 스프라이트 시트를 선택하세요!") \ + X(TEXT_THIS_FILE, "This File", "Este Archivo", "Этот файл", "此文件", "이 파일") \ X(TEXT_TOOL_ANIMATION_PREVIEW, "This tool can only be used in Animation Preview!", "¡Esta herramienta solo se puede usar en Vista previa de animación!", "Этот инструмент можно использовать только в \"Предпросмотре анимации\"!", "该工具只能在“动画预放”中使用!", "이 도구는 애니메이션 프리뷰에서만 사용할 수 있습니다!") \ X(TEXT_TOOL_SPRITESHEET_EDITOR, "This tool can only be used in Spritesheet Editor!", "¡Esta herramienta solo se puede usar en el Editor de spritesheets!", "Этот инструмент можно использовать только в \"Редакторе спрайт-листов\"!", "该工具只能在“图集编辑器”中使用!", "이 도구는 스프라이트 시트 편집기에서만 사용할 수 있습니다!") \ X(TEXT_NEW_ANIMATION, "New Animation", "Nueva Animacion", "Новая анимация", "新动画", "새 애니메이션") \ @@ -563,6 +593,7 @@ namespace anm2ed X(TOAST_DESERIALIZE_FRAMES_FAILED, "Failed to deserialize frames:", "Falla al deserializar Frames:", "Не удалось десериализировать кадры: {0}", "反序列化帧失败: {0}", "프레임 역직렬화 실패: {0}") \ X(TOAST_DESERIALIZE_FRAMES_NO_SELECTION, "Failed to deserialize frames: no selection.", "Falla al deserializar Frames: sin seleccion.", "Не удалось десериализировать кадры: ничего не выбрано.", "到所选帧", "프레임 역직렬화 실패. 선택한 것이 없습니다.") \ X(TOAST_DESERIALIZE_LAYERS_FAILED, "Failed to deserialize layer(s):", "Falla al deserializar capas(s):", "Не удалось десериализировать слои: {0}", "反序列化动画层失败: {0}", "레이어 역직렬화 실패: {0}") \ + X(TOAST_DESERIALIZE_LIBRARIES_FAILED, "Failed to deserialize libraries: {0}", "Falla al deserializar bibliotecas: {0}", "Не удалось десериализировать библиотеки: {0}", "反序列化库失败: {0}", "라이브러리 역직렬화 실패: {0}") \ X(TOAST_DESERIALIZE_REGIONS_FAILED, "Failed to deserialize region(s): {0}", "Falla al deserializar región(es): {0}", "Не удалось десериализировать регионы: {0}", "反序列化区域失败: {0}", "영역 역직렬화 실패: {0}") \ X(TOAST_DESERIALIZE_NULLS_FAILED, "Failed to deserialize null(s): {0}", "Falla al deserializar null(s): {0}", "Не удалось десериализировать нули: {0}", "反序列化Null失败: {0}", "Null 역직렬화 실패: {0}") \ X(TOAST_DESERIALIZE_SPRITESHEETS_FAILED, "Failed to deserialize spritesheet(s): {0}", "Falla al deserializar spritesheet(s): {0}", "Не удалось десериализировать спрайт-листы: {0}", "反序列化图集失败: {0}", "스프라이트 시트 역직렬화 실패: {0}") \ @@ -578,6 +609,7 @@ namespace anm2ed X(TOAST_ADD_SPRITESHEET_FAILED, "Failed to add spritesheet! Open a document first.", "¡Error a añadir spritesheet! Abre un documento primero.", "Не удалось добавить спрайт-лист! Сначала откройте документ.", "无法添加图集!请先打开文档。", "스프라이트 시트를 추가할 수 없습니다! 먼저 문서를 여세요.") \ 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_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}") \ @@ -586,6 +618,7 @@ namespace anm2ed X(TOAST_REDO, "Redo: {0}", "Rehacer: {0}", "Повтор: {0}", "重做: {0}", "다시 실행: {0}") \ X(ERROR_FILE_NOT_FOUND, "File not found!", "¡Archivo no encontrado!", "Файл не найден!", "找不到文件!", "파일을 찾을 수 없습니다!") \ X(ERROR_FILE_PERMISSIONS, "File does not have write permissions!", "¡El archivo no tiene permisos de escritura!", "У файла нет прав на запись!", "文件没有写入权限!", "파일에 쓰기 권한이 없습니다!") \ + X(TOAST_RELOAD_LIBRARY, "Reloaded library #{0}: {1}", "Se ha recargado biblioteca #{0}: {1}", "Библиотека #{0} перезагружена: {1}", "重新加载了库 #{0}: {1}", "{0}번 라이브러리 다시 불러옴: {1}") \ X(TOAST_RELOAD_SPRITESHEET, "Reloaded spritesheet #{0}: {1}", "Se ha recargado spritesheet #{0}: {1}", "Спрайт-лист #{0} перезагружен: {1}", "重新加载了图集 #{0}: {1}", "{0}번 스프라이트 시트 다시 불러옴: {1}") \ X(TOAST_RELOAD_SHADER, "Reloaded shader #{0}: {1}", "Reloaded shader #{0}: {1}", "Reloaded shader #{0}: {1}", "Reloaded shader #{0}: {1}", "Reloaded shader #{0}: {1}") \ X(TOAST_MERGE_SPRITESHEETS, "Merged selected spritesheets.", "Spritesheets seleccionados combinados.", "Выбранные спрайт-листы объединены.", "已合并所选图集。", "선택된 스프라이트 시트를 병합했습니다.") \ @@ -730,6 +763,8 @@ namespace anm2ed X(TOOLTIP_POSITION, "Change the position of the frame.", "Cambia la posicion del Frame.", "Изменить позицию кадра.", "更改此帧的位置.", "프레임의 위치를 변경합니다.") \ X(TOOLTIP_PREVIEW_ZOOM, "Change the zoom of the preview.", "Cambia el zoom de la vista previa.", "Изменить масштаб предпросмотра.", "更改预览视图的缩放.", "미리보기의 줌을 변경합니다.") \ X(TOOLTIP_PREVIEW_TRANSPARENT, "Toggle the animation preview background being transparent.", "Alterna la transparencia del fondo de la vista previa de animacion.", "Переключить прозрачность фона предпросмотра анимации.", "切换动画预览背景是否透明.", "애니메이션 미리보기 배경을 투명하게 전환합니다.") \ + X(TOOLTIP_RELOAD_LIBRARIES, "Reloads the selected libraries.", "Recarga las bibliotecas seleccionadas.", "Перезагружает выбранные библиотеки.", "重新加载所选库.", "선택한 라이브러리를 다시 불러옵니다.") \ + X(TOOLTIP_REMOVE_UNUSED_LIBRARIES, "Remove libraries no layer plays from.", "Elimina las bibliotecas que ninguna capa usa.", "Удалить библиотеки, которые не использует ни один слой.", "删除没有图层使用的库。", "어떤 레이어도 사용하지 않는 라이브러리를 제거합니다.") \ 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.") \ X(TOOLTIP_RENDER_FPS, "Set the exported animation frame rate.", "Set the exported animation frame rate.", "Set the exported animation frame rate.", "Set the exported animation frame rate.", "Set the exported animation frame rate.") \ diff --git a/src/selection.cpp b/src/selection.cpp index 53f946f..f887ae7 100644 --- a/src/selection.cpp +++ b/src/selection.cpp @@ -56,6 +56,7 @@ namespace anm2ed if (kind == SelectionKind::NULLS) add(content.nulls); if (kind == SelectionKind::EVENTS) add(content.events); if (kind == SelectionKind::SOUNDS) add(content.sounds); + if (kind == SelectionKind::LIBRARIES) add(content.libraries); if (kind == SelectionKind::REGIONS) if (auto spritesheet = model::item_get(content.spritesheets, selection_focus_id_get(selection, model, SelectionKind::SPRITESHEETS))) diff --git a/src/selection.hpp b/src/selection.hpp index e8829bb..e1a16bb 100644 --- a/src/selection.hpp +++ b/src/selection.hpp @@ -20,7 +20,8 @@ namespace anm2ed LAYERS, NULLS, EVENTS, - SOUNDS + SOUNDS, + LIBRARIES }; // What is selected, by element uid, plus the focused animation/track/frame. uids follow elements through edits, diff --git a/src/settings.cpp b/src/settings.cpp index a0b7c6f..96e28f2 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -104,6 +104,12 @@ Size=744,305 Collapsed=0 DockId=0x0000000F,0 +[Window][###Libraries] +Pos=1166,62 +Size=744,305 +Collapsed=0 +DockId=0x0000000F,2 + [Window][###Tools] Pos=8,62 Size=50,660 diff --git a/src/settings.hpp b/src/settings.hpp index debb7bd..4afc35b 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -25,7 +25,7 @@ namespace anm2ed constexpr auto OUTPUT_PATH_DEFAULT = "./output.gif"; #endif - constexpr auto AUTO_RELOAD_INTERVAL = 3.0f; // seconds between checks of spritesheet files + constexpr auto AUTO_RELOAD_INTERVAL = 3.0f; // seconds between checks of spritesheet and library files // Scales are percents. constexpr auto UI_SCALE_MIN = 50.0f; constexpr auto UI_SCALE_MAX = 200.0f; @@ -286,6 +286,7 @@ namespace anm2ed X(WINDOW_EVENTS, windowIsEvents, LABEL_EVENTS_WINDOW, BOOL, true) \ X(WINDOW_FRAME_PROPERTIES, windowIsFrameProperties, LABEL_FRAME_PROPERTIES_WINDOW, BOOL, true) \ X(WINDOW_LAYERS, windowIsLayers, LABEL_LAYERS_WINDOW, BOOL, true) \ + X(WINDOW_LIBRARIES, windowIsLibraries, LABEL_LIBRARIES_WINDOW, BOOL, true) \ X(WINDOW_NULLS, windowIsNulls, LABEL_NULLS_WINDOW, BOOL, true) \ X(WINDOW_ONIONSKIN, windowIsOnionskin, LABEL_ONIONSKIN_WINDOW, BOOL, true) \ X(WINDOW_PREVIEW, windowIsSpritesheets, LABEL_SPRITESHEETS_WINDOW, BOOL, true) \ diff --git a/src/util/imgui/input.cpp b/src/util/imgui/input.cpp index 46ceb56..0e68894 100644 --- a/src/util/imgui/input.cpp +++ b/src/util/imgui/input.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include @@ -42,6 +43,18 @@ namespace anm2ed::imgui return edited; } + // A combo over `values` shown as `labels`. + bool combo_string_mapped(const std::string& label, std::string* value, const std::vector& values, + const std::vector& labels) + { + std::vector ids(values.size()); + std::iota(ids.begin(), ids.end(), 0); + auto index = (int)std::distance(values.begin(), std::ranges::find(values, *value)); + if (!combo_id_mapped(label, &index, ids, labels) || index < 0) return false; + *value = values[index]; + return true; + } + bool combo_id_mapped(const std::string& label, int* id, const std::vector& ids, const std::vector& labelStrings) { diff --git a/src/util/imgui/input.hpp b/src/util/imgui/input.hpp index 4759b28..eec596f 100644 --- a/src/util/imgui/input.hpp +++ b/src/util/imgui/input.hpp @@ -31,4 +31,6 @@ namespace anm2ed::imgui types::edit_state::Type color_edit4_persistent(const char*, glm::vec4*, ImGuiColorEditFlags = 0); bool radio_button_icon(const char*, int*, int, ImTextureID, ImVec2, ImVec4 = ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); bool combo_id_mapped(const std::string&, int*, const std::vector&, const std::vector&); + bool combo_string_mapped(const std::string&, std::string*, const std::vector&, + const std::vector&); } diff --git a/tests/draw.cpp b/tests/draw.cpp index 0879ea2..0056fcb 100644 --- a/tests/draw.cpp +++ b/tests/draw.cpp @@ -57,3 +57,42 @@ TEST_CASE("a layer frame's depth moves it among the layers for that frame only") CHECK(model_load(text).frame_get({0, LAYER, 0, 0})->depth == -1); CHECK(model::isaac_issues_get(anm2).depthFrames == 1); } + +TEST_CASE("an animation layer draws its child animation, from this file or a library") +{ + auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); + auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); + model::DrawOptions options{.library_get = [&](const model::Model&, int id) { return id == 0 ? &spin : nullptr; }}; + auto red_position_get = [&](int layerId) + { + std::optional position{}; + for (const auto& draw : model::animation_draws_get(anm2, *anm2.animation_get(0), options)) + if (draw.type == model::DrawType::LAYER && draw.id == layerId && draw.frame.crop == glm::vec2()) + position = glm::vec2(draw.parent * glm::vec4(draw.frame.position, 0.0f, 1.0f)); + return position; + }; + + // The library's red square, half size at (40, 0), starts on its fifth frame (at x 16). + CHECK(red_position_get(0) == glm::vec2(48.0f, 0.0f)); + // This file's Inner holds its first frame however far the parent plays. + options.time = 1.0f; + CHECK(red_position_get(1) == glm::vec2(-40.0f, 0.0f)); + // An animation never draws inside itself. + CHECK_FALSE(red_position_get(3)); + + // Once stops on the child's last frame; Loop wraps around it. + options.time = 6.0f; + anm2.frame_edit({0, LAYER, 1, 0})->childMode = ChildMode::ONCE; + CHECK(red_position_get(1) == glm::vec2(-40.0f, 10.0f)); + anm2.frame_edit({0, LAYER, 1, 0})->childMode = ChildMode::LOOP; + CHECK(red_position_get(1) == glm::vec2(-40.0f, 0.0f)); + + // Without the library loaded, its layer draws nothing. + options.library_get = {}; + CHECK_FALSE(red_position_get(0)); + + auto text = model::model_to_string(anm2, {.isExtendedFormat = true}); + 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/render/golden/nested_frame_0.png b/tests/render/golden/nested_frame_0.png new file mode 100644 index 0000000000000000000000000000000000000000..c7d74e0458624bd9c16040d3728472e1c881b247 GIT binary patch literal 782 zcmeAS@N?(olHy`uVBq!ia0y~yVAKJ!4LI0<#n(I0;174NzMsdye($^fZ5n17O}Xq6l~9l76$H>da9)tp9Mtr zSj|cUE79O@^!}~oVbWsq6=Yl@fLK(8Pf zyybwDFEhj;iVklD5+r#q0Yini5lE~MII#5SlqbRTs#5^?x=*`WuVXkYboRC*|x#$ z@)d})fC&TUEO07;a&8DnycOzG`v=ja_b@{W65haoX=gZfC@^YWfNbwBn2|tt?`~O~ mnE?q7VDf+k2QW=BFvKiU2>!6quNIij89ZJ6T-G@yGywpI85^ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/render/render.cpp b/tests/render/render.cpp index fb63866..ac14443 100644 --- a/tests/render/render.cpp +++ b/tests/render/render.cpp @@ -132,3 +132,28 @@ TEST_CASE("a recorded spritesheet holds every frame") CHECK(sheet.size == glm::ivec2(fixture.canvas->size) * glm::ivec2(layout.columns, layout.rows)); golden_image_check("spin_sheet.png"); } + +TEST_CASE("animation layers draw their child animations") +{ + RenderFixture fixture("nested.anm2"); + if (!fixture.gl.is_valid()) + { + MESSAGE("skipped: no OpenGL context"); + return; + } + REQUIRE(fixture.document->is_valid()); + + // The library's red square at half size starts on its fifth frame, centered at (48, 0); this file's Inner holds its + // red square at (-40, 0). + auto pixels = fixture.frame_get(0.0f); + for (auto point : {glm::vec2(48.0f, 0.0f), glm::vec2(-40.0f, 0.0f)}) + { + auto red = fixture.pixel_get(pixels, point); + CHECK(red.r > 200); + CHECK(red.g < 80); + } + + REQUIRE(resource::Image::write_pixels_png(OUTPUT_DIR / "nested_frame_0.png", glm::ivec2(fixture.canvas->size), + pixels.data())); + golden_image_check("nested_frame_0.png"); +}