Remove items in use; drop Remove Unused

Every content window's Remove (the Delete key) takes the selection out with
what refers to it: a layer's or null's tracks in every animation, a
spritesheet's plain layers (and regions), an event or sound from its triggers
(dropping triggers left with neither), a shader or region from its frames
(which keep the region's rectangle), and a library's layers, flattened into
plain ones. When anything is in use it asks first, listing what goes ("This
will remove:" ... "Are you sure?"). Remove Unused is gone; Remove takes its
place in each footer.

One reference walk (model.cpp) counts uses and finds unused items, so
shaders on null and root frames count, and an animation layer's unused
spritesheet doesn't. Flattening can be limited to some layers, merging only
their children's triggers, which now record the layer they fired through.
edit::content_remove does the removal; Document::spritesheet_path_resolver_get
is shared with saving.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shweetandClaude Opus 5.5 committed 2026-10-28 22:33:25 -04:00
1 parent c9d68781d0
commit 065dd522f3
22 files changed
+468 -217

No files matched your search

+14 -9
View File
@@ -229,14 +229,10 @@ namespace anm2ed
return false;
}
// Writes the document; a Rebirth document's game copy has its animation layers flattened into plain layers.
bool Document::file_write(const std::filesystem::path& path, std::string* errorString, Options options)
// A library's spritesheet path, made relative to this document (for flattening its animation layers).
edit::SpritesheetPathGet Document::spritesheet_path_resolver_get() const
{
std::optional<model::Model> game{};
if (!options.isJson && std::ranges::any_of(model.content.layers, &model::Layer::is_animation))
game = edit::animation_layers_flatten(
model, library_resolver_get(),
[&](const model::Model& source, const std::filesystem::path& spritesheetPath)
return [this](const model::Model& source, const std::filesystem::path& spritesheetPath)
{
for (const auto& [libraryPath, library] : libraries)
if (&library.model == &source)
@@ -244,7 +240,15 @@ namespace anm2ed
path::make_relative(document::absolute_path_get(libraryPath.parent_path(), spritesheetPath),
std::filesystem::absolute(directory_get())));
return spritesheetPath;
});
};
}
// Writes the document; a Rebirth document's game copy has its animation layers flattened into plain layers.
bool Document::file_write(const std::filesystem::path& path, std::string* errorString, Options options)
{
std::optional<model::Model> game{};
if (!options.isJson && std::ranges::any_of(model.content.layers, &model::Layer::is_animation))
game = edit::animation_layers_flatten(model, library_resolver_get(), spritesheet_path_resolver_get());
options.gameModel = game ? &*game : nullptr;
return model::model_save(model, path, errorString, options);
}
@@ -571,7 +575,8 @@ namespace anm2ed
int index) const
{
std::vector<const resource::AudioData*> result{};
for (const auto& [source, trigger] : model::animation_triggers_get(model, animation, time, library_resolver_get()))
for (const auto& [source, trigger, layerId] :
model::animation_triggers_get(model, animation, time, library_resolver_get()))
{
if (trigger.soundIds.empty()) continue;
auto count = trigger.soundIds.size();
+1
View File
@@ -148,6 +148,7 @@ namespace anm2ed
std::filesystem::path library_path_get(int) const;
const LibraryData* library_get(const model::Model&, int) const;
model::LibraryGet library_resolver_get() const;
edit::SpritesheetPathGet spritesheet_path_resolver_get() const;
std::vector<std::string> animation_names_get(int) const;
const resource::Image* draw_image_get(const model::Draw&, float = 1.0f) const;
const resource::Image* vector_image_get(const resource::Image*, float) const;
+99 -5
View File
@@ -123,12 +123,106 @@ namespace anm2ed::edit
}
// Clears frame references to the spritesheet's unused regions, then removes them.
Uids regions_remove_unused(Model& model, int spritesheetId)
// Removes content items (regions of spritesheet `spritesheetId`) with what refers to them: a layer's or null's tracks
// in every animation, an event or sound from its triggers (dropping those left with neither), a shader from its
// frames (which go back to the default), a region from its frames (which keep its crop, size and pivot), a
// spritesheet's plain layers, and a library's layers, flattened into plain ones.
Uids content_remove(Model& model, ElementType type, const std::set<int>& ids, int spritesheetId,
const LibraryGet& library_get, const SpritesheetPathGet& path_get)
{
auto unused = model.region_unused_get(spritesheetId);
auto spritesheet = item_get(model.content.spritesheets, spritesheetId);
if (unused.empty() || !spritesheet) return {};
std::erase_if(spritesheet->regions, [&](const Region& region) { return unused.contains(region.id); });
auto& content = model.content;
auto items_erase = [&](auto& items)
{ std::erase_if(items, [&](const auto& item) { return ids.contains(item.id); }); };
auto layer_ids_get = [&](auto&& is_removed)
{
std::set<int> layerIds{};
for (const auto& layer : content.layers)
if (is_removed(layer)) layerIds.insert(layer.id);
return layerIds;
};
// Only the animations that refer to them are edited.
auto animations_edit = [&](auto&& edit)
{
for (int i = 0; i < model.animations_count_get(); ++i)
if (model.uses_count(type, ids, spritesheetId, model.animation_get(i)) > 0) edit(*model.animation_edit(i), i);
};
switch (type)
{
case ElementType::LIBRARY:
model =
animation_layers_flatten(std::move(model), library_get, path_get,
layer_ids_get([&](const Layer& layer) { return ids.contains(layer.libraryId); }));
items_erase(content.libraries);
break;
case ElementType::SPRITESHEET:
content_remove(model, ElementType::LAYER_ELEMENT,
layer_ids_get([&](const Layer& layer)
{ return !layer.is_animation() && ids.contains(layer.spritesheetId); }),
-1, library_get, path_get);
items_erase(content.spritesheets);
break;
case ElementType::LAYER_ELEMENT:
case ElementType::NULL_ELEMENT:
{
auto itemType = type == ElementType::LAYER_ELEMENT ? LAYER : NULL_;
animations_edit([&](Animation&, int index) { items_remove(model, index, {{itemType, ids}}, {}); });
if (type == ElementType::LAYER_ELEMENT)
items_erase(content.layers);
else
items_erase(content.nulls);
break;
}
case ElementType::EVENT_ELEMENT:
case ElementType::SOUND_ELEMENT:
animations_edit(
[&](Animation& animation, int)
{
std::erase_if(animation.triggers.frames,
[&](Frame& trigger)
{
auto& triggerIds =
type == ElementType::EVENT_ELEMENT ? trigger.eventIds : trigger.soundIds;
if (!std::erase_if(triggerIds, [&](int id) { return ids.contains(id); })) return false;
return trigger.eventIds.empty() && trigger.soundIds.empty();
});
});
if (type == ElementType::EVENT_ELEMENT)
items_erase(content.events);
else
items_erase(content.sounds);
break;
case ElementType::SHADER:
animations_edit(
[&](Animation& animation, int)
{
animation_tracks_each(animation,
[&](Track& track)
{
for (auto& frame : track.frames)
if (ids.contains(frame.shaderId)) frame.shaderId = -1;
});
});
items_erase(content.shaders);
break;
case ElementType::REGION:
animations_edit(
[&](Animation& animation, int)
{
tracks_each(animation.layers,
[&](Track& track, auto*)
{
auto layer = item_get(content.layers, track.id);
if (!layer || layer->spritesheetId != spritesheetId) return;
for (auto& frame : track.frames)
if (ids.contains(frame.regionId)) frame.regionId = -1;
});
});
if (auto spritesheet = item_get(content.spritesheets, spritesheetId)) items_erase(spritesheet->regions);
break;
default:
break;
}
return {};
}
+4 -2
View File
@@ -129,7 +129,6 @@ namespace anm2ed::edit
RegionFrameMapping);
Uids regions_scan(model::Model&);
Uids region_frames_sync(model::Model&);
Uids regions_remove_unused(model::Model&, int);
Uids regions_paste(model::Model&, int, const std::string&, int, std::string*);
Uids animation_grid_generate(model::Model&, const std::vector<Reference>&, const GridOptions&);
Uids frames_change_apply(model::Model&, const ChangeTargets&, FrameChange, ChangeType);
@@ -140,6 +139,9 @@ namespace anm2ed::edit
// Where a spritesheet path of a document (this one, or a library) points, from this document.
using SpritesheetPathGet = std::function<std::filesystem::path(const model::Model&, const std::filesystem::path&)>;
model::Model animation_layers_flatten(model::Model, const model::LibraryGet&, const SpritesheetPathGet&);
model::Model animation_layers_flatten(model::Model, const model::LibraryGet&, const SpritesheetPathGet&,
const std::set<int>& = {});
Uids content_remove(model::Model&, ElementType, const std::set<int>&, int, const model::LibraryGet&,
const SpritesheetPathGet&);
bool file_merge(model::Model&, const std::filesystem::path&, const std::filesystem::path&, FileMergePreset);
}
+24 -17
View File
@@ -42,12 +42,16 @@ namespace anm2ed::edit
return a == b;
}
// The game's copy of a document: each animation layer's track becomes plain layer tracks (one per layer its child
// animation draws), baked a frame at a time. A library's spritesheets join the copy, at paths from `path_get`.
Model animation_layers_flatten(Model model, const LibraryGet& library_get, const SpritesheetPathGet& path_get)
// The game's copy of a document: each animation layer's track (or only those of `layerIds`) becomes plain layer
// tracks (one per layer its child animation draws), baked a frame at a time. A library's spritesheets join the copy,
// at paths from `path_get`.
Model animation_layers_flatten(Model model, const LibraryGet& library_get, const SpritesheetPathGet& path_get,
const std::set<int>& layerIds)
{
auto& content = model.content;
if (std::ranges::none_of(content.layers, &Layer::is_animation)) return model;
auto is_flattened = [&](const Layer& layer)
{ return layer.is_animation() && (layerIds.empty() || layerIds.contains(layer.id)); };
if (std::ranges::none_of(content.layers, is_flattened)) return model;
std::map<std::pair<const Model*, int>, int> spritesheetIds{};
auto spritesheet_id_get = [&](const Model* source, int id)
@@ -63,10 +67,10 @@ namespace anm2ed::edit
};
// (animation layer, source, source layer) -> the plain layer standing in for it.
std::map<std::tuple<int, const Model*, int>, int> layerIds{};
std::map<std::tuple<int, const Model*, int>, int> plainIds{};
auto layer_id_get = [&](const Draw& draw)
{
auto [it, isNew] = layerIds.try_emplace({draw.id, draw.source, draw.sourceId});
auto [it, isNew] = plainIds.try_emplace({draw.id, draw.source, draw.sourceId});
if (!isNew) return it->second;
auto parent = item_get(content.layers, draw.id);
auto sourceLayer = item_get(draw.source->content.layers, draw.sourceId);
@@ -84,7 +88,7 @@ namespace anm2ed::edit
auto tracks_flatten = [&](const Track& track)
{
auto layer = item_get(content.layers, track.id);
if (!layer || !layer->is_animation()) return std::vector{track};
if (!layer || !is_flattened(*layer)) return std::vector{track};
std::map<int, std::vector<Frame>> frames{};
std::vector<int> order{};
for (int time = 0; time < source.frameNum; ++time)
@@ -123,24 +127,27 @@ namespace anm2ed::edit
group.tracks.push_back(std::move(flat));
entries.emplace_back(std::move(group));
}
// The children's triggers join the animation's own, on the frames they fire (their events found by name).
// The flattened children's triggers join the animation's own, on the frames they fire (their events found by
// name).
auto triggers = source.triggers;
for (int time = 0; time < source.frameNum; ++time)
{
auto fires = animation_triggers_get(model, source, time, library_get);
auto isOwn = source.triggers.isVisible && frame_generate(source.triggers, (float)time).isVisible;
std::vector<int> eventIds{};
for (int i = isOwn ? 1 : 0; i < (int)fires.size(); ++i)
for (auto eventId : fires[i].trigger.eventIds)
if (auto event = item_get(fires[i].source->content.events, eventId))
for (const auto& fire : animation_triggers_get(model, source, time, library_get))
{
auto layer = item_get(content.layers, fire.layerId);
if (!layer || !is_flattened(*layer)) continue;
for (auto eventId : fire.trigger.eventIds)
if (auto event = item_get(fire.source->content.events, eventId))
{
auto existing = std::ranges::find(content.events, event->name, &Event::name);
eventIds.push_back(existing != content.events.end()
eventIds.push_back(
existing != content.events.end()
? existing->id
: content.events.emplace_back(Event{.id = item_next_id_get(content.events),
.name = event->name})
: content.events.emplace_back(Event{.id = item_next_id_get(content.events), .name = event->name})
.id);
}
}
if (eventIds.empty()) continue;
auto trigger = std::ranges::find(triggers.frames, time, &Frame::atFrame);
if (trigger == triggers.frames.end())
@@ -153,7 +160,7 @@ namespace anm2ed::edit
flattened->layers = std::move(entries);
flattened->triggers = std::move(triggers);
}
std::erase_if(content.layers, [](const Layer& layer) { return layer.is_animation(); });
std::erase_if(content.layers, is_flattened);
return model;
}
}
-1
View File
@@ -15,7 +15,6 @@ namespace anm2ed::imgui
X(ACTION_REDO, SHORTCUT_STRING_REDO, SHORTCUT_REDO) \
X(ACTION_ADD, BASIC_ADD, SHORTCUT_ADD) \
X(ACTION_REMOVE, BASIC_REMOVE, SHORTCUT_REMOVE) \
X(ACTION_REMOVE_UNUSED, BASIC_REMOVE_UNUSED, SHORTCUT_REMOVE) \
X(ACTION_DUPLICATE, BASIC_DUPLICATE, SHORTCUT_DUPLICATE) \
X(ACTION_MERGE, BASIC_MERGE, SHORTCUT_MERGE) \
X(ACTION_GROUP, BASIC_GROUP, SHORTCUT_GROUP) \
+1 -1
View File
@@ -836,7 +836,7 @@ namespace anm2ed::imgui
// The events triggers (the animation's and its children's) fire on this frame.
std::string names{};
if (animation && !isOnlyShowLayers && !manager.isRecording)
for (const auto& [source, trigger] :
for (const auto& [source, trigger, layerId] :
model::animation_triggers_get(model, *animation, (int)frameTime, document.library_resolver_get()))
for (auto eventId : trigger.eventIds)
if (auto event = model::item_get(source->content.events, eventId))
+11 -16
View File
@@ -159,8 +159,8 @@ namespace anm2ed::imgui
// Layers and nulls: properties popup, add, remove unused, copy and paste.
template <class Item, class ItemsGet>
void track_items_actions_add(Actions& actions, Panel& panel, SelectionKind kind, ElementType type,
StringType addTooltip, StringType removeUnusedTooltip, StringType removeUnusedEdit,
StringType pasteEdit, StringType pasteFailToast, ItemsGet items_get)
StringType addTooltip, StringType pasteEdit, StringType pasteFailToast,
ItemsGet items_get)
{
auto selection = panel.document.selected_ids_get(kind);
auto& manager = panel.manager;
@@ -168,9 +168,7 @@ namespace anm2ed::imgui
ACTION_PROPERTIES, [selection]() { return selection.size() == 1; },
[&manager, type, selection]() { manager.item_properties_open(type, *selection.begin()); });
actions.add(ACTION_ADD, {}, [&manager, type]() { manager.item_properties_open(type, -1); }, addTooltip);
actions.add(
ACTION_REMOVE_UNUSED, {}, [&panel, type, removeUnusedEdit, items_get]()
{ items_unused_remove(panel, type, removeUnusedEdit, items_get); }, removeUnusedTooltip);
content_remove_action_add(actions, panel, type, kind);
items_clipboard_actions_add<Item>(actions, panel, kind, pasteEdit, pasteFailToast, items_get);
}
@@ -182,8 +180,8 @@ namespace anm2ed::imgui
{
Actions actions{};
track_items_actions_add<model::Layer>(actions, panel, SelectionKind::LAYERS, ElementType::LAYER_ELEMENT,
TOOLTIP_ADD_LAYER, TOOLTIP_REMOVE_UNUSED_LAYERS, EDIT_REMOVE_UNUSED_LAYERS,
EDIT_PASTE_LAYERS, TOAST_DESERIALIZE_LAYERS_FAILED, layers_get);
TOOLTIP_ADD_LAYER, EDIT_PASTE_LAYERS, TOAST_DESERIALIZE_LAYERS_FAILED,
layers_get);
ListRows rows{.label_get = [&](int id) { return layer_label_get(*model::item_get(layers, id)); },
.is_invalid = [&](int id)
{ return document.is_layer_animation_missing(*model::item_get(layers, id)); },
@@ -195,7 +193,7 @@ namespace anm2ed::imgui
layer_source_tooltip_draw(document, *layer);
},
.activate = [&](int id) { manager.item_properties_open(ElementType::LAYER_ELEMENT, id); }};
list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE_UNUSED}},
list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE}},
[&]() { content_list_draw(panel, SelectionKind::LAYERS, item_ids_get(layers), rows); });
}
ImGui::End();
@@ -217,8 +215,8 @@ namespace anm2ed::imgui
{
Actions actions{};
track_items_actions_add<model::Null>(actions, panel, SelectionKind::NULLS, ElementType::NULL_ELEMENT,
TOOLTIP_ADD_NULL, TOOLTIP_REMOVE_UNUSED_NULLS, EDIT_REMOVE_UNUSED_NULLS,
EDIT_PASTE_NULLS, TOAST_DESERIALIZE_NULLS_FAILED, nulls_get);
TOOLTIP_ADD_NULL, EDIT_PASTE_NULLS, TOAST_DESERIALIZE_NULLS_FAILED,
nulls_get);
ListRows rows{.label_get =
[&](int id)
{
@@ -228,7 +226,7 @@ namespace anm2ed::imgui
.tooltip_draw = [&](int id) { item_tooltip_draw(resources, model::item_get(nulls, id)->name, id); },
.activate = [&](int id) { manager.item_properties_open(ElementType::NULL_ELEMENT, id); },
.isFocusItalic = true};
list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE_UNUSED}},
list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE}},
[&]() { content_list_draw(panel, SelectionKind::NULLS, item_ids_get(nulls), rows); });
}
ImGui::End();
@@ -275,10 +273,7 @@ namespace anm2ed::imgui
});
},
TOOLTIP_ADD_EVENT);
actions.add(
ACTION_REMOVE_UNUSED, {},
[&panel]() { items_unused_remove(panel, ElementType::EVENT_ELEMENT, EDIT_REMOVE_UNUSED_EVENTS, events_get); },
TOOLTIP_REMOVE_UNUSED_EVENTS);
content_remove_action_add(actions, panel, ElementType::EVENT_ELEMENT, SelectionKind::EVENTS);
items_clipboard_actions_add<model::Event>(actions, panel, SelectionKind::EVENTS, EDIT_PASTE_EVENTS,
TOAST_DESERIALIZE_EVENTS_FAILED, events_get);
ListRows rows{.label_get = [&](int id) { return model::item_get(events, id)->name; },
@@ -299,7 +294,7 @@ namespace anm2ed::imgui
},
.tooltip_draw = [&](int id)
{ item_tooltip_draw(resources, model::item_get(events, id)->name, id); }};
list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE_UNUSED}},
list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE}},
[&]() { content_list_draw(panel, SelectionKind::EVENTS, item_ids_get(events), rows); });
}
ImGui::End();
+2 -5
View File
@@ -51,10 +51,7 @@ namespace anm2ed::imgui
actions.add(ACTION_OPEN_DIRECTORY, isOne,
[&]() { directory_open(dialog, document, model::item_get(libraries, *selection.begin())->path); });
actions.add(ACTION_ADD, {}, [&]() { dialog.file_open(Dialog::LIBRARY_OPEN, true); }, TOOLTIP_LIBRARY_ADD);
actions.add(
ACTION_REMOVE_UNUSED, {},
[&]() { items_unused_remove(panel, ElementType::LIBRARY, EDIT_REMOVE_UNUSED_LIBRARIES, libraries_get); },
TOOLTIP_REMOVE_UNUSED_LIBRARIES);
content_remove_action_add(actions, panel, ElementType::LIBRARY, SelectionKind::LIBRARIES);
actions.add(
ACTION_RELOAD, [selection]() { return !selection.empty(); },
[&]()
@@ -115,7 +112,7 @@ namespace anm2ed::imgui
.activate = open,
.cardLines = LIBRARY_CARD_LINES};
list_panel_draw(
panel, actions, {{ACTION_ADD, ACTION_REMOVE_UNUSED, ACTION_RELOAD, ACTION_OPEN}},
panel, actions, {{ACTION_ADD, ACTION_REMOVE, ACTION_RELOAD, ACTION_OPEN}},
[&]() { content_list_draw(panel, SelectionKind::LIBRARIES, item_ids_get(libraries), rows); }, true);
}
ImGui::End();
+147
View File
@@ -17,6 +17,7 @@ using namespace glm;
namespace anm2ed::imgui
{
constexpr float SCROLL_CENTER = 0.5f;
constexpr std::size_t REMOVE_LINES_MAX = 10;
constexpr float TOOLTIP_PADDING_MULTIPLIER = 4.0f;
constexpr float PREVIEW_VIEWPORT_FRACTION = 0.5f;
constexpr const char* CONTEXT_MENU_LABEL = "##Context Menu";
@@ -273,6 +274,151 @@ namespace anm2ed::imgui
}
// The list in a bordered child with its context menu and shortcuts, then the footer buttons.
// The confirmation's lines: the items by name, then what goes with them.
std::vector<std::string> remove_lines_get(const model::Model& model, ElementType type, const std::set<int>& ids,
int spritesheetId)
{
auto& content = model.content;
std::vector<std::string> lines{};
auto names_add = [&](const auto& items, auto&& name_get)
{
for (auto id : ids)
if (auto item = model::item_get(items, id)) lines.push_back(std::format("\"{}\"", name_get(*item)));
};
auto name_get = [](const auto& item) { return item.name; };
auto path_get = [](const auto& item) { return path::to_utf8(item.path); };
auto count_add = [&](StringType format, int count)
{
if (count > 0) lines.push_back(localize_format(format, count));
};
auto layers_add = [&](StringType format, auto&& is_removed)
{
std::set<int> layerIds{};
for (const auto& layer : content.layers)
if (is_removed(layer))
{
layerIds.insert(layer.id);
lines.push_back(localize_format(format, layer.name));
}
return layerIds;
};
auto uses = model.uses_count(type, ids, spritesheetId);
switch (type)
{
case ElementType::LAYER_ELEMENT:
names_add(content.layers, name_get);
count_add(FORMAT_REMOVE_TRACKS, uses);
break;
case ElementType::NULL_ELEMENT:
names_add(content.nulls, name_get);
count_add(FORMAT_REMOVE_TRACKS, uses);
break;
case ElementType::EVENT_ELEMENT:
case ElementType::SOUND_ELEMENT:
{
auto isEvent = type == ElementType::EVENT_ELEMENT;
if (isEvent)
names_add(content.events, name_get);
else
names_add(content.sounds, path_get);
count_add(FORMAT_REMOVE_TRIGGER_USES, uses);
// Triggers whose every event and sound goes.
int emptied{};
for (auto [index, animation] : model.animations_get())
for (const auto& trigger : animation->triggers.frames)
{
auto& own = isEvent ? trigger.eventIds : trigger.soundIds;
auto& other = isEvent ? trigger.soundIds : trigger.eventIds;
emptied +=
other.empty() && !own.empty() && std::ranges::all_of(own, [&](int id) { return ids.contains(id); });
}
count_add(FORMAT_REMOVE_TRIGGERS_EMPTY, emptied);
break;
}
case ElementType::SHADER:
names_add(content.shaders, name_get);
count_add(FORMAT_REMOVE_SHADER_USES, uses);
break;
case ElementType::REGION:
if (auto spritesheet = model::item_get(content.spritesheets, spritesheetId))
names_add(spritesheet->regions, name_get);
count_add(FORMAT_REMOVE_REGION_USES, uses);
break;
case ElementType::SPRITESHEET:
{
names_add(content.spritesheets, path_get);
auto layerIds = layers_add(FORMAT_REMOVE_LAYER, [&](const model::Layer& layer)
{ return !layer.is_animation() && ids.contains(layer.spritesheetId); });
count_add(FORMAT_REMOVE_TRACKS, model.uses_count(ElementType::LAYER_ELEMENT, layerIds));
break;
}
default:
names_add(content.libraries, path_get);
layers_add(FORMAT_REMOVE_FLATTENED_LAYER,
[&](const model::Layer& layer) { return ids.contains(layer.libraryId); });
break;
}
return lines;
}
void content_remove_apply(Panel& panel)
{
command_push(panel,
[removal = panel.state.removal](Document& document)
{
document.edit_apply(EDIT_REMOVE_ITEMS,
[&](model::Model& model)
{
return edit::content_remove(
model, removal.type, removal.ids, removal.spritesheetId,
document.library_resolver_get(), document.spritesheet_path_resolver_get());
});
document.selected_clear(removal.kind);
});
}
// Removes the selected content items; when anything uses them, it asks first, saying what goes with them.
void content_remove_action_add(Actions& actions, Panel& panel, ElementType type, SelectionKind kind,
int spritesheetId)
{
auto selection = panel.document.selected_ids_get(kind);
actions.add(
ACTION_REMOVE, [selection]() { return !selection.empty(); },
[&panel, type, kind, selection, spritesheetId]()
{
auto& model = panel.document.model;
panel.state.removal = {type, kind, selection, spritesheetId,
remove_lines_get(model, type, selection, spritesheetId)};
if (model.uses_count(type, selection, spritesheetId) > 0)
panel.state.removePopup.open();
else
content_remove_apply(panel);
},
TOOLTIP_REMOVE_CONTENT);
}
void content_remove_popup_draw(Panel& panel)
{
auto& popup = panel.state.removePopup;
popup.trigger();
if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end();
auto& removal = panel.state.removal;
ImGui::TextUnformatted(localize.get(TEXT_REMOVE_LIST));
auto& lines = removal.lines;
for (std::size_t i = 0; i < std::min(lines.size(), REMOVE_LINES_MAX); ++i)
ImGui::BulletText("%s", lines[i].c_str());
if (lines.size() > REMOVE_LINES_MAX)
ImGui::BulletText("%s", localize_format(FORMAT_REMOVE_MORE, (int)(lines.size() - REMOVE_LINES_MAX)).c_str());
ImGui::Spacing();
ImGui::TextUnformatted(localize.get(TEXT_REMOVE_CONFIRM));
auto result = popup_buttons_draw(panel.manager, localize.get(BASIC_REMOVE));
if (result == PopupButton::CONFIRM) content_remove_apply(panel);
if (result != PopupButton::NONE) popup.close();
ImGui::EndPopup();
popup.end();
}
void list_panel_draw(Panel& panel, Actions& actions, const Footer& footer, const std::function<void()>& list,
bool isCards, Actions* footerActions)
{
@@ -306,6 +452,7 @@ namespace anm2ed::imgui
if (auto action = std::ranges::find(buttons.items, type, &Action::type); action != buttons.items.end())
action_button_draw(*action, manager, settings, widgetSize, isSameLine);
}
content_remove_popup_draw(panel);
}
void tooltip_name_draw(Resources& resources, const std::string& name)
+11 -16
View File
@@ -50,6 +50,16 @@ namespace anm2ed::imgui
MultiSelectStorage selection{};
ImVec2 tooltipPadding{};
ImVec2 tooltipSpacing{};
PopupHelper removePopup{PopupHelper(LABEL_REMOVE_IN_USE, POPUP_SMALL_NO_HEIGHT)};
// A removal waiting on its confirmation, since what it removes is in use.
struct Removal
{
ElementType type{};
SelectionKind kind{};
std::set<int> ids{};
int spritesheetId{-1};
std::vector<std::string> lines{};
} removal{};
};
// Everything a panel draws with, for one frame. Commands get the document again when they run.
@@ -104,6 +114,7 @@ namespace anm2ed::imgui
void directory_open(Dialog&, Document&, const std::filesystem::path&);
std::filesystem::path asset_path_get(Document&, const std::filesystem::path&);
PopupButton popup_buttons_draw(Manager&, const char*, bool = true, StringType = BASIC_CANCEL);
void content_remove_action_add(Actions&, Panel&, ElementType, SelectionKind, int = -1);
struct SpritesheetsPanel
{
@@ -223,20 +234,4 @@ namespace anm2ed::imgui
[&panel, kind, pasteEdit, failToast, items_get]()
{ items_paste<Item>(panel, kind, pasteEdit, failToast, items_get); });
}
// Removes content items no animation (or layer, for spritesheets) uses.
template <class ItemsGet>
void items_unused_remove(const Panel& panel, ElementType type, StringType edit, ItemsGet items_get)
{
command_push(
panel,
[type, edit, items_get](Document& document)
{
auto unused = document.model.unused_get(type);
if (unused.empty()) return;
document.edit_apply(
edit, [&](model::Model& model)
{ std::erase_if(items_get(model), [&](const auto& item) { return unused.contains(item.id); }); });
});
}
}
+2 -13
View File
@@ -414,18 +414,7 @@ namespace anm2ed::imgui
Actions actions{};
actions.add(ACTION_PROPERTIES, isOne, [&]() { region_properties_open(regions, document, *selection.begin()); });
actions.add(ACTION_ADD, {}, [&]() { region_properties_open(regions, document, -1); }, TOOLTIP_ADD_REGION);
actions.add(
ACTION_REMOVE_UNUSED, {},
[&]()
{
command_push(panel,
[spritesheetId](Document& document)
{
document.edit_apply(EDIT_REMOVE_UNUSED_REGIONS, [&](model::Model& model)
{ return edit::regions_remove_unused(model, spritesheetId); });
});
},
TOOLTIP_REMOVE_UNUSED_REGIONS);
content_remove_action_add(actions, panel, ElementType::REGION, SelectionKind::REGIONS, spritesheetId);
actions.add(
ACTION_TRIM, [selection]() { return !selection.empty(); },
[&]()
@@ -519,7 +508,7 @@ namespace anm2ed::imgui
.drag_drop_update = [&](int id, int index) { return region_drag_drop_update(panel, id, index); },
.cardLines = REGION_CARD_LINES};
list_panel_draw(
panel, actions, {{ACTION_ADD, ACTION_EXPORT, ACTION_REMOVE_UNUSED}},
panel, actions, {{ACTION_ADD, ACTION_EXPORT, ACTION_REMOVE}},
[&]()
{
content_list_draw(panel, SelectionKind::REGIONS, item_ids_get(spritesheet->regions), rows);
+2 -5
View File
@@ -333,10 +333,7 @@ namespace anm2ed::imgui
});
},
TOOLTIP_ADD_SHADER);
actions.add(
ACTION_REMOVE_UNUSED, {},
[&]() { items_unused_remove(panel, ElementType::SHADER, EDIT_REMOVE_UNUSED_SHADERS, shaders_get); },
TOOLTIP_REMOVE_UNUSED_SHADERS);
content_remove_action_add(actions, panel, ElementType::SHADER, SelectionKind::SHADERS);
actions.add(
ACTION_RELOAD, [selection]() { return !selection.empty(); },
[&]()
@@ -379,7 +376,7 @@ namespace anm2ed::imgui
.activate = properties_open,
.cardLines = SHADER_CARD_LINES};
list_panel_draw(
panel, actions, {{ACTION_ADD, ACTION_REMOVE_UNUSED, ACTION_RELOAD}},
panel, actions, {{ACTION_ADD, ACTION_REMOVE, ACTION_RELOAD}},
[&]() { content_list_draw(panel, SelectionKind::SHADERS, item_ids_get(items), rows); }, true);
propertiesPopup.trigger();
+2 -5
View File
@@ -67,10 +67,7 @@ namespace anm2ed::imgui
actions.add(ACTION_PLAY, isOne, [&]() { play(*selection.begin()); }, STRING_UNDEFINED, -1);
actions.add(ACTION_OPEN_DIRECTORY, isOne, [&]() { open(*selection.begin()); });
actions.add(ACTION_ADD, {}, [&]() { dialog.file_open(Dialog::SOUND_OPEN, true); }, TOOLTIP_SOUND_ADD);
actions.add(
ACTION_REMOVE_UNUSED, {},
[&]() { items_unused_remove(panel, ElementType::SOUND_ELEMENT, EDIT_REMOVE_UNUSED_SOUNDS, sounds_get); },
TOOLTIP_REMOVE_UNUSED_SOUNDS);
content_remove_action_add(actions, panel, ElementType::SOUND_ELEMENT, SelectionKind::SOUNDS);
actions.add(
ACTION_RELOAD, [selection]() { return !selection.empty(); },
[&]()
@@ -132,7 +129,7 @@ namespace anm2ed::imgui
.activate = open,
.cardLines = SOUND_CARD_LINES};
list_panel_draw(
panel, actions, {{ACTION_ADD, ACTION_REMOVE_UNUSED, ACTION_RELOAD, ACTION_REPLACE}},
panel, actions, {{ACTION_ADD, ACTION_REMOVE, ACTION_RELOAD, ACTION_REPLACE}},
[&]() { content_list_draw(panel, SelectionKind::SOUNDS, item_ids_get(sounds), rows); }, true);
}
ImGui::End();
+2 -26
View File
@@ -241,31 +241,7 @@ namespace anm2ed::imgui
actions.add(ACTION_OPEN_DIRECTORY, isOne, [&]() { open(*selection.begin()); });
actions.add(ACTION_SET_FILE_PATH, isOne, [&]() { dialog.file_save(Dialog::SPRITESHEET_PATH_SET); });
actions.add(ACTION_ADD, {}, [&]() { dialog.file_open(Dialog::SPRITESHEET_OPEN, true); }, TOOLTIP_ADD_SPRITESHEET);
actions.add(
ACTION_REMOVE_UNUSED, {},
[&]()
{
command_push(panel,
[](Document& document)
{
auto unused = document.model.unused_get(ElementType::SPRITESHEET);
if (unused.empty()) return;
document.edit_apply(EDIT_REMOVE_UNUSED_SPRITESHEETS,
[&](model::Model& model)
{
std::erase_if(model.content.spritesheets,
[&](const model::Spritesheet& spritesheet)
{
if (!unused.contains(spritesheet.id)) return false;
toast_log(Level::INFO, TOAST_REMOVE_SPRITESHEET,
spritesheet.id,
path::to_utf8(spritesheet.path));
return true;
});
});
});
},
TOOLTIP_REMOVE_UNUSED_SPRITESHEETS);
content_remove_action_add(actions, panel, ElementType::SPRITESHEET, SelectionKind::SPRITESHEETS);
actions.add(
ACTION_RELOAD, isAny,
[&]() { command_push(panel, [selection](Document& document) { document.spritesheets_reload(selection); }); },
@@ -365,7 +341,7 @@ namespace anm2ed::imgui
.activate = open,
.cardLines = SPRITESHEET_CARD_LINES};
list_panel_draw(
panel, actions, {{ACTION_ADD, ACTION_RELOAD, ACTION_REPLACE}, {ACTION_REMOVE_UNUSED, ACTION_SAVE}},
panel, actions, {{ACTION_ADD, ACTION_RELOAD, ACTION_REPLACE}, {ACTION_REMOVE, ACTION_SAVE}},
[&]() { content_list_draw(panel, SelectionKind::SPRITESHEETS, item_ids_get(items), rows); }, true);
}
ImGui::End();
+4 -3
View File
@@ -106,11 +106,11 @@ namespace anm2ed::model
}
void animation_triggers_add(std::vector<TriggerFire>& fires, const Model& model, const Animation& animation, int time,
const LibraryGet& library_get, std::vector<const Animation*>& playing)
const LibraryGet& library_get, std::vector<const Animation*>& playing, int layerId = -1)
{
if (animation.triggers.isVisible)
if (auto trigger = frame_generate(animation.triggers, (float)time); trigger.isVisible)
fires.push_back({&model, std::move(trigger)});
fires.push_back({&model, std::move(trigger), layerId});
// A child fires the trigger of each frame it reaches: when its frame (or animation) changes from the parent's last.
tracks_each(
@@ -132,7 +132,8 @@ namespace anm2ed::model
return;
}
playing.push_back(childAnimation);
animation_triggers_add(fires, *childModel, *childAnimation, childTime, library_get, playing);
animation_triggers_add(fires, *childModel, *childAnimation, childTime, library_get, playing,
layerId == -1 ? layer->id : layerId);
playing.pop_back();
});
}
+1
View File
@@ -59,6 +59,7 @@ namespace anm2ed::model
{
const Model* source{};
Frame trigger{};
int layerId{-1}; // the animation's layer whose child fired it; -1 for the animation's own
};
glm::mat4 draw_quad_model_get(const Draw&);
+46 -31
View File
@@ -222,37 +222,60 @@ namespace anm2ed::model
return unused;
}
std::set<int> Model::unused_get(ElementType type, const Animation* only) const
// Each reference to a content item of `type`, as the id it holds: a plain layer's spritesheet or a layer's library, a
// track's layer or null, a trigger's events or sounds, a frame's shader, or (from layers on spritesheet
// `spritesheetId`) a frame's region. With `only`, those in that animation (layers name spritesheets and libraries
// either way).
template <class Callback>
void references_each(const Model& model, ElementType type, int spritesheetId, const Animation* only,
Callback&& callback)
{
std::set<int> used{};
auto used_insert = [&](const Animation& animation)
auto& content = model.content;
if (type == ElementType::SPRITESHEET || type == ElementType::LIBRARY)
{
// An animation layer's spritesheet isn't drawn.
for (const auto& layer : content.layers)
if (type == ElementType::LIBRARY)
callback(layer.libraryId);
else if (!layer.is_animation())
callback(layer.spritesheetId);
return;
}
auto animation_references_each = [&](const Animation& animation)
{
if (type == ElementType::LAYER_ELEMENT || type == ElementType::NULL_ELEMENT)
tracks_each(type == ElementType::LAYER_ELEMENT ? animation.layers : animation.nulls,
[&](const Track& track, auto*) { used.insert(track.id); });
[&](const Track& track, auto*) { callback(track.id); });
if (type == ElementType::EVENT_ELEMENT || type == ElementType::SOUND_ELEMENT)
for (const auto& trigger : animation.triggers.frames)
{
if (type == ElementType::EVENT_ELEMENT) used.insert(trigger.eventIds.begin(), trigger.eventIds.end());
if (type == ElementType::SOUND_ELEMENT) used.insert(trigger.soundIds.begin(), trigger.soundIds.end());
}
for (auto id : type == ElementType::EVENT_ELEMENT ? trigger.eventIds : trigger.soundIds)
callback(id);
if (type == ElementType::SHADER)
animation_tracks_each(animation,
[&](const Track& track)
{
for (const auto& frame : track.frames)
callback(frame.shaderId);
});
if (type == ElementType::REGION)
tracks_each(animation.layers,
[&](const Track& track, auto*)
{
auto layer = item_get(content.layers, track.id);
if (!layer || layer->spritesheetId != spritesheetId) return;
for (const auto& frame : track.frames)
used.insert(frame.shaderId);
callback(frame.regionId);
});
};
if (only) return animation_references_each(*only);
for (auto [index, animation] : model.animations_get())
animation_references_each(*animation);
}
if (type == ElementType::SPRITESHEET || type == ElementType::LIBRARY)
for (const auto& layer : content.layers)
used.insert(type == ElementType::LIBRARY ? layer.libraryId : layer.spritesheetId);
else if (only)
used_insert(*only);
else
for (auto [index, animation] : animations_get())
used_insert(*animation);
std::set<int> Model::unused_get(ElementType type, const Animation* only) const
{
std::set<int> used{};
references_each(*this, type, -1, only, [&](int id) { used.insert(id); });
switch (type)
{
case ElementType::SPRITESHEET:
@@ -274,20 +297,12 @@ namespace anm2ed::model
}
}
std::set<int> Model::region_unused_get(int spritesheetId) const
// How many references there are to the items `ids` (see references_each).
int Model::uses_count(ElementType type, const std::set<int>& ids, int spritesheetId, const Animation* only) const
{
std::set<int> used{};
for (auto [index, animation] : animations_get())
tracks_each(animation->layers,
[&](const Track& track, auto*)
{
auto layer = item_get(content.layers, track.id);
if (!layer || layer->spritesheetId != spritesheetId) return;
for (const auto& frame : track.frames)
used.insert(frame.regionId);
});
auto spritesheet = item_get(content.spritesheets, spritesheetId);
return spritesheet ? unused_ids_get(spritesheet->regions, used) : std::set<int>{};
int count{};
references_each(*this, type, spritesheetId, only, [&](int id) { count += ids.contains(id); });
return count;
}
Handle Model::handle_get(Reference reference, bool isGroup) const
+1 -1
View File
@@ -379,7 +379,7 @@ namespace anm2ed::model
const Spritesheet* layer_spritesheet_get(int) const;
Frame frame_effective(int, const Frame&) const;
std::set<int> unused_get(ElementType, const Animation* = nullptr) const;
std::set<int> region_unused_get(int) const;
int uses_count(ElementType, const std::set<int>&, int = -1, const Animation* = nullptr) const;
std::uint64_t uid_get(Reference, bool = false) const;
Handle handle_get(Reference, bool = false) const;
void uids_repair();
+12 -18
View File
@@ -90,7 +90,6 @@ namespace anm2ed
X(BASIC_RENAME, "Rename", "Renombrar", "Переименовать", "重命名", "이름 변경") \
X(BASIC_RELOAD, "Reload", "Recargar", "Перезагрузить", "重新加载", "다시 불러오기") \
X(BASIC_REMOVE, "Remove", "Remover", "Удалить", "删除", "제거") \
X(BASIC_REMOVE_UNUSED, "Remove Unused", "Remover no utilizados", "Удалить неизпользуемые", "删除未使用", "미사용 시트 제거") \
X(BASIC_REPLACE, "Replace", "Reemplazar", "Заменить", "替换", "교체") \
X(BASIC_REVERSE, "Reverse", "Invertir", "Развернуть", "反转", "역순") \
X(BASIC_ROOT, "Root", "Root", "Корень", "根", "Root") \
@@ -151,7 +150,6 @@ namespace anm2ed
X(EDIT_FPS, "FPS", "FPS", "FPS", "每秒帧数(FPS)", "FPS") \
X(EDIT_GROUP_ITEMS, "Group Item(s)", "Agrupar item(s)", "Сгруппировать элементы", "将项目分组", "항목 그룹화") \
X(EDIT_REMOVE_GROUP, "Remove Group", "Eliminar grupo", "Удалить группу", "删除组", "그룹 삭제") \
X(EDIT_REMOVE_UNUSED_LIBRARIES, "Remove Unused Libraries", "Eliminar Bibliotecas No Usadas", "Удалить неиспользуемые библиотеки", "删除未使用的库", "사용하지 않는 라이브러리 제거") \
X(EDIT_START_MARKER, "Set Start Marker", "Poner Marcador de Inicio", "Начальный маркер", "设置起始标记", "시작 마커 설정") \
X(EDIT_TOGGLE_GROUP_EXPANDED, "Toggle Group Expanded", "Alternar grupo expandido", "Развернуть/свернуть группу", "展开/折叠组", "그룹 펼침 전환") \
X(EDIT_FRAME_COLOR_OFFSET, "Frame Color Offset", "Offset de color de Frame", "Смещение цвета кадра", "帧颜色偏移", "프레임 색상 오프셋") \
@@ -198,13 +196,6 @@ namespace anm2ed
X(EDIT_REMOVE_ANIMATIONS, "Remove Animation(s)", "Remover Animacion(es)", "Удалить анимации", "删除动画层", "애니메이션 제거") \
X(EDIT_REVERSE_FRAMES, "Reverse Frame(s)", "Invertir Frame(s)", "Развернуть кадры", "反转帧", "프레임 역순") \
X(EDIT_REMOVE_ITEMS, "Remove Item(s)", "Remover Item(s)", "Удалить предметы", "删除物品", "항목 제거") \
X(EDIT_REMOVE_UNUSED_EVENTS, "Remove Unused Events", "Remover Eventos No Utilizados", "Удалить неизпользуемые события", "删除未使用的事件", "미사용 이벤트 제거") \
X(EDIT_REMOVE_UNUSED_REGIONS, "Remove Unused Regions", "Remover Regiones No Utilizadas", "Удалить неиспользуемые регионы", "删除未使用的区域", "미사용 영역 제거") \
X(EDIT_REMOVE_UNUSED_LAYERS, "Remove Unused Layers", "Remover Capas No Utilizadas", "Удалить неизпользуемые слои", "删除未使用的动画层", "미사용 레이어 제거") \
X(EDIT_REMOVE_UNUSED_NULLS, "Remove Unused Nulls", "Remover Nulls No Utilizados", "Удалить неизпользуемые нули", "删除未使用的Null", "미사용 Null 제거") \
X(EDIT_REMOVE_UNUSED_SOUNDS, "Remove Unused Sounds", "Remover Sonidos No Utilizados", "Удалить неизпользуемые звуки", "删除未使用的声音", "미사용 사운드 제거") \
X(EDIT_REMOVE_UNUSED_SHADERS, "Remove Unused Shaders", "Remove Unused Shaders", "Remove Unused Shaders", "Remove Unused Shaders", "Remove Unused Shaders") \
X(EDIT_REMOVE_UNUSED_SPRITESHEETS, "Remove Unused Spritesheets", "Remover Spritesheets No Utilizadas", "Удалить неизпользуемые спрайт-листы", "删除未使用的图集", "미사용 스프라이트 시트 제거") \
X(EDIT_RENAME_GROUP, "Rename Group", "Renombrar grupo", "Переименовать группу", "重命名组", "그룹 이름 바꾸기") \
X(EDIT_RENAME_EVENT, "Rename Event", "Renombrar Evento", "Переименовать событие", "重命名事件", "이벤트 이름 바꾸기") \
X(EDIT_REPLACE_SPRITESHEET, "Replace Spritesheet", "Reemplazar Spritesheet", "Заменить спрайт-лист", "替换图集", "스프라이트 시트 교체") \
@@ -248,6 +239,14 @@ namespace anm2ed
X(FORMAT_LAYER_LIBRARY, "Library: {}", "Biblioteca: {}", "Библиотека: {}", "库: {}", "라이브러리: {}") \
X(FORMAT_LIBRARY_ANIMATIONS, "Animations ({0})", "Animaciones ({0})", "Анимации ({0})", "动画 ({0})", "애니메이션 ({0})") \
X(FORMAT_ORIGIN, "Origin: {0}", "Origen: {0}", "Точка отсчета: {0}", "原点: {0}", "원점: {0}") \
X(FORMAT_REMOVE_FLATTENED_LAYER, "Layer \"{0}\" (flattened into plain layers)", "Capa \"{0}\" (aplanada en capas simples)", "Слой \"{0}\" (сводится в обычные слои)", "图层\"{0}\"(展平为普通图层)", "레이어 \"{0}\" (일반 레이어로 평탄화)") \
X(FORMAT_REMOVE_LAYER, "Layer \"{0}\"", "Capa \"{0}\"", "Слой \"{0}\"", "图层\"{0}\"", "레이어 \"{0}\"") \
X(FORMAT_REMOVE_MORE, "...and {0} more", "...y {0} más", "...и ещё {0}", "...以及另外 {0} 项", "...외 {0}개") \
X(FORMAT_REMOVE_REGION_USES, "{0} use(s) on frames (the frames keep its crop, size and pivot)", "{0} uso(s) en Frames (los Frames conservan su recorte, tamaño y pivote)", "{0} использ. в кадрах (кадры сохранят обрезку, размер и опорную точку)", "{0} 处帧上的使用(帧保留其裁剪、尺寸和枢轴)", "프레임에서 {0}회 사용 (프레임은 자르기, 크기, 피벗을 유지)") \
X(FORMAT_REMOVE_SHADER_USES, "{0} use(s) on frames (the frames go back to the default shader)", "{0} uso(s) en Frames (los Frames vuelven al shader por defecto)", "{0} использ. в кадрах (кадры вернутся к шейдеру по умолчанию)", "{0} 处帧上的使用(帧改用默认着色器)", "프레임에서 {0}회 사용 (프레임은 기본 셰이더로 돌아감)") \
X(FORMAT_REMOVE_TRACKS, "{0} track(s), with their frames", "{0} pista(s), con sus Frames", "{0} дорож(ек), вместе с их кадрами", "{0} 条轨道及其帧", "{0}개 트랙과 해당 프레임") \
X(FORMAT_REMOVE_TRIGGERS_EMPTY, "{0} trigger(s) left with no events or sounds", "{0} disparador(es) que quedan sin eventos ni sonidos", "{0} триггер(ов), оставшихся без событий и звуков", "{0} 个没有事件或声音的触发器", "이벤트나 사운드가 남지 않는 트리거 {0}개") \
X(FORMAT_REMOVE_TRIGGER_USES, "{0} use(s) in triggers", "{0} uso(s) en disparadores", "{0} использ. в триггерах", "{0} 处触发器中的使用", "트리거에서 {0}회 사용") \
X(FORMAT_SPRITESHEET_ID, "Spritesheet ID: {0}", "ID de Spritesheet: {0}", "", "图集 ID: {0}", "스프라이트 시트 ID: {0}") \
X(FORMAT_INDEX, "Index: {0}", "Indice: {0}", "Индекс: {0}", "下标: {0}", "인덱스: {0}") \
X(FORMAT_INTERPOLATED, "Interpolation: {0}", "Interpolación: {0}", "Интерполяция: {0}", "插值: {0}", "보간: {0}") \
@@ -306,6 +305,7 @@ namespace anm2ed
X(LABEL_PURGE_DEFAULT_COLORS, "Purge Default Color Values", "Omitir Valores de Color por Defecto", "Убирать цвета по умолчанию", "清除默认颜色值", "기본 색상 값 제거") \
X(LABEL_RANDOM, "Random", "Aleatorio", "Случайно", "随机", "무작위") \
X(LABEL_RASTERIZE, "Rasterize", "Rasterizar", "Растеризовать", "栅格化", "래스터화") \
X(LABEL_REMOVE_IN_USE, "Remove Items in Use", "Remover Elementos en Uso", "Удалить используемые элементы", "删除正在使用的项目", "사용 중인 항목 제거") \
X(LABEL_REMOVE_MARKERS, "Remove Markers", "Quitar Marcadores", "Удалить маркеры", "移除标记", "마커 제거") \
X(LABEL_RESTART, "Restart", "Reiniciar", "Перезапуск", "重新开始", "다시 시작") \
X(LABEL_SAVE_ANYWAY, "Save Anyway", "Guardar de Todos Modos", "Всё равно сохранить", "仍然保存", "그래도 저장") \
@@ -573,6 +573,8 @@ namespace anm2ed
X(TEXT_ISAAC_ISSUES, "Some of this file won't work in the game as it is:", "Parte de este archivo no funcionará tal cual en el juego:", "Часть этого файла не будет работать в игре как есть:", "此文件的部分内容在游戏中无法按原样工作:", "이 파일의 일부는 게임에서 그대로 작동하지 않습니다:") \
X(TEXT_ISAAC_JSON, "Save as JSON is on: the game only reads XML, so it won't be able to load this file. Turn it off in Configure to save a copy the game can read.", "Guardar como JSON está activado: el juego solo lee XML, así que no podrá cargar este archivo. Desactívalo en Configurar para guardar una copia que el juego pueda leer.", "Включено сохранение в JSON: игра читает только XML, поэтому не сможет загрузить этот файл. Отключите это в настройках, чтобы сохранить копию, которую игра сможет прочитать.", "已启用保存为 JSON:游戏只读取 XML,因此无法加载此文件。在配置中关闭此选项以保存游戏可读取的副本。", "JSON으로 저장이 켜져 있습니다: 게임은 XML만 읽으므로 이 파일을 불러올 수 없습니다. 게임이 읽을 수 있는 사본을 저장하려면 설정에서 끄세요.") \
X(TEXT_LAYER_ANIMATION, "Layer's", "De la Capa", "Как у слоя", "图层的", "레이어 기본값") \
X(TEXT_REMOVE_CONFIRM, "Are you sure?", "¿Estás seguro?", "Вы уверены?", "确定吗?", "계속하시겠습니까?") \
X(TEXT_REMOVE_LIST, "This will remove:", "Esto eliminará:", "Будет удалено:", "这将删除:", "다음 항목이 제거됩니다:") \
X(TEXT_SELECT_FRAME, "Select a frame first!", "¡Selecciona primero un frame!", "Сначала выберите кадр!", "请先选择帧!", "먼저 프레임을 선택하세요!") \
X(TEXT_SELECT_FRAME_OR_REGION, "Select a frame or region first!", "¡Selecciona primero un frame o región!", "Сначала выберите кадр или регион!", "请先选择帧或区域!", "먼저 프레임 또는 영역을 선택하세요!") \
X(TOOLTIP_ADD_TRIGGER_EVENT, "Add another event to the trigger; all of them fire on its frame.\n(Only the first reaches the game.)", "Añade otro evento al trigger; todos se disparan en su Frame.\n(Solo el primero llega al juego.)", "Добавить ещё одно событие в триггер; все срабатывают на его кадре.\n(В игру попадает только первое.)", "向触发器添加另一个事件;它们都会在该帧触发。\n(只有第一个会进入游戏。)", "트리거에 이벤트를 하나 더 추가합니다. 모두 해당 프레임에서 발생합니다.\n(게임에는 첫 번째만 전달됩니다.)") \
@@ -651,7 +653,6 @@ namespace anm2ed
X(TOAST_PACK_SPRITESHEET_FAILED, "Failed to pack spritesheet.", "No se pudo empaquetar el spritesheet.", "Не удалось упаковать спрайт-лист.", "图集打包失败。", "스프라이트 시트 패킹에 실패했습니다.") \
X(TOAST_RELOAD_SOUND, "Reloaded sound #{0}: {1}", "Se ha recargado sonido #{0}: {1}", "Звук #{0} перезагружен: {1}", "重新加载了声音 #{0}: {1}", "{0}번 사운드 다시 불러옴: {1}") \
X(TOAST_SCAN_AND_SET_REGIONS, "Matched regionless frames to candidate regions.", "Se emparejaron frames sin region con regiones candidatas.", "Кадры без региона сопоставлены с подходящими регионами.", "已将无区域帧匹配到候选区域。", "영역이 없는 프레임을 후보 영역에 매칭했습니다.") \
X(TOAST_REMOVE_SPRITESHEET, "Removed spritesheet #{0}: {1}", "Se ha removido spritesheet #{0}: {1}", "Спрайт-лист #{0} удален: {1}", "去除了图集 #{0}: {1}", "{0}번 스프라이트 시트 제거됨: {1}") \
X(TOAST_REPLACE_SPRITESHEET, "Replaced spritesheet #{0}: {1}", "Se ha reemplazado spritesheet #{0}: {1}", "Спрайт-лист #{0} заменен: {1}", "替换了图集 #{0}: {1}", "{0}번 스프라이트 시트 교체됨: {1}") \
X(TOAST_REPLACE_SOUND, "Replaced sound #{0}: {1}", "Se ha reemplazado sonido #{0}: {1}", "Звук #{0} заменен: {1}", "已替换声音 #{0}: {1}", "{0}번 사운드 교체됨: {1}") \
X(TOAST_SAVE_DOCUMENT, "Saved document to: {0}", "Documento Guardado en: {0}", "Документ сохранен в: {0}", "保存文件至: {0}", "{0}에 파일을 저장했습니다.") \
@@ -790,8 +791,8 @@ namespace anm2ed
X(TOOLTIP_PREVIEW_ZOOM, "Change the zoom of the preview.", "Cambia el zoom de la vista previa.", "Изменить масштаб предпросмотра.", "更改预览视图的缩放.", "미리보기의 줌을 변경합니다.") \
X(TOOLTIP_PREVIEW_TRANSPARENT, "Toggle the animation preview background being transparent.", "Alterna la transparencia del fondo de la vista previa de animacion.", "Переключить прозрачность фона предпросмотра анимации.", "切换动画预览背景是否透明.", "애니메이션 미리보기 배경을 투명하게 전환합니다.") \
X(TOOLTIP_RELOAD_LIBRARIES, "Reloads the selected libraries.", "Recarga las bibliotecas seleccionadas.", "Перезагружает выбранные библиотеки.", "重新加载所选库.", "선택한 라이브러리를 다시 불러옵니다.") \
X(TOOLTIP_REMOVE_CONTENT, "Remove the selected items. If anything uses them, you are asked first.", "Elimina los elementos seleccionados. Si algo los usa, se te pregunta primero.", "Удалить выбранные элементы. Если что-то их использует, сначала будет запрошено подтверждение.", "删除所选项目。如果有内容正在使用它们,会先询问你。", "선택한 항목을 제거합니다. 사용 중인 경우 먼저 확인합니다.") \
X(TOOLTIP_REMOVE_TRIGGER_EVENT, "Remove the last trigger event.", "Remover el último evento del trigger.", "Удалить последнее событие триггера.", "移除最后一个触发事件。", "마지막 트리거 이벤트를 제거합니다.") \
X(TOOLTIP_REMOVE_UNUSED_LIBRARIES, "Remove libraries no layer plays from.", "Elimina las bibliotecas que ninguna capa usa.", "Удалить библиотеки, которые не использует ни один слой.", "删除没有图层使用的库。", "어떤 레이어도 사용하지 않는 라이브러리를 제거합니다.") \
X(TOOLTIP_SAVE_AS_JSON, "Save documents as JSON (the editor's copy only; the game reads XML). JSON documents are recognized when opened either way.", "Guarda los documentos como JSON (solo la copia del editor; el juego lee XML). Los documentos JSON se reconocen al abrirlos de todas formas.", "Сохранять документы в JSON (только копия редактора; игра читает XML). JSON-документы распознаются при открытии в любом случае.", "将文档保存为 JSON(仅编辑器副本;游戏读取 XML)。无论如何,打开时都会识别 JSON 文档。", "문서를 JSON으로 저장합니다(에디터 사본만, 게임은 XML을 읽습니다). JSON 문서는 어느 경우든 열 때 인식됩니다.") \
X(TOOLTIP_STEP_OUT, "Go back to editing this animation.", "Volver a editar esta animación.", "Вернуться к редактированию этой анимации.", "返回编辑此动画。", "이 애니메이션 편집으로 돌아갑니다.") \
X(TOOLTIP_USE_ANIMATION_BOUNDS, "Render using the animation's bounds instead of the preview viewport.", "Render using the animation's bounds instead of the preview viewport.", "Render using the animation's bounds instead of the preview viewport.", "Render using the animation's bounds instead of the preview viewport.", "Render using the animation's bounds instead of the preview viewport.") \
@@ -802,16 +803,9 @@ namespace anm2ed
X(TOOLTIP_RELOAD_SHADERS, "Reloads the selected shaders.", "Reloads the selected shaders.", "Reloads the selected shaders.", "Reloads the selected shaders.", "Reloads the selected shaders.") \
X(TOOLTIP_REMOVE_ANIMATION, "Remove the selected animation(s).", "Remueve la(s) animacion(es) seleccionada(s).", "Удалить выбранные анимации.", "去除所选动画.", "선택한 애니메이션을 제거합니다.") \
X(TOOLTIP_REMOVE_ITEMS, "Remove the selected item(s).", "Remueve el/los item(s) seleccionado(s).", "Удалить выбранные предметы.", "去除所选物品.", "선택한 항목을 제거합니다.") \
X(TOOLTIP_REMOVE_UNUSED_REGIONS, "Remove unused regions (i.e., ones not used by any frame in any animation.)", "Remueve regiones no utilizadas (es decir, aquellas no usadas por ningun frame en ninguna animacion.)", "Удалить неиспользуемые регионы (т. е. те, которые не используются ни одним кадром ни в одной анимации.)", "移除未使用的区域(即未被任何动画中的任何帧使用的区域。)", "사용되지 않는 영역(어떤 애니메이션의 어떤 프레임에서도 사용되지 않는 것)를 제거합니다.") \
X(TOOLTIP_REMOVE_UNUSED_SHADERS, "Remove unused shaders (i.e., ones not used by any frame in any animation.)", "Remove unused shaders (i.e., ones not used by any frame in any animation.)", "Remove unused shaders (i.e., ones not used by any frame in any animation.)", "Remove unused shaders (i.e., ones not used by any frame in any animation.)", "Remove unused shaders (i.e., ones not used by any frame in any animation.)") \
X(TOOLTIP_EXPORT_MAKE_SPRITESHEET, "Make a new spritesheet from this region.", "Make a new spritesheet from this region.", "Make a new spritesheet from this region.", "Make a new spritesheet from this region.", "Make a new spritesheet from this region.") \
X(TOOLTIP_EXPORT_REMOVE_CURRENT_REGION, "The region will be removed from the current spritesheet.", "The region will be removed from the current spritesheet.", "The region will be removed from the current spritesheet.", "The region will be removed from the current spritesheet.", "The region will be removed from the current spritesheet.") \
X(TOOLTIP_TRIM_REGIONS, "Trim region to non-transparent content.", "Recorta la región al contenido no transparente.", "Обрезать регион до непрозрачного содержимого.", "将区域裁剪到非透明内容。", "영역을 불투명 콘텐츠에 맞게 자릅니다.") \
X(TOOLTIP_REMOVE_UNUSED_EVENTS, "Remove unused events (i.e., ones not used by any trigger in any animation.)", "Remueve eventos no utilizados (i. e., aquellos no usados por algun trigger en ninguna animacion.)", "Удалить неиспользуемые события (т. е. события, которые не использует ни один триггер в ни одной анимации.)", "去除未使用的事件 (未被任何动画触发的事件.)", "사용되지 않는 이벤트(어떤 애니메이션의 트리거에서도 사용되지 않는 것)를 제거합니다.") \
X(TOOLTIP_REMOVE_UNUSED_LAYERS, "Remove unused layers (i.e., ones not used in any animation.)", "Remueve capas no utilizadas (i. e., aquellos no usados en ninguna animacion.)", "Удалить неиспользуемые слои (т. е. слои, которые не используются ни одной анимацией.)", "去除未使用的动画层 (未被任何动画使用的那些)", "사용되지 않는 레이어(어떤 애니메이션에서도 사용되지 않는 것)를 제거합니다.") \
X(TOOLTIP_REMOVE_UNUSED_NULLS, "Remove unused nulls (i.e., ones not used in any animation.)", "Remueve nulls no utilizados (i. e., aquellos no usados en ninguna animacion.)", "Удалить неиспользуемые нули (т. е. нули, которые не используются ни одной анимацией.)", "去除未使用的Null (未被任何动画使用的那些.)", "사용되지 않는 Null(어떤 애니메이션에서도 사용되지 않는 것)을 제거합니다.") \
X(TOOLTIP_REMOVE_UNUSED_SOUNDS, "Remove unused sounds (i.e., ones not used in any trigger.)", "Remueve sonidos no utilizados (i. e., aquellos no usados en ningun trigger.)", "Удалить неиспользуемые звуки (т. е. звуки, которые не используются ни одным триггером.)", "去除未使用的声音 (未被任何触发器使用的那些.)", "사용되지 않는 사운드(어떤 트리거에서도 사용되지 않는 것)를 제거합니다.") \
X(TOOLTIP_REMOVE_UNUSED_SPRITESHEETS, "Remove all unused spritesheets (i.e., not used in any layer.).", "Remueve todos los spritesheets no utilizados (i. e., aquellos no usados en ninguna capa.)", "Удалить неиспользуемые спрайт-листы (т. е. те, которые не используются ни одним слоем.)", "去除未使用的图集 (未被任何动画层使用的那些.)", "사용되지 않는 모든 스프라이트 시트(어떤 레이어에서도 사용되지 않는 것)를 제거합니다.") \
X(TOOLTIP_RENDER_BUTTON, "Render the animation using the current settings.", "Renderiza la animacion usando la configuracion actual", "Рендерировать анимацию, используя текущие настройки.", "应用当前设置去渲染动画.", "현재 설정으로 애니메이션을 렌더링합니다.") \
X(TOOLTIP_RENDER_TYPE, "Set the type of the output.", "Ajusta el tipo de la salida", "Установить тип вывода.", "设置输出的类型.", "출력 유형을 설정합니다.") \
X(TOOLTIP_REPEAT_DELAY, "Set how often, after repeating begins, key inputs will be fired.", "Ajusta que tanto, despues de que empieza la repeticion, seran disparadas las entradas clave.", "Установить, как часто после начала повторения будут срабатывать нажатия клавиш.", "更改键盘按键开启重复时, 重复的速率.", "반복 입력이 시작된 후 입력이 얼마나 자주 들어갈지 설정합니다.") \
@@ -1,41 +0,0 @@
<AnimatedActor>
<Info CreatedBy="fixture" CreatedOn="01/01/2026 12:00:00 PM" Fps="30" Version="2"/>
<Content>
<Spritesheets>
<Spritesheet Id="0" Path="sheet.png">
<Region Id="0" Name="custom" XCrop="0" YCrop="0" Width="16" Height="16" XPivot="3" YPivot="5"/>
<Region Id="1" Name="topleft" XCrop="16" YCrop="0" Width="16" Height="32" Origin="TopLeft"/>
<Region Id="2" Name="center" XCrop="32" YCrop="0" Width="10" Height="20" Origin="Center"/>
<Region Id="3" Name="gap" XCrop="0" YCrop="32" Width="8" Height="8" XPivot="0" YPivot="0"/>
</Spritesheet>
<Spritesheet Id="1" Path="other.png"/>
</Spritesheets>
<Layers>
<Layer Id="0" Name="a" SpritesheetId="0"/>
<Layer Id="1" Name="b" SpritesheetId="1"/>
</Layers>
<Nulls/>
<Events/>
</Content>
<Animations DefaultAnimation="A">
<Animation Name="A" FrameNum="20" Loop="true">
<RootAnimation>
<Frame XPosition="0" YPosition="0" Delay="4" Visible="true" XScale="100" YScale="100" SkewX="0" SkewY="0" RedTint="255" GreenTint="255" BlueTint="255" AlphaTint="255" RedOffset="0" GreenOffset="0" BlueOffset="0" Rotation="0" Interpolated="false"/>
</RootAnimation>
<LayerAnimations>
<LayerAnimation LayerId="0" Visible="true">
<Frame RegionId="0" XPosition="0" YPosition="0" Delay="4" Visible="true" XScale="100" YScale="100" SkewX="0" SkewY="0" RedTint="255" GreenTint="255" BlueTint="255" AlphaTint="255" RedOffset="0" GreenOffset="0" BlueOffset="0" Rotation="0" Interpolated="false"/>
<Frame RegionId="1" XPosition="0" YPosition="0" Delay="4" Visible="true" XScale="100" YScale="100" SkewX="0" SkewY="0" RedTint="255" GreenTint="255" BlueTint="255" AlphaTint="255" RedOffset="0" GreenOffset="0" BlueOffset="0" Rotation="0" Interpolated="false"/>
<Frame RegionId="2" XPosition="0" YPosition="0" Delay="4" Visible="true" XScale="100" YScale="100" SkewX="0" SkewY="0" RedTint="255" GreenTint="255" BlueTint="255" AlphaTint="255" RedOffset="0" GreenOffset="0" BlueOffset="0" Rotation="0" Interpolated="false"/>
<Frame XPivot="1" YPivot="1" XCrop="2" YCrop="2" Width="4" Height="4" XPosition="0" YPosition="0" Delay="4" Visible="true" XScale="100" YScale="100" SkewX="0" SkewY="0" RedTint="255" GreenTint="255" BlueTint="255" AlphaTint="255" RedOffset="0" GreenOffset="0" BlueOffset="0" Rotation="0" Interpolated="false"/>
<Frame RegionId="3" XPosition="0" YPosition="0" Delay="4" Visible="true" XScale="100" YScale="100" SkewX="0" SkewY="0" RedTint="255" GreenTint="255" BlueTint="255" AlphaTint="255" RedOffset="0" GreenOffset="0" BlueOffset="0" Rotation="0" Interpolated="false"/>
</LayerAnimation>
<LayerAnimation LayerId="1" Visible="true">
<Frame XPivot="8" YPivot="8" XCrop="0" YCrop="0" Width="16" Height="16" XPosition="0" YPosition="0" Delay="4" Visible="true" XScale="100" YScale="100" SkewX="0" SkewY="0" RedTint="255" GreenTint="255" BlueTint="255" AlphaTint="255" RedOffset="0" GreenOffset="0" BlueOffset="0" Rotation="0" Interpolated="false"/>
</LayerAnimation>
</LayerAnimations>
<NullAnimations/>
<Triggers/>
</Animation>
</Animations>
</AnimatedActor>
+82 -2
View File
@@ -203,8 +203,6 @@ TEST_CASE("edit layer operations")
return edit::animations_paste(anm2, text, 0, -1, groupIds, nullptr);
},
1},
{"regions_remove_unused", "05_regions.anm2",
[&](model::Model& anm2) { return edit::regions_remove_unused(anm2, 0); }, 0},
{"regions_paste", "05_regions.anm2",
[&](model::Model& anm2)
{
@@ -485,3 +483,85 @@ TEST_CASE("SVG spritesheets pack and merge into SVGs")
REQUIRE(edit::spritesheets_merge(model, {0, 1}, image_get, true, false, false, Origin::TOP_LEFT));
CHECK(model::item_get(model.content.spritesheets, 0)->path == "white.svg");
}
TEST_CASE("content_remove takes what refers to an item with it")
{
auto path_keep = [](const model::Model&, const std::filesystem::path& path) { return path; };
auto remove = [&](model::Model& model, ElementType type, std::set<int> ids, int spritesheetId = -1,
const model::LibraryGet& library_get = {})
{ edit::content_remove(model, type, ids, spritesheetId, library_get, path_keep); };
auto tracks_count = [](const model::Model& model, int layerId)
{
int count{};
for (auto [index, animation] : model.animations_get())
model::tracks_each(animation->layers, [&](const model::Track& track, auto*) { count += track.id == layerId; });
return count;
};
SUBCASE("a layer's tracks, and a spritesheet's plain layers")
{
auto model = fixture_load("02_items.anm2");
CHECK(model.uses_count(ElementType::LAYER_ELEMENT, {0}) == tracks_count(model, 0));
remove(model, ElementType::LAYER_ELEMENT, {0});
CHECK_FALSE(model::item_get(model.content.layers, 0));
CHECK(tracks_count(model, 0) == 0);
CHECK(tracks_count(model, 1) > 0);
CHECK(model.uses_count(ElementType::SPRITESHEET, {1}) == 1);
remove(model, ElementType::SPRITESHEET, {1});
CHECK(model.content.layers.empty());
CHECK(tracks_count(model, 1) == 0);
CHECK(model.content.spritesheets.size() == 1);
}
SUBCASE("an event or sound from its triggers, and triggers left with neither")
{
auto model = fixture_load("02_items.anm2");
auto& triggers = model.animation_get(0)->triggers.frames;
REQUIRE(triggers.size() == 3);
CHECK(model.uses_count(ElementType::SOUND_ELEMENT, {1}) == 2);
remove(model, ElementType::SOUND_ELEMENT, {1});
REQUIRE(triggers.size() == 2);
CHECK(triggers[1].soundIds == std::vector{0});
remove(model, ElementType::EVENT_ELEMENT, {0});
REQUIRE(triggers.size() == 2);
CHECK(triggers[0].eventIds.empty());
CHECK(triggers[0].soundIds == std::vector{0});
}
SUBCASE("a shader, and a region, from their frames")
{
auto shaders = fixture_load("06_shaders.anm2");
remove(shaders, ElementType::SHADER, {0});
CHECK(shaders.frame_get({0, LAYER, 0, 0})->shaderId == -1);
CHECK(shaders.frame_get({0, LAYER, 0, 1})->shaderId == 4);
auto regions = fixture_load("05_regions.anm2");
auto before = *regions.frame_get({0, LAYER, 0, 0});
REQUIRE(before.regionId == 0);
CHECK(regions.uses_count(ElementType::REGION, {0}, 0) == 1);
remove(regions, ElementType::REGION, {0}, 0);
auto after = *regions.frame_get({0, LAYER, 0, 0});
CHECK(after.regionId == -1);
CHECK(after.crop == before.crop);
CHECK(after.size == before.size);
CHECK(after.pivot == before.pivot);
CHECK_FALSE(model::item_get(regions.content.spritesheets.front().regions, 0));
}
SUBCASE("a library's layers, flattened")
{
auto model = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
CHECK(model.uses_count(ElementType::LIBRARY, {0}) == 1);
remove(model, ElementType::LIBRARY, {0}, -1,
[&](const model::Model&, int id) { return id == 0 ? &spin : nullptr; });
CHECK(model.content.libraries.empty());
CHECK_FALSE(model::item_get(model.content.layers, 0));
CHECK(
std::ranges::any_of(model.content.layers, [](const model::Layer& layer) { return layer.name == "spin/red"; }));
// Layers playing this file's animations stay as they are.
CHECK(model::item_get(model.content.layers, 1)->is_animation());
CHECK(model::item_get(model.content.layers, 3)->is_animation());
}
}