Slim Document: move data-model code out, unify edit plumbing

- Region generate/scan move to anm2/regions.cpp; both generators number from 1
- file_merge moves to anm2/merge.cpp and is table-driven
- MaxRects packer moves to util/pack
- Uniform config apply/trim/save move to resource/shader
- Snapshots push from their owned state; Document snapshot wrappers removed
- DocumentData base replaces the hand-written move constructor
- toast_log replaces 55 duplicated toast + English log pairs
- Apply repo .clang-format to touched files

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shweetandClaude Opus 5.5 committed 2026-10-03 13:08:00 -04:00
1 parent a9f48bc3a0
commit 3f31cedeed
32 files changed
+3405 -4428

No files matched your search

+22 -5
View File
@@ -1,5 +1,6 @@
#pragma once #pragma once
#include <algorithm>
#include <cstdint> #include <cstdint>
#include <filesystem> #include <filesystem>
#include <optional> #include <optional>
@@ -8,7 +9,6 @@
#include <string_view> #include <string_view>
#include <type_traits> #include <type_traits>
#include <vector> #include <vector>
#include <algorithm>
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <tinyxml2/tinyxml2.h> #include <tinyxml2/tinyxml2.h>
@@ -193,6 +193,20 @@ namespace anm2ed
#undef X #undef X
}; };
enum class RegionFrameMapping
{
PRESERVE,
SET
};
enum FileMergePreset
{
FILE_MERGE_PRESET_MERGE_BY_NAME,
FILE_MERGE_PRESET_APPEND_AS_NEW,
FILE_MERGE_PRESET_REPLACE_MATCHING,
FILE_MERGE_PRESET_COUNT
};
enum class ChangeType enum class ChangeType
{ {
ADJUST, ADJUST,
@@ -401,8 +415,8 @@ namespace anm2ed
template <class E> ElementPointer<E> shader_uniform_component_get(E& uniform, int index) template <class E> ElementPointer<E> shader_uniform_component_get(E& uniform, int index)
{ {
return child_find( return child_find(uniform, [&](const Element& child)
uniform, [&](const Element& child) { return child.type == ElementType::COMPONENT && child.index == index; }); { return child.type == ElementType::COMPONENT && child.index == index; });
} }
template <class E> ElementPointer<E> element_first_get(E& element, ElementType type) template <class E> ElementPointer<E> element_first_get(E& element, ElementType type)
@@ -432,8 +446,7 @@ namespace anm2ed
} }
template <class E> template <class E>
ElementPointer<E> animation_item_get(E& animation, ItemType type, int id = -1, int groupType = NONE, ElementPointer<E> animation_item_get(E& animation, ItemType type, int id = -1, int groupType = NONE, int groupId = -1)
int groupId = -1)
{ {
auto trackType = TYPE_TRACKS[(int)type]; auto trackType = TYPE_TRACKS[(int)type];
auto isGrouped = groupType != NONE && groupId != -1; auto isGrouped = groupType != NONE && groupId != -1;
@@ -495,6 +508,7 @@ namespace anm2ed
int element_child_max_id_get(const Element&, ElementType); int element_child_max_id_get(const Element&, ElementType);
bool element_child_id_erase(Element&, ElementType, int); bool element_child_id_erase(Element&, ElementType, int);
int track_frames_count_get(const Element&); int track_frames_count_get(const Element&);
int animations_count_get(const Element&);
float interpolation_factor(Interpolation, float); float interpolation_factor(Interpolation, float);
void frame_mix(Element&, const Element&, float); void frame_mix(Element&, const Element&, float);
Element frame_generate(const Element&, float); Element frame_generate(const Element&, float);
@@ -542,5 +556,8 @@ namespace anm2ed
bool animations_deserialize(const std::string&, int, std::set<int>&, std::string* = nullptr, bool animations_deserialize(const std::string&, int, std::set<int>&, std::string* = nullptr,
std::set<int>* = nullptr); std::set<int>* = nullptr);
int animations_merge(int, std::set<int>&, types::merge::Type = types::merge::APPEND, bool = true); int animations_merge(int, std::set<int>&, types::merge::Type = types::merge::APPEND, bool = true);
bool file_merge(const std::filesystem::path&, const std::filesystem::path&, FileMergePreset);
bool regions_generate(const std::set<int>&, const std::set<Reference>&, const std::string&, RegionFrameMapping);
void regions_scan();
}; };
} }
+29 -1
View File
@@ -61,7 +61,6 @@ namespace anm2ed
ElementType group_child_type_get(ElementType); ElementType group_child_type_get(ElementType);
Element* content_container_get(Element&, ElementType); Element* content_container_get(Element&, ElementType);
std::unordered_map<int, int> child_ids_compact(Element&, ElementType); std::unordered_map<int, int> child_ids_compact(Element&, ElementType);
int animations_count_get(const Element&);
int animations_child_index_get(const Element&, int); int animations_child_index_get(const Element&, int);
int animations_child_insert_index_get(const Element&, int); int animations_child_insert_index_get(const Element&, int);
Element root_animation_make(); Element root_animation_make();
@@ -88,6 +87,35 @@ namespace anm2ed
void special_interpolated_frames_bake(Element&, int, bool, bool); void special_interpolated_frames_bake(Element&, int, bool, bool);
void all_interpolated_frames_bake(Element&, int, bool, bool); void all_interpolated_frames_bake(Element&, int, bool, bool);
int color_write(float); int color_write(float);
bool is_region_matched(const Element&, const Element&);
Element* region_match_get(Element&, const Element&);
template <class Callback> void layer_frames_each(Element& root, Element& animation, Callback&& callback)
{
auto layers = content_container_get(root, ElementType::LAYERS);
auto spritesheets = content_container_get(root, ElementType::SPRITESHEETS);
auto tracks = child_first_get(animation, ElementType::LAYER_ANIMATIONS);
if (!layers || !spritesheets || !tracks) return;
tracks_each(*tracks, ElementType::LAYER_ANIMATION,
[&](Element& track)
{
auto layer = child_id_get(*layers, ElementType::LAYER_ELEMENT, track.layerId);
auto spritesheet =
layer ? child_id_get(*spritesheets, ElementType::SPRITESHEET, layer->spritesheetId) : nullptr;
if (!spritesheet) return;
for (auto& frame : track.children)
if (frame.type == ElementType::FRAME) callback(frame, *spritesheet);
});
}
template <class Callback> void layer_frames_each(Element& root, Callback&& callback)
{
if (auto animations = element_first_get(root, ElementType::ANIMATIONS))
for (auto& animation : animations->children)
if (animation.type == ElementType::ANIMATION) layer_frames_each(root, animation, callback);
}
std::uint64_t anm2_hash_get(const Element&, Options); std::uint64_t anm2_hash_get(const Element&, Options);
std::uint64_t element_hash(const Element&, Flags); std::uint64_t element_hash(const Element&, Flags);
} }
+226 -1
View File
@@ -104,7 +104,8 @@ namespace anm2ed
[&](const Element& child) [&](const Element& child)
{ {
return child.type == ElementType::GROUP && return child.type == ElementType::GROUP &&
child.name == sourceGroup.name && !matchedGroupIds.contains(child.id); child.name == sourceGroup.name &&
!matchedGroupIds.contains(child.id);
}); });
if (destinationGroup == destinationTracks->children.end()) if (destinationGroup == destinationTracks->children.end())
@@ -182,4 +183,228 @@ namespace anm2ed
finalAnimation->frameNum = animation_length_get(*finalAnimation); finalAnimation->frameNum = animation_length_get(*finalAnimation);
return finalIndex; return finalIndex;
} }
bool Anm2::file_merge(const std::filesystem::path& path, const std::filesystem::path& directory,
FileMergePreset preset)
{
Anm2 source(path);
if (!source.isValid) return false;
auto isAppendAsNew = preset == FILE_MERGE_PRESET_APPEND_AS_NEW;
std::map<ElementType, std::unordered_map<int, int>> remaps{};
auto path_remap = [&](const std::filesystem::path& original)
{
if (directory.empty() || original.empty()) return original;
std::error_code ec{};
auto absolute =
original.is_absolute() ? original : std::filesystem::weakly_canonical(path.parent_path() / original, ec);
if (ec) absolute = path.parent_path() / original;
auto relative = std::filesystem::relative(absolute, directory, ec);
return ec ? original : relative;
};
auto id_remap = [&](ElementType type, int id)
{
auto it = remaps[type].find(id);
return it == remaps[type].end() ? -1 : it->second;
};
auto name_find = [](Element& container, ElementType type, const std::string& name)
{ return child_find(container, [&](const Element& child) { return child.type == type && child.name == name; }); };
auto name_unique_get = [&](Element& container, ElementType type, const std::string& name)
{
auto candidate = name;
for (int i = 2; name_find(container, type, candidate); ++i)
candidate = std::format("{} {}", name, i);
return candidate;
};
auto named_element_merge = [&](Element& container, Element item)
{
auto existing = isAppendAsNew ? nullptr : name_find(container, item.type, item.name);
if (existing)
{
item.id = existing->id;
*existing = item;
return item.id;
}
item.id = element_child_next_id_get(container, item.type);
if (isAppendAsNew) item.name = name_unique_get(container, item.type, item.name);
container.children.push_back(item);
return item.id;
};
auto spritesheet_import = [&](int sourceId)
{
auto& remap = remaps[ElementType::SPRITESHEET];
if (remap.contains(sourceId)) return remap[sourceId];
auto spritesheet = source.element_get(ElementType::SPRITESHEET, sourceId);
auto destination = element_get(ElementType::SPRITESHEETS);
if (sourceId < 0 || !spritesheet || !destination) return -1;
auto imported = *spritesheet;
imported.id = element_child_next_id_get(*destination, ElementType::SPRITESHEET);
imported.path = path_remap(imported.path);
destination->children.push_back(imported);
return remap[sourceId] = imported.id;
};
auto sourceSounds = source.element_get(ElementType::SOUNDS);
auto destinationSounds = element_get(ElementType::SOUNDS);
if (sourceSounds && destinationSounds)
for (auto sound : sourceSounds->children)
{
if (sound.type != ElementType::SOUND_ELEMENT) continue;
auto sourceId = sound.id;
sound.path = path_remap(sound.path);
auto existing = isAppendAsNew ? nullptr
: child_find(*destinationSounds, [&](const Element& child)
{ return child.type == sound.type && child.path == sound.path; });
sound.id = existing ? existing->id : element_child_next_id_get(*destinationSounds, sound.type);
if (existing)
*existing = sound;
else
destinationSounds->children.push_back(sound);
remaps[sound.type][sourceId] = sound.id;
}
for (auto type : {ElementType::LAYER_ELEMENT, ElementType::NULL_ELEMENT, ElementType::EVENT_ELEMENT})
{
auto sourceContainer = source.element_get(ELEMENT_CONTAINERS[(int)type]);
auto destinationContainer = element_get(ELEMENT_CONTAINERS[(int)type]);
if (!sourceContainer || !destinationContainer) continue;
for (auto item : sourceContainer->children)
{
if (item.type != type) continue;
if (type == ElementType::LAYER_ELEMENT)
{
auto existing = isAppendAsNew ? nullptr : name_find(*destinationContainer, type, item.name);
item.spritesheetId = existing ? existing->spritesheetId : spritesheet_import(item.spritesheetId);
}
remaps[type][item.id] = named_element_merge(*destinationContainer, item);
}
}
auto item_remap = [&](Element& item)
{
for (auto& frame : item.children)
{
if (frame.type != ElementType::FRAME && frame.type != ElementType::TRIGGER) continue;
for (auto& soundId : frame.soundIds)
soundId = id_remap(ElementType::SOUND_ELEMENT, soundId);
frame.eventId = id_remap(ElementType::EVENT_ELEMENT, frame.eventId);
}
};
auto animation_build = [&](const Element& incoming)
{
auto animation = element_make(ElementType::ANIMATION);
animation.name = incoming.name;
animation.frameNum = incoming.frameNum;
animation.isLoop = incoming.isLoop;
auto single_track_build = [&](ElementType type)
{
if (auto track = child_first_get(incoming, type)) item_remap(animation.children.emplace_back(*track));
};
single_track_build(ElementType::ROOT_ANIMATION);
for (const auto& row : TRACK_CONTAINERS)
{
auto sourceTracks = child_first_get(incoming, row.container);
if (!sourceTracks) continue;
auto container = element_make(row.container);
for (auto item : sourceTracks->children)
{
if (item.type == ElementType::GROUP)
{
std::erase_if(item.children,
[](const Element& child) { return child.type != ElementType::ROOT_ANIMATION; });
if (item.children.empty()) item.children.push_back(root_animation_make());
if (item.id == -1) item.id = element_child_next_id_get(container, ElementType::GROUP);
container.children.push_back(item);
continue;
}
if (item.type != row.track) continue;
item.*(row.id) = id_remap(row.element, item.*(row.id));
if (item.*(row.id) < 0) continue;
item_remap(item);
container.children.push_back(item);
}
animation.children.push_back(container);
}
single_track_build(ElementType::TRIGGERS);
return animation;
};
auto sourceAnimations = source.element_get(ElementType::ANIMATIONS);
auto destinationAnimations = element_get(ElementType::ANIMATIONS);
if (!sourceAnimations || !destinationAnimations) return true;
std::string defaultAnimationName{};
for (const auto& incoming : sourceAnimations->children)
{
if (incoming.type != ElementType::ANIMATION) continue;
auto processed = animation_build(incoming);
auto destination = name_find(*destinationAnimations, ElementType::ANIMATION, processed.name);
if (isAppendAsNew)
processed.name = name_unique_get(*destinationAnimations, ElementType::ANIMATION, processed.name);
if (incoming.name == sourceAnimations->defaultAnimation) defaultAnimationName = processed.name;
if (!destination || isAppendAsNew)
{
destinationAnimations->children.push_back(processed);
continue;
}
if (preset == FILE_MERGE_PRESET_REPLACE_MATCHING)
{
*destination = processed;
continue;
}
destination->isLoop = processed.isLoop;
for (auto type : {ElementType::ROOT_ANIMATION, ElementType::TRIGGERS})
if (auto track = child_first_get(processed, type); track && !track->children.empty())
child_ensure(*destination, type) = *track;
for (const auto& row : TRACK_CONTAINERS)
{
auto sourceTracks = child_first_get(processed, row.container);
if (!sourceTracks) continue;
auto& destinationTracks = child_ensure(*destination, row.container);
std::unordered_map<int, int> groupRemap{};
for (auto item : sourceTracks->children)
{
if (item.type != ElementType::GROUP) continue;
auto sourceGroupId = item.id;
item.id = element_child_next_id_get(destinationTracks, ElementType::GROUP);
destinationTracks.children.push_back(item);
groupRemap[sourceGroupId] = item.id;
}
for (auto item : sourceTracks->children)
{
if (item.type != row.track) continue;
if (item.groupId != -1) item.groupId = groupRemap.contains(item.groupId) ? groupRemap[item.groupId] : -1;
if (auto existing = track_find(destinationTracks, row.track, track_id_get(item)))
{
if (!item.children.empty()) *existing = item;
}
else
destinationTracks.children.push_back(item);
}
}
destination->frameNum = std::max({destination->frameNum, processed.frameNum, animation_length_get(*destination)});
}
if (destinationAnimations->defaultAnimation.empty() && !sourceAnimations->defaultAnimation.empty())
destinationAnimations->defaultAnimation =
defaultAnimationName.empty() ? sourceAnimations->defaultAnimation : defaultAnimationName;
return true;
}
} }
+3 -30
View File
@@ -15,25 +15,6 @@ namespace anm2ed
}); });
} }
template <class Callback> void layer_frames_each(Element& root, Callback&& callback)
{
auto layers = content_container_get(root, ElementType::LAYERS);
auto spritesheets = content_container_get(root, ElementType::SPRITESHEETS);
if (!layers || !spritesheets) return;
animations_tracks_each(root, ElementType::LAYER_ANIMATION,
[&](Element& track)
{
auto layer = child_id_get(*layers, ElementType::LAYER_ELEMENT, track.layerId);
auto spritesheet = layer ? child_id_get(*spritesheets, ElementType::SPRITESHEET,
layer->spritesheetId)
: nullptr;
if (!spritesheet) return;
for (auto& frame : track.children)
if (frame.type == ElementType::FRAME) callback(frame, *spritesheet);
});
}
void shader_ids_repair(Element& root) void shader_ids_repair(Element& root)
{ {
auto shaders = content_container_get(root, ElementType::SHADERS); auto shaders = content_container_get(root, ElementType::SHADERS);
@@ -69,21 +50,13 @@ namespace anm2ed
void region_frame_ids_repair(Element& root) void region_frame_ids_repair(Element& root)
{ {
layer_frames_each(root, layer_frames_each(root,
[](Element& frame, const Element& spritesheet) [](Element& frame, Element& spritesheet)
{ {
auto is_region_match = [&](const Element& region)
{
return region.type == ElementType::REGION &&
glm::ivec2(region.crop) == glm::ivec2(frame.crop) &&
glm::ivec2(region.size) == glm::ivec2(frame.size) &&
glm::ivec2(region.pivot) == glm::ivec2(frame.pivot);
};
auto region = frame.regionId == -1 auto region = frame.regionId == -1
? nullptr ? nullptr
: child_id_get(spritesheet, ElementType::REGION, frame.regionId); : child_id_get(spritesheet, ElementType::REGION, frame.regionId);
if (region && is_region_match(*region)) return; if (region && is_region_matched(*region, frame)) return;
if (auto candidate = child_find(spritesheet, is_region_match)) frame.regionId = candidate->id; if (auto match = region_match_get(spritesheet, frame)) frame.regionId = match->id;
}); });
} }
+82
View File
@@ -0,0 +1,82 @@
#include "internal.hpp"
namespace anm2ed
{
std::string region_name_get(const std::string& format, int number)
{
try
{
return std::vformat(format, std::make_format_args(number));
}
catch (const std::format_error&)
{
return format;
}
}
bool is_region_matched(const Element& region, const Element& frame)
{
return region.type == ElementType::REGION && glm::ivec2(region.crop) == glm::ivec2(frame.crop) &&
glm::ivec2(region.size) == glm::ivec2(frame.size) && glm::ivec2(region.pivot) == glm::ivec2(frame.pivot);
}
Element* region_match_get(Element& spritesheet, const Element& frame)
{
return child_find(spritesheet, [&](const Element& region) { return is_region_matched(region, frame); });
}
bool Anm2::regions_generate(const std::set<int>& animationIndices, const std::set<Reference>& frameReferences,
const std::string& format, RegionFrameMapping mapping)
{
std::vector<std::pair<Element*, Element*>> frames{};
for (auto animationIndex : animationIndices)
if (auto animation = element_get(ElementType::ANIMATION, animationIndex))
layer_frames_each(root, *animation,
[&](Element& frame, Element& spritesheet) { frames.emplace_back(&frame, &spritesheet); });
for (auto frameReference : frameReferences)
{
if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) continue;
auto frame = element_get(frameReference);
auto layer = element_get(ElementType::LAYER_ELEMENT, frameReference.itemID);
auto spritesheet = layer ? element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr;
if (frame && frame->type == ElementType::FRAME && frame->regionId == -1 && spritesheet)
frames.emplace_back(frame, spritesheet);
}
std::unordered_map<int, int> regionNumbers{};
bool isChanged{};
for (auto [frame, spritesheet] : frames)
{
auto region = region_match_get(*spritesheet, *frame);
if (!region)
{
auto id = element_child_next_id_get(*spritesheet, ElementType::REGION);
region = &spritesheet->children.emplace_back(element_make(ElementType::REGION));
region->id = id;
region->name = region_name_get(format, ++regionNumbers[spritesheet->id]);
region->crop = frame->crop;
region->size = frame->size;
region->pivot = frame->pivot;
isChanged = true;
}
if (mapping == RegionFrameMapping::SET && frame->regionId != region->id)
{
frame->regionId = region->id;
isChanged = true;
}
}
return isChanged;
}
void Anm2::regions_scan()
{
layer_frames_each(root,
[](Element& frame, Element& spritesheet)
{
if (frame.regionId != -1) return;
if (auto region = region_match_get(spritesheet, frame)) frame.regionId = region->id;
});
}
}
+1 -2
View File
@@ -85,8 +85,7 @@ namespace anm2ed
auto pathUtf8 = path::to_utf8(path); auto pathUtf8 = path::to_utf8(path);
system(std::format("xdg-open \"{}\" &", pathUtf8).c_str()); system(std::format("xdg-open \"{}\" &", pathUtf8).c_str());
#else #else
toasts.push(localize.get(TOAST_NOT_SUPPORTED)); toast_log(Level::WARNING, TOAST_NOT_SUPPORTED);
logger.warning(localize.get(TOAST_NOT_SUPPORTED, anm2ed::ENGLISH));
#endif #endif
} }
+365 -1675
View File
File diff suppressed because it is too large. Load diff
+39 -95
View File
@@ -20,7 +20,41 @@ namespace anm2ed
class Manager; class Manager;
struct Command; struct Command;
class Document struct DocumentData
{
std::filesystem::path path{};
uint64_t tabId{};
Snapshots snapshots{};
std::map<int, Storage> regionBySpritesheet{};
int changeAllFramePropertiesRegionId{-1};
int changeAllFramePropertiesShaderId{-1};
float previewZoom{200};
glm::vec2 previewPan{};
glm::vec2 editorPan{};
float editorZoom{200};
int overlayIndex{-1};
uint64_t overlayDocumentId{};
uint64_t hash{};
uint64_t saveHash{};
uint64_t autosaveHash{};
double lastAutosaveTime{};
bool isValid{true};
bool isOpen{true};
bool isForceDirty{false};
std::unordered_map<int, uint64_t> spritesheetHashes{};
std::unordered_map<int, uint64_t> spritesheetSaveHashes{};
std::unordered_map<int, std::filesystem::path> texturePaths{};
std::unordered_map<int, std::filesystem::path> soundPaths{};
std::map<int, std::filesystem::path> shaderVertexPaths{};
std::map<int, std::filesystem::path> shaderFragmentPaths{};
std::map<int, resource::Shader> shaders{};
bool isAnimationPreviewSet{false};
bool isSpritesheetEditorSet{false};
};
class Document : public DocumentData
{ {
public: public:
enum ChangeType enum ChangeType
@@ -54,72 +88,13 @@ namespace anm2ed
SPRITESHEET SPRITESHEET
}; };
enum class RegionFrameMapping
{
PRESERVE,
SET
};
enum FileMergePreset
{
FILE_MERGE_PRESET_MERGE_BY_NAME,
FILE_MERGE_PRESET_APPEND_AS_NEW,
FILE_MERGE_PRESET_REPLACE_MATCHING,
FILE_MERGE_PRESET_COUNT
};
std::filesystem::path path{};
uint64_t tabId{};
Snapshots snapshots{};
Snapshot& current = snapshots.current; Snapshot& current = snapshots.current;
#define X(type, name) type& name = current.name;
Playback& playback = current.playback; SNAPSHOT_STEP_STATE_FIELDS
Storage& animation = current.animation; SNAPSHOT_STEP_RESOURCE_FIELDS
Storage& event = current.event; #undef X
Storage& frames = current.frames;
Storage& items = current.items;
Storage& layer = current.layer;
Storage& merge = current.merge;
Storage& null = current.null;
Storage& region = current.region;
Storage& shader = current.shader;
Storage& sound = current.sound;
Storage& spritesheet = current.spritesheet;
std::map<int, resource::Texture>& textures = current.textures;
std::map<int, resource::Audio>& sounds = current.sounds;
Anm2& anm2 = current.anm2; Anm2& anm2 = current.anm2;
Reference& reference = current.reference;
std::set<Reference>& groupReferences = current.groupReferences;
float& frameTime = current.frameTime;
std::string& message = current.message; std::string& message = current.message;
std::map<int, Storage> regionBySpritesheet{};
int changeAllFramePropertiesRegionId{-1};
int changeAllFramePropertiesShaderId{-1};
float previewZoom{200};
glm::vec2 previewPan{};
glm::vec2 editorPan{};
float editorZoom{200};
int overlayIndex{-1};
uint64_t overlayDocumentId{};
uint64_t hash{};
uint64_t saveHash{};
uint64_t autosaveHash{};
double lastAutosaveTime{};
bool isValid{true};
bool isOpen{true};
bool isForceDirty{false};
std::unordered_map<int, uint64_t> spritesheetHashes{};
std::unordered_map<int, uint64_t> spritesheetSaveHashes{};
std::unordered_map<int, std::filesystem::path> texturePaths{};
std::unordered_map<int, std::filesystem::path> soundPaths{};
std::map<int, std::filesystem::path> shaderVertexPaths{};
std::map<int, std::filesystem::path> shaderFragmentPaths{};
std::map<int, resource::Shader> shaders{};
bool isAnimationPreviewSet{false};
bool isSpritesheetEditorSet{false};
EditTarget editTarget{EditTarget::NONE}; EditTarget editTarget{EditTarget::NONE};
Document(const std::filesystem::path&, bool = false, std::string* = nullptr); Document(const std::filesystem::path&, bool = false, std::string* = nullptr);
@@ -128,25 +103,17 @@ namespace anm2ed
Document(Document&&) noexcept; Document(Document&&) noexcept;
Document& operator=(Document&&) noexcept; Document& operator=(Document&&) noexcept;
bool save(const std::filesystem::path& = {}, std::string* = nullptr, Options = {}); bool save(const std::filesystem::path& = {}, std::string* = nullptr, Options = {});
void anm2_change(ChangeType);
void assets_sync(ChangeType = ALL); void assets_sync(ChangeType = ALL);
void texture_change(int); void texture_change(int);
bool texture_reload(int); bool texture_reload(int);
bool sound_reload(int); bool sound_reload(int);
bool shader_reload(int, std::string* = nullptr); bool shader_reload(int, std::string* = nullptr);
resource::Texture* texture_get(int); resource::Texture* texture_get(int);
const resource::Texture* texture_get(int) const;
resource::Audio* sound_get(int); resource::Audio* sound_get(int);
const resource::Audio* sound_get(int) const;
resource::Shader* shader_get(int); resource::Shader* shader_get(int);
const resource::Shader* shader_get(int) const;
bool regions_trim(int, const std::set<int>&); bool regions_trim(int, const std::set<int>&);
bool regions_generate_from_animations(const std::set<int>&, const std::string&, RegionFrameMapping);
bool regions_generate_from_frames(const std::set<Reference>&, const std::string&, RegionFrameMapping);
bool spritesheet_pack(int, int); bool spritesheet_pack(int, int);
bool spritesheets_merge(const std::set<int>&, bool, bool, bool, origin::Type); bool spritesheets_merge(const std::set<int>&, bool, bool, bool, origin::Type);
void scan_and_set_regions();
bool file_merge(const std::filesystem::path&, FileMergePreset = FILE_MERGE_PRESET_MERGE_BY_NAME);
void hash_set(); void hash_set();
void clean(); void clean();
void change(ChangeType); void change(ChangeType);
@@ -175,39 +142,16 @@ namespace anm2ed
Element* spritesheet_get(); Element* spritesheet_get();
Element* animation_get(); Element* animation_get();
void spritesheet_add(const std::filesystem::path&);
void spritesheets_add(const std::vector<std::filesystem::path>&); void spritesheets_add(const std::vector<std::filesystem::path>&);
void sound_add(const std::filesystem::path&);
void sounds_add(const std::vector<std::filesystem::path>&); void sounds_add(const std::vector<std::filesystem::path>&);
bool autosave(std::string* = nullptr, Options = {}); bool autosave(std::string* = nullptr, Options = {});
std::filesystem::path autosave_path_get(); std::filesystem::path autosave_path_get();
std::filesystem::path path_from_autosave_get(const std::filesystem::path&); std::filesystem::path path_from_autosave_get(const std::filesystem::path&);
void anm2_snapshot(const std::string& message);
void tracks_snapshot(const std::string& message, const std::set<Reference>&);
void frames_snapshot(const std::string& message, const std::set<Reference>&);
void regions_snapshot(const std::string& message, int, const std::set<int>&);
void textures_snapshot(const std::string& message);
void anm2_textures_snapshot(const std::string& message);
void undo(); void undo();
void redo(); void redo();
bool is_able_to_undo(); bool is_able_to_undo();
bool is_able_to_redo(); bool is_able_to_redo();
}; };
#define DOCUMENT_EDIT(document, message, changeType, body) \
{ \
document.anm2_snapshot(message); \
body; \
document.change(changeType); \
}
#define DOCUMENT_EDIT_PTR(document, message, changeType, body) \
{ \
document->anm2_snapshot(message); \
body; \
document->change(changeType); \
}
} }
+31 -38
View File
@@ -27,18 +27,18 @@ namespace anm2ed::imgui
uint64_t documentId{}; uint64_t documentId{};
}; };
#define ANM2_DRAG_DROP_MERGE_PRESETS \ #define ANM2_DRAG_DROP_MERGE_PRESETS \
X(FILE_MERGE_PRESET_MERGE_BY_NAME, BASIC_MERGE, TOOLTIP_MERGE_PRESET_MERGE_BY_NAME) \ X(FILE_MERGE_PRESET_MERGE_BY_NAME, BASIC_MERGE, TOOLTIP_MERGE_PRESET_MERGE_BY_NAME) \
X(FILE_MERGE_PRESET_APPEND_AS_NEW, BASIC_APPEND, TOOLTIP_MERGE_PRESET_APPEND_AS_NEW) \ X(FILE_MERGE_PRESET_APPEND_AS_NEW, BASIC_APPEND, TOOLTIP_MERGE_PRESET_APPEND_AS_NEW) \
X(FILE_MERGE_PRESET_REPLACE_MATCHING, BASIC_REPLACE, TOOLTIP_MERGE_PRESET_REPLACE_MATCHING) X(FILE_MERGE_PRESET_REPLACE_MATCHING, BASIC_REPLACE, TOOLTIP_MERGE_PRESET_REPLACE_MATCHING)
constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_LABELS[Document::FILE_MERGE_PRESET_COUNT] = { constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_LABELS[FILE_MERGE_PRESET_COUNT] = {
#define X(preset, label, tooltip) label, #define X(preset, label, tooltip) label,
ANM2_DRAG_DROP_MERGE_PRESETS ANM2_DRAG_DROP_MERGE_PRESETS
#undef X #undef X
}; };
constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_TOOLTIPS[Document::FILE_MERGE_PRESET_COUNT] = { constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_TOOLTIPS[FILE_MERGE_PRESET_COUNT] = {
#define X(preset, label, tooltip) tooltip, #define X(preset, label, tooltip) tooltip,
ANM2_DRAG_DROP_MERGE_PRESETS ANM2_DRAG_DROP_MERGE_PRESETS
#undef X #undef X
@@ -47,13 +47,13 @@ namespace anm2ed::imgui
#undef ANM2_DRAG_DROP_MERGE_PRESETS #undef ANM2_DRAG_DROP_MERGE_PRESETS
void anm2_drag_drop_merge_queue(Manager& manager, const std::vector<std::filesystem::path>& paths, void anm2_drag_drop_merge_queue(Manager& manager, const std::vector<std::filesystem::path>& paths,
Document::FileMergePreset preset) FileMergePreset preset)
{ {
manager.command_push({manager.selected, manager.command_push({manager.selected, [paths, preset](Manager&, Document& document)
[paths, preset](Manager&, Document& document)
{ {
document.anm2_snapshot(localize.get(EDIT_MERGE_ANM2)); document.snapshots.anm2_push(localize.get(EDIT_MERGE_ANM2));
for (auto& path : paths) document.file_merge(path, preset); for (auto& path : paths)
document.anm2.file_merge(path, document.directory_get(), preset);
document.change(Document::ALL); document.change(Document::ALL);
}}); }});
} }
@@ -70,8 +70,8 @@ namespace anm2ed::imgui
order.reserve(manager.documents.size()); order.reserve(manager.documents.size());
for (auto documentId : pendingDocumentTabIds) for (auto documentId : pendingDocumentTabIds)
{ {
auto it = std::ranges::find_if(manager.documents, [documentId](const Document& document) auto it = std::ranges::find_if(manager.documents,
{ return document.tabId == documentId; }); [documentId](const Document& document) { return document.tabId == documentId; });
if (it == manager.documents.end()) if (it == manager.documents.end())
{ {
pendingDocumentTabIds.clear(); pendingDocumentTabIds.clear();
@@ -115,7 +115,8 @@ namespace anm2ed::imgui
index_remap(manager.selected); index_remap(manager.selected);
index_remap(manager.pendingSelected); index_remap(manager.pendingSelected);
index_remap(closeDocumentIndex); index_remap(closeDocumentIndex);
for (auto& index : manager.selectionHistory) index_remap(index); for (auto& index : manager.selectionHistory)
index_remap(index);
for (auto& command : manager.commands) for (auto& command : manager.commands)
if (!command.runManager) index_remap(command.documentIndex); if (!command.runManager) index_remap(command.documentIndex);
std::erase(manager.selectionHistory, -1); std::erase(manager.selectionHistory, -1);
@@ -151,8 +152,8 @@ namespace anm2ed::imgui
if (document.lastAutosaveTime > time::SECOND_M) if (document.lastAutosaveTime > time::SECOND_M)
{ {
auto options = settings.anm2_options_get(); auto options = settings.anm2_options_get();
manager.command_push({i, [options](Manager& manager, Document& document) manager.command_push(
{ manager.autosave(document, options); }}); {i, [options](Manager& manager, Document& document) { manager.autosave(document, options); }});
} }
} }
} }
@@ -324,17 +325,11 @@ namespace anm2ed::imgui
if (texture->write_png(savePath)) if (texture->write_png(savePath))
{ {
closeDocument.spritesheet_hash_set_saved(id); closeDocument.spritesheet_hash_set_saved(id);
toasts.push( toast_log(Level::INFO, TOAST_SAVE_SPRITESHEET, id, pathString);
std::vformat(localize.get(TOAST_SAVE_SPRITESHEET), std::make_format_args(id, pathString)));
logger.info(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET, anm2ed::ENGLISH),
std::make_format_args(id, pathString)));
} }
else else
{ {
toasts.push(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET_FAILED), toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString);
std::make_format_args(id, pathString)));
logger.error(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET_FAILED, anm2ed::ENGLISH),
std::make_format_args(id, pathString)));
} }
} }
} }
@@ -350,12 +345,11 @@ namespace anm2ed::imgui
if (ImGui::Button(localize.get(BASIC_NO), widgetSize)) if (ImGui::Button(localize.get(BASIC_NO), widgetSize))
{ {
auto index = closeDocumentIndex; auto index = closeDocumentIndex;
manager.command_push({.runManager = manager.command_push({.runManager = [index](Manager& manager)
[index](Manager& manager) {
{ manager.autosave_file_clear(index);
manager.autosave_file_clear(index); manager.close(index);
manager.close(index); }});
}});
close(); close();
} }
@@ -389,7 +383,7 @@ namespace anm2ed::imgui
manager.anm2DragDropPaths.clear(); manager.anm2DragDropPaths.clear();
manager.anm2DragDropPopup.close(); manager.anm2DragDropPopup.close();
manager.anm2DragDropMergePopup.close(); manager.anm2DragDropMergePopup.close();
manager.anm2DragDropMergePreset = Document::FILE_MERGE_PRESET_MERGE_BY_NAME; manager.anm2DragDropMergePreset = FILE_MERGE_PRESET_MERGE_BY_NAME;
}; };
if (manager.anm2DragDropPaths.empty()) if (manager.anm2DragDropPaths.empty())
@@ -402,10 +396,9 @@ namespace anm2ed::imgui
ImGuiWindowFlags_NoResize)) ImGuiWindowFlags_NoResize))
{ {
auto document = manager.get(); auto document = manager.get();
manager.anm2DragDropMergePreset = manager.anm2DragDropMergePreset = std::clamp(manager.anm2DragDropMergePreset, 0, FILE_MERGE_PRESET_COUNT - 1);
std::clamp(manager.anm2DragDropMergePreset, 0, Document::FILE_MERGE_PRESET_COUNT - 1);
for (int preset = 0; preset < Document::FILE_MERGE_PRESET_COUNT; ++preset) for (int preset = 0; preset < FILE_MERGE_PRESET_COUNT; ++preset)
{ {
ImGui::PushID(preset); ImGui::PushID(preset);
ImGui::RadioButton(localize.get(ANM2_DRAG_DROP_MERGE_PRESET_LABELS[preset]), ImGui::RadioButton(localize.get(ANM2_DRAG_DROP_MERGE_PRESET_LABELS[preset]),
@@ -420,7 +413,7 @@ namespace anm2ed::imgui
if (ImGui::Button(localize.get(BASIC_MERGE), widgetSize)) if (ImGui::Button(localize.get(BASIC_MERGE), widgetSize))
{ {
auto paths = manager.anm2DragDropPaths; auto paths = manager.anm2DragDropPaths;
auto preset = (Document::FileMergePreset)manager.anm2DragDropMergePreset; auto preset = (FileMergePreset)manager.anm2DragDropMergePreset;
anm2_drag_drop_merge_queue(manager, paths, preset); anm2_drag_drop_merge_queue(manager, paths, preset);
drag_drop_reset(); drag_drop_reset();
} }
@@ -452,11 +445,11 @@ namespace anm2ed::imgui
: localize.get(LABEL_DOCUMENTS_OPEN_NEW))) : localize.get(LABEL_DOCUMENTS_OPEN_NEW)))
{ {
auto paths = manager.anm2DragDropPaths; auto paths = manager.anm2DragDropPaths;
manager.command_push({.runManager = manager.command_push({.runManager = [paths](Manager& manager)
[paths](Manager& manager) {
{ for (auto& path : paths)
for (auto& path : paths) manager.open(path); manager.open(path);
}}); }});
drag_drop_reset(); drag_drop_reset();
} }
+6 -7
View File
@@ -195,8 +195,7 @@ namespace anm2ed::imgui::popup
auto queuedAddItemSpritesheetID = addItemSpritesheetID; auto queuedAddItemSpritesheetID = addItemSpritesheetID;
auto queuedAddItemIsShowRect = addItemIsShowRect; auto queuedAddItemIsShowRect = addItemIsShowRect;
manager.command_push({manager.selected, manager.command_push({manager.selected, [=](Manager&, Document& document)
[=](Manager&, Document& document)
{ {
Element item{}; Element item{};
item.id = queuedAddItemID; item.id = queuedAddItemID;
@@ -204,12 +203,12 @@ namespace anm2ed::imgui::popup
item.spritesheetId = queuedAddItemSpritesheetID; item.spritesheetId = queuedAddItemSpritesheetID;
item.isShowRect = queuedAddItemIsShowRect; item.isShowRect = queuedAddItemIsShowRect;
document.anm2_snapshot(localize.get(EDIT_ADD_ITEM)); document.snapshots.anm2_push(localize.get(EDIT_ADD_ITEM));
auto addId = document.anm2.item_add((ItemType)queuedType, queuedAnimationIndex, item, auto addId =
queuedInsertBeforeID, document.anm2.item_add((ItemType)queuedType, queuedAnimationIndex, item,
(destination::Type)queuedDestination); queuedInsertBeforeID, (destination::Type)queuedDestination);
document.anm2_change(Document::ITEMS); document.change(Document::ITEMS);
if (addId != -1) if (addId != -1)
{ {
+19 -27
View File
@@ -38,9 +38,7 @@ namespace anm2ed::imgui
auto path = request.path; auto path = request.path;
auto options = request.options; auto options = request.options;
manager.command_push({.runManager = manager.command_push({.runManager = [=](Manager& manager) { manager.save(index, path, options); }});
[=](Manager& manager)
{ manager.save(index, path, options); }});
} }
bool Taskbar::save_request(Manager& manager, Settings& settings, int index, const std::filesystem::path& path, bool Taskbar::save_request(Manager& manager, Settings& settings, int index, const std::filesystem::path& path,
@@ -145,11 +143,11 @@ namespace anm2ed::imgui
if (dialog.is_selected(Dialog::ANM2_OPEN)) if (dialog.is_selected(Dialog::ANM2_OPEN))
{ {
auto paths = dialog.paths; auto paths = dialog.paths;
manager.command_push({.runManager = manager.command_push({.runManager = [paths](Manager& manager)
[paths](Manager& manager) {
{ for (auto& path : paths)
for (auto& path : paths) manager.open(path); manager.open(path);
}}); }});
dialog.reset(); dialog.reset();
} }
@@ -172,15 +170,13 @@ namespace anm2ed::imgui
if (ImGui::MenuItem(localize.get(LABEL_SCAN_AND_SET_REGIONS), nullptr, false, document && hasRegions)) if (ImGui::MenuItem(localize.get(LABEL_SCAN_AND_SET_REGIONS), nullptr, false, document && hasRegions))
{ {
manager.command_push({manager.selected, manager.command_push({manager.selected, [](Manager&, Document& document)
[](Manager&, Document& document)
{ {
document.anm2_snapshot(localize.get(EDIT_SCAN_AND_SET_REGIONS)); document.snapshots.anm2_push(localize.get(EDIT_SCAN_AND_SET_REGIONS));
document.scan_and_set_regions(); document.anm2.regions_scan();
document.change(Document::FRAMES); document.change(Document::FRAMES);
}}); }});
toasts.push(localize.get(TOAST_SCAN_AND_SET_REGIONS)); toast_log(Level::INFO, TOAST_SCAN_AND_SET_REGIONS);
logger.info(localize.get(TOAST_SCAN_AND_SET_REGIONS, anm2ed::ENGLISH));
} }
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_SCAN_AND_SET_REGIONS)); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_SCAN_AND_SET_REGIONS));
@@ -284,19 +280,15 @@ namespace anm2ed::imgui
auto queuedAnimationIndices = animationIndices; auto queuedAnimationIndices = animationIndices;
auto queuedFormat = settings.generateRegionNameFormat; auto queuedFormat = settings.generateRegionNameFormat;
auto queuedMapping = isGenerateRegionsMapFrames ? Document::RegionFrameMapping::SET auto queuedMapping = isGenerateRegionsMapFrames ? RegionFrameMapping::SET : RegionFrameMapping::PRESERVE;
: Document::RegionFrameMapping::PRESERVE; manager.command_push(
manager.command_push({manager.selected, {manager.selected, [=](Manager&, Document& document)
[=](Manager&, Document& document) {
{ if (queuedAnimationIndices.empty()) return;
if (queuedAnimationIndices.empty()) return; document.snapshots.anm2_push(localize.get(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS));
document.anm2_snapshot(localize.get(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS)); if (document.anm2.regions_generate(queuedAnimationIndices, {}, queuedFormat, queuedMapping))
if (document.regions_generate_from_animations(queuedAnimationIndices, queuedFormat, document.change(queuedMapping == RegionFrameMapping::SET ? Document::ALL : Document::SPRITESHEETS);
queuedMapping)) }});
document.anm2_change(queuedMapping == Document::RegionFrameMapping::SET
? Document::ALL
: Document::SPRITESHEETS);
}});
generateRegionsPopup.close(); generateRegionsPopup.close();
} }
+20
View File
@@ -1,8 +1,12 @@
#pragma once #pragma once
#include <format>
#include <string> #include <string>
#include <vector> #include <vector>
#include "log.hpp"
#include "strings.hpp"
namespace anm2ed::imgui namespace anm2ed::imgui
{ {
class Toast class Toast
@@ -26,3 +30,19 @@ namespace anm2ed::imgui
} }
extern anm2ed::imgui::Toasts toasts; extern anm2ed::imgui::Toasts toasts;
namespace anm2ed
{
template <class... Args> void toast_log(Level level, StringType type, Args&&... args)
{
auto format = [&](Language language) -> std::string
{
if constexpr (sizeof...(Args) == 0)
return localize.get(type, language);
else
return std::vformat(localize.get(type, language), std::make_format_args(args...));
};
toasts.push(format(localize.language));
logger.write(level, format(ENGLISH));
}
}
+12 -35
View File
@@ -306,16 +306,11 @@ namespace anm2ed::imgui
{ {
if (!renderTempFrames.empty()) if (!renderTempFrames.empty())
{ {
toasts.push(std::vformat(localize.get(TOAST_EXPORT_RENDERED_FRAMES), std::make_format_args(pathString))); toast_log(Level::INFO, TOAST_EXPORT_RENDERED_FRAMES, pathString);
logger.info(std::vformat(localize.get(TOAST_EXPORT_RENDERED_FRAMES, anm2ed::ENGLISH),
std::make_format_args(pathString)));
} }
else else
{ {
toasts.push( toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_FRAMES_FAILED, pathString);
std::vformat(localize.get(TOAST_EXPORT_RENDERED_FRAMES_FAILED), std::make_format_args(pathString)));
logger.error(std::vformat(localize.get(TOAST_EXPORT_RENDERED_FRAMES_FAILED, anm2ed::ENGLISH),
std::make_format_args(pathString)));
} }
} }
else if (type == render::SPRITESHEET) else if (type == render::SPRITESHEET)
@@ -328,16 +323,14 @@ namespace anm2ed::imgui
if (renderTempFrames.empty()) if (renderTempFrames.empty())
{ {
toasts.push(localize.get(TOAST_SPRITESHEET_NO_FRAMES)); toast_log(Level::WARNING, TOAST_SPRITESHEET_NO_FRAMES);
logger.warning(localize.get(TOAST_SPRITESHEET_NO_FRAMES, anm2ed::ENGLISH));
} }
else else
{ {
auto firstFrame = Texture(renderTempFrames.front()); auto firstFrame = Texture(renderTempFrames.front());
if (firstFrame.size.x <= 0 || firstFrame.size.y <= 0 || firstFrame.pixels.empty()) if (firstFrame.size.x <= 0 || firstFrame.size.y <= 0 || firstFrame.pixels.empty())
{ {
toasts.push(localize.get(TOAST_SPRITESHEET_EMPTY)); toast_log(Level::ERROR, TOAST_SPRITESHEET_EMPTY);
logger.error(localize.get(TOAST_SPRITESHEET_EMPTY, anm2ed::ENGLISH));
} }
else else
{ {
@@ -368,16 +361,11 @@ namespace anm2ed::imgui
Texture spritesheetTexture(spritesheet.data(), spritesheetSize); Texture spritesheetTexture(spritesheet.data(), spritesheetSize);
if (spritesheetTexture.write_png(path)) if (spritesheetTexture.write_png(path))
{ {
toasts.push(std::vformat(localize.get(TOAST_EXPORT_SPRITESHEET), std::make_format_args(pathString))); toast_log(Level::INFO, TOAST_EXPORT_SPRITESHEET, pathString);
logger.info(std::vformat(localize.get(TOAST_EXPORT_SPRITESHEET, anm2ed::ENGLISH),
std::make_format_args(pathString)));
} }
else else
{ {
toasts.push( toast_log(Level::ERROR, TOAST_EXPORT_SPRITESHEET_FAILED, pathString);
std::vformat(localize.get(TOAST_EXPORT_SPRITESHEET_FAILED), std::make_format_args(pathString)));
logger.error(std::vformat(localize.get(TOAST_EXPORT_SPRITESHEET_FAILED, anm2ed::ENGLISH),
std::make_format_args(pathString)));
} }
} }
} }
@@ -398,16 +386,11 @@ namespace anm2ed::imgui
if (animation_render(ffmpegPath, path, renderTempFrames, audioStream, (render::Type)type, renderFrameRate)) if (animation_render(ffmpegPath, path, renderTempFrames, audioStream, (render::Type)type, renderFrameRate))
{ {
toasts.push(std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION), std::make_format_args(pathString))); toast_log(Level::INFO, TOAST_EXPORT_RENDERED_ANIMATION, pathString);
logger.info(std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION, anm2ed::ENGLISH),
std::make_format_args(pathString)));
} }
else else
{ {
toasts.push( toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString);
std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED), std::make_format_args(pathString)));
logger.error(std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED, anm2ed::ENGLISH),
std::make_format_args(pathString)));
} }
} }
@@ -791,10 +774,7 @@ namespace anm2ed::imgui
} }
auto pathString = path::to_utf8(settings.renderPath); auto pathString = path::to_utf8(settings.renderPath);
toasts.push( toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString);
std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED), std::make_format_args(pathString)));
logger.error(std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED, anm2ed::ENGLISH),
std::make_format_args(pathString)));
manager.isRecording = false; manager.isRecording = false;
manager.isRecordingStart = false; manager.isRecordingStart = false;
renderFrameIndex = 0; renderFrameIndex = 0;
@@ -1240,10 +1220,7 @@ namespace anm2ed::imgui
auto render_capture_fail = [&]() auto render_capture_fail = [&]()
{ {
auto pathString = path::to_utf8(settings.renderPath); auto pathString = path::to_utf8(settings.renderPath);
toasts.push( toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString);
std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED), std::make_format_args(pathString)));
logger.error(std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED, anm2ed::ENGLISH),
std::make_format_args(pathString)));
if (renderType != render::PNGS) render_temp_cleanup(renderTempDirectory, renderTempFrames); if (renderType != render::PNGS) render_temp_cleanup(renderTempDirectory, renderTempFrames);
renderFrameSoundIDs.clear(); renderFrameSoundIDs.clear();
if (isRenderPreviewOverridden) if (isRenderPreviewOverridden)
@@ -1407,7 +1384,7 @@ namespace anm2ed::imgui
{ {
auto queuedFrameReferences = selectedFrameReferences; auto queuedFrameReferences = selectedFrameReferences;
manager.command_push({manager.selected, [message, queuedFrameReferences](Manager&, Document& document) manager.command_push({manager.selected, [message, queuedFrameReferences](Manager&, Document& document)
{ document.frames_snapshot(localize.get(message), queuedFrameReferences); }}); { document.snapshots.frames_push(localize.get(message), queuedFrameReferences); }});
}; };
auto frame_change_apply = [&](FrameChange frameChange, ChangeType changeType = ChangeType::ADJUST) auto frame_change_apply = [&](FrameChange frameChange, ChangeType changeType = ChangeType::ADJUST)
{ {
@@ -1450,7 +1427,7 @@ namespace anm2ed::imgui
auto frames_changed = [&]() auto frames_changed = [&]()
{ {
manager.command_push( manager.command_push(
{manager.selected, [](Manager&, Document& document) { document.anm2_change(Document::FRAMES); }}); {manager.selected, [](Manager&, Document& document) { document.change(Document::FRAMES); }});
}; };
auto null_rect_change = [&](vec2 topLeft, vec2 rectSize) auto null_rect_change = [&](vec2 topLeft, vec2 rectSize)
{ {
+4 -4
View File
@@ -49,9 +49,9 @@ namespace anm2ed::imgui
auto item = document.anm2.element_get(itemReference); auto item = document.anm2.element_get(itemReference);
if (!frame) return; if (!frame) return;
document.frames_snapshot(localize.get(message), {queuedReference}); document.snapshots.frames_push(localize.get(message), {queuedReference});
behavior(document, *frame, item, queuedReference); behavior(document, *frame, item, queuedReference);
document.anm2_change(Document::FRAMES); document.change(Document::FRAMES);
}}); }});
}; };
@@ -70,9 +70,9 @@ namespace anm2ed::imgui
if (!frame) return; if (!frame) return;
if (state == edit::START) if (state == edit::START)
document.frames_snapshot(localize.get(message), {queuedReference}); document.snapshots.frames_push(localize.get(message), {queuedReference});
behavior(document, *frame, item, queuedReference); behavior(document, *frame, item, queuedReference);
if (state == edit::END) document.anm2_change(Document::FRAMES); if (state == edit::END) document.change(Document::FRAMES);
}}); }});
}; };
+11 -53
View File
@@ -124,57 +124,20 @@ namespace anm2ed::imgui
void shader_uniform_config_save(Document& document, Element& shaderElement, const resource::shader::Uniform& uniform) void shader_uniform_config_save(Document& document, Element& shaderElement, const resource::shader::Uniform& uniform)
{ {
auto config = shader_uniform_get(shaderElement, uniform.name); resource::shader::uniform_config_save(shaderElement, uniform);
if (!config)
{
config = &shaderElement.children.emplace_back(element_make(ElementType::UNIFORM));
config->name = uniform.name;
}
config->binding = std::string(resource::shader::uniform_binding_value_get(uniform.binding));
config->value = resource::shader::uniform_value_string_get(uniform);
if (uniform.binding == resource::shader::UNIFORM_BINDING_COMPONENTS)
{
for (int index = 0; index < (int)uniform.components.size(); ++index)
{
auto component = shader_uniform_component_get(*config, index);
if (!component)
{
component = &config->children.emplace_back(element_make(ElementType::COMPONENT));
component->index = index;
}
component->binding =
std::string(resource::shader::uniform_binding_value_get(uniform.components[index].binding));
component->value = std::format("{:.6g}", uniform.components[index].value);
}
}
else
std::erase_if(config->children, [](const Element& child) { return child.type == ElementType::COMPONENT; });
document.change(Document::SHADERS); document.change(Document::SHADERS);
} }
int shader_uniform_component_count_get(resource::shader::UniformValueType type)
{
if (type == resource::shader::UNIFORM_VALUE_VEC2) return 2;
if (type == resource::shader::UNIFORM_VALUE_VEC3) return 3;
if (type == resource::shader::UNIFORM_VALUE_VEC4) return 4;
return 0;
}
void shader_uniform_components_from_value_set(resource::shader::Uniform& uniform) void shader_uniform_components_from_value_set(resource::shader::Uniform& uniform)
{ {
uniform.components[0].value = uniform.value.x; for (int i = 0; i < (int)uniform.components.size(); ++i)
uniform.components[1].value = uniform.value.y; uniform.components[i].value = uniform.value[i];
uniform.components[2].value = uniform.value.z;
uniform.components[3].value = uniform.value.w;
} }
void shader_uniform_value_from_components_set(resource::shader::Uniform& uniform) void shader_uniform_value_from_components_set(resource::shader::Uniform& uniform)
{ {
uniform.value.x = uniform.components[0].value; for (int i = 0; i < (int)uniform.components.size(); ++i)
uniform.value.y = uniform.components[1].value; uniform.value[i] = uniform.components[i].value;
uniform.value.z = uniform.components[2].value;
uniform.value.w = uniform.components[3].value;
} }
bool shader_uniform_value_update(resource::shader::Uniform& uniform) bool shader_uniform_value_update(resource::shader::Uniform& uniform)
@@ -227,7 +190,7 @@ namespace anm2ed::imgui
{ {
bool isChanged{}; bool isChanged{};
constexpr const char* labels[] = {"X", "Y", "Z", "W"}; constexpr const char* labels[] = {"X", "Y", "Z", "W"};
auto componentCount = shader_uniform_component_count_get(uniform.valueType); auto componentCount = resource::shader::UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount;
for (int index = 0; index < componentCount; ++index) for (int index = 0; index < componentCount; ++index)
{ {
@@ -328,12 +291,7 @@ namespace anm2ed::imgui
if (ImGui::Begin(localize.get(LABEL_SHADERS_WINDOW), &settings.windowIsShaders)) if (ImGui::Begin(localize.get(LABEL_SHADERS_WINDOW), &settings.windowIsShaders))
{ {
auto document = manager.get(); auto document = manager.get();
if (!document) auto shaders = document ? document->anm2.element_get(ElementType::SHADERS) : nullptr;
{
ImGui::End();
return;
}
auto shaders = document->anm2.element_get(ElementType::SHADERS);
if (!shaders) if (!shaders)
{ {
ImGui::End(); ImGui::End();
@@ -354,12 +312,12 @@ namespace anm2ed::imgui
shader.id = element_child_next_id_get(*shaders, ElementType::SHADER); shader.id = element_child_next_id_get(*shaders, ElementType::SHADER);
shader.name = localize.get(TEXT_NEW_SHADER); shader.name = localize.get(TEXT_NEW_SHADER);
document.anm2_snapshot(localize.get(EDIT_ADD_SHADER)); document.snapshots.anm2_push(localize.get(EDIT_ADD_SHADER));
shaders->children.push_back(shader); shaders->children.push_back(shader);
document.shader.selection = {shader.id}; document.shader.selection = {shader.id};
document.shader.reference = shader.id; document.shader.reference = shader.id;
newElementId = shader.id; newElementId = shader.id;
document.anm2_change(Document::SHADERS); document.change(Document::SHADERS);
}}); }});
}; };
@@ -372,7 +330,7 @@ namespace anm2ed::imgui
auto unused = document.anm2.element_unused(ElementType::SHADER); auto unused = document.anm2.element_unused(ElementType::SHADER);
if (unused.empty()) return; if (unused.empty()) return;
document.anm2_snapshot(localize.get(EDIT_REMOVE_UNUSED_SHADERS)); document.snapshots.anm2_push(localize.get(EDIT_REMOVE_UNUSED_SHADERS));
for (auto id : unused) for (auto id : unused)
{ {
element_child_id_erase(*shaders, ElementType::SHADER, id); element_child_id_erase(*shaders, ElementType::SHADER, id);
@@ -380,7 +338,7 @@ namespace anm2ed::imgui
if (document.shader.reference == id) document.shader.reference = -1; if (document.shader.reference == id) document.shader.reference = -1;
if (popupShaderId == id) propertiesPopup.close(); if (popupShaderId == id) propertiesPopup.close();
} }
document.anm2_change(Document::SHADERS); document.change(Document::SHADERS);
}}); }});
}; };
+51 -52
View File
@@ -238,7 +238,8 @@ namespace anm2ed::imgui
auto spritesheetModel = math::quad_model_get(viewTexture->size); auto spritesheetModel = math::quad_model_get(viewTexture->size);
auto spritesheetTransform = transform * spritesheetModel; auto spritesheetTransform = transform * spritesheetModel;
if (baseTexture && baseTexture->is_valid()) texture_render(shaderTexture, baseTexture->id, spritesheetTransform); if (baseTexture && baseTexture->is_valid())
texture_render(shaderTexture, baseTexture->id, spritesheetTransform);
if (isGrid) grid_render(shaderGrid, zoom, pan, gridSize, gridOffset, gridColor); if (isGrid) grid_render(shaderGrid, zoom, pan, gridSize, gridOffset, gridColor);
@@ -431,9 +432,8 @@ namespace anm2ed::imgui
{ {
auto message = std::string(localize.get(messageType)); auto message = std::string(localize.get(messageType));
auto queuedFrameReferences = frameReferences; auto queuedFrameReferences = frameReferences;
manager.command_push({manager.selected, manager.command_push({manager.selected, [message, queuedFrameReferences](Manager&, Document& document)
[message, queuedFrameReferences](Manager&, Document& document) { document.snapshots.frames_push(message, queuedFrameReferences); }});
{ document.frames_snapshot(message, queuedFrameReferences); }});
}; };
auto region_snapshot_push = [&](StringType messageType, const std::set<int>& regionIds) auto region_snapshot_push = [&](StringType messageType, const std::set<int>& regionIds)
{ {
@@ -442,42 +442,41 @@ namespace anm2ed::imgui
auto queuedRegionIds = regionIds; auto queuedRegionIds = regionIds;
manager.command_push({manager.selected, manager.command_push({manager.selected,
[message, queuedSpritesheet, queuedRegionIds](Manager&, Document& document) [message, queuedSpritesheet, queuedRegionIds](Manager&, Document& document)
{ document.regions_snapshot(message, queuedSpritesheet, queuedRegionIds); }}); { document.snapshots.regions_push(message, queuedSpritesheet, queuedRegionIds); }});
}; };
auto texture_snapshot_push = [&](StringType messageType) auto texture_snapshot_push = [&](StringType messageType)
{ {
auto message = std::string(localize.get(messageType)); auto message = std::string(localize.get(messageType));
manager.command_push( manager.command_push({manager.selected, [message](Manager&, Document& document)
{manager.selected, [message](Manager&, Document& document) { document.textures_snapshot(message); }}); { document.snapshots.textures_push(message); }});
}; };
auto document_change_push = [&](Document::ChangeType changeType) auto document_change_push = [&](Document::ChangeType changeType)
{ {
manager.command_push( manager.command_push(
{manager.selected, [changeType](Manager&, Document& document) { document.anm2_change(changeType); }}); {manager.selected, [changeType](Manager&, Document& document) { document.change(changeType); }});
}; };
auto frame_change_apply_to = [&](const std::set<Reference>& frameReferences, FrameChange frameChange, auto frame_change_apply_to = [&](const std::set<Reference>& frameReferences, FrameChange frameChange,
ChangeType changeType = ChangeType::ADJUST) ChangeType changeType = ChangeType::ADJUST)
{ {
auto queuedFrameReferences = frameReferences; auto queuedFrameReferences = frameReferences;
manager.command_push( manager.command_push({manager.selected, [=](Manager&, Document& document)
{manager.selected, [=](Manager&, Document& document) {
{ std::map<Reference, std::set<int>> groupedFrames{};
std::map<Reference, std::set<int>> groupedFrames{}; for (auto frameReference : queuedFrameReferences)
for (auto frameReference : queuedFrameReferences) {
{ auto itemReference = frameReference;
auto itemReference = frameReference; itemReference.frameIndex = -1;
itemReference.frameIndex = -1; groupedFrames[itemReference].insert(frameReference.frameIndex);
groupedFrames[itemReference].insert(frameReference.frameIndex); }
}
for (auto& [itemReference, itemFrames] : groupedFrames) for (auto& [itemReference, itemFrames] : groupedFrames)
{ {
auto itemType = static_cast<ItemType>(itemReference.itemType); auto itemType = static_cast<ItemType>(itemReference.itemType);
auto item = document.anm2.element_get(itemReference); auto item = document.anm2.element_get(itemReference);
if (!item) continue; if (!item) continue;
frames_change(*item, frameChange, itemType, changeType, itemFrames); frames_change(*item, frameChange, itemType, changeType, itemFrames);
} }
}}); }});
}; };
auto frame_change_apply = [&](FrameChange frameChange, ChangeType changeType = ChangeType::ADJUST) auto frame_change_apply = [&](FrameChange frameChange, ChangeType changeType = ChangeType::ADJUST)
{ frame_change_apply_to(selectedFrameReferences, frameChange, changeType); }; { frame_change_apply_to(selectedFrameReferences, frameChange, changeType); };
@@ -486,29 +485,28 @@ namespace anm2ed::imgui
{ {
auto queuedReference = editReference; auto queuedReference = editReference;
auto queuedFrameReferences = frameReferences; auto queuedFrameReferences = frameReferences;
manager.command_push( manager.command_push({manager.selected, [=](Manager&, Document& document)
{manager.selected, [=](Manager&, Document& document) {
{ if (queuedReference.frameIndex < 0) return;
if (queuedReference.frameIndex < 0) return; auto frame = document.anm2.element_get(queuedReference);
auto frame = document.anm2.element_get(queuedReference); if (!frame) return;
if (!frame) return;
std::map<Reference, std::set<int>> groupedFrames{}; std::map<Reference, std::set<int>> groupedFrames{};
for (auto frameReference : queuedFrameReferences) for (auto frameReference : queuedFrameReferences)
{ {
auto itemReference = frameReference; auto itemReference = frameReference;
itemReference.frameIndex = -1; itemReference.frameIndex = -1;
groupedFrames[itemReference].insert(frameReference.frameIndex); groupedFrames[itemReference].insert(frameReference.frameIndex);
} }
for (auto& [itemReference, itemFrames] : groupedFrames) for (auto& [itemReference, itemFrames] : groupedFrames)
{ {
auto itemType = static_cast<ItemType>(itemReference.itemType); auto itemType = static_cast<ItemType>(itemReference.itemType);
auto item = document.anm2.element_get(itemReference); auto item = document.anm2.element_get(itemReference);
if (!item) continue; if (!item) continue;
frames_change(*item, frameChangeGet(*frame), itemType, changeType, itemFrames); frames_change(*item, frameChangeGet(*frame), itemType, changeType, itemFrames);
} }
}}); }});
}; };
auto frame_crop_normalize_apply_to = auto frame_crop_normalize_apply_to =
[&](const std::set<Reference>& frameReferences, bool isSnap, ivec2 snapGridSize, ivec2 snapGridOffset) [&](const std::set<Reference>& frameReferences, bool isSnap, ivec2 snapGridSize, ivec2 snapGridOffset)
@@ -639,8 +637,7 @@ namespace anm2ed::imgui
{ {
auto queuedSpritesheet = referenceSpritesheet; auto queuedSpritesheet = referenceSpritesheet;
manager.command_push( manager.command_push(
{manager.selected, [=](Manager&, Document& document) {manager.selected, [=](Manager&, Document& document) { document.texture_change(queuedSpritesheet); }});
{ document.texture_change(queuedSpritesheet); }});
}; };
auto region_selection_set = [&](int id) auto region_selection_set = [&](int id)
@@ -808,7 +805,8 @@ namespace anm2ed::imgui
if (isEnd) document_change_push(Document::FRAMES); if (isEnd) document_change_push(Document::FRAMES);
break; break;
case tool::CROP: case tool::CROP:
if ((isRegionEditTarget || isRegionInUse || selectedFrameToolReferences.empty()) && !regionSelection.empty()) if ((isRegionEditTarget || isRegionInUse || selectedFrameToolReferences.empty()) &&
!regionSelection.empty())
{ {
if (!spritesheet || regionSelection.empty()) break; if (!spritesheet || regionSelection.empty()) break;
if (isBegin) region_snapshot_push(EDIT_REGION_CROP, regionSelection); if (isBegin) region_snapshot_push(EDIT_REGION_CROP, regionSelection);
@@ -1022,8 +1020,9 @@ namespace anm2ed::imgui
actions_undo_redo_add(actions, manager, document); actions_undo_redo_add(actions, manager, document);
actions.separator(); actions.separator();
actions.add(ACTION_CENTER_VIEW, []() { return true; }, center_view); actions.add(ACTION_CENTER_VIEW, []() { return true; }, center_view);
actions.add(ACTION_FIT_VIEW, [&]() actions.add(
{ return (baseTexture && baseTexture->is_valid()) || (texture && texture->is_valid()); }, fit_view); ACTION_FIT_VIEW,
[&]() { return (baseTexture && baseTexture->is_valid()) || (texture && texture->is_valid()); }, fit_view);
actions.separator(); actions.separator();
actions.add(ACTION_ZOOM_IN, []() { return true; }, zoom_in); actions.add(ACTION_ZOOM_IN, []() { return true; }, zoom_in);
actions.add(ACTION_ZOOM_OUT, []() { return true; }, zoom_out); actions.add(ACTION_ZOOM_OUT, []() { return true; }, zoom_out);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+24 -23
View File
@@ -36,11 +36,10 @@ namespace anm2ed::imgui
{ {
auto targetFrames = makeManyRegionReferences; auto targetFrames = makeManyRegionReferences;
auto format = settings.generateRegionNameFormat; auto format = settings.generateRegionNameFormat;
auto mapping = isMakeManyRegionsMapFrames ? Document::RegionFrameMapping::SET auto mapping = isMakeManyRegionsMapFrames ? RegionFrameMapping::SET : RegionFrameMapping::PRESERVE;
: Document::RegionFrameMapping::PRESERVE;
edit_command_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, Document::ALL, edit_command_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, Document::ALL,
[=, this](Manager&, Document& document) mutable [=, this](Manager&, Document& document) mutable
{ document.regions_generate_from_frames(targetFrames, format, mapping); }); { document.anm2.regions_generate({}, targetFrames, format, mapping); });
makeManyRegionsPopup.close(); makeManyRegionsPopup.close();
} }
@@ -178,16 +177,17 @@ namespace anm2ed::imgui
if (!selectedFrames.empty()) if (!selectedFrames.empty())
{ {
if (!isShortenChordHeld) frames_snapshot_command_push(EDIT_SHORTEN_FRAME, selectedFrames); if (!isShortenChordHeld) frames_snapshot_command_push(EDIT_SHORTEN_FRAME, selectedFrames);
command_push([=, this](Manager&, Document& document) command_push(
{ [=, this](Manager&, Document& document)
for (auto frameReference : selectedFrames) {
{ for (auto frameReference : selectedFrames)
auto frame = command_frame_get(document, frameReference); {
if (!frame) continue; auto frame = command_frame_get(document, frameReference);
frame->duration = std::max(FRAME_DURATION_MIN, frame->duration - 1); if (!frame) continue;
} frame->duration = std::max(FRAME_DURATION_MIN, frame->duration - 1);
document.anm2_change(Document::FRAMES); }
}); document.change(Document::FRAMES);
});
} }
} }
isShortenChordHeld = isShortenFrame; isShortenChordHeld = isShortenFrame;
@@ -203,16 +203,17 @@ namespace anm2ed::imgui
if (!selectedFrames.empty()) if (!selectedFrames.empty())
{ {
if (!isExtendChordHeld) frames_snapshot_command_push(EDIT_EXTEND_FRAME, selectedFrames); if (!isExtendChordHeld) frames_snapshot_command_push(EDIT_EXTEND_FRAME, selectedFrames);
command_push([=, this](Manager&, Document& document) command_push(
{ [=, this](Manager&, Document& document)
for (auto frameReference : selectedFrames) {
{ for (auto frameReference : selectedFrames)
auto frame = command_frame_get(document, frameReference); {
if (!frame) continue; auto frame = command_frame_get(document, frameReference);
frame->duration = std::min(FRAME_DURATION_MAX, frame->duration + 1); if (!frame) continue;
} frame->duration = std::min(FRAME_DURATION_MAX, frame->duration + 1);
document.anm2_change(Document::FRAMES); }
}); document.change(Document::FRAMES);
});
} }
} }
isExtendChordHeld = isExtendFrame; isExtendChordHeld = isExtendFrame;
File diff suppressed because it is too large. Load diff
@@ -413,7 +413,7 @@ namespace anm2ed::imgui::wizard
groupedFrames[itemReference].insert(frameReference.frameIndex); groupedFrames[itemReference].insert(frameReference.frameIndex);
} }
document.anm2_snapshot(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); document.snapshots.anm2_push(localize.get(EDIT_CHANGE_FRAME_PROPERTIES));
for (auto& [itemReference, selection] : groupedFrames) for (auto& [itemReference, selection] : groupedFrames)
{ {
auto item = anm2.element_get(itemReference); auto item = anm2.element_get(itemReference);
@@ -421,13 +421,13 @@ namespace anm2ed::imgui::wizard
frames_change(*item, frameChange, static_cast<ItemType>(itemReference.itemType), frames_change(*item, frameChange, static_cast<ItemType>(itemReference.itemType),
changeType, selection); changeType, selection);
} }
document.anm2_change(Document::FRAMES); document.change(Document::FRAMES);
return; return;
} }
if (queuedIsItemsDestination) if (queuedIsItemsDestination)
{ {
document.anm2_snapshot(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); document.snapshots.anm2_push(localize.get(EDIT_CHANGE_FRAME_PROPERTIES));
for (auto itemReference : queuedItemReferences) for (auto itemReference : queuedItemReferences)
{ {
if (itemReference.itemType == TRIGGER) continue; if (itemReference.itemType == TRIGGER) continue;
@@ -438,11 +438,11 @@ namespace anm2ed::imgui::wizard
frames_change(*item, frameChange, static_cast<ItemType>(itemReference.itemType), frames_change(*item, frameChange, static_cast<ItemType>(itemReference.itemType),
changeType, selection); changeType, selection);
} }
document.anm2_change(Document::FRAMES); document.change(Document::FRAMES);
return; return;
} }
document.anm2_snapshot(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); document.snapshots.anm2_push(localize.get(EDIT_CHANGE_FRAME_PROPERTIES));
for (auto animationIndex : queuedAnimations) for (auto animationIndex : queuedAnimations)
{ {
auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex); auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex);
@@ -459,8 +459,7 @@ namespace anm2ed::imgui::wizard
if (queuedIsLayers) if (queuedIsLayers)
{ {
auto layerAnimations = auto layerAnimations = child_first_get(*animation, ElementType::LAYER_ANIMATIONS);
child_first_get(*animation, ElementType::LAYER_ANIMATIONS);
if (layerAnimations) if (layerAnimations)
{ {
auto item_change = [&](auto&& self, Element& item) -> void auto item_change = [&](auto&& self, Element& item) -> void
@@ -484,8 +483,7 @@ namespace anm2ed::imgui::wizard
if (queuedIsNulls) if (queuedIsNulls)
{ {
auto nullAnimations = auto nullAnimations = child_first_get(*animation, ElementType::NULL_ANIMATIONS);
child_first_get(*animation, ElementType::NULL_ANIMATIONS);
if (nullAnimations) if (nullAnimations)
{ {
auto item_change = [&](auto&& self, Element& item) -> void auto item_change = [&](auto&& self, Element& item) -> void
@@ -507,7 +505,7 @@ namespace anm2ed::imgui::wizard
} }
} }
} }
document.anm2_change(Document::FRAMES); document.change(Document::FRAMES);
}}); }});
isChanged = true; isChanged = true;
}; };
@@ -1,12 +1,12 @@
#include "generate_animation_from_grid.hpp" #include "generate_animation_from_grid.hpp"
#include <algorithm>
#include <format>
#include "math.hpp" #include "math.hpp"
#include "types.hpp" #include "types.hpp"
#include "util/imgui/draw.hpp" #include "util/imgui/draw.hpp"
#include "util/imgui/input.hpp" #include "util/imgui/input.hpp"
#include "util/imgui/layout.hpp" #include "util/imgui/layout.hpp"
#include <algorithm>
#include <format>
using namespace anm2ed::types; using namespace anm2ed::types;
using namespace anm2ed::util; using namespace anm2ed::util;
@@ -102,10 +102,10 @@ namespace anm2ed::imgui::wizard
{ {
auto uvMin = frame.crop / textureSize; auto uvMin = frame.crop / textureSize;
auto uvMax = (frame.crop + frame.size) / textureSize; auto uvMax = (frame.crop + frame.size) / textureSize;
mat4 transform = transform_get(zoom) * mat4 transform =
math::quad_model_get(frame.size, frame.position, frame.pivot, transform_get(zoom) * math::quad_model_get(frame.size, frame.position, frame.pivot,
math::percent_to_unit(frame.scale), frame.rotation, math::percent_to_unit(frame.scale), frame.rotation,
math::percent_to_unit(frame.shear)); math::percent_to_unit(frame.shear));
auto vertices = math::uv_vertices_get(uvMin, uvMax); auto vertices = math::uv_vertices_get(uvMin, uvMax);
texture_render(shaderTexture, sourceTexture->id, transform, frame.tint, frame.colorOffset, vertices.data()); texture_render(shaderTexture, sourceTexture->id, transform, frame.tint, frame.colorOffset, vertices.data());
@@ -144,64 +144,60 @@ namespace anm2ed::imgui::wizard
auto queuedIsMakeRegions = isMakeRegions; auto queuedIsMakeRegions = isMakeRegions;
auto queuedRegionNameFormat = regionNameFormat; auto queuedRegionNameFormat = regionNameFormat;
manager.command_push({manager.selected, manager.command_push(
[=](Manager&, Document& document) {manager.selected, [=](Manager&, Document& document)
{ {
auto region_name_get = [](const std::string& format, int frameNumber) auto region_name_get = [](const std::string& format, int frameNumber)
{ {
try try
{ {
return std::vformat(format, std::make_format_args(frameNumber)); return std::vformat(format, std::make_format_args(frameNumber));
} }
catch (const std::format_error&) catch (const std::format_error&)
{ {
return format; return format;
} }
}; };
bool isChanged{}; bool isChanged{};
bool isRegionsChanged{}; bool isRegionsChanged{};
for (auto queuedReference : queuedLayerReferences) for (auto queuedReference : queuedLayerReferences)
{ {
auto item = document.anm2.element_get(queuedReference); auto item = document.anm2.element_get(queuedReference);
auto animation = auto animation = document.anm2.element_get(ElementType::ANIMATION, queuedReference.animationIndex);
document.anm2.element_get(ElementType::ANIMATION, queuedReference.animationIndex); auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, queuedReference.itemID);
auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, auto spritesheet =
queuedReference.itemID); layer ? document.anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr;
auto spritesheet = layer ? document.anm2.element_get(ElementType::SPRITESHEET, if (!item || !animation) continue;
layer->spritesheetId)
: nullptr;
if (!item || !animation) continue;
if (!isChanged) if (!isChanged)
{ {
document.anm2_snapshot(localize.get(EDIT_GENERATE_ANIMATION_FROM_GRID)); document.snapshots.anm2_push(localize.get(EDIT_GENERATE_ANIMATION_FROM_GRID));
isChanged = true; isChanged = true;
} }
auto frameIndexStart = (int)item->children.size(); auto frameIndexStart = (int)item->children.size();
frames_generate_from_grid(*item, queuedStartPosition, queuedSize, queuedPivot, frames_generate_from_grid(*item, queuedStartPosition, queuedSize, queuedPivot, queuedColumns,
queuedColumns, queuedCount, queuedDelay); queuedCount, queuedDelay);
if (queuedIsMakeRegions && spritesheet) if (queuedIsMakeRegions && spritesheet)
for (int frameIndex = frameIndexStart; frameIndex < (int)item->children.size(); for (int frameIndex = frameIndexStart; frameIndex < (int)item->children.size(); ++frameIndex)
++frameIndex) {
{ auto& frame = item->children[frameIndex];
auto& frame = item->children[frameIndex]; if (frame.type != ElementType::FRAME) continue;
if (frame.type != ElementType::FRAME) continue;
auto region = element_make(ElementType::REGION); auto region = element_make(ElementType::REGION);
region.id = element_child_next_id_get(*spritesheet, ElementType::REGION); region.id = element_child_next_id_get(*spritesheet, ElementType::REGION);
region.name = region_name_get(queuedRegionNameFormat, frameIndex - frameIndexStart); region.name = region_name_get(queuedRegionNameFormat, frameIndex - frameIndexStart);
region.crop = frame.crop; region.crop = frame.crop;
region.size = frame.size; region.size = frame.size;
region.pivot = frame.pivot; region.pivot = frame.pivot;
frame.regionId = region.id; frame.regionId = region.id;
spritesheet->children.push_back(region); spritesheet->children.push_back(region);
isRegionsChanged = true; isRegionsChanged = true;
} }
animation->frameNum = animation_length_get(*animation); animation->frameNum = animation_length_get(*animation);
} }
if (isChanged) document.anm2_change(isRegionsChanged ? Document::ALL : Document::FRAMES); if (isChanged) document.change(isRegionsChanged ? Document::ALL : Document::FRAMES);
}}); }});
isEnd = true; isEnd = true;
} }
ImGui::EndDisabled(); ImGui::EndDisabled();
+7 -11
View File
@@ -37,7 +37,8 @@ namespace anm2ed::imgui::wizard
{ {
return frameReference.animationIndex != reference.animationIndex || return frameReference.animationIndex != reference.animationIndex ||
frameReference.itemType != reference.itemType || frameReference.itemID != reference.itemID || frameReference.itemType != reference.itemType || frameReference.itemID != reference.itemID ||
frameReference.groupType != reference.groupType || frameReference.groupId != reference.groupId; frameReference.groupType != reference.groupType ||
frameReference.groupId != reference.groupId;
}); });
if (!frameReferences.empty()) if (!frameReferences.empty())
{ {
@@ -283,8 +284,7 @@ namespace anm2ed::imgui::wizard
{ {
if (!ffmpeg_is_valid()) if (!ffmpeg_is_valid())
{ {
toasts.push(localize.get(TOAST_INVALID_FFMPEG)); toast_log(Level::ERROR, TOAST_INVALID_FFMPEG);
logger.error(localize.get(TOAST_INVALID_FFMPEG, anm2ed::ENGLISH));
return false; return false;
} }
return true; return true;
@@ -295,8 +295,7 @@ namespace anm2ed::imgui::wizard
auto formatString = path::to_utf8(format); auto formatString = path::to_utf8(format);
if (!formatString.contains("{}")) if (!formatString.contains("{}"))
{ {
toasts.push(localize.get(TOAST_PNG_FORMAT_INVALID)); toast_log(Level::ERROR, TOAST_PNG_FORMAT_INVALID);
logger.error(localize.get(TOAST_PNG_FORMAT_INVALID, anm2ed::ENGLISH));
return false; return false;
} }
return true; return true;
@@ -306,8 +305,7 @@ namespace anm2ed::imgui::wizard
{ {
if (path.empty()) if (path.empty())
{ {
toasts.push(localize.get(TOAST_RENDER_PATH_EMPTY)); toast_log(Level::ERROR, TOAST_RENDER_PATH_EMPTY);
logger.error(localize.get(TOAST_RENDER_PATH_EMPTY, anm2ed::ENGLISH));
return false; return false;
} }
return true; return true;
@@ -317,8 +315,7 @@ namespace anm2ed::imgui::wizard
{ {
if (!path::ensure_directory(path)) if (!path::ensure_directory(path))
{ {
toasts.push(localize.get(TOAST_PNG_DIRECTORY_INVALID)); toast_log(Level::ERROR, TOAST_PNG_DIRECTORY_INVALID);
logger.error(localize.get(TOAST_PNG_DIRECTORY_INVALID, anm2ed::ENGLISH));
return false; return false;
} }
return true; return true;
@@ -328,8 +325,7 @@ namespace anm2ed::imgui::wizard
{ {
if (rows <= 0 && columns <= 0) if (rows <= 0 && columns <= 0)
{ {
toasts.push(localize.get(TOAST_RENDER_PATH_EMPTY)); toast_log(Level::ERROR, TOAST_RENDER_PATH_EMPTY);
logger.error(localize.get(TOAST_RENDER_PATH_EMPTY, anm2ed::ENGLISH));
return false; return false;
} }
return true; return true;
+5 -14
View File
@@ -112,10 +112,7 @@ namespace anm2ed
if (!document.is_valid()) if (!document.is_valid())
{ {
documents.pop_back(); documents.pop_back();
toasts.push( toast_log(Level::ERROR, TOAST_OPEN_DOCUMENT_FAILED, pathString, errorString);
std::vformat(localize.get(TOAST_OPEN_DOCUMENT_FAILED), std::make_format_args(pathString, errorString)));
logger.error(std::vformat(localize.get(TOAST_OPEN_DOCUMENT_FAILED, anm2ed::ENGLISH),
std::make_format_args(pathString, errorString)));
return nullptr; return nullptr;
} }
@@ -124,8 +121,7 @@ namespace anm2ed
selected = (int)documents.size() - 1; selected = (int)documents.size() - 1;
pendingSelected = selected; pendingSelected = selected;
selection_history_push(selected); selection_history_push(selected);
toasts.push(std::vformat(localize.get(TOAST_OPEN_DOCUMENT), std::make_format_args(pathString))); toast_log(Level::INFO, TOAST_OPEN_DOCUMENT, pathString);
logger.info(std::vformat(localize.get(TOAST_OPEN_DOCUMENT, anm2ed::ENGLISH), std::make_format_args(pathString)));
return &document; return &document;
} }
@@ -142,8 +138,7 @@ namespace anm2ed
savePath.replace_extension(".anm2"); savePath.replace_extension(".anm2");
ensure_parent_directory_exists(savePath); ensure_parent_directory_exists(savePath);
if (!document->save(savePath, &errorString, options)) if (!document->save(savePath, &errorString, options)) return false;
return false;
const auto autosavePath = document->autosave_path_get(); const auto autosavePath = document->autosave_path_get();
autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), previousAutosavePath), autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), previousAutosavePath),
@@ -160,17 +155,13 @@ namespace anm2ed
return false; return false;
} }
bool Manager::save(const std::filesystem::path& path, Options options) bool Manager::save(const std::filesystem::path& path, Options options) { return save(selected, path, options); }
{
return save(selected, path, options);
}
void Manager::autosave(Document& document, Options options) void Manager::autosave(Document& document, Options options)
{ {
std::string errorString{}; std::string errorString{};
auto autosavePath = document.autosave_path_get(); auto autosavePath = document.autosave_path_get();
if (!document.autosave(&errorString, options)) if (!document.autosave(&errorString, options)) return;
return;
autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), autosavePath), autosaveFiles.end()); autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), autosavePath), autosaveFiles.end());
autosaveFiles.insert(autosaveFiles.begin(), autosavePath); autosaveFiles.insert(autosaveFiles.begin(), autosavePath);
+1 -1
View File
@@ -53,7 +53,7 @@ namespace anm2ed
std::vector<std::filesystem::path> anm2DragDropPaths{}; std::vector<std::filesystem::path> anm2DragDropPaths{};
bool isAnm2DragDrop{}; bool isAnm2DragDrop{};
int anm2DragDropMergePreset{Document::FILE_MERGE_PRESET_MERGE_BY_NAME}; int anm2DragDropMergePreset{FILE_MERGE_PRESET_MERGE_BY_NAME};
imgui::PopupHelper anm2DragDropPopup{ imgui::PopupHelper anm2DragDropPopup{
imgui::PopupHelper(LABEL_MANAGER_ANM2_DRAG_DROP, imgui::POPUP_NORMAL, imgui::POPUP_BY_CURSOR)}; imgui::PopupHelper(LABEL_MANAGER_ANM2_DRAG_DROP, imgui::POPUP_NORMAL, imgui::POPUP_BY_CURSOR)};
imgui::PopupHelper anm2DragDropMergePopup{ imgui::PopupHelper anm2DragDropMergePopup{
+105 -25
View File
@@ -1,10 +1,12 @@
#include "shader.hpp" #include "shader.hpp"
#include <algorithm>
#include <cctype> #include <cctype>
#include <format> #include <format>
#include <sstream> #include <sstream>
#include <utility> #include <utility>
#include "anm2/anm2.hpp"
#include "log.hpp" #include "log.hpp"
namespace anm2ed::resource::shader namespace anm2ed::resource::shader
@@ -26,15 +28,15 @@ namespace anm2ed::resource::shader
X(UNIFORM_BINDING_MAIN_TEXTURE, "Texture") \ X(UNIFORM_BINDING_MAIN_TEXTURE, "Texture") \
X(UNIFORM_BINDING_MAIN_TEXTURE, "Sampler0") \ X(UNIFORM_BINDING_MAIN_TEXTURE, "Sampler0") \
X(UNIFORM_BINDING_MAIN_TEXTURE, "ColorMap") \ X(UNIFORM_BINDING_MAIN_TEXTURE, "ColorMap") \
X(UNIFORM_BINDING_TRANSFORM, UNIFORM_TRANSFORM) \ X(UNIFORM_BINDING_TRANSFORM, UNIFORM_TRANSFORM) \
X(UNIFORM_BINDING_TRANSFORM, "Transform") \ X(UNIFORM_BINDING_TRANSFORM, "Transform") \
X(UNIFORM_BINDING_TRANSFORM, "MVP") \ X(UNIFORM_BINDING_TRANSFORM, "MVP") \
X(UNIFORM_BINDING_TRANSFORM, "Matrix") \ X(UNIFORM_BINDING_TRANSFORM, "Matrix") \
X(UNIFORM_BINDING_FRAME_TINT, UNIFORM_TINT) \ X(UNIFORM_BINDING_FRAME_TINT, UNIFORM_TINT) \
X(UNIFORM_BINDING_FRAME_TINT, "Tint") \ X(UNIFORM_BINDING_FRAME_TINT, "Tint") \
X(UNIFORM_BINDING_FRAME_TINT, "Color") \ X(UNIFORM_BINDING_FRAME_TINT, "Color") \
X(UNIFORM_BINDING_FRAME_TINT, "Color0") \ X(UNIFORM_BINDING_FRAME_TINT, "Color0") \
X(UNIFORM_BINDING_COLOR_OFFSET, UNIFORM_COLOR_OFFSET) \ X(UNIFORM_BINDING_COLOR_OFFSET, UNIFORM_COLOR_OFFSET) \
X(UNIFORM_BINDING_COLOR_OFFSET, "ColorOffset") \ X(UNIFORM_BINDING_COLOR_OFFSET, "ColorOffset") \
X(UNIFORM_BINDING_COLOR_OFFSET, "ColorOffset0") \ X(UNIFORM_BINDING_COLOR_OFFSET, "ColorOffset0") \
X(UNIFORM_BINDING_TEXTURE_SIZE, "u_texture_size") \ X(UNIFORM_BINDING_TEXTURE_SIZE, "u_texture_size") \
@@ -47,10 +49,7 @@ namespace anm2ed::resource::shader
#undef X #undef X
}; };
bool is_shader_identifier(char character) bool is_shader_identifier(char character) { return std::isalnum((unsigned char)character) || character == '_'; }
{
return std::isalnum((unsigned char)character) || character == '_';
}
std::string shader_text_replace(std::string string, std::string_view from, std::string_view to) std::string shader_text_replace(std::string string, std::string_view from, std::string_view to)
{ {
@@ -234,9 +233,7 @@ namespace anm2ed::resource::shader
std::string_view uniform_value_type_label_get(UniformValueType type) std::string_view uniform_value_type_label_get(UniformValueType type)
{ {
for (const auto& info : UNIFORM_VALUE_TYPE_INFOS) return UNIFORM_VALUE_TYPE_INFOS[type < UNIFORM_VALUE_COUNT ? type : UNIFORM_VALUE_UNKNOWN].label;
if (type == info.type) return info.label;
return UNIFORM_VALUE_TYPE_INFOS[0].label;
} }
bool is_uniform_value_editable(UniformValueType type) bool is_uniform_value_editable(UniformValueType type)
@@ -245,9 +242,100 @@ namespace anm2ed::resource::shader
type == UNIFORM_VALUE_VEC3 || type == UNIFORM_VALUE_VEC4 || type == UNIFORM_VALUE_SAMPLER2D; type == UNIFORM_VALUE_VEC3 || type == UNIFORM_VALUE_VEC4 || type == UNIFORM_VALUE_SAMPLER2D;
} }
bool is_uniform_value_vector(UniformValueType type) bool is_uniform_value_vector(UniformValueType type) { return UNIFORM_VALUE_TYPE_INFOS[type].componentCount > 0; }
bool is_component_binding_valid(UniformBinding binding)
{ {
return type == UNIFORM_VALUE_VEC2 || type == UNIFORM_VALUE_VEC3 || type == UNIFORM_VALUE_VEC4; return binding == UNIFORM_BINDING_MANUAL || binding == UNIFORM_BINDING_PLAYBACK_TIME;
}
void uniform_configs_apply(const Element& shaderElement, std::vector<Uniform>& uniforms)
{
for (auto& uniform : uniforms)
{
auto config = shader_uniform_get(shaderElement, uniform.name);
if (!config) continue;
if (auto binding = uniform_binding_get(config->binding);
!config->binding.empty() && is_uniform_binding_valid(binding, uniform.valueType))
uniform.binding = binding;
if (!config->value.empty()) uniform_value_parse(uniform, config->value);
for (int index = 0; index < (int)uniform.components.size(); ++index)
{
auto component = shader_uniform_component_get(*config, index);
if (!component) continue;
if (auto binding = uniform_binding_get(component->binding);
!component->binding.empty() && is_component_binding_valid(binding))
uniform.components[index].binding = binding;
if (!component->value.empty()) std::stringstream{component->value} >> uniform.components[index].value;
}
}
}
bool uniform_configs_trim(Element& shaderElement, const std::vector<Uniform>& uniforms)
{
bool isChanged = std::erase_if(shaderElement.children,
[&](const Element& child)
{
return child.type == ElementType::UNIFORM &&
std::ranges::none_of(uniforms, [&](const Uniform& uniform)
{ return uniform.name == child.name; });
}) > 0;
for (auto& config : shaderElement.children)
{
if (config.type != ElementType::UNIFORM) continue;
auto& uniform = *std::ranges::find(uniforms, config.name, &Uniform::name);
if (!config.binding.empty() && !is_uniform_binding_valid(uniform_binding_get(config.binding), uniform.valueType))
{
config.binding.clear();
isChanged = true;
}
auto componentCount = UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount;
auto isComponents = uniform_binding_get(config.binding) == UNIFORM_BINDING_COMPONENTS;
isChanged |= std::erase_if(config.children,
[&](const Element& component)
{
return component.type == ElementType::COMPONENT &&
(!isComponents || component.index < 0 || component.index >= componentCount);
}) > 0;
for (auto& component : config.children)
{
if (component.type != ElementType::COMPONENT || component.binding.empty() ||
is_component_binding_valid(uniform_binding_get(component.binding)))
continue;
component.binding.clear();
isChanged = true;
}
}
return isChanged;
}
void uniform_config_save(Element& shaderElement, const Uniform& uniform)
{
auto config = shader_uniform_get(shaderElement, uniform.name);
if (!config)
{
config = &shaderElement.children.emplace_back(element_make(ElementType::UNIFORM));
config->name = uniform.name;
}
config->binding = std::string(uniform_binding_value_get(uniform.binding));
config->value = uniform_value_string_get(uniform);
std::erase_if(config->children, [](const Element& child) { return child.type == ElementType::COMPONENT; });
if (uniform.binding != UNIFORM_BINDING_COMPONENTS) return;
for (int index = 0; index < (int)uniform.components.size(); ++index)
{
auto& component = config->children.emplace_back(element_make(ElementType::COMPONENT));
component.index = index;
component.binding = std::string(uniform_binding_value_get(uniform.components[index].binding));
component.value = std::format("{:.6g}", uniform.components[index].value);
}
} }
bool is_uniform_binding_valid(UniformBinding binding, UniformValueType type) bool is_uniform_binding_valid(UniformBinding binding, UniformValueType type)
@@ -302,7 +390,8 @@ namespace anm2ed::resource::shader
case UNIFORM_VALUE_SAMPLER2D: case UNIFORM_VALUE_SAMPLER2D:
return std::format("{}", uniform.intValue); return std::format("{}", uniform.intValue);
case UNIFORM_VALUE_VEC2: case UNIFORM_VALUE_VEC2:
return std::format("{} {}", uniform_float_string_get(uniform.value.x), uniform_float_string_get(uniform.value.y)); return std::format("{} {}", uniform_float_string_get(uniform.value.x),
uniform_float_string_get(uniform.value.y));
case UNIFORM_VALUE_VEC3: case UNIFORM_VALUE_VEC3:
return std::format("{} {} {}", uniform_float_string_get(uniform.value.x), return std::format("{} {} {}", uniform_float_string_get(uniform.value.x),
uniform_float_string_get(uniform.value.y), uniform_float_string_get(uniform.value.z)); uniform_float_string_get(uniform.value.y), uniform_float_string_get(uniform.value.z));
@@ -374,15 +463,9 @@ namespace anm2ed::resource::shader
return "#version 330 core\n" + declarations + body; return "#version 330 core\n" + declarations + body;
} }
std::string gles_fragment_convert(std::string_view source) std::string gles_fragment_convert(std::string_view source) { return gles_convert(source, SHADER_STAGE_FRAGMENT); }
{
return gles_convert(source, SHADER_STAGE_FRAGMENT);
}
std::string gles_vertex_convert(std::string_view source) std::string gles_vertex_convert(std::string_view source) { return gles_convert(source, SHADER_STAGE_VERTEX); }
{
return gles_convert(source, SHADER_STAGE_VERTEX);
}
} }
namespace anm2ed::resource namespace anm2ed::resource
@@ -485,8 +568,5 @@ namespace anm2ed::resource
if (is_valid()) glDeleteProgram(id); if (is_valid()) glDeleteProgram(id);
} }
bool Shader::is_valid() const bool Shader::is_valid() const { return id != 0; }
{
return id != 0;
}
} }
+21 -12
View File
@@ -8,6 +8,11 @@
#include <string_view> #include <string_view>
#include <vector> #include <vector>
namespace anm2ed
{
struct Element;
}
namespace anm2ed::resource::shader namespace anm2ed::resource::shader
{ {
struct Info struct Info
@@ -257,14 +262,14 @@ namespace anm2ed::resource::shader
}; };
#define RESOURCE_SHADER_UNIFORM_BINDINGS \ #define RESOURCE_SHADER_UNIFORM_BINDINGS \
X(IGNORE, "Ignore", "Ignore") \ X(IGNORE, "Ignore", "Ignore") \
X(MAIN_TEXTURE, "MainTexture", "Main Texture") \ X(MAIN_TEXTURE, "MainTexture", "Main Texture") \
X(TRANSFORM, "Transform", "Transform") \ X(TRANSFORM, "Transform", "Transform") \
X(FRAME_TINT, "FrameTint", "Frame Tint") \ X(FRAME_TINT, "FrameTint", "Frame Tint") \
X(COLOR_OFFSET, "ColorOffset", "Color Offset") \ X(COLOR_OFFSET, "ColorOffset", "Color Offset") \
X(TEXTURE_SIZE, "TextureSize", "Texture Size") \ X(TEXTURE_SIZE, "TextureSize", "Texture Size") \
X(PLAYBACK_TIME, "PlaybackTime", "Playback Time") \ X(PLAYBACK_TIME, "PlaybackTime", "Playback Time") \
X(COMPONENTS, "Components", "Per Component") \ X(COMPONENTS, "Components", "Per Component") \
X(MANUAL, "Manual", "Manual") X(MANUAL, "Manual", "Manual")
enum UniformBinding enum UniformBinding
@@ -289,18 +294,18 @@ namespace anm2ed::resource::shader
}; };
#define RESOURCE_SHADER_UNIFORM_VALUE_TYPES \ #define RESOURCE_SHADER_UNIFORM_VALUE_TYPES \
X(UNKNOWN, "Unknown") \ X(UNKNOWN, "Unknown", 0) \
X(FLOAT, "Float") \ X(FLOAT, "Float", 0) \
X(INT, "Int") \ X(INT, "Int", 0) \
X(VEC2, "Vec2") \ X(VEC2, "Vec2", 2) \
X(VEC3, "Vec3") \ X(VEC3, "Vec3", 3) \
X(VEC4, "Vec4") \ X(VEC4, "Vec4", 4) \
X(MAT4, "Mat4") \ X(MAT4, "Mat4", 0) \
X(SAMPLER2D, "Sampler2D") X(SAMPLER2D, "Sampler2D", 0)
enum UniformValueType enum UniformValueType
{ {
#define X(symbol, label) UNIFORM_VALUE_##symbol, #define X(symbol, label, componentCount) UNIFORM_VALUE_##symbol,
RESOURCE_SHADER_UNIFORM_VALUE_TYPES RESOURCE_SHADER_UNIFORM_VALUE_TYPES
#undef X #undef X
UNIFORM_VALUE_COUNT UNIFORM_VALUE_COUNT
@@ -310,10 +315,11 @@ namespace anm2ed::resource::shader
{ {
UniformValueType type{}; UniformValueType type{};
const char* label{}; const char* label{};
int componentCount{};
}; };
inline constexpr UniformValueTypeInfo UNIFORM_VALUE_TYPE_INFOS[] = { inline constexpr UniformValueTypeInfo UNIFORM_VALUE_TYPE_INFOS[] = {
#define X(symbol, label) {UNIFORM_VALUE_##symbol, label}, #define X(symbol, label, componentCount) {UNIFORM_VALUE_##symbol, label, componentCount},
RESOURCE_SHADER_UNIFORM_VALUE_TYPES RESOURCE_SHADER_UNIFORM_VALUE_TYPES
#undef X #undef X
}; };
@@ -360,6 +366,9 @@ namespace anm2ed::resource::shader
{GRID_VERTEX, GRID_FRAGMENT}}; {GRID_VERTEX, GRID_FRAGMENT}};
UniformBinding uniform_binding_auto_get(std::string_view, UniformValueType); UniformBinding uniform_binding_auto_get(std::string_view, UniformValueType);
void uniform_configs_apply(const Element&, std::vector<Uniform>&);
bool uniform_configs_trim(Element&, const std::vector<Uniform>&);
void uniform_config_save(Element&, const Uniform&);
UniformBinding uniform_binding_get(std::string_view); UniformBinding uniform_binding_get(std::string_view);
std::string_view uniform_binding_value_get(UniformBinding); std::string_view uniform_binding_value_get(UniformBinding);
std::string_view uniform_binding_label_get(UniformBinding); std::string_view uniform_binding_label_get(UniformBinding);
+53 -139
View File
@@ -131,20 +131,9 @@ namespace anm2ed::snapshots
} }
} }
Element* element_get(Element& root, const std::vector<int>& path) template <class E> ElementPointer<E> element_get(E& root, const std::vector<int>& path)
{ {
auto* element = &root; auto element = &root;
for (auto index : path)
{
if (index < 0 || index >= (int)element->children.size()) return nullptr;
element = &element->children[index];
}
return element;
}
const Element* element_get(const Element& root, const std::vector<int>& path)
{
auto* element = &root;
for (auto index : path) for (auto index : path)
{ {
if (index < 0 || index >= (int)element->children.size()) return nullptr; if (index < 0 || index >= (int)element->children.size()) return nullptr;
@@ -158,46 +147,12 @@ namespace anm2ed::snapshots
for (size_t i = 0; i < element.children.size(); ++i) for (size_t i = 0; i < element.children.size(); ++i)
{ {
path.push_back((int)i); path.push_back((int)i);
if (&element.children[i] == target) return true; if (&element.children[i] == target || element_path_get(element.children[i], target, path)) return true;
if (element_path_get(element.children[i], target, path)) return true;
path.pop_back(); path.pop_back();
} }
return false; return false;
} }
std::optional<std::vector<int>> frame_path_get(const Anm2& anm2, Reference frameReference)
{
auto frame = anm2.element_get(frameReference);
if (!frame) return std::nullopt;
std::vector<int> path{};
if (!element_path_get(anm2.root, frame, path)) return std::nullopt;
return path;
}
std::optional<std::vector<int>> track_path_get(const Anm2& anm2, Reference trackReference)
{
trackReference.frameIndex = -1;
auto track = anm2.element_get(trackReference);
if (!track) return std::nullopt;
std::vector<int> path{};
if (!element_path_get(anm2.root, track, path)) return std::nullopt;
return path;
}
std::optional<std::vector<int>> region_path_get(const Anm2& anm2, int spritesheetId, int regionId)
{
auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetId);
if (!spritesheet) return std::nullopt;
auto region = child_id_get(*spritesheet, ElementType::REGION, regionId);
if (!region) return std::nullopt;
std::vector<int> path{};
if (!element_path_get(anm2.root, region, path)) return std::nullopt;
return path;
}
void step_state_seed(SnapshotStep& step, const Snapshot& snapshot) void step_state_seed(SnapshotStep& step, const Snapshot& snapshot)
{ {
#define X(type, name) step.name = SnapshotStepValue<type>{snapshot.name, {}}; #define X(type, name) step.name = SnapshotStepValue<type>{snapshot.name, {}};
@@ -205,61 +160,27 @@ namespace anm2ed::snapshots
#undef X #undef X
} }
void step_textures_seed(SnapshotStep& step, const Snapshot& snapshot) SnapshotStep step_anm2_make(const Snapshot& snapshot)
{
step.textures = SnapshotStepValue<SnapshotTextureMap>{snapshot.textures, {}};
}
SnapshotStep step_anm2_seed(const Snapshot& snapshot, const std::string& message)
{ {
SnapshotStep step{}; SnapshotStep step{};
step.message = message;
step.anm2.isValid = SnapshotStepValue<bool>{snapshot.anm2.isValid, {}}; step.anm2.isValid = SnapshotStepValue<bool>{snapshot.anm2.isValid, {}};
step.anm2.elements.push_back({{}, snapshot.anm2.root, {}}); step.anm2.elements.push_back({{}, snapshot.anm2.root, {}});
step_state_seed(step, snapshot); step_state_seed(step, snapshot);
return step; return step;
} }
void tracks_step_add(SnapshotStep& step, const Snapshot& snapshot, Reference trackReference) SnapshotStep step_elements_make(const Snapshot& snapshot, const std::vector<const Element*>& elements)
{ {
trackReference.frameIndex = -1; SnapshotStep step{};
auto path = track_path_get(snapshot.anm2, trackReference); for (auto element : elements)
if (!path) return; {
for (auto& elementStep : step.anm2.elements) std::vector<int> path{};
if (elementStep.path == *path) return; 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; }))
auto track = snapshot.anm2.element_get(trackReference); continue;
if (!track) return; step.anm2.elements.push_back({std::move(path), *element, {}});
}
step.anm2.elements.push_back({std::move(*path), *track, {}}); return step;
}
void frames_step_add(SnapshotStep& step, const Snapshot& snapshot, Reference frameReference)
{
auto path = frame_path_get(snapshot.anm2, frameReference);
if (!path) return;
for (auto& elementStep : step.anm2.elements)
if (elementStep.path == *path) return;
auto frame = snapshot.anm2.element_get(frameReference);
if (!frame) return;
step.anm2.elements.push_back({std::move(*path), *frame, {}});
}
void regions_step_add(SnapshotStep& step, const Snapshot& snapshot, int spritesheetId, int regionId)
{
auto path = region_path_get(snapshot.anm2, spritesheetId, regionId);
if (!path) return;
for (auto& elementStep : step.anm2.elements)
if (elementStep.path == *path) return;
auto spritesheet = snapshot.anm2.element_get(ElementType::SPRITESHEET, spritesheetId);
if (!spritesheet) return;
auto region = child_id_get(*spritesheet, ElementType::REGION, regionId);
if (!region) return;
step.anm2.elements.push_back({std::move(*path), *region, {}});
} }
SnapshotAnm2Step anm2_step_make(const Anm2& before, const Anm2& after) SnapshotAnm2Step anm2_step_make(const Anm2& before, const Anm2& after)
@@ -360,70 +281,63 @@ namespace anm2ed
int SnapshotStack::max_size_get() { return maxSize; } int SnapshotStack::max_size_get() { return maxSize; }
Snapshot* Snapshots::get() { return &current; } void Snapshots::step_push(const std::string& message, SnapshotStep step)
void Snapshots::anm2_push(const Snapshot& snapshot, const std::string& message)
{ {
if (pendingStep) commit(snapshot); if (pendingStep) commit();
pendingStep = snapshots::step_anm2_seed(snapshot, message); current.message = message;
step.message = message;
pendingStep = step.is_empty() ? std::nullopt : std::optional<SnapshotStep>(std::move(step));
} }
void Snapshots::tracks_push(const Snapshot& snapshot, const std::string& message, void Snapshots::anm2_push(const std::string& message) { step_push(message, snapshots::step_anm2_make(current)); }
const std::set<Reference>& trackReferences)
void Snapshots::tracks_push(const std::string& message, const std::set<Reference>& trackReferences)
{ {
if (pendingStep) commit(snapshot); std::vector<const Element*> tracks{};
SnapshotStep step{};
step.message = message;
for (auto trackReference : trackReferences) for (auto trackReference : trackReferences)
snapshots::tracks_step_add(step, snapshot, trackReference); {
snapshots::step_state_seed(step, snapshot); trackReference.frameIndex = -1;
tracks.push_back(current.anm2.element_get(trackReference));
pendingStep = step.is_empty() ? std::nullopt : std::optional<SnapshotStep>(std::move(step)); }
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 Snapshot& snapshot, const std::string& message, void Snapshots::frames_push(const std::string& message, const std::set<Reference>& frameReferences)
const std::set<Reference>& frameReferences)
{ {
if (pendingStep) commit(snapshot); std::vector<const Element*> frames{};
SnapshotStep step{};
step.message = message;
for (auto frameReference : frameReferences) for (auto frameReference : frameReferences)
snapshots::frames_step_add(step, snapshot, frameReference); frames.push_back(current.anm2.element_get(frameReference));
step_push(message, snapshots::step_elements_make(current, frames));
pendingStep = step.is_empty() ? std::nullopt : std::optional<SnapshotStep>(std::move(step));
} }
void Snapshots::regions_push(const Snapshot& snapshot, const std::string& message, int spritesheetId, void Snapshots::regions_push(const std::string& message, int spritesheetId, const std::set<int>& regionIds)
const std::set<int>& regionIds) {
std::vector<const Element*> 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)
{ {
if (pendingStep) commit(snapshot);
SnapshotStep step{}; SnapshotStep step{};
step.message = message; step.textures = SnapshotStepValue<SnapshotTextureMap>{current.textures, {}};
for (auto regionId : regionIds) step_push(message, std::move(step));
snapshots::regions_step_add(step, snapshot, spritesheetId, regionId);
pendingStep = step.is_empty() ? std::nullopt : std::optional<SnapshotStep>(std::move(step));
} }
void Snapshots::textures_push(const Snapshot& snapshot, const std::string& message) void Snapshots::anm2_textures_push(const std::string& message)
{ {
if (pendingStep) commit(snapshot); auto step = snapshots::step_anm2_make(current);
SnapshotStep step{}; step.textures = SnapshotStepValue<SnapshotTextureMap>{current.textures, {}};
step.message = message; step_push(message, std::move(step));
snapshots::step_textures_seed(step, snapshot);
pendingStep = std::move(step);
} }
void Snapshots::anm2_textures_push(const Snapshot& snapshot, const std::string& message) void Snapshots::commit()
{
if (pendingStep) commit(snapshot);
auto step = snapshots::step_anm2_seed(snapshot, message);
snapshots::step_textures_seed(step, snapshot);
pendingStep = std::move(step);
}
void Snapshots::commit(const Snapshot& snapshot)
{ {
const auto& snapshot = current;
if (!pendingStep) return; if (!pendingStep) return;
auto step = std::move(*pendingStep); auto step = std::move(*pendingStep);
+8 -8
View File
@@ -137,14 +137,14 @@ namespace anm2ed
Snapshot current{}; Snapshot current{};
std::optional<SnapshotStep> pendingStep{}; std::optional<SnapshotStep> pendingStep{};
Snapshot* get(); void anm2_push(const std::string&);
void anm2_push(const Snapshot&, const std::string&); void tracks_push(const std::string&, const std::set<Reference>&);
void tracks_push(const Snapshot&, const std::string&, const std::set<Reference>&); void frames_push(const std::string&, const std::set<Reference>&);
void frames_push(const Snapshot&, const std::string&, const std::set<Reference>&); void regions_push(const std::string&, int, const std::set<int>&);
void regions_push(const Snapshot&, const std::string&, int, const std::set<int>&); void textures_push(const std::string&);
void textures_push(const Snapshot&, const std::string&); void anm2_textures_push(const std::string&);
void anm2_textures_push(const Snapshot&, const std::string&); void step_push(const std::string&, SnapshotStep);
void commit(const Snapshot&); void commit();
bool undo(); bool undo();
bool redo(); bool redo();
void reset(); void reset();
+6 -8
View File
@@ -107,27 +107,25 @@ namespace anm2ed
if (!spritesheetDropPaths.empty()) if (!spritesheetDropPaths.empty())
{ {
auto paths = spritesheetDropPaths; auto paths = spritesheetDropPaths;
manager.command_push({manager.selected, [paths](Manager&, Document& document) manager.command_push(
{ document.spritesheets_add(paths); }}); {manager.selected, [paths](Manager&, Document& document) { document.spritesheets_add(paths); }});
} }
if (!soundDropPaths.empty()) if (!soundDropPaths.empty())
{ {
auto paths = soundDropPaths; auto paths = soundDropPaths;
manager.command_push({manager.selected, [paths](Manager&, Document& document) manager.command_push(
{ document.sounds_add(paths); }}); {manager.selected, [paths](Manager&, Document& document) { document.sounds_add(paths); }});
} }
} }
else else
{ {
if (!spritesheetDropPaths.empty()) if (!spritesheetDropPaths.empty())
{ {
toasts.push(localize.get(TOAST_ADD_SPRITESHEET_FAILED)); toast_log(Level::WARNING, TOAST_ADD_SPRITESHEET_FAILED);
logger.warning(localize.get(TOAST_ADD_SPRITESHEET_FAILED, anm2ed::ENGLISH));
} }
if (!soundDropPaths.empty()) if (!soundDropPaths.empty())
{ {
toasts.push(localize.get(TOAST_ADD_SOUND_FAILED)); toast_log(Level::WARNING, TOAST_ADD_SOUND_FAILED);
logger.warning(localize.get(TOAST_ADD_SOUND_FAILED, anm2ed::ENGLISH));
} }
} }
spritesheetDropPaths.clear(); spritesheetDropPaths.clear();
+150
View File
@@ -0,0 +1,150 @@
#include "pack.hpp"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <limits>
namespace anm2ed::util::pack
{
constexpr int WIDTH_CANDIDATES_MAX = 512;
struct Rect
{
int x{};
int y{};
int w{};
int h{};
};
bool is_rect_intersecting(const Rect& a, const Rect& b)
{
return !(b.x >= a.x + a.w || b.x + b.w <= a.x || b.y >= a.y + a.h || b.y + b.h <= a.y);
}
bool is_rect_contained(const Rect& a, const Rect& b)
{
return b.x >= a.x && b.y >= a.y && b.x + b.w <= a.x + a.w && b.y + b.h <= a.y + a.h;
}
void free_rects_split(std::vector<Rect>& freeRects, const Rect& used)
{
std::vector<Rect> next{};
next.reserve(freeRects.size() * 2);
for (auto& free : freeRects)
{
if (!is_rect_intersecting(free, used))
{
next.push_back(free);
continue;
}
if (used.x > free.x) next.push_back({free.x, free.y, used.x - free.x, free.h});
if (used.x + used.w < free.x + free.w)
next.push_back({used.x + used.w, free.y, free.x + free.w - (used.x + used.w), free.h});
if (used.y > free.y) next.push_back({free.x, free.y, free.w, used.y - free.y});
if (used.y + used.h < free.y + free.h)
next.push_back({free.x, used.y + used.h, free.w, free.y + free.h - (used.y + used.h)});
}
freeRects = std::move(next);
}
void free_rects_prune(std::vector<Rect>& freeRects)
{
for (int i = 0; i < (int)freeRects.size(); ++i)
{
if (freeRects[i].w <= 0 || freeRects[i].h <= 0)
{
freeRects.erase(freeRects.begin() + i--);
continue;
}
for (int j = i + 1; j < (int)freeRects.size();)
{
if (is_rect_contained(freeRects[i], freeRects[j]))
freeRects.erase(freeRects.begin() + j);
else if (is_rect_contained(freeRects[j], freeRects[i]))
{
freeRects.erase(freeRects.begin() + i--);
break;
}
else
++j;
}
}
}
bool rect_insert(std::vector<Rect>& freeRects, glm::ivec2 size, Rect& result)
{
int bestShort = std::numeric_limits<int>::max();
int bestLong = std::numeric_limits<int>::max();
bool isFound{};
for (auto& free : freeRects)
{
if (size.x > free.w || size.y > free.h) continue;
int shortSide = std::min(free.w - size.x, free.h - size.y);
int longSide = std::max(free.w - size.x, free.h - size.y);
if (shortSide > bestShort || (shortSide == bestShort && longSide >= bestLong)) continue;
bestShort = shortSide;
bestLong = longSide;
result = {free.x, free.y, size.x, size.y};
isFound = true;
}
if (!isFound) return false;
free_rects_split(freeRects, result);
free_rects_prune(freeRects);
return true;
}
bool rects_pack(const std::vector<glm::ivec2>& sizes, glm::ivec2& packedSize, std::vector<glm::ivec2>& positions)
{
if (sizes.empty()) return false;
glm::ivec2 maxSize{};
glm::ivec2 sumSize{};
std::int64_t totalArea{};
for (auto& size : sizes)
{
maxSize = glm::max(maxSize, size);
sumSize += size;
totalArea += (std::int64_t)size.x * size.y;
}
if (maxSize.x <= 0 || maxSize.y <= 0) return false;
int bestSquareDelta = std::numeric_limits<int>::max();
int bestArea = std::numeric_limits<int>::max();
int endWidth = std::max(maxSize.x, sumSize.x);
int step = std::max(1, (endWidth - maxSize.x) / WIDTH_CANDIDATES_MAX);
for (int width = maxSize.x; width <= endWidth; width += step)
{
std::vector<glm::ivec2> candidate(sizes.size());
glm::ivec2 used{};
bool isValid{};
for (int height = std::max(maxSize.y, (int)std::ceil((double)totalArea / width)); height <= sumSize.y && !isValid;
++height)
{
std::vector<Rect> freeRects{{0, 0, width, height}};
used = {};
isValid = true;
for (int i = 0; i < (int)sizes.size() && isValid; ++i)
{
Rect rect{};
isValid = rect_insert(freeRects, sizes[i], rect);
candidate[i] = {rect.x, rect.y};
used = glm::max(used, glm::ivec2(rect.x + rect.w, rect.y + rect.h));
}
}
if (!isValid) continue;
int area = used.x * used.y;
int squareDelta = std::abs(used.x - used.y);
if (squareDelta > bestSquareDelta || (squareDelta == bestSquareDelta && area >= bestArea)) continue;
bestSquareDelta = squareDelta;
bestArea = area;
packedSize = used;
positions = std::move(candidate);
if (bestArea == totalArea && bestSquareDelta == 0) break;
}
return bestArea != std::numeric_limits<int>::max();
}
}
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include <vector>
#include <glm/glm.hpp>
namespace anm2ed::util::pack
{
bool rects_pack(const std::vector<glm::ivec2>&, glm::ivec2&, std::vector<glm::ivec2>&);
}