diff --git a/CMakeLists.txt b/CMakeLists.txt index db9fbe8..2dd9033 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -75,11 +75,9 @@ add_subdirectory(external/lunasvg) set(GLAD_SRC ${CMAKE_CURRENT_SOURCE_DIR}/include/glad/glad.cpp) +set(IMGUI_CORE_SRC external/imgui/imgui.cpp external/imgui/imgui_draw.cpp external/imgui/imgui_widgets.cpp + external/imgui/imgui_tables.cpp) set(IMGUI_SRC - external/imgui/imgui.cpp - external/imgui/imgui_draw.cpp - external/imgui/imgui_widgets.cpp - external/imgui/imgui_tables.cpp external/imgui/backends/imgui_impl_sdl3.cpp external/imgui/backends/imgui_impl_opengl3.cpp) @@ -110,9 +108,9 @@ file(GLOB PROJECT_SRC CONFIGURE_DEPENDS src/*.hpp) set(CORE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src) -file(GLOB CORE_SRC CONFIGURE_DEPENDS ${CORE_DIR}/anm2/*.cpp) +file(GLOB CORE_SRC CONFIGURE_DEPENDS ${CORE_DIR}/anm2/*.cpp ${CORE_DIR}/edit/*.cpp) foreach(CORE_FILE log resource/strings resource/image resource/audio_data util/file util/path util/math util/string util/time util/working_directory - util/xml util/pack) + util/xml util/pack util/imgui/multiselect snapshots storage playback) list(APPEND CORE_SRC ${CORE_DIR}/${CORE_FILE}.cpp) endforeach() list(REMOVE_ITEM PROJECT_SRC ${CORE_SRC}) @@ -129,8 +127,9 @@ set(CORE_INCLUDE_DIRS src/resource src/util) -add_library(anm2ed_core STATIC ${CORE_SRC} ${TINYXML2_SRC}) +add_library(anm2ed_core STATIC ${CORE_SRC} ${TINYXML2_SRC} ${IMGUI_CORE_SRC}) target_include_directories(anm2ed_core PUBLIC ${CORE_INCLUDE_DIRS}) +target_compile_definitions(anm2ed_core PUBLIC IMGUI_DISABLE_OBSOLETE_FUNCTIONS IMGUI_DEBUG_PARANOID IMGUI_ENABLE_DOCKING) if(NOT MSVC) target_compile_options(anm2ed_core PRIVATE -Wall -Wextra -Wpedantic) endif() @@ -144,8 +143,6 @@ set_target_properties( RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_BINARY_DIR}/bin" RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_BINARY_DIR}/bin") -target_compile_definitions(${PROJECT_NAME} PRIVATE IMGUI_DISABLE_OBSOLETE_FUNCTIONS IMGUI_DEBUG_PARANOID - IMGUI_ENABLE_DOCKING) target_include_directories( ${PROJECT_NAME} diff --git a/src/anm2/anm2.hpp b/src/anm2/anm2.hpp index a60f957..9fefb5f 100644 --- a/src/anm2/anm2.hpp +++ b/src/anm2/anm2.hpp @@ -597,5 +597,6 @@ namespace anm2ed public: explicit UidIndex(const Anm2&); std::optional reference_get(Handle, Reference) const; + std::optional reference_get(std::uint64_t) const; }; } diff --git a/src/anm2/handle.cpp b/src/anm2/handle.cpp index dff5387..08ad944 100644 --- a/src/anm2/handle.cpp +++ b/src/anm2/handle.cpp @@ -92,6 +92,12 @@ namespace anm2ed } } + std::optional UidIndex::reference_get(std::uint64_t uid) const + { + auto it = locations.find(uid); + return it == locations.end() ? std::nullopt : std::optional(it->second); + } + std::optional UidIndex::reference_get(Handle handle, Reference reference) const { auto location_get = [&](std::uint64_t uid) -> const Reference* diff --git a/src/document.cpp b/src/document.cpp index a5f3699..eb20e34 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -731,6 +731,25 @@ namespace anm2ed snapshots.commit(); } + void Document::edit_begin(StringType label, bool isTextures) { snapshots.push(localize.get(label), isTextures); } + + edit::Uids Document::edit_run(StringType label, ChangeType type, const std::function& operation) + { + edit_begin(label); + auto uids = operation(anm2); + change(type); + return uids; + } + + std::vector Document::references_get(const edit::Uids& uids) const + { + UidIndex index(anm2); + std::vector references{}; + for (auto uid : uids) + if (auto reference = index.reference_get(uid)) references.push_back(*reference); + return references; + } + bool Document::is_dirty() const { return hash != saveHash; } bool Document::is_autosave_dirty() const { return hash != autosaveHash; } @@ -916,7 +935,7 @@ namespace anm2ed } if (loaded.empty()) return; - snapshots.anm2_push(localize.get(EDIT_ADD_SPRITESHEET)); + edit_begin(EDIT_ADD_SPRITESHEET); std::set added{}; for (auto& [relativePath, texture] : loaded) @@ -940,7 +959,7 @@ namespace anm2ed auto items = anm2.element_get(ElementType::SOUNDS); if (!items || std::ranges::all_of(paths, [](const auto& path) { return path.empty(); })) return; - snapshots.anm2_push(localize.get(EDIT_ADD_SOUND)); + edit_begin(EDIT_ADD_SOUND); std::set added{}; for (auto& path : paths) diff --git a/src/document.hpp b/src/document.hpp index 1eaebbd..22eef0f 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -2,12 +2,16 @@ #include #include +#include #include #include +#include #include #include +#include "edit/edit.hpp" #include "snapshots.hpp" +#include "strings.hpp" #include @@ -117,6 +121,25 @@ namespace anm2ed void hash_set(); void clean(); void change(ChangeType); + void edit_begin(StringType, bool = false); + edit::Uids edit_run(StringType, ChangeType, const std::function&); + + // Snapshots for undo, runs the operation on the model, then commits; void operations select nothing. + template edit::Uids edit_apply(StringType label, ChangeType type, Operation&& operation) + { + return edit_run(label, type, + [&](Anm2& anm2) -> edit::Uids + { + if constexpr (std::is_void_v>) + { + operation(anm2); + return {}; + } + else + return operation(anm2); + }); + } + std::vector references_get(const edit::Uids&) const; bool is_dirty() const; bool is_autosave_dirty() const; std::filesystem::path directory_get() const; diff --git a/src/edit/animations.cpp b/src/edit/animations.cpp new file mode 100644 index 0000000..c4ef6a8 --- /dev/null +++ b/src/edit/animations.cpp @@ -0,0 +1,182 @@ +#include "edit.hpp" + +#include "vector.hpp" + +namespace anm2ed::edit +{ + std::set animation_group_ids_get(const Element& animations) + { + std::set result{}; + for (const auto& item : animations.children) + if (item.type == ElementType::GROUP) result.insert(item.id); + return result; + } + + std::set animation_group_indices_get(const Element& animations, int groupId) + { + std::set result{}; + int animationIndex{}; + for (const auto& animation : animations.children) + if (animation.type == ElementType::ANIMATION) + { + if (animation.groupId == groupId) result.insert(animationIndex); + ++animationIndex; + } + return result; + } + + // An empty copy of a track container: same tracks and groups, no frames. + Element track_container_shell_copy(const Element* source, const TrackContainer& row) + { + auto destination = element_make(row.container); + if (!source) return destination; + + auto nextGroupId = element_child_next_id_get(*source, ElementType::GROUP); + std::set copiedTrackIds{}; + auto track_push = [&](const Element& track, int groupId) + { + if (track.type != row.track || !copiedTrackIds.insert(track_id_get(track)).second) return; + auto item = element_make(row.track); + item.*(row.id) = track.*(row.id); + item.groupId = track.groupId != -1 ? track.groupId : groupId; + item.isVisible = track.isVisible; + destination.children.push_back(item); + }; + + for (const auto& sourceItem : source->children) + { + if (sourceItem.type != ElementType::GROUP) + { + track_push(sourceItem, -1); + continue; + } + auto group = element_make(ElementType::GROUP); + group.id = sourceItem.id >= 0 ? sourceItem.id : nextGroupId++; + group.name = sourceItem.name; + group.isExpanded = sourceItem.isExpanded; + group.isVisible = sourceItem.isVisible; + group.children.push_back(root_animation_make()); + destination.children.push_back(group); + for (const auto& child : sourceItem.children) + track_push(child, group.id); + } + return destination; + } + + // Adds an animation with the same (empty) tracks as the template animation. + Uids animation_add(Anm2& anm2, int index, int groupId, int templateIndex, const std::string& name) + { + auto animations = anm2.element_get(ElementType::ANIMATIONS); + if (!animations) return {}; + + auto animation = element_make(ElementType::ANIMATION); + animation.name = name; + animation.groupId = groupId; + animation.children.push_back(root_animation_make()); + auto templateAnimation = anm2.element_get(ElementType::ANIMATION, templateIndex); + for (const auto& row : TRACK_CONTAINERS) + animation.children.push_back(track_container_shell_copy( + templateAnimation ? child_first_get(*templateAnimation, row.container) : nullptr, row)); + animation.children.push_back(element_make(ElementType::TRIGGERS)); + animation = element_clone(animation); + + if (animations_count_get(*animations) == 0) animations->defaultAnimation = animation.name; + animations->children.insert(animations->children.begin() + animations_child_insert_index_get(*animations, index), + animation); + return {animation.uid}; + } + + Uids animations_remove(Anm2& anm2, const std::set& indices, const std::set& groupIds) + { + auto animations = anm2.element_get(ElementType::ANIMATIONS); + if (!animations) return {}; + animation_groups_remove(*animations, groupIds); + for (auto it = indices.rbegin(); it != indices.rend(); ++it) + if (auto childIndex = animations_child_index_get(*animations, *it); childIndex != -1) + animations->children.erase(animations->children.begin() + childIndex); + return {}; + } + + void animation_groups_remove(Element& animations, const std::set& groupIds) + { + for (auto& item : animations.children) + if (item.type == ElementType::ANIMATION && groupIds.contains(item.groupId)) item.groupId = -1; + std::erase_if(animations.children, + [&](const Element& item) { return item.type == ElementType::GROUP && groupIds.contains(item.id); }); + } + + // Moves animations and whole groups to a child position; animations moved on their own join targetGroupId. + Uids animations_move(Anm2& anm2, const std::set& indices, const std::set& groupIds, int targetChildIndex, + int targetGroupId) + { + auto animations = anm2.element_get(ElementType::ANIMATIONS); + if (!animations) return {}; + auto existingGroupIds = animation_group_ids_get(*animations); + auto groupId = existingGroupIds.contains(targetGroupId) ? targetGroupId : -1; + + Uids uids{}; + std::vector childIndices{}; + int animationIndex{}; + for (int i = 0; i < (int)animations->children.size(); ++i) + { + auto& item = animations->children[i]; + if (item.type == ElementType::GROUP && groupIds.contains(item.id)) childIndices.push_back(i); + if (item.type != ElementType::ANIMATION) continue; + auto isGroupMoved = groupIds.contains(item.groupId); + auto isMoved = indices.contains(animationIndex++); + if (isMoved && !isGroupMoved) + { + item.groupId = groupId; + uids.push_back(item.uid); + } + if (isGroupMoved || isMoved) childIndices.push_back(i); + } + + util::vector::move_indices_to_position(animations->children, childIndices, targetChildIndex); + return uids; + } + + Uids animations_group(Anm2& anm2, const std::set& indices, const std::string& name) + { + auto animations = anm2.element_get(ElementType::ANIMATIONS); + if (!animations || indices.empty()) return {}; + + auto group = element_make(ElementType::GROUP); + group.id = element_child_next_id_get(*animations, ElementType::GROUP); + group.name = name; + for (auto index : indices) + if (auto animation = anm2.element_get(ElementType::ANIMATION, index)) animation->groupId = group.id; + animations->children.insert( + animations->children.begin() + animations_child_index_get(*animations, *indices.begin()), group); + return {}; + } + + Uids animations_paste(Anm2& anm2, const std::string& text, int start, int targetGroupId, std::set& groupIds, + std::string* errorString) + { + std::set indices{}; + if (!anm2.animations_deserialize(text, start, indices, errorString, &groupIds)) return {}; + anm2.uids_repair(); + + Uids uids{}; + for (auto index : indices) + if (auto animation = anm2.element_get(ElementType::ANIMATION, index)) + { + if (targetGroupId != -1 && groupIds.empty()) animation->groupId = targetGroupId; + uids.push_back(animation->uid); + } + return uids; + } + + Uids animations_merge(Anm2& anm2, int target, std::set sources, types::merge::Type type, bool isDeleteAfter, + const std::set& ungroupIds) + { + auto merged = sources.size() > 1 || !sources.contains(target) + ? anm2.animations_merge(target, sources, type, isDeleteAfter) + : target; + if (merged == -1) return {}; + if (auto animations = anm2.element_get(ElementType::ANIMATIONS)) animation_groups_remove(*animations, ungroupIds); + auto animation = anm2.element_get(ElementType::ANIMATION, merged); + return animation ? Uids{animation->uid} : Uids{}; + } +} diff --git a/src/edit/content.cpp b/src/edit/content.cpp new file mode 100644 index 0000000..91af55d --- /dev/null +++ b/src/edit/content.cpp @@ -0,0 +1,127 @@ +#include "edit.hpp" + +#include "vector.hpp" + +namespace anm2ed +{ + std::string region_name_get(const std::string&, int); +} + +namespace anm2ed::edit +{ + // Clears frame references to the spritesheet's unused regions, then removes them. + Uids regions_remove_unused(Anm2& anm2, int spritesheetId) + { + auto unused = anm2.region_unused(spritesheetId); + auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetId); + if (unused.empty() || !spritesheet) return {}; + + animations_tracks_each(anm2.root, ElementType::LAYER_ANIMATION, + [&](Element& track) + { + auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, track.layerId); + if (!layer || layer->spritesheetId != spritesheetId) return; + for (auto& frame : track.children) + if (frame.type == ElementType::FRAME && unused.contains(frame.regionId)) + frame.regionId = -1; + }); + for (auto id : unused) + element_child_id_erase(*spritesheet, ElementType::REGION, id); + return {}; + } + + // Pastes regions into a spritesheet at a child position; they get fresh ids after the existing ones. + Uids regions_paste(Anm2& anm2, int spritesheetId, const std::string& text, int insertIndex, std::string* errorString) + { + auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetId); + if (!spritesheet) return {}; + auto maxId = element_child_max_id_get(*spritesheet, ElementType::REGION); + if (!anm2.deserialize(ElementType::REGION, text, true, errorString, {}, spritesheetId)) return {}; + + spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetId); + std::vector pasted{}; + for (int i = 0; i < (int)spritesheet->children.size(); i++) + if (spritesheet->children[i].type == ElementType::REGION && spritesheet->children[i].id > maxId) + pasted.push_back(i); + util::vector::move_indices_to_position(spritesheet->children, pasted, insertIndex); + return {}; + } + + // Appends grid frames to each layer track (optionally making a region per frame) and fits the animation length. + Uids animation_grid_generate(Anm2& anm2, const std::vector& tracks, const GridOptions& options) + { + Uids uids{}; + for (auto reference : tracks) + { + auto track = anm2.element_get(reference); + auto animation = anm2.element_get(ElementType::ANIMATION, reference.animationIndex); + auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, reference.itemID); + auto spritesheet = layer ? anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; + if (!track || !animation) continue; + + auto start = (int)track->children.size(); + frames_generate_from_grid(*track, options.start, options.size, options.pivot, options.columns, options.count, + options.delay); + for (int i = start; i < (int)track->children.size(); ++i) + { + auto& frame = track->children[i]; + if (frame.type != ElementType::FRAME) continue; + if (!options.isMakeRegions || !spritesheet) continue; + + auto region = element_make(ElementType::REGION); + region.id = element_child_next_id_get(*spritesheet, ElementType::REGION); + region.name = region_name_get(options.regionNameFormat, i - start); + region.crop = frame.crop; + region.size = frame.size; + region.pivot = frame.pivot; + frame.regionId = region.id; + spritesheet->children.push_back(region); + } + animation->frameNum = animation_length_get(*animation); + + anm2.uids_repair(); + for (int i = start; i < (int)track->children.size(); ++i) + uids.push_back(track->children[i].uid); + } + return uids; + } + + // Applies a frame change to explicit frames, to whole tracks (frameIndex -1), and to every matching track of the + // given animations. + Uids frames_change_apply(Anm2& anm2, const ChangeTargets& targets, FrameChange change, ChangeType type) + { + std::map> frames{}; + std::set wholeTracks{}; + for (auto reference : targets.references) + { + auto index = std::exchange(reference.frameIndex, -1); + index < 0 ? (void)wholeTracks.insert(reference) : (void)frames[reference].insert(index); + } + + auto whole_apply = [&](Element* track, ItemType itemType) + { + if (!track) return; + std::set indices{}; + for (int i = 0; i < track_frames_count_get(*track); ++i) + indices.insert(i); + frames_change(*track, change, itemType, type, indices); + }; + + for (auto& [reference, indices] : frames) + if (auto track = anm2.element_get(reference)) + frames_change(*track, change, (ItemType)reference.itemType, type, indices); + for (auto reference : wholeTracks) + whole_apply(anm2.element_get(reference), (ItemType)reference.itemType); + for (auto animationIndex : targets.animations) + { + auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex); + if (!animation) continue; + if (targets.isRoot) whole_apply(animation_item_get(*animation, ItemType::ROOT), ItemType::ROOT); + for (const auto& row : TRACK_CONTAINERS) + if (auto container = child_first_get(*animation, row.container); + container && (row.itemType == ItemType::LAYER ? targets.isLayers : targets.isNulls)) + tracks_each(*container, row.track, [&](Element& track) { whole_apply(&track, row.itemType); }); + } + return {}; + } +} diff --git a/src/edit/edit.hpp b/src/edit/edit.hpp new file mode 100644 index 0000000..8d98a75 --- /dev/null +++ b/src/edit/edit.hpp @@ -0,0 +1,89 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "anm2/anm2.hpp" + +// Document edits as plain functions of the model. Each returns the uids of the elements it created or changed that +// the caller may want to select (the first one is the focus); selection itself stays with the UI. +namespace anm2ed::edit +{ + using Uids = std::vector; + + struct RowTarget + { + bool isGroup{}; + int type{NONE}; + int id{-1}; + int groupId{-1}; + }; + + struct RootBakeOptions + { + bool isRoundScale{}; + bool isRoundRotation{}; + bool isMatchRootInterpolation{}; + bool isUseRootPivot{}; + }; + + struct GridOptions + { + glm::ivec2 start{}; + glm::ivec2 size{}; + glm::vec2 pivot{}; + int columns{}; + int count{}; + int delay{}; + bool isMakeRegions{}; + std::string regionNameFormat{}; + }; + + struct ChangeTargets + { + std::set references{}; + std::set animations{}; + bool isRoot{}; + bool isLayers{}; + bool isNulls{}; + }; + + Element element_clone(Element); + Element* track_get(Anm2&, Reference); + std::map> frames_by_track_get(const std::set&); + + Uids frame_insert(Anm2&, Reference, int); + Uids frames_delete(Anm2&, const std::set&); + Uids frames_duplicate(Anm2&, const std::set&, Reference); + Uids frames_reverse(Anm2&, const std::set&); + Uids frames_bake(Anm2&, const std::set&, int, bool, bool); + Uids frame_split(Anm2&, Reference, int); + Uids frames_move(Anm2&, const std::set&, Reference, int); + Uids frame_durations_set(Anm2&, const std::map&); + Uids trigger_at_frame_set(Anm2&, Reference, int); + Uids frames_paste(Anm2&, Reference, const std::set&, const std::string&, int, std::string*); + Uids root_bake_into(Anm2&, const std::set&, const std::set&, RootBakeOptions); + void frame_root_transform_apply(Element&, const Element&, bool, bool, bool); + + Uids items_remove(Anm2&, int, const std::map>&, const std::map>&); + Uids items_group(Anm2&, int, int, const std::set&, const std::string&); + Uids items_move(Anm2&, int, int, const std::set&, const std::set&, RowTarget, bool, bool); + Uids animation_length_fit(Anm2&, int); + + std::set animation_group_ids_get(const Element&); + std::set animation_group_indices_get(const Element&, int); + void animation_groups_remove(Element&, const std::set&); + Uids animation_add(Anm2&, int, int, int, const std::string&); + Uids animations_remove(Anm2&, const std::set&, const std::set&); + Uids animations_move(Anm2&, const std::set&, const std::set&, int, int); + Uids animations_group(Anm2&, const std::set&, const std::string&); + Uids animations_paste(Anm2&, const std::string&, int, int, std::set&, std::string*); + Uids regions_remove_unused(Anm2&, int); + Uids regions_paste(Anm2&, int, const std::string&, int, std::string*); + Uids animation_grid_generate(Anm2&, const std::vector&, const GridOptions&); + Uids frames_change_apply(Anm2&, const ChangeTargets&, FrameChange, ChangeType); + Uids animations_merge(Anm2&, int, std::set, types::merge::Type, bool, const std::set&); +} diff --git a/src/edit/frames.cpp b/src/edit/frames.cpp new file mode 100644 index 0000000..8b11066 --- /dev/null +++ b/src/edit/frames.cpp @@ -0,0 +1,376 @@ +#include "edit.hpp" + +#include + +#include "math.hpp" +#include "uid.hpp" + +using namespace anm2ed::util; + +namespace anm2ed::edit +{ + Element element_clone(Element element) + { + element_each(element, [](Element& child) { child.uid = uid_next(); }); + return element; + } + + Element* track_get(Anm2& anm2, Reference reference) + { + reference.frameIndex = -1; + return anm2.element_get(reference); + } + + std::map> frames_by_track_get(const std::set& frames) + { + std::map> result{}; + for (auto frame : frames) + { + auto index = std::exchange(frame.frameIndex, -1); + result[frame].insert(index); + } + return result; + } + + Uids frames_uids_get(const Element& track, int start, int count) + { + Uids uids{}; + for (int i = start; i < start + count; ++i) + if (auto frame = track_frame_get(track, i)) uids.push_back(frame->uid); + return uids; + } + + Uids frame_insert(Anm2& anm2, Reference reference, int time) + { + auto track = track_get(anm2, reference); + if (!track) return {}; + + if (reference.itemType == TRIGGER) + { + if (std::ranges::any_of(track->children, [&](const Element& trigger) { return trigger.atFrame == time; })) + return {}; + auto trigger = element_clone(element_make(ElementType::TRIGGER)); + trigger.atFrame = time; + track->children.push_back(trigger); + frames_sort_by_at_frame(*track); + return {trigger.uid}; + } + + auto count = track_frames_count_get(*track); + auto source = track_frame_get(*track, reference.frameIndex); + auto last = track_frame_get(*track, count - 1); + auto frame = element_clone(source ? *source : last ? *last : element_make(ElementType::FRAME)); + auto index = source ? std::clamp(reference.frameIndex + 1, 0, count) : count; + track->children.insert(track->children.begin() + track_frame_insert_child_index_get(*track, index), frame); + return {frame.uid}; + } + + Uids frames_delete(Anm2& anm2, const std::set& frames) + { + for (auto& [trackReference, indices] : frames_by_track_get(frames)) + if (auto track = track_get(anm2, trackReference)) + for (auto it = indices.rbegin(); it != indices.rend(); ++it) + if (auto childIndex = track_frame_child_index_get(*track, *it); childIndex != -1) + track->children.erase(track->children.begin() + childIndex); + return {}; + } + + Uids frames_duplicate(Anm2& anm2, const std::set& frames, Reference focus) + { + Uids uids{}; + std::uint64_t focusUid{}; + for (auto& [trackReference, indices] : frames_by_track_get(frames)) + { + auto track = track_get(anm2, trackReference); + if (!track) continue; + + std::vector copies{}; + int lastIndex{-1}; + for (auto index : indices) + if (auto frame = track_frame_get(*track, index)) + { + copies.push_back(element_clone(*frame)); + lastIndex = index; + if (trackReference.animationIndex == focus.animationIndex && index == focus.frameIndex && + track_get(anm2, focus) == track) + focusUid = copies.back().uid; + } + if (copies.empty()) continue; + + for (const auto& copy : copies) + uids.push_back(copy.uid); + auto childIndex = track_frame_insert_child_index_get(*track, lastIndex + 1); + track->children.insert(track->children.begin() + childIndex, copies.begin(), copies.end()); + } + + if (auto it = std::ranges::find(uids, focusUid); focusUid && it != uids.end()) + std::rotate(uids.begin(), it, it + 1); + return uids; + } + + Uids frames_reverse(Anm2& anm2, const std::set& frames) + { + for (auto& [trackReference, indices] : frames_by_track_get(frames)) + { + auto track = track_get(anm2, trackReference); + if (!track || indices.size() < 2) continue; + + std::vector reversed{}; + for (auto it = indices.rbegin(); it != indices.rend(); ++it) + if (auto childIndex = track_frame_child_index_get(*track, *it); childIndex != -1) + { + reversed.push_back(std::move(track->children[childIndex])); + track->children.erase(track->children.begin() + childIndex); + } + auto childIndex = track_frame_insert_child_index_get(*track, *indices.begin()); + track->children.insert(track->children.begin() + childIndex, reversed.begin(), reversed.end()); + } + return {}; + } + + Uids frames_bake(Anm2& anm2, const std::set& frames, int interval, bool isRoundScale, bool isRoundRotation) + { + Uids uids{}; + for (auto& [trackReference, indices] : frames_by_track_get(frames)) + { + auto track = track_get(anm2, trackReference); + if (!track) continue; + + int inserted{}; + for (auto originalIndex : indices) + { + auto index = originalIndex + inserted; + auto frame = track_frame_get(*track, index); + if (!frame) continue; + + auto count = frame->duration <= FRAME_DURATION_MIN ? 1 : (int)std::ceil((float)frame->duration / interval); + frame_bake(*track, index, interval, isRoundScale, isRoundRotation); + anm2.uids_repair(); + uids.append_range(frames_uids_get(*track, index, count)); + inserted += count - 1; + } + } + return uids; + } + + Uids frame_split(Anm2& anm2, Reference reference, int time) + { + auto track = reference.itemType == TRIGGER ? nullptr : track_get(anm2, reference); + auto frame = track ? track_frame_get(*track, reference.frameIndex) : nullptr; + if (!frame || frame->duration <= 1) return {}; + + auto duration = frame->duration; + auto firstDuration = time - (int)std::round(frame_time_from_index_get(*track, reference.frameIndex)) + 1; + if (firstDuration <= 0 || firstDuration >= duration) return {}; + + auto split = element_clone(*frame); + split.duration = duration - firstDuration; + if (auto next = track_frame_get(*track, reference.frameIndex + 1); + next && frame->interpolation != Interpolation::NONE) + frame_mix(split, *next, interpolation_factor(frame->interpolation, (float)firstDuration / (float)duration)); + + frame->duration = firstDuration; + auto uid = frame->uid; + track->children.insert( + track->children.begin() + track_frame_insert_child_index_get(*track, reference.frameIndex + 1), split); + return {uid}; + } + + // Moves frames (from any tracks) into one track before the frame at the given index. + Uids frames_move(Anm2& anm2, const std::set& frames, Reference target, int insertIndex) + { + auto targetTrack = track_get(anm2, target); + if (!targetTrack) return {}; + insertIndex = std::clamp(insertIndex, 0, track_frames_count_get(*targetTrack)); + target.frameIndex = -1; + + std::vector moved{}; + for (auto& [trackReference, indices] : frames_by_track_get(frames)) + { + auto track = track_get(anm2, trackReference); + if (!track) continue; + std::vector trackMoved{}; + for (auto it = indices.rbegin(); it != indices.rend(); ++it) + if (auto childIndex = track_frame_child_index_get(*track, *it); childIndex != -1) + { + trackMoved.insert(trackMoved.begin(), std::move(track->children[childIndex])); + track->children.erase(track->children.begin() + childIndex); + if (track == targetTrack && *it < insertIndex) --insertIndex; + } + moved.append_range(trackMoved); + } + if (moved.empty()) return {}; + + insertIndex = std::clamp(insertIndex, 0, track_frames_count_get(*targetTrack)); + auto childIndex = track_frame_insert_child_index_get(*targetTrack, insertIndex); + targetTrack->children.insert(targetTrack->children.begin() + childIndex, moved.begin(), moved.end()); + return frames_uids_get(*targetTrack, insertIndex, (int)moved.size()); + } + + Uids frame_durations_set(Anm2& anm2, const std::map& durations) + { + for (auto [reference, duration] : durations) + if (auto frame = anm2.element_get(reference)) + frame->duration = std::clamp(duration, FRAME_DURATION_MIN, FRAME_DURATION_MAX); + return {}; + } + + // Places a trigger at a frame, stepping it back past any other trigger already there. + Uids trigger_at_frame_set(Anm2& anm2, Reference reference, int atFrame) + { + auto track = track_get(anm2, reference); + auto trigger = track ? track_frame_get(*track, reference.frameIndex) : nullptr; + if (!trigger) return {}; + trigger->atFrame = atFrame; + for (const auto& other : track->children) + if (&other != trigger && other.atFrame == trigger->atFrame) trigger->atFrame--; + return {}; + } + + Uids frames_paste(Anm2& anm2, Reference reference, const std::set& selection, const std::string& text, + int time, std::string* errorString) + { + auto track = track_get(anm2, reference); + if (!track) return {}; + + auto trackReference = reference; + trackReference.frameIndex = -1; + auto selected = frames_by_track_get(selection); + auto count = (int)track->children.size(); + auto insertIndex = count; + if (auto it = selected.find(trackReference); it != selected.end() && !it->second.empty()) + insertIndex = std::min(count, *it->second.rbegin() + 1); + else if (reference.frameIndex >= 0 && reference.frameIndex < count) + insertIndex = reference.frameIndex + 1; + + std::set indices{}; + if (!frames_deserialize(*track, text, reference.itemType == TRIGGER ? time : insertIndex, indices, errorString)) + return {}; + + auto layer = reference.itemType == LAYER ? anm2.element_get(ElementType::LAYER_ELEMENT, reference.itemID) : nullptr; + auto spritesheet = layer ? anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; + for (auto index : indices) + { + auto frame = track_frame_get(*track, index); + if (!frame) continue; + if (reference.itemType != LAYER) + { + frame->regionId = -1; + frame->crop = frame->size = frame->pivot = {}; + } + else if (frame->regionId != -1 && + (!spritesheet || !child_id_get(*spritesheet, ElementType::REGION, frame->regionId))) + frame->regionId = -1; + } + + anm2.uids_repair(); + Uids uids{}; + for (auto index : indices) + uids.append_range(frames_uids_get(*track, index, 1)); + return uids; + } + + void frame_root_transform_apply(Element& frame, const Element& rootFrame, bool isRoundScale, bool isRoundRotation, + bool isUseRootPivot) + { + auto rootScale = math::percent_to_unit(rootFrame.scale); + auto pivot = isUseRootPivot ? rootFrame.position : glm::vec2(); + auto offset = (frame.position - pivot) * rootScale; + auto radians = glm::radians(rootFrame.rotation); + auto cos = std::cos(radians); + auto sin = std::sin(radians); + + frame.position = rootFrame.position + glm::vec2(offset.x * cos - offset.y * sin, offset.x * sin + offset.y * cos); + frame.scale *= rootScale; + frame.rotation += rootFrame.rotation; + frame.tint *= rootFrame.tint; + frame.colorOffset += rootFrame.colorOffset; + + if (isRoundScale) frame.scale = glm::round(frame.scale); + if (isRoundRotation) frame.rotation = std::round(frame.rotation); + } + + // Applies the selected root frames' transforms to the target tracks' frames under them, then resets those root + // frames to a default frame spanning the same time. + Uids root_bake_into(Anm2& anm2, const std::set& rootFrames, const std::set& targets, + RootBakeOptions options) + { + auto byTrack = frames_by_track_get(rootFrames); + if (byTrack.size() != 1 || targets.empty()) return {}; + auto& [rootReference, rootIndices] = *byTrack.begin(); + auto root = track_get(anm2, rootReference); + if (!root) return {}; + + std::vector> spans{}; + for (auto index : rootIndices) + if (auto frame = track_frame_get(*root, index)) + { + auto start = (int)frame_time_from_index_get(*root, index); + spans.emplace_back(start, start + frame->duration); + } + if (spans.empty()) return {}; + auto is_spanned = [&](int time) + { return std::ranges::any_of(spans, [&](auto span) { return time >= span.first && time < span.second; }); }; + + for (auto target : targets) + { + auto track = track_get(anm2, target); + if (!track) continue; + auto frameType = track_frame_type_get(*track); + + if (options.isMatchRootInterpolation) + { + std::vector bakeIndices{}; + int frameIndex{}; + for (const auto& frame : track->children) + if (frame.type == frameType) + { + if (is_spanned((int)frame_time_from_index_get(*track, frameIndex))) bakeIndices.push_back(frameIndex); + ++frameIndex; + } + for (auto it = bakeIndices.rbegin(); it != bakeIndices.rend(); ++it) + frame_bake(*track, *it, FRAME_DURATION_MIN, options.isRoundScale, options.isRoundRotation); + } + + int frameIndex{}; + for (auto& frame : track->children) + { + if (frame.type != frameType) continue; + auto start = (int)frame_time_from_index_get(*track, frameIndex++); + if (is_spanned(start)) + frame_root_transform_apply(frame, frame_generate(*root, (float)start), options.isRoundScale, + options.isRoundRotation, options.isUseRootPivot); + } + } + + Uids uids{}; + std::vector rewritten{}; + int frameIndex{}; + int defaultDuration{}; + auto default_push = [&]() + { + if (defaultDuration <= 0) return; + auto frame = element_clone(element_make(ElementType::FRAME)); + frame.duration = std::max(defaultDuration, FRAME_DURATION_MIN); + uids.push_back(frame.uid); + rewritten.push_back(frame); + defaultDuration = 0; + }; + + for (const auto& frame : root->children) + { + if (frame.type == ElementType::FRAME && rootIndices.contains(frameIndex++)) + { + defaultDuration += frame.duration; + continue; + } + default_push(); + rewritten.push_back(frame); + } + default_push(); + + root->children = std::move(rewritten); + anm2.uids_repair(); + return uids; + } +} diff --git a/src/edit/tracks.cpp b/src/edit/tracks.cpp new file mode 100644 index 0000000..2742630 --- /dev/null +++ b/src/edit/tracks.cpp @@ -0,0 +1,118 @@ +#include "edit.hpp" + +namespace anm2ed::edit +{ + Element* track_container_get(Anm2& anm2, int animationIndex, int type) + { + auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex); + return animation ? child_first_get(*animation, TYPE_CONTAINERS[type]) : nullptr; + } + + Uids items_remove(Anm2& anm2, int animationIndex, const std::map>& ids, + const std::map>& groupIds) + { + for (auto type : {LAYER, NULL_}) + { + auto container = track_container_get(anm2, animationIndex, type); + if (!container) continue; + auto typeIds = ids.contains(type) ? ids.at(type) : std::set{}; + auto typeGroupIds = groupIds.contains(type) ? groupIds.at(type) : std::set{}; + std::erase_if(container->children, + [&](const Element& item) + { + if (item.type == ElementType::GROUP) return typeGroupIds.contains(item.id); + return item.type == TYPE_TRACKS[type] && + (typeIds.contains(track_id_get(item)) || typeGroupIds.contains(item.groupId)); + }); + } + return {}; + } + + Uids items_group(Anm2& anm2, int animationIndex, int type, const std::set& ids, const std::string& name) + { + auto container = track_container_get(anm2, animationIndex, type); + if (!container) return {}; + + auto group = element_clone(element_make(ElementType::GROUP)); + group.id = element_child_next_id_get(*container, ElementType::GROUP); + group.name = name; + group.children.push_back(element_clone(root_animation_make())); + + auto insertIndex = (int)container->children.size(); + for (int i = 0; i < (int)container->children.size(); ++i) + { + auto& item = container->children[i]; + if (item.type != TYPE_TRACKS[type] || !ids.contains(track_id_get(item))) continue; + insertIndex = std::min(insertIndex, i); + item.groupId = group.id; + } + if (insertIndex == (int)container->children.size()) return {}; + + container->children.insert(container->children.begin() + insertIndex, group); + return {group.uid}; + } + + // Moves tracks and whole groups next to (or into) a target row. Layers list top-down in reverse of nulls, so the + // drop side flips for them. + Uids items_move(Anm2& anm2, int animationIndex, int type, const std::set& ids, const std::set& groupIds, + RowTarget target, bool isDropAfter, bool isDropIntoGroup) + { + auto container = track_container_get(anm2, animationIndex, type); + if (!container) return {}; + if (target.groupId != -1 && groupIds.contains(target.groupId)) return {}; + if (target.isGroup && groupIds.contains(target.id)) return {}; + + auto trackType = TYPE_TRACKS[type]; + auto& children = container->children; + auto is_moved = [&](const Element& item) + { + return (item.type == ElementType::GROUP && groupIds.contains(item.id)) || + (item.type == trackType && (ids.contains(track_id_get(item)) || groupIds.contains(item.groupId))); + }; + std::vector moved{}; + std::ranges::copy_if(children, std::back_inserter(moved), is_moved); + if (moved.empty()) return {}; + + auto targetIndex = (int)children.size(); + if (target.isGroup || target.type == type) + { + auto rowIndex = -1; + auto groupEndIndex = -1; + for (int i = 0; i < (int)children.size(); ++i) + { + auto& item = children[i]; + auto isGroupRow = item.type == ElementType::GROUP && item.id == target.id; + if ((target.isGroup && isGroupRow) || + (!target.isGroup && item.type == trackType && track_id_get(item) == target.id)) + if (rowIndex == -1) rowIndex = i; + if (isGroupRow || (item.type == trackType && item.groupId == target.id)) groupEndIndex = i; + } + if (rowIndex == -1) return {}; + if (target.isGroup) + targetIndex = type == LAYER ? (isDropAfter ? rowIndex : groupEndIndex + 1) : rowIndex + isDropAfter; + else + targetIndex = rowIndex + (type == LAYER ? !isDropAfter : isDropAfter); + } + + for (int i = (int)children.size() - 1; i >= 0; --i) + if (is_moved(children[i])) + { + if (i < targetIndex) --targetIndex; + children.erase(children.begin() + i); + } + + auto targetGroupId = target.isGroup && isDropIntoGroup ? target.id : target.type == type ? target.groupId : -1; + for (auto& item : moved) + if (item.type == trackType && !groupIds.contains(item.groupId)) item.groupId = targetGroupId; + + children.insert(children.begin() + std::clamp(targetIndex, 0, (int)children.size()), moved.begin(), moved.end()); + return {}; + } + + Uids animation_length_fit(Anm2& anm2, int animationIndex) + { + if (auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex)) + animation->frameNum = animation_length_get(*animation); + return {}; + } +} diff --git a/src/imgui/documents.cpp b/src/imgui/documents.cpp index d27f861..c0c71be 100644 --- a/src/imgui/documents.cpp +++ b/src/imgui/documents.cpp @@ -51,10 +51,12 @@ namespace anm2ed::imgui { manager.command_push({manager.selected, [paths, preset](Manager&, Document& document) { - document.snapshots.anm2_push(localize.get(EDIT_MERGE_ANM2)); - for (auto& path : paths) - document.anm2.file_merge(path, document.directory_get(), preset); - document.change(Document::ALL); + document.edit_apply(EDIT_MERGE_ANM2, Document::ALL, + [&](Anm2& anm2) + { + for (auto& path : paths) + anm2.file_merge(path, document.directory_get(), preset); + }); }}); } diff --git a/src/imgui/popup/item_properties.cpp b/src/imgui/popup/item_properties.cpp index 777351b..5abe4ea 100644 --- a/src/imgui/popup/item_properties.cpp +++ b/src/imgui/popup/item_properties.cpp @@ -203,12 +203,14 @@ namespace anm2ed::imgui::popup item.spritesheetId = queuedAddItemSpritesheetID; item.isShowRect = queuedAddItemIsShowRect; - document.snapshots.anm2_push(localize.get(EDIT_ADD_ITEM)); - auto addId = - document.anm2.item_add((ItemType)queuedType, queuedAnimationIndex, item, - queuedInsertBeforeID, (destination::Type)queuedDestination); - - document.change(Document::ITEMS); + int addId{-1}; + document.edit_apply(EDIT_ADD_ITEM, Document::ITEMS, + [&](Anm2& anm2) + { + addId = anm2.item_add((ItemType)queuedType, queuedAnimationIndex, + item, queuedInsertBeforeID, + (destination::Type)queuedDestination); + }); if (addId != -1) { diff --git a/src/imgui/taskbar.cpp b/src/imgui/taskbar.cpp index 21e1134..46dc71e 100644 --- a/src/imgui/taskbar.cpp +++ b/src/imgui/taskbar.cpp @@ -172,9 +172,8 @@ namespace anm2ed::imgui { manager.command_push({manager.selected, [](Manager&, Document& document) { - document.snapshots.anm2_push(localize.get(EDIT_SCAN_AND_SET_REGIONS)); - document.anm2.regions_scan(); - document.change(Document::FRAMES); + document.edit_apply(EDIT_SCAN_AND_SET_REGIONS, Document::FRAMES, + [](Anm2& anm2) { anm2.regions_scan(); }); }}); toast_log(Level::INFO, TOAST_SCAN_AND_SET_REGIONS); } @@ -285,9 +284,10 @@ namespace anm2ed::imgui {manager.selected, [=](Manager&, Document& document) { if (queuedAnimationIndices.empty()) return; - document.snapshots.anm2_push(localize.get(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS)); - if (document.anm2.regions_generate(queuedAnimationIndices, {}, queuedFormat, queuedMapping)) - document.change(queuedMapping == RegionFrameMapping::SET ? Document::ALL : Document::SPRITESHEETS); + document.edit_apply( + EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, + queuedMapping == RegionFrameMapping::SET ? Document::ALL : Document::SPRITESHEETS, [&](Anm2& anm2) + { anm2.regions_generate(queuedAnimationIndices, {}, queuedFormat, queuedMapping); }); }}); generateRegionsPopup.close(); } diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index 9a5f6e5..3e82b63 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -1305,11 +1305,10 @@ namespace anm2ed::imgui auto isToolDuring = isToolMouseDown || isKeyDown; auto isToolEnd = isToolMouseReleased || isKeyReleased; - auto frame_snapshot = [&](auto message) + auto frame_snapshot = [&](StringType label) { - auto queuedFrameReferences = selectedFrameReferences; - manager.command_push({manager.selected, [message, queuedFrameReferences](Manager&, Document& document) - { document.snapshots.frames_push(localize.get(message), queuedFrameReferences); }}); + manager.command_push( + {manager.selected, [label](Manager&, Document& document) { document.edit_begin(label); }}); }; auto frame_change_apply = [&](FrameChange frameChange, ChangeType changeType = ChangeType::ADJUST) { diff --git a/src/imgui/window/animations.cpp b/src/imgui/window/animations.cpp index 12733fc..450727c 100644 --- a/src/imgui/window/animations.cpp +++ b/src/imgui/window/animations.cpp @@ -9,11 +9,9 @@ #include "util/imgui/layout.hpp" #include "util/imgui/shortcut.hpp" #include "util/imgui/tree.hpp" -#include "vector.hpp" using namespace anm2ed::resource; using namespace anm2ed::types; -using namespace anm2ed::util; namespace anm2ed::imgui { @@ -52,39 +50,6 @@ namespace anm2ed::imgui bool isDeleteAnimationsAfter{}; }; - std::set animation_group_ids_get(const Element& animations) - { - std::set result{}; - for (const auto& item : animations.children) - if (item.type == ElementType::GROUP) result.insert(item.id); - return result; - } - - std::set animation_group_indices_get(const Element& animations, int groupId) - { - std::set result{}; - int animationIndex{}; - for (const auto& animation : animations.children) - if (animation.type == ElementType::ANIMATION) - { - if (animation.groupId == groupId) result.insert(animationIndex); - ++animationIndex; - } - return result; - } - - int animation_index_from_child_index_get(const Element& animations, int childIndex) - { - int current{}; - for (int i = 0; i < (int)animations.children.size(); ++i) - if (animations.children[i].type == ElementType::ANIMATION) - { - if (i == childIndex) return current; - ++current; - } - return -1; - } - int animation_group_child_insert_index_get(const Element& animations, int groupId, AnimationDropZone dropZone) { auto group = std::ranges::find_if(animations.children, [&](const Element& item) @@ -110,7 +75,7 @@ namespace anm2ed::imgui std::set result(document.animation.selection.begin(), document.animation.selection.end()); if (auto animations = document.anm2.element_get(ElementType::ANIMATIONS)) for (auto groupId : window.selection) - result.merge(animation_group_indices_get(*animations, groupId)); + result.merge(edit::animation_group_indices_get(*animations, groupId)); return result; } @@ -120,7 +85,7 @@ namespace anm2ed::imgui auto& selection = document.animation.selection; if (!animations || selection.empty()) return {}; - auto groupIds = animation_group_ids_get(*animations); + auto groupIds = edit::animation_group_ids_get(*animations); std::vector result{}; int index{}; for (const auto& animation : animations->children) @@ -141,7 +106,7 @@ namespace anm2ed::imgui if (!is_window_group_key(key)) result.insert(key); else if (animations) - result.merge(animation_group_indices_get(*animations, window_group_id_from_key_get(key))); + result.merge(edit::animation_group_indices_get(*animations, window_group_id_from_key_get(key))); result.erase(reference); return result; } @@ -154,29 +119,27 @@ namespace anm2ed::imgui document.overlayDocumentId = 0; } - void animation_groups_remove(Element& animations, const std::set& groupIds) + void animations_erase(Window& window, Document& document, const std::set& indices, const std::set& groupIds, + StringType label) { - for (auto& item : animations.children) - if (item.type == ElementType::ANIMATION && groupIds.contains(item.groupId)) item.groupId = -1; - std::erase_if(animations.children, - [&](const Element& item) { return item.type == ElementType::GROUP && groupIds.contains(item.id); }); + document.edit_apply(label, window.changeType, + [&](Anm2& anm2) + { + animation_overlay_reset(document, indices); + if (indices.contains(document.reference.animationIndex)) + document.reference.animationIndex = -1; + document.animation.selection.clear(); + window.selection.clear(); + return edit::animations_remove(anm2, indices, groupIds); + }); } - void animations_erase(Window& window, Document& document, const std::set& indices, const std::set& groupIds) + std::set animation_indices_get(Document& document, const edit::Uids& uids) { - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - if (!animations) return; - animation_groups_remove(*animations, groupIds); - animation_overlay_reset(document, indices); - for (auto it = indices.rbegin(); it != indices.rend(); ++it) - { - auto childIndex = animations_child_index_get(*animations, *it); - if (childIndex == -1) continue; - if (document.reference.animationIndex == *it) document.reference.animationIndex = -1; - animations->children.erase(animations->children.begin() + childIndex); - } - document.animation.selection.clear(); - window.selection.clear(); + std::set indices{}; + for (auto reference : document.references_get(uids)) + indices.insert(reference.animationIndex); + return indices; } std::string animation_clipboard_text_get(Document& document, const Window& window) @@ -200,112 +163,69 @@ namespace anm2ed::imgui void animations_insert(Window& window, Document& document, const std::string& text, int start, int targetGroupId, StringType edit) { - std::set indices{}; std::set groupIds{}; std::string errorString{}; - auto pasted = document.anm2; - if (!pasted.animations_deserialize(text, start, indices, &errorString, &groupIds)) - { - toast_log(Level::ERROR, TOAST_DESERIALIZE_ANIMATIONS_FAILED, errorString); - return; - } - - window_edit(document, window.changeType, localize.get(edit), - [&]() - { - document.anm2 = std::move(pasted); - if (targetGroupId != -1 && groupIds.empty()) - for (auto index : indices) - if (auto animation = document.anm2.element_get(ElementType::ANIMATION, index)) - animation->groupId = targetGroupId; - - document.animation.selection = groupIds.empty() ? indices : std::set{}; - window.selection = groupIds; - document.reference = {}; - window.newElementId = -1; - if (indices.empty()) return; - window.scrollQueued = *indices.rbegin(); - if (!groupIds.empty()) return; - document.reference = {*indices.rbegin()}; - if (indices.size() == 1) window.newElementId = *indices.rbegin(); - }); + auto uids = document.edit_apply(edit, window.changeType, + [&](Anm2& anm2) + { + auto uids = edit::animations_paste(anm2, text, start, targetGroupId, groupIds, + &errorString); + if (uids.empty()) return uids; + auto indices = animation_indices_get(document, uids); + document.animation.selection = groupIds.empty() ? indices : std::set{}; + window.selection = groupIds; + document.reference = {}; + window.newElementId = -1; + if (indices.empty()) return uids; + window.scrollQueued = *indices.rbegin(); + if (!groupIds.empty()) return uids; + document.reference = {*indices.rbegin()}; + if (indices.size() == 1) window.newElementId = *indices.rbegin(); + return uids; + }); + if (!errorString.empty()) toast_log(Level::ERROR, TOAST_DESERIALIZE_ANIMATIONS_FAILED, errorString); } int animations_merge(Document& document, const AnimationMergeOptions& options, const std::set* quickSelection = nullptr, const std::set* quickGroupSelection = nullptr) { - auto& anm2 = document.anm2; - int merged{-1}; - document.snapshots.anm2_push(localize.get(EDIT_MERGE_ANIMATIONS)); + auto target = options.reference; + auto sources = + options.selection.empty() ? *quickSelection : animation_merge_indices_get(document, options.selection, target); + auto type = options.selection.empty() ? merge::APPEND : options.type; + auto isDeleteAfter = options.selection.empty() || options.isDeleteAnimationsAfter; + auto ungroupIds = options.selection.empty() && quickGroupSelection ? *quickGroupSelection : std::set{}; + if (options.selection.empty()) { - auto selected = *quickSelection; - auto isQuickGroupMerge = quickGroupSelection && !quickGroupSelection->empty(); - auto animations = anm2.element_get(ElementType::ANIMATIONS); + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); auto count = animations ? animations_count_get(*animations) : 0; - animation_overlay_reset(document, selected); - - if (selected.size() == 1 && !isQuickGroupMerge && *selected.begin() != count - 1) - selected.insert(*selected.begin() + 1); - if (selected.size() > 1) - merged = anm2.animations_merge(*selected.begin(), selected); - else if (selected.size() == 1 && isQuickGroupMerge) - merged = *selected.begin(); - if (merged != -1 && isQuickGroupMerge && animations) animation_groups_remove(*animations, *quickGroupSelection); - } - else - { - auto mergeSelection = animation_merge_indices_get(document, options.selection, options.reference); - if (mergeSelection.empty()) return -1; - animation_overlay_reset(document, mergeSelection); - merged = anm2.animations_merge(options.reference, mergeSelection, options.type, options.isDeleteAnimationsAfter); + if (sources.empty()) return -1; + if (sources.size() == 1 && ungroupIds.empty() && *sources.begin() != count - 1) + sources.insert(*sources.begin() + 1); + if (sources.size() == 1 && ungroupIds.empty()) return -1; + target = *sources.begin(); } + else if (sources.empty()) + return -1; - if (merged == -1) return -1; - document.animation.selection = {merged}; - document.reference = {merged}; - document.change(Document::ANIMATIONS); + int merged{-1}; + document.edit_apply(EDIT_MERGE_ANIMATIONS, Document::ANIMATIONS, + [&](Anm2& anm2) + { + animation_overlay_reset(document, sources); + auto uids = edit::animations_merge(anm2, target, sources, type, isDeleteAfter, ungroupIds); + auto indices = animation_indices_get(document, uids); + if (indices.empty()) return uids; + merged = *indices.begin(); + document.animation.selection = {merged}; + document.reference = {merged}; + return uids; + }); return merged; } - Element animation_track_container_shell_copy(const Element* source, const TrackContainer& row) - { - auto destination = element_make(row.container); - if (!source) return destination; - - auto nextGroupId = element_child_next_id_get(*source, ElementType::GROUP); - std::set copiedTrackIds{}; - auto track_push = [&](const Element& track, int groupId) - { - if (track.type != row.track || !copiedTrackIds.insert(track_id_get(track)).second) return; - auto item = element_make(row.track); - item.*(row.id) = track.*(row.id); - item.groupId = track.groupId != -1 ? track.groupId : groupId; - item.isVisible = track.isVisible; - destination.children.push_back(item); - }; - - for (const auto& sourceItem : source->children) - { - if (sourceItem.type != ElementType::GROUP) - { - track_push(sourceItem, -1); - continue; - } - auto group = element_make(ElementType::GROUP); - group.id = sourceItem.id >= 0 ? sourceItem.id : nextGroupId++; - group.name = sourceItem.name; - group.isExpanded = sourceItem.isExpanded; - group.isVisible = sourceItem.isVisible; - group.children.push_back(root_animation_make()); - destination.children.push_back(group); - for (const auto& child : sourceItem.children) - track_push(child, group.id); - } - return destination; - } - AnimationDropZone animation_drop_zone_get(ImVec2 min, ImVec2 max) { auto zoneHeight = (max.y - min.y) * DROP_ZONE_FRACTION; @@ -315,52 +235,17 @@ namespace anm2ed::imgui return AnimationDropZone::INSIDE; } - void animation_items_move(Window& window, Document& document, const std::vector& items, - int targetChildIndex, int targetGroupId) + void animation_items_move(Window& window, Document& document, Anm2& anm2, + const std::vector& items, int targetChildIndex, int targetGroupId) { - auto animations = window_container_get(window, document); - if (!animations) return; - - auto groupIds = animation_group_ids_get(*animations); - auto groupId = groupIds.contains(targetGroupId) ? targetGroupId : -1; - std::set draggedAnimationIds{}; - std::set draggedGroupIds{}; + std::set indices{}; + std::set groupIds{}; for (auto item : items) - if (item.type == AnimationDragDropType::GROUP && groupIds.contains(item.id)) - draggedGroupIds.insert(item.id); - else if (item.type == AnimationDragDropType::ANIMATION && animations_child_index_get(*animations, item.id) != -1) - draggedAnimationIds.insert(item.id); - if (draggedAnimationIds.empty() && draggedGroupIds.empty()) return; - - std::vector childIndices{}; - std::set directAnimationChildIndices{}; - int animationIndex{}; - for (int i = 0; i < (int)animations->children.size(); ++i) - { - auto& item = animations->children[i]; - if (item.type == ElementType::GROUP && draggedGroupIds.contains(item.id)) childIndices.push_back(i); - if (item.type != ElementType::ANIMATION) continue; - auto isGroupDragged = draggedGroupIds.contains(item.groupId); - if (draggedAnimationIds.contains(animationIndex) && !isGroupDragged) - { - item.groupId = groupId; - directAnimationChildIndices.insert(i); - } - if (isGroupDragged || draggedAnimationIds.contains(animationIndex)) childIndices.push_back(i); - ++animationIndex; - } - - auto movedChildIndices = vector::move_indices_to_position(animations->children, childIndices, targetChildIndex); - if (movedChildIndices.empty()) return; - - document.animation.selection.clear(); - window.selection = draggedGroupIds; - auto moved = movedChildIndices.begin(); - for (auto source = childIndices.begin(); source != childIndices.end() && moved != movedChildIndices.end(); - ++source, ++moved) - if (directAnimationChildIndices.contains(*source)) - if (auto index = animation_index_from_child_index_get(*animations, *moved); index != -1) - document.animation.selection.insert(index); + (item.type == AnimationDragDropType::GROUP ? groupIds : indices).insert(item.id); + auto uids = edit::animations_move(anm2, indices, groupIds, targetChildIndex, targetGroupId); + if (uids.empty() && groupIds.empty()) return; + document.animation.selection = animation_indices_get(document, uids); + window.selection = groupIds; } void animation_move_command_push(Window& window, Manager& manager, std::vector items, @@ -372,9 +257,12 @@ namespace anm2ed::imgui { auto animations = window_container_get(window, document); if (!animations) return; - window_edit( - document, window.changeType, localize.get(EDIT_MOVE_ANIMATIONS), [&]() - { animation_items_move(window, document, items, target_child_index_get(*animations), targetGroupId); }); + document.edit_apply(EDIT_MOVE_ANIMATIONS, window.changeType, + [&](Anm2& anm2) + { + animation_items_move(window, document, anm2, items, + target_child_index_get(*animations), targetGroupId); + }); }}); } @@ -390,7 +278,7 @@ namespace anm2ed::imgui : document.animation.selection.contains(fallback.id); if (animations && isFallbackSelected) { - auto groupIds = animation_group_ids_get(*animations); + auto groupIds = edit::animation_group_ids_get(*animations); for (auto groupId : window.selection) if (groupIds.contains(groupId)) items.push_back({AnimationDragDropType::GROUP, groupId}); for (auto animationIndex : document.animation.selection) @@ -475,12 +363,12 @@ namespace anm2ed::imgui if (!group || (name.value_or(group->name) == group->name && isExpanded.value_or(group->isExpanded) == group->isExpanded)) return; - window_edit(document, Document::ANIMATIONS, localize.get(edit), - [&]() - { - group->name = name.value_or(group->name); - group->isExpanded = isExpanded.value_or(group->isExpanded); - }); + document.edit_apply(edit, Document::ANIMATIONS, + [&](Anm2&) + { + group->name = name.value_or(group->name); + group->isExpanded = isExpanded.value_or(group->isExpanded); + }); }}); } @@ -632,7 +520,7 @@ namespace anm2ed::imgui { auto container = window_container_get(window, document); if (!container) return; - auto groupIds = animation_group_ids_get(*container); + auto groupIds = edit::animation_group_ids_get(*container); std::erase_if(window.selection, [&](int groupId) { return !groupIds.contains(groupId); }); std::vector visibleIds{}; @@ -641,7 +529,7 @@ namespace anm2ed::imgui for (auto& item : container->children) { if (item.type == ElementType::GROUP && item.isExpanded) - visibleIds.insert_range(visibleIds.end(), animation_group_indices_get(*container, item.id)); + visibleIds.insert_range(visibleIds.end(), edit::animation_group_indices_get(*container, item.id)); if (item.type != ElementType::ANIMATION) continue; if (!is_animation_grouped(groupIds, item)) visibleIds.push_back(animationIndex); window.order.push_back(animationIndex++); @@ -675,62 +563,47 @@ namespace anm2ed::imgui auto animations = window_container_get(window, document); if (!animations) return; - window_edit(document, window.changeType, localize.get(EDIT_ADD_ANIMATION), - [&]() - { - auto groupIds = animation_group_ids_get(*animations); - auto targetGroupId = window.selection.size() == 1 && groupIds.contains(*window.selection.begin()) - ? *window.selection.begin() - : -1; + auto groupIds = edit::animation_group_ids_get(*animations); + auto targetGroupId = + window.selection.size() == 1 && groupIds.contains(*window.selection.begin()) ? *window.selection.begin() : -1; + auto count = animations_count_get(*animations); + auto groupIndices = + targetGroupId != -1 ? edit::animation_group_indices_get(*animations, targetGroupId) : std::set{}; + auto index = !selection.empty() ? std::min(*selection.rbegin() + 1, count) + : !groupIndices.empty() ? std::min(*groupIndices.rbegin() + 1, count) + : count; + auto selected = + selection.empty() ? nullptr : document.anm2.element_get(ElementType::ANIMATION, *selection.rbegin()); + auto groupId = selection.empty() ? targetGroupId + : selected && groupIds.contains(selected->groupId) ? selected->groupId + : -1; - auto animation = element_make(ElementType::ANIMATION); - animation.name = localize.get(TEXT_NEW_ANIMATION); - animation.children.push_back(root_animation_make()); - auto referenceAnimation = - document.anm2.element_get(ElementType::ANIMATION, document.reference.animationIndex); - for (const auto& row : TRACK_CONTAINERS) - animation.children.push_back(animation_track_container_shell_copy( - referenceAnimation ? child_first_get(*referenceAnimation, row.container) : nullptr, row)); - animation.children.push_back(element_make(ElementType::TRIGGERS)); - - auto count = animations_count_get(*animations); - auto groupIndices = - targetGroupId != -1 ? animation_group_indices_get(*animations, targetGroupId) : std::set{}; - auto index = !selection.empty() ? std::min(*selection.rbegin() + 1, count) - : !groupIndices.empty() ? std::min(*groupIndices.rbegin() + 1, count) - : count; - auto selected = selection.empty() - ? nullptr - : document.anm2.element_get(ElementType::ANIMATION, *selection.rbegin()); - if (selected && groupIds.contains(selected->groupId)) animation.groupId = selected->groupId; - if (selection.empty()) animation.groupId = targetGroupId; - if (count == 0) animations->defaultAnimation = animation.name; - - animations->children.insert(animations->children.begin() + - animations_child_insert_index_get(*animations, index), - animation); - selection = {index}; - window.selection.clear(); - document.reference = {index}; - window.newElementId = index; - window.scrollQueued = index; - }); + document.edit_apply(EDIT_ADD_ANIMATION, window.changeType, + [&](Anm2& anm2) + { + auto uids = edit::animation_add(anm2, index, groupId, document.reference.animationIndex, + localize.get(TEXT_NEW_ANIMATION)); + selection = {index}; + window.selection.clear(); + document.reference = {index}; + window.newElementId = index; + window.scrollQueued = index; + return uids; + }); }; window.remove = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { auto selection = std::set(document.animation.selection.begin(), document.animation.selection.end()); auto groupSelection = window.selection; - window_edit(document, window.changeType, - localize.get(groupSelection.empty() ? EDIT_REMOVE_ANIMATIONS : EDIT_REMOVE_GROUP), - [&]() { animations_erase(window, document, selection, groupSelection); }); + animations_erase(window, document, selection, groupSelection, + groupSelection.empty() ? EDIT_REMOVE_ANIMATIONS : EDIT_REMOVE_GROUP); }; window.cut = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) { if (auto text = animation_clipboard_text_get(document, window); !text.empty()) clipboard.set(text); auto selectedIndices = animation_selected_indices_get(document, window); auto groupSelection = window.selection; - window_edit(document, window.changeType, localize.get(EDIT_CUT_ANIMATIONS), - [&]() { animations_erase(window, document, selectedIndices, groupSelection); }); + animations_erase(window, document, selectedIndices, groupSelection, EDIT_CUT_ANIMATIONS); }; window.copy = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) { @@ -753,13 +626,13 @@ namespace anm2ed::imgui if (clipboard.is_empty() || !animations) return; auto& selection = document.animation.selection; auto count = animations_count_get(*animations); - auto groupIds = animation_group_ids_get(*animations); + auto groupIds = edit::animation_group_ids_get(*animations); auto targetGroupId = selection.empty() && window.selection.size() == 1 && groupIds.contains(*window.selection.begin()) ? *window.selection.begin() : -1; auto groupIndices = - targetGroupId != -1 ? animation_group_indices_get(*animations, targetGroupId) : std::set{}; + targetGroupId != -1 ? edit::animation_group_indices_get(*animations, targetGroupId) : std::set{}; auto start = !selection.empty() ? *selection.rbegin() + 1 : !groupIndices.empty() ? std::min(*groupIndices.rbegin() + 1, count) : count; @@ -796,31 +669,26 @@ namespace anm2ed::imgui auto animations = window_container_get(window, document); if (targetIndices.empty() || !animations) return; - window_edit(document, window.changeType, localize.get(EDIT_GROUP_ITEMS), - [&]() - { - std::set targetSet(targetIndices.begin(), targetIndices.end()); - auto group = element_make(ElementType::GROUP); - group.id = element_child_next_id_get(*animations, ElementType::GROUP); - group.name = localize.get(TEXT_NEW_GROUP); - for (auto index : targetSet) - document.anm2.element_get(ElementType::ANIMATION, index)->groupId = group.id; - animations->children.insert(animations->children.begin() + - animations_child_index_get(*animations, *targetSet.begin()), - group); - document.animation.selection = targetSet; - window.selection = {group.id}; - document.reference = {*targetSet.begin()}; - window.scrollQueued = *targetSet.begin(); - }); + std::set targetSet(targetIndices.begin(), targetIndices.end()); + auto groupId = element_child_next_id_get(*animations, ElementType::GROUP); + document.edit_apply(EDIT_GROUP_ITEMS, window.changeType, + [&](Anm2& anm2) + { + auto uids = edit::animations_group(anm2, targetSet, localize.get(TEXT_NEW_GROUP)); + document.animation.selection = targetSet; + window.selection = {groupId}; + document.reference = {*targetSet.begin()}; + window.scrollQueued = *targetSet.begin(); + return uids; + }); }; window.default_set = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { auto animations = window_container_get(window, document); auto animation = document.anm2.element_get(ElementType::ANIMATION, *document.animation.selection.begin()); if (!animations || !animation) return; - window_edit(document, window.changeType, localize.get(EDIT_DEFAULT_ANIMATION), - [&]() { animations->defaultAnimation = animation->name; }); + document.edit_apply(EDIT_DEFAULT_ANIMATION, window.changeType, + [&](Anm2&) { animations->defaultAnimation = animation->name; }); }; window.body_update = [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard&, Document& document) @@ -838,7 +706,7 @@ namespace anm2ed::imgui }; std::vector candidates{}; auto animations = window_container_get(window, document); - auto groupIds = animations ? animation_group_ids_get(*animations) : std::set{}; + auto groupIds = animations ? edit::animation_group_ids_get(*animations) : std::set{}; static const Element EMPTY{}; auto candidate_animation_push = [&](const Element& animation, int animationIndex, bool isGrouped) { @@ -851,7 +719,7 @@ namespace anm2ed::imgui { if (item.type == ElementType::GROUP) { - auto groupIndices = animation_group_indices_get(*animations, item.id); + auto groupIndices = edit::animation_group_indices_get(*animations, item.id); groupIndices.erase(mergeReference); if (groupIndices.empty()) continue; candidates.push_back({window_group_key_get(item.id), diff --git a/src/imgui/window/frame_properties.cpp b/src/imgui/window/frame_properties.cpp index 0b0a04e..c556f3d 100644 --- a/src/imgui/window/frame_properties.cpp +++ b/src/imgui/window/frame_properties.cpp @@ -64,9 +64,9 @@ namespace anm2ed::imgui auto& type = reference.itemType; auto frame = reference.frameIndex >= 0 ? anm2.element_get(reference) : nullptr; - auto frame_edit = [&](edit::Type state, StringType message, auto behavior) + auto frame_edit = [&](edit_state::Type state, StringType message, auto behavior) { - if (state == edit::NONE) return; + if (state == edit_state::NONE) return; manager.command_push( {manager.selected, [=, queuedReference = reference](Manager&, Document& document) mutable { @@ -75,10 +75,9 @@ namespace anm2ed::imgui auto item = document.anm2.element_get(Reference{queuedReference.animationIndex, queuedReference.itemType, queuedReference.itemID, -1, queuedReference.groupType, queuedReference.groupId}); - if (state == edit::START || state == edit::COMPLETE) - document.snapshots.frames_push(localize.get(message), {queuedReference}); + if (state == edit_state::START || state == edit_state::COMPLETE) document.edit_begin(message); behavior(document, *frame, item, queuedReference); - if (state == edit::END || state == edit::COMPLETE) document.change(Document::FRAMES); + if (state == edit_state::END || state == edit_state::COMPLETE) document.change(Document::FRAMES); }}); }; @@ -122,7 +121,7 @@ namespace anm2ed::imgui frame) { auto eventId = useFrame.eventId; - frame_edit(edit::COMPLETE, EDIT_TRIGGER_EVENT, + frame_edit(edit_state::COMPLETE, EDIT_TRIGGER_EVENT, [eventId](Document&, Element& frame, Element*, const Reference&) { frame.eventId = eventId; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TRIGGER_EVENT)); @@ -133,7 +132,7 @@ namespace anm2ed::imgui frame) { auto atFrame = useFrame.atFrame; - frame_edit(edit::COMPLETE, EDIT_TRIGGER_AT_FRAME, + frame_edit(edit_state::COMPLETE, EDIT_TRIGGER_AT_FRAME, [atFrame](Document& document, Element& frame, Element* item, const Reference&) { frame.atFrame = atFrame; @@ -149,7 +148,7 @@ namespace anm2ed::imgui frame) { auto isVisible = useFrame.isVisible; - frame_edit(edit::COMPLETE, EDIT_TRIGGER_VISIBILITY, + frame_edit(edit_state::COMPLETE, EDIT_TRIGGER_VISIBILITY, [isVisible](Document&, Element& frame, Element*, const Reference&) { frame.isVisible = isVisible; }); } @@ -172,7 +171,7 @@ namespace anm2ed::imgui { auto soundIndex = (std::size_t)i; auto soundId = id; - frame_edit(edit::COMPLETE, EDIT_TRIGGER_SOUND, + frame_edit(edit_state::COMPLETE, EDIT_TRIGGER_SOUND, [soundIndex, soundId](Document&, Element& frame, Element*, const Reference&) { if (soundIndex < frame.soundIds.size()) frame.soundIds[soundIndex] = soundId; @@ -188,7 +187,7 @@ namespace anm2ed::imgui auto widgetSize = imgui::widget_size_with_row_get(2); if (ImGui::Button(localize.get(BASIC_ADD), widgetSize) && frame) - frame_edit(edit::COMPLETE, EDIT_ADD_TRIGGER_SOUND, + frame_edit(edit_state::COMPLETE, EDIT_ADD_TRIGGER_SOUND, [](Document&, Element& frame, Element*, const Reference&) { frame.soundIds.push_back(-1); }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ADD_TRIGGER_SOUND)); @@ -196,7 +195,7 @@ namespace anm2ed::imgui ImGui::BeginDisabled(useFrame.soundIds.empty()); if (ImGui::Button(localize.get(BASIC_REMOVE), widgetSize) && frame) - frame_edit(edit::COMPLETE, EDIT_REMOVE_TRIGGER_SOUND, + frame_edit(edit_state::COMPLETE, EDIT_REMOVE_TRIGGER_SOUND, [](Document&, Element& frame, Element*, const Reference&) { if (!frame.soundIds.empty()) frame.soundIds.pop_back(); @@ -237,7 +236,7 @@ namespace anm2ed::imgui frame) { auto duration = useFrame.duration; - frame_edit(edit::COMPLETE, EDIT_FRAME_DURATION, + frame_edit(edit_state::COMPLETE, EDIT_FRAME_DURATION, [duration](Document&, Element& frame, Element*, const Reference&) { frame.duration = duration; }); } @@ -263,7 +262,7 @@ namespace anm2ed::imgui frame) { auto regionId = useFrame.regionId; - frame_edit(edit::COMPLETE, EDIT_SET_REGION_PROPERTIES, + frame_edit(edit_state::COMPLETE, EDIT_SET_REGION_PROPERTIES, [regionId](Document& document, Element& frame, Element*, const Reference& reference) { frame.regionId = regionId; @@ -280,7 +279,7 @@ namespace anm2ed::imgui if (ImGui::Combo(localize.get(BASIC_INTERPOLATED), &interpolationValue, interpolationLabels.data(), (int)interpolationLabels.size()) && frame) - frame_edit(edit::COMPLETE, EDIT_FRAME_INTERPOLATION, + frame_edit(edit_state::COMPLETE, EDIT_FRAME_INTERPOLATION, [interpolationValue](Document&, Element& frame, Element*, const Reference&) { frame.interpolation = static_cast(interpolationValue); }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_INTERPOLATION)); @@ -291,7 +290,7 @@ namespace anm2ed::imgui frame) { auto shaderId = useFrame.shaderId; - frame_edit(edit::COMPLETE, EDIT_FRAME_SHADER, + frame_edit(edit_state::COMPLETE, EDIT_FRAME_SHADER, [shaderId](Document&, Element& frame, Element*, const Reference&) { frame.shaderId = shaderId; }); } @@ -302,7 +301,7 @@ namespace anm2ed::imgui frame) { auto isVisible = useFrame.isVisible; - frame_edit(edit::COMPLETE, EDIT_FRAME_VISIBILITY, + frame_edit(edit_state::COMPLETE, EDIT_FRAME_VISIBILITY, [isVisible](Document&, Element& frame, Element*, const Reference&) { frame.isVisible = isVisible; }); } @@ -314,7 +313,7 @@ namespace anm2ed::imgui { if (axis > 0) ImGui::SameLine(); if (ImGui::Button(localize.get(FLIP_BUTTONS[axis].label), widgetSize) && frame) - frame_edit(edit::COMPLETE, FLIP_BUTTONS[axis].edit, + frame_edit(edit_state::COMPLETE, FLIP_BUTTONS[axis].edit, [axis, isPositionFlipped = ImGui::IsKeyDown(ImGuiMod_Ctrl)](Document&, Element& frame, Element*, const Reference&) { diff --git a/src/imgui/window/items.cpp b/src/imgui/window/items.cpp index 8c609f0..f1727ad 100644 --- a/src/imgui/window/items.cpp +++ b/src/imgui/window/items.cpp @@ -143,16 +143,16 @@ namespace anm2ed::imgui event.name = localize.get(TEXT_NEW_EVENT); auto events = window_container_get(window, document); if (!events) return; - window_edit(document, window.changeType, localize.get(window.addEdit), - [&]() - { - event.id = element_child_next_id_get(*events, ElementType::EVENT_ELEMENT); - events->children.push_back(event); - auto& storage = window.storage_get(document); - storage.selection = {event.id}; - storage.reference = event.id; - window.newElementId = event.id; - }); + document.edit_apply(window.addEdit, window.changeType, + [&](Anm2&) + { + event.id = element_child_next_id_get(*events, ElementType::EVENT_ELEMENT); + events->children.push_back(event); + auto& storage = window.storage_get(document); + storage.selection = {event.id}; + storage.reference = event.id; + window.newElementId = event.id; + }); }; return window; } diff --git a/src/imgui/window/regions.cpp b/src/imgui/window/regions.cpp index 7e30862..106494b 100644 --- a/src/imgui/window/regions.cpp +++ b/src/imgui/window/regions.cpp @@ -133,7 +133,7 @@ namespace anm2ed::imgui if (options.isMakeSpritesheet || options.isRemoveCurrent) { - document.snapshots.anm2_textures_push(localize.get(EDIT_EXPORT_REGION)); + document.edit_begin(EDIT_EXPORT_REGION, true); if (options.isMakeSpritesheet) { @@ -218,12 +218,12 @@ namespace anm2ed::imgui { auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, spritesheetId); if (!spritesheet) return; - window_edit(document, window.changeType, localize.get(EDIT_MOVE_REGIONS), - [&]() - { - vector::move_indices_to_position(spritesheet->children, indices, targetIndex); - document.region.selection = std::set(movedIds.begin(), movedIds.end()); - }); + document.edit_apply(EDIT_MOVE_REGIONS, window.changeType, + [&](Anm2&) + { + vector::move_indices_to_position(spritesheet->children, indices, targetIndex); + document.region.selection = std::set(movedIds.begin(), movedIds.end()); + }); }}); isMoved = true; } @@ -452,73 +452,42 @@ namespace anm2ed::imgui }; window.remove_unused = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { - auto spritesheetId = document.spritesheet.reference; - auto unused = document.anm2.region_unused(spritesheetId); - auto spritesheet = region_spritesheet_get(document); - if (unused.empty() || !spritesheet) return; - window_edit(document, window.changeType, localize.get(EDIT_REMOVE_UNUSED_REGIONS), - [&]() - { - animations_tracks_each(document.anm2.root, ElementType::LAYER_ANIMATION, - [&](Element& track) - { - auto layer = - document.anm2.element_get(ElementType::LAYER_ELEMENT, track.layerId); - if (!layer || layer->spritesheetId != spritesheetId) return; - for (auto& frame : track.children) - if (frame.type == ElementType::FRAME && unused.contains(frame.regionId)) - frame.regionId = -1; - }); - for (auto id : unused) - element_child_id_erase(*spritesheet, ElementType::REGION, id); - }); + document.edit_apply(EDIT_REMOVE_UNUSED_REGIONS, window.changeType, [&](Anm2& anm2) + { return edit::regions_remove_unused(anm2, document.spritesheet.reference); }); }; window.trim = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { auto& region = document.region; - window_edit(document, window.changeType, localize.get(EDIT_TRIM_REGIONS), - [&]() - { - if (!document.regions_trim(document.spritesheet.reference, region.selection)) return; - if (region.reference != -1 && !region.selection.contains(region.reference)) - region.reference = *region.selection.begin(); - document.reference = {document.reference.animationIndex}; - document.frames.reference = -1; - document.frames.selection.clear(); - }); + document.edit_apply(EDIT_TRIM_REGIONS, window.changeType, + [&](Anm2&) + { + if (!document.regions_trim(document.spritesheet.reference, region.selection)) return; + if (region.reference != -1 && !region.selection.contains(region.reference)) + region.reference = *region.selection.begin(); + document.reference = {document.reference.animationIndex}; + document.frames.reference = -1; + document.frames.selection.clear(); + }); }; window.paste = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) { - auto spritesheetId = document.spritesheet.reference; auto spritesheet = region_spritesheet_get(document); if (!spritesheet || clipboard.is_empty()) return; - auto maxIdBefore = element_child_max_id_get(*spritesheet, ElementType::REGION); - auto insertIndex = region_insert_index_get(document); - auto pasted = document.anm2; std::string errorString{}; - if (!pasted.deserialize(ElementType::REGION, clipboard.get(), true, &errorString, {}, spritesheetId)) - { - toast_log(Level::ERROR, TOAST_DESERIALIZE_REGIONS_FAILED, errorString); - return; - } - - window_edit(document, window.changeType, localize.get(EDIT_PASTE_REGIONS), - [&]() - { - document.anm2 = std::move(pasted); - auto target = region_spritesheet_get(document); - auto maxIdAfter = element_child_max_id_get(*target, ElementType::REGION); - if (maxIdAfter <= maxIdBefore) return; - std::vector pastedIndices{}; - for (int i = 0; i < (int)target->children.size(); i++) - if (target->children[i].type == ElementType::REGION && target->children[i].id > maxIdBefore) - pastedIndices.push_back(i); - vector::move_indices_to_position(target->children, pastedIndices, insertIndex); - window.newElementId = maxIdAfter; - document.region.selection = {maxIdAfter}; - document.region.reference = maxIdAfter; - }); + document.edit_apply(EDIT_PASTE_REGIONS, window.changeType, + [&](Anm2& anm2) + { + edit::regions_paste(anm2, document.spritesheet.reference, clipboard.get(), + region_insert_index_get(document), &errorString); + auto target = region_spritesheet_get(document); + auto maxIdAfter = target ? element_child_max_id_get(*target, ElementType::REGION) : -1; + if (maxIdAfter <= maxIdBefore) return; + window.newElementId = maxIdAfter; + document.region.selection = {maxIdAfter}; + document.region.reference = maxIdAfter; + }); + if (!errorString.empty()) toast_log(Level::ERROR, TOAST_DESERIALIZE_REGIONS_FAILED, errorString); }; window.rows_update = [](Window& window, Manager& manager, Settings& settings, Resources& resources, Clipboard& clipboard, Document& document) diff --git a/src/imgui/window/shaders.cpp b/src/imgui/window/shaders.cpp index f30b9d0..d90b4ed 100644 --- a/src/imgui/window/shaders.cpp +++ b/src/imgui/window/shaders.cpp @@ -312,12 +312,14 @@ namespace anm2ed::imgui shader.id = element_child_next_id_get(*shaders, ElementType::SHADER); shader.name = localize.get(TEXT_NEW_SHADER); - document.snapshots.anm2_push(localize.get(EDIT_ADD_SHADER)); - shaders->children.push_back(shader); - document.shader.selection = {shader.id}; - document.shader.reference = shader.id; - newElementId = shader.id; - document.change(Document::SHADERS); + document.edit_apply(EDIT_ADD_SHADER, Document::SHADERS, + [&](Anm2&) + { + shaders->children.push_back(shader); + document.shader.selection = {shader.id}; + document.shader.reference = shader.id; + newElementId = shader.id; + }); }}); }; @@ -330,15 +332,18 @@ namespace anm2ed::imgui auto unused = document.anm2.element_unused(ElementType::SHADER); if (unused.empty()) return; - document.snapshots.anm2_push(localize.get(EDIT_REMOVE_UNUSED_SHADERS)); - for (auto id : unused) - { - element_child_id_erase(*shaders, ElementType::SHADER, id); - document.shader.selection.erase(id); - if (document.shader.reference == id) document.shader.reference = -1; - if (popupShaderId == id) propertiesPopup.close(); - } - document.change(Document::SHADERS); + document.edit_apply(EDIT_REMOVE_UNUSED_SHADERS, Document::SHADERS, + [&](Anm2&) + { + for (auto id : unused) + { + element_child_id_erase(*shaders, ElementType::SHADER, id); + document.shader.selection.erase(id); + if (document.shader.reference == id) + document.shader.reference = -1; + if (popupShaderId == id) propertiesPopup.close(); + } + }); }}); }; diff --git a/src/imgui/window/sounds.cpp b/src/imgui/window/sounds.cpp index 8b5dd98..e3b90ac 100644 --- a/src/imgui/window/sounds.cpp +++ b/src/imgui/window/sounds.cpp @@ -83,16 +83,16 @@ namespace anm2ed::imgui }; window.reload = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { - window_edit(document, window.changeType, localize.get(EDIT_RELOAD_SOUNDS), - [&]() - { - for (auto id : document.sound.selection) - if (auto sound = window_element_get(window, document, id)) - { - document.sound_reload(id); - toast_log(Level::INFO, TOAST_RELOAD_SOUND, id, path::to_utf8(sound->path)); - } - }); + document.edit_apply(EDIT_RELOAD_SOUNDS, window.changeType, + [&](Anm2&) + { + for (auto id : document.sound.selection) + if (auto sound = window_element_get(window, document, id)) + { + document.sound_reload(id); + toast_log(Level::INFO, TOAST_RELOAD_SOUND, id, path::to_utf8(sound->path)); + } + }); }; window.body_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) { @@ -115,14 +115,14 @@ namespace anm2ed::imgui { auto sound = window_element_get(window, document, id); if (!sound) return; - window_edit(document, window.changeType, localize.get(EDIT_REPLACE_SOUND), - [&]() - { - sound->path = window_asset_path_get(document, dialogPath); - document.sound_reload(id); - toast_log(Level::INFO, TOAST_REPLACE_SOUND, id, - path::to_utf8(sound->path)); - }); + document.edit_apply(EDIT_REPLACE_SOUND, window.changeType, + [&](Anm2&) + { + sound->path = window_asset_path_get(document, dialogPath); + document.sound_reload(id); + toast_log(Level::INFO, TOAST_REPLACE_SOUND, id, + path::to_utf8(sound->path)); + }); }}); window.dialog->reset(); } diff --git a/src/imgui/window/spritesheet_editor.cpp b/src/imgui/window/spritesheet_editor.cpp index ffe34d5..ebfd368 100644 --- a/src/imgui/window/spritesheet_editor.cpp +++ b/src/imgui/window/spritesheet_editor.cpp @@ -359,27 +359,10 @@ namespace anm2ed::imgui auto fraction = current - glm::floor(current); return glm::floor(value) + fraction; }; - auto frame_snapshot_push = [&](StringType messageType, const std::set& frameReferences) + auto edit_begin_push = [&](StringType label, bool isTextures = false) { - auto message = std::string(localize.get(messageType)); - auto queuedFrameReferences = frameReferences; - manager.command_push({manager.selected, [message, queuedFrameReferences](Manager&, Document& document) - { document.snapshots.frames_push(message, queuedFrameReferences); }}); - }; - auto region_snapshot_push = [&](StringType messageType, const std::set& regionIds) - { - auto message = std::string(localize.get(messageType)); - auto queuedSpritesheet = referenceSpritesheet; - auto queuedRegionIds = regionIds; - manager.command_push({manager.selected, - [message, queuedSpritesheet, queuedRegionIds](Manager&, Document& document) - { document.snapshots.regions_push(message, queuedSpritesheet, queuedRegionIds); }}); - }; - auto texture_snapshot_push = [&](StringType messageType) - { - auto message = std::string(localize.get(messageType)); - manager.command_push({manager.selected, [message](Manager&, Document& document) - { document.snapshots.textures_push(message); }}); + manager.command_push({manager.selected, [label, isTextures](Manager&, Document& document) + { document.edit_begin(label, isTextures); }}); }; auto document_change_push = [&](Document::ChangeType changeType) { @@ -656,7 +639,7 @@ namespace anm2ed::imgui region_selection_set(hoveredRegionId); if (isReferenceLayerOnSpritesheet) { - frame_snapshot_push(EDIT_FRAME_REGION, selectedFrameReferences); + edit_begin_push(EDIT_FRAME_REGION); FrameChange change{}; change.regionId = hoveredRegionId; if (auto region = region_get(hoveredRegionId)) @@ -681,7 +664,7 @@ namespace anm2ed::imgui auto region = region_get(regionReference); if (!region) break; - if (isBegin) region_snapshot_push(EDIT_REGION_MOVE, {regionReference}); + if (isBegin) edit_begin_push(EDIT_REGION_MOVE); if (isMouseDown) region_pivot_set(regionReference, pivot_snap(mousePos - region->crop, region->pivot)); if (isLeftPressed) region_pivot_offset(regionReference, vec2(-step, 0)); if (isRightPressed) region_pivot_offset(regionReference, vec2(step, 0)); @@ -704,7 +687,7 @@ namespace anm2ed::imgui } if (!item || !frame || selectedFrameToolReferences.empty() || isRegionInUse) break; - if (isBegin) frame_snapshot_push(EDIT_FRAME_PIVOT, selectedFrameToolReferences); + if (isBegin) edit_begin_push(EDIT_FRAME_PIVOT); if (isMouseDown) { auto pivot = pivot_snap(mousePos - frame->crop, frame->pivot); @@ -740,7 +723,7 @@ namespace anm2ed::imgui !regionSelection.empty()) { if (!spritesheet || regionSelection.empty()) break; - if (isBegin) region_snapshot_push(EDIT_REGION_CROP, regionSelection); + if (isBegin) edit_begin_push(EDIT_REGION_CROP); if (isMouseClicked) { @@ -781,7 +764,7 @@ namespace anm2ed::imgui } if (!item || !frame || selectedFrameToolReferences.empty() || isRegionInUse) break; - if (isBegin) frame_snapshot_push(EDIT_FRAME_CROP, selectedFrameToolReferences); + if (isBegin) edit_begin_push(EDIT_FRAME_CROP); if (isMouseClicked) { @@ -836,7 +819,7 @@ namespace anm2ed::imgui { if (!texture) break; auto color = useTool == tool::DRAW ? toolColor : vec4(); - if (isMouseClicked) texture_snapshot_push(useTool == tool::DRAW ? EDIT_DRAW : EDIT_ERASE); + if (isMouseClicked) edit_begin_push(useTool == tool::DRAW ? EDIT_DRAW : EDIT_ERASE, true); if (isMouseDown) texture_line_apply(ivec2(previousTextureMousePos), ivec2(textureMousePos), color); if (isMouseReleased) texture_change_push(); break; diff --git a/src/imgui/window/spritesheets.cpp b/src/imgui/window/spritesheets.cpp index 78174ee..1ad60f2 100644 --- a/src/imgui/window/spritesheets.cpp +++ b/src/imgui/window/spritesheets.cpp @@ -49,38 +49,38 @@ namespace anm2ed::imgui auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id); auto texture = document.texture_get(id); if (!spritesheet || (isWritten && !texture)) return; - window_edit(document, window.changeType, localize.get(edit), - [&]() - { - auto newPath = window_asset_path_get(document, dialogPath); - auto pathString = path::to_utf8(newPath); - if (isWritten) - { - WorkingDirectory workingDirectory(document.directory_get()); - path::ensure_directory(newPath.parent_path()); - if (!texture->write_png(newPath)) - { - toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); - return; - } - } - spritesheet->path = newPath; - if (isWritten) - document.texturePaths[id] = newPath; - else - document.texture_reload(id); - document.spritesheet_hash_set_saved(id); - toast_log(Level::INFO, - isWritten ? TOAST_SAVE_SPRITESHEET : TOAST_REPLACE_SPRITESHEET, id, - pathString); - }); + document.edit_apply( + edit, window.changeType, + [&](Anm2&) + { + auto newPath = window_asset_path_get(document, dialogPath); + auto pathString = path::to_utf8(newPath); + if (isWritten) + { + WorkingDirectory workingDirectory(document.directory_get()); + path::ensure_directory(newPath.parent_path()); + if (!texture->write_png(newPath)) + { + toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); + return; + } + } + spritesheet->path = newPath; + if (isWritten) + document.texturePaths[id] = newPath; + else + document.texture_reload(id); + document.spritesheet_hash_set_saved(id); + toast_log(Level::INFO, isWritten ? TOAST_SAVE_SPRITESHEET : TOAST_REPLACE_SPRITESHEET, + id, pathString); + }); }}); } void spritesheet_textures_edit(Document& document, StringType edit, Document::ChangeType changeType, const std::function& behavior, StringType successToast, StringType failToast) { - document.snapshots.anm2_textures_push(localize.get(edit)); + document.edit_begin(edit, true); auto isSuccess = behavior(); toast_log(isSuccess ? Level::INFO : Level::ERROR, isSuccess ? successToast : failToast); document.change(changeType); @@ -178,26 +178,26 @@ namespace anm2ed::imgui auto unused = document.anm2.element_unused(ElementType::SPRITESHEET); auto spritesheets = window_container_get(window, document); if (unused.empty() || !spritesheets) return; - window_edit(document, window.changeType, localize.get(EDIT_REMOVE_UNUSED_SPRITESHEETS), - [&]() - { - for (auto id : unused) - if (auto spritesheet = window_element_get(window, document, id)) - { - toast_log(Level::INFO, TOAST_REMOVE_SPRITESHEET, id, path::to_utf8(spritesheet->path)); - element_child_id_erase(*spritesheets, ElementType::SPRITESHEET, id); - } - }); + document.edit_apply(EDIT_REMOVE_UNUSED_SPRITESHEETS, window.changeType, + [&](Anm2&) + { + for (auto id : unused) + if (auto spritesheet = window_element_get(window, document, id)) + { + toast_log(Level::INFO, TOAST_REMOVE_SPRITESHEET, id, path::to_utf8(spritesheet->path)); + element_child_id_erase(*spritesheets, ElementType::SPRITESHEET, id); + } + }); }; window.reload = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { auto selected = document.spritesheet.selection; - window_edit(document, window.changeType, localize.get(EDIT_RELOAD_SPRITESHEETS), - [&]() - { - for (auto id : selected) - document.texture_reload(id); - }); + document.edit_apply(EDIT_RELOAD_SPRITESHEETS, window.changeType, + [&](Anm2&) + { + for (auto id : selected) + document.texture_reload(id); + }); for (auto id : selected) if (auto spritesheet = window_element_get(window, document, id)) { diff --git a/src/imgui/window/timeline/context.hpp b/src/imgui/window/timeline/context.hpp index 519108e..5ddfb84 100644 --- a/src/imgui/window/timeline/context.hpp +++ b/src/imgui/window/timeline/context.hpp @@ -129,21 +129,6 @@ namespace anm2ed::imgui {ITEM_COLOR_LIGHT_ACTIVE, TYPE_COLOR_ACTIVE}, {ITEM_COLOR_LIGHT_SELECTED, TYPE_COLOR_ACTIVE}}; - enum class SnapshotKind - { - ANM2, - TRACKS, - FRAMES - }; - - inline void snapshot_take(Document& document, const std::string& message, SnapshotKind kind, - const std::set& references) - { - if (kind == SnapshotKind::ANM2) document.snapshots.anm2_push(message); - if (kind == SnapshotKind::TRACKS) document.snapshots.tracks_push(message, references); - if (kind == SnapshotKind::FRAMES) document.snapshots.frames_push(message, references); - } - inline bool is_trigger_reference(const Reference& reference) { return reference.itemType == TRIGGER; } constexpr resource::icon::Type INTERPOLATION_ICONS[] = {resource::icon::UNINTERPOLATED, resource::icon::INTERPOLATED, @@ -220,22 +205,24 @@ namespace anm2ed::imgui bool is_track_group_visible(int type, int groupId); Element* row_group_get(const TimelineItemRow& row); int group_items_count_get(int type, int groupId); - Element* command_item_get(Document& document, int animationIndex, int type, int id, int groupType = NONE, - int groupId = -1); Element* command_item_reference_get(Document& document, Reference itemReference); glm::vec4 color_get(TimelineColor, int); - template std::map> frames_by_item_get(const Range& frameReferences) - { - std::map> result{}; - for (auto frameReference : frameReferences) - result[item_reference_from_frame_get(frameReference)].insert(frameReference.frameIndex); - return result; - } void frames_focus_sync_for(Document&); std::set drag_frame_references_get(const Reference&); - void snapshot_command_push(StringType, SnapshotKind, const std::set&); - void edit_command_push(StringType, Document::ChangeType, std::function, - SnapshotKind = SnapshotKind::ANM2, const std::set& = {}); + // Queues an edit on the document; its result is selected (frames by default). + template + void edit_push(StringType label, Document::ChangeType type, Operation operation, + std::function select = {}) + { + command_push( + [=, this](Manager&, Document& document) mutable + { + auto uids = document.edit_apply(label, type, operation); + select ? select(document, uids) : frames_select_for(document, uids); + }); + } + void edit_begin_push(StringType); + void frames_select_for(Document&, const edit::Uids&); Element* command_frame_get(Document& document, const Reference& targetReference); Reference item_reference_get(int type, int id, int groupType = NONE, int groupId = -1); Reference item_reference_from_frame_get(Reference frameReference); @@ -257,11 +244,9 @@ namespace anm2ed::imgui void reference_set_item_reference_for(Document& targetDocument, Reference itemReference); void reference_set_timeline_item_reference_for(Document& targetDocument, Reference itemReference); void command_push(std::function run); - std::set track_references_from_frame_references_get(std::set frameReferences); void overlay_icon(GLuint textureId, ImVec4 tint, bool isForced = false); void playback_stop(); void frame_insert(); - void frames_delete_for(Document& document, std::set selectedFrames); void frames_delete_action(); void frames_duplicate(); bool is_frames_reverse_available(std::set selectedFrames); @@ -273,8 +258,6 @@ namespace anm2ed::imgui BakeIntoOtherFramesTarget target, bool isLayers, bool isNulls); bool is_bake_into_other_frames_ready(); - void frame_root_transform_apply(Element& frame, const Element& rootFrame, bool isRoundScale, bool isRoundRotation, - bool isUseRootPivot); void bake_into_other_frames(); void frame_split(); void reference_clear(); diff --git a/src/imgui/window/timeline/edit.cpp b/src/imgui/window/timeline/edit.cpp index a62ab4b..0bc633b 100644 --- a/src/imgui/window/timeline/edit.cpp +++ b/src/imgui/window/timeline/edit.cpp @@ -5,98 +5,19 @@ namespace anm2ed::imgui void TimelineContext::frame_insert() { auto targetReference = reference; - auto targetFrameTime = document.frameTime; + auto time = (int)document.frameTime; if (!animation || !command_item_reference_get(document, targetReference)) return; - - edit_command_push(EDIT_INSERT_FRAME, Document::FRAMES, - [=, this](Manager&, Document& document) mutable - { - auto animation = - document.anm2.element_get(ElementType::ANIMATION, targetReference.animationIndex); - auto item = command_item_reference_get(document, targetReference); - if (!animation || !item) return; - - auto newReference = targetReference; - - if (targetReference.itemType == TRIGGER) - { - for (auto& trigger : item->children) - if (targetFrameTime == trigger.atFrame) return; - - auto addFrame = element_make(ElementType::TRIGGER); - addFrame.atFrame = targetFrameTime; - item->children.push_back(addFrame); - frames_sort_by_at_frame(*item); - newReference.frameIndex = frame_index_from_at_frame_get(*item, addFrame.atFrame); - } - else - { - auto frame = command_frame_get(document, targetReference); - auto framesCount = track_frames_count_get(*item); - if (frame) - { - auto addFrame = *frame; - auto insertIndex = std::clamp(targetReference.frameIndex + 1, 0, framesCount); - auto childIndex = track_frame_insert_child_index_get(*item, insertIndex); - item->children.insert(item->children.begin() + childIndex, addFrame); - newReference.frameIndex = insertIndex; - } - else if (auto lastFrame = track_frame_get(*item, framesCount - 1)) - { - item->children.emplace_back(*lastFrame); - newReference.frameIndex = framesCount; - } - else - { - item->children.emplace_back(element_make(ElementType::FRAME)); - newReference.frameIndex = 0; - } - } - - document.reference = newReference; - frames_selection_set_reference_for(document); - if (newReference.itemType != TRIGGER) - document.frameTime = frame_time_from_index_get(*item, newReference.frameIndex); - }, - SnapshotKind::TRACKS, {targetReference}); - } - - void TimelineContext::frames_delete_for(Document& document, std::set selectedFrames) - { - auto groupedFrames = frames_by_item_get(selectedFrames); - - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; - - for (auto it = indices.rbegin(); it != indices.rend(); ++it) - { - auto childIndex = track_frame_child_index_get(*item, *it); - if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); - } - } - - auto item = command_item_reference_get(document, document.reference); - if (!item || item->children.empty()) - { - document.reference.frameIndex = -1; - frames_selection_reset_for(document); - return; - } - - document.reference.frameIndex = glm::clamp(document.reference.frameIndex, 0, (int)item->children.size() - 1); - frames_selection_set_reference_for(document); + edit_push(EDIT_INSERT_FRAME, Document::FRAMES, + [=](Anm2& anm2) { return edit::frame_insert(anm2, targetReference, time); }); } void TimelineContext::frames_delete_action() { auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); if (selectedFrames.empty()) return; - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - edit_command_push( - EDIT_DELETE_FRAMES, Document::FRAMES, [=, this](Manager&, Document& document) mutable - { frames_delete_for(document, selectedFrames); }, SnapshotKind::TRACKS, trackReferences); + edit_push( + EDIT_DELETE_FRAMES, Document::FRAMES, [=](Anm2& anm2) { return edit::frames_delete(anm2, selectedFrames); }, + [this](Document& document, const edit::Uids&) { frames_selection_set_reference_for(document); }); } void TimelineContext::frames_duplicate() @@ -104,63 +25,8 @@ namespace anm2ed::imgui auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); std::erase_if(selectedFrames, is_trigger_reference); if (selectedFrames.empty()) return; - - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - edit_command_push( - EDIT_DUPLICATE_FRAMES, Document::FRAMES, - [=, this](Manager&, Document& document) mutable - { - auto groupedFrames = frames_by_item_get(selectedFrames); - - std::set duplicatedSelection{}; - auto newReference = document.reference; - bool isReferenceSet{}; - - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; - - std::vector validIndices{}; - std::vector duplicatedFrames{}; - for (auto i : indices) - { - auto frame = track_frame_get(*item, i); - if (!frame) continue; - validIndices.push_back(i); - duplicatedFrames.push_back(*frame); - } - if (validIndices.empty()) continue; - - auto insertIndex = validIndices.back() + 1; - auto childIndex = track_frame_insert_child_index_get(*item, insertIndex); - item->children.insert(item->children.begin() + childIndex, - std::make_move_iterator(duplicatedFrames.begin()), - std::make_move_iterator(duplicatedFrames.end())); - - for (int offset = 0; offset < (int)validIndices.size(); ++offset) - { - auto targetReference = itemReference; - targetReference.frameIndex = insertIndex + offset; - duplicatedSelection.insert(targetReference); - auto sourceReference = itemReference; - sourceReference.frameIndex = validIndices[offset]; - if (sourceReference == document.reference) - { - newReference = targetReference; - isReferenceSet = true; - } - } - } - - if (duplicatedSelection.empty()) return; - document.reference = isReferenceSet ? newReference : *duplicatedSelection.begin(); - document.frame_references_set(std::move(duplicatedSelection)); - if (auto item = command_item_reference_get(document, document.reference)) - document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); - frames_focus_sync_for(document); - }, - SnapshotKind::TRACKS, trackReferences); + edit_push(EDIT_DUPLICATE_FRAMES, Document::FRAMES, + [=, focus = reference](Anm2& anm2) { return edit::frames_duplicate(anm2, selectedFrames, focus); }); } bool TimelineContext::is_frames_reverse_available(std::set selectedFrames) @@ -180,126 +46,19 @@ namespace anm2ed::imgui auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); std::erase_if(selectedFrames, is_trigger_reference); if (!is_frames_reverse_available(selectedFrames)) return; - - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - edit_command_push( - EDIT_REVERSE_FRAMES, Document::FRAMES, - [=, this](Manager&, Document& document) mutable - { - auto groupedFrames = frames_by_item_get(selectedFrames); - - std::set reversedSelection{}; - auto newReference = document.reference; - bool isReferenceSet{}; - - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item || indices.size() < 2) continue; - - std::vector validIndices{}; - std::vector reversedFrames{}; - for (auto i : indices) - { - auto frame = track_frame_get(*item, i); - if (!frame) continue; - validIndices.push_back(i); - reversedFrames.push_back(std::move(*frame)); - } - if (validIndices.size() < 2) continue; - - auto insertIndex = validIndices.front(); - for (auto it = validIndices.rbegin(); it != validIndices.rend(); ++it) - { - auto childIndex = track_frame_child_index_get(*item, *it); - if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); - } - - std::ranges::reverse(reversedFrames); - auto childIndex = track_frame_insert_child_index_get(*item, insertIndex); - item->children.insert(item->children.begin() + childIndex, std::make_move_iterator(reversedFrames.begin()), - std::make_move_iterator(reversedFrames.end())); - - for (int offset = 0; offset < (int)validIndices.size(); ++offset) - { - auto targetReference = itemReference; - targetReference.frameIndex = insertIndex + offset; - reversedSelection.insert(targetReference); - auto sourceIndex = validIndices[(int)validIndices.size() - 1 - offset]; - auto sourceReference = itemReference; - sourceReference.frameIndex = sourceIndex; - if (sourceReference == document.reference) - { - newReference = targetReference; - isReferenceSet = true; - } - } - } - - if (reversedSelection.empty()) return; - document.reference = isReferenceSet ? newReference : *reversedSelection.begin(); - document.frame_references_set(std::move(reversedSelection)); - if (auto item = command_item_reference_get(document, document.reference)) - document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); - frames_focus_sync_for(document); - }, - SnapshotKind::TRACKS, trackReferences); + edit_push(EDIT_REVERSE_FRAMES, Document::FRAMES, + [=](Anm2& anm2) { return edit::frames_reverse(anm2, selectedFrames); }); } void TimelineContext::frames_bake() { auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); - auto bakeInterval = settings.bakeInterval; - auto isRoundScale = settings.bakeIsRoundScale; - auto isRoundRotation = settings.bakeIsRoundRotation; std::erase_if(selectedFrames, is_trigger_reference); if (selectedFrames.empty()) return; - - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - edit_command_push( - EDIT_BAKE_FRAMES, Document::FRAMES, - [=, this](Manager&, Document& document) mutable - { - auto groupedFrames = frames_by_item_get(selectedFrames); - - std::set bakedSelection{}; - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; - - int insertedBefore = 0; - for (auto originalIndex : indices) - { - auto i = originalIndex + insertedBefore; - auto frame = track_frame_get(*item, i); - if (!frame) continue; - - auto originalDuration = frame->duration; - frame_bake(*item, i, bakeInterval, isRoundScale, isRoundRotation); - - auto bakedCount = - originalDuration <= FRAME_DURATION_MIN ? 1 : (int)std::ceil((float)originalDuration / bakeInterval); - for (int offset = 0; offset < bakedCount; ++offset) - { - auto frameReference = itemReference; - frameReference.frameIndex = i + offset; - bakedSelection.insert(frameReference); - } - - insertedBefore += bakedCount - 1; - } - } - - document.frame_references_set(std::move(bakedSelection)); - if (!document.frames.references.empty()) - { - frames_focus_sync_for(document); - } - else - frames_selection_reset_for(document); - }, - SnapshotKind::TRACKS, trackReferences); + edit_push(EDIT_BAKE_FRAMES, Document::FRAMES, + [=, interval = settings.bakeInterval, isRoundScale = settings.bakeIsRoundScale, + isRoundRotation = settings.bakeIsRoundRotation](Anm2& anm2) + { return edit::frames_bake(anm2, selectedFrames, interval, isRoundScale, isRoundRotation); }); } std::set TimelineContext::selected_root_frame_references_get() @@ -350,158 +109,16 @@ namespace anm2ed::imgui return !targetItems.empty(); } - void TimelineContext::frame_root_transform_apply(Element& frame, const Element& rootFrame, bool isRoundScale, - bool isRoundRotation, bool isUseRootPivot) - { - auto rootScale = math::percent_to_unit(rootFrame.scale); - auto pivot = isUseRootPivot ? rootFrame.position : glm::vec2(); - auto offset = (frame.position - pivot) * rootScale; - auto radians = glm::radians(rootFrame.rotation); - auto cos = std::cos(radians); - auto sin = std::sin(radians); - - frame.position = rootFrame.position + glm::vec2(offset.x * cos - offset.y * sin, offset.x * sin + offset.y * cos); - frame.scale *= rootScale; - frame.rotation += rootFrame.rotation; - frame.tint *= rootFrame.tint; - frame.colorOffset += rootFrame.colorOffset; - - if (isRoundScale) frame.scale = glm::round(frame.scale); - if (isRoundRotation) frame.rotation = std::round(frame.rotation); - } - void TimelineContext::bake_into_other_frames() { auto selectedRootFrames = selected_root_frame_references_get(); - if (selectedRootFrames.empty()) return; - if (!animation) return; - auto target = bakeIntoOtherFramesTarget; - auto isLayers = isBakeIntoOtherFramesLayers; - auto isNulls = isBakeIntoOtherFramesNulls; - auto isRoundScale = settings.bakeIsRoundScale; - auto isRoundRotation = settings.bakeIsRoundRotation; - auto isMatchRootInterpolation = settings.bakeIsMatchRootInterpolation; - auto isUseRootPivot = settings.bakeIsUseRootPivot; + if (selectedRootFrames.empty() || !animation) return; auto targetItems = item_references_for_bake_into_other_frames_get( - document, *animation, target, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); - auto trackReferences = track_references_from_frame_references_get(selectedRootFrames); - trackReferences.insert(targetItems.begin(), targetItems.end()); - edit_command_push( - EDIT_BAKE_INTO_OTHER_FRAMES, Document::FRAMES, - [=, this](Manager&, Document& document) mutable - { - auto animation = document.anm2.element_get(ElementType::ANIMATION, document.reference.animationIndex); - if (!animation) return; - auto rootItemReference = item_reference_from_frame_get(*selectedRootFrames.begin()); - for (auto rootReference : selectedRootFrames) - if (!is_same_item(rootReference, rootItemReference)) return; - auto root = command_item_reference_get(document, rootItemReference); - if (!root) return; - - std::vector spans{}; - for (auto rootReference : selectedRootFrames) - { - auto rootFrame = command_frame_get(document, rootReference); - if (!rootFrame) continue; - auto start = (int)frame_time_from_index_get(*root, rootReference.frameIndex); - spans.push_back({start, start + rootFrame->duration}); - } - if (spans.empty()) return; - auto is_spanned = [&](int time) - { - return std::ranges::any_of(spans, - [&](RootFrameSpan span) { return time >= span.start && time < span.end; }); - }; - - auto targetItems = - item_references_for_bake_into_other_frames_get(document, *animation, target, isLayers, isNulls); - if (targetItems.empty()) return; - - for (auto itemReference : targetItems) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; - - if (isMatchRootInterpolation) - { - std::vector bakeIndices{}; - auto frameType = track_frame_type_get(*item); - int frameIndex{}; - for (const auto& frame : item->children) - { - if (frame.type != frameType) continue; - if (is_spanned((int)frame_time_from_index_get(*item, frameIndex))) bakeIndices.push_back(frameIndex); - ++frameIndex; - } - for (auto it = bakeIndices.rbegin(); it != bakeIndices.rend(); ++it) - frame_bake(*item, *it, FRAME_DURATION_MIN, isRoundScale, isRoundRotation); - } - - auto frameType = track_frame_type_get(*item); - int frameIndex{}; - for (auto& frame : item->children) - { - if (frame.type != frameType) continue; - auto frameStart = (int)frame_time_from_index_get(*item, frameIndex++); - if (is_spanned(frameStart)) - frame_root_transform_apply(frame, frame_generate(*root, (float)frameStart), isRoundScale, - isRoundRotation, isUseRootPivot); - } - } - - std::set selectedRootFrameIndices{}; - for (auto rootReference : selectedRootFrames) - { - auto rootFrame = command_frame_get(document, rootReference); - if (!rootFrame) continue; - selectedRootFrameIndices.insert(rootReference.frameIndex); - } - if (selectedRootFrameIndices.empty()) return; - - std::vector rootFrames{}; - std::set defaultRootSelection{}; - int frameIndex{}; - int rewrittenFrameIndex{}; - int defaultDuration{}; - auto default_root_frame_push = [&]() - { - if (defaultDuration <= 0) return; - auto frame = element_make(ElementType::FRAME); - frame.duration = glm::max(defaultDuration, FRAME_DURATION_MIN); - auto defaultRootReference = rootItemReference; - defaultRootReference.frameIndex = rewrittenFrameIndex; - defaultRootSelection.insert(defaultRootReference); - rootFrames.push_back(frame); - ++rewrittenFrameIndex; - defaultDuration = 0; - }; - - for (const auto& frame : root->children) - { - if (frame.type != ElementType::FRAME) - { - default_root_frame_push(); - rootFrames.push_back(frame); - continue; - } - - if (selectedRootFrameIndices.contains(frameIndex)) - defaultDuration += frame.duration; - else - { - default_root_frame_push(); - rootFrames.push_back(frame); - ++rewrittenFrameIndex; - } - ++frameIndex; - } - default_root_frame_push(); - - root->children = std::move(rootFrames); - document.frame_references_set(std::move(defaultRootSelection)); - frames_focus_sync_for(document); - }, - SnapshotKind::TRACKS, trackReferences); + document, *animation, bakeIntoOtherFramesTarget, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); + edit::RootBakeOptions options{settings.bakeIsRoundScale, settings.bakeIsRoundRotation, + settings.bakeIsMatchRootInterpolation, settings.bakeIsUseRootPivot}; + edit_push(EDIT_BAKE_INTO_OTHER_FRAMES, Document::FRAMES, + [=](Anm2& anm2) { return edit::root_bake_into(anm2, selectedRootFrames, targetItems, options); }); } void TimelineContext::frame_split() @@ -509,93 +126,26 @@ namespace anm2ed::imgui auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); if (selectedFrames.size() != 1) return; auto targetReference = *selectedFrames.begin(); - auto splitTime = frameSplitTimeAtCursor.value_or((int)std::floor(playback.time)); - if (targetReference.itemType == TRIGGER) return; - - edit_command_push( - EDIT_SPLIT_FRAME, Document::FRAMES, - [=, this](Manager&, Document& document) mutable - { - if (targetReference.itemType == TRIGGER) return; - - auto item = command_item_reference_get(document, targetReference); - auto frame = command_frame_get(document, targetReference); - - if (!item || !frame) return; - - auto originalDuration = frame->duration; - if (originalDuration <= 1) return; - - auto frameStartTime = frame_time_from_index_get(*item, targetReference.frameIndex); - int frameStart = (int)std::round(frameStartTime); - int firstDuration = splitTime - frameStart + 1; - - if (firstDuration <= 0 || firstDuration >= originalDuration) return; - - int secondDuration = originalDuration - firstDuration; - auto splitFrame = *frame; - splitFrame.duration = secondDuration; - - auto nextFrame = track_frame_get(*item, targetReference.frameIndex + 1); - if (frame->interpolation != Interpolation::NONE && nextFrame) - frame_mix(splitFrame, *nextFrame, - interpolation_factor(frame->interpolation, (float)firstDuration / (float)originalDuration)); - - frame->duration = firstDuration; - auto insertIndex = track_frame_insert_child_index_get(*item, targetReference.frameIndex + 1); - item->children.insert(item->children.begin() + insertIndex, splitFrame); - document.reference = targetReference; - frames_selection_set_reference_for(document); - }, - SnapshotKind::TRACKS, {targetReference}); + auto time = frameSplitTimeAtCursor.value_or((int)std::floor(playback.time)); + edit_push(EDIT_SPLIT_FRAME, Document::FRAMES, + [=](Anm2& anm2) { return edit::frame_split(anm2, targetReference, time); }); } void TimelineContext::item_remove() { - auto targetRows = selected_row_references_get(); - std::map> targetIds{}; - std::map> targetGroupIds{}; - for (auto row : targetRows) - { - if (row.type != LAYER && row.type != NULL_) continue; - if (row.isGroup) - targetGroupIds[row.type].insert(row.id); - else - targetIds[row.type].insert(row.id); - } - auto animationIndex = reference.animationIndex; - if (!animation) return; - if (targetIds.empty() && targetGroupIds.empty()) return; - edit_command_push(EDIT_REMOVE_ITEMS, Document::ITEMS, - [=, this](Manager&, Document& document) mutable - { - auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); - if (!animation) return; - for (auto targetType : {LAYER, NULL_}) - { - auto containerType = TYPE_CONTAINERS[targetType]; - auto targetTrackType = TYPE_TRACKS[targetType]; - auto container = child_first_get(*animation, containerType); - if (!container) continue; - auto ids = targetIds.contains(targetType) ? targetIds.at(targetType) : std::set{}; - auto groupIds = - targetGroupIds.contains(targetType) ? targetGroupIds.at(targetType) : std::set{}; - for (int i = (int)container->children.size() - 1; i >= 0; --i) - { - auto& item = container->children[i]; - if (item.type == ElementType::GROUP && groupIds.contains(item.id)) - { - container->children.erase(container->children.begin() + i); - continue; - } - if (item.type == targetTrackType && - (ids.contains(anm2ed::track_id_get(item)) || groupIds.contains(item.groupId))) - container->children.erase(container->children.begin() + i); - } - } - reference_clear_for(document); - group_selection_reset_for(document); - }); + std::map> ids{}; + std::map> groupIds{}; + for (auto row : selected_row_references_get()) + if (row.type == LAYER || row.type == NULL_) (row.isGroup ? groupIds : ids)[row.type].insert(row.id); + if (!animation || (ids.empty() && groupIds.empty())) return; + edit_push( + EDIT_REMOVE_ITEMS, Document::ITEMS, [=, animationIndex = reference.animationIndex](Anm2& anm2) + { return edit::items_remove(anm2, animationIndex, ids, groupIds); }, + [this](Document& document, const edit::Uids&) + { + reference_clear_for(document); + group_selection_reset_for(document); + }); } std::vector TimelineContext::item_references_groupable_get() @@ -625,51 +175,21 @@ namespace anm2ed::imgui { auto targetReferences = item_references_groupable_get(); if (targetReferences.empty()) return; - auto targetType = targetReferences.front().itemType; - auto animationIndex = reference.animationIndex; - auto groupName = std::string(localize.get(TEXT_NEW_GROUP)); - - edit_command_push(EDIT_GROUP_ITEMS, Document::ITEMS, - [=, this](Manager&, Document& document) mutable - { - auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); - if (!animation) return; - - auto containerType = TYPE_CONTAINERS[targetType]; - auto targetTrackType = TYPE_TRACKS[targetType]; - auto container = child_first_get(*animation, containerType); - if (!container) return; - - std::set targetIds{}; - for (auto itemReference : targetReferences) - targetIds.insert(itemReference.itemID); - - auto group = element_make(ElementType::GROUP); - group.id = element_child_next_id_get(*container, ElementType::GROUP); - group.name = groupName; - group.children.push_back(root_animation_make()); - int insertIndex = (int)container->children.size(); - - for (int i = 0; i < (int)container->children.size(); ++i) - { - auto& item = container->children[i]; - if (item.type == targetTrackType && targetIds.contains(anm2ed::track_id_get(item))) - { - insertIndex = std::min(insertIndex, i); - item.groupId = group.id; - } - } - - if (insertIndex == (int)container->children.size()) return; - insertIndex = std::clamp(insertIndex, 0, (int)container->children.size()); - container->children.insert(container->children.begin() + insertIndex, group); - - document.items.references.clear(); - for (auto itemReference : targetReferences) - document.items.references.insert(itemReference); - document.reference = targetReferences.front(); - frames_selection_reset_for(document); - }); + std::set ids{}; + for (auto itemReference : targetReferences) + ids.insert(itemReference.itemID); + edit_push( + EDIT_GROUP_ITEMS, Document::ITEMS, + [=, animationIndex = reference.animationIndex, type = targetReferences.front().itemType, + name = std::string(localize.get(TEXT_NEW_GROUP))](Anm2& anm2) + { return edit::items_group(anm2, animationIndex, type, ids, name); }, + [=, this](Document& document, const edit::Uids& uids) + { + if (uids.empty()) return; + document.items.references = {targetReferences.begin(), targetReferences.end()}; + document.reference = targetReferences.front(); + frames_selection_reset_for(document); + }); } void TimelineContext::rows_move_to_row(std::vector draggedRows, TimelineItemRow targetRow, @@ -678,126 +198,37 @@ namespace anm2ed::imgui if (draggedRows.empty()) return; auto targetType = draggedRows.front().type; if (targetType != LAYER && targetType != NULL_) return; - for (const auto& draggedRow : draggedRows) - if (draggedRow.type != targetType) return; - + if (std::ranges::any_of(draggedRows, [&](const auto& row) { return row.type != targetType; })) return; if (targetRow.isGroup && targetRow.type != targetType) return; if (!targetRow.isGroup && targetRow.type != targetType && targetRow.type != NONE && targetRow.type != ROOT && targetRow.type != TRIGGER) return; + std::set ids{}; + std::set groupIds{}; + for (const auto& row : draggedRows) + (row.isGroup ? groupIds : ids).insert(row.id); + edit::RowTarget target{targetRow.isGroup, targetRow.type, targetRow.id, targetRow.groupId}; auto animationIndex = reference.animationIndex; - edit_command_push( + + edit_push( EDIT_MOVE_ITEMS, Document::ITEMS, - [=, this](Manager&, Document& document) mutable + [=](Anm2& anm2) + { + return edit::items_move(anm2, animationIndex, targetType, ids, groupIds, target, isDropAfter, + isDropIntoGroup); + }, + [=, this](Document& document, const edit::Uids&) { - auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); - if (!animation) return; - auto container = child_first_get(*animation, TYPE_CONTAINERS[targetType]); - if (!container) return; - auto targetTrackType = TYPE_TRACKS[targetType]; - - std::set draggedIds{}; - std::set draggedGroupIds{}; - for (const auto& draggedRow : draggedRows) - { - if (draggedRow.isGroup) - draggedGroupIds.insert(draggedRow.id); - else - draggedIds.insert(draggedRow.id); - } - - if (targetRow.groupId != -1 && draggedGroupIds.contains(targetRow.groupId)) return; - - auto is_dragged = [&](const Element& item) - { - return (item.type == ElementType::GROUP && draggedGroupIds.contains(item.id)) || - (item.type == targetTrackType && - (draggedIds.contains(anm2ed::track_id_get(item)) || draggedGroupIds.contains(item.groupId))); - }; - std::vector movedItems{}; - std::ranges::copy_if(container->children, std::back_inserter(movedItems), is_dragged); - if (movedItems.empty()) return; - - if (targetRow.isGroup && draggedGroupIds.contains(targetRow.id)) return; - - auto row_index_get = [&](const TimelineItemRow& row) - { - for (int i = 0; i < (int)container->children.size(); ++i) - { - auto& item = container->children[i]; - if (row.isGroup && item.type == ElementType::GROUP && item.id == row.id) return i; - if (!row.isGroup && row.type == targetType && item.type == targetTrackType && - anm2ed::track_id_get(item) == row.id) - return i; - } - return -1; - }; - auto group_end_index_get = [&](int groupId) - { - int result = -1; - for (int i = 0; i < (int)container->children.size(); ++i) - { - auto& item = container->children[i]; - if (item.type == ElementType::GROUP && item.id == groupId) result = std::max(result, i); - if (item.type == targetTrackType && item.groupId == groupId) result = std::max(result, i); - } - return result; - }; - - int targetIndex = (int)container->children.size(); - if (targetRow.isGroup || targetRow.type == targetType) - { - auto rowIndex = row_index_get(targetRow); - if (rowIndex == -1) return; - if (targetRow.isGroup) - { - auto groupEndIndex = group_end_index_get(targetRow.id); - if (targetType == LAYER) - targetIndex = isDropAfter ? rowIndex : groupEndIndex + 1; - else - targetIndex = rowIndex + isDropAfter; - } - else - targetIndex = rowIndex + (targetType == LAYER ? !isDropAfter : isDropAfter); - } - - int removedBeforeTarget = 0; - for (int i = (int)container->children.size() - 1; i >= 0; --i) - { - if (is_dragged(container->children[i])) - { - if (i < targetIndex) ++removedBeforeTarget; - container->children.erase(container->children.begin() + i); - } - } - - auto targetGroupId = -1; - if (targetRow.isGroup && isDropIntoGroup) - targetGroupId = targetRow.id; - else if (targetRow.type == targetType) - targetGroupId = targetRow.groupId; - - for (auto& item : movedItems) - if (item.type == targetTrackType && !draggedGroupIds.contains(item.groupId)) item.groupId = targetGroupId; - - targetIndex -= removedBeforeTarget; - targetIndex = std::clamp(targetIndex, 0, (int)container->children.size()); - container->children.insert(container->children.begin() + targetIndex, movedItems.begin(), movedItems.end()); - document.items.references.clear(); document.groupReferences.clear(); - for (const auto& draggedRow : draggedRows) - { - if (draggedRow.isGroup) - document.groupReferences.insert({draggedRow.animationIndex, draggedRow.type, draggedRow.id}); + for (const auto& row : draggedRows) + if (row.isGroup) + document.groupReferences.insert({row.animationIndex, row.type, row.id}); else - document.items.references.insert(row_item_reference_get(draggedRow)); - } - if (!document.items.references.empty()) - document.reference = *document.items.references.begin(); - else - document.reference = {animationIndex}; + document.items.references.insert(row_item_reference_get(row)); + document.reference = + document.items.references.empty() ? Reference{animationIndex} : *document.items.references.begin(); frames_selection_reset_for(document); }); } @@ -805,14 +236,8 @@ namespace anm2ed::imgui void TimelineContext::fit_animation_length() { if (!animation) return; - auto animationIndex = reference.animationIndex; - edit_command_push(EDIT_FIT_ANIMATION_LENGTH, Document::ANIMATIONS, - [=, this](Manager&, Document& document) - { - auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); - if (!animation) return; - animation->frameNum = animation_length_get(*animation); - }); + edit_push(EDIT_FIT_ANIMATION_LENGTH, Document::ANIMATIONS, [animationIndex = reference.animationIndex](Anm2& anm2) + { return edit::animation_length_fit(anm2, animationIndex); }); } void TimelineContext::frame_references_copy(const std::set& selectedFrames) @@ -845,94 +270,34 @@ namespace anm2ed::imgui auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); if (selectedFrames.empty()) return; frame_references_copy(selectedFrames); - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - edit_command_push( - EDIT_CUT_FRAMES, Document::FRAMES, [=, this](Manager&, Document& document) mutable - { frames_delete_for(document, selectedFrames); }, SnapshotKind::TRACKS, trackReferences); + edit_push( + EDIT_CUT_FRAMES, Document::FRAMES, [=](Anm2& anm2) { return edit::frames_delete(anm2, selectedFrames); }, + [this](Document& document, const edit::Uids&) { frames_selection_set_reference_for(document); }); } void TimelineContext::paste() { - auto targetReference = reference; - auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); - auto clipboardString = clipboard.get(); - if (clipboardString.empty()) return; - auto targetHoveredTime = hoveredTime; - auto message = std::string(localize.get(EDIT_PASTE_FRAMES)); - command_push( - [=, this](Manager&, Document& document) mutable + auto text = clipboard.get(); + if (text.empty()) return; + if (!command_item_reference_get(document, reference)) + { + toast_log(Level::WARNING, TOAST_DESERIALIZE_FRAMES_NO_SELECTION); + return; + } + + auto errorString = std::make_shared(); + edit_push( + EDIT_PASTE_FRAMES, Document::FRAMES, + [=, targetReference = reference, + selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE), + time = hoveredTime](Anm2& anm2) + { return edit::frames_paste(anm2, targetReference, selectedFrames, text, time, errorString.get()); }, + [=, this](Document& document, const edit::Uids& uids) { - auto animation = document.anm2.element_get(ElementType::ANIMATION, targetReference.animationIndex); - if (!animation) return; - if (auto item = command_item_reference_get(document, targetReference)) - { - document.snapshots.tracks_push(message, {targetReference}); - std::set indices{}; - std::string errorString{}; - int insertIndex = (int)item->children.size(); - std::set selectedIndices{}; - for (auto frameReference : selectedFrames) - if (is_same_item(frameReference, targetReference)) selectedIndices.insert(frameReference.frameIndex); - - if (!selectedIndices.empty()) - insertIndex = std::min((int)item->children.size(), *selectedIndices.rbegin() + 1); - else if (targetReference.frameIndex >= 0 && targetReference.frameIndex < (int)item->children.size()) - insertIndex = targetReference.frameIndex + 1; - - auto start = targetReference.itemType == TRIGGER ? targetHoveredTime : insertIndex; - if (frames_deserialize(*item, clipboardString, start, indices, &errorString)) - { - if (targetReference.itemType != LAYER) - { - for (auto i : indices) - if (auto frame = track_frame_get(*item, i); frame) - { - frame->regionId = -1; - frame->crop = {}; - frame->size = {}; - frame->pivot = {}; - } - } - else if (targetReference.itemID != -1) - { - auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, targetReference.itemID); - auto spritesheet = - layer ? document.anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; - - for (auto i : indices) - { - auto frame = track_frame_get(*item, i); - if (!frame || frame->regionId == -1) continue; - auto region = - spritesheet ? child_id_get(*spritesheet, ElementType::REGION, frame->regionId) : nullptr; - if (!region) frame->regionId = -1; - } - } - - std::set pastedSelection{}; - for (auto i : indices) - { - auto pastedReference = targetReference; - pastedReference.frameIndex = i; - pastedSelection.insert(pastedReference); - } - document.reference = targetReference; - document.reference.frameIndex = *indices.begin(); - document.frame_references_set(std::move(pastedSelection)); - document.change(Document::FRAMES); - } - else - { - document.snapshots.pendingStep.reset(); - toasts.push(std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED), errorString)); - logger.error( - std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED, anm2ed::ENGLISH), errorString)); - } - } - else - { - toast_log(Level::WARNING, TOAST_DESERIALIZE_FRAMES_NO_SELECTION); - } + if (errorString->empty()) return frames_select_for(document, uids); + toasts.push(std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED), *errorString)); + logger.error( + std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED, anm2ed::ENGLISH), *errorString)); }); } } diff --git a/src/imgui/window/timeline/frames.cpp b/src/imgui/window/timeline/frames.cpp index cf52a22..1b3fb8c 100644 --- a/src/imgui/window/timeline/frames.cpp +++ b/src/imgui/window/timeline/frames.cpp @@ -30,74 +30,18 @@ namespace anm2ed::imgui { return frameReference.itemType == TRIGGER || frameReference.frameIndex < 0; }); if (drag.references.empty()) return; - auto trackReferences = - track_references_from_frame_references_get(std::set(drag.references.begin(), drag.references.end())); - trackReferences.insert({drag.animationIndex, targetType, targetID, -1, targetGroupType, targetGroupId}); - edit_command_push( + Reference target{drag.animationIndex, targetType, targetID, -1, targetGroupType, targetGroupId}; + edit_push( EDIT_MOVE_FRAMES, Document::FRAMES, - [=, this](Manager&, Document& document) mutable + [frames = std::set(drag.references.begin(), drag.references.end()), target, insertIndex](Anm2& anm2) + { return edit::frames_move(anm2, frames, target, insertIndex); }, + [=, this](Document& document, const edit::Uids& uids) { - auto targetItem = - command_item_get(document, drag.animationIndex, targetType, targetID, targetGroupType, targetGroupId); - if (!targetItem) return; - - auto groupedFrames = frames_by_item_get(drag.references); - - int removedBeforeTarget = 0; - std::vector movedFrames; - for (auto& [itemReference, indices] : groupedFrames) - { - auto sourceItem = command_item_reference_get(document, itemReference); - if (!sourceItem) continue; - - for (auto i : indices) - { - auto childIndex = track_frame_child_index_get(*sourceItem, i); - if (childIndex == -1) continue; - movedFrames.push_back(std::move(sourceItem->children[childIndex])); - if (itemReference.itemType == targetType && itemReference.itemID == targetID && - itemReference.groupType == targetGroupType && itemReference.groupId == targetGroupId && - i < insertIndex) - ++removedBeforeTarget; - } - - for (auto it = indices.rbegin(); it != indices.rend(); ++it) - { - auto childIndex = track_frame_child_index_get(*sourceItem, *it); - if (childIndex != -1) sourceItem->children.erase(sourceItem->children.begin() + childIndex); - } - } - - if (movedFrames.empty()) return; - - int desired = std::clamp(insertIndex, 0, track_frames_count_get(*targetItem)); - desired -= removedBeforeTarget; - desired = std::clamp(desired, 0, track_frames_count_get(*targetItem)); - - auto insertPosResult = desired; - auto insertedCount = (int)movedFrames.size(); - auto childIndex = track_frame_insert_child_index_get(*targetItem, insertPosResult); - targetItem->children.insert(targetItem->children.begin() + childIndex, - std::make_move_iterator(movedFrames.begin()), - std::make_move_iterator(movedFrames.end())); - - if (insertedCount <= 0) return; - - std::set movedSelection{}; - for (int offset = 0; offset < insertedCount; ++offset) - movedSelection.insert( - {drag.animationIndex, targetType, targetID, insertPosResult + offset, targetGroupType, targetGroupId}); - - document.reference = {drag.animationIndex, targetType, targetID, - insertPosResult, targetGroupType, targetGroupId}; - document.frame_references_set(std::move(movedSelection)); - document.frameTime = frame_time_from_index_get(*targetItem, document.reference.frameIndex); - frames_focus_sync_for(document); + frames_select_for(document, uids); if (targetType == LAYER) if (auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, targetID)) document.spritesheet.reference = layer->spritesheetId; - }, - SnapshotKind::TRACKS, trackReferences); + }); } ImVec2 TimelineContext::frame_box_content_point_get() @@ -487,16 +431,13 @@ namespace anm2ed::imgui if (ImGui::IsKeyDown(ImGuiMod_Alt)) { auto targetReference = frameReference; - edit_command_push(EDIT_FRAME_INTERPOLATION, Document::FRAMES, - [=, this](Manager&, Document& document) - { - auto frame = command_frame_get(document, targetReference); - if (!frame) return; - frame->interpolation = frame->interpolation == Interpolation::NONE - ? Interpolation::LINEAR - : Interpolation::NONE; - }, - SnapshotKind::FRAMES, {targetReference}); + edit_push(EDIT_FRAME_INTERPOLATION, Document::FRAMES, + [=](Anm2& anm2) + { + if (auto frame = anm2.element_get(targetReference)) + frame->interpolation = frame->interpolation == Interpolation::NONE ? Interpolation::LINEAR + : Interpolation::NONE; + }); } document.frameTime = frameTime; @@ -653,68 +594,28 @@ namespace anm2ed::imgui if (!isDraggedFrameSnapshot && isDraggedFrameChanged) { isDraggedFrameSnapshot = true; - if (draggedFrameType == TRIGGER) - snapshot_command_push(EDIT_TRIGGER_AT_FRAME, SnapshotKind::TRACKS, - {item_reference_from_frame_get(draggedFrameReference)}); - else - { - std::set draggedFrameReferences{}; - if (draggedFrameStartDurations.empty()) - draggedFrameReferences.insert(draggedFrameReference); - else - for (auto& frameDuration : draggedFrameStartDurations) - draggedFrameReferences.insert(frameDuration.reference); - snapshot_command_push(EDIT_FRAME_DURATION, SnapshotKind::FRAMES, draggedFrameReferences); - } + edit_begin_push(draggedFrameType == TRIGGER ? EDIT_TRIGGER_AT_FRAME : EDIT_FRAME_DURATION); } if (isDraggedFrameSnapshot) { auto targetReference = draggedFrameReference; - auto targetType = draggedFrameType; - auto targetIndex = draggedFrameIndex; - auto targetStartDuration = draggedFrameStartDuration; - auto targetStartDurations = draggedFrameStartDurations; - auto targetHoveredTime = hoveredTime; - auto targetDurationDelta = durationDelta; - auto isPlaybackClamp = settings.playbackIsClamp; - auto animationLength = animation ? animation->frameNum : FRAME_NUM_MAX; - command_push( - [=, this](Manager&, Document& document) - { - auto item = command_item_reference_get(document, targetReference); - auto frame = command_frame_get(document, targetReference); - if (!item || !frame) return; - - if (targetType == TRIGGER) - { - frame->atFrame = - glm::clamp(targetHoveredTime, 0, isPlaybackClamp ? animationLength - 1 : FRAME_NUM_MAX - 1); - - for (auto [i, trigger] : std::views::enumerate(item->children)) - { - if ((int)i == targetIndex) continue; - if (trigger.atFrame == frame->atFrame) frame->atFrame--; - } - } - else - { - if (targetStartDurations.empty()) - { - frame->duration = - glm::clamp(targetStartDuration + targetDurationDelta, FRAME_DURATION_MIN, FRAME_DURATION_MAX); - return; - } - - for (auto frameDuration : targetStartDurations) - { - auto targetFrame = command_frame_get(document, frameDuration.reference); - if (!targetFrame) continue; - targetFrame->duration = - glm::clamp(frameDuration.duration + targetDurationDelta, FRAME_DURATION_MIN, FRAME_DURATION_MAX); - } - } - }); + if (draggedFrameType == TRIGGER) + { + auto atFrame = glm::clamp( + hoveredTime, 0, settings.playbackIsClamp && animation ? animation->frameNum - 1 : FRAME_NUM_MAX - 1); + command_push([=](Manager&, Document& document) + { edit::trigger_at_frame_set(document.anm2, targetReference, atFrame); }); + } + else + { + std::map durations{}; + if (draggedFrameStartDurations.empty()) + durations[targetReference] = draggedFrameStartDuration + durationDelta; + for (auto frameDuration : draggedFrameStartDurations) + durations[frameDuration.reference] = frameDuration.duration + durationDelta; + command_push([=](Manager&, Document& document) { edit::frame_durations_set(document.anm2, durations); }); + } } if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) @@ -990,13 +891,13 @@ namespace anm2ed::imgui if (isLengthChanged && animation) { auto animationIndex = animationLengthEditIndex != -1 ? animationLengthEditIndex : currentAnimationIndex; - edit_command_push(EDIT_ANIMATION_LENGTH, Document::ANIMATIONS, - [=, this](Manager&, Document& document) - { - auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); - if (!animation) return; - animation->frameNum = frameNum; - }); + edit_push(EDIT_ANIMATION_LENGTH, Document::ANIMATIONS, + [=](Anm2& anm2) + { + auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex); + if (!animation) return; + animation->frameNum = frameNum; + }); } if (ImGui::IsItemDeactivated()) animationLengthEditIndex = -1; ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ANIMATION_LENGTH)); @@ -1008,13 +909,13 @@ namespace anm2ed::imgui if (ImGui::Checkbox(localize.get(LABEL_LOOP), &isLoop) && animation) { auto animationIndex = reference.animationIndex; - edit_command_push(EDIT_LOOP, Document::ANIMATIONS, - [=, this](Manager&, Document& document) - { - auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); - if (!animation) return; - animation->isLoop = isLoop; - }); + edit_push(EDIT_LOOP, Document::ANIMATIONS, + [=](Anm2& anm2) + { + auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex); + if (!animation) return; + animation->isLoop = isLoop; + }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LOOP_ANIMATION)); } @@ -1027,17 +928,17 @@ namespace anm2ed::imgui ImGui::SetNextItemWidth(widgetSize.x); if (input_int_range(localize.get(LABEL_FPS), fps, FPS_MIN, FPS_MAX)) { - edit_command_push(EDIT_FPS, Document::INFO, - [=, this](Manager&, Document& document) - { - auto info = element_first_get(document.anm2.root, ElementType::INFO); - if (!info) - { - document.anm2.root.children.push_back(element_make(ElementType::INFO)); - info = &document.anm2.root.children.back(); - } - info->fps = fps; - }); + edit_push(EDIT_FPS, Document::INFO, + [=](Anm2& anm2) + { + auto info = element_first_get(anm2.root, ElementType::INFO); + if (!info) + { + anm2.root.children.push_back(element_make(ElementType::INFO)); + info = &anm2.root.children.back(); + } + info->fps = fps; + }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FPS)); @@ -1048,17 +949,17 @@ namespace anm2ed::imgui ImGui::SetNextItemWidth(widgetSize.x); if (input_text_string(localize.get(LABEL_AUTHOR), &createdBy)) { - edit_command_push(EDIT_AUTHOR, Document::INFO, - [=, this](Manager&, Document& document) - { - auto info = element_first_get(document.anm2.root, ElementType::INFO); - if (!info) - { - document.anm2.root.children.push_back(element_make(ElementType::INFO)); - info = &document.anm2.root.children.back(); - } - info->createdBy = createdBy; - }); + edit_push(EDIT_AUTHOR, Document::INFO, + [=](Anm2& anm2) + { + auto info = element_first_get(anm2.root, ElementType::INFO); + if (!info) + { + anm2.root.children.push_back(element_make(ElementType::INFO)); + info = &anm2.root.children.back(); + } + info->createdBy = createdBy; + }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AUTHOR)); diff --git a/src/imgui/window/timeline/menus.cpp b/src/imgui/window/timeline/menus.cpp index b29eb44..50c46d1 100644 --- a/src/imgui/window/timeline/menus.cpp +++ b/src/imgui/window/timeline/menus.cpp @@ -88,7 +88,6 @@ namespace anm2ed::imgui }; auto item = selected_item_get(); - auto frame = frame_get(); auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); auto copyFrames = copy_frame_references_get(); auto selectedBakeFrames = selectedFrames; @@ -208,16 +207,15 @@ namespace anm2ed::imgui auto targetAnimationIndex = groupAnimationIndex; auto targetType = groupType; auto targetId = groupId; - edit_command_push(EDIT_RENAME_GROUP, Document::ITEMS, - [=, this](Manager&, Document& document) - { - auto animation = document.anm2.element_get(ElementType::ANIMATION, targetAnimationIndex); - auto container = - animation ? child_first_get(*animation, TYPE_CONTAINERS[targetType]) : nullptr; - auto group = container ? child_id_get(*container, ElementType::GROUP, targetId) : nullptr; - if (!group) return; - group->name = targetName; - }); + edit_push(EDIT_RENAME_GROUP, Document::ITEMS, + [=](Anm2& anm2) + { + auto animation = anm2.element_get(ElementType::ANIMATION, targetAnimationIndex); + auto container = animation ? child_first_get(*animation, TYPE_CONTAINERS[targetType]) : nullptr; + auto group = container ? child_id_get(*container, ElementType::GROUP, targetId) : nullptr; + if (!group) return; + group->name = targetName; + }); } if (result != PopupButton::NONE) group_properties_close(); diff --git a/src/imgui/window/timeline/popups.cpp b/src/imgui/window/timeline/popups.cpp index 7eefb97..c1b0266 100644 --- a/src/imgui/window/timeline/popups.cpp +++ b/src/imgui/window/timeline/popups.cpp @@ -33,11 +33,10 @@ namespace anm2ed::imgui auto result = window_popup_buttons_draw(manager, localize.get(LABEL_MAKE_MANY_REGIONS)); if (result == PopupButton::CONFIRM) - edit_command_push( - EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, Document::ALL, - [targetFrames = makeManyRegionReferences, format = settings.generateRegionNameFormat, - mapping = isMakeManyRegionsMapFrames ? RegionFrameMapping::SET : RegionFrameMapping::PRESERVE]( - Manager&, Document& document) { document.anm2.regions_generate({}, targetFrames, format, mapping); }); + edit_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, Document::ALL, + [targetFrames = makeManyRegionReferences, format = settings.generateRegionNameFormat, + mapping = isMakeManyRegionsMapFrames ? RegionFrameMapping::SET : RegionFrameMapping::PRESERVE]( + Anm2& anm2) { anm2.regions_generate({}, targetFrames, format, mapping); }); if (result != PopupButton::NONE) makeManyRegionsPopup.close(); ImGui::EndPopup(); @@ -176,7 +175,7 @@ namespace anm2ed::imgui std::erase_if(selectedFrames, is_trigger_reference); if (!selectedFrames.empty()) { - if (!isResizeChordHeld[i]) snapshot_command_push(resize.edit, SnapshotKind::FRAMES, selectedFrames); + if (!isResizeChordHeld[i]) edit_begin_push(resize.edit); command_push( [=, this](Manager&, Document& document) { diff --git a/src/imgui/window/timeline/selection.cpp b/src/imgui/window/timeline/selection.cpp index d4b9fe0..53774ee 100644 --- a/src/imgui/window/timeline/selection.cpp +++ b/src/imgui/window/timeline/selection.cpp @@ -52,12 +52,6 @@ namespace anm2ed::imgui return targetReference.frameIndex < 0 ? nullptr : document.anm2.element_get(targetReference); } - Element* TimelineContext::command_item_get(Document& document, int animationIndex, int type, int id, int groupType, - int groupId) - { - return document.anm2.element_get(Reference{animationIndex, type, id, -1, groupType, groupId}); - } - Element* TimelineContext::frame_get() { return command_frame_get(document, reference); } Element* TimelineContext::selected_item_get() { return command_item_reference_get(document, reference); } @@ -68,14 +62,6 @@ namespace anm2ed::imgui return isLightTheme ? colors.light[std::clamp(type, 0, TRIGGER)] : colors.dark[type]; } - std::set TimelineContext::track_references_from_frame_references_get(std::set frameReferences) - { - std::set result{}; - for (auto frameReference : frameReferences) - result.insert(item_reference_from_frame_get(frameReference)); - return result; - } - void TimelineContext::frames_focus_sync_for(Document& targetDocument) { frames_selection_sync_for(targetDocument); @@ -93,25 +79,22 @@ namespace anm2ed::imgui return selectedReferences.empty() ? std::set{frameReference} : selectedReferences; } - void TimelineContext::snapshot_command_push(StringType messageType, SnapshotKind kind, - const std::set& references) + void TimelineContext::edit_begin_push(StringType label) { - command_push([message = std::string(localize.get(messageType)), kind, references](Manager&, Document& document) - { snapshot_take(document, message, kind, references); }); + command_push([label](Manager&, Document& document) { document.edit_begin(label); }); } - void TimelineContext::edit_command_push(StringType messageType, Document::ChangeType changeType, - std::function run, SnapshotKind kind, - const std::set& references) + void TimelineContext::frames_select_for(Document& targetDocument, const edit::Uids& uids) { - command_push( - [message = std::string(localize.get(messageType)), changeType, run, kind, references](Manager& manager, - Document& document) - { - snapshot_take(document, message, kind, references); - run(manager, document); - document.change(changeType); - }); + auto references = targetDocument.references_get(uids); + if (references.empty()) return; + targetDocument.reference = references.front(); + targetDocument.editTarget = Document::EditTarget::FRAME; + targetDocument.frame_references_set({references.begin(), references.end()}); + if (auto item = command_item_reference_get(targetDocument, targetDocument.reference); + item && targetDocument.reference.itemType != TRIGGER) + targetDocument.frameTime = frame_time_from_index_get(*item, targetDocument.reference.frameIndex); + frames_focus_sync_for(targetDocument); } Reference TimelineContext::item_reference_get(int type, int id, int groupType, int groupId) diff --git a/src/imgui/window/timeline/tracks.cpp b/src/imgui/window/timeline/tracks.cpp index bb25fb4..299f964 100644 --- a/src/imgui/window/timeline/tracks.cpp +++ b/src/imgui/window/timeline/tracks.cpp @@ -40,17 +40,16 @@ namespace anm2ed::imgui { auto targetRow = row; auto targetAnimationIndex = reference.animationIndex; - edit_command_push(EDIT_TOGGLE_GROUP_EXPANDED, Document::ITEMS, - [=, this](Manager&, Document& document) mutable - { - auto animation = document.anm2.element_get(ElementType::ANIMATION, targetAnimationIndex); - auto container = - animation ? child_first_get(*animation, TYPE_CONTAINERS[targetRow.type]) : nullptr; - auto group = - container ? child_id_get(*container, ElementType::GROUP, targetRow.id) : nullptr; - if (!group) return; - group->isExpanded = !group->isExpanded; - }); + edit_push(EDIT_TOGGLE_GROUP_EXPANDED, Document::ITEMS, + [=](Anm2& anm2) + { + auto animation = anm2.element_get(ElementType::ANIMATION, targetAnimationIndex); + auto container = + animation ? child_first_get(*animation, TYPE_CONTAINERS[targetRow.type]) : nullptr; + auto group = container ? child_id_get(*container, ElementType::GROUP, targetRow.id) : nullptr; + if (!group) return; + group->isExpanded = !group->isExpanded; + }); }; ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing))); @@ -140,17 +139,16 @@ namespace anm2ed::imgui auto targetType = type; auto targetGroupId = group->id; auto targetVisible = !isGroupVisible; - edit_command_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES, - [=, this](Manager&, Document& document) - { - auto animation = document.anm2.element_get(ElementType::ANIMATION, targetAnimationIndex); - auto container = - animation ? child_first_get(*animation, TYPE_CONTAINERS[targetType]) : nullptr; - if (!container) return; - auto group = child_id_get(*container, ElementType::GROUP, targetGroupId); - if (!group) return; - group->isVisible = targetVisible; - }); + edit_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES, + [=](Anm2& anm2) + { + auto animation = anm2.element_get(ElementType::ANIMATION, targetAnimationIndex); + auto container = animation ? child_first_get(*animation, TYPE_CONTAINERS[targetType]) : nullptr; + if (!container) return; + auto group = child_id_get(*container, ElementType::GROUP, targetGroupId); + if (!group) return; + group->isVisible = targetVisible; + }); } auto visibleButtonMin = ImGui::GetItemRectMin(); auto visibleButtonMax = ImGui::GetItemRectMax(); @@ -405,14 +403,13 @@ namespace anm2ed::imgui auto targetID = id; auto targetGroupType = row.rootGroupType; auto targetGroupId = row.rootGroupId; - edit_command_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES, - [=, this](Manager&, Document& document) - { - auto item = command_item_get(document, animationIndex, targetType, targetID, - targetGroupType, targetGroupId); - if (!item) return; - item->isVisible = !item->isVisible; - }); + edit_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES, + [=](Anm2& anm2) + { + if (auto item = anm2.element_get( + Reference{animationIndex, targetType, targetID, -1, targetGroupType, targetGroupId})) + item->isVisible = !item->isVisible; + }); } overlay_icon(resources.icon_id_get(visibleIcon), iconTintCurrent, false); ImGui::SetItemTooltip("%s", isItemVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) @@ -430,14 +427,14 @@ namespace anm2ed::imgui if (ImGui::ImageButton("##Rect Toggle", resources.icon_id_get(rectIcon), icon_size_get())) { auto nullID = id; - edit_command_push(EDIT_TOGGLE_NULL_RECT, Document::FRAMES, - [=, this](Manager&, Document& document) - { - auto nulls = document.anm2.element_get(ElementType::NULLS); - auto null = nulls ? child_id_get(*nulls, ElementType::NULL_ELEMENT, nullID) : nullptr; - if (!null) return; - null->isShowRect = !null->isShowRect; - }); + edit_push(EDIT_TOGGLE_NULL_RECT, Document::FRAMES, + [=](Anm2& anm2) + { + auto nulls = anm2.element_get(ElementType::NULLS); + auto null = nulls ? child_id_get(*nulls, ElementType::NULL_ELEMENT, nullID) : nullptr; + if (!null) return; + null->isShowRect = !null->isShowRect; + }); } overlay_icon(resources.icon_id_get(rectIcon), iconTintCurrent, false); ImGui::SetItemTooltip("%s", isShowRect ? localize.get(TOOLTIP_NULL_RECT_SHOWN) diff --git a/src/imgui/window/window.cpp b/src/imgui/window/window.cpp index 0f34e5e..07cc7fe 100644 --- a/src/imgui/window/window.cpp +++ b/src/imgui/window/window.cpp @@ -59,39 +59,32 @@ namespace anm2ed::imgui auto target = reference == -1 || !container ? nullptr : child_id_get(*container, window.elementType, reference); if (!container || (reference != -1 && !target)) return; - window_edit( - document, window.changeType, localize.get(reference == -1 ? window.addEdit : window.propertiesEdit), - [&]() - { - auto changed = edited; - changed.type = window.elementType; - changed.tag = element_make(window.elementType).tag; - changed.id = reference == -1 ? element_child_next_id_get(*container, window.elementType) : reference; - if (target) - *target = changed; - else - { - auto insertIndex = - window.insert_index_get ? window.insert_index_get(document) : (int)container->children.size(); - container->children.insert(container->children.begin() + insertIndex, changed); - window.newElementId = changed.id; - } - auto& storage = window.storage_get(document); - storage.selection = {changed.id}; - storage.reference = changed.id; - if (window.row_select) window.row_select(window, document, changed.id); - }); + document.edit_apply(reference == -1 ? window.addEdit : window.propertiesEdit, window.changeType, + [&](Anm2&) + { + auto changed = edited; + changed.type = window.elementType; + changed.tag = element_make(window.elementType).tag; + changed.id = reference == -1 + ? element_child_next_id_get(*container, window.elementType) + : reference; + if (target) + *target = changed; + else + { + auto insertIndex = window.insert_index_get ? window.insert_index_get(document) + : (int)container->children.size(); + container->children.insert(container->children.begin() + insertIndex, changed); + window.newElementId = changed.id; + } + auto& storage = window.storage_get(document); + storage.selection = {changed.id}; + storage.reference = changed.id; + if (window.row_select) window.row_select(window, document, changed.id); + }); }}); } - void window_edit(Document& document, Document::ChangeType changeType, const std::string& message, - const std::function& behavior) - { - document.snapshots.anm2_push(message); - behavior(); - document.change(changeType); - } - void window_command_push(Window& window, Manager& manager, Settings& settings, Clipboard& clipboard, const Window::Command& command) { @@ -107,13 +100,13 @@ namespace anm2ed::imgui { auto element = window_element_get(window, document, key); if (!element || element->name == name) return; - window_edit(document, window.changeType, localize.get(window.renameEdit), - [&]() - { - element->name = name; - if (window.rename_finish) - window.rename_finish(document, *element, key, count); - }); + document.edit_apply(window.renameEdit, window.changeType, + [&](Anm2&) + { + element->name = name; + if (window.rename_finish) + window.rename_finish(document, *element, key, count); + }); }}); } @@ -140,18 +133,18 @@ namespace anm2ed::imgui return; } - window_edit(document, window.changeType, localize.get(window.pasteEdit), - [&]() - { - document.anm2 = std::move(pasted); - container = window_container_get(window, document); - auto maxIdAfter = container ? element_child_max_id_get(*container, window.elementType) : -1; - if (maxIdAfter <= maxIdBefore) return; - window.newElementId = maxIdAfter; - storage.selection = {maxIdAfter}; - storage.reference = maxIdAfter; - if (window.row_select) window.row_select(window, document, maxIdAfter); - }); + document.edit_apply(window.pasteEdit, window.changeType, + [&](Anm2&) + { + document.anm2 = std::move(pasted); + container = window_container_get(window, document); + auto maxIdAfter = container ? element_child_max_id_get(*container, window.elementType) : -1; + if (maxIdAfter <= maxIdBefore) return; + window.newElementId = maxIdAfter; + storage.selection = {maxIdAfter}; + storage.reference = maxIdAfter; + if (window.row_select) window.row_select(window, document, maxIdAfter); + }); } void window_remove_unused(Window& window, Manager&, Settings&, Document& document, Clipboard&) @@ -159,12 +152,12 @@ namespace anm2ed::imgui auto unused = document.anm2.element_unused(window.elementType); auto container = window_container_get(window, document); if (unused.empty() || !container) return; - window_edit(document, window.changeType, localize.get(window.removeUnusedEdit), - [&]() - { - for (auto id : unused) - element_child_id_erase(*container, window.elementType, id); - }); + document.edit_apply(window.removeUnusedEdit, window.changeType, + [&](Anm2&) + { + for (auto id : unused) + element_child_id_erase(*container, window.elementType, id); + }); } bool is_window_group_selected(const Window& window) diff --git a/src/imgui/window/window.hpp b/src/imgui/window/window.hpp index d5483f6..388bd87 100644 --- a/src/imgui/window/window.hpp +++ b/src/imgui/window/window.hpp @@ -180,7 +180,6 @@ namespace anm2ed::imgui Element* window_container_get(const Window&, Document&); Element* window_element_get(const Window&, Document&, int); void window_element_apply_push(Window&, Manager&, const Element&, int); - void window_edit(Document&, Document::ChangeType, const std::string&, const std::function&); void window_command_push(Window&, Manager&, Settings&, Clipboard&, const Window::Command&); int window_selection_start(Window&, Document&, const std::vector&); void window_selection_finish(Window&, Manager&, Settings&, Clipboard&, Document&, int); diff --git a/src/imgui/wizard/change_all_frame_properties.cpp b/src/imgui/wizard/change_all_frame_properties.cpp index 81de0ca..3ffb508 100644 --- a/src/imgui/wizard/change_all_frame_properties.cpp +++ b/src/imgui/wizard/change_all_frame_properties.cpp @@ -248,45 +248,15 @@ namespace anm2ed::imgui::wizard [=, queuedAnimations = std::set(animations.begin(), animations.end()), isRoot = settings.changeIsRoot, isLayers = settings.changeIsLayers, isNulls = settings.changeIsNulls](Manager&, Document& document) { - auto& anm2 = document.anm2; - std::vector>> targets{}; - auto all_target_push = [&](Element* item, ItemType type) - { - if (!item) return; - auto indices = std::views::iota(0, track_frames_count_get(*item)); - targets.emplace_back(item, type, std::set(indices.begin(), indices.end())); - }; - + edit::ChangeTargets targets{.isRoot = isRoot, .isLayers = isLayers, .isNulls = isNulls}; if (isFramesDestination) - { - std::map> groupedFrames{}; - for (auto frameReference : selectedFrameReferences) - groupedFrames[{frameReference.animationIndex, frameReference.itemType, frameReference.itemID, -1, - frameReference.groupType, frameReference.groupId}] - .insert(frameReference.frameIndex); - for (auto& [itemReference, selection] : groupedFrames) - if (auto item = anm2.element_get(itemReference)) - targets.emplace_back(item, (ItemType)itemReference.itemType, selection); - } + targets.references = {selectedFrameReferences.begin(), selectedFrameReferences.end()}; else if (isItemsDestination) - for (auto itemReference : selectedItemReferences) - all_target_push(anm2.element_get(itemReference), (ItemType)itemReference.itemType); + targets.references = {selectedItemReferences.begin(), selectedItemReferences.end()}; else - for (auto animationIndex : queuedAnimations) - { - auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex); - if (!animation) continue; - if (isRoot) all_target_push(animation_item_get(*animation, ItemType::ROOT), ItemType::ROOT); - for (const auto& row : TRACK_CONTAINERS) - if (auto container = child_first_get(*animation, row.container); - container && (row.itemType == ItemType::LAYER ? isLayers : isNulls)) - tracks_each(*container, row.track, [&](Element& track) { all_target_push(&track, row.itemType); }); - } - - document.snapshots.anm2_push(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); - for (auto& [item, type, selection] : targets) - frames_change(*item, frameChange, type, changeType, selection); - document.change(Document::FRAMES); + targets.animations = queuedAnimations; + document.edit_apply(EDIT_CHANGE_FRAME_PROPERTIES, Document::FRAMES, [&](Anm2& anm2) + { return edit::frames_change_apply(anm2, targets, frameChange, changeType); }); }}); isChanged = true; }; diff --git a/src/imgui/wizard/generate_animation_from_grid.cpp b/src/imgui/wizard/generate_animation_from_grid.cpp index c61fb48..137fb51 100644 --- a/src/imgui/wizard/generate_animation_from_grid.cpp +++ b/src/imgui/wizard/generate_animation_from_grid.cpp @@ -148,56 +148,11 @@ namespace anm2ed::imgui::wizard manager.command_push( {manager.selected, [=](Manager&, Document& document) { - auto region_name_get = [](const std::string& format, int frameNumber) - { - try - { - return std::vformat(format, std::make_format_args(frameNumber)); - } - catch (const std::format_error&) - { - return format; - } - }; - - bool isChanged{}; - bool isRegionsChanged{}; - for (auto queuedReference : queuedLayerReferences) - { - auto item = document.anm2.element_get(queuedReference); - auto animation = document.anm2.element_get(ElementType::ANIMATION, queuedReference.animationIndex); - auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, queuedReference.itemID); - auto spritesheet = - layer ? document.anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; - if (!item || !animation) continue; - - if (!isChanged) - { - document.snapshots.anm2_push(localize.get(EDIT_GENERATE_ANIMATION_FROM_GRID)); - isChanged = true; - } - auto frameIndexStart = (int)item->children.size(); - frames_generate_from_grid(*item, queuedStartPosition, queuedSize, queuedPivot, queuedColumns, - queuedCount, queuedDelay); - if (queuedIsMakeRegions && spritesheet) - for (int frameIndex = frameIndexStart; frameIndex < (int)item->children.size(); ++frameIndex) - { - auto& frame = item->children[frameIndex]; - if (frame.type != ElementType::FRAME) continue; - - auto region = element_make(ElementType::REGION); - region.id = element_child_next_id_get(*spritesheet, ElementType::REGION); - region.name = region_name_get(queuedRegionNameFormat, frameIndex - frameIndexStart); - region.crop = frame.crop; - region.size = frame.size; - region.pivot = frame.pivot; - frame.regionId = region.id; - spritesheet->children.push_back(region); - isRegionsChanged = true; - } - animation->frameNum = animation_length_get(*animation); - } - if (isChanged) document.change(isRegionsChanged ? Document::ALL : Document::FRAMES); + edit::GridOptions options{queuedStartPosition, queuedSize, queuedPivot, queuedColumns, + queuedCount, queuedDelay, queuedIsMakeRegions, queuedRegionNameFormat}; + document.edit_apply(EDIT_GENERATE_ANIMATION_FROM_GRID, + queuedIsMakeRegions ? Document::ALL : Document::FRAMES, [&](Anm2& anm2) + { return edit::animation_grid_generate(anm2, queuedLayerReferences, options); }); }}); isEnd = true; } diff --git a/src/snapshots.cpp b/src/snapshots.cpp index cbc819d..1c632aa 100644 --- a/src/snapshots.cpp +++ b/src/snapshots.cpp @@ -142,15 +142,14 @@ namespace anm2ed::snapshots return element; } - bool element_path_get(const Element& element, const Element* target, std::vector& path) + SnapshotAnm2Step anm2_step_make(const Anm2& before, const Anm2& after) { - for (size_t i = 0; i < element.children.size(); ++i) - { - path.push_back((int)i); - if (&element.children[i] == target || element_path_get(element.children[i], target, path)) return true; - path.pop_back(); - } - return false; + SnapshotAnm2Step step{}; + if (before.isValid != after.isValid) step.isValid = SnapshotStepValue{before.isValid, after.isValid}; + + std::vector path{}; + element_steps_build(step.elements, before.root, after.root, path); + return step; } void step_state_seed(SnapshotStep& step, const Snapshot& snapshot) @@ -169,37 +168,6 @@ namespace anm2ed::snapshots return step; } - SnapshotStep step_elements_make(const Snapshot& snapshot, const std::vector& elements) - { - SnapshotStep step{}; - for (auto element : elements) - { - std::vector path{}; - if (!element || !element_path_get(snapshot.anm2.root, element, path)) continue; - if (std::ranges::any_of(step.anm2.elements, [&](const SnapshotElementStep& other) { return other.path == path; })) - continue; - step.anm2.elements.push_back({std::move(path), *element, {}}); - } - return step; - } - - SnapshotAnm2Step anm2_step_make(const Anm2& before, const Anm2& after) - { - SnapshotAnm2Step step{}; - if (before.isValid != after.isValid) step.isValid = SnapshotStepValue{before.isValid, after.isValid}; - - std::vector path{}; - element_steps_build(step.elements, before.root, after.root, path); - return step; - } - - bool is_anm2_step_seeded(const SnapshotStep& step) - { - return step.anm2.elements.size() == 1 && step.anm2.elements.front().path.empty() && - step.anm2.elements.front().redo.type == ElementType::UNKNOWN && - step.anm2.elements.front().redo.children.empty(); - } - bool is_same_item(Reference left, Reference right) { left.frameIndex = right.frameIndex = -1; @@ -389,49 +357,10 @@ namespace anm2ed pendingStep = step.is_empty() ? std::nullopt : std::optional(std::move(step)); } - void Snapshots::anm2_push(const std::string& message) { step_push(message, snapshots::step_anm2_make(current)); } - - void Snapshots::tracks_push(const std::string& message, const std::set& trackReferences) - { - std::vector tracks{}; - for (auto trackReference : trackReferences) - { - trackReference.frameIndex = -1; - tracks.push_back(current.anm2.element_get(trackReference)); - } - auto step = snapshots::step_elements_make(current, tracks); - snapshots::step_state_seed(step, current); - step_push(message, std::move(step)); - } - - void Snapshots::frames_push(const std::string& message, const std::set& frameReferences) - { - std::vector frames{}; - for (auto frameReference : frameReferences) - frames.push_back(current.anm2.element_get(frameReference)); - step_push(message, snapshots::step_elements_make(current, frames)); - } - - void Snapshots::regions_push(const std::string& message, int spritesheetId, const std::set& regionIds) - { - std::vector regions{}; - if (auto spritesheet = current.anm2.element_get(ElementType::SPRITESHEET, spritesheetId)) - for (auto regionId : regionIds) - regions.push_back(child_id_get(*spritesheet, ElementType::REGION, regionId)); - step_push(message, snapshots::step_elements_make(current, regions)); - } - - void Snapshots::textures_push(const std::string& message) - { - SnapshotStep step{}; - step.textures = SnapshotStepValue{current.textures, {}}; - step_push(message, std::move(step)); - } - - void Snapshots::anm2_textures_push(const std::string& message) + void Snapshots::push(const std::string& message, bool isTextures) { auto step = snapshots::step_anm2_make(current); - step.textures = SnapshotStepValue{current.textures, {}}; + if (isTextures) step.textures = SnapshotStepValue{current.textures, {}}; step_push(message, std::move(step)); } @@ -444,13 +373,10 @@ namespace anm2ed auto step = std::move(*pendingStep); pendingStep.reset(); - if (snapshots::is_anm2_step_seeded(step)) - { - Anm2 before{}; - before.isValid = step.anm2.isValid ? step.anm2.isValid->undo : snapshot.anm2.isValid; - before.root = std::move(step.anm2.elements.front().undo); - step.anm2 = snapshots::anm2_step_make(before, snapshot.anm2); - } + Anm2 before{}; + before.isValid = step.anm2.isValid ? step.anm2.isValid->undo : snapshot.anm2.isValid; + before.root = std::move(step.anm2.elements.front().undo); + step.anm2 = snapshots::anm2_step_make(before, snapshot.anm2); if (step.anm2.isValid) { diff --git a/src/snapshots.hpp b/src/snapshots.hpp index 44d6653..8623a6b 100644 --- a/src/snapshots.hpp +++ b/src/snapshots.hpp @@ -151,12 +151,7 @@ namespace anm2ed std::optional pendingStep{}; std::optional pendingSelection{}; - void anm2_push(const std::string&); - void tracks_push(const std::string&, const std::set&); - void frames_push(const std::string&, const std::set&); - void regions_push(const std::string&, int, const std::set&); - void textures_push(const std::string&); - void anm2_textures_push(const std::string&); + void push(const std::string&, bool = false); void step_push(const std::string&, SnapshotStep); void commit(); bool undo(); diff --git a/src/types.hpp b/src/types.hpp index 45204a5..abad17c 100644 --- a/src/types.hpp +++ b/src/types.hpp @@ -79,7 +79,7 @@ namespace anm2ed::types::merge }; } -namespace anm2ed::types::edit +namespace anm2ed::types::edit_state { enum Type { diff --git a/src/util/imgui/input.cpp b/src/util/imgui/input.cpp index 67d103c..c66c810 100644 --- a/src/util/imgui/input.cpp +++ b/src/util/imgui/input.cpp @@ -74,7 +74,7 @@ namespace anm2ed::imgui return isActivated; } - edit::Type drag_int_persistent(const char* label, int* value, float speed, int min, int max, const char* format, + edit_state::Type drag_int_persistent(const char* label, int* value, float speed, int min, int max, const char* format, ImGuiSliderFlags flags) { static bool isEditing{}; @@ -82,30 +82,30 @@ namespace anm2ed::imgui auto persistent = value ? *value : 0; ImGui::DragInt(label, &persistent, speed, min, max, format, flags); - if (!value) return edit::NONE; + if (!value) return edit_state::NONE; if (ImGui::IsItemActivated() && persistent != start) { isEditing = true; start = *value; - return edit::START; + return edit_state::START; } else if (ImGui::IsItemDeactivatedAfterEdit()) { isEditing = false; *value = persistent; start = INT_MAX; - return edit::END; + return edit_state::END; } else if (isEditing) { *value = persistent; - return edit::DURING; + return edit_state::DURING; } - return edit::NONE; + return edit_state::NONE; } - edit::Type drag_float_persistent(const char* label, float* value, float speed, float min, float max, + edit_state::Type drag_float_persistent(const char* label, float* value, float speed, float min, float max, const char* format, ImGuiSliderFlags flags) { static bool isEditing{}; @@ -113,30 +113,30 @@ namespace anm2ed::imgui auto persistent = value ? *value : 0; ImGui::DragFloat(label, &persistent, speed, min, max, format, flags); - if (!value) return edit::NONE; + if (!value) return edit_state::NONE; if (ImGui::IsItemActivated() && persistent != start) { isEditing = true; start = *value; - return edit::START; + return edit_state::START; } else if (ImGui::IsItemDeactivatedAfterEdit()) { isEditing = false; *value = persistent; start = NAN; - return edit::END; + return edit_state::END; } else if (isEditing) { *value = persistent; - return edit::DURING; + return edit_state::DURING; } - return edit::NONE; + return edit_state::NONE; } - edit::Type drag_float2_persistent(const char* label, vec2* value, float speed, float min, float max, + edit_state::Type drag_float2_persistent(const char* label, vec2* value, float speed, float min, float max, const char* format, ImGuiSliderFlags flags) { static bool isEditing{}; @@ -144,87 +144,87 @@ namespace anm2ed::imgui auto persistent = value ? *value : vec2(); ImGui::DragFloat2(label, value_ptr(persistent), speed, min, max, format, flags); - if (!value) return edit::NONE; + if (!value) return edit_state::NONE; if (ImGui::IsItemActivated() && persistent != start) { isEditing = true; start = *value; - return edit::START; + return edit_state::START; } else if (ImGui::IsItemDeactivatedAfterEdit()) { isEditing = false; *value = persistent; start = vec2{NAN}; - return edit::END; + return edit_state::END; } else if (isEditing) { *value = persistent; - return edit::DURING; + return edit_state::DURING; } - return edit::NONE; + return edit_state::NONE; } - edit::Type color_edit3_persistent(const char* label, vec3* value, ImGuiColorEditFlags flags) + edit_state::Type color_edit3_persistent(const char* label, vec3* value, ImGuiColorEditFlags flags) { static bool isEditing{}; static vec3 start{NAN}; auto persistent = value ? *value : vec4(); ImGui::ColorEdit3(label, value_ptr(persistent), flags); - if (!value) return edit::NONE; + if (!value) return edit_state::NONE; if (ImGui::IsItemActivated() && persistent != start) { isEditing = true; start = *value; - return edit::START; + return edit_state::START; } else if (ImGui::IsItemDeactivatedAfterEdit()) { isEditing = false; *value = persistent; start = vec4{NAN}; - return edit::END; + return edit_state::END; } else if (isEditing) { *value = persistent; - return edit::DURING; + return edit_state::DURING; } - return edit::NONE; + return edit_state::NONE; } - edit::Type color_edit4_persistent(const char* label, vec4* value, ImGuiColorEditFlags flags) + edit_state::Type color_edit4_persistent(const char* label, vec4* value, ImGuiColorEditFlags flags) { static bool isEditing{}; static vec4 start{NAN}; auto persistent = value ? *value : vec4(); ImGui::ColorEdit4(label, value_ptr(persistent), flags); - if (!value) return edit::NONE; + if (!value) return edit_state::NONE; if (ImGui::IsItemActivated() && persistent != start) { isEditing = true; start = *value; - return edit::START; + return edit_state::START; } else if (ImGui::IsItemDeactivatedAfterEdit()) { isEditing = false; *value = persistent; start = vec4{NAN}; - return edit::END; + return edit_state::END; } else if (isEditing) { *value = persistent; - return edit::DURING; + return edit_state::DURING; } - return edit::NONE; + return edit_state::NONE; } bool radio_button_icon(const char* label, int* value, int buttonValue, ImTextureID texture, ImVec2 size, ImVec4 tint) diff --git a/src/util/imgui/input.hpp b/src/util/imgui/input.hpp index ff3ccfa..781b044 100644 --- a/src/util/imgui/input.hpp +++ b/src/util/imgui/input.hpp @@ -19,14 +19,14 @@ namespace anm2ed::imgui bool input_int2_range(const char*, glm::ivec2&, glm::ivec2, glm::ivec2, ImGuiInputTextFlags = 0); bool input_float_range(const char*, float&, float, float, float = STEP, float = STEP_FAST, const char* = "%.3f", ImGuiInputTextFlags = 0); - types::edit::Type drag_int_persistent(const char*, int*, float = DRAG_SPEED, int = {}, int = {}, const char* = "%d", + types::edit_state::Type drag_int_persistent(const char*, int*, float = DRAG_SPEED, int = {}, int = {}, const char* = "%d", ImGuiSliderFlags = 0); - types::edit::Type drag_float_persistent(const char*, float*, float = DRAG_SPEED, float = {}, float = {}, + types::edit_state::Type drag_float_persistent(const char*, float*, float = DRAG_SPEED, float = {}, float = {}, const char* = "%.3f", ImGuiSliderFlags = 0); - types::edit::Type drag_float2_persistent(const char*, glm::vec2*, float = DRAG_SPEED, float = {}, float = {}, + types::edit_state::Type drag_float2_persistent(const char*, glm::vec2*, float = DRAG_SPEED, float = {}, float = {}, const char* = "%.3f", ImGuiSliderFlags = 0); - types::edit::Type color_edit3_persistent(const char*, glm::vec3*, ImGuiColorEditFlags = 0); - types::edit::Type color_edit4_persistent(const char*, glm::vec4*, ImGuiColorEditFlags = 0); + types::edit_state::Type color_edit3_persistent(const char*, glm::vec3*, ImGuiColorEditFlags = 0); + 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_negative_one_indexed(const std::string&, int*, std::vector&); bool combo_id_mapped(const std::string&, int*, const std::vector&, std::vector&); diff --git a/tests/golden/operation.animation_add.xml b/tests/golden/operation.animation_add.xml new file mode 100644 index 0000000..74e50b5 --- /dev/null +++ b/tests/golden/operation.animation_add.xml @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.animation_grid_generate.xml b/tests/golden/operation.animation_grid_generate.xml new file mode 100644 index 0000000..af8d60b --- /dev/null +++ b/tests/golden/operation.animation_grid_generate.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.animations_group.xml b/tests/golden/operation.animations_group.xml new file mode 100644 index 0000000..3d89504 --- /dev/null +++ b/tests/golden/operation.animations_group.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.animations_merge.xml b/tests/golden/operation.animations_merge.xml new file mode 100644 index 0000000..0a365bb --- /dev/null +++ b/tests/golden/operation.animations_merge.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.animations_move.xml b/tests/golden/operation.animations_move.xml new file mode 100644 index 0000000..ac455f8 --- /dev/null +++ b/tests/golden/operation.animations_move.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.animations_paste.xml b/tests/golden/operation.animations_paste.xml new file mode 100644 index 0000000..0aa7116 --- /dev/null +++ b/tests/golden/operation.animations_paste.xml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.animations_remove.xml b/tests/golden/operation.animations_remove.xml new file mode 100644 index 0000000..cc12cad --- /dev/null +++ b/tests/golden/operation.animations_remove.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.frame_insert.xml b/tests/golden/operation.frame_insert.xml new file mode 100644 index 0000000..2c59b60 --- /dev/null +++ b/tests/golden/operation.frame_insert.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.frame_split.xml b/tests/golden/operation.frame_split.xml new file mode 100644 index 0000000..3238060 --- /dev/null +++ b/tests/golden/operation.frame_split.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.frames_bake.xml b/tests/golden/operation.frames_bake.xml new file mode 100644 index 0000000..c9fb84b --- /dev/null +++ b/tests/golden/operation.frames_bake.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.frames_change_apply.xml b/tests/golden/operation.frames_change_apply.xml new file mode 100644 index 0000000..9a1c4c2 --- /dev/null +++ b/tests/golden/operation.frames_change_apply.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.frames_delete.xml b/tests/golden/operation.frames_delete.xml new file mode 100644 index 0000000..4f0fc23 --- /dev/null +++ b/tests/golden/operation.frames_delete.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.frames_duplicate.xml b/tests/golden/operation.frames_duplicate.xml new file mode 100644 index 0000000..2dfd6ca --- /dev/null +++ b/tests/golden/operation.frames_duplicate.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.frames_move.xml b/tests/golden/operation.frames_move.xml new file mode 100644 index 0000000..f01f32c --- /dev/null +++ b/tests/golden/operation.frames_move.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.frames_paste.xml b/tests/golden/operation.frames_paste.xml new file mode 100644 index 0000000..29ac20b --- /dev/null +++ b/tests/golden/operation.frames_paste.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.frames_reverse.xml b/tests/golden/operation.frames_reverse.xml new file mode 100644 index 0000000..b226fcd --- /dev/null +++ b/tests/golden/operation.frames_reverse.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.items_group.xml b/tests/golden/operation.items_group.xml new file mode 100644 index 0000000..99b57b3 --- /dev/null +++ b/tests/golden/operation.items_group.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.items_move.xml b/tests/golden/operation.items_move.xml new file mode 100644 index 0000000..3fed977 --- /dev/null +++ b/tests/golden/operation.items_move.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.items_remove.xml b/tests/golden/operation.items_remove.xml new file mode 100644 index 0000000..b3c4f41 --- /dev/null +++ b/tests/golden/operation.items_remove.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.regions_paste.xml b/tests/golden/operation.regions_paste.xml new file mode 100644 index 0000000..b259396 --- /dev/null +++ b/tests/golden/operation.regions_paste.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.regions_remove_unused.xml b/tests/golden/operation.regions_remove_unused.xml new file mode 100644 index 0000000..dd6047e --- /dev/null +++ b/tests/golden/operation.regions_remove_unused.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.root_bake_into.xml b/tests/golden/operation.root_bake_into.xml new file mode 100644 index 0000000..fa2d5b7 --- /dev/null +++ b/tests/golden/operation.root_bake_into.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/golden/operation.trigger_insert.xml b/tests/golden/operation.trigger_insert.xml new file mode 100644 index 0000000..88405d7 --- /dev/null +++ b/tests/golden/operation.trigger_insert.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/operations.cpp b/tests/operations.cpp index abc0f7e..3bf4b3a 100644 --- a/tests/operations.cpp +++ b/tests/operations.cpp @@ -1,5 +1,6 @@ #include "common.hpp" +#include "edit/edit.hpp" #include "util/pack.hpp" using namespace anm2ed; @@ -135,3 +136,110 @@ TEST_CASE("rects_pack fits every rect without overlap") } } } + +// Each edit runs on a fixture; its result document is a golden, and every returned uid must resolve. +TEST_CASE("edit layer operations") +{ + struct Case + { + const char* name; + const char* fixture; + std::function operation; + std::size_t uidCount; + }; + + const Reference head{0, LAYER, 0}; + const Case CASES[] = { + {"frame_insert", "02_items.anm2", [&](Anm2& anm2) { return edit::frame_insert(anm2, {0, LAYER, 0, 0}, 0); }, 1}, + {"trigger_insert", "02_items.anm2", [&](Anm2& anm2) { return edit::frame_insert(anm2, {0, TRIGGER, -1, 0}, 2); }, + 1}, + {"frames_delete", "02_items.anm2", + [&](Anm2& anm2) { return edit::frames_delete(anm2, {{0, LAYER, 0, 0}, {0, ROOT, -1, 1}}); }, 0}, + {"frames_duplicate", "02_items.anm2", [&](Anm2& anm2) + { return edit::frames_duplicate(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, {0, LAYER, 0, 1}); }, 2}, + {"frames_reverse", "07_special_interpolation.anm2", + [&](Anm2& anm2) { return edit::frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 2}}); }, 0}, + {"frames_bake", "07_special_interpolation.anm2", + [&](Anm2& anm2) { return edit::frames_bake(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, 2, true, false); }, 5}, + {"frame_split", "02_items.anm2", [&](Anm2& anm2) { return edit::frame_split(anm2, {0, LAYER, 1, 0}, 2); }, 1}, + {"frames_move", "02_items.anm2", + [&](Anm2& anm2) { return edit::frames_move(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 1, 0}}, head, 2); }, 2}, + {"frames_paste", "02_items.anm2", + [&](Anm2& anm2) + { + auto frame = anm2.element_get(Reference{0, LAYER, 1, 0}); + auto text = element_to_string(*frame, ElementType::LAYER_ANIMATION) + + element_to_string(*frame, ElementType::LAYER_ANIMATION); + return edit::frames_paste(anm2, {0, LAYER, 0, 0}, {}, text, 0, nullptr); + }, + 2}, + {"root_bake_into", "04_group_root_transform.anm2", + [&](Anm2& anm2) + { + return edit::root_bake_into(anm2, {{0, ROOT, -1, 0}}, {{0, LAYER, 2}}, + {.isRoundScale = true, .isMatchRootInterpolation = true}); + }, + 1}, + {"items_group", "03b_groups_legacy_flat.anm2", + [&](Anm2& anm2) { return edit::items_group(anm2, 0, LAYER, {2}, "New"); }, 1}, + {"items_move", "03b_groups_legacy_flat.anm2", + [&](Anm2& anm2) { return edit::items_move(anm2, 0, LAYER, {2}, {}, {true, LAYER, 0, -1}, false, true); }, 0}, + {"items_remove", "03b_groups_legacy_flat.anm2", + [&](Anm2& anm2) { return edit::items_remove(anm2, 0, {{LAYER, {2}}}, {{NULL_, {3}}}); }, 0}, + {"animation_add", "03a_groups_nested.anm2", + [&](Anm2& anm2) { return edit::animation_add(anm2, 1, 0, 0, "Added"); }, 1}, + {"animations_remove", "03a_groups_nested.anm2", + [&](Anm2& anm2) { return edit::animations_remove(anm2, {1}, {0}); }, 0}, + {"animations_move", "02_items.anm2", [&](Anm2& anm2) { return edit::animations_move(anm2, {0}, {}, 2, -1); }, 1}, + {"animations_group", "02_items.anm2", [&](Anm2& anm2) { return edit::animations_group(anm2, {0, 1}, "Group"); }, + 0}, + {"animations_paste", "02_items.anm2", + [&](Anm2& anm2) + { + std::set groupIds{}; + auto text = element_to_string(*anm2.element_get(ElementType::ANIMATION, 1)); + return edit::animations_paste(anm2, text, 0, -1, groupIds, nullptr); + }, + 1}, + {"regions_remove_unused", "05_regions.anm2", [&](Anm2& anm2) { return edit::regions_remove_unused(anm2, 0); }, 0}, + {"regions_paste", "05_regions.anm2", + [&](Anm2& anm2) + { + auto region = child_id_get(*anm2.element_get(ElementType::SPRITESHEET, 0), ElementType::REGION, 1); + return edit::regions_paste(anm2, 0, element_to_string(*region), 1, nullptr); + }, + 0}, + {"animation_grid_generate", "05_regions.anm2", + [&](Anm2& anm2) + { + return edit::animation_grid_generate(anm2, {{0, LAYER, 0}}, + {{0, 0}, {8, 8}, {4, 4}, 2, 3, 2, true, "Grid {}"}); + }, + 3}, + {"frames_change_apply", "02_items.anm2", + [&](Anm2& anm2) + { + FrameChange change{.positionX = 3.0f, .rotation = 10.0f}; + return edit::frames_change_apply( + anm2, {.references = {{0, LAYER, 0, 1}, {0, NULL_, 0}}, .animations = {1}, .isRoot = true}, change, + ChangeType::ADD); + }, + 0}, + {"animations_merge", "03a_groups_nested.anm2", + [&](Anm2& anm2) { return edit::animations_merge(anm2, 0, {1}, types::merge::APPEND, true, {0}); }, 1}, + }; + + for (const auto& entry : CASES) + { + INFO("operation: ", std::string(entry.name)); + auto anm2 = fixture_load(entry.fixture); + anm2.uids_repair(); + auto uids = entry.operation(anm2); + CHECK(uids.size() == entry.uidCount); + anm2.uids_repair(); + UidIndex index(anm2); + for (auto uid : uids) + CHECK(index.reference_get(uid)); + operation_check(entry.name, anm2); + } +} diff --git a/tests/undo.cpp b/tests/undo.cpp new file mode 100644 index 0000000..76ef1b2 --- /dev/null +++ b/tests/undo.cpp @@ -0,0 +1,126 @@ +#include "common.hpp" + +#include + +#include "edit/edit.hpp" +#include "snapshots.hpp" + +using namespace anm2ed; +using namespace anm2ed::test; + +constexpr int WALK_STEPS = 150; +constexpr int WALK_SEED = 1234; +constexpr int UNDO_LIMIT = 1000; + +std::vector references_all_get(const Anm2& anm2, bool isFrames) +{ + UidIndex index(anm2); + std::vector result{}; + element_each(anm2.root, + [&](const Element& element) + { + auto reference = index.reference_get(element.uid); + if (!reference || reference->itemType == NONE || reference->itemType == TRIGGER) return; + if (isFrames == (reference->frameIndex >= 0)) result.push_back(*reference); + }); + return result; +} + +// One random edit on randomly chosen live elements; returns false when nothing applicable exists. +bool edit_random_apply(Anm2& anm2, std::mt19937& random) +{ + auto frames = references_all_get(anm2, true); + auto tracks = references_all_get(anm2, false); + if (frames.empty() || tracks.empty()) return false; + auto pick = [&](const auto& items) + { return items[std::uniform_int_distribution(0, (int)items.size() - 1)(random)]; }; + auto frame = pick(frames); + auto other = pick(frames); + + switch (std::uniform_int_distribution(0, 8)(random)) + { + case 0: + edit::frame_insert(anm2, frame, 0); + break; + case 1: + if (frames.size() > 4) edit::frames_delete(anm2, {frame, other}); + break; + case 2: + edit::frames_duplicate(anm2, {frame, other}, frame); + break; + case 3: + edit::frames_reverse(anm2, {frame, other}); + break; + case 4: + edit::frames_bake(anm2, {frame}, 1, false, false); + break; + case 5: + edit::frame_split(anm2, frame, 1); + break; + case 6: + if (frame.itemType != ROOT) edit::frames_move(anm2, {frame}, pick(tracks), 0); + break; + case 7: + edit::animation_add(anm2, 0, -1, frame.animationIndex, "Walk"); + break; + default: + edit::animations_move(anm2, {frame.animationIndex}, {}, 0, -1); + break; + } + return true; +} + +TEST_CASE("undo and redo restore every state of a random edit walk") +{ + SnapshotStack::max_size_set(UNDO_LIMIT); + for (auto name : + {"02_items.anm2", "03a_groups_nested.anm2", "04_group_root_transform.anm2", "07_special_interpolation.anm2"}) + { + INFO("fixture: ", name); + Snapshots snapshots{}; + snapshots.current.anm2 = anm2_load(file_load(CORPUS_DIR / name)); + std::mt19937 random(WALK_SEED); + + std::vector hashes{snapshots.current.anm2.hash()}; + for (int step = 0; step < WALK_STEPS; ++step) + { + snapshots.push("Edit"); + if (!edit_random_apply(snapshots.current.anm2, random)) break; + snapshots.commit(); + if (snapshots.current.anm2.hash() != hashes.back()) hashes.push_back(snapshots.current.anm2.hash()); + } + REQUIRE(hashes.size() > 1); + + for (auto it = hashes.rbegin() + 1; it != hashes.rend(); ++it) + { + REQUIRE(snapshots.undo()); + CHECK(snapshots.current.anm2.hash() == *it); + } + CHECK_FALSE(snapshots.undo()); + + for (auto it = hashes.begin() + 1; it != hashes.end(); ++it) + { + REQUIRE(snapshots.redo()); + CHECK(snapshots.current.anm2.hash() == *it); + } + } +} + +TEST_CASE("selection follows its frame through an edit and its undo") +{ + Snapshots snapshots{}; + snapshots.current.anm2 = anm2_load(file_load(CORPUS_DIR / "02_items.anm2")); + snapshots.current.reference = {0, LAYER, 0, 1}; + snapshots.current.frames.references = {{0, LAYER, 0, 1}}; + + snapshots.push("Insert"); + edit::frame_insert(snapshots.current.anm2, {0, LAYER, 0, -1}, 0); + auto& track = *snapshots.current.anm2.element_get(Reference{0, LAYER, 0}); + std::rotate(track.children.begin(), track.children.end() - 1, track.children.end()); + snapshots.commit(); + CHECK(snapshots.current.reference == Reference{0, LAYER, 0, 2}); + CHECK(snapshots.current.frames.references == std::set{{0, LAYER, 0, 2}}); + + REQUIRE(snapshots.undo()); + CHECK(snapshots.current.reference == Reference{0, LAYER, 0, 1}); +}